From f9bbd991ce9962a23a432710b405c8151de061f0 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:14:12 -0500 Subject: [PATCH 01/28] fix(conversation): a first message to a new user compiles the draft first The first `--text` send of a new conversation ran the old build of the draft, and vf said so only afterwards: "This turn ran an older build of the draft". Five testers hit it right after an edit, and read the stale reply as "my edit didn't work". `send --help` promised vf "compiles the draft first when a conversation starts", but compileBeforeSend counted only a launch action as a start, while a text message to a user ID with no conversation starts one too: the runtime launches it itself. Now a draft send that isn't a launch reads the user's conversation state first. An empty stack, which the API returns for a user ID it hasn't met and after a conversation ends, means the send starts a conversation, so vf compiles before it, as it does for a launch. A 404 counts as no conversation; a state vf can't read counts as one going, so the send goes on as before. A launch still compiles without the read, and --no-compile and the published version skip both. A later turn still runs the build as it is: nothing in the API says before a turn that the draft changed since the last compile (needsRecompile comes only in a send's answer), so a mid-conversation edit is still caught after the turn, compiled, and warned about. `send --help` (its description and --no-compile) and the README now say exactly this. --- README.md | 2 +- internal/cli/autocompile_test.go | 80 +++++++++++++++++++++--- internal/cli/conversation/autocompile.go | 69 +++++++++++++++++--- 3 files changed, 132 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 84f1aa1a..37e5eb3a 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` with a `launch` action. If a later turn still ran an older build (you edited mid-conversation, or started with a `text` action), vf compiles right after it and warns, so the next turn runs the edits. `--no-compile` talks to the last build as it is; the published version is never compiled. +- **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. - **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 4cd3c6ea..04f22ec3 100644 --- a/internal/cli/autocompile_test.go +++ b/internal/cli/autocompile_test.go @@ -16,9 +16,16 @@ import ( "github.com/voiceflow/cli/internal/output" ) -// conversationServer answers compile with compileStatus, and a conversation -// with answer. It records each request as "compile" or "conversation". +// conversationServer answers compile with compileStatus, the user's state +// with a conversation going, and a conversation with answer. It records each +// request as "compile", "state" or "conversation". func conversationServer(t *testing.T, compileStatus int, answer string) (url string, requests func() []string) { + return conversationServerWithState(t, compileStatus, answer, 200, goingState) +} + +// conversationServerWithState is conversationServer, with the user's state +// answered with stateStatus and state. +func conversationServerWithState(t *testing.T, compileStatus int, answer string, stateStatus int, state string) (url string, requests func() []string) { t.Helper() var mu sync.Mutex var seen []string @@ -27,14 +34,22 @@ func conversationServer(t *testing.T, compileStatus int, answer string) (url str mu.Lock() defer mu.Unlock() w.Header().Set("Content-Type", "application/json") - if strings.HasSuffix(r.URL.Path, "/compile") { + switch { + case strings.HasSuffix(r.URL.Path, "/compile"): seen = append(seen, "compile") w.WriteHeader(compileStatus) io.WriteString(w, `{"message":"Environment compiled","durationMs":5}`) - return + case strings.Contains(r.URL.Path, "/conversation-state/"): + seen = append(seen, "state") + if r.Method != http.MethodGet || r.URL.Query().Get("version") != "draft" { + t.Errorf("read the state with %s %s", r.Method, r.URL) + } + w.WriteHeader(stateStatus) + io.WriteString(w, state) + default: + seen = append(seen, "conversation") + io.WriteString(w, answer) } - seen = append(seen, "conversation") - io.WriteString(w, answer) })) t.Cleanup(srv.Close) return srv.URL, func() []string { @@ -68,6 +83,11 @@ const ( freshTurn = `{"traces":[],"needsRecompile":false}` staleTurn = `{"traces":[],"needsRecompile":true}` script = `{"userID":"u1","transcriptID":null,"needsRecompile":false,"turns":[],"notSent":[]}` + // The state of a user with a conversation going, and of one with none: + // the API's answer for a user ID it hasn't met, or whose conversation + // ended. + goingState = `{"state":{"stack":[{"diagramID":"d1","nodeID":"n1","storage":{},"variables":{}}],"storage":{},"variables":{"name":"Sam"}}}` + noneState = `{"state":{"stack":[],"storage":{},"variables":{}}}` ) func TestAConversationWithTheDraftCompilesItFirst(t *testing.T) { @@ -83,10 +103,11 @@ func TestAConversationWithTheDraftCompilesItFirst(t *testing.T) { {"run-script --no-compile", script, append([]string{"run-script", "-m", `["hi"]`, "--no-compile"}, scope...), "conversation"}, {"run-script on published", script, append([]string{"run-script", "-m", `["hi"]`, "--version-param", "published"}, scope...), "conversation"}, {"a launch compiles first", freshTurn, append(send, "-a", `{"type":"launch"}`), "compile conversation"}, - {"a later turn doesn't", freshTurn, append(send, "-a", `{"type":"text","payload":"hi"}`), "conversation"}, - {"a stale turn compiles after", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`), "conversation compile"}, - {"a stale turn compiles after, -o json", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`, "-o", "json"), "conversation compile"}, + {"a later turn doesn't", freshTurn, append(send, "-a", `{"type":"text","payload":"hi"}`), "state conversation"}, + {"a stale turn compiles after", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`), "state conversation compile"}, + {"a stale turn compiles after, -o json", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`, "-o", "json"), "state conversation compile"}, {"a stale turn with --no-compile", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`, "--no-compile"), "conversation"}, + {"a later turn on published", freshTurn, []string{"send", "-u", "u1", "-v", "published", "-p", "p1", "-e", "main", "--text", "hi"}, "conversation"}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -109,6 +130,47 @@ func TestAConversationWithTheDraftCompilesItFirst(t *testing.T) { } } +// 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. +func TestAFirstMessageCompilesTheDraftFirst(t *testing.T) { + send := []string{"send", "-u", "new-user", "-v", "draft", "-p", "p1", "-e", "main"} + cases := []struct { + name string + stateStatus int + state string + args []string + want string + }{ + {"--text to a new user", 200, noneState, []string{"--text", "hi"}, "state compile conversation"}, + {"a text action to a new user", 200, noneState, []string{"-a", `{"type":"text","payload":"hi"}`}, "state compile conversation"}, + {"--body to a new user", 200, noneState, []string{"--body", `{"action":{"type":"text","payload":"hi"},"version":"draft"}`}, "state compile conversation"}, + {"a user the API has no state for", 404, `{"message":"Not found"}`, []string{"--text", "hi"}, "state compile conversation"}, + {"a conversation going", 200, goingState, []string{"--text", "hi"}, "state conversation"}, + {"a state vf can't read", 500, `{"message":"boom"}`, []string{"--text", "hi"}, "state conversation"}, + {"--no-compile reads nothing first", 200, noneState, []string{"--text", "hi", "--no-compile"}, "conversation"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + url, requests := conversationServerWithState(t, 200, freshTurn, c.stateStatus, c.state) + out, err := runConversation(t, url, append(send, c.args...)...) + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + if got := strings.Join(requests(), " "); got != c.want { + t.Errorf("requests = %q, want %q", got, c.want) + } + compiled := strings.Contains(c.want, "compile") + if says := strings.Contains(out, "Compiled the draft of main"); says != compiled { + t.Errorf("compiled %v, but saying so is %v:\n%s", compiled, says, out) + } + if strings.Contains(out, "older build") { + t.Errorf("warned of an older build:\n%s", out) + } + }) + } +} + // A draft that won't compile stops the script before it spends credits, and // says how to run the last build anyway. func TestADraftThatWontCompileStopsTheScript(t *testing.T) { diff --git a/internal/cli/conversation/autocompile.go b/internal/cli/conversation/autocompile.go index b2951c4e..83126049 100644 --- a/internal/cli/conversation/autocompile.go +++ b/internal/cli/conversation/autocompile.go @@ -9,16 +9,24 @@ // // Nothing says the draft is stale before a run, so vf compiles it whenever a // conversation with the draft starts: before every run-script, and before a -// send that launches. A send later in a conversation keeps its build, but if -// its turn still ran a stale one, vf compiles right after and says so, so the -// next turn runs the edits. --no-compile runs whatever was last compiled. -// The published version is a release, and is never compiled. +// send that starts one. A send starts a conversation when it launches, and +// when its user has none going: a user ID new to the agent, or one whose +// conversation ended, has an empty stack, and the runtime starts afresh. The +// first `--text` to a new user ID used to run the old build, because only a +// launch counted as a start, though help said "when a conversation starts". +// +// 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. package conversation import ( "encoding/json" "fmt" + "net/http" "strings" "time" @@ -34,11 +42,22 @@ import ( const noCompileFlag = "no-compile" -// addNoCompileFlag lets cmd run the draft as last compiled. +// addNoCompileFlag lets cmd run the draft as last compiled, and says when vf +// compiles it otherwise. func addNoCompileFlag(cmd *cobra.Command) { - cmd.Flags().Bool(noCompileFlag, false, "Run the draft as last compiled. Without it, vf compiles the draft first when a conversation starts, so it runs your latest edits.") + usage := "Run the draft as last compiled. Without it, vf compiles the draft first, so the script runs your latest edits." + if cmd.Name() == "send" { + usage = "Run the draft as last compiled. Without it, vf compiles the draft before a turn that starts a conversation (a launch, or the first message to a user ID with no conversation going), and right after a later turn that ran an older build." + cmd.Long += "\n\n" + sendCompiles + } + cmd.Flags().Bool(noCompileFlag, false, usage) } +// 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.` + // compileBeforeScript compiles the draft before run-script, which always // starts a new conversation. func compileBeforeScript(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableConversationControllerRunScriptRequest) error { @@ -48,15 +67,47 @@ func compileBeforeScript(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operation return compileDraft(cmd, s, req.ProjectID, req.EnvironmentAlias) } -// compileBeforeSend compiles the draft before a send that launches a -// conversation. +// compileBeforeSend compiles the draft before a send that starts a +// conversation: a launch, or any action to a user with no conversation +// going. func compileBeforeSend(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableConversationControllerSendRequest) error { - if string(req.Body.Version) != "draft" || actionType(req.Body.Action) != "launch" { + if string(req.Body.Version) != "draft" || skipCompile(cmd) { + return nil + } + if actionType(req.Body.Action) != "launch" && !startsConversation(cmd, s, req) { return nil } return compileDraft(cmd, s, req.ProjectID, req.EnvironmentAlias) } +// startsConversation reports whether req's user has no conversation going, +// so that the runtime starts one for it: the user's state has an empty +// stack, as it has for a user ID it hasn't met (it answers 200 with an empty +// state) and after a conversation ends. A state vf can't read counts as a +// conversation going, so the send goes on as it would have and says what's +// wrong; a 404 counts as none. +func startsConversation(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableConversationControllerSendRequest) bool { + ctx := client.WithSpinnerMessage(cmd.Context(), "Reading the conversation…") + res, err := s.Conversation.State.Get(ctx, operations.StableConversationStateControllerGetRequest{ + UserID: req.UserID, + ProjectID: req.ProjectID, + EnvironmentAlias: req.EnvironmentAlias, + Version: operations.StableConversationStateControllerGetVersionDraft, + }, operations.WithSkipDeserialization()) + if err != nil { + return output.StatusCode(err) == http.StatusNotFound + } + var answer struct { + State struct { + Stack []json.RawMessage `json:"stack"` + } `json:"state"` + } + if !output.PeekJSON(res.HTTPMeta.Response, &answer) { + return false + } + return len(answer.State.Stack) == 0 +} + // compileAfterStaleSend reads a send's answer before it is printed. When the // turn ran a stale build of the draft, the function it returns compiles the // draft once the answer is printed, and says so. From 35f552f73bb5ed762c576dda1b900e9bdf3169f6 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:20:06 -0500 Subject: [PATCH 02/28] fix(conversation): refuse an action type vf doesn't know before sending `--action '{"type":"bogus"}'` was sent. The action union has two forms that take any type, a path request (a button's request) and a general request, so the SDK read the bogus action as a path request and added "label": "". The live API followed a path that isn't there, the reply was empty, and vf exited 0. A typo such as "lauch" or "txet" looked like a silent agent to a script or an agent. Now send refuses an action whose type none of the union's forms names, before any request, compile included: exit 2, invalid_flag_value, with the types there are (launch, text, end, intent, event, action, message, file, no-reply, dtmf, live-agent-handoff) and "Did you mean ...?" for a near miss. Agent mode gets details[{field: action.type, flag: --action}]. The same goes for a misspelt type that fits no form at all, such as {"type":"txet","payload":"hi"}, which got only "it isn't any of the forms --action takes", and for --body. The catch-all forms are there on purpose, so two ways through stay: a button's path-... type goes as given, and the new --custom-action flag sends any other type as given, such as one a custom action step waits for. Refusing rather than warning after the turn, because a script reads the exit code, not stderr. The list is the SDK's own type constants, and a test fails if the SDK gains a form with a type the list lacks. --- internal/cli/conversation/actiontype.go | 169 +++++++++++++++++++ internal/cli/conversation/actiontype_test.go | 58 +++++++ internal/cli/conversation/send.go | 6 +- internal/cli/conversationactiontype_test.go | 124 ++++++++++++++ internal/cli/conversationend_test.go | 4 +- 5 files changed, 359 insertions(+), 2 deletions(-) create mode 100644 internal/cli/conversation/actiontype.go create mode 100644 internal/cli/conversation/actiontype_test.go create mode 100644 internal/cli/conversationactiontype_test.go diff --git a/internal/cli/conversation/actiontype.go b/internal/cli/conversation/actiontype.go new file mode 100644 index 00000000..b791c585 --- /dev/null +++ b/internal/cli/conversation/actiontype.go @@ -0,0 +1,169 @@ +// This file is not generated by Speakeasy. It keeps a misspelt action type +// from being sent as an empty turn. +// +// An action is a union of fifteen forms. Thirteen name their type: launch, +// text, end and the rest. Two take any type: a path request, the form a +// button's request has ({"type":"path-…","payload":{"label":"…"}}), and a +// general request, for a type the agent itself defines, such as the one a +// custom action step waits for. So --action '{"type":"lauch"}' is a valid +// path request: the SDK adds the label it needs ("label": ""), the API +// follows a path that isn't there, and the turn comes back empty with exit +// 0. In the usability sweep, {"type":"bogus"} looked like a silent agent. +// +// So vf refuses an action whose type no form names, before anything is sent, +// and says which types there are, with the nearest when it's a typo. That +// holds too for one that fits no form, {"type":"txet","payload":"hi"}, which +// got only "it isn't any of the forms --action takes". A button's path-… +// type goes as given, and --custom-action sends any other type as given: +// the catch-all forms are there on purpose, and a warning after the turn +// would come too late for a script that reads exit 0. + +package conversation + +import ( + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" +) + +const customActionFlag = "custom-action" + +// actionTypes is every type the action's forms name, most used first. The +// intent forms (intent, Alexa's and the legacy one) share "intent". +var actionTypes = []string{ + string(components.LaunchRequestTypeLaunch), + string(components.TextRequestTypeText), + string(components.EndRequestTypeEnd), + string(components.IntentRequestTypeIntent), + string(components.EventRequestTypeEvent), + string(components.ActionRequestTypeAction), + string(components.MessageRequestTypeMessage), + string(components.FileRequestTypeFile), + string(components.NoReplyRequestTypeNoReply), + string(components.DTMFRequestTypeDtmf), + string(components.LiveAgentHandoffRequestTypeLiveAgentHandoff), +} + +// pathPrefix starts the type of a button's request, which a path request +// carries. +const pathPrefix = "path-" + +// addCustomFlag lets cmd send an action whose type vf doesn't know. +func addCustomFlag(cmd *cobra.Command) { + cmd.Flags().Bool(customActionFlag, false, `Send --action as given when its type is none of the standard ones, such as a type a custom action step waits for. Without it, vf refuses a type it doesn't know, so a typo such as "lauch" isn't sent as an empty turn.`) +} + +// refuseUnknownAction explains an action whose type no form names, unless +// it is a button's path or --custom-action says to send it as given. +func refuseUnknownAction(cmd *cobra.Command, req *operations.StableConversationControllerSendRequest) error { + if typ := actionType(req.Body.Action); !sendable(cmd, typ) { + return unknownType(cmd, typ) + } + return nil +} + +// actionNotBuilt explains a send whose request didn't build. An action that +// is none of the forms, such as {"type":"txet","payload":"hi"}, is most +// likely a misspelt type, and gets unknownType when it is one. A missing +// action gets noMessage. Other errors pass through. +func actionNotBuilt(cmd *cobra.Command, err error) error { + var value string + var flagErr *flagutil.FlagValueError + var bodyErr *flagutil.BodyError + switch { + case errors.As(err, &flagErr) && flagErr.Flag == actionFlag: + value = `{"action":` + flagErr.Value + `}` + case errors.As(err, &bodyErr): + value = bodyErr.Value + } + var body struct { + Action struct { + Type *string `json:"type"` + } `json:"action"` + } + if value != "" && json.Unmarshal([]byte(value), &body) == nil && body.Action.Type != nil && !sendable(cmd, *body.Action.Type) { + return unknownType(cmd, *body.Action.Type) + } + return noMessage(cmd, err) // text.go: no action names --text +} + +// sendable reports whether vf sends an action of type typ: one a form +// names, a button's path, or any other with --custom-action. +func sendable(cmd *cobra.Command, typ string) bool { + if slices.Contains(actionTypes, typ) || strings.HasPrefix(typ, pathPrefix) { + return true + } + custom, _ := cmd.Flags().GetBool(customActionFlag) + return custom && typ != "" +} + +// unknownType explains an action of a type vf doesn't send: the types there +// are, and the nearest when typ looks like a typo of one. +func unknownType(cmd *cobra.Command, typ string) error { + x := output.Explanation{ + Type: "invalid_flag_value", + Title: fmt.Sprintf("The action's type %q is none vf knows", typ), + Why: []string{"The API would take it as a path to follow and answer with nothing, so vf didn't send it."}, + } + if typ == "" { + x.Title = "The action has no type" + x.Why = []string{`An action is JSON with a "type", such as {"type":"launch"}.`} + } + if near := nearestType(typ); near != "" { + x.Next = append(x.Next, fmt.Sprintf("Did you mean %q?", near)) + } + x.Next = append(x.Next, + "The types are "+strings.Join(actionTypes, ", ")+", and a button's "+pathPrefix+"… type", + "To send a custom action's own type as given, add `--"+customActionFlag+"`", + ) + msg := fmt.Sprintf("type %q is none of %s", typ, strings.Join(actionTypes, ", ")) + if output.WantsJSONError(cmd) { + detail := output.FieldError{Field: "action.type", Message: msg} + if flagutil.FlagChanged(cmd, actionFlag) { + detail.Flag = "--" + actionFlag + } + x.Details = []output.FieldError{detail} + } + return output.Report(cmd, x, errors.New("action "+msg)) +} + +// nearestType is the action type typ is likely a typo of, or "". +func nearestType(typ string) string { + best, bestDist := "", 3 // at most two edits, and fewer than the word's length + for _, t := range actionTypes { + if d := editDistance(strings.ToLower(typ), t); d < bestDist && d < len(t) { + best, bestDist = t, d + } + } + return best +} + +// editDistance is the Levenshtein distance between a and b. +func editDistance(a, b string) int { + prev := make([]int, len(b)+1) + for j := range prev { + prev[j] = j + } + for i := 1; i <= len(a); i++ { + cur := make([]int, len(b)+1) + cur[0] = i + for j := 1; j <= len(b); j++ { + cost := 1 + if a[i-1] == b[j-1] { + cost = 0 + } + cur[j] = min(prev[j]+1, cur[j-1]+1, prev[j-1]+cost) + } + prev = cur + } + return prev[len(b)] +} diff --git a/internal/cli/conversation/actiontype_test.go b/internal/cli/conversation/actiontype_test.go new file mode 100644 index 00000000..a8ccdc39 --- /dev/null +++ b/internal/cli/conversation/actiontype_test.go @@ -0,0 +1,58 @@ +// This file is not generated by Speakeasy. It covers actiontype.go: the +// action types vf knows are the ones the SDK's action forms name. + +package conversation + +import ( + "encoding/json" + "reflect" + "strconv" + "testing" + + "github.com/voiceflow/cli/internal/sdk/models/components" +) + +// Every form of the action union either names one of actionTypes or takes +// any type (the path and general requests). A form the SDK gains with a type +// of its own fails here until actionTypes has it. +func TestActionTypesAreTheFormsTypes(t *testing.T) { + union := reflect.TypeOf(components.AnyRequest{}) + anyType := 0 + for i := 0; i < union.NumField(); i++ { + member := union.Field(i) + if member.Tag.Get("union") != "member" { + continue + } + field, ok := member.Type.Elem().FieldByName("Type") + if !ok { + t.Fatalf("%s has no Type", member.Name) + } + if field.Type == reflect.TypeOf("") { + anyType++ + continue + } + var takes []string + for _, typ := range actionTypes { + if json.Unmarshal([]byte(strconv.Quote(typ)), reflect.New(field.Type).Interface()) == nil { + takes = append(takes, typ) + } + } + if len(takes) != 1 { + t.Errorf("%s takes %v of actionTypes, want one", member.Name, takes) + } + } + if anyType != 2 { + t.Errorf("%d forms take any type, want 2 (path and general requests)", anyType) + } +} + +func TestNearestType(t *testing.T) { + for typ, want := range map[string]string{ + "lauch": "launch", "txet": "text", "Text": "text", "ned": "end", + "noreply": "no-reply", "bogus": "", "x": "", "order_placed": "", + } { + if got := nearestType(typ); got != want { + t.Errorf("nearestType(%q) = %q, want %q", typ, got, want) + } + } +} diff --git a/internal/cli/conversation/send.go b/internal/cli/conversation/send.go index ec45dd64..a0c03bb7 100644 --- a/internal/cli/conversation/send.go +++ b/internal/cli/conversation/send.go @@ -38,6 +38,7 @@ func initSendCmd(parent *cobra.Command) error { addNoCompileFlag(cmd) // autocompile.go: --no-compile addShowDebugFlag(cmd) // reply.go: --show-debug addTextFlag(cmd) // text.go: --text, the message as typed + addCustomFlag(cmd) // actiontype.go: --custom-action sends an unknown type as given if err := flagutil.ValidateMeta[operations.StableConversationControllerSendRequest](sendCmdMeta); err != nil { return fmt.Errorf("invalid metadata for send: %w", err) } @@ -62,7 +63,10 @@ func runSendCmd(cmd *cobra.Command, args []string) error { } req, err := flagutil.BuildRequest[operations.StableConversationControllerSendRequest](cmd, sendCmdMeta, "Body", "body") if err != nil { - return noMessage(cmd, err) // text.go: --text or --action + return actionNotBuilt(cmd, err) // actiontype.go: a misspelt type, or none (text.go) + } + if err := refuseUnknownAction(cmd, req); err != nil { // actiontype.go: a misspelt type isn't sent + return err } giveEndAReason(req) // endaction.go: an end action without a reason gets one s, err := client.NewClient(cmd) diff --git a/internal/cli/conversationactiontype_test.go b/internal/cli/conversationactiontype_test.go new file mode 100644 index 00000000..8f925822 --- /dev/null +++ b/internal/cli/conversationactiontype_test.go @@ -0,0 +1,124 @@ +// This file is not generated by Speakeasy. It covers +// conversation/actiontype.go: an action whose type vf doesn't know isn't +// sent. + +package cli + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// --action '{"type":"bogus"}' went out as a path request the API answered +// with nothing, exit 0. Now it stops before any request, exit 2, naming the +// types there are. +func TestAnUnknownActionTypeIsNotSent(t *testing.T) { + t.Run("person", func(t *testing.T) { + url, requests := conversationServer(t, 200, freshTurn) + out, err := runConversation(t, url, "send", "-u", "u1", "-v", "draft", "-p", "p1", "-e", "main", "-a", `{"type":"bogus"}`) + if err == nil { + t.Fatalf("no error:\n%s", out) + } + if got := requests(); len(got) != 0 { + t.Errorf("sent %v", got) + } + if code := output.ExitCode(err); code != output.ExitUsage { + t.Errorf("exit %d, want %d", code, output.ExitUsage) + } + for _, want := range []string{`type "bogus" is none vf knows`, "launch, text, end, intent", "path-", "--custom-action"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q:\n%s", want, out) + } + } + if strings.Contains(out, "Did you mean") { + t.Errorf("suggested a type for a word near none:\n%s", out) + } + }) + t.Run("a typo", func(t *testing.T) { + url, requests := conversationServer(t, 200, freshTurn) + out, err := runConversation(t, url, "send", "-u", "u1", "-v", "draft", "-p", "p1", "-e", "main", "--no-compile", "-a", `{"type":"lauch"}`) + if err == nil || len(requests()) != 0 { + t.Fatalf("sent it, err %v:\n%s", err, out) + } + if !strings.Contains(out, `Did you mean "launch"?`) { + t.Errorf("no suggestion:\n%s", out) + } + }) + // {"type":"txet"} builds as a path request; with a text's payload it + // builds as no form at all. Both are the same typo. + for _, action := range []string{`{"type":"txet"}`, `{"type":"txet","payload":"hi"}`} { + t.Run("agent "+action, func(t *testing.T) { + url, requests := conversationServer(t, 200, freshTurn) + _, errOut, err := runSend(t, url, true, "-a", action) + if err == nil || len(requests()) != 0 { + t.Fatalf("sent it, err %v:\n%s", err, errOut) + } + var e struct { + Type string `json:"error_type"` + ExitCode int `json:"exit_code"` + Details []struct { + Field string `json:"field"` + Flag string `json:"flag"` + Message string `json:"message"` + } `json:"details"` + Hints []string `json:"hints"` + } + if err := json.Unmarshal([]byte(errOut), &e); err != nil { + t.Fatalf("not JSON: %v\n%s", err, errOut) + } + if e.Type != "invalid_flag_value" || e.ExitCode != output.ExitUsage { + t.Errorf("error_type %q, exit_code %d", e.Type, e.ExitCode) + } + if len(e.Details) != 1 || e.Details[0].Field != "action.type" || e.Details[0].Flag != "--action" || !strings.Contains(e.Details[0].Message, `type "txet" is none of launch, text`) { + t.Errorf("details = %+v", e.Details) + } + if !strings.Contains(strings.Join(e.Hints, "\n"), `Did you mean "text"?`) { + t.Errorf("hints = %q", e.Hints) + } + }) + } + for _, body := range []string{`{"action":{"type":"bogus"},"version":"published"}`, `{"action":{"type":"bogus","payload":"hi"},"version":"published"}`} { + t.Run("--body "+body, func(t *testing.T) { + url, requests := conversationServer(t, 200, freshTurn) + out, err := runConversation(t, url, "send", "-u", "u1", "-p", "p1", "-e", "main", "--body", body) + if err == nil || len(requests()) != 0 { + t.Fatalf("sent it, err %v:\n%s", err, out) + } + if !strings.Contains(out, `type "bogus" is none vf knows`) { + t.Errorf("doesn't name the type:\n%s", out) + } + }) + } +} + +// The types the forms name, a button's path, and any type with +// --custom-action go out as given. +func TestKnownActionTypesAreSent(t *testing.T) { + for _, c := range []struct { + action string + extra []string + }{ + {`{"type":"launch"}`, nil}, + {`{"type":"text","payload":"hi"}`, nil}, + {`{"type":"intent","payload":{"intent":{"name":"yes"},"query":"yes","entities":[]}}`, nil}, + {`{"type":"event","payload":{"event":{"name":"opened"}}}`, nil}, + {`{"type":"no-reply"}`, nil}, + {`{"type":"path-1sx3k9nw","payload":{"label":"Yes"}}`, nil}, + {`{"type":"order_placed"}`, []string{"--custom-action"}}, + } { + t.Run(c.action, func(t *testing.T) { + url, requests := conversationServer(t, 200, freshTurn) + args := append([]string{"send", "-u", "u1", "-v", "published", "-p", "p1", "-e", "main", "-a", c.action}, c.extra...) + out, err := runConversation(t, url, args...) + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + if got := strings.Join(requests(), " "); got != "conversation" { + t.Errorf("requests = %q", got) + } + }) + } +} diff --git a/internal/cli/conversationend_test.go b/internal/cli/conversationend_test.go index 08f6aab4..a1fc9455 100644 --- a/internal/cli/conversationend_test.go +++ b/internal/cli/conversationend_test.go @@ -174,6 +174,8 @@ func TestSendActionErrorNamesTheForm(t *testing.T) { }) t.Run("a type no form has", func(t *testing.T) { // Every branch's type is wrong: the end branch too, for a type "ned". + // vf refuses such a type itself (actiontype.go) unless + // --custom-action sends it, as here, when the API's error is the one. body := strings.Replace(unionError, `[{"code":"invalid_type","expected":"string","message":"Invalid input: expected string, received undefined","path":["payload","reason"]}]`, `[{"code":"invalid_value","message":"Invalid input: expected \"end\"","path":["type"],"values":["end"]}]`, 1) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -182,7 +184,7 @@ func TestSendActionErrorNamesTheForm(t *testing.T) { io.WriteString(w, body) })) t.Cleanup(srv.Close) - _, errOut, err := runSend(t, srv.URL, false, "--action", `{"type":"ned","payload":{}}`) + _, errOut, err := runSend(t, srv.URL, false, "--action", `{"type":"ned","payload":{}}`, "--custom-action") if err == nil { t.Fatal("no error") } From 6bb8e2dee1ea31baac6c053b1fffd77e2c777859 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:24:16 -0500 Subject: [PATCH 03/28] fix(conversation): a send missing only its action keeps the flags given MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `vf conversation send -p … -e main -u u1 -v draft` with no --text or --action said "Say something: 'vf conversation send --text '". Copying that dropped the project, environment, user and version, and in agent mode the error had no `details`. With -u missing as well, the same command got the full line from missingflags.go, so the most common case got the weaker hint. text.go's noMessage built its own explanation instead of the shared one. noMessage is gone, and a missing action now reaches explainMissingFlags like any missing flag: "vf conversation send needs --text (or --action)", "Pass it: 'vf conversation send --environment-alias main --project-id … --user-id u1 --version-param draft --text '", and in agent mode details [{flag: --action, message: "required, or --text"}]. The send tests' runSend now renders an error the command didn't print, as main does, so what they read is what a user sees. --- internal/cli/conversation/actiontype.go | 8 ++-- internal/cli/conversation/send.go | 2 +- internal/cli/conversation/text.go | 21 ---------- internal/cli/conversationreply_test.go | 2 +- internal/cli/conversationtext_test.go | 3 +- internal/cli/missingflags_test.go | 54 +++++++++++++++++++++++++ 6 files changed, 63 insertions(+), 27 deletions(-) diff --git a/internal/cli/conversation/actiontype.go b/internal/cli/conversation/actiontype.go index b791c585..8a862266 100644 --- a/internal/cli/conversation/actiontype.go +++ b/internal/cli/conversation/actiontype.go @@ -73,8 +73,10 @@ func refuseUnknownAction(cmd *cobra.Command, req *operations.StableConversationC // actionNotBuilt explains a send whose request didn't build. An action that // is none of the forms, such as {"type":"txet","payload":"hi"}, is most -// likely a misspelt type, and gets unknownType when it is one. A missing -// action gets noMessage. Other errors pass through. +// likely a misspelt type, and gets unknownType when it is one. Other errors +// pass through: a missing action, say, is explained with the rest of the +// missing flags (internal/cli/missingflags.go), as "--text (or --action)", +// on a command line that keeps the flags given. func actionNotBuilt(cmd *cobra.Command, err error) error { var value string var flagErr *flagutil.FlagValueError @@ -93,7 +95,7 @@ func actionNotBuilt(cmd *cobra.Command, err error) error { if value != "" && json.Unmarshal([]byte(value), &body) == nil && body.Action.Type != nil && !sendable(cmd, *body.Action.Type) { return unknownType(cmd, *body.Action.Type) } - return noMessage(cmd, err) // text.go: no action names --text + return err } // sendable reports whether vf sends an action of type typ: one a form diff --git a/internal/cli/conversation/send.go b/internal/cli/conversation/send.go index a0c03bb7..3f8ca4ee 100644 --- a/internal/cli/conversation/send.go +++ b/internal/cli/conversation/send.go @@ -63,7 +63,7 @@ func runSendCmd(cmd *cobra.Command, args []string) error { } req, err := flagutil.BuildRequest[operations.StableConversationControllerSendRequest](cmd, sendCmdMeta, "Body", "body") if err != nil { - return actionNotBuilt(cmd, err) // actiontype.go: a misspelt type, or none (text.go) + return actionNotBuilt(cmd, err) // actiontype.go: a misspelt type names the types there are } if err := refuseUnknownAction(cmd, req); err != nil { // actiontype.go: a misspelt type isn't sent return err diff --git a/internal/cli/conversation/text.go b/internal/cli/conversation/text.go index 5dff984d..59a542a4 100644 --- a/internal/cli/conversation/text.go +++ b/internal/cli/conversation/text.go @@ -22,7 +22,6 @@ import ( "github.com/spf13/cobra" "github.com/voiceflow/cli/internal/flagutil" - "github.com/voiceflow/cli/internal/interactive" "github.com/voiceflow/cli/internal/output" ) @@ -86,23 +85,3 @@ func textAsAction(cmd *cobra.Command) error { } return cmd.Flags().Set(actionFlag, string(action)) } - -// noMessage explains a send that says nothing to send, with both ways to say -// it; other errors pass through. -func noMessage(cmd *cobra.Command, err error) error { - if err == nil || err.Error() != "missing required flag: --"+actionFlag { - return err - } - x := output.Explanation{ - Type: "missing_flag", - Title: cmd.CommandPath() + " needs something to send: --text or --action", - Next: []string{ - "Say something: `" + cmd.CommandPath() + " --" + textFlag + " `", - `Or send any other action as JSON, such as a launch: --action '{"type":"launch"}'`, - }, - } - if !output.IsAgentMode() && !interactive.IsInteractive(cmd) { - x.Why = []string{"vf asks for the message only at a terminal, and this isn't one."} - } - return output.Report(cmd, x, err) -} diff --git a/internal/cli/conversationreply_test.go b/internal/cli/conversationreply_test.go index 8d69c740..769a668b 100644 --- a/internal/cli/conversationreply_test.go +++ b/internal/cli/conversationreply_test.go @@ -47,7 +47,7 @@ func runSend(t *testing.T, url string, agent bool, args ...string) (stdout, stde } send := []string{"conversation", "send", "-p", "p1", "-e", "main", "-u", "u1", "-v", "published"} root.SetArgs(append(append(send, args...), mode, "--no-interactive")) - _, err = root.ExecuteC() + err = renderError(root.ExecuteC()) // as main does: an error the command didn't print is explained return out.String(), errOut.String(), err } diff --git a/internal/cli/conversationtext_test.go b/internal/cli/conversationtext_test.go index 977d9ad8..a7246c55 100644 --- a/internal/cli/conversationtext_test.go +++ b/internal/cli/conversationtext_test.go @@ -93,7 +93,8 @@ func TestSendWithNothingToSendNamesText(t *testing.T) { if err == nil { t.Fatalf("agent=%v: no error", agent) } - if !strings.Contains(errOut, "needs something to send: --text or --action") || !strings.Contains(errOut, "--text ") { + // The command line keeps the flags runSend gives (missingflags.go). + if !strings.Contains(errOut, "needs --text (or --action)") || !strings.Contains(errOut, "--user-id u1 --version-param published --text ") { t.Errorf("agent=%v: the error doesn't offer --text:\n%s", agent, errOut) } if n := len(bodies()); n != 0 { diff --git a/internal/cli/missingflags_test.go b/internal/cli/missingflags_test.go index c5630a73..4f0617bd 100644 --- a/internal/cli/missingflags_test.go +++ b/internal/cli/missingflags_test.go @@ -5,6 +5,7 @@ package cli import ( + "encoding/json" "strings" "testing" @@ -91,6 +92,59 @@ func TestAndList(t *testing.T) { } } +// `conversation send` missing only the action said "Say something: 'vf +// conversation send --text '", which dropped -p -e -u -v, and gave +// agent mode no details. It now gets the same error as any missing flag. +func TestOnlyAMissingActionKeepsTheFlagsGiven(t *testing.T) { + given := []string{"conversation", "send", "-p", "p1", "-e", "main", "-u", "u1", "-v", "draft"} + line := "vf conversation send --environment-alias main --project-id p1 --user-id u1 --version-param draft --text " + + x := runWithStdin(t, "", given...) + all := explained(x) + for _, want := range []string{"vf conversation send needs --text (or --action)", "Pass it: `" + line + "`"} { + if !strings.Contains(all, want) { + t.Errorf("missing %q in:\n%s", want, all) + } + } + if x.Type != "missing_flag" { + t.Errorf("type = %q", x.Type) + } + + t.Setenv("HOME", t.TempDir()) + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var stdout, stderr strings.Builder + root.SetOut(&stdout) + root.SetErr(&stderr) + root.SetIn(strings.NewReader("")) + root.SetArgs(append(given, "--agent-mode", "--no-interactive")) + err = renderError(root.ExecuteC()) + if output.ExitCode(err) != output.ExitUsage { + t.Errorf("exit %d, want %d", output.ExitCode(err), output.ExitUsage) + } + var e struct { + Type string `json:"error_type"` + Hints []string `json:"hints"` + Details []struct { + Flag string `json:"flag"` + Message string `json:"message"` + } `json:"details"` + } + if err := json.Unmarshal([]byte(stderr.String()), &e); err != nil { + t.Fatalf("not JSON: %v\n%s", err, stderr.String()) + } + if e.Type != "missing_flag" || len(e.Details) != 1 || e.Details[0].Flag != "--action" || e.Details[0].Message != "required, or --text" { + t.Errorf("error_type %q, details %+v", e.Type, e.Details) + } + if !strings.Contains(strings.Join(e.Hints, "\n"), "'"+line+"'") { + t.Errorf("hints = %q, want the command line %q", e.Hints, line) + } +} + // `conversation send` without an action names --text first, the plain way to // give one, and its command line uses it. func TestAMissingActionNamesText(t *testing.T) { From 084aa77f5fc13068b246d7b956cc507c71e1b978 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:27:28 -0500 Subject: [PATCH 04/28] fix(prompt): send's flag menu leads with --text, not --action MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Typing `conversation send ` in the home prompt led with --action, "required · JSON value (one of: { type: string, payload: object, …", and --text, what a newcomer needs, came last, under "↓ 3 more". The menu put required flags first, and --action is required unless --text, which stands in for it, is given; --text itself isn't marked required. The menu now knows the stand-in pair (flagutil.StandIn). A flag that stands in for a required one leads, marked required, as "or --action · The message to send…". The flag it stands for moves among the optional, as "or --text · JSON value…", without its "[required, or --text]" marker. Once either is on the line the other isn't offered, since send refuses both together. --- internal/cli/conversationtext_test.go | 20 +++++++++++++ internal/prompt/complete.go | 39 ++++++++++++++++++++++--- internal/prompt/complete_test.go | 41 +++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 4 deletions(-) diff --git a/internal/cli/conversationtext_test.go b/internal/cli/conversationtext_test.go index a7246c55..dbf69add 100644 --- a/internal/cli/conversationtext_test.go +++ b/internal/cli/conversationtext_test.go @@ -11,6 +11,8 @@ import ( "strings" "sync" "testing" + + "github.com/voiceflow/cli/internal/prompt" ) // sendServer answers every conversation turn with answer, and records each @@ -118,3 +120,21 @@ func TestSendHelpLeadsWithText(t *testing.T) { t.Errorf("the first example doesn't send typed words with --text alone: %s", first) } } + +// The home prompt's flag menu leads with --text too: it led with --action's +// JSON union, and --text came last, under "↓ 3 more". +func TestSendFlagMenuLeadsWithText(t *testing.T) { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + menu := prompt.Commands(root, nil)("conversation send ") + if len(menu) == 0 || menu[0].Label != "--text" || !menu[0].Required { + t.Fatalf("the menu doesn't lead with --text: %+v", menu) + } + for _, s := range menu { + if s.Label == "--action" && s.Required { + t.Errorf("--action is still marked required: %+v", s) + } + } +} diff --git a/internal/prompt/complete.go b/internal/prompt/complete.go index fe71828c..d96e5bfe 100644 --- a/internal/prompt/complete.go +++ b/internal/prompt/complete.go @@ -11,6 +11,9 @@ import ( "github.com/spf13/cobra" "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/ui" ) // Suggestion is one row of the menu. @@ -274,18 +277,31 @@ func flags(cmd *cobra.Command, partial token, used map[string]bool, fill Filler) } // flagsWhere is cmd's flags whose names pass keep: the required ones you -// must give, the required ones vf fills, then optional, then, once a dash is -// typed, the global ones. +// must give, the plain way to give one first (send's --text, for --action), +// the required ones vf fills, then optional, then, once a dash is typed, the +// global ones. func flagsWhere(cmd *cobra.Command, partial token, used map[string]bool, fill Filler, keep func(name string) bool) []Suggestion { - var required, filled, optional, global []Suggestion + var standIns, required, filled, optional, global []Suggestion add := func(f *pflag.Flag, inherited bool) { if f.Hidden || used[f.Name] || f.Name == "help" || !keep(f.Name) { return } s := Suggestion{Label: "--" + f.Name, Detail: flagDetail(f.Usage), From: partial.start} + other, given := standsIn(cmd, f, used) + or := "or --" + other + " " + ui.Separator.Symbol() + " " switch { + case given: + return // the other of its pair is on the line already case inherited: global = append(global, s) + case other != "" && !isRequired(f): + // It gives a required flag the plain way, so it leads. + s.Required, s.Detail = true, or+s.Detail + standIns = append(standIns, s) + case other != "": + // Required, unless the flag that stands in for it is given. + s.Detail = or + strings.TrimSpace(strings.Replace(s.Detail, "[required, or --"+other+"]", "", 1)) + optional = append(optional, s) case isRequired(f) && fill != nil && fill(cmd, f.Name) != "": s.Detail, s.Filled = fill(cmd, f.Name), true filled = append(filled, s) @@ -302,7 +318,22 @@ func flagsWhere(cmd *cobra.Command, partial token, used map[string]bool, fill Fi if strings.HasPrefix(partial.text, "-") { cmd.InheritedFlags().VisitAll(func(f *pflag.Flag) { add(f, true) }) } - return append(append(append(required, filled...), optional...), global...) + return append(append(append(append(standIns, required...), filled...), optional...), global...) +} + +// standsIn pairs f with the flag that stands in for it, or with the +// required flag it stands in for (flagutil.StandIn): other names that flag, +// or is "" when f has no pair, and given says other is on the line. +func standsIn(cmd *cobra.Command, f *pflag.Flag, used map[string]bool) (other string, given bool) { + if stand := flagutil.StandInFor(cmd, f.Name); stand != "" { + return stand, used[stand] + } + for _, name := range f.Annotations[flagutil.StandsFor] { + if g := cmd.Flags().Lookup(name); g != nil && isRequired(g) { + return name, used[name] + } + } + return "", false } // flagDetail is a flag's usage, first line, without the generated diff --git a/internal/prompt/complete_test.go b/internal/prompt/complete_test.go index eb596a27..5e4b4348 100644 --- a/internal/prompt/complete_test.go +++ b/internal/prompt/complete_test.go @@ -8,6 +8,9 @@ import ( "testing" "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/ui" ) // tree is a small command tree shaped like vf's: groups with operations @@ -267,3 +270,41 @@ func TestFilledFlagsSayWhatFillsThem(t *testing.T) { t.Errorf("markers: %+v", got[:2]) } } + +// `conversation send ` led with --action ("required · JSON value (one of: { +// type: string, …"), and --text, the plain way to give it, came last, under +// "↓ 3 more". A flag that stands in for a required one now leads, and the +// one it stands for waits among the optional, each naming the other. Once +// one of the pair is on the line, the other isn't offered. +func TestAStandInLeadsTheFlagsItGives(t *testing.T) { + root := tree() + send := &cobra.Command{Use: "send", Run: func(*cobra.Command, []string) {}} + for _, name := range []string{"action", "user-id"} { + send.Flags().String(name, "", "The "+name+" [required]") + _ = send.Flags().SetAnnotation(name, "speakeasy:required", []string{"true"}) + } + send.Flags().String("text", "", "The message") + send.Flags().Bool("no-compile", false, "Run the last build") + flagutil.StandIn(send, "text", "action") + root.AddCommand(send) + complete := Commands(root, nil) + + got := complete("send ") + if want := []string{"--text", "--user-id", "--action", "--no-compile"}; !reflect.DeepEqual(labels(got), want) { + t.Fatalf("got %v, want %v", labels(got), want) + } + or := " " + ui.Separator.Symbol() + " " + if !got[0].Required || got[0].Detail != "or --action"+or+"The message" { + t.Errorf("--text: %+v", got[0]) + } + if got[2].Required || got[2].Detail != "or --text"+or+"The action" { + t.Errorf("--action: %+v", got[2]) + } + rest := []string{"--user-id", "--no-compile", "--debug", "--output-format"} + if got := labels(complete("send --text hi --")); !reflect.DeepEqual(got, rest) { + t.Errorf("with --text given: %v, want %v", got, rest) + } + if got := labels(complete(`send --action '{"type":"launch"}' --`)); !reflect.DeepEqual(got, rest) { + t.Errorf("with --action given: %v, want %v", got, rest) + } +} From 972814fe2977b6e7dffa0d95b6f16739e9a9264c Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:16:13 -0500 Subject: [PATCH 05/28] fix(output): empty values and multi-line strings keep pretty output's indent The pretty printer wrote an empty object or list on the line below its key, at column 0, so `metadata:` was followed by a flush-left `{}` and `resources:` by `[]`. A string with newlines in it (a knowledge-base chunk, a system prompt in a run's logs) carried on at column 0 and broke the layout of everything after it. An unchanged `environment diff` gave three zero counts and an empty list, and nothing said in words that there was nothing to publish. An empty object or list now prints on its key's line (`metadata: {}`), and a multi-line string prints under its key, one step in, as a YAML block scalar (`content: |`). Pretty `environment diff` ends with "No differences." when it found none; JSON, YAML, TOON, tables, --jq and agent mode get the response alone. Round-4 sweep #2 (human-poweruser, human-newcomer, human-kb, agent-ci). --- internal/cli/environment/diff.go | 1 + internal/cli/environment/nodiff.go | 34 +++++++++ internal/cli/outputview_test.go | 96 +++++++++++++++++++++++++ internal/output/pretty.go | 1 + internal/output/prettyshape.go | 106 ++++++++++++++++++++++++++++ internal/output/prettyshape_test.go | 83 ++++++++++++++++++++++ internal/output/view.go | 20 ++++++ 7 files changed, 341 insertions(+) create mode 100644 internal/cli/environment/nodiff.go create mode 100644 internal/cli/outputview_test.go create mode 100644 internal/output/prettyshape.go create mode 100644 internal/output/prettyshape_test.go create mode 100644 internal/output/view.go diff --git a/internal/cli/environment/diff.go b/internal/cli/environment/diff.go index d3bebe89..218f1dc5 100644 --- a/internal/cli/environment/diff.go +++ b/internal/cli/environment/diff.go @@ -78,5 +78,6 @@ func runDiffCmd(cmd *cobra.Command, args []string) error { if err := output.Result(cmd, res); err != nil { return err } + sayNoDifferences(cmd, res) // nodiff.go: a diff that found nothing says so return nil } diff --git a/internal/cli/environment/nodiff.go b/internal/cli/environment/nodiff.go new file mode 100644 index 00000000..d97a2c70 --- /dev/null +++ b/internal/cli/environment/nodiff.go @@ -0,0 +1,34 @@ +// 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 new file mode 100644 index 00000000..72e234ca --- /dev/null +++ b/internal/cli/outputview_test.go @@ -0,0 +1,96 @@ +// This file is not generated by Speakeasy. It covers the views commands add +// to pretty output for a person: environment/nodiff.go. + +package cli + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// viewServer answers each request with the body routes gives for its path. +func viewServer(t *testing.T, routes map[string]string) string { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + body, ok := routes[r.URL.Path] + if !ok { + t.Errorf("unexpected request %s %s", r.Method, r.URL) + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, body) + })) + t.Cleanup(srv.Close) + return srv.URL +} + +// runView runs vf with args against url, in agent mode or not, and returns +// what it printed. +func runView(t *testing.T, url string, agent bool, args ...string) (stdout, stderr string) { + 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")) + if _, err := root.ExecuteC(); err != nil { + t.Fatalf("vf %s: %v\n%s%s", strings.Join(args, " "), err, out.String(), errOut.String()) + } + return out.String(), errOut.String() +} + +const ( + unchangedDiff = `{"diff":{"created":0,"updated":0,"deleted":0,"resources":[],"truncated":false}}` + changedDiff = `{"diff":{"created":1,"updated":0,"deleted":0,"resources":[{"type":"playbook","id":"pb1","name":"Refunds","change":"created"}],"truncated":false}}` +) + +func TestEnvironmentDiffSaysWhenThereAreNoDifferences(t *testing.T) { + diff := []string{"environment", "diff", "-p", "p1", "-e", "main"} + cases := []struct { + name string + body string + agent bool + args []string + want bool + }{ + {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"}}, + } + 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) + } + }) + } +} diff --git a/internal/output/pretty.go b/internal/output/pretty.go index b5ab85bc..24a90b7d 100644 --- a/internal/output/pretty.go +++ b/internal/output/pretty.go @@ -28,6 +28,7 @@ func prettyPrint(w io.Writer, content interface{}, colorize bool) error { _, err = fmt.Fprintln(w, string(data)) return err } + parsed = shapeForPretty(parsed, colorize) // prettyshape.go: [] and {} on their key's line; a multi-line string indented under it pp := &prettyPrinter{w: w, colorize: colorize} pp.printValue(parsed, 0) diff --git a/internal/output/prettyshape.go b/internal/output/prettyshape.go new file mode 100644 index 00000000..8d3b38cd --- /dev/null +++ b/internal/output/prettyshape.go @@ -0,0 +1,106 @@ +// This file is not generated by Speakeasy. It keeps pretty output's +// indentation when a value is empty or runs over several lines. +// +// The generated printer writes an object or a list on the lines below its +// key, one step in. An empty one has no lines, so its `{}` or `[]` landed on +// the next line at column 0, under a key that seemed to have no value: +// +// metadata: +// {} +// score: 0.18 +// +// And it wrote a string as it came, so a string with newlines in it (a +// knowledge-base chunk, a system prompt in a run's logs) carried on at +// column 0 and broke the layout of everything after it. In the usability +// sweep `test run get`, `transcript get` and `knowledge-base query` all read +// as a wall of text for that reason. +// +// Now an empty object or list prints after its key, `metadata: {}`, and a +// multi-line string prints under its key, one step in, as a YAML block +// scalar does: +// +// content: | +// Opening hours +// Saturday: 8 am to 4 pm + +package output + +import "strings" + +// prettyText is a value the printer writes as it is, uncolored: the printer +// writes a value of a type it doesn't know by its %v. +type prettyText string + +func (t prettyText) String() string { return string(t) } + +// shapeForPretty readies parsed, a decoded JSON value, for the printer: each +// empty object or list below the top is `{}` or `[]` on its key's line, and +// each multi-line string a block indented for where it prints. +func shapeForPretty(parsed interface{}, colorize bool) interface{} { + return shapeEntries(parsed, 0, colorize) +} + +// shapeEntries shapes the entries of an object or list whose keys or items +// print level steps in. The lines under an entry print one step further. +func shapeEntries(v interface{}, level int, colorize bool) interface{} { + switch val := v.(type) { + case map[string]interface{}: + for k, child := range val { + val[k] = shapeValue(child, level+1, colorize) + } + case []interface{}: + for i, child := range val { + val[i] = shapeValue(child, level+1, colorize) + } + } + return v +} + +// shapeValue shapes an entry's value. level is the step its lines print at +// when they go below the entry's own line. +func shapeValue(v interface{}, level int, colorize bool) interface{} { + switch val := v.(type) { + case map[string]interface{}: + if len(val) == 0 { + return prettyText("{}") + } + return shapeEntries(val, level, colorize) + case []interface{}: + if len(val) == 0 { + return prettyText("[]") + } + return shapeEntries(val, level, colorize) + case string: + return blockText(val, level, colorize) + } + return v +} + +// blockText is s as the printer should write it after a key or "- ": as it +// is when it is one line, and otherwise "|" with each line below it, level +// steps in. Trailing newlines are dropped: they would print blank lines. +func blockText(s string, level int, colorize bool) interface{} { + text := strings.ReplaceAll(s, "\r\n", "\n") + text = strings.ReplaceAll(text, "\r", "\n") + text = strings.TrimRight(text, "\n") + if !strings.Contains(text, "\n") { + if text == s { + return s + } + return text + } + indent := strings.Repeat(" ", level) + var b strings.Builder + b.WriteString("|") + for _, line := range strings.Split(text, "\n") { + b.WriteString("\n") + if strings.TrimSpace(line) == "" { + continue // no trailing spaces on a blank line + } + if colorize { + line = colorString + line + colorReset + } + b.WriteString(indent + line) + } + return prettyText(b.String()) +} diff --git a/internal/output/prettyshape_test.go b/internal/output/prettyshape_test.go new file mode 100644 index 00000000..7bee0cc9 --- /dev/null +++ b/internal/output/prettyshape_test.go @@ -0,0 +1,83 @@ +// This file is not generated by Speakeasy. It covers prettyshape.go: pretty +// output keeps its indentation for empty values and multi-line strings. + +package output + +import ( + "bytes" + "encoding/json" + "strings" + "testing" +) + +func prettyOf(t *testing.T, raw string) string { + t.Helper() + var v any + if err := json.Unmarshal([]byte(raw), &v); err != nil { + t.Fatal(err) + } + var out bytes.Buffer + if err := prettyPrint(&out, v, false); err != nil { + t.Fatal(err) + } + return out.String() +} + +// No line starts at column 0 unless it is a top-level key: an empty value +// or a string's second line used to. +func assertIndented(t *testing.T, out string, topKeys ...string) { + t.Helper() + for _, line := range strings.Split(strings.TrimRight(out, "\n"), "\n") { + if line == "" || strings.HasPrefix(line, " ") { + continue + } + top := false + for _, k := range topKeys { + top = top || strings.HasPrefix(line, k+":") + } + if !top { + t.Errorf("line at column 0: %q\n--- got:\n%s", line, out) + } + } +} + +func TestPrettyPutsEmptyValuesOnTheirKeysLine(t *testing.T) { + out := prettyOf(t, `{"diff":{"created":0,"resources":[],"truncated":false}, + "chunks":[{"chunkID":"c1","metadata":{},"tags":[]},{}],"nested":[[],{}]}`) + for _, want := range []string{ + " resources: []\n", + " - chunkID: c1\n metadata: {}\n tags: []\n", + " - {}\n", + "nested:\n - []\n - {}\n", + } { + if !strings.Contains(out, want) { + t.Errorf("missing %q\n--- got:\n%s", want, out) + } + } + assertIndented(t, out, "diff", "chunks", "nested") +} + +func TestPrettyIndentsAMultiLineStringUnderItsKey(t *testing.T) { + out := prettyOf(t, `{"answer":{"chunks":[{"content":"Opening hours\r\nSaturday: 8 am\n\n to 4 pm\n","score":0.39}], + "output":"8 am.\n"},"notes":["one\ntwo"]}`) + for _, want := range []string{ + " - content: |\n Opening hours\n Saturday: 8 am\n\n to 4 pm\n score: 0.39\n", + " output: 8 am.\n", + "notes:\n - |\n one\n two\n", + } { + if !strings.Contains(out, want) { + t.Errorf("missing %q\n--- got:\n%s", want, out) + } + } + assertIndented(t, out, "answer", "notes") +} + +// A top-level empty value or string has nothing to line up with, and prints +// as before. +func TestPrettyTopLevelValuesAreUnchanged(t *testing.T) { + for raw, want := range map[string]string{`[]`: "[]\n", `{}`: "{}\n", `"a\nb"`: "a\nb\n"} { + if got := prettyOf(t, raw); got != want { + t.Errorf("%s: got %q, want %q", raw, got, want) + } + } +} diff --git a/internal/output/view.go b/internal/output/view.go new file mode 100644 index 00000000..7bf94ef6 --- /dev/null +++ b/internal/output/view.go @@ -0,0 +1,20 @@ +// This file is not generated by Speakeasy. It lets a command that shows its +// result its own way for a person (`knowledge-base query`, `test run get`, +// `environment diff`) ask what Result would print, so the views it adds +// appear where pretty output does and nowhere else. + +package output + +import "github.com/spf13/cobra" + +// FormatOf is the format Result prints cmd's result in: --output-format, +// then the setting, then TOON in agent mode, then pretty. +func FormatOf(cmd *cobra.Command) string { + return resolveOutputFormat(cmd) +} + +// ForAPerson reports whether cmd's result prints as pretty output for a +// person: not JSON, YAML, TOON, a table or --jq, and not in agent mode. +func ForAPerson(cmd *cobra.Command) bool { + return !WantsRawJSON(cmd) && FormatOf(cmd) == "pretty" && !IsAgentMode() +} From 7e397c8c9dc3d7d13c851b822abbee569522afa6 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:19:25 -0500 Subject: [PATCH 06/28] fix(knowledge-base): a query shows its answer first, then its sources `knowledge-base query` printed the response as it came: fifteen fields of token accounting, then every chunk with its whole text, and the answer last, "about 470 lines down" for one tester and at line 306 of 316 for another. With --synthesis=false there is no answer, but the zero-valued accounting printed anyway, in pretty output, TOON and tables. Pretty output and TOON now give the answer, then its sources best first, one line each with the document's name (its ID when it has none) and the chunk's score. Each chunk's text and the token use show with --show-debug, as `conversation send` shows its traces. An empty answer says so. With --synthesis=false the chunks are the result: their text shows, and the accounting doesn't, in tables either. JSON, YAML and --jq still print the response as the API sent it. Round-4 sweep #3 (human-newcomer, human-kb, agent-builder). --- internal/cli/knowledgebase/answer.go | 219 +++++++++++++++++++++++++++ internal/cli/knowledgebase/query.go | 3 +- internal/cli/outputview_test.go | 142 ++++++++++++++++- 3 files changed, 362 insertions(+), 2 deletions(-) create mode 100644 internal/cli/knowledgebase/answer.go diff --git a/internal/cli/knowledgebase/answer.go b/internal/cli/knowledgebase/answer.go new file mode 100644 index 00000000..1c64152b --- /dev/null +++ b/internal/cli/knowledgebase/answer.go @@ -0,0 +1,219 @@ +// This file is not generated by Speakeasy. It shows a knowledge-base +// query's answer first, then where it came from. +// +// A query comes back as one object: fifteen fields of token accounting and +// billing multipliers, every chunk the search found with its whole text, and +// somewhere among them `output`, the answer. Printed as it came, the answer +// was the last of hundreds of lines: "about 470 lines down" and "line 306 of +// 316" in the usability sweep, after a page of Wikipedia and the token +// counts. With --synthesis=false there is no answer and no accounting, but +// the zero-valued fields printed anyway. +// +// So pretty output, and TOON in agent mode, now give the answer, then its +// sources best first, one line each: the document's name and the chunk's +// score. Each chunk's text and the token use show with --show-debug, the +// flag `conversation send` hides its traces behind. With --synthesis=false +// the chunks are the result, so their text shows, and the accounting +// doesn't, in tables too. JSON, YAML and --jq still print the response as +// the API sent it. + +package knowledgebase + +import ( + "encoding/json" + "fmt" + "io" + "sort" + "strconv" + "strings" + + "github.com/charmbracelet/x/ansi" + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/ui" +) + +const showDebugFlag = "show-debug" + +// addShowDebugFlag lets cmd show what the answer was made from. +func addShowDebugFlag(cmd *cobra.Command) { + cmd.Flags().Bool(showDebugFlag, false, "Also show each source's text and the token use. Without it, vf shows the answer and its sources, best first. -o json and -o yaml always print the whole response.") +} + +// source is one chunk the answer may have drawn on. +type source struct { + name string // the document's name; its ID when it has none + documentID string + score float64 + text string +} + +// showAnswer prints a query's result: the response as sent for the formats +// scripts read, and the answer, then its sources, for a person and in TOON. +func showAnswer(cmd *cobra.Command, res *operations.StableKnowledgeBaseControllerQueryResponse) error { + headers, _ := flagutil.GetBoolFlag(cmd, "include-headers") + if res == nil || res.StableKnowledgeBaseQueryResponse == nil || client.IsDryRun(cmd) || headers || output.WantsRawJSON(cmd) { + return output.Result(cmd, res) + } + answer := res.StableKnowledgeBaseQueryResponse.Answer + debug, _ := cmd.Flags().GetBool(showDebugFlag) + asked := synthesized(answer) + switch output.FormatOf(cmd) { + case "pretty": + out, done := output.ResultWriter(cmd) + writeAnswer(output.UI(cmd, cmd.OutOrStdout()), out, answer, asked, debug) + done() + if debug { + fmt.Fprintln(cmd.OutOrStdout()) + return output.Result(cmd, res) + } + return nil + case "toon": + return output.Result(cmd, digest(answer, asked, debug)) + case "table": + if !asked { + return output.Result(cmd, struct { + Chunks []components.StableKnowledgeBaseQueryResponseChunk `json:"chunks"` + }{answer.Chunks}) + } + } + return output.Result(cmd, res) +} + +// synthesized reports whether an answer was asked for: with +// --synthesis=false the API names no model and counts no tokens. +func synthesized(a components.Answer) bool { + return a.Model != "" || (a.Output != nil && *a.Output != "") || a.Tokens > 0 || a.QueryTokens > 0 || a.AnswerTokens > 0 +} + +// sources are the answer's chunks, best score first. +func sources(a components.Answer) []source { + list := make([]source, 0, len(a.Chunks)) + for _, c := range a.Chunks { + s := source{name: sourceName(c.Source), documentID: c.DocumentID, score: c.Score, text: c.Content} + if s.name == "" { + s.name = c.DocumentID + } + list = append(list, s) + } + sort.SliceStable(list, func(i, j int) bool { return list[i].score > list[j].score }) + return list +} + +// sourceName is a chunk's document's name, whichever kind of document it is. +func sourceName(data components.KBDocumentData) string { + raw, err := json.Marshal(data) + if err != nil { + return "" + } + var doc struct { + Name string `json:"name"` + } + _ = json.Unmarshal(raw, &doc) + return doc.Name +} + +// score is a chunk's score as it reads best: at most four decimals. +func score(f float64) string { + s := strings.TrimRight(strconv.FormatFloat(f, 'f', 4, 64), "0") + return strings.TrimSuffix(s, ".") +} + +// writeAnswer prints the answer for a person: +// +// Answer 8 am. +// +// Sources +// northwind-faq.txt 0.39 +// en.wikipedia.org/wiki/Cortado 0.18 +// +// Each source's text and the token use · --show-debug shows them +// +// Without an answer asked for, each source's text prints under it. +func writeAnswer(u *ui.UI, out io.Writer, a components.Answer, asked, debug bool) { + const label = "Answer " + indent := strings.Repeat(" ", len(label)) + text := "" + if a.Output != nil { + text = strings.TrimRight(*a.Output, "\n") + } + switch { + case !asked: + case strings.TrimSpace(text) == "": + fmt.Fprintln(out, u.Muted("No answer: none of the sources answers this question.")) + default: + for i, line := range strings.Split(text, "\n") { + lead := indent + if i == 0 { + lead = u.Bold(label) + } + fmt.Fprintln(out, strings.TrimRight(lead+line, " ")) + } + } + + list := sources(a) + if len(list) == 0 { + fmt.Fprintln(out, u.Muted("No sources: nothing in the knowledge base matched.")) + return + } + if asked { + fmt.Fprintln(out) + } + fmt.Fprintln(out, u.Bold("Sources")) + width := 0 + for _, s := range list { + width = max(width, ansi.StringWidth(s.name)) + } + for i, s := range list { + if !asked && i > 0 { + fmt.Fprintln(out) + } + pad := strings.Repeat(" ", width-ansi.StringWidth(s.name)) + fmt.Fprintln(out, " "+u.Accent(s.name)+pad+" "+u.Muted(score(s.score))) + if asked { + continue + } + for _, line := range strings.Split(strings.TrimRight(s.text, "\n"), "\n") { + fmt.Fprintln(out, strings.TrimRight(" "+line, " ")) + } + } + if asked && !debug { + fmt.Fprintln(out) + fmt.Fprintln(out, u.Muted("Each source's text and the token use "+u.Glyph(ui.Separator)+" --show-debug shows them")) + } +} + +// digest is the result for an agent: the answer, then its sources, best +// first. TOON sorts keys, so the names keep that order: answer, sources, +// textHidden (or usage, with --show-debug). +func digest(a components.Answer, asked, debug bool) map[string]any { + list := sources(a) + rows := make([]map[string]any, len(list)) + for i, s := range list { + rows[i] = map[string]any{"name": s.name, "documentID": s.documentID, "score": s.score} + if debug || !asked { + rows[i]["content"] = s.text + } + } + d := map[string]any{"sources": rows} + if !asked { + return d + } + d["answer"] = a.Output + if !debug { + d["textHidden"] = "each source's text and the token use: --show-debug shows them, and -o json prints the response as sent" + return d + } + usage := map[string]any{} + if raw, err := json.Marshal(a); err == nil && json.Unmarshal(raw, &usage) == nil { + delete(usage, "output") + delete(usage, "chunks") + d["usage"] = usage + } + return d +} diff --git a/internal/cli/knowledgebase/query.go b/internal/cli/knowledgebase/query.go index ba5acb95..d92c7f53 100644 --- a/internal/cli/knowledgebase/query.go +++ b/internal/cli/knowledgebase/query.go @@ -37,6 +37,7 @@ func initQueryCmd(parent *cobra.Command) error { RunE: runQueryCmd, } flagutil.RegisterFlags(cmd, queryCmdMeta) + addShowDebugFlag(cmd) // answer.go: --show-debug if err := flagutil.ValidateMeta[operations.StableKnowledgeBaseControllerQueryRequest](queryCmdMeta); err != nil { return fmt.Errorf("invalid metadata for query: %w", err) } @@ -83,7 +84,7 @@ func runQueryCmd(cmd *cobra.Command, args []string) error { return output.Error(cmd, err) } - if err := output.Result(cmd, res); err != nil { + if err := showAnswer(cmd, res); err != nil { // answer.go: the answer first, then its sources; their text and the tokens with --show-debug return err } return nil diff --git a/internal/cli/outputview_test.go b/internal/cli/outputview_test.go index 72e234ca..f623c473 100644 --- a/internal/cli/outputview_test.go +++ b/internal/cli/outputview_test.go @@ -1,10 +1,12 @@ // 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/nodiff.go and +// knowledgebase/answer.go. package cli import ( "bytes" + "encoding/json" "io" "net/http" "net/http/httptest" @@ -94,3 +96,141 @@ func TestEnvironmentDiffSaysWhenThereAreNoDifferences(t *testing.T) { }) } } + +// kbChunks are two chunks as the API sends them: the better one second. +const kbChunks = `[ +{"score":0.18,"chunkID":"c-wiki","documentID":"d-wiki","content":"Cortado - Wikipedia\nJump to content","source":{"type":"url","name":"en.wikipedia.org/wiki/Cortado","url":"https://en.wikipedia.org/wiki/Cortado","title":"Cortado - Wikipedia"},"metadata":{}}, +{"score":0.3895,"chunkID":"c-faq","documentID":"d-faq","content":"Opening hours\nSaturday: 8 am to 4 pm","source":{"type":"text","name":"northwind-faq.txt"},"metadata":{}}]` + +// kbAnswer is a query's answer, after its token accounting and chunks; +// kbChunksOnly is the same query with --synthesis=false. +const ( + kbAnswer = `{"answer":{"model":"gpt-4o-mini","output":"8 am.","tokens":3900,"duration":812,"queryTokens":3806,"answerTokens":18,` + + `"inputMultiplier":1,"cacheMultiplier":0.56,"outputMultiplier":4,"cacheWriteTokens":0,"queryCachedTokens":256,"cacheWriteMultiplier":1.25,` + + `"queryRemainderTokens":3550,"base":{"queryTokens":3806,"answerTokens":5,"cacheWriteTokens":0,"queryCachedTokens":256},"chunks":` + kbChunks + `}}` + kbChunksOnly = `{"answer":{"model":"","output":null,"tokens":0,"duration":0,"queryTokens":0,"answerTokens":0,` + + `"inputMultiplier":0,"cacheMultiplier":0,"outputMultiplier":0,"cacheWriteTokens":0,"queryCachedTokens":0,"cacheWriteMultiplier":0,` + + `"queryRemainderTokens":0,"base":{"queryTokens":0,"answerTokens":0,"cacheWriteTokens":0,"queryCachedTokens":0},"chunks":` + kbChunks + `}}` +) + +// wantInOrder fails unless each of want is in out, in order, the first at +// the top. +func wantInOrder(t *testing.T, out string, want, not []string) { + t.Helper() + rest := out + for i, w := range want { + at := strings.Index(rest, w) + if at < 0 { + t.Fatalf("missing, or out of order: %q\n--- got:\n%s", w, out) + } + if i == 0 && at != 0 { + t.Errorf("%q isn't first:\n%s", w, out) + } + rest = rest[at+len(w):] + } + for _, n := range not { + if strings.Contains(out, n) { + t.Errorf("shows %q:\n%s", n, out) + } + } +} + +func TestKnowledgeBaseQueryShowsTheAnswerFirst(t *testing.T) { + query := []string{"knowledge-base", "query", "-p", "p1", "-e", "main", "-v", "draft", "--question", "When do you open on Saturday?"} + accounting := []string{"answerTokens", "cacheMultiplier", "queryRemainderTokens", "inputMultiplier"} + cases := []struct { + name string + body string + agent bool + args []string + want []string // in this order, from the top + not []string + }{ + { + name: "pretty", + body: kbAnswer, + want: []string{"Answer 8 am.\n", "Sources\n", " northwind-faq.txt 0.3895\n", " en.wikipedia.org/wiki/Cortado 0.18\n", "--show-debug shows them"}, + not: append([]string{"Opening hours", "chunkID", "c-faq"}, accounting...), + }, + { + name: "pretty --show-debug", + body: kbAnswer, + args: []string{"--show-debug"}, + want: []string{"Answer 8 am.\n", "northwind-faq.txt", "answerTokens:", "Opening hours"}, + not: []string{"--show-debug shows them"}, + }, + { + name: "pretty --synthesis=false", + body: kbChunksOnly, + args: []string{"--synthesis=false"}, + want: []string{"Sources\n", " northwind-faq.txt 0.3895\n Opening hours\n Saturday: 8 am to 4 pm\n", "en.wikipedia.org/wiki/Cortado", " Cortado - Wikipedia\n"}, + not: append([]string{"Answer", "--show-debug"}, accounting...), + }, + { + name: "TOON in agent mode", + body: kbAnswer, + agent: true, + want: []string{"answer: 8 am.\n", "sources[2]{documentID,name,score}:\n d-faq,northwind-faq.txt,0.3895\n d-wiki,en.wikipedia.org/wiki/Cortado,0.18\n", "textHidden:"}, + not: append([]string{"Opening hours"}, accounting...), + }, + { + name: "TOON --show-debug", + body: kbAnswer, + agent: true, + args: []string{"--show-debug"}, + want: []string{"answer: 8 am.\n", "sources[2]{content,documentID,name,score}:", "Opening hours", "usage:", "answerTokens: 18"}, + not: []string{"textHidden"}, + }, + { + name: "TOON --synthesis=false", + body: kbChunksOnly, + agent: true, + args: []string{"--synthesis=false"}, + want: []string{"sources[2]{content,documentID,name,score}:", "Opening hours", "Cortado - Wikipedia"}, + not: append([]string{"answer:", "textHidden", "usage"}, accounting...), + }, + { + name: "table --synthesis=false", + body: kbChunksOnly, + args: []string{"--synthesis=false", "-o", "table"}, + want: []string{"NAME", "en.wikipedia.org/wiki/Cortado", "northwind-faq.txt"}, + not: []string{"MODEL", "OUTPUT", "TOKENS", "MULTIPLIER", "DURATION"}, + }, + { + name: "table keeps the accounting of an answer", + body: kbAnswer, + args: []string{"-o", "table"}, + want: []string{"NAME", "northwind-faq.txt", "OUTPUT", "8 am.", "ANSWER TOKENS"}, + }, + { + name: "yaml is the whole response", + body: kbAnswer, + args: []string{"-o", "yaml"}, + want: []string{"answer:"}, + not: []string{"Sources", "textHidden"}, + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + url := viewServer(t, map[string]string{"/v1/stable/knowledge-base/query": c.body}) + out, _ := runView(t, url, c.agent, append(query, c.args...)...) + wantInOrder(t, out, c.want, c.not) + }) + } +} + +// -o json is the response as the API sent it. +func TestKnowledgeBaseQueryJSONIsTheResponseAsSent(t *testing.T) { + url := viewServer(t, map[string]string{"/v1/stable/knowledge-base/query": kbAnswer}) + out, _ := runView(t, url, true, "knowledge-base", "query", "-p", "p1", "-e", "main", "-v", "draft", "--question", "When?", "-o", "json") + var got, want any + if err := json.Unmarshal([]byte(out), &got); err != nil { + t.Fatalf("not JSON: %v\n%s", err, out) + } + _ = json.Unmarshal([]byte(kbAnswer), &want) + g, _ := json.Marshal(got) + w, _ := json.Marshal(want) + if string(g) != string(w) { + t.Errorf("-o json changed the response:\n got %s\nwant %s", g, w) + } +} From e1c80f754e8eb4128b71b329d72e02ae8a9f7639 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:22:53 -0500 Subject: [PATCH 07/28] fix(output): -o yaml prints the keys and values -o json prints MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit YAML was encoded from the SDK's Go structs, which have json tags and no yaml tags, so every key was the Go field name lowercased: `requestname`, `goesto`, `hascredits`. A `yq '.events[].goesTo'` script got null. Times were Go's (`…20:30:55Z` where JSON has `…20:30:55.000Z`), fields the API never sent appeared as empty strings, and each level was indented four spaces. YAML is now encoded from the JSON -o json prints: the response body as the API sent it, or the SDK's JSON for a result vf built. It goes through YAML nodes, so keys keep JSON's order and numbers every digit, and a string is quoted only where YAML would read it as something else. Two spaces indent each level, with --include-headers too. Round-4 sweep #15 (human-poweruser). --- internal/output/output.go | 5 +- internal/output/yamlkeys.go | 83 +++++++++++++++++++++++++ internal/output/yamlkeys_test.go | 100 +++++++++++++++++++++++++++++++ 3 files changed, 185 insertions(+), 3 deletions(-) create mode 100644 internal/output/yamlkeys.go create mode 100644 internal/output/yamlkeys_test.go diff --git a/internal/output/output.go b/internal/output/output.go index 4b117dd1..12df2d00 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -18,7 +18,6 @@ import ( "github.com/alpkeskin/gotoon" "github.com/spf13/cobra" - "gopkg.in/yaml.v3" "github.com/voiceflow/cli/internal/config" "github.com/voiceflow/cli/internal/flagutil" @@ -259,7 +258,7 @@ func Result(cmd *cobra.Command, res interface{}) (err error) { } printJSON(out, data, colorize) case "yaml": - data, err := yaml.Marshal(content) + data, err := marshalYAML(res, content) // yamlkeys.go: what -o json prints, as YAML indented two spaces if err != nil { return fmt.Errorf("failed to marshal response as YAML: %w", err) } @@ -672,7 +671,7 @@ func outputWithHeaders(out io.Writer, content interface{}, headers http.Header, switch format { case "yaml": - yamlData, err := yaml.Marshal(merged) + yamlData, err := marshalYAML(nil, merged) // yamlkeys.go: the JSON keys, as YAML indented two spaces if err != nil { return fmt.Errorf("failed to marshal response as YAML: %w", err) } diff --git a/internal/output/yamlkeys.go b/internal/output/yamlkeys.go new file mode 100644 index 00000000..180f0d0b --- /dev/null +++ b/internal/output/yamlkeys.go @@ -0,0 +1,83 @@ +// This file is not generated by Speakeasy. It makes -o yaml print what +// -o json prints: the same keys, in the same order, with the same values. +// +// YAML was encoded from the SDK's Go structs, which carry json tags and no +// yaml tags, so the encoder named every field by lowercasing its Go name: +// `requestname`, `goesto`, `hascredits`, `addcreditsurl`. A `yq +// '.events[].goesTo'` script got null. It also printed times as Go formats +// them (`…20:30:55Z`, where JSON has `…20:30:55.000Z`), added fields the +// API never sent, and indented four spaces. +// +// Now YAML is encoded from the JSON -o json prints: the response body as +// the API sent it, or, for a result vf made itself, the SDK's JSON for it +// (see jsonValue). The JSON is read into YAML nodes, so keys keep their +// order and numbers every digit. A string is quoted only where YAML would +// read it as something else (`"123"`, `"true"`, a timestamp), and two +// spaces indent each level. + +package output + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + + "gopkg.in/yaml.v3" +) + +// marshalYAML encodes content, the result of res, as YAML, from the JSON +// that -o json prints for it. +func marshalYAML(res, content interface{}) ([]byte, error) { + data := responseBody(res) + if data == nil { + var err error + if data, err = marshalJSON(content); err != nil { + return nil, err + } + } + // JSON is YAML, so the YAML parser reads it as it is: keys in order, and + // each number as the literal it was. + var doc yaml.Node + if err := yaml.Unmarshal(data, &doc); err != nil { + return nil, fmt.Errorf("failed to marshal response as YAML: %w", err) + } + blockStyle(&doc) + var out bytes.Buffer + enc := yaml.NewEncoder(&out) + enc.SetIndent(2) + if err := enc.Encode(&doc); err != nil { + return nil, fmt.Errorf("failed to marshal response as YAML: %w", err) + } + if err := enc.Close(); err != nil { + return nil, fmt.Errorf("failed to marshal response as YAML: %w", err) + } + return out.Bytes(), nil +} + +// responseBody is res's body as the API sent it, when it is JSON, and nil +// otherwise. The SDK puts the body back once it has decoded it, and so does +// this. +func responseBody(res interface{}) []byte { + httpRes := extractHTTPResponse(res) + if httpRes == nil || httpRes.Body == nil { + return nil + } + raw, err := io.ReadAll(httpRes.Body) + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewReader(raw)) + if err != nil || !json.Valid(raw) { + return nil + } + return raw +} + +// blockStyle drops the JSON styling the parser recorded, the braces, +// brackets and quotes, so the encoder writes block YAML and quotes a string +// only where it must. +func blockStyle(n *yaml.Node) { + n.Style = 0 + for _, child := range n.Content { + blockStyle(child) + } +} diff --git a/internal/output/yamlkeys_test.go b/internal/output/yamlkeys_test.go new file mode 100644 index 00000000..11e16d04 --- /dev/null +++ b/internal/output/yamlkeys_test.go @@ -0,0 +1,100 @@ +// This file is not generated by Speakeasy. It covers yamlkeys.go: -o yaml +// prints what -o json prints. + +package output + +import ( + "encoding/json" + "io" + "net/http" + "reflect" + "strings" + "testing" + "time" + + "gopkg.in/yaml.v3" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" +) + +// A result with no body to read, as a typed value, still gets the JSON +// keys: the struct has json tags and no yaml tags. +func TestYAMLKeysAreTheJSONKeys(t *testing.T) { + res := operations.StableCreditsControllerGetResponse{ + StableCreditsResponse: &components.StableCreditsResponse{Credits: components.StableCredits{HasCredits: true, AddCreditsURL: "https://example.com/billing"}}, + } + out := render(t, "yaml", res) + want := "credits:\n addCreditsURL: https://example.com/billing\n hasCredits: true\n" + if out != want { + t.Errorf("got:\n%s\nwant:\n%s", out, want) + } + if !strings.Contains(render(t, "json", res), `"addCreditsURL"`) { + t.Errorf("-o json names the key otherwise") + } +} + +// With the response body to hand, YAML is that body: its keys in its order, +// its timestamps as sent, every digit of a big number, and nothing the SDK's +// structs add. +func TestYAMLIsTheBodyAsSent(t *testing.T) { + body := `{"events":[{"id":"e1","requestName":"Order_Shipped","goesTo":"global_agent","workflowID":null,` + + `"isSystem":false,"createdAt":"2026-11-30T20:30:55.000Z","count":9007199254740993,` + + `"notes":"Line one\nLine two","code":"123","flag":"true","empty":"","yes":"yes","tags":[],"meta":{},` + + `"long":"` + strings.Repeat("word ", 40) + `end","quote":"a: b # c"}]}` + created := time.Date(2026, 11, 30, 20, 30, 55, 0, time.UTC) + goesTo := components.GoesTo("global_agent") + res := operations.StableEventControllerListResponse{ + HTTPMeta: components.HTTPMetadata{Response: &http.Response{Body: io.NopCloser(strings.NewReader(body))}}, + StableEventListResponse: &components.StableEventListResponse{Events: []components.StableEvent{ + {ID: "e1", RequestName: "Order_Shipped", GoesTo: &goesTo, CreatedAt: created, UpdatedAt: created}, + }}, + } + out := render(t, "yaml", res) + for _, want := range []string{ + "events:\n - id: e1\n requestName: Order_Shipped\n goesTo: global_agent\n workflowID: null\n", + `createdAt: "2026-11-30T20:30:55.000Z"`, + "count: 9007199254740993\n", + "notes: |-\n Line one\n Line two\n", + } { + if !strings.Contains(out, want) { + t.Errorf("missing %q\n--- got:\n%s", want, out) + } + } + for _, not := range []string{"requestname", "goesto", "updatedAt", "name:", " - "} { + if strings.Contains(out, not) { + t.Errorf("has %q\n--- got:\n%s", not, out) + } + } + + // Read back, it is the JSON value: no string became a number, a bool, + // null or a time, and no long line was folded. + var fromYAML, fromJSON any + if err := yaml.Unmarshal([]byte(out), &fromYAML); err != nil { + t.Fatalf("not YAML: %v\n%s", err, out) + } + if err := json.Unmarshal([]byte(body), &fromJSON); err != nil { + t.Fatal(err) + } + normal := func(v any) any { + b, _ := json.Marshal(v) + var n any + _ = json.Unmarshal(b, &n) + return n + } + if got, want := normal(fromYAML), normal(fromJSON); !reflect.DeepEqual(got, want) { + t.Errorf("YAML reads back as\n%v\nwant\n%v", got, want) + } +} + +// --include-headers YAML gets the JSON keys and two-space indent too. +func TestYAMLWithHeadersHasTheJSONKeys(t *testing.T) { + res := operations.StableCreditsControllerGetResponse{ + HTTPMeta: components.HTTPMetadata{Response: &http.Response{Header: http.Header{"X-Request-Id": {"r1"}}}}, + StableCreditsResponse: &components.StableCreditsResponse{Credits: components.StableCredits{HasCredits: true}}, + } + out := renderWith(t, "yaml", true, res) + if !strings.Contains(out, "credits:\n addCreditsURL: \"\"\n hasCredits: true\n") || !strings.Contains(out, "X-Request-Id: r1") { + t.Errorf("got:\n%s", out) + } +} From 36acdc0266115b713dba9e73f784bac56cdd5d08 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:28:45 -0500 Subject: [PATCH 08/28] fix(test): `test run get` shows the verdict, then the conversation Pretty `test run get` printed the run as it came: about 400 lines of logs, the agent's whole system prompt and every tool's schema among them, with `passed: true` and the check's reason at the very bottom. Its table listed each log's type and not one word of the conversation: the user's text is at payload.payload and the agent's at payload.payload.message, where no column reached. Pretty output now gives the verdict first (checks passed of the total, each check's reason, why a run failed), the run's ID, credits and time, then the turns as a chat reads, then a count of the other logs. The logs show with --show-debug, the flag `conversation send` and `knowledge-base query` use. Off a terminal a failed run reads "Failed:", not "Error:". The table brings a message two containers down up to a MESSAGE column. JSON, YAML, TOON and --jq print the run as sent. Round-4 sweep #13 (human-poweruser, fix-verifier). --- internal/cli/outputview_test.go | 84 +++++++- internal/cli/tableview_test.go | 13 +- internal/cli/test/run/get.go | 3 +- internal/cli/test/run/runview.go | 317 +++++++++++++++++++++++++++++++ internal/output/tableview.go | 33 +++- 5 files changed, 442 insertions(+), 8 deletions(-) create mode 100644 internal/cli/test/run/runview.go diff --git a/internal/cli/outputview_test.go b/internal/cli/outputview_test.go index f623c473..01b9a93b 100644 --- a/internal/cli/outputview_test.go +++ b/internal/cli/outputview_test.go @@ -1,6 +1,6 @@ // This file is not generated by Speakeasy. It covers the views commands add -// to pretty output for a person: environment/nodiff.go and -// knowledgebase/answer.go. +// to pretty output for a person: environment/nodiff.go, +// knowledgebase/answer.go and test/run/runview.go. package cli @@ -234,3 +234,83 @@ func TestKnowledgeBaseQueryJSONIsTheResponseAsSent(t *testing.T) { t.Errorf("-o json changed the response:\n got %s\nwant %s", g, w) } } + +// passedRun is a run as the API sends it: the verdict near the end of its +// logs, after a debug log carrying the agent's whole prompt. +const passedRun = `{"run":{"id":"R1","status":"passed","testID":"T1","failReason":null,"totalChecks":1,"passedChecks":1,"totalCredits":1.0055, +"createdAt":"2026-11-30T20:36:18.000Z","startedAt":"2026-11-30T20:36:19.000Z","finishedAt":"2026-11-30T20:36:21.000Z","logs":[ +{"id":"l1","type":"action","payload":{"type":"text","payload":"What is the capital of France?"},"createdAt":"2026-11-30T20:36:19.327Z","seq":0}, +{"id":"l2","type":"trace","payload":{"type":"block","payload":{"blockID":"start00000000000000000000"},"time":1,"turnID":"t1"},"createdAt":"2026-11-30T20:36:19.400Z","seq":1}, +{"id":"l3","type":"trace","payload":{"type":"debug","payload":{"type":"agent","message":"starting execution","metadata":{"assistant":"# Starting message\n\nGreet the user."}},"time":2,"turnID":"t1"},"createdAt":"2026-11-30T20:36:19.410Z","seq":2}, +{"id":"l4","type":"trace","payload":{"type":"text","payload":{"message":"Paris.\nAnything else?"},"time":3,"turnID":"t1"},"createdAt":"2026-11-30T20:36:19.630Z","seq":3}, +{"id":"l5","type":"trace","payload":{"type":"choice","payload":{"buttons":[{"name":"Yes"},{"name":"No"}]},"time":4,"turnID":"t1"},"createdAt":"2026-11-30T20:36:19.640Z","seq":4}, +{"id":"l6","type":"trace","payload":{"type":"simulation-test-result","payload":{"passed":true,"reason":"The agent answered Paris.","testID":"T1","testType":"response","turnID":"u1"},"time":5},"createdAt":"2026-11-30T20:36:20.764Z","seq":5}, +{"id":"l7","type":"end","payload":{"reason":"test ended"},"createdAt":"2026-11-30T20:36:20.773Z","seq":6}]}}` + +func TestTestRunGetShowsTheVerdictThenTheTurns(t *testing.T) { + get := []string{"test", "run", "get", "-p", "p1", "-e", "main", "--run-id", "R1"} + failed := strings.NewReplacer(`"status":"passed"`, `"status":"failed"`, `"passedChecks":1`, `"passedChecks":0`, + `"failReason":null`, `"failReason":"1 check failed"`, `"passed":true,"reason":"The agent answered Paris."`, + `"passed":false,"reason":"It never said Paris."`).Replace(passedRun) + cases := []struct { + name string + body string + agent bool + args []string + want []string // in this order, from the top + not []string + }{ + { + name: "passed", + body: passedRun, + want: []string{ + "Passed: 1 of 1 checks passed\n", + " + The agent answered Paris.\n", + "Run R1 of test T1 | 1.0055 credits | took 2s\n\n", + "User What is the capital of France?\nAgent Paris.\n Anything else?\n [buttons: Yes | No]\n\n", + "3 other logs (block, debug, end) | --show-debug shows them\n", + }, + not: []string{"Greet the user", "blockID", "seq:", "Error:"}, + }, + { + name: "failed", + body: failed, + want: []string{"Failed: 0 of 1 checks passed\n", " Why: 1 check failed\n", " x It never said Paris.\n", "User What is the capital"}, + not: []string{"Error:"}, + }, + { + name: "not finished", + body: `{"run":{"id":"R1","status":"idle","testID":"T1","failReason":null,"totalChecks":2,"passedChecks":null,"totalCredits":0,"createdAt":"2026-11-30T20:36:18.000Z","startedAt":null,"finishedAt":null,"logs":[]}}`, + want: []string{"Not finished (idle): 2 checks\n", "Run R1 of test T1\n", "\nNo logs yet.\n"}, + not: []string{"credits", "took"}, + }, + { + name: "--show-debug", + body: passedRun, + args: []string{"--show-debug"}, + want: []string{"Passed: 1 of 1 checks passed\n", "Agent Paris.", "logs:\n", "blockID:", "assistant: |\n"}, + not: []string{"--show-debug shows them"}, + }, + { + name: "TOON in agent mode is the run as sent", + body: passedRun, + agent: true, + want: []string{"run:\n", "logs[7]:", "blockID: start00000000000000000000"}, + not: []string{"Passed:", "--show-debug"}, + }, + { + name: "yaml is the run as sent", + body: passedRun, + args: []string{"-o", "yaml"}, + want: []string{"run:\n", "blockID: start00000000000000000000"}, + not: []string{"Passed:"}, + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + url := viewServer(t, map[string]string{"/v1/stable/test-run/R1": c.body}) + out, _ := runView(t, url, c.agent, append(get, c.args...)...) + wantInOrder(t, out, c.want, c.not) + }) + } +} diff --git a/internal/cli/tableview_test.go b/internal/cli/tableview_test.go index 2bcae3d5..dfe6c10b 100644 --- a/internal/cli/tableview_test.go +++ b/internal/cli/tableview_test.go @@ -95,15 +95,20 @@ func TestOutputTableShowsWhatAConversationSaid(t *testing.T) { } // fix-verifier:N5: a test run's logs printed as `UNKNOWNRAW TYPE`, then -// the run. +// the run. Round-4 #13: then each log's type, and neither the user's words +// (payload.payload) nor the agent's (payload.payload.message). func TestOutputTableShowsATestRunsLogs(t *testing.T) { lines := tableLines(t, `{"run":{"id":"R1","testID":"T1","status":"passed","failReason":null,"totalChecks":1,"passedChecks":1,"totalCredits":0.5,"createdAt":"2026-11-30T17:24:13Z", "logs":[{"id":"l1","type":"action","payload":{"type":"launch"},"createdAt":"2026-11-30T17:24:14Z","seq":1}, - {"id":"l2","type":"trace","payload":{"type":"text","payload":{"message":"Hi"}},"createdAt":"2026-11-30T17:24:15Z","seq":2}]}}`, + {"id":"l2","type":"trace","payload":{"type":"text","payload":{"message":"Hi"}},"createdAt":"2026-11-30T17:24:15Z","seq":2}, + {"id":"l3","type":"action","payload":{"type":"text","payload":"Where is my order?"},"createdAt":"2026-11-30T17:24:16Z","seq":3}, + {"id":"l4","type":"trace","payload":{"type":"block","payload":{"blockID":"b1"}},"createdAt":"2026-11-30T17:24:17Z","seq":4}]}}`, "test", "run", "get", "-p", "p1", "-e", "main", "--run-id", "R1") wantLines(t, lines, - "ID TYPE PAYLOAD TYPE CREATED AT SEQ", + "ID TYPE PAYLOAD TYPE MESSAGE CREATED AT SEQ", "l1 action launch 2026-11-30T17:24:14Z 1", - "l2 trace text 2026-11-30T17:24:15Z 2", + "l2 trace text Hi 2026-11-30T17:24:15Z 2", + "l3 action text Where is my order? 2026-11-30T17:24:16Z 3", + "l4 trace block 2026-11-30T17:24:17Z 4", "STATUS passed") } diff --git a/internal/cli/test/run/get.go b/internal/cli/test/run/get.go index c03fd568..919166ce 100644 --- a/internal/cli/test/run/get.go +++ b/internal/cli/test/run/get.go @@ -31,6 +31,7 @@ func initGetCmd(parent *cobra.Command) error { RunE: runGetCmd, } flagutil.RegisterFlags(cmd, getCmdMeta) + addShowDebugFlag(cmd) // runview.go: --show-debug if err := flagutil.ValidateMeta[operations.StableTestRunControllerGetRequest](getCmdMeta); err != nil { return fmt.Errorf("invalid metadata for get: %w", err) } @@ -76,7 +77,7 @@ func runGetCmd(cmd *cobra.Command, args []string) error { return output.Error(cmd, err) } - if err := output.Result(cmd, res); err != nil { + if err := showRun(cmd, res); err != nil { // runview.go: the verdict, then the turns; the logs with --show-debug return err } return nil diff --git a/internal/cli/test/run/runview.go b/internal/cli/test/run/runview.go new file mode 100644 index 00000000..a07eb4ea --- /dev/null +++ b/internal/cli/test/run/runview.go @@ -0,0 +1,317 @@ +// This file is not generated by Speakeasy. It shows `vf test run get` the +// way `test run wait` reads: the verdict first, then the conversation. +// +// A run comes back with every log the runtime wrote: blocks, debug messages +// carrying the agent's whole system prompt and each tool's JSON schema, the +// turns, and, near the end, each check's verdict and reason. Printed as it +// came, that was about 400 lines for one short test, with `passed: true` at +// the very bottom. +// +// So pretty output now gives the verdict (how many checks passed, each +// check's reason, why the run failed), then the turns as a chat reads, then +// a count of the other logs. --show-debug prints the logs too, the flag +// `conversation send` and `knowledge-base query` use. JSON, YAML, TOON, +// tables and --jq still print the run as the API sent it. + +package run + +import ( + "encoding/json" + "fmt" + "io" + "sort" + "strconv" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/ui" +) + +const showDebugFlag = "show-debug" + +// addShowDebugFlag lets cmd show a run's logs. +func addShowDebugFlag(cmd *cobra.Command) { + cmd.Flags().Bool(showDebugFlag, false, "Also show the run's logs: blocks, debug messages, tool calls and the like. Without it, vf shows the verdict and the conversation and counts the rest. -o json always prints every log.") +} + +// check is one check's verdict, as a run's logs record it. +type check struct { + passed bool + reason string +} + +// line is one thing said in a run: by the user or by the agent. +type line struct { + agent bool + text string +} + +// runLogs is what a run's logs say, read for a person. +type runLogs struct { + checks []check + said []line + hidden []string // the kind of each log not shown, in order +} + +// showRun prints `test run get`'s result: the run as sent for every format +// but pretty, and for a person the verdict, then the turns. +func showRun(cmd *cobra.Command, res *operations.StableTestRunControllerGetResponse) error { + headers, _ := flagutil.GetBoolFlag(cmd, "include-headers") + if res == nil || res.StableTestRunResponse == nil || client.IsDryRun(cmd) || headers || !output.ForAPerson(cmd) { + return output.Result(cmd, res) + } + run := res.StableTestRunResponse.Run + var logs []map[string]any + raw, err := json.Marshal(run.Logs) + if err != nil || json.Unmarshal(raw, &logs) != nil { + return output.Result(cmd, res) + } + debug, _ := cmd.Flags().GetBool(showDebugFlag) + out, done := output.ResultWriter(cmd) + writeRun(output.UI(cmd, cmd.OutOrStdout()), out, run, readRunLogs(logs), debug) + done() + if debug && len(run.Logs) > 0 { + fmt.Fprintln(cmd.OutOrStdout()) + return output.Result(cmd, map[string]any{"logs": run.Logs}) + } + return nil +} + +// readRunLogs reads the checks and the turns out of a run's logs, in order. +// A streamed completion's pieces join into the one message they make. +func readRunLogs(logs []map[string]any) runLogs { + var r runLogs + var streaming *strings.Builder + for _, entry := range logs { + kind, _ := entry["type"].(string) + payload, _ := entry["payload"].(map[string]any) + inner := payload["payload"] + body, _ := inner.(map[string]any) + traceType, _ := payload["type"].(string) + switch kind { + case "action": + if text := userText(traceType, inner); text != "" { + r.said = append(r.said, line{text: text}) + continue + } + case "trace": + switch traceType { + case "simulation-test-result": + if body == nil { + body = payload + } + passed, _ := body["passed"].(bool) + reason, _ := body["reason"].(string) + r.checks = append(r.checks, check{passed: passed, reason: reason}) + continue + case "text", "speak": + if msg, _ := body["message"].(string); msg != "" { + r.said = append(r.said, line{agent: true, text: msg}) + continue + } + case "choice": + if b := buttons(body["buttons"]); b != "" { + r.said = append(r.said, line{agent: true, text: b}) + continue + } + case "completion": + state, _ := body["state"].(string) + switch state { + case "start": + streaming = &strings.Builder{} + case "content": + if streaming != nil { + piece, _ := body["content"].(string) + streaming.WriteString(piece) + } + case "end": + if streaming != nil && streaming.Len() > 0 { + r.said = append(r.said, line{agent: true, text: streaming.String()}) + } + streaming = nil + } + continue + } + } + if traceType != "" { + kind = traceType // a launch action, a block or debug trace + } + r.hidden = append(r.hidden, kind) + } + return r +} + +// userText is what an action said: a text action's words, or the query of +// one that carries one. Empty for an action that said nothing. +func userText(actionType string, payload any) string { + if text, ok := payload.(string); ok && actionType == "text" { + return text + } + body, _ := payload.(map[string]any) + for _, key := range []string{"query", "label", "message"} { + if text, _ := body[key].(string); text != "" { + return text + } + } + return "" +} + +// buttons is "[buttons: Yes | No]", as `conversation send` shows them. +func buttons(v any) string { + list, _ := v.([]any) + var names []string + for _, b := range list { + m, _ := b.(map[string]any) + if name, _ := m["name"].(string); name != "" { + names = append(names, name) + } + } + if len(names) == 0 { + return "" + } + return "[buttons: " + strings.Join(names, " | ") + "]" +} + +// writeRun prints a run for a person: +// +// ✓ Passed: 1 of 1 checks passed +// ✓ The agent answered Paris, the capital of France. +// Run 6b0dde8c… of test 6b0dde42… · 1.0055 credits · took 2s +// +// User What is the capital of France? +// Agent Paris. +// +// 3 other logs (block, debug, end) · --show-debug shows them +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) + } + for _, c := range r.checks { + mark := u.Success(u.Glyph(ui.Done)) + if !c.passed { + mark = u.Error(u.Glyph(ui.Failed)) + } + reason := c.reason + if reason == "" { + reason = u.Muted("(no reason given)") + } + writeIndented(out, " ", mark+" "+reason) + } + sep := " " + u.Glyph(ui.Separator) + " " + about := []string{"Run " + run.ID + " of test " + run.TestID} + if run.TotalCredits > 0 { + about = append(about, strconv.FormatFloat(run.TotalCredits, 'f', -1, 64)+" credits") + } + 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))) + + if len(r.said) > 0 { + fmt.Fprintln(out) + } + for i, l := range r.said { + label := "User " + if l.agent { + label = "Agent " + } + lead := u.Bold(label) + if i > 0 && r.said[i-1].agent == l.agent { + lead = strings.Repeat(" ", len(label)) + } + for j, text := range strings.Split(strings.TrimRight(l.text, "\n"), "\n") { + if j > 0 { + lead = strings.Repeat(" ", len(label)) + } + if l.agent && strings.HasPrefix(l.text, "[") { + text = u.Accent(text) + } + fmt.Fprintln(out, strings.TrimRight(lead+text, " ")) + } + } + + switch { + case len(r.said)+len(r.checks)+len(r.hidden) == 0: + fmt.Fprintln(out) + fmt.Fprintln(out, u.Muted("No logs yet.")) + case len(r.hidden) > 0 && !debug: + fmt.Fprintln(out) + fmt.Fprintln(out, u.Muted(hiddenNote(r.hidden)+sep+"--show-debug shows them")) + } +} + +// verdict is the run's outcome in one line: "✓ Passed: 1 of 1 checks passed". +func verdict(u *ui.UI, run components.StableTestRun) string { + checks := fmt.Sprintf("%d %s", int(run.TotalChecks), plural(int(run.TotalChecks), "check")) + if run.PassedChecks != nil { + checks = fmt.Sprintf("%d of %d checks passed", int(*run.PassedChecks), int(run.TotalChecks)) + } + kind := ui.StatusInfo + msg := "" + switch run.Status { + case components.StableTestRunStatusPassed: + kind, msg = ui.StatusDone, "Passed: "+checks + case components.StableTestRunStatusFailed: + kind, msg = ui.StatusFailed, "Failed: "+checks + case components.StableTestRunStatusCanceled: + kind, msg = ui.StatusFailed, "Canceled: "+checks + default: + msg = "Not finished (" + string(run.Status) + "): " + checks + } + if !u.Decorated() { + return msg // a failed run is not vf's error, so no "Error:" off a terminal + } + return u.Status(kind, msg) +} + +// hiddenNote counts the logs not shown, by kind: "4 other logs (debug ×2, block, end)". +func hiddenNote(hidden []string) string { + counts := map[string]int{} + for _, kind := range hidden { + counts[kind]++ + } + kinds := make([]string, 0, len(counts)) + for kind := range counts { + kinds = append(kinds, kind) + } + sort.Slice(kinds, func(i, j int) bool { + if counts[kinds[i]] != counts[kinds[j]] { + return counts[kinds[i]] > counts[kinds[j]] + } + return kinds[i] < kinds[j] + }) + parts := make([]string, len(kinds)) + for i, kind := range kinds { + parts[i] = kind + if counts[kind] > 1 { + parts[i] += fmt.Sprintf(" ×%d", counts[kind]) + } + } + return fmt.Sprintf("%d other %s (%s)", len(hidden), plural(len(hidden), "log"), strings.Join(parts, ", ")) +} + +func plural(n int, noun string) string { + if n == 1 { + return noun + } + return noun + "s" +} + +// 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) { + for i, l := range strings.Split(strings.TrimRight(text, "\n"), "\n") { + if i > 0 { + l = " " + l + } + fmt.Fprintln(out, strings.TrimRight(indent+l, " ")) + } +} diff --git a/internal/output/tableview.go b/internal/output/tableview.go index 1faaa9f5..20859ae4 100644 --- a/internal/output/tableview.go +++ b/internal/output/tableview.go @@ -27,7 +27,9 @@ // So the table is now built from the response's JSON, as -o json prints it: // a union is the kind the API returned. Its columns are every row's plain // fields, in the order the API sends them, plus the name, title, type, -// status, message or text of a field that is an object, one level down. +// status, message or text of a field that is an object, one level down. A +// message two containers down (a test run's log: payload.payload.message, +// or the user's words at payload.payload) is brought up to that level. // `status: {"type": "SUCCESS"}` is a STATUS column. A column no row has a // value for is left out, and id, name, type, status and message come first. // @@ -216,6 +218,34 @@ func promotedFields(obj *jsonObject) []string { // "type" is the row's type, not theirs. var containers = map[string]bool{"data": true, "payload": true} +// liftNestedText gives a row whose text sits in a container inside a +// container a message one level down, where a column reaches it. A test +// run's log holds what the user said at payload.payload and what the agent +// said at payload.payload.message, so its table showed every turn's type +// and not one word of it. +func liftNestedText(row *jsonObject) { + for _, outer := range []string{"payload", "data"} { + obj, ok := row.values[outer].(*jsonObject) + if !ok || obj.values["message"] != nil || obj.values["text"] != nil { + continue + } + for _, inner := range []string{"payload", "data"} { + text, _ := obj.values[inner].(string) + if in, ok := obj.values[inner].(*jsonObject); ok { + text, _ = in.values["message"].(string) + if text == "" { + text, _ = in.values["text"].(string) + } + } + if text != "" { + obj.keys = append(obj.keys, "message") + obj.values["message"] = text + break + } + } + } +} + // firstColumns come before the rest, in this order. var firstColumns = []string{"id", "name", "title", "type", "status", "message", "text"} @@ -238,6 +268,7 @@ func printRows(out io.Writer, items []any, width int) error { var rows []*jsonObject for _, item := range items { if row, ok := item.(*jsonObject); ok { + liftNestedText(row) rows = append(rows, row) } } From 04f22b64d50bc9b47a315fe322d8105df52d6251 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:33:45 -0500 Subject: [PATCH 09/28] fix(output): TOON output ends with a newline The TOON encoder returns its text with no final newline, and vf printed it as it came. TOON is agent mode's default, so whatever came next ran onto the result's last line: `echo EXIT=$?` gave `workspaceID: VzElNm0wjLEXIT=0`, a `message: Project ... deleted.` ran into the next command's output, the error envelope on stderr began on the result's last line (`waitedSeconds: 0{`), and `vf ... | while read line` dropped the last line altogether. Both TOON prints (a result, and a result with --include-headers) now end with one newline, as JSON, YAML, pretty output and tables do. An empty result still prints nothing. Round-4 sweep #26 (fix-verifier, agent-builder, agent-migrator, human-kb). --- internal/output/endline.go | 23 +++++++++++++++++++ internal/output/endline_test.go | 39 +++++++++++++++++++++++++++++++++ internal/output/output.go | 4 ++-- internal/output/toon_test.go | 2 +- test/toon-output.test.ts | 10 +++++++-- 5 files changed, 73 insertions(+), 5 deletions(-) create mode 100644 internal/output/endline.go create mode 100644 internal/output/endline_test.go diff --git a/internal/output/endline.go b/internal/output/endline.go new file mode 100644 index 00000000..0777e1ca --- /dev/null +++ b/internal/output/endline.go @@ -0,0 +1,23 @@ +// This file is not generated by Speakeasy. It ends TOON output with a +// newline, as JSON, YAML, pretty output and tables end. +// +// The TOON encoder returns its text with no final newline, and vf printed +// it as it came. TOON is agent mode's default, so whatever came next ran +// onto the last line: the shell's prompt or an `echo EXIT=$?` gave +// `workspaceID: VzElNm0wjLEXIT=0`, a `message: Project … deleted.` ran into +// the next command's output, and the error envelope on stderr began on the +// result's last line (`waitedSeconds: 0{`). `vf … | while read line` +// dropped the last line altogether. + +package output + +import "strings" + +// endLine is s ending in a newline. Nothing stays nothing: an empty result +// prints no blank line. +func endLine(s string) string { + if s == "" || strings.HasSuffix(s, "\n") { + return s + } + return s + "\n" +} diff --git a/internal/output/endline_test.go b/internal/output/endline_test.go new file mode 100644 index 00000000..f5626026 --- /dev/null +++ b/internal/output/endline_test.go @@ -0,0 +1,39 @@ +// This file is not generated by Speakeasy. It covers endline.go: TOON ends +// with one newline, as every other format does. + +package output + +import ( + "net/http" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" +) + +func TestEveryFormatEndsWithOneNewline(t *testing.T) { + credits := &components.StableCreditsResponse{Credits: components.StableCredits{HasCredits: true}} + withHeaders := operations.StableCreditsControllerGetResponse{ + HTTPMeta: components.HTTPMetadata{Response: &http.Response{Header: http.Header{"X-Request-Id": {"r1"}}}}, + StableCreditsResponse: credits, + } + for _, format := range []string{"toon", "json", "yaml", "pretty", "table"} { + for name, out := range map[string]string{ + "a record": renderWith(t, format, false, operations.StableCreditsControllerGetResponse{StableCreditsResponse: credits}), + "a message": renderWith(t, format, false, map[string]any{"message": "Project p1 deleted."}), + "a result with --headers": renderWith(t, format, true, withHeaders), + } { + if !strings.HasSuffix(out, "\n") || strings.HasSuffix(out, "\n\n") { + t.Errorf("%s, %s: doesn't end with one newline: %q", format, name, out[max(0, len(out)-40):]) + } + } + } +} + +// An empty result prints nothing, not a blank line. +func TestAnEmptyTOONResultPrintsNothing(t *testing.T) { + if out := render(t, "toon", map[string]any{}); out != "" { + t.Errorf("got %q", out) + } +} diff --git a/internal/output/output.go b/internal/output/output.go index 12df2d00..c8e7ccb2 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -277,7 +277,7 @@ func Result(cmd *cobra.Command, res interface{}) (err error) { if err != nil { return fmt.Errorf("failed to encode response as TOON: %w", err) } - fmt.Fprint(out, toonStr) + fmt.Fprint(out, endLine(toonStr)) // endline.go: TOON ends with a newline, as the other formats do default: // "pretty" or unset if writeDocument(cmd, out, content) { // document.go: a prompt's page, as a document return nil @@ -681,7 +681,7 @@ func outputWithHeaders(out io.Writer, content interface{}, headers http.Header, if err != nil { return fmt.Errorf("failed to encode response as TOON: %w", err) } - fmt.Fprint(out, toonStr) + fmt.Fprint(out, endLine(toonStr)) // endline.go: TOON ends with a newline, as the other formats do default: // "json" or any other jsonData, err := json.MarshalIndent(merged, "", " ") if err != nil { diff --git a/internal/output/toon_test.go b/internal/output/toon_test.go index e3b4d1c5..9b603fc9 100644 --- a/internal/output/toon_test.go +++ b/internal/output/toon_test.go @@ -160,7 +160,7 @@ func TestTOONIsTheJSONOutputReencoded(t *testing.T) { if err != nil { t.Fatal(err) } - if got := render(t, "toon", res); got != want { + if got := render(t, "toon", res); got != want+"\n" { // endline.go: and a final newline t.Errorf("%s: TOON differs from the JSON output re-encoded\n got:\n%s\nwant:\n%s", name, got, want) } } diff --git a/test/toon-output.test.ts b/test/toon-output.test.ts index 350c049d..b09a2576 100644 --- a/test/toon-output.test.ts +++ b/test/toon-output.test.ts @@ -75,10 +75,10 @@ afterAll(async () => { fs.rmSync(home, { recursive: true, force: true }); }); -function run(args: string[]) { +function run(args: string[], { stripFinalNewline = true } = {}) { const env: Record = Object.fromEntries(AGENT_ENV_VARS.map((name) => [name, undefined])); Object.assign(env, { HOME: home, VF_TOKEN: 'vfp_test', CLAUDECODE: '1' }); - return execa({ reject: false, timeout: 20_000, stdin: 'ignore', env, extendEnv: true })(VF, [...args, '--server-url', serverURL]); + return execa({ reject: false, timeout: 20_000, stdin: 'ignore', env, extendEnv: true, stripFinalNewline })(VF, [...args, '--server-url', serverURL]); } describe('TOON output in agent mode', () => { @@ -95,6 +95,12 @@ describe('TOON output in agent mode', () => { expect(result.stdout).toContain(INSTRUCTIONS); }); + it('ends with a newline, so what is printed next starts a line of its own', async () => { + const result = await run(['agent', 'get', ...PROJECT, '--include-instructions'], { stripFinalNewline: false }); + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stdout).toMatch(/[^\n]\n$/); + }); + it('renders a union as the API returns it, not as its Go wrapper', async () => { const result = await run(['tool', 'list', ...PROJECT, '--global', '--output-format', 'toon']); expect(result.exitCode, result.stderr).toBe(0); From 736c10d9b9882b8adfe6d36c0cf0464dbd8b8feb Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:15:30 -0500 Subject: [PATCH 10/28] fix(tool): a bare tool list lists the agent's own tools MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The API lists one target's tools, the agent's (global) or a playbook's, and neither flag was required. So `vf tool list -p … -e main`, run as help showed it, got HTTP 400 "Tool target does not exist.", which named no flag. Without --global or --playbook-id vf now asks for the agent's tools, and help says so and shows a playbook's. --global=false alone and --global with --playbook-id are refused before sending, exit 2, naming the flag that fixes each. get, update and delete take a tool ID and no target, so they weren't affected. Found by the round-4 sweep's agent-migrator and fix-verifier. --- internal/cli/tool/list.go | 4 + internal/cli/tool/target.go | 58 +++++++++++++ internal/cli/tooltarget_test.go | 148 ++++++++++++++++++++++++++++++++ 3 files changed, 210 insertions(+) create mode 100644 internal/cli/tool/target.go create mode 100644 internal/cli/tooltarget_test.go diff --git a/internal/cli/tool/list.go b/internal/cli/tool/list.go index 345e86ab..4c968cd1 100644 --- a/internal/cli/tool/list.go +++ b/internal/cli/tool/list.go @@ -33,6 +33,7 @@ func initListCmd(parent *cobra.Command) error { RunE: runListCmd, } flagutil.RegisterFlags(cmd, listCmdMeta) + explainListTarget(cmd) // target.go: help says whose tools it lists by default if err := flagutil.ValidateMeta[operations.StableToolControllerListV2Request](listCmdMeta); err != nil { return fmt.Errorf("invalid metadata for list: %w", err) } @@ -54,6 +55,9 @@ func runListCmd(cmd *cobra.Command, args []string) error { if err != nil { return err } + if err := listTarget(req); err != nil { // target.go: no target lists the agent's tools, not a 400 + return err + } s, err := client.NewClient(cmd) if err != nil { return err diff --git a/internal/cli/tool/target.go b/internal/cli/tool/target.go new file mode 100644 index 00000000..165043e2 --- /dev/null +++ b/internal/cli/tool/target.go @@ -0,0 +1,58 @@ +// This file is not generated by Speakeasy. It has `vf tool list` list the +// agent's own tools when it isn't told whose to list. +// +// The API lists the tools of one target: the agent (global=true) or one +// playbook (playbookID). Neither flag is required, and help's example gave +// neither, so `vf tool list -p … -e main`, run as help showed it, got +// HTTP 400 "Tool target does not exist." It named no flag, and testers took +// --help, then --dry-run, to find --global. The agent's own tools are what +// "list the tools" means when no playbook is named, so vf asks for those, +// and help says so. --global=false with no playbook names no target, and +// --global with a playbook names two, so both are refused before sending. + +package tool + +import ( + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/usage" +) + +// explainListTarget says in list's help, and in --global's, whose tools it +// lists without --global or --playbook-id, and shows a playbook's. +func explainListTarget(cmd *cobra.Command) { + cmd.Long += " Without --global or --playbook-id it lists the agent's own tools, as --global does." + cmd.Example += "\n vf tool list --project-id --environment-alias --playbook-id " + if f := cmd.Flags().Lookup("global"); f != nil { + f.Usage = "List the agent's own tools, not a playbook's. The default without --playbook-id." + _ = cmd.Flags().SetAnnotation("global", usage.OwnHelp, []string{"true"}) + } +} + +// listTarget gives req a target: the agent's when it names none. It refuses +// --global=false alone, which names none, and --global with --playbook-id, +// which name two. +func listTarget(req *operations.StableToolControllerListV2Request) error { + agent := req.Global != nil && *req.Global + switch { + case req.PlaybookID == nil && req.Global == nil: + req.Global = &[]bool{true}[0] + case req.PlaybookID == nil && !agent: + return &flagutil.FlagValueError{ + Flag: "global", + Value: "false", + Expected: "with --global=false, tool list needs --playbook-id to name the playbook whose tools it lists", + Hints: []string{"Add --playbook-id ('vf playbook list' lists them), or drop --global=false to list the agent's own tools"}, + } + case req.PlaybookID != nil && agent: + return &flagutil.FlagValueError{ + Flag: "playbook-id", + Value: *req.PlaybookID, + Expected: "--global and --playbook-id each name whose tools to list; give one", + Hints: []string{"Drop --global to list this playbook's tools, or drop --playbook-id for the agent's"}, + } + } + return nil +} diff --git a/internal/cli/tooltarget_test.go b/internal/cli/tooltarget_test.go new file mode 100644 index 00000000..0ec317ca --- /dev/null +++ b/internal/cli/tooltarget_test.go @@ -0,0 +1,148 @@ +// This file is not generated by Speakeasy. It covers tool/target.go: `vf +// tool list` without --global or --playbook-id lists the agent's own tools. + +package cli + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// toolListServer answers a tool list as the API does: HTTP 400 "Tool target +// does not exist." unless global or playbookID names a target. It records +// each request's query. +func toolListServer(t *testing.T) (url string, queries func() []string) { + t.Helper() + var mu sync.Mutex + var seen []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + mu.Lock() + seen = append(seen, r.URL.RawQuery) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + q := r.URL.Query() + if q.Get("global") != "true" && q.Get("playbookID") == "" { + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, `{"statusCode":400,"message":"Tool target does not exist.","error":"Bad Request"}`) + return + } + io.WriteString(w, `{"tools":[]}`) + })) + t.Cleanup(srv.Close) + return srv.URL, func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), seen...) + } +} + +// runTool runs `vf tool ` against url, and returns what it printed. +func runTool(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(append([]string{"tool"}, args...), mode, "--no-interactive")) + err = renderError(root.ExecuteC()) // as Execute reports it, with its exit code + return out.String(), errOut.String(), err +} + +func TestToolListWithoutATargetListsTheAgentsTools(t *testing.T) { + url, queries := toolListServer(t) + stdout, stderr, err := runTool(t, url, false, "list", "--project-id", "p1", "--environment-alias", "main") + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if got := queries(); len(got) != 1 || !strings.Contains(got[0], "global=true") || strings.Contains(got[0], "playbookID") { + t.Errorf("queries = %q, want one with global=true", got) + } + if !strings.Contains(stdout, "tools") { + t.Errorf("the tools weren't printed:\n%s", stdout) + } + + // A playbook is listed as asked, with no global. + url, queries = toolListServer(t) + if _, stderr, err := runTool(t, url, false, "list", "-p", "p1", "-e", "main", "--playbook-id", "pb1"); err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if got := queries(); len(got) != 1 || !strings.Contains(got[0], "playbookID=pb1") || strings.Contains(got[0], "global") { + t.Errorf("queries = %q, want playbookID=pb1 alone", got) + } +} + +// Flags that name no target, or two, are refused before anything is sent, +// with exit 2 and the flags that fix it. +func TestToolListRefusesNoTargetOrTwo(t *testing.T) { + for _, c := range []struct { + name string + args []string + says string + }{ + {"--global=false alone", []string{"--global=false"}, "--playbook-id"}, + {"--global with a playbook", []string{"--global", "--playbook-id", "pb1"}, "give one"}, + } { + t.Run(c.name, func(t *testing.T) { + url, queries := toolListServer(t) + _, stderr, err := runTool(t, url, true, append([]string{"list", "-p", "p1", "-e", "main"}, c.args...)...) + if code := output.ExitCode(err); code != output.ExitUsage { + t.Errorf("exit %d, want %d: %v", code, output.ExitUsage, err) + } + if got := queries(); len(got) != 0 { + t.Errorf("sent %q", got) + } + if !strings.Contains(stderr, c.says) || !strings.Contains(stderr, "invalid_flag_value") { + t.Errorf("stderr doesn't say %q:\n%s", c.says, stderr) + } + }) + } +} + +// Help says what a bare list lists, and each example runs as written. +func TestToolListHelpSaysWhoseToolsItLists(t *testing.T) { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + list, _, err := root.Find([]string{"tool", "list"}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(list.Long, "Without --global or --playbook-id it lists the agent's own tools") { + t.Errorf("Long: %s", list.Long) + } + for _, line := range strings.Split(list.Example, "\n") { + words := strings.Fields(strings.NewReplacer("", "x1", "", "main").Replace(line)) + if len(words) < 3 { + continue + } + url, queries := toolListServer(t) + if _, stderr, err := runTool(t, url, false, words[2:]...); err != nil { + t.Errorf("%s: %v\n%s", line, err, stderr) + } + if len(queries()) != 1 { + t.Errorf("%s: sent %q", line, queries()) + } + } +} From d65b0f33d86d5fe68eba7a3f96899e946b88853e Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:23:00 -0500 Subject: [PATCH 11/28] fix(tool): a function tool that leaves out its function's inputs says so MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A function tool hands the agent's values to its function only through inputVariables, one entry per input keyed by the input's name. Left out, the map was sent empty, and help showed it as `inputVariables?: { : {…} }`, so a tester's lookup_order tool saved with no inputs and nothing said so. Help for tool create and update now spells out the entry (functionInputVariableID and the optional keys), says where the input IDs come from, and gives a worked example. After a function tool is created or updated, vf reads the function's inputs (and, for an update, the tool back) and names any the tool doesn't pass, with the update that wires them: a warning for a person, a JSON warning with the hint in agent mode. A dry run checks nothing. Found by the round-4 sweep's agent-builder. --- internal/cli/tool/create.go | 2 + internal/cli/tool/update.go | 2 + internal/cli/tool/wiring.go | 222 +++++++++++++++++++++++++++++++ internal/cli/tool/wiring_test.go | 30 +++++ internal/cli/toolinputs_test.go | 184 +++++++++++++++++++++++++ internal/flagutil/warning.go | 3 + 6 files changed, 443 insertions(+) create mode 100644 internal/cli/tool/wiring.go create mode 100644 internal/cli/tool/wiring_test.go create mode 100644 internal/cli/toolinputs_test.go diff --git a/internal/cli/tool/create.go b/internal/cli/tool/create.go index 49a078fd..53f9fb03 100644 --- a/internal/cli/tool/create.go +++ b/internal/cli/tool/create.go @@ -40,6 +40,7 @@ func initCreateCmd(parent *cobra.Command) error { return fmt.Errorf("invalid metadata for create: %w", err) } cmd.Flags().String("body", "", "Request body as JSON (alternative to individual flags). Can also be provided via stdin.") + explainInputs(cmd) // wiring.go: help spells out a function tool's inputVariables parent.AddCommand(cmd) return nil } @@ -81,6 +82,7 @@ func runCreateCmd(cmd *cobra.Command, args []string) error { if err != nil { return output.Error(cmd, err) } + defer checkCreatedInputs(cmd, s, req, res)() // wiring.go: names the function's inputs the tool doesn't pass if err := output.Result(cmd, res); err != nil { return err diff --git a/internal/cli/tool/update.go b/internal/cli/tool/update.go index 31a1da75..a4416b76 100644 --- a/internal/cli/tool/update.go +++ b/internal/cli/tool/update.go @@ -41,6 +41,7 @@ func initUpdateCmd(parent *cobra.Command) error { return fmt.Errorf("invalid metadata for update: %w", err) } cmd.Flags().String("body", "", "Request body as JSON (alternative to individual flags). Can also be provided via stdin.") + explainInputs(cmd) // wiring.go: help spells out a function tool's inputVariables parent.AddCommand(cmd) return nil } @@ -86,5 +87,6 @@ func runUpdateCmd(cmd *cobra.Command, args []string) error { if err := output.Result(cmd, res); err != nil { return err } + checkUpdatedInputs(cmd, s, req) // wiring.go: names the function's inputs the tool doesn't pass return nil } diff --git a/internal/cli/tool/wiring.go b/internal/cli/tool/wiring.go new file mode 100644 index 00000000..3c5561ed --- /dev/null +++ b/internal/cli/tool/wiring.go @@ -0,0 +1,222 @@ +// This file is not generated by Speakeasy. It says when a function tool +// doesn't pass its function's inputs, and shows how to wire them. +// +// A function tool hands the agent's values to its function only through +// inputVariables: an entry per input, keyed by the input's name, that holds +// the input's ID. Left out, the map was sent empty, and help showed it as +// `inputVariables?: { : {…} }`. So a tester's lookup_order tool saved +// with no inputs, and nothing said so: the agent could call it, but never +// with the order_number the function needs. Wiring it took three docs +// searches and a guess that the key is the input's name. +// +// Help now spells out the entry and gives a worked example. After a +// function tool is created or updated, vf reads the function's inputs (one +// GET; an update also reads the tool back, since it answers with a message +// only) and names any the tool doesn't pass, with the update that wires +// them: a warning for a person, a JSON warning with that hint for an agent. +// A dry run sends nothing, so nothing is checked. A check that fails says +// nothing: the write itself went through. + +package tool + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "regexp" + "strings" + + "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" +) + +// collapsedInputs is how the function form's help wrote inputVariables, cut +// short to fit, and inputEntry is the entry it stands for. +const ( + collapsedInputs = "inputVariables?: { : {…} }" + inputEntry = "inputVariables?: { : { functionInputVariableID: string, description?: string, defaultValue?: string, required?: boolean, captureType?: string } }" +) + +// inputsHelp is what create's and update's help say of a function tool's +// inputs. +const inputsHelp = "A function tool passes the agent's values to its function only through inputVariables: " + + "one entry per input, keyed by the input's name, with the input's ID as functionInputVariableID " + + "('vf function variable list --function-id ' lists both). An input left out is never passed, and vf warns when one is." + +// explainInputs gives create's or update's help the entry a function tool +// needs for each input, and an example of it. +func explainInputs(cmd *cobra.Command) { + cmd.Long += "\n\n" + inputsHelp + switch cmd.Name() { + case "create": + cmd.Example += "\n vf tool create --project-id --environment-alias --body-param.function " + + `'{"functionID":"","target":{"global":true},"description":"Looks up an order by its number",` + + `"inputVariables":{"order_number":{"functionInputVariableID":"","description":"The order number the customer gives"}}}'` + case "update": + cmd.Long += " An update merges inputVariables by input name: an entry sent replaces that input's, one left out stays, and null removes it." + cmd.Example += "\n vf tool update --tool-id --project-id --environment-alias --body-param.function " + + `'{"inputVariables":{"order_number":{"functionInputVariableID":""}}}'` + } + if f := cmd.Flags().Lookup("body-param.function"); f != nil { + f.Usage = strings.Replace(f.Usage, collapsedInputs, inputEntry, 1) + } +} + +// wiring is what the check reads of a function tool. +type wiring struct { + ID string `json:"id"` + FunctionID string `json:"functionID"` + InputVariables map[string]struct { + FunctionInputVariableID string `json:"functionInputVariableID"` + } `json:"inputVariables"` +} + +// functionInput is one input a function declares. +type functionInput struct{ ID, Name string } + +// checkCreatedInputs reads the function tool a create made, before Result +// prints it, and returns what warns, once it has been, of the function's +// inputs the tool doesn't pass. +func checkCreatedInputs(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableToolControllerCreateV2Request, res *operations.StableToolControllerCreateV2Response) func() { + none := func() {} + if res == nil || req.Body.StableToolCreateRequestV2Function == nil || client.IsDryRun(cmd) { + return none + } + var created struct { + Tool wiring `json:"tool"` + } + if !decodeTool(res, &created) || created.Tool.ID == "" || created.Tool.FunctionID == "" { + return none + } + return func() { warnUnwired(cmd, s, req.ProjectID, req.EnvironmentAlias, created.Tool) } +} + +// decodeTool decodes the tool a create returned: the SDK's, or with -o json +// and --jq the body it left unread, which is put back to be printed. +func decodeTool(res *operations.StableToolControllerCreateV2Response, v any) bool { + if res.StableToolResponseV2 == nil { + return output.PeekJSON(res.HTTPMeta.Response, v) + } + data, err := json.Marshal(res.StableToolResponseV2) + return err == nil && json.Unmarshal(data, v) == nil +} + +// checkUpdatedInputs warns of the function's inputs a function tool doesn't +// pass once an update has changed it. The update answers with a message +// only, so the tool is read back. +func checkUpdatedInputs(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableToolControllerUpdateV2Request) { + if req.Body.StableToolUpdateRequestV2Function == nil || client.IsDryRun(cmd) { + return + } + res, err := s.Tool.Get(client.WithSpinnerMessage(cmd.Context(), "Reading the tool back…"), operations.StableToolControllerGetV2Request{ + ToolID: req.ToolID, ProjectID: req.ProjectID, EnvironmentAlias: req.EnvironmentAlias, + Type: operations.StableToolControllerGetV2TypeFunction, + }, operations.WithSkipDeserialization()) + if err != nil || res == nil { + return + } + var read struct { + Tool wiring `json:"tool"` + } + if !readBody(res.HTTPMeta.Response, &read) || read.Tool.FunctionID == "" { + return + } + read.Tool.ID = req.ToolID + warnUnwired(cmd, s, req.ProjectID, req.EnvironmentAlias, read.Tool) +} + +// warnUnwired warns of the inputs of tool's function that tool doesn't +// pass, if any. +func warnUnwired(cmd *cobra.Command, s *sdk.VoiceflowSDK, projectID, alias string, tool wiring) { + inputs := functionInputs(cmd, s, projectID, alias, tool.FunctionID) + wired := map[string]bool{} + for _, in := range tool.InputVariables { + wired[in.FunctionInputVariableID] = true + } + var missing []functionInput + for _, in := range inputs { + if !wired[in.ID] { + missing = append(missing, in) + } + } + if len(missing) > 0 { + flagutil.EmitWarning(cmd, unwiredWarning(tool.ID, projectID, alias, missing, len(inputs))) + } +} + +// functionInputs are the inputs function functionID declares, or none when +// they can't be read. +func functionInputs(cmd *cobra.Command, s *sdk.VoiceflowSDK, projectID, alias, functionID string) []functionInput { + res, err := s.Function.Variable.List(client.WithSpinnerMessage(cmd.Context(), "Checking the function's inputs…"), operations.StableFunctionVariableControllerListRequest{ + ProjectID: projectID, EnvironmentAlias: alias, FunctionID: functionID, + }, operations.WithSkipDeserialization()) + if err != nil || res == nil { + return nil + } + var list struct { + Variables []struct{ ID, Name, Type string } `json:"variables"` + } + if !readBody(res.HTTPMeta.Response, &list) { + return nil + } + var inputs []functionInput + for _, v := range list.Variables { + if v.Type == "input" && v.ID != "" { + inputs = append(inputs, functionInput{ID: v.ID, Name: v.Name}) + } + } + return inputs +} + +// unwiredWarning names the inputs missing, of the total its function +// declares, and gives the update that wires them. +func unwiredWarning(toolID, projectID, alias string, missing []functionInput, total int) flagutil.Warning { + names := make([]string, len(missing)) + entries := map[string]map[string]string{} + for i, in := range missing { + names[i] = in.Name + entries[in.Name] = map[string]string{"functionInputVariableID": in.ID} + } + them, wire := "them", "Wire them: " + if len(missing) == 1 { + them, wire = "it", "Wire it: " + } + msg := fmt.Sprintf("The tool passes none of its function's inputs, so the agent never fills %s: %s", them, strings.Join(names, ", ")) + if len(missing) < total { + msg = fmt.Sprintf("The tool doesn't pass %d of its function's %d inputs, so the agent never fills %s: %s", len(missing), total, them, strings.Join(names, ", ")) + } + body, _ := json.Marshal(map[string]any{"inputVariables": entries}) + return flagutil.Warning{ + Type: "tool_inputs_not_passed", + Message: msg, + Keys: names, + Hints: []string{wire + "vf tool update --tool-id " + shellWord(toolID) + " --project-id " + shellWord(projectID) + + " --environment-alias " + shellWord(alias) + " --body-param.function " + shellWord(string(body))}, + } +} + +// 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 +} + +var plainWord = regexp.MustCompile(`^[A-Za-z0-9_./:@-]+$`) + +// shellWord is s as one shell word: as it is when it can be, or quoted. +func shellWord(s string) string { + if plainWord.MatchString(s) { + return s + } + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} diff --git a/internal/cli/tool/wiring_test.go b/internal/cli/tool/wiring_test.go new file mode 100644 index 00000000..9b492d19 --- /dev/null +++ b/internal/cli/tool/wiring_test.go @@ -0,0 +1,30 @@ +// This file is not generated by Speakeasy. It covers wiring.go's warning. + +package tool + +import ( + "strings" + "testing" +) + +func TestUnwiredWarningNamesTheInputsLeftAndHowToWireThem(t *testing.T) { + orderNumber := functionInput{ID: "fv1", Name: "order_number"} + email := functionInput{ID: "fv2", Name: "email"} + + w := unwiredWarning("t1", "p1", "main", []functionInput{email}, 2) + if w.Message != "The tool doesn't pass 1 of its function's 2 inputs, so the agent never fills it: email" { + t.Errorf("one of two: %q", w.Message) + } + w = unwiredWarning("t1", "p1", "my env", []functionInput{orderNumber, email}, 2) + if w.Message != "The tool passes none of its function's inputs, so the agent never fills them: order_number, email" { + t.Errorf("none: %q", w.Message) + } + want := `Wire them: vf tool update --tool-id t1 --project-id p1 --environment-alias 'my env' --body-param.function ` + + `'{"inputVariables":{"email":{"functionInputVariableID":"fv2"},"order_number":{"functionInputVariableID":"fv1"}}}'` + if len(w.Hints) != 1 || w.Hints[0] != want { + t.Errorf("hints:\n got %q\nwant %q", w.Hints, want) + } + if strings.Join(w.Keys, ",") != "order_number,email" || w.Type != "tool_inputs_not_passed" { + t.Errorf("keys %v, type %s", w.Keys, w.Type) + } +} diff --git a/internal/cli/toolinputs_test.go b/internal/cli/toolinputs_test.go new file mode 100644 index 00000000..13e5ec94 --- /dev/null +++ b/internal/cli/toolinputs_test.go @@ -0,0 +1,184 @@ +// This file is not generated by Speakeasy. It covers tool/wiring.go: a +// function tool that doesn't pass its function's inputs says so, and help +// spells out the entry that passes one. + +package cli + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +const ( + lookupOrder = "6b0ddd1b297e8fc83d559f59" // the function + orderNumber = "6b0ddd1b297e8fc83d559f5a" // its input + newTool = "6b0ddd2a297e8fc83d559f70" +) + +// toolInputsServer answers as the API does for a function tool whose +// function, lookup_order, takes order_number and returns status. A created +// tool passes what its request wired; a tool read back passes stored. +func toolInputsServer(t *testing.T, stored string) (url string, requests func() []string) { + t.Helper() + var mu sync.Mutex + var seen []string + tool := func(inputs string) string { + return `{"tool":{"id":"` + newTool + `","createdAt":"2026-11-01T00:00:00Z","updatedAt":"2026-11-01T00:00:00Z",` + + `"messages":null,"toolSound":null,"description":"Look up an order","captureInputVariables":{},"type":"function",` + + `"functionID":"` + lookupOrder + `","asyncExecution":false,"inputVariables":` + inputs + `,"captureResponse":{}}}` + } + 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) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPost && r.URL.Path == "/v2/stable/tool": + var sent struct { + InputVariables json.RawMessage `json:"inputVariables"` + } + _ = json.Unmarshal(body, &sent) + if len(sent.InputVariables) == 0 { + sent.InputVariables = json.RawMessage(`{}`) + } + w.WriteHeader(http.StatusCreated) + io.WriteString(w, tool(string(sent.InputVariables))) + case r.Method == http.MethodPatch: + io.WriteString(w, `{"message":"Tool `+newTool+` updated."}`) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/v2/stable/tool/"): + if r.URL.Query().Get("type") != "function" { + t.Errorf("read back as %q", r.URL.Query().Get("type")) + } + io.WriteString(w, tool(stored)) + case r.Method == http.MethodGet && r.URL.Path == "/v1/stable/function-variable": + if r.URL.Query().Get("functionID") != lookupOrder { + t.Errorf("function variables of %q", r.URL.Query().Get("functionID")) + } + io.WriteString(w, `{"variables":[`+ + `{"id":"`+orderNumber+`","name":"order_number","type":"input","createdAt":"2026-11-01T00:00:00Z","updatedAt":"2026-11-01T00:00:00Z","functionID":"`+lookupOrder+`","description":"The order number"},`+ + `{"id":"6b0ddd1b297e8fc83d559f5b","name":"status","type":"output","createdAt":"2026-11-01T00:00:00Z","updatedAt":"2026-11-01T00:00:00Z","functionID":"`+lookupOrder+`","description":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...) + } +} + +const ( + unwiredFunction = `{"functionID":"` + lookupOrder + `","target":{"global":true},"description":"Look up an order"}` + wiredFunction = `{"functionID":"` + lookupOrder + `","target":{"global":true},"inputVariables":{"order_number":{"functionInputVariableID":"` + orderNumber + `"}}}` + wireHint = `vf tool update --tool-id ` + newTool + ` --project-id p1 --environment-alias main --body-param.function '{"inputVariables":{"order_number":{"functionInputVariableID":"` + orderNumber + `"}}}'` +) + +func TestAFunctionToolThatPassesNoInputsSaysSo(t *testing.T) { + scope := []string{"-p", "p1", "-e", "main"} + create := append([]string{"create"}, scope...) + update := append([]string{"update", "--tool-id", newTool}, scope...) + cases := []struct { + name string + stored string // the tool's inputs, read back after an update + agent bool + args []string + requests string + warns bool + }{ + {"create, none wired", "", false, append(create, "--body-param.function", unwiredFunction), + "POST /v2/stable/tool, GET /v1/stable/function-variable", true}, + {"create, all wired", "", false, append(create, "--body-param.function", wiredFunction), + "POST /v2/stable/tool, GET /v1/stable/function-variable", false}, + {"create, none wired, -o json", "", false, append(create, "--body-param.function", unwiredFunction, "-o", "json"), + "POST /v2/stable/tool, GET /v1/stable/function-variable", true}, + {"create, none wired, agent mode", "", true, append(create, "--body-param.function", unwiredFunction), + "POST /v2/stable/tool, GET /v1/stable/function-variable", true}, + {"create, dry run", "", false, append(create, "--body-param.function", unwiredFunction, "--dry-run"), "", false}, + {"create an api tool", "", false, append(create, "--body-param.api", `{"apiToolID":"a1","target":{"global":true}}`), + "POST /v2/stable/tool", false}, + {"update, still none wired", `{}`, false, append(update, "--body-param.function", `{"description":"Look up an order by number"}`), + "PATCH /v2/stable/tool/" + newTool + ", GET /v2/stable/tool/" + newTool + ", GET /v1/stable/function-variable", true}, + {"update, wired", `{"order_number":{"functionInputVariableID":"` + orderNumber + `","description":null,"defaultValue":null,"required":true}}`, false, + append(update, "--body-param.function", `{"inputVariables":{"order_number":{"functionInputVariableID":"`+orderNumber+`"}}}`), + "PATCH /v2/stable/tool/" + newTool + ", GET /v2/stable/tool/" + newTool + ", GET /v1/stable/function-variable", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + url, requests := toolInputsServer(t, c.stored) + stdout, stderr, err := runTool(t, url, c.agent, c.args...) + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if got := strings.Join(requests(), ", "); got != c.requests { + t.Errorf("requests:\n got %s\nwant %s", got, c.requests) + } + warned := strings.Contains(stderr, "order_number") + if warned != c.warns { + t.Fatalf("warned %v, want %v:\n%s", warned, c.warns, stderr) + } + if !c.warns { + return + } + if c.agent { + var event struct { + Warning string `json:"warning"` + Type string `json:"warning_type"` + Keys []string `json:"keys"` + 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 != "tool_inputs_not_passed" || len(event.Keys) != 1 || event.Keys[0] != "order_number" || + len(event.Hints) != 1 || event.Hints[0] != "Wire it: "+wireHint { + t.Errorf("warning: %+v", event) + } + return + } + for _, want := range []string{"The tool passes none of its function's inputs, so the agent never fills it: order_number", "Wire it: " + wireHint} { + if !strings.Contains(stderr, want) { + t.Errorf("stderr lacks %q:\n%s", want, stderr) + } + } + if strings.Contains(c.name, "-o json") && !strings.Contains(stdout, `"functionID":"`+lookupOrder+`"`) { + t.Errorf("the tool wasn't printed as it came:\n%s", stdout) + } + }) + } +} + +// Help spells out a function tool's input entry, and the worked example +// sends one. +func TestToolHelpSpellsOutAFunctionToolsInputs(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + root := testRoot(t) + for _, verb := range []string{"create", "update"} { + c := find(t, root, "tool", verb) + if !strings.Contains(c.Long, "keyed by the input's name, with the input's ID as functionInputVariableID") { + t.Errorf("%s Long: %s", verb, c.Long) + } + f := c.Flags().Lookup("body-param.function") + if f == nil || !strings.Contains(f.Usage, "inputVariables?: { : { functionInputVariableID: string, description?: string") || strings.Contains(f.Usage, "inputVariables?: { : {…} }") { + t.Errorf("%s --body-param.function: %v", verb, f) + } + lines := strings.Split(c.Example, "\n") + line := strings.TrimSpace(lines[len(lines)-1]) + if !strings.Contains(line, "functionInputVariableID") { + t.Fatalf("%s: no worked example: %s", verb, c.Example) + } + sent := dryRunErr(t, append(shellWords(t, line)[1:], "--agent-mode=false")) + if !strings.Contains(sent, `"functionInputVariableID": "`) || !strings.Contains(sent, `"order_number"`) { + t.Errorf("%s: the example doesn't send the entry:\n%s", verb, sent) + } + } +} diff --git a/internal/flagutil/warning.go b/internal/flagutil/warning.go index d9b56d5f..fffe4222 100644 --- a/internal/flagutil/warning.go +++ b/internal/flagutil/warning.go @@ -35,6 +35,9 @@ func SetWarningLine(draw func(cmd *cobra.Command, w io.Writer, msg string) strin warningLine = draw } +// EmitWarning writes w on cmd's stderr, for a command's own warnings. +func EmitWarning(cmd *cobra.Command, w Warning) { emitWarning(cmd, w) } + // emitWarning writes w on cmd's stderr. func emitWarning(cmd *cobra.Command, w Warning) { out := cmd.ErrOrStderr() From ab926d811f8c287c1e67179fb2d8b894e1fae556 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:27:05 -0500 Subject: [PATCH 12/28] fix(variable): a new variable gets the editor's color by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The API requires a variable's color, a hex code only the editor shows, so `vf variable create --name … --description …` failed with "needs --color-param", and the hint offered `--color-param `. Help's example passed `black`, while the flag's own text said to use #515A63 and invent no other hex code. --color-param is now optional: left out, by flag or in --body, the variable gets #515A63, the editor's default. Help says so, and its examples run as written, the second with a quoted hex (an unquoted # starts a shell comment). The missing-flag tests that used --color-param as their second missing flag now use function create's --code. Found by the round-4 sweep's agent-builder, agent-migrator, agent-ci and fix-verifier. --- internal/cli/missingflags_test.go | 14 +++---- internal/cli/stdinhint_test.go | 10 ++--- internal/cli/variable/color.go | 48 ++++++++++++++++++++++++ internal/cli/variable/create.go | 2 + internal/cli/variablecolor_test.go | 59 ++++++++++++++++++++++++++++++ test/errors-teach.test.ts | 12 +++--- 6 files changed, 127 insertions(+), 18 deletions(-) create mode 100644 internal/cli/variable/color.go create mode 100644 internal/cli/variablecolor_test.go diff --git a/internal/cli/missingflags_test.go b/internal/cli/missingflags_test.go index 4f0617bd..269ad1b0 100644 --- a/internal/cli/missingflags_test.go +++ b/internal/cli/missingflags_test.go @@ -14,19 +14,19 @@ import ( "github.com/voiceflow/cli/internal/output" ) -// `vf variable create -p p1 -n "two words"` is missing two flags, and one run +// `vf function create -p p1 -n "two words"` is missing two flags, and one run // names both, and the command line keeps the flags already given. func TestEveryMissingFlagIsNamedInOneRun(t *testing.T) { - x := runWithStdin(t, "", "variable", "create", "-p", "p1", "-n", "two words") + x := runWithStdin(t, "", "function", "create", "-p", "p1", "-n", "two words") if x.Type != "missing_flag" { t.Fatalf("type = %q:\n%s", x.Type, explained(x)) } all := explained(x) for _, want := range []string{ - "vf variable create needs --environment-alias and --color-param", + "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", - "Pass them: `vf variable create --name \"two words\" --project-id p1 --environment-alias --color-param `", + "Pass them: `vf function create --name \"two words\" --project-id p1 --environment-alias --code `", } { if !strings.Contains(all, want) { t.Errorf("missing %q in:\n%s", want, all) @@ -42,13 +42,13 @@ func TestMissingFlagsAreDetailsInJSON(t *testing.T) { root := testRoot(t) t.Setenv("FORCE_AGENT_MODE", "1") output.InitAgentMode(root) - create := find(t, root, "variable", "create") - x := explainMissingFlags(create, []string{"environment-alias", "color-param"}) + create := find(t, root, "function", "create") + x := explainMissingFlags(create, []string{"environment-alias", "code"}) var flags []string for _, d := range x.Details { flags = append(flags, d.Flag) } - if strings.Join(flags, " ") != "--environment-alias --color-param" { + if strings.Join(flags, " ") != "--environment-alias --code" { t.Errorf("details = %+v", x.Details) } } diff --git a/internal/cli/stdinhint_test.go b/internal/cli/stdinhint_test.go index da1fb278..48708f32 100644 --- a/internal/cli/stdinhint_test.go +++ b/internal/cli/stdinhint_test.go @@ -46,13 +46,13 @@ func runWithStdin(t *testing.T, content string, args ...string) output.Explanati return explainCLIError(cmd, err) } -// `echo '{"name":…,"color":…}' | vf variable create -n x` needs --color-param; -// the error says the piped body wasn't read, and how to read it. +// `echo '{"name":…,"code":…}' | vf function create -n x` needs --code; the +// error says the piped body wasn't read, and how to read it. func TestAMissingFlagSaysThePipedBodyWasntRead(t *testing.T) { - x := runWithStdin(t, `{"name":"from_stdin","color":"#515A63"}`, - "variable", "create", "-p", "p1", "-e", "main", "-n", "from_flag") + x := runWithStdin(t, `{"name":"from_stdin","code":"export default async function main() {}"}`, + "function", "create", "-p", "p1", "-e", "main", "-n", "from_flag") all := explained(x) - for _, want := range []string{"needs --color-param", "Body flags were given, so vf didn't read stdin.", "add --body - to read it"} { + for _, want := range []string{"needs --code", "Body flags were given, so vf didn't read stdin.", "add --body - to read it"} { if !strings.Contains(all, want) { t.Errorf("missing %q in:\n%s", want, all) } diff --git a/internal/cli/variable/color.go b/internal/cli/variable/color.go new file mode 100644 index 00000000..45069e11 --- /dev/null +++ b/internal/cli/variable/color.go @@ -0,0 +1,48 @@ +// This file is not generated by Speakeasy. It gives a new variable the +// editor's default color, so `vf variable create` doesn't need one. +// +// The API requires a variable's color, a hex code only the editor shows. +// So `vf variable create --name … --description …` failed with "needs +// --color-param", and its hint offered `--color-param `. Help's +// example passed `black`, while the flag's own text said to use #515A63, +// the editor's default, and invent no other hex code. Four testers spent a +// run on it. Now a variable made without a color gets #515A63, as one made +// in the editor does; --color-param still sets another, and help's example +// passes one of the editor's colors, quoted, since an unquoted # starts a +// shell comment. + +package variable + +import ( + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/sdk/models/operations" +) + +// editorColor is the color the editor gives a new variable. +const editorColor = "#515A63" + +// optionalColor makes create's --color-param optional, says what it +// defaults to, and gives help an example that runs as written. It runs +// before meta's flags are registered. +func optionalColor(cmd *cobra.Command, meta []flagutil.FlagMeta) { + for i := range meta { + if meta[i].FlagName == "color-param" { + meta[i].Required, meta[i].Optional = false, true + meta[i].Description = "The variable's color in the Voiceflow editor, as a hex code. Left out, it is " + editorColor + + ", the editor's default; to match a color asked for, use the closest of #5B9FD7, #CB627B, #56B365, #DC8879, #9A63BC." + } + } + cmd.Example = strings.Replace(cmd.Example, " --color-param black", "", 1) + + "\n vf variable create --project-id --environment-alias --name --color-param '#5B9FD7'" +} + +// defaultColor gives req the editor's default color when it names none. +func defaultColor(req *operations.StableVariableControllerCreateV2Request) { + if strings.TrimSpace(req.Body.Color) == "" { + req.Body.Color = editorColor + } +} diff --git a/internal/cli/variable/create.go b/internal/cli/variable/create.go index 0124bf93..81749641 100644 --- a/internal/cli/variable/create.go +++ b/internal/cli/variable/create.go @@ -33,6 +33,7 @@ func initCreateCmd(parent *cobra.Command) error { Example: " vf variable create --project-id --environment-alias --name --color-param black", RunE: runCreateCmd, } + optionalColor(cmd, createCmdMeta) // color.go: a new variable gets the editor's default color flagutil.RegisterFlags(cmd, createCmdMeta) if err := flagutil.ValidateMeta[operations.StableVariableControllerCreateV2Request](createCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create: %w", err) @@ -56,6 +57,7 @@ func runCreateCmd(cmd *cobra.Command, args []string) error { if err != nil { return err } + defaultColor(req) // color.go: #515A63 when no color is given s, err := client.NewClient(cmd) if err != nil { return err diff --git a/internal/cli/variablecolor_test.go b/internal/cli/variablecolor_test.go new file mode 100644 index 00000000..bb6c8d4c --- /dev/null +++ b/internal/cli/variablecolor_test.go @@ -0,0 +1,59 @@ +// This file is not generated by Speakeasy. It covers variable/color.go: a +// new variable gets the editor's default color unless it is given one. + +package cli + +import ( + "strings" + "testing" +) + +func TestANewVariableGetsTheEditorsColor(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + scope := []string{"variable", "create", "-p", "p1", "-e", "main", "--agent-mode=false"} + for _, c := range []struct { + name string + args []string + want string + }{ + {"no color", []string{"--name", "customer_name"}, `"color": "#515A63"`}, + {"--color-param", []string{"--name", "customer_name", "--color-param", "#5B9FD7"}, `"color": "#5B9FD7"`}, + {"a body's color", []string{"--body", `{"name":"customer_name","color":"#CB627B"}`}, `"color": "#CB627B"`}, + {"a body with none", []string{"--body", `{"name":"customer_name"}`}, `"color": "#515A63"`}, + } { + t.Run(c.name, func(t *testing.T) { + sent := dryRunErr(t, append(append([]string{}, scope...), c.args...)) + if !strings.Contains(sent, "Would send: POST") || !strings.Contains(sent, c.want) { + t.Errorf("want %s sent:\n%s", c.want, sent) + } + }) + } + + // A variable missing its name isn't told it needs a color too. + sent := dryRunErr(t, scope) + if !strings.Contains(sent, "--name") || strings.Contains(sent, "color") { + t.Errorf("missing a name:\n%s", sent) + } +} + +// Help says what the color defaults to, and its examples run as written: +// no `black`, and a hex is quoted, since an unquoted # starts a comment. +func TestVariableCreateHelpGivesAHex(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + create := find(t, testRoot(t), "variable", "create") + if f := create.Flags().Lookup("color-param"); f == nil || !strings.Contains(f.Usage, "Left out, it is #515A63") || strings.Contains(f.Usage, "[required]") { + t.Errorf("--color-param: %v", f) + } + if strings.Contains(create.Example, "black") || !strings.Contains(create.Example, "--color-param '#5B9FD7'") { + t.Errorf("example: %s", create.Example) + } + for _, line := range strings.Split(create.Example, "\n") { + line = strings.NewReplacer("", "p1", "", "main").Replace(strings.TrimSpace(line)) + sent := dryRunErr(t, append(shellWords(t, line)[1:], "--agent-mode=false")) + if !strings.Contains(sent, "Would send: POST") || !strings.Contains(sent, `"color": "#`) { + t.Errorf("%s:\n%s", line, sent) + } + } +} diff --git a/test/errors-teach.test.ts b/test/errors-teach.test.ts index 8502d5a2..fb53e3ea 100644 --- a/test/errors-teach.test.ts +++ b/test/errors-teach.test.ts @@ -119,22 +119,22 @@ describe('required-flag preflight', () => { }); it('names every missing flag in one run, with one command line that gives them', async () => { - // It used to take a run per flag: --environment-alias, then --color-param. - const args = ['variable', 'create', '-p', 'p1', '-n', 'hi', '--token', 'vfp_x', '--server-url', 'http://127.0.0.1:1']; + // It used to take a run per flag: --environment-alias, then --code. + const args = ['function', 'create', '-p', 'p1', '-n', 'hi', '--token', 'vfp_x', '--server-url', 'http://127.0.0.1:1']; const result = await $vf(args); expect(result.exitCode).toBe(2); const envelope = parseEnvelope(result.stderr); - expect(envelope.error).toBe('vf variable create needs --environment-alias and --color-param'); + expect(envelope.error).toBe('vf function create needs --environment-alias and --code'); expect(envelope.details).toEqual([ { flag: '--environment-alias', message: 'required' }, - { flag: '--color-param', message: 'required' }, + { flag: '--code', message: 'required' }, ]); const lines = (envelope.hints as string[]).filter((h) => h.startsWith('Pass')); - expect(lines).toEqual(["Pass them: 'vf variable create --name hi --project-id p1 --environment-alias --color-param '"]); + expect(lines).toEqual(["Pass them: 'vf function create --name hi --project-id p1 --environment-alias --code '"]); const human = await $vf([...args, '--agent-mode=false', '--no-interactive']); expect(human.exitCode).toBe(2); - expect(human.stderr).toContain('Error: vf variable create needs --environment-alias and --color-param'); + expect(human.stderr).toContain('Error: vf function create needs --environment-alias and --code'); }); it('is not bypassed by piped stdin on params-only commands', async () => { From 31508dd23e40eb79ced8a2343f03b2b99554d662 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:36:17 -0500 Subject: [PATCH 13/28] =?UTF-8?q?fix(output):=20updates,=20deletes=20and?= =?UTF-8?q?=20a=20passing=20wait=20end=20with=20a=20=E2=9C=93=20line?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A create said "✓ Created event …", but an update, a delete and secret set-value printed the API's bare answer, "message: Event … updated.", and a passing `test run wait` printed nothing after its results while a failing one ended "✗ 1 of 1 runs did not pass". Testers (human-poweruser, human-newcomer, agent-builder, human-kb) read the missing ✓ as "maybe nothing happened". Now, for a person reading pretty output at a terminal, an answer that is only a message reads as "✓ Event … updated."; set-value's line adds which environment and version now serve the value; and `test run wait`, `wait-suite` and `create-suite --wait` end with "✓ 2 of 2 runs passed" on stderr. JSON, YAML, TOON, --jq, agent mode and a pipe get the answer as the API sent it. The output change is one hook line in output.go; the rest is in output/done.go. --- internal/cli/donetty_test.go | 110 ++++++++++++++++++++++ internal/cli/test/run/createsuite_wait.go | 1 + internal/cli/test/run/wait_exit.go | 17 +++- internal/cli/test/run/wait_passed_test.go | 22 +++++ internal/output/done.go | 92 ++++++++++++++++++ internal/output/done_test.go | 52 ++++++++++ internal/output/output.go | 3 + 7 files changed, 296 insertions(+), 1 deletion(-) create mode 100644 internal/cli/donetty_test.go create mode 100644 internal/cli/test/run/wait_passed_test.go create mode 100644 internal/output/done.go create mode 100644 internal/output/done_test.go diff --git a/internal/cli/donetty_test.go b/internal/cli/donetty_test.go new file mode 100644 index 00000000..48ee12ec --- /dev/null +++ b/internal/cli/donetty_test.go @@ -0,0 +1,110 @@ +// This file is not generated by Speakeasy. It covers output/done.go where +// it matters, at a terminal: an update's, a delete's and secret set-value's +// answer reads as a ✓ line, and a wait whose runs all passed ends with one. +// The test runs itself again under script(1), which gives it a terminal, and +// is skipped where script isn't installed. Off a terminal the answers print +// as sent (output/done_test.go). + +package cli + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "runtime" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +const doneAtATerminal = "VF_TEST_DONE_AT_A_TERMINAL" + +func TestAtATerminalUpdatesAndDeletesEndWithADoneLine(t *testing.T) { + if os.Getenv(doneAtATerminal) != "" { + runDoneCommands(t) + return + } + script, err := exec.LookPath("script") + if err != nil { + t.Skip("script(1) isn't installed, so there is no terminal to run under") + } + self := []string{os.Args[0], "-test.run=^TestAtATerminalUpdatesAndDeletesEndWithADoneLine$", "-test.count=1"} + var cmd *exec.Cmd + switch runtime.GOOS { + case "darwin", "freebsd": + cmd = exec.Command(script, append([]string{"-q", "/dev/null"}, self...)...) + case "linux": + cmd = exec.Command(script, "-q", "-e", "-c", strings.Join(self, " "), "/dev/null") + default: + t.Skipf("script(1) on %s isn't known", runtime.GOOS) + } + cmd.Env = append(os.Environ(), doneAtATerminal+"=1", "TERM=xterm", "NO_COLOR=1") + out, err := cmd.CombinedOutput() + got := strings.ReplaceAll(string(out), "\r", "") + if err != nil { + t.Fatalf("%v:\n%s", err, got) + } + for _, want := range []string{ + "vf event update\n✓ Event e1 updated.\n", + "vf project delete\n✓ Project p9 deleted.\n", + "vf secret set-value\n✓ Secret s1 value updated. Now served by main's published version.\n", + "vf test run wait\n", + "✓ 2 of 2 runs passed\n", + "vf event update -o json\n{", + } { + if !strings.Contains(got, want) { + t.Errorf("missing %q in:\n%s", want, got) + } + } + if strings.Contains(got, "message: ") { + t.Errorf("a bare message line is left:\n%s", got) + } +} + +// runDoneCommands runs an update, a delete, a set-value and a passing wait with stdout +// and stderr the terminal script gave the test, each after a line naming it. +func runDoneCommands(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPatch: + io.WriteString(w, `{"message":"Event e1 updated."}`) + case r.Method == http.MethodPut: + io.WriteString(w, `{"message":"Secret s1 value updated.","environmentAlias":"main","versionVariant":"published"}`) + case r.Method == http.MethodDelete: + io.WriteString(w, `{"message":"Project p9 deleted."}`) + default: + io.WriteString(w, waitBody("passed", "passed")) + } + })) + defer srv.Close() + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", srv.URL) + t.Setenv("HOME", t.TempDir()) + for _, c := range []struct { + name string + args []string + }{ + {"vf event update", []string{"event", "update", "-p", "p1", "-e", "main", "--event-id", "e1", "--name", "Order placed"}}, + {"vf project delete", []string{"project", "delete", "-p", "p9", "--yes"}}, + {"vf secret set-value", []string{"secret", "set-value", "-s", "s1", "-p", "p1", "--value", "sk_test"}}, + {"vf test run wait", []string{"test", "run", "wait", "-p", "p1", "-e", "main", "-r", "runa", "-r", "runb"}}, + {"vf event update -o json", []string{"event", "update", "-p", "p1", "-e", "main", "--event-id", "e1", "--name", "Order placed", "-o", "json"}}, + } { + output.ResetAgentMode() + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + fmt.Println(c.name) + root.SetArgs(append(c.args, "--agent-mode=false", "--no-interactive")) + if err := renderError(root.ExecuteC()); err != nil { + t.Errorf("%s: %v", c.name, err) + } + } +} diff --git a/internal/cli/test/run/createsuite_wait.go b/internal/cli/test/run/createsuite_wait.go index 3f561672..e49d8843 100644 --- a/internal/cli/test/run/createsuite_wait.go +++ b/internal/cli/test/run/createsuite_wait.go @@ -484,6 +484,7 @@ func suiteOutcome( notPassed, counts.Total, target.bulkID, counts.Failed, counts.Canceled), []string{fmt.Sprintf("Read a run's logs: vf test run get %s --run-id ", target.flags())}) } + output.Done(cmd, passed(int(counts.Total), target.bulkID)) // done.go: a ✓ line, as a failure ends with ✗ return nil } diff --git a/internal/cli/test/run/wait_exit.go b/internal/cli/test/run/wait_exit.go index 33e37192..9f702413 100644 --- a/internal/cli/test/run/wait_exit.go +++ b/internal/cli/test/run/wait_exit.go @@ -8,7 +8,9 @@ // still going when the wait stopped, or a run ID that wasn't found makes the // command exit non-zero (6, 5 and 4: internal/output/exitcode.go), and the // error says which. -o json and --jq skip decoding the response, so the -// verdict reads the raw body and puts it back to be printed as before. +// verdict reads the raw body and puts it back to be printed as before. When +// every run passed, a person at a terminal gets a ✓ line saying so, as a +// failure ends with its ✗ line. package run @@ -106,9 +108,22 @@ func runsOutcome(cmd *cobra.Command, w *components.StableTestRunWaitResponse) er fmt.Sprintf("%d of the runs asked for weren't found: %s", len(w.NotFoundRunIDs), strings.Join(w.NotFoundRunIDs, ", ")), []string{"Pass each run's id from 'vf test run create', not its testID"}) } + output.Done(cmd, passed(len(w.Runs), "")) // done.go: a ✓ line, as a failure ends with ✗ return nil } +// passed is the line that says all n runs passed, in suite when it is one; +// "" for no runs. +func passed(n int, suite string) string { + switch { + case n == 0: + return "" + case suite != "": + return fmt.Sprintf("%d of %d runs in suite %s passed", n, n, suite) + } + return fmt.Sprintf("%d of %d runs passed", n, n) +} + func quoteAll(values []string) []string { out := make([]string, len(values)) for i, v := range values { diff --git a/internal/cli/test/run/wait_passed_test.go b/internal/cli/test/run/wait_passed_test.go new file mode 100644 index 00000000..65d1e8d4 --- /dev/null +++ b/internal/cli/test/run/wait_passed_test.go @@ -0,0 +1,22 @@ +// This file is not generated by Speakeasy. It covers the line a passing +// wait ends with (wait_exit.go). + +package run + +import "testing" + +func TestAPassingWaitSaysHowManyRunsPassed(t *testing.T) { + for _, c := range []struct { + n int + suite string + want string + }{ + {2, "", "2 of 2 runs passed"}, + {3, "bulk1", "3 of 3 runs in suite bulk1 passed"}, + {0, "", ""}, + } { + if got := passed(c.n, c.suite); got != c.want { + t.Errorf("passed(%d, %q) = %q, want %q", c.n, c.suite, got, c.want) + } + } +} diff --git a/internal/output/done.go b/internal/output/done.go new file mode 100644 index 00000000..bcfab5ce --- /dev/null +++ b/internal/output/done.go @@ -0,0 +1,92 @@ +// This file is not generated by Speakeasy. It ends an update, a delete or a +// passing wait with a ✓ line, as a create starts with one (created.go). +// +// A create said "✓ Created event …", but an update, a delete and secret +// set-value printed the API's bare answer, +// +// message: Event 6b0ddf8b297e8fc83d55a316 updated. +// +// and a passing `test run wait` printed nothing after its results, while a +// failing one ended "✗ 1 of 1 runs did not pass". Testers read the missing +// ✓ as "maybe nothing happened". Now a person reading pretty output at a +// terminal gets that answer as a ✓ line, +// +// ✓ Event 6b0ddf8b297e8fc83d55a316 updated. +// +// set-value's line also says which environment and version now serve the +// value, and a wait whose runs all passed ends with a ✓ line too. JSON, +// YAML, TOON, --jq, agent mode and a pipe get the answer as the API sent it. + +package output + +import ( + "fmt" + "io" + "os" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/ui" +) + +// writeDone writes content as a ✓ line when it is only a message, as an +// update's or a delete's answer is, and a person is reading pretty output +// at a terminal. It reports whether it did; if not, the result prints as +// before. +func writeDone(cmd *cobra.Command, out io.Writer, content interface{}) bool { + u := UI(cmd, cmd.OutOrStdout()) + if !u.Decorated() { + return false + } + line, ok := doneLine(u, content) + if ok { + io.WriteString(out, line) //nolint:errcheck // a terminal write + } + return ok +} + +// doneLine is content's message as a ✓ line, when content holds a message +// and nothing else but, as secret set-value's answer does, the environment +// and version that now serve the value. +func doneLine(u *ui.UI, content interface{}) (string, bool) { + v, err := jsonValue(content) + m, ok := v.(map[string]interface{}) + if err != nil || !ok { + return "", false + } + text := map[string]string{} + for k, val := range m { + s, isText := val.(string) + if !isText || (k != "message" && k != "environmentAlias" && k != "versionVariant") { + return "", false + } + text[k] = strings.TrimSpace(s) + } + msg := text["message"] + if msg == "" { + return "", false + } + return u.Status(ui.StatusDone, msg+servedBy(text["environmentAlias"], text["versionVariant"])) + "\n", true +} + +// servedBy says which environment and version now serve a value, or "". +func servedBy(env, version string) string { + switch { + case env != "" && version != "": + return fmt.Sprintf(" Now served by %s's %s version.", env, version) + case env != "": + return " Now served by environment " + env + "." + case version != "": + return " Now served by the " + version + " version." + } + return "" +} + +// Done says msg, unless it is "", as a ✓ line on stderr when a person is +// reading pretty output at a terminal, as a create's line is said. +func Done(cmd *cobra.Command, msg string) { + if msg != "" && announces(cmd) { + fmt.Fprintln(os.Stderr, UI(cmd, os.Stderr).Status(ui.StatusDone, msg)) + } +} diff --git a/internal/output/done_test.go b/internal/output/done_test.go new file mode 100644 index 00000000..1823f08d --- /dev/null +++ b/internal/output/done_test.go @@ -0,0 +1,52 @@ +// This file is not generated by Speakeasy. It covers done.go. + +package output + +import ( + "io" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/ui" +) + +// An answer that is only a message reads as a ✓ line; one that says more +// prints as it came. +func TestAnUpdatesMessageReadsAsADoneLine(t *testing.T) { + u := ui.New(io.Discard, ui.Options{Decorate: true}) + for _, c := range []struct { + name string + content interface{} + want string + }{ + {"update", &components.StableTextUpdateResponse{Message: "Event 6b0ddf8b297e8fc83d55a316 updated."}, "✓ Event 6b0ddf8b297e8fc83d55a316 updated.\n"}, + {"delete", &components.StableDeleteResponse{Message: "Project 6b0ddcbe0369ea7ad5c68774 deleted."}, "✓ Project 6b0ddcbe0369ea7ad5c68774 deleted.\n"}, + {"a map", map[string]interface{}{"message": "Agent updated."}, "✓ Agent updated.\n"}, + {"set-value", &components.StableSecretValueResponse{Message: "Secret s1 value updated.", + EnvironmentAlias: &[]string{"main"}[0], VersionVariant: components.VersionVariantDraft.ToPointer()}, + "✓ Secret s1 value updated. Now served by main's draft version.\n"}, + {"set-value, no environment", &components.StableSecretValueResponse{Message: "Secret s1 value updated."}, "✓ Secret s1 value updated.\n"}, + {"a message among other things", map[string]interface{}{"message": "Agent updated.", "agentID": "a1"}, ""}, + {"unresolved references too", &components.StableTextUpdateResponse{Message: "Tool t1 updated.", + UnresolvedReferences: []components.StableUnresolvedReference{{Path: "description", Token: "nme", Reason: "unknown"}}}, ""}, + {"an empty message", &components.StableTextUpdateResponse{}, ""}, + {"a thing", &components.StableProjectResponse{Project: components.StableProject{ID: "p1", Name: "Help bot"}}, ""}, + } { + got, ok := doneLine(u, c.content) + if got != c.want || ok != (c.want != "") { + t.Errorf("%s: got %q, %v; want %q", c.name, got, ok, c.want) + } + } +} + +// Off a terminal the answer prints as the API sent it. +func TestOffATerminalAnUpdatesMessageIsUnchanged(t *testing.T) { + cmd := &cobra.Command{Use: "update"} + cmd.Flags().String("color", "auto", "") + cmd.SetOut(io.Discard) + if writeDone(cmd, io.Discard, &components.StableTextUpdateResponse{Message: "Event e1 updated."}) { + t.Error("a pipe should get the message as sent") + } +} diff --git a/internal/output/output.go b/internal/output/output.go index c8e7ccb2..046f1375 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -282,6 +282,9 @@ func Result(cmd *cobra.Command, res interface{}) (err error) { if writeDocument(cmd, out, content) { // document.go: a prompt's page, as a document return nil } + 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 { return err } From a3568e13091f0e7b788d95f6c3af216c79dd331e Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:24:57 -0500 Subject: [PATCH 14/28] fix(document): say when a document is ready, and --wait for it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The knowledge base processes a document after the create returns, and nothing said so: create-text, create-url and create-table printed a raw dump ending in `status: type: PENDING`, with no ✓ line, no Next line and no way to wait. Testers ran `document list` until it read SUCCESS, and an agent polled `document get` by hand. At a terminal a create now ends with "✓ Added billing.md (id) · processing (PENDING)" and Next lines naming `vf document get --wait` and `vf document list -o table`. --wait on the creates, on update (new text is processed again) and on get polls the document every 2s until it is SUCCESS or ERROR, with a spinner at a terminal, then prints the answer with the final status, -o json and --jq included. It exits 1 with the API's reason when processing failed, and 5 when --max-wait (5m by default) runs out, saying how to keep waiting. Agent mode keeps the data, status included, and adds nothing to it. Found by the round-4 sweep's human-kb, human-newcomer and agent-builder testers. --- internal/cli/docready_test.go | 218 ++++++++++ internal/cli/document/createtable.go | 4 +- internal/cli/document/createtext.go | 4 +- internal/cli/document/createurl.go | 4 +- internal/cli/document/docready.go | 571 +++++++++++++++++++++++++ internal/cli/document/docready_test.go | 94 ++++ internal/cli/document/get.go | 4 +- internal/cli/document/update.go | 4 +- internal/client/spinner.go | 12 + test/run-suite-wait.test.ts | 3 +- 10 files changed, 912 insertions(+), 6 deletions(-) create mode 100644 internal/cli/docready_test.go create mode 100644 internal/cli/document/docready.go create mode 100644 internal/cli/document/docready_test.go diff --git a/internal/cli/docready_test.go b/internal/cli/docready_test.go new file mode 100644 index 00000000..19a32744 --- /dev/null +++ b/internal/cli/docready_test.go @@ -0,0 +1,218 @@ +// This file is not generated by Speakeasy. It covers document/docready.go: +// `vf document create-text --wait` (and create-url, create-table, update and +// get) polls the document until it is processed, prints the final status, and +// exits 0, 1 or 5 by how processing went. + +package cli + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// documentServer creates documents as PENDING and answers each get with the +// next of statuses, repeating the last. It records each request as its method. +func documentServer(t *testing.T, statuses ...string) (url string, requests func() []string) { + t.Helper() + var mu sync.Mutex + var seen []string + gets := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + mu.Lock() + defer mu.Unlock() + seen = append(seen, r.Method) + w.Header().Set("Content-Type", "application/json") + doc := func(status string) string { + return `{"document":{"id":"d1","data":{"type":"md","name":"billing.md","canEdit":true},"status":` + status + + `,"smartChunking":{"llmBasedChunks":false},"folderID":null}}` + } + switch r.Method { + case http.MethodPost: + w.WriteHeader(http.StatusCreated) + io.WriteString(w, doc(`{"type":"PENDING"}`)) + case http.MethodPatch: + io.WriteString(w, `{"message":"Document d1 now holds the new content."}`) + default: + status := statuses[min(gets, len(statuses)-1)] + gets++ + io.WriteString(w, strings.TrimSuffix(doc(status), "}}")+`,"chunks":[],"metadata":[]}}`) + } + })) + t.Cleanup(srv.Close) + return srv.URL, func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), seen...) + } +} + +// runDocument runs `vf document ` against url and returns stdout, +// stderr and the error the command ended with. +func runDocument(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(append([]string{"document"}, args...), mode, "--no-interactive")) + _, err = root.ExecuteC() + return out.String(), errOut.String(), err +} + +var createText = []string{"create-text", "-p", "p1", "-e", "main", "--file", "docready_test.go"} + +const ( + pending = `{"type":"PENDING"}` + success = `{"type":"SUCCESS"}` + failed = `{"type":"ERROR","data":"Could not parse the file: unsupported encoding"}` +) + +// A create with --wait gets the document until it is processed, and prints +// the create's answer with the final status. +func TestADocumentCreateWaitsUntilItIsProcessed(t *testing.T) { + url, requests := documentServer(t, pending, success) + stdout, stderr, err := runDocument(t, url, false, append(createText, "--wait")...) + if err != nil { + t.Fatalf("%v\n%s%s", err, stdout, stderr) + } + if got := strings.Join(requests(), " "); got != "POST GET GET" { + t.Errorf("requests = %q, want a create, then gets until it's processed", got) + } + if !strings.Contains(stdout, "SUCCESS") || strings.Contains(stdout, "PENDING") { + t.Errorf("the answer should carry the final status:\n%s", stdout) + } + if !strings.Contains(stderr, "Waiting up to 5m0s for billing.md") { + t.Errorf("a person reading a pipe should see one line saying what it waits for:\n%s", stderr) + } +} + +// -o json prints the API's answer as it came, with only the status replaced. +func TestADocumentWaitKeepsTheRawAnswer(t *testing.T) { + url, _ := documentServer(t, success) + stdout, _, err := runDocument(t, url, false, append(createText, "--wait", "-o", "json")...) + if err != nil { + t.Fatal(err) + } + want := `{"document":{"id":"d1","data":{"type":"md","name":"billing.md","canEdit":true},"status":{"type":"SUCCESS"},"smartChunking":{"llmBasedChunks":false},"folderID":null}}` + if strings.TrimSpace(stdout) != want { + t.Errorf("got %s\nwant %s", strings.TrimSpace(stdout), want) + } + stdout, _, err = runDocument(t, url, false, append(createText, "--wait", "--jq", ".document.status.type")...) + if err != nil || strings.TrimSpace(stdout) != "SUCCESS" { + t.Errorf("--jq should read the final status, got %q (%v)", stdout, err) + } +} + +// A document that fails to process fails the command, with the API's reason, +// in every mode. +func TestADocumentThatFailsToProcessExits1(t *testing.T) { + for _, agent := range []bool{false, true} { + url, _ := documentServer(t, failed) + stdout, stderr, err := runDocument(t, url, agent, append(createText, "--wait")...) + 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) + } + if !strings.Contains(stdout, "ERROR") { + t.Errorf("agent %v: the answer should still print, with status ERROR:\n%s", agent, stdout) + } + if !strings.Contains(stderr, "unsupported encoding") || !strings.Contains(stderr, "Couldn't process billing.md (d1)") { + t.Errorf("agent %v: the error should name the document and the reason:\n%s", agent, stderr) + } + if agent { + var envelope map[string]any + if json.Unmarshal([]byte(stderr), &envelope) != nil || envelope["error_type"] != "document_failed" { + t.Errorf("agent mode should get the JSON envelope:\n%s", stderr) + } + } + } +} + +// A wait that runs out exits with the timeout code and says how to keep +// waiting. +func TestADocumentWaitThatRunsOutExits5(t *testing.T) { + url, _ := documentServer(t, pending) + stdout, stderr, err := runDocument(t, url, false, append(createText, "--wait", "--max-wait", "1s")...) + if code := output.ExitCode(err); code != output.ExitTimeout { + t.Fatalf("exit %d, want %d\n%s%s", code, output.ExitTimeout, stdout, stderr) + } + if !strings.Contains(stderr, "still processing after 1s") || !strings.Contains(stderr, "vf document get --document-id d1 --wait -p p1 -e main") { + t.Errorf("the error should say how to keep waiting:\n%s", stderr) + } +} + +// --max-wait means nothing without --wait, and nothing is sent. +func TestMaxWaitNeedsWait(t *testing.T) { + url, requests := documentServer(t, success) + _, stderr, err := runDocument(t, url, false, append(createText, "--max-wait", "1m")...) + if code := output.ExitCode(err); code != output.ExitUsage { + t.Fatalf("exit %d, want %d\n%s", code, output.ExitUsage, stderr) + } + if len(requests()) != 0 { + t.Errorf("nothing should be sent, got %v", requests()) + } +} + +// Without --wait a create is one request, and its answer prints as before. +func TestADocumentCreateWithoutWaitDoesntPoll(t *testing.T) { + url, requests := documentServer(t, success) + stdout, stderr, err := runDocument(t, url, true, createText...) + if err != nil { + t.Fatal(err) + } + if got := strings.Join(requests(), " "); got != "POST" { + t.Errorf("requests = %q, want the create alone", got) + } + if !strings.Contains(stdout, "PENDING") || stderr != "" { + t.Errorf("agent mode keeps the data, status included, and adds nothing:\nstdout %s\nstderr %s", stdout, stderr) + } +} + +// update --wait waits for new text to be processed, and get --wait for a +// document already there. +func TestUpdateAndGetWait(t *testing.T) { + url, requests := documentServer(t, pending, success) + _, stderr, err := runDocument(t, url, false, "update", "--document-id", "d1", "-p", "p1", "-e", "main", "--content", "Refunds take 5 days.", "--wait") + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if got := strings.Join(requests(), " "); got != "PATCH GET GET" { + t.Errorf("update: requests = %q", got) + } + + 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 { + t.Fatalf("%v\n%s", err, stderr) + } + if got := strings.Join(requests(), " "); got != "GET GET GET" || !strings.Contains(stdout, "SUCCESS") { + t.Errorf("get: requests = %q, want polls then the get that prints it:\n%s", got, stdout) + } + + url, _ = documentServer(t, failed) + _, _, err = runDocument(t, url, false, "get", "--document-id", "d1", "-p", "p1", "-e", "main", "--wait") + if code := output.ExitCode(err); code != output.ExitFailure { + t.Errorf("get --wait on a failed document: exit %d, want %d", code, output.ExitFailure) + } +} diff --git a/internal/cli/document/createtable.go b/internal/cli/document/createtable.go index eb8c7a6d..e5c62317 100644 --- a/internal/cli/document/createtable.go +++ b/internal/cli/document/createtable.go @@ -45,6 +45,7 @@ func initCreateTableCmd(parent *cobra.Command) error { Aliases: []string{"ct"}, } flagutil.RegisterFlags(cmd, createTableCmdMeta) + addWait(cmd) // docready.go: --wait waits until the document is processed if err := flagutil.ValidateMeta[operations.StableDocumentControllerCreateTableRequest](createTableCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create-table: %w", err) } @@ -90,9 +91,10 @@ func runCreateTableCmd(cmd *cobra.Command, args []string) error { if err != nil { return output.Error(cmd, err) } + processed := whenProcessed(cmd, req.ProjectID, req.EnvironmentAlias, res) // docready.go: with --wait, polls until it's processed if err := output.Result(cmd, res); err != nil { return err } - return nil + return processed() // docready.go: whether it's ready, and how to check } diff --git a/internal/cli/document/createtext.go b/internal/cli/document/createtext.go index 8c5bf47a..69829103 100644 --- a/internal/cli/document/createtext.go +++ b/internal/cli/document/createtext.go @@ -44,6 +44,7 @@ func initCreateTextCmd(parent *cobra.Command) error { Aliases: []string{"cte"}, } flagutil.RegisterFlags(cmd, createTextCmdMeta) + addWait(cmd) // docready.go: --wait waits until the document is processed if err := flagutil.ValidateMeta[operations.StableDocumentControllerCreateTextRequest](createTextCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create-text: %w", err) } @@ -88,9 +89,10 @@ func runCreateTextCmd(cmd *cobra.Command, args []string) error { if err != nil { return output.Error(cmd, err) } + processed := whenProcessed(cmd, req.ProjectID, req.EnvironmentAlias, res) // docready.go: with --wait, polls until it's processed if err := output.Result(cmd, res); err != nil { return err } - return nil + return processed() // docready.go: whether it's ready, and how to check } diff --git a/internal/cli/document/createurl.go b/internal/cli/document/createurl.go index a88fd6d9..7709bc11 100644 --- a/internal/cli/document/createurl.go +++ b/internal/cli/document/createurl.go @@ -43,6 +43,7 @@ func initCreateUrlCmd(parent *cobra.Command) error { Aliases: []string{"cu"}, } flagutil.RegisterFlags(cmd, createURLCmdMeta) + addWait(cmd) // docready.go: --wait waits until the document is processed if err := flagutil.ValidateMeta[operations.StableDocumentControllerCreateURLRequest](createURLCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create-url: %w", err) } @@ -88,9 +89,10 @@ func runCreateUrlCmd(cmd *cobra.Command, args []string) error { if err != nil { return output.Error(cmd, err) } + processed := whenProcessed(cmd, req.ProjectID, req.EnvironmentAlias, res) // docready.go: with --wait, polls until it's processed if err := output.Result(cmd, res); err != nil { return err } - return nil + return processed() // docready.go: whether it's ready, and how to check } diff --git a/internal/cli/document/docready.go b/internal/cli/document/docready.go new file mode 100644 index 00000000..64801d96 --- /dev/null +++ b/internal/cli/document/docready.go @@ -0,0 +1,571 @@ +// This file is not generated by Speakeasy. It says when a knowledge base +// document is ready, and can wait until it is. +// +// The knowledge base processes a document after the request that adds it +// returns: create-text, create-url and create-table answer status PENDING, +// and the document is searchable once `vf document get` says SUCCESS, or has +// failed when it says ERROR. Nothing said so. A create printed a raw dump +// ending in `status: type: PENDING`, with no ✓ line, no Next line and no way +// to wait, so the usability sweep's testers ran `document list` until it read +// SUCCESS, and an agent polled `document get` by hand. +// +// Now a create, at a terminal, ends by saying what it added, its status and +// how to check on it. With --wait it polls the document until it is processed, +// with a progress line at a terminal, then prints the create's answer with the +// final status. It exits 0 when the document is ready, 1 when processing +// failed (with the API's reason) and 5 when --max-wait ran out first. +// `document update` takes --wait too, since new text is processed again, and +// `document get --wait` waits on a document already there: that is what a +// wait that ran out says to run next. +// +// Hooked in by lines in createtext.go, createurl.go, createtable.go, +// update.go and get.go, which a regeneration could drop without anything +// failing to compile; internal/cli/docready_test.go covers each of them. + +package document + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/config" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/sdk/models/sdkerrors" + "github.com/voiceflow/cli/internal/session" + "github.com/voiceflow/cli/internal/ui" + "github.com/voiceflow/cli/internal/usage" +) + +const ( + waitFlag = "wait" + maxWaitFlag = "max-wait" + + // Testers saw every document processed within about two minutes; a crawl + // can take longer. + defaultMaxWait = 5 * time.Minute + + // Transient failures of a poll retried before the wait gives up. + pollRetries = 3 +) + +// pollInterval is the time between two polls. +const pollInterval = 2 * time.Second + +// waitHelp says what --wait waits for on each command that takes it, and +// waitExample shows it. +var ( + waitHelp = map[string]string{ + "create-text": "Wait until the knowledge base has processed the document, then print it. Exits 1 if processing failed, and 5 if --max-wait ran out first.", + "create-url": "Wait until the knowledge base has crawled and processed the page, then print the document. Exits 1 if processing failed, and 5 if --max-wait ran out first.", + "create-table": "Wait until the knowledge base has processed the table, then print it. Exits 1 if processing failed, and 5 if --max-wait ran out first.", + "update": "Wait until the knowledge base has processed the document's new text. Exits 1 if processing failed, and 5 if --max-wait ran out first.", + "get": "Wait until the document is processed (status SUCCESS or ERROR), then print it. Exits 1 if processing failed, and 5 if --max-wait ran out first.", + } + waitExample = map[string]string{ + "create-text": "vf document create-text --project-id --environment-alias --file faq.md --wait", + "create-url": "vf document create-url --project-id --environment-alias --url https://example.com/faq --wait", + "update": "vf document update --document-id --project-id --environment-alias --content 'Refunds take 5 days.' --wait", + "get": "vf document get --document-id --project-id --environment-alias --wait", + } +) + +// addWait gives cmd --wait and --max-wait. +func addWait(cmd *cobra.Command) { + cmd.Flags().Bool(waitFlag, false, waitHelp[cmd.Name()]) + cmd.Flags().Duration(maxWaitFlag, defaultMaxWait, "With --wait, how long to wait at most (e.g. 10m). The document keeps processing after that.") + usage.AddFlags("document "+cmd.Name(), + usage.UsageFlag{Spec: "--" + waitFlag, Help: cmd.Flags().Lookup(waitFlag).Usage}, + usage.UsageFlag{Spec: "--" + maxWaitFlag + " ", Help: cmd.Flags().Lookup(maxWaitFlag).Usage}) + if example := waitExample[cmd.Name()]; example != "" { + cmd.Example += "\n " + example + } + cmd.PreRunE = checkWaitFlags +} + +// checkWaitFlags refuses --max-wait without --wait before anything is sent. +func checkWaitFlags(cmd *cobra.Command, _ []string) error { + if cmd.Flags().Changed(maxWaitFlag) && !waits(cmd) { + return usageError(cmd, fmt.Sprintf("--%s only applies with --%s", maxWaitFlag, waitFlag), + fmt.Sprintf("Add --%s, or drop --%s", waitFlag, maxWaitFlag)) + } + if maxWait, _ := cmd.Flags().GetDuration(maxWaitFlag); maxWait <= 0 { + return usageError(cmd, fmt.Sprintf("--%s must be more than zero, got %s", maxWaitFlag, maxWait), + fmt.Sprintf("Pass a duration such as --%s 10m, or drop it to wait up to %s", maxWaitFlag, defaultMaxWait)) + } + return nil +} + +func usageError(cmd *cobra.Command, message, hint string) error { + return output.Report(cmd, output.Explanation{Type: "invalid_flag_value", Title: message, Next: []string{hint}}, errors.New(message)) +} + +func waits(cmd *cobra.Command) bool { + wait, _ := flagutil.GetBoolFlag(cmd, waitFlag) + return wait +} + +// docRef is a document a command added or named, and where it lives. +type docRef struct { + id, name, projectID, alias string +} + +// call is how to refer to the document: its name and ID, or its ID alone. +func (d docRef) call() string { + if d.name == "" || d.name == d.id { + return "document " + d.id + } + return d.name + " (" + d.id + ")" +} + +// get is the command that shows the document, with --wait when wait is set. +// Inside the home prompt the project and environment are left out, since the +// prompt fills them. +func (d docRef) get(wait bool) string { + c := "vf document get --document-id " + d.id + if wait { + c += " --wait" + } + if !session.Active() { + c += " -p " + d.projectID + " -e " + d.alias + } + return c +} + +// createdDocument is the answer of create-text, create-url and create-table. +type createdDocument interface { + GetHTTPMeta() components.HTTPMetadata + GetStableDocumentResponse() *components.StableDocumentResponse +} + +// documentSummary is the part of a document this file reads, from a typed +// answer or a raw one alike. +type documentSummary struct { + Document struct { + ID string `json:"id"` + Data struct { + Name string `json:"name"` + } `json:"data"` + Status components.KBDocumentStatus `json:"status"` + } `json:"document"` +} + +// whenProcessed reads a create's answer before it is printed. With --wait it +// polls the document until it is processed and puts the final status in the +// answer. The func it returns runs once the answer is printed: it says +// whether the document is ready, and how to check, and returns how the +// command exits. +func whenProcessed(cmd *cobra.Command, projectID, alias string, res createdDocument) func() error { + none := func() error { return nil } + if res == nil || client.IsDryRun(cmd) { + return none + } + var doc documentSummary + if typed := res.GetStableDocumentResponse(); typed != nil { + data, err := json.Marshal(typed) + if err != nil || json.Unmarshal(data, &doc) != nil { + return none + } + } else if !output.PeekJSON(res.GetHTTPMeta().Response, &doc) { + return none + } + ref := docRef{id: doc.Document.ID, name: doc.Document.Data.Name, projectID: projectID, alias: alias} + if ref.id == "" { + return none + } + if !waits(cmd) { + return func() error { + announceAdded(cmd, ref, doc.Document.Status) + return nil + } + } + w := pollDocument(cmd, &ref) + if w.err == nil { + setStatus(res, w.status) + } + return func() error { return w.outcome(cmd, ref, verb(cmd)) } +} + +// 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 { + none := func() error { return nil } + if req == nil || client.IsDryRun(cmd) { + return none + } + ref := docRef{id: req.DocumentID, projectID: req.ProjectID, alias: req.EnvironmentAlias} + if !waits(cmd) { + if req.Body.Content == nil { + return none + } + return func() error { + if announces(cmd) { + nextSteps(cmd, []ui.Tip{{Command: ref.get(true), Does: "wait until the new text is searchable"}}) + } + return nil + } + } + w := pollDocument(cmd, &ref) + return func() error { return w.outcome(cmd, ref, "Updated") } +} + +// waitBeforeGet makes `document get --wait` poll the document until it is +// processed, before the get that prints it. The func it returns judges what +// the wait saw. A poll that fails leaves the get to report the same failure. +func waitBeforeGet(cmd *cobra.Command, req *operations.StableDocumentControllerGetRequest) func() error { + none := func() error { return nil } + if req == nil || !waits(cmd) || client.IsDryRun(cmd) { + return none + } + ref := docRef{id: req.DocumentID, projectID: req.ProjectID, alias: req.EnvironmentAlias} + w := pollDocument(cmd, &ref) + if w.err != nil { + return none + } + return func() error { return w.outcome(cmd, ref, "") } +} + +// verb is what a create did: added the document, or replaced one by the +// same name with --overwrite. +func verb(cmd *cobra.Command) string { + if v, _ := flagutil.GetStringFlag(cmd, "overwrite"); strings.EqualFold(strings.Trim(v, `"' `), "true") { + return "Replaced" + } + return "Added" +} + +// announces is whether a person is reading pretty output at a terminal, so +// the lines around the result help rather than get in the way. A var so +// tests can be at one. +var announces = func(cmd *cobra.Command) bool { + jq, _ := flagutil.GetStringFlag(cmd, "jq") + format, changed := flagutil.GetStringFlag(cmd, "output-format") + if !changed && config.GetString("output-format") != "" { + format = config.GetString("output-format") + } + human := format == "" || format == "pretty" || format == "table" + return jq == "" && human && !output.IsAgentMode() && output.UI(cmd, cmd.ErrOrStderr()).Decorated() +} + +// announceAdded ends a create without --wait: what was added, its status, and +// how to check on it. +// +// ✓ Added billing.md (6b0d…) · processing (PENDING), usually for under a minute +// Next: +// vf document get --document-id 6b0d… --wait wait until it's ready +// vf document list -o table every document's status +func announceAdded(cmd *cobra.Command, ref docRef, status components.KBDocumentStatus) { + if !announces(cmd) { + return + } + w := cmd.ErrOrStderr() + u := output.UI(cmd, w) + what := verb(cmd) + " " + ref.call() + switch status.Type { + case components.KnowledgeBaseDocumentStatusSuccess: + fmt.Fprintln(w, u.Status(ui.StatusDone, what+" · ready: the knowledge base answers from it")) + return + case components.KnowledgeBaseDocumentStatusError: + 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 + } + fmt.Fprintln(w, u.Status(ui.StatusDone, what+" · processing ("+string(status.Type)+"), usually for under a minute")) + list := "vf document list -o table" + if !session.Active() { + list += " -p " + ref.projectID + " -e " + ref.alias + } + nextSteps(cmd, []ui.Tip{ + {Command: ref.get(true), Does: "wait until it's ready"}, + {Command: list, Does: "every document's status"}, + }) +} + +// nextSteps prints tips under "Next:", as a create's are (output/created.go). +func nextSteps(cmd *cobra.Command, tips []ui.Tip) { + w := cmd.ErrOrStderr() + u := output.UI(cmd, w) + fmt.Fprintln(w, u.Bold("Next:")) + for _, row := range u.Tips(tips, ui.TerminalWidth(w)-2) { + fmt.Fprintln(w, " "+row) + } +} + +// waited is what a wait saw: the document's last status, how long it took, +// and the error that stopped it early, if one did. +type waited struct { + status components.KBDocumentStatus + took time.Duration + maxWait time.Duration + err error +} + +func processed(status components.KBDocumentStatus) bool { + return status.Type == components.KnowledgeBaseDocumentStatusSuccess || status.Type == components.KnowledgeBaseDocumentStatusError +} + +// pollDocument gets the document until it is processed or --max-wait runs +// out. A poll that fails for a moment (a rate limit, a server error, a +// dropped connection) is tried again. It learns the document's name, if ref +// lacks one. +func pollDocument(cmd *cobra.Command, ref *docRef) waited { + maxWait, _ := cmd.Flags().GetDuration(maxWaitFlag) + w := waited{maxWait: maxWait} + s, err := client.NewClient(cmd) + if err != nil { + w.err = err + return w + } + opts, err := output.PrepareCallOpts(cmd) + if err != nil { + w.err = err + return w + } + ctx := client.WithoutSpinner(cmd.Context()) + start := time.Now() + deadline := start.Add(maxWait) + stop := showProgress(cmd, *ref, maxWait) + defer stop() + failures := 0 + for { + res, err := s.Document.Get(ctx, operations.StableDocumentControllerGetRequest{ + DocumentID: ref.id, ProjectID: ref.projectID, EnvironmentAlias: ref.alias, + }, opts...) + w.took = time.Since(start) + if err != nil { + if ctx.Err() == nil && transient(err) && failures < pollRetries && time.Until(deadline) > 0 { + failures++ + if sleep(ctx, min(pollInterval, time.Until(deadline))) == nil { + continue + } + } + w.err = err + return w + } + failures = 0 + if details := res.GetStableDocumentDetailsResponse(); details != nil { + w.status = details.Document.Status + if ref.name == "" { + ref.name = nameOf(details.Document) + } + } + if processed(w.status) || time.Until(deadline) <= 0 { + return w + } + if err := sleep(ctx, min(pollInterval, time.Until(deadline))); err != nil { + w.err = err + return w + } + } +} + +// nameOf is the document's name, whatever its type. +func nameOf(doc components.StableDocumentDetails) string { + var named struct { + Data struct { + Name string `json:"name"` + } `json:"data"` + } + if data, err := json.Marshal(doc); err == nil { + _ = json.Unmarshal(data, &named) + } + return named.Data.Name +} + +// showProgress shows the wait: a spinner at a terminal, one plain line for a +// person reading a pipe or a log, and nothing for an agent, which reads the +// outcome. The func it returns ends it. +func showProgress(cmd *cobra.Command, ref docRef, maxWait time.Duration) func() { + if output.IsAgentMode() { + return func() {} + } + w := cmd.ErrOrStderr() + u := output.UI(cmd, w) + what := ref.name + if what == "" { + what = "document " + ref.id + } + spinner := u.Spin(w, "Processing "+what+"…", "ctrl-c stops waiting, not the processing") + if !spinner.Active() { + fmt.Fprintf(w, "Waiting up to %s for %s to be processed…\n", maxWait, what) + } + return spinner.Stop +} + +// outcome says how the wait ended, once the answer is printed, and returns +// how the command exits: nil when the document is ready. +func (w waited) outcome(cmd *cobra.Command, ref docRef, did string) error { + if w.err != nil { + x := output.ExplainError(cmd, w.err) + title := "Stopped waiting for " + ref.call() + if _, status, ok := strings.Cut(x.Title, " · "); ok { + title += " · " + status + } + x.Title = title + x.Next = append(x.Next, "It keeps processing. Check on it: `"+ref.get(true)+"`") + return output.Report(cmd, x, w.err) + } + switch w.status.Type { + case components.KnowledgeBaseDocumentStatusSuccess: + if announces(cmd) { + what := ref.call() + " is ready" + if did != "" { + what = did + " " + ref.call() + " · ready" + } + fmt.Fprintln(cmd.ErrOrStderr(), output.UI(cmd, cmd.ErrOrStderr()).Status(ui.StatusDone, + fmt.Sprintf("%s: the knowledge base answers from it (%s)", what, w.took.Round(time.Second)))) + } + return nil + case components.KnowledgeBaseDocumentStatusError: + message := "Couldn't process " + ref.call() + return output.Report(cmd, output.Explanation{ + Type: "document_failed", + Title: message, + Message: failureReason(w.status), + Why: []string{"The knowledge base couldn't read the document, so it can't answer from it."}, + Next: []string{ + "See it: `" + ref.get(false) + "`", + "Fix the source, then add it again with `--overwrite true`, which keeps its ID", + }, + }, errors.New(message+": "+failureReason(w.status))) + } + message := fmt.Sprintf("%s was still processing after %s", ref.call(), w.maxWait) + return output.Report(cmd, output.Explanation{ + Type: "timeout", + Title: message, + Why: []string{"Processing goes on without vf. The document is searchable once its status is SUCCESS."}, + Next: []string{ + "Keep waiting: `" + ref.get(true) + "`", + "Wait longer at once with `--max-wait 15m`", + }, + }, errors.New(message)) +} + +// failureReason is why processing failed, in the API's words. +func failureReason(status components.KBDocumentStatus) string { + switch data := status.Data.(type) { + case string: + if strings.TrimSpace(data) != "" { + return data + } + case map[string]any: + for _, key := range []string{"message", "error", "reason"} { + if s, ok := data[key].(string); ok && strings.TrimSpace(s) != "" { + return s + } + } + if raw, err := json.Marshal(data); err == nil && len(data) > 0 { + return string(raw) + } + } + return "the knowledge base didn't say why" +} + +// setStatus puts status in a create's answer before it is printed: the typed +// answer, or the raw body that -o json and --jq print as it came, with only +// the status's value replaced. +func setStatus(res createdDocument, status components.KBDocumentStatus) { + if typed := res.GetStableDocumentResponse(); typed != nil { + typed.Document.Status = status + return + } + httpRes := res.GetHTTPMeta().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 + } + value, err := json.Marshal(status) + if err != nil { + return + } + if patched, ok := replaceStatus(raw, value); ok { + httpRes.Body = io.NopCloser(bytes.NewReader(patched)) + } +} + +// replaceStatus replaces the value of document.status in a JSON object, +// leaving every other byte as it was. +func replaceStatus(raw, status []byte) ([]byte, bool) { + dec := json.NewDecoder(bytes.NewReader(raw)) + if t, err := dec.Token(); err != nil || t != json.Delim('{') { + return nil, false + } + for dec.More() { + key, err := dec.Token() + if err != nil { + return nil, false + } + if key != "document" { + var skip json.RawMessage + if dec.Decode(&skip) != nil { + return nil, false + } + continue + } + if t, err := dec.Token(); err != nil || t != json.Delim('{') { + return nil, false + } + for dec.More() { + field, err := dec.Token() + if err != nil { + return nil, false + } + var value json.RawMessage + if dec.Decode(&value) != nil { + return nil, false + } + if field == "status" { + end := int(dec.InputOffset()) + start := end - len(value) + return append(append(append([]byte{}, raw[:start]...), status...), raw[end:]...), true + } + } + return nil, false + } + return nil, false +} + +// transient is whether a failed poll is worth repeating: a rate limit, a +// server error, or a request that never got an answer. +func transient(err error) bool { + var apiErr *sdkerrors.SDKDefaultError + if errors.As(err, &apiErr) { + return apiErr.StatusCode == http.StatusTooManyRequests || apiErr.StatusCode >= 500 + } + var urlErr *url.Error + var netErr net.Error + return errors.As(err, &urlErr) || errors.As(err, &netErr) || errors.Is(err, io.ErrUnexpectedEOF) +} + +func sleep(ctx context.Context, d time.Duration) error { + if d <= 0 { + return ctx.Err() + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil + } +} diff --git a/internal/cli/document/docready_test.go b/internal/cli/document/docready_test.go new file mode 100644 index 00000000..82277899 --- /dev/null +++ b/internal/cli/document/docready_test.go @@ -0,0 +1,94 @@ +// This file is not generated by Speakeasy. It covers what docready.go prints +// for a person, which only shows at a terminal, and its edit of a raw answer. + +package document + +import ( + "bytes" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" +) + +func atATerminal(t *testing.T) { + t.Helper() + was := announces + announces = func(*cobra.Command) bool { return true } + t.Cleanup(func() { announces = was }) +} + +// A create without --wait ends by saying what it added, its status, and how +// to check on it. +func TestACreateSaysTheDocumentIsProcessingAndHowToCheck(t *testing.T) { + atATerminal(t) + cmd := &cobra.Command{Use: "create-text"} + cmd.Flags().String("overwrite", "", "") + var stderr bytes.Buffer + cmd.SetErr(&stderr) + ref := docRef{id: "d1", name: "billing.md", projectID: "p1", alias: "main"} + + announceAdded(cmd, ref, components.KBDocumentStatus{Type: components.KnowledgeBaseDocumentStatusPending}) + got := stderr.String() + for _, want := range []string{ + "Added billing.md (d1) · processing (PENDING)", + "Next:", + "vf document get --document-id d1 --wait -p p1 -e main", + "vf document list -o table -p p1 -e main", + } { + if !strings.Contains(got, want) { + t.Errorf("missing %q in:\n%s", want, got) + } + } + + stderr.Reset() + _ = cmd.Flags().Set("overwrite", "true") + announceAdded(cmd, ref, components.KBDocumentStatus{Type: components.KnowledgeBaseDocumentStatusSuccess}) + if got := stderr.String(); !strings.Contains(got, "Replaced billing.md (d1) · ready") || strings.Contains(got, "Next:") { + t.Errorf("a document that's ready needs no next step:\n%s", got) + } +} + +// An update of a document's text says how to wait for it; a move doesn't. +func TestAnUpdateOfTheTextSaysHowToWait(t *testing.T) { + atATerminal(t) + cmd := &cobra.Command{Use: "update"} + cmd.Flags().Bool(waitFlag, false, "") + var stderr bytes.Buffer + cmd.SetErr(&stderr) + text := "new text" + req := updateRequest("d1", &text) + if err := whenReprocessed(cmd, req)(); err != nil { + t.Fatal(err) + } + 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 { + t.Errorf("a move isn't processed again, so says nothing, got %q", stderr.String()) + } +} + +// 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"}` + got, ok := replaceStatus([]byte(raw), []byte(`{"type":"SUCCESS"}`)) + want := `{"document":{"id":"d1","data":{"name":"a","status":"x"},"status": {"type":"SUCCESS"} ,"folderID":null},"status":"top"}` + if !ok || string(got) != want { + t.Errorf("got %s\nwant %s", got, want) + } + if _, ok := replaceStatus([]byte(`{"message":"x"}`), []byte(`{}`)); ok { + t.Error("an answer with no document has no status to replace") + } +} + +func updateRequest(id string, content *string) *operations.StableDocumentControllerUpdateV2Request { + return &operations.StableDocumentControllerUpdateV2Request{ + DocumentID: id, ProjectID: "p1", EnvironmentAlias: "main", + Body: components.StableDocumentUpdateRequestV2{Content: content}, + } +} diff --git a/internal/cli/document/get.go b/internal/cli/document/get.go index e555bf99..e9506744 100644 --- a/internal/cli/document/get.go +++ b/internal/cli/document/get.go @@ -31,6 +31,7 @@ func initGetCmd(parent *cobra.Command) error { RunE: runGetCmd, } flagutil.RegisterFlags(cmd, getCmdMeta) + addWait(cmd) // docready.go: --wait waits until the document is processed if err := flagutil.ValidateMeta[operations.StableDocumentControllerGetRequest](getCmdMeta); err != nil { return fmt.Errorf("invalid metadata for get: %w", err) } @@ -71,6 +72,7 @@ func runGetCmd(cmd *cobra.Command, args []string) error { if output.WantsRawJSON(cmd) { sdkOpts = append(sdkOpts, operations.WithSkipDeserialization()) } + waited := waitBeforeGet(cmd, req) // docready.go: with --wait, polls until it's processed res, err := s.Document.Get(cmd.Context(), *req, sdkOpts...) if err != nil { return output.Error(cmd, err) @@ -79,5 +81,5 @@ func runGetCmd(cmd *cobra.Command, args []string) error { if err := output.Result(cmd, res); err != nil { return err } - return nil + return waited() // docready.go: whether it's ready } diff --git a/internal/cli/document/update.go b/internal/cli/document/update.go index 0297a330..3457c621 100644 --- a/internal/cli/document/update.go +++ b/internal/cli/document/update.go @@ -34,6 +34,7 @@ func initUpdateCmd(parent *cobra.Command) error { RunE: runUpdateCmd, } flagutil.RegisterFlags(cmd, updateCmdMeta) + addWait(cmd) // docready.go: --wait waits until new text is processed if err := flagutil.ValidateMeta[operations.StableDocumentControllerUpdateV2Request](updateCmdMeta); err != nil { return fmt.Errorf("invalid metadata for update: %w", err) } @@ -79,9 +80,10 @@ 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 if err := output.Result(cmd, res); err != nil { return err } - return nil + return processed() // docready.go: whether it's ready, and how to check } diff --git a/internal/client/spinner.go b/internal/client/spinner.go index e7e21224..020077dd 100644 --- a/internal/client/spinner.go +++ b/internal/client/spinner.go @@ -59,6 +59,15 @@ func WithSpinnerMessage(ctx context.Context, msg string) context.Context { return context.WithValue(ctx, spinnerMessageKey{}, msg) } +type noSpinnerKey struct{} + +// WithoutSpinner makes requests made with ctx draw no spinner of their own, +// for a wait that draws one across many requests: `vf document create-text +// --wait` polls the document, and a spinner per poll would fight its own. +func WithoutSpinner(ctx context.Context) context.Context { + return context.WithValue(ctx, noSpinnerKey{}, true) +} + // spinnerMessage is what the command does, as its help says it ("List // projects"), so the line reads like Claude Code's "Reading file…". func spinnerMessage(cmd *cobra.Command) string { @@ -79,6 +88,9 @@ type spinnerClient struct { // Do runs the request under a spinner. The spinner stops when the response // headers arrive, so a streamed body is never drawn over. func (c *spinnerClient) Do(req *http.Request) (*http.Response, error) { + if req.Context().Value(noSpinnerKey{}) != nil { + return c.inner.Do(req) + } msg := c.msg if m, ok := req.Context().Value(spinnerMessageKey{}).(string); ok { msg = m diff --git a/test/run-suite-wait.test.ts b/test/run-suite-wait.test.ts index 1c0940d8..1eae32af 100644 --- a/test/run-suite-wait.test.ts +++ b/test/run-suite-wait.test.ts @@ -376,7 +376,8 @@ describe('create-suite --wait', () => { const createSuite = block.slice(0, block.search(/\n\s*\}\n/)); expect(createSuite, args.join(' ')).toContain('flag "--wait"'); expect(createSuite, args.join(' ')).toContain('flag "--max-wait "'); - expect(result.stdout.match(/flag "--wait"/g), args.join(' ')).toHaveLength(1); + // Once: other commands have a --wait of their own (vf document create-text). + expect(result.stdout.match(/flag "--wait" help="Wait until every run in the suite/g), args.join(' ')).toHaveLength(1); } }); From cc36e82249e3f1590203406f10403abdeda7ad86 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:29:53 -0500 Subject: [PATCH 15/28] fix(document): long text flags read a file, and a path isn't sent as text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `document update --content` took only the text itself, so a tester who typed faq/refunds.md into the Content field replaced the live document's text with the words "faq/refunds.md", with no warning. `agent update --prompt` and `--instructions` had no file form either, and agents built a --body with jq --rawfile to get a prompt file in. `document update` takes --file for a text or Markdown file. --content, --prompt and --instructions (agent update, playbook create and update) take @file for a file's text and - for stdin's, read as the flag is set, so a form's answer works too; @@ starts text that starts with @. A --content that is one word naming a file is not sent as is: at a terminal vf asks whether to send the file's text instead, No sending nothing; elsewhere nobody can answer, so it refuses with exit 2 and names --file, and --body '{"content":…}' for the words themselves. Found by the round-4 sweep's human-kb, agent-builder and agent-ci testers. --- internal/cli/agent/update.go | 1 + internal/cli/contentfile_test.go | 130 ++++++++++++++++++ internal/cli/document/contentfile.go | 154 ++++++++++++++++++++++ internal/cli/document/contentfile_test.go | 67 ++++++++++ internal/cli/document/update.go | 6 +- internal/cli/playbook/create.go | 1 + internal/cli/playbook/update.go | 1 + internal/flagutil/textfile.go | 135 +++++++++++++++++++ internal/flagutil/textfile_test.go | 81 ++++++++++++ 9 files changed, 575 insertions(+), 1 deletion(-) create mode 100644 internal/cli/contentfile_test.go create mode 100644 internal/cli/document/contentfile.go create mode 100644 internal/cli/document/contentfile_test.go create mode 100644 internal/flagutil/textfile.go create mode 100644 internal/flagutil/textfile_test.go diff --git a/internal/cli/agent/update.go b/internal/cli/agent/update.go index 5cacb249..529b37ff 100644 --- a/internal/cli/agent/update.go +++ b/internal/cli/agent/update.go @@ -46,6 +46,7 @@ func initUpdateCmd(parent *cobra.Command) error { RunE: runUpdateCmd, } flagutil.RegisterFlags(cmd, updateCmdMeta) + flagutil.ReadsText(cmd, "prompt", "instructions") // flagutil/textfile.go: @file and - read the text if err := flagutil.ValidateMeta[operations.StableAgentControllerUpdateV2Request](updateCmdMeta); err != nil { return fmt.Errorf("invalid metadata for update: %w", err) } diff --git a/internal/cli/contentfile_test.go b/internal/cli/contentfile_test.go new file mode 100644 index 00000000..1047f951 --- /dev/null +++ b/internal/cli/contentfile_test.go @@ -0,0 +1,130 @@ +// This file is not generated by Speakeasy. It covers document/contentfile.go +// and the flags that read text with flagutil/textfile.go: a document's new +// text, an agent's prompt and a playbook's instructions can come from a file, +// and a path typed as a document's text isn't sent as the text. + +package cli + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// inFolder makes a folder with faq/refunds.md the working directory. +func inFolder(t *testing.T) { + t.Helper() + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "faq"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "faq", "refunds.md"), []byte("Refunds take 7 business days.\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Chdir(dir) +} + +var updateDoc = []string{"update", "--document-id", "d1", "-p", "p1", "-e", "main"} + +// A document's new text comes from --file, or from @file in --content. +func TestADocumentUpdateReadsItsTextFromAFile(t *testing.T) { + inFolder(t) + for _, flags := range [][]string{{"--file", "faq/refunds.md"}, {"--content", "@faq/refunds.md"}} { + url, requests := documentServer(t, success) + _, stderr, err := runDocument(t, url, false, append(append(updateDoc, flags...), "--dry-run")...) + if err != nil { + t.Fatalf("%v: %v\n%s", flags, err, stderr) + } + if !strings.Contains(stderr, `"content": "Refunds take 7 business days.\n"`) { + t.Errorf("%v: the body should hold the file's text:\n%s", flags, stderr) + } + if len(requests()) != 0 { + t.Errorf("a dry run sends nothing") + } + } +} + +// A path typed as --content isn't sent as the document's text: without a +// terminal to ask at, vf refuses, and says how to send either one. +func TestAPathAsADocumentsTextIsRefused(t *testing.T) { + inFolder(t) + for _, agent := range []bool{false, true} { + url, requests := documentServer(t, success) + _, stderr, err := runDocument(t, url, agent, append(updateDoc, "--content", "faq/refunds.md")...) + if code := output.ExitCode(err); code != output.ExitUsage { + t.Fatalf("agent %v: exit %d, want %d\n%s", agent, code, output.ExitUsage, stderr) + } + if len(requests()) != 0 { + t.Errorf("agent %v: nothing should be sent, got %v", agent, requests()) + } + said := stderr + if agent { + var envelope struct { + Error string `json:"error"` + Hints []string `json:"hints"` + } + if err := json.Unmarshal([]byte(stderr), &envelope); err != nil { + t.Fatalf("agent mode should get the JSON envelope: %v\n%s", err, stderr) + } + said = envelope.Error + "\n" + strings.Join(envelope.Hints, "\n") + } + for _, want := range []string{"names a file", "--file faq/refunds.md", `--body '{"content":"faq/refunds.md"}'`} { + if !strings.Contains(said, want) { + t.Errorf("agent %v: missing %s in:\n%s", agent, want, said) + } + } + } + + // Text that only looks like a path, or names no file, is sent as typed. + for _, text := range []string{"faq/missing.md", "Refunds take 5 days."} { + url, requests := documentServer(t, success) + if _, stderr, err := runDocument(t, url, false, append(updateDoc, "--content", text)...); err != nil { + t.Errorf("%q: %v\n%s", text, err, stderr) + } + if got := strings.Join(requests(), " "); got != "PATCH" { + t.Errorf("%q: requests = %q", text, got) + } + } +} + +// --prompt and --instructions read @file and -. +func TestAPromptComesFromAFileOrStdin(t *testing.T) { + inFolder(t) + url, _ := documentServer(t, success) + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", url) + t.Setenv("HOME", t.TempDir()) + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + cases := []struct { + args []string + stdin string + want string + }{ + {[]string{"agent", "update", "-p", "p1", "-e", "main", "--prompt", "@faq/refunds.md"}, "", `"prompt": "Refunds take 7 business days.\n"`}, + {[]string{"agent", "update", "-p", "p1", "-e", "main", "--instructions", "-"}, "Be brief.", `"instructions": "Be brief."`}, + {[]string{"playbook", "update", "-p", "p1", "-e", "main", "--playbook-id", "pb1", "--instructions", "@faq/refunds.md"}, "", `"instructions": "Refunds take 7 business days.\n"`}, + {[]string{"playbook", "create", "-p", "p1", "-e", "main", "--name", "Refunds", "--instructions", "@faq/refunds.md"}, "", `"instructions": "Refunds take 7 business days.\n"`}, + } + for _, c := range cases { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var out strings.Builder + root.SetOut(&out) + root.SetErr(&out) + root.SetIn(strings.NewReader(c.stdin)) + root.SetArgs(append(c.args, "--dry-run", "--agent-mode=false", "--no-interactive")) + if _, err := root.ExecuteC(); err != nil { + t.Fatalf("%v: %v\n%s", c.args, err, out.String()) + } + if !strings.Contains(out.String(), c.want) { + t.Errorf("%v: want %s in:\n%s", c.args, c.want, out.String()) + } + } +} diff --git a/internal/cli/document/contentfile.go b/internal/cli/document/contentfile.go new file mode 100644 index 00000000..7b6460d7 --- /dev/null +++ b/internal/cli/document/contentfile.go @@ -0,0 +1,154 @@ +// This file is not generated by Speakeasy. It lets `vf document update` take +// a document's new text from a file, and stops a file's path from becoming +// the text. +// +// --content takes the document's whole new text, and nothing else could. A +// help-center writer who edits refunds.md typed its path into the Content +// field, and the update replaced the live FAQ with the words +// "faq/refunds.md", without a warning. +// +// Now --file reads the new text from a file, and --content takes @file and - +// (flagutil/textfile.go). A --content that is one word naming a file here is +// almost surely a path meant as --file, and sending it would wipe the +// document, so vf doesn't send it as is. At a terminal it asks whether to +// send the file's text instead, No sending nothing. Anywhere else nobody can +// answer, and a script or an agent that names a file wants its text more +// often than the path, so vf refuses with exit 2 and says how to send +// either one. The words themselves still go with --body +// '{"content":"faq/refunds.md"}', which is unambiguous, so no --force flag is +// needed for a document whose whole text is a path. + +package document + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "unicode/utf8" + + "github.com/spf13/cobra" + "golang.org/x/term" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/usage" +) + +const contentFileFlag = "file" + +// addContentFile gives `document update` --file, and @file and - for +// --content. +func addContentFile(cmd *cobra.Command) { + flagutil.ReadsText(cmd, "content") + cmd.Flags().String(contentFileFlag, "", "A text or Markdown file whose text replaces the document's, as --content does. To replace a PDF or Word document, upload it again: vf document create-text --file --overwrite true.") + usage.AddFlags("document update", usage.UsageFlag{Spec: "--" + contentFileFlag + " ", Help: cmd.Flags().Lookup(contentFileFlag).Usage}) + cmd.Example += "\n vf document update --document-id --project-id --environment-alias --file faq/refunds.md" +} + +// askYesNo and atTerminal are vars so tests can answer and be at one. +var ( + askYesNo = interactive.AskYesNo + atTerminal = func() bool { + return term.IsTerminal(int(os.Stdin.Fd())) && term.IsTerminal(int(os.Stderr.Fd())) + } +) + +// contentFromFile sets --content from --file, and stops a --content that +// names a file from being sent as the document's text. +func contentFromFile(cmd *cobra.Command) error { + path, fromFile := flagutil.GetStringFlag(cmd, contentFileFlag) + content, given := flagutil.GetStringFlag(cmd, "content") + if fromFile { + if given { + return refuse(cmd, "--file and --content both give the document's new text", nil, + "Pass one of them: --file reads a file, --content takes the text") + } + return setContentFrom(cmd, path) + } + if !given { + return nil + } + file, ok := namesAFile(content) + if !ok { + return nil + } + words := strings.TrimSpace(content) + sendWords := fmt.Sprintf("To send the words %q as the text after all, put them in the body: --body '{\"content\":%q}'", words, words) + if !asks(cmd) { + return refuse(cmd, + fmt.Sprintf("--content %q names a file, so it would replace the document's whole text with those words", words), + []string{"--content takes the new text itself. Nothing was sent."}, + "Send the file's text: --file "+words+" (or --content @"+words+")", sendWords) + } + yes, err := askYesNo(cmd.Context(), "Send the text of the file "+words+"?", + fmt.Sprintf("--content is the document's whole new text, and %q names a file here. Yes sends the file's text, as --file does. No sends nothing.", words)) + if err != nil || !yes { + message := "Canceled: nothing was sent" + return output.Report(cmd, output.Explanation{ + Type: "canceled", + Title: message, + Next: []string{"Send the file's text: `--file " + words + "`", sendWords}, + }, fmt.Errorf("%s: %w", message, context.Canceled)) + } + return setContentFrom(cmd, file) +} + +// setContentFrom sets --content to the text of the file at path. +func setContentFrom(cmd *cobra.Command, path string) error { + text, err := flagutil.ReadTextFile(path, "--"+contentFileFlag) + if err != nil { + return refuse(cmd, err.Error(), nil, "Check the path; it's read from "+workingDir()) + } + if !utf8.ValidString(text) || strings.ContainsRune(text, 0) { + base := filepath.Base(path) + return refuse(cmd, base+" isn't text, and a document's new text has to be", + []string{"--file replaces the text of a text or Markdown document."}, + "To replace a PDF or Word document, upload it again: `vf document create-text --file "+path+" --overwrite true`") + } + return flagutil.SetText(cmd, "content", text) +} + +// namesAFile reports whether value is one word that names a file here, and +// which. +func namesAFile(value string) (string, bool) { + word := strings.TrimSpace(value) + if word == "" || len(word) > 4096 || strings.ContainsAny(word, " \t\r\n") { + return "", false + } + path := word + if rest, ok := strings.CutPrefix(word, "~/"); ok { + if home, err := os.UserHomeDir(); err == nil { + path = filepath.Join(home, rest) + } + } + info, err := os.Stat(path) + if err != nil || !info.Mode().IsRegular() { + return "", false + } + return path, true +} + +// asks is whether a person can answer a question: stdin and stderr are a +// terminal, agent mode is off, and --no-interactive isn't set. +func asks(cmd *cobra.Command) bool { + if off, _ := flagutil.GetBoolFlag(cmd, "no-interactive"); off { + return false + } + return !output.IsAgentMode() && atTerminal() +} + +// refuse reports a usage error before anything is sent, exit 2. +func refuse(cmd *cobra.Command, message string, why []string, next ...string) error { + return output.Report(cmd, output.Explanation{Type: "invalid_flag_value", Title: message, Why: why, Next: next}, errors.New(message)) +} + +func workingDir() string { + if dir, err := os.Getwd(); err == nil { + return dir + } + return "the current folder" +} diff --git a/internal/cli/document/contentfile_test.go b/internal/cli/document/contentfile_test.go new file mode 100644 index 00000000..b69d6963 --- /dev/null +++ b/internal/cli/document/contentfile_test.go @@ -0,0 +1,67 @@ +// This file is not generated by Speakeasy. It covers the question +// contentfile.go asks at a terminal, which the cli tests can't reach. + +package document + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// atTerminalAnswering makes vf be at a terminal, where the question is +// answered yes, and records what it asked. +func atTerminalAnswering(t *testing.T, yes bool) (asked *string) { + t.Helper() + asked = new(string) + wasAsk, wasAt := askYesNo, atTerminal + askYesNo = func(_ context.Context, title, _ string) (bool, error) { *asked = title; return yes, nil } + atTerminal = func() bool { return true } + t.Cleanup(func() { askYesNo, atTerminal = wasAsk, wasAt }) + return asked +} + +func updateCommand(t *testing.T, content string) *cobra.Command { + t.Helper() + cmd := &cobra.Command{Use: "update"} + cmd.Flags().String("content", "", "") + addContentFile(cmd) + cmd.SetErr(&bytes.Buffer{}) + if err := cmd.Flags().Set("content", content); err != nil { + t.Fatal(err) + } + return cmd +} + +func TestAtATerminalAPathAsTheTextAsksFirst(t *testing.T) { + dir := t.TempDir() + file := filepath.Join(dir, "refunds.md") + if err := os.WriteFile(file, []byte("Refunds take 7 business days.\n"), 0o600); err != nil { + t.Fatal(err) + } + + asked := atTerminalAnswering(t, true) + cmd := updateCommand(t, file) + if err := contentFromFile(cmd); err != nil { + t.Fatal(err) + } + if *asked != "Send the text of the file "+file+"?" { + t.Errorf("asked %q", *asked) + } + if got, _ := flagutil.GetStringFlag(cmd, "content"); got != "Refunds take 7 business days.\n" { + t.Errorf("Yes should send the file's text, got %q", got) + } + + atTerminalAnswering(t, false) + cmd = updateCommand(t, file) + if err := contentFromFile(cmd); !errors.Is(err, context.Canceled) { + t.Errorf("No should send nothing, got %v", err) + } +} diff --git a/internal/cli/document/update.go b/internal/cli/document/update.go index 3457c621..ae3e17b1 100644 --- a/internal/cli/document/update.go +++ b/internal/cli/document/update.go @@ -34,7 +34,8 @@ func initUpdateCmd(parent *cobra.Command) error { RunE: runUpdateCmd, } flagutil.RegisterFlags(cmd, updateCmdMeta) - addWait(cmd) // docready.go: --wait waits until new text is processed + addWait(cmd) // docready.go: --wait waits until new text is processed + addContentFile(cmd) // contentfile.go: --file, and @file or - for --content if err := flagutil.ValidateMeta[operations.StableDocumentControllerUpdateV2Request](updateCmdMeta); err != nil { return fmt.Errorf("invalid metadata for update: %w", err) } @@ -53,6 +54,9 @@ func runUpdateCmd(cmd *cobra.Command, args []string) error { return err } } + if err := contentFromFile(cmd); err != nil { // contentfile.go: --file, or a --content that names a file + return err + } req, err := flagutil.BuildRequest[operations.StableDocumentControllerUpdateV2Request](cmd, updateCmdMeta, "Body", "body") if err != nil { return err diff --git a/internal/cli/playbook/create.go b/internal/cli/playbook/create.go index 1bd7d9ba..71accca4 100644 --- a/internal/cli/playbook/create.go +++ b/internal/cli/playbook/create.go @@ -42,6 +42,7 @@ func initCreateCmd(parent *cobra.Command) error { RunE: runCreateCmd, } flagutil.RegisterFlags(cmd, createCmdMeta) + flagutil.ReadsText(cmd, "instructions") // flagutil/textfile.go: @file and - read the text if err := flagutil.ValidateMeta[operations.StablePlaybookControllerCreateV2Request](createCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create: %w", err) } diff --git a/internal/cli/playbook/update.go b/internal/cli/playbook/update.go index f3358c9f..efff0777 100644 --- a/internal/cli/playbook/update.go +++ b/internal/cli/playbook/update.go @@ -43,6 +43,7 @@ func initUpdateCmd(parent *cobra.Command) error { RunE: runUpdateCmd, } flagutil.RegisterFlags(cmd, updateCmdMeta) + flagutil.ReadsText(cmd, "instructions") // flagutil/textfile.go: @file and - read the text if err := flagutil.ValidateMeta[operations.StablePlaybookControllerUpdateV2Request](updateCmdMeta); err != nil { return fmt.Errorf("invalid metadata for update: %w", err) } diff --git a/internal/flagutil/textfile.go b/internal/flagutil/textfile.go new file mode 100644 index 00000000..49ca8bce --- /dev/null +++ b/internal/flagutil/textfile.go @@ -0,0 +1,135 @@ +// This file is not generated by Speakeasy. It lets a long text flag read its +// text from a file or from stdin: --prompt @prompt.md, or --prompt -. +// +// `vf agent update --prompt` and `--instructions`, `vf playbook create` and +// `update --instructions`, and `vf document update --content` took only the +// text itself. A prompt kept in a file had to go in as "$(cat prompt.md)", or +// into a --body built with jq --rawfile, as the round-4 sweep's agent-ci +// tester did, and a path typed as the value became the text. +// +// ReadsText makes a command's named flags take @path for the file's text and +// - 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 @. + +package flagutil + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// textHelp is what a flag that reads text says about it. +const textHelp = "@file reads the text from a file, and - from stdin." + +// textValue is a flag's value that reads @path and - before it is set. +type textValue struct { + pflag.Value + cmd *cobra.Command + name string +} + +func (v *textValue) Set(s string) error { + text, err := readText(v.cmd, v.name, s) + if err != nil { + return err + } + return v.Value.Set(text) +} + +// 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) { + for _, name := range names { + f := cmd.Flags().Lookup(name) + if f == nil { + continue + } + if _, done := f.Value.(*textValue); done { + continue + } + f.Value = &textValue{Value: f.Value, cmd: cmd, name: name} + if strings.TrimSpace(f.Usage) == "" { + f.Usage = "The text itself, @file to read it from a file, or - to read it from stdin." + } else { + f.Usage = strings.TrimSpace(f.Usage) + " " + textHelp + } + } +} + +// SetText sets flag name of cmd to text as it is, without reading a file or +// stdin even if text starts with @ or is -, and marks it given. +func SetText(cmd *cobra.Command, name, text string) error { + f := cmd.Flags().Lookup(name) + if f == nil { + return fmt.Errorf("no flag --%s", name) + } + tv, ok := f.Value.(*textValue) + if !ok { + return cmd.Flags().Set(name, text) + } + if err := tv.Value.Set(text); err != nil { + return err + } + f.Changed = true + return nil +} + +// readText is the text value stands for: a file's for @path, stdin's for -, +// and value itself otherwise, less one @ for @@. +func readText(cmd *cobra.Command, name, value string) (string, error) { + switch { + case value == "-": + return textFromStdin(cmd, name) + case strings.HasPrefix(value, "@@"): + return value[1:], nil + case strings.HasPrefix(value, "@") && len(value) > 1: + return ReadTextFile(value[1:], "--"+name) + } + return value, 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) { + if rest, ok := strings.CutPrefix(path, "~/"); ok { + if home, err := os.UserHomeDir(); err == nil { + path = filepath.Join(home, rest) + } + } + info, err := os.Stat(path) + switch { + case errors.Is(err, os.ErrNotExist): + return "", fmt.Errorf("there is no file %s to read for %s; to give text that starts with @, write @@", path, what) + case err != nil: + return "", fmt.Errorf("can't read %s for %s: %w", path, what, err) + case info.IsDir(): + return "", fmt.Errorf("%s is a folder; %s reads a file", path, what) + } + data, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("can't read %s for %s: %w", path, what, err) + } + return string(data), nil +} + +// 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) + } + data, err := readStdinBounded(cmd.InOrStdin(), 0) + if err != nil { + return "", fmt.Errorf("failed to read stdin for --%s -: %w", name, err) + } + if len(data) == 0 { + return "", fmt.Errorf("%w, and --%s - reads the text from it", ErrStdinEmpty, name) + } + return string(data), nil +} diff --git a/internal/flagutil/textfile_test.go b/internal/flagutil/textfile_test.go new file mode 100644 index 00000000..343cf50e --- /dev/null +++ b/internal/flagutil/textfile_test.go @@ -0,0 +1,81 @@ +// This file is not generated by Speakeasy. It covers textfile.go: a long text +// flag takes @file and -. + +package flagutil + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +func textCommand(stdin string) *cobra.Command { + cmd := &cobra.Command{Use: "update"} + cmd.Flags().String("prompt", "", "") + cmd.Flags().String("name", "", "The name.") + cmd.SetIn(strings.NewReader(stdin)) + ReadsText(cmd, "prompt", "name", "missing") + return cmd +} + +func TestATextFlagReadsAFileOrStdin(t *testing.T) { + dir := t.TempDir() + file := filepath.Join(dir, "prompt.md") + if err := os.WriteFile(file, []byte("# Role\nYou help.\n"), 0o600); err != nil { + t.Fatal(err) + } + cases := []struct{ value, stdin, want string }{ + {"@" + file, "", "# Role\nYou help.\n"}, + {"-", "piped\n", "piped\n"}, + {"@@everyone", "", "@everyone"}, + {"@", "", "@"}, + {"plain text", "", "plain text"}, + } + for _, c := range cases { + cmd := textCommand(c.stdin) + if err := cmd.Flags().Set("prompt", c.value); err != nil { + t.Fatalf("%q: %v", c.value, err) + } + if got, changed := GetStringFlag(cmd, "prompt"); got != c.want || !changed { + t.Errorf("%q: got %q (changed %v), want %q", c.value, got, changed, c.want) + } + } +} + +func TestATextFlagSaysWhatItCouldntRead(t *testing.T) { + dir := t.TempDir() + for value, want := range map[string]string{ + "@" + filepath.Join(dir, "nope.md"): "there is no file", + "@" + dir: "is a folder", + "-": "stdin was empty", + } { + err := textCommand("").Flags().Set("prompt", value) + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%q: got %v, want it to say %q", value, err, want) + } + } +} + +func TestATextFlagSaysItReadsFiles(t *testing.T) { + cmd := textCommand("") + if got := cmd.Flags().Lookup("prompt").Usage; !strings.Contains(got, "@file") { + t.Errorf("an empty help should say what the flag takes, got %q", got) + } + if got := cmd.Flags().Lookup("name").Usage; !strings.HasPrefix(got, "The name. ") || !strings.Contains(got, "@file") { + t.Errorf("a help should keep its text and add @file, got %q", got) + } +} + +// SetText sets the text as it is: a file's own text may start with @. +func TestSetTextDoesntReadAgain(t *testing.T) { + cmd := textCommand("") + if err := SetText(cmd, "prompt", "@not-a-file"); err != nil { + t.Fatal(err) + } + if got, changed := GetStringFlag(cmd, "prompt"); got != "@not-a-file" || !changed { + t.Errorf("got %q (changed %v)", got, changed) + } +} From ba1bc8328bbc9972ae5eae5840e096fe3d82fbfd Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:39:59 -0500 Subject: [PATCH 16/28] fix(document): a table's rows can come from a CSV file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `document create-table` took its rows only as JSON in --items, so a table kept in a spreadsheet had to be rewritten by hand as [{"plan":"Pro","price":"$20"},…], and a file name typed into --items was "not valid JSON", with no word of another way. --csv plans.csv reads the rows instead: the header row gives the keys, and each row after it becomes an item, its values kept as text. A .tsv file is read as tab-separated, by its extension. Excel's BOM and the empty rows below a table are skipped. Without --schema every column is searchable; --schema still chooses. An empty file, a header with a blank or repeated name, a row of the wrong length, a file that isn't UTF-8 (an .xlsx) and --csv with --items are refused with exit 2 and the reason, before anything is sent. --csv stands in for --items, so help and the missing-flag error offer it, and an --items that names a CSV file points at --csv. --csv rather than --items @rows.csv: help examples are parsed as they are written, and a flag that read its file as it was set would fail there; --csv also shows up in help's flag list and in --usage. A file that isn't there no longer tells --file and --csv to write @@, which only means something to a flag that takes text. Found by the round-4 sweep's human-kb tester. --- internal/cli/document/createtable.go | 6 +- internal/cli/document/tablecsv.go | 172 +++++++++++++++++++++++++++ internal/cli/tablecsv_test.go | 159 +++++++++++++++++++++++++ internal/flagutil/textfile.go | 14 ++- internal/flagutil/textfile_test.go | 2 +- 5 files changed, 349 insertions(+), 4 deletions(-) create mode 100644 internal/cli/document/tablecsv.go create mode 100644 internal/cli/tablecsv_test.go diff --git a/internal/cli/document/createtable.go b/internal/cli/document/createtable.go index e5c62317..46444a55 100644 --- a/internal/cli/document/createtable.go +++ b/internal/cli/document/createtable.go @@ -45,7 +45,8 @@ func initCreateTableCmd(parent *cobra.Command) error { Aliases: []string{"ct"}, } flagutil.RegisterFlags(cmd, createTableCmdMeta) - addWait(cmd) // docready.go: --wait waits until the document is processed + addWait(cmd) // docready.go: --wait waits until the document is processed + addTableCSV(cmd) // tablecsv.go: --csv reads the rows from a CSV file if err := flagutil.ValidateMeta[operations.StableDocumentControllerCreateTableRequest](createTableCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create-table: %w", err) } @@ -59,6 +60,9 @@ func runCreateTableCmd(cmd *cobra.Command, args []string) error { if usage.UsageRequested(cmd) { return usage.EmitSchema(cmd, cmd.OutOrStdout()) } + if err := itemsFromCSV(cmd); err != nil { // tablecsv.go: --csv gives --items, and --schema unless it is given + return err + } if interactive.ShouldPrompt(cmd, createTableCmdMeta) { if err := interactive.PromptAndSetFlags(cmd, createTableCmdMeta); err != nil { return err diff --git a/internal/cli/document/tablecsv.go b/internal/cli/document/tablecsv.go new file mode 100644 index 00000000..d84a089a --- /dev/null +++ b/internal/cli/document/tablecsv.go @@ -0,0 +1,172 @@ +// This file is not generated by Speakeasy. It lets `vf document +// create-table` read the table's rows from a CSV file. +// +// --items takes the rows only as JSON, so a table kept in a spreadsheet had +// to be rewritten by hand as [{"plan":"Pro","price":"$20"},…] before it could +// be added, and a file name typed into --items was "not valid JSON". +// +// --csv plans.csv reads them instead: the header row gives the keys, and +// each row after it becomes an item, its values kept as text. A .tsv file is +// read as tab-separated. Without --schema every column is searchable, the +// one schema that needs no knowledge of the file; --schema still chooses. +// --csv stands in for --items (flagutil/standin.go), so help and the +// missing-flag error offer it, and an --items that names a CSV file points +// at it. +// +// Hooked in by two lines in createtable.go; internal/cli/tablecsv_test.go +// covers them. + +package document + +import ( + "encoding/csv" + "encoding/json" + "errors" + "fmt" + "io" + "path/filepath" + "slices" + "strings" + "unicode/utf8" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/usage" +) + +const csvFlag = "csv" + +// csvHint says what --csv reads, for an error about a file it couldn't. +const csvHint = "--csv reads a header row of column names, then one row per item, separated by commas (tabs in a .tsv file), as a spreadsheet's Save as CSV UTF-8 writes it" + +// addTableCSV gives `document create-table` --csv. +func addTableCSV(cmd *cobra.Command) { + cmd.Flags().String(csvFlag, "", "A CSV file of the table's rows, in place of --items: its header row gives the keys, and each row after it becomes an item. A .tsv file is read as tab-separated. Without --schema, every column is searchable.") + flagutil.StandIn(cmd, csvFlag, "items") + usage.AddFlags("document create-table", usage.UsageFlag{Spec: "--" + csvFlag + " ", Help: cmd.Flags().Lookup(csvFlag).Usage}) + cmd.Example += "\n vf document create-table --project-id --environment-alias --name Plans --csv plans.csv" +} + +// itemsFromCSV sets --items from the --csv file, and --schema unless it is +// given, before anything asks for them. +func itemsFromCSV(cmd *cobra.Command) error { + path, given := flagutil.GetStringFlag(cmd, csvFlag) + if !given { + return itemsNameACSV(cmd) + } + if flagutil.FlagChanged(cmd, "items") { + return refuse(cmd, "--csv and --items both give the table's rows", nil, + "Pass one of them: --csv reads a CSV file, --items takes the rows as JSON") + } + text, err := flagutil.ReadTextFile(path, "--"+csvFlag) + if err != nil { + return refuse(cmd, err.Error(), nil, "Check the path; it's read from "+workingDir()) + } + columns, rows, err := readTable(text, filepath.Base(path)) + if err != nil { + return refuse(cmd, err.Error(), nil, csvHint) + } + items, err := json.Marshal(rows) + if err != nil { + return err + } + if err := cmd.Flags().Set("items", string(items)); err != nil { + return err + } + if flagutil.FlagChanged(cmd, "schema") { + return nil + } + schema, err := json.Marshal(map[string][]string{"searchableFields": columns}) + if err != nil { + return err + } + return cmd.Flags().Set("schema", string(schema)) +} + +// itemsNameACSV stops an --items that names a CSV file, which isn't JSON, +// with a pointer to --csv. +func itemsNameACSV(cmd *cobra.Command) error { + items, given := flagutil.GetStringFlag(cmd, "items") + if !given || json.Valid([]byte(items)) { + return nil + } + file, ok := namesAFile(items) + if !ok || !isTable(file) { + return nil + } + return refuse(cmd, "--items takes the rows as JSON, and "+items+" names a file", nil, + "Read the file's rows with --csv: `--csv "+items+"`") +} + +func isTable(path string) bool { + return slices.Contains([]string{".csv", ".tsv"}, strings.ToLower(filepath.Ext(path))) +} + +// readTable is text's column names and its rows, each a map of the row's +// values by column. A .tsv name is tab-separated. Rows of empty values are +// left out, as spreadsheets write them below a table. +func readTable(text, name string) ([]string, []map[string]any, error) { + kind, comma := "CSV", ',' + if strings.EqualFold(filepath.Ext(name), ".tsv") { + kind, comma = "TSV", '\t' + } + if !utf8.ValidString(text) || strings.ContainsRune(text, 0) { + return nil, nil, fmt.Errorf("%s isn't %s text: it isn't UTF-8", name, kind) + } + r := csv.NewReader(strings.NewReader(strings.TrimPrefix(text, "\ufeff"))) // Excel starts a CSV UTF-8 file with a BOM + r.Comma = comma + r.FieldsPerRecord = -1 // rows of the wrong length are explained below + header, err := r.Read() + if errors.Is(err, io.EOF) { + return nil, nil, fmt.Errorf("%s is empty", name) + } + if err != nil { + return nil, nil, fmt.Errorf("%s isn't valid %s: %w", name, kind, err) + } + columns := make([]string, len(header)) + for i, h := range header { + h = strings.TrimSpace(h) + switch { + case h == "": + return nil, nil, fmt.Errorf("column %d of %s's header row has no name, and each column's name is its key", i+1, name) + case slices.Contains(columns[:i], h): + return nil, nil, fmt.Errorf("%s's header row names %s twice, and each column's name is its key", name, h) + } + columns[i] = h + } + var rows []map[string]any + for { + record, err := r.Read() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return nil, nil, fmt.Errorf("%s isn't valid %s: %w", name, kind, err) + } + if !slices.ContainsFunc(record, func(v string) bool { return strings.TrimSpace(v) != "" }) { + continue + } + if len(record) != len(columns) { + line, _ := r.FieldPos(0) + return nil, nil, fmt.Errorf("line %d of %s has %s, and its header row %s", line, name, count(len(record), "value"), count(len(columns), "column")) + } + row := make(map[string]any, len(columns)) + for i, column := range columns { + row[column] = record[i] + } + rows = append(rows, row) + } + if len(rows) == 0 { + return nil, nil, fmt.Errorf("%s has a header row and no rows under it", name) + } + return columns, rows, nil +} + +// count is n things: 1 value, 3 values. +func count(n int, thing string) string { + if n == 1 { + return "1 " + thing + } + return fmt.Sprintf("%d %ss", n, thing) +} diff --git a/internal/cli/tablecsv_test.go b/internal/cli/tablecsv_test.go new file mode 100644 index 00000000..c7b30f00 --- /dev/null +++ b/internal/cli/tablecsv_test.go @@ -0,0 +1,159 @@ +// This file is not generated by Speakeasy. It covers document/tablecsv.go: +// `vf document create-table --csv` reads the table's rows from a CSV file. + +package cli + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "sync" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// tableServer creates a table document, and keeps each body it was sent. +func tableServer(t *testing.T) (url string, bodies func() []string) { + t.Helper() + var mu sync.Mutex + var seen []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + mu.Lock() + seen = append(seen, string(body)) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + io.WriteString(w, `{"document":{"id":"d1","data":{"type":"table","name":"Plans","canEdit":true},"status":{"type":"PENDING"},"smartChunking":{"llmBasedChunks":false},"folderID":null}}`) + })) + t.Cleanup(srv.Close) + return srv.URL, func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), seen...) + } +} + +// inTableFolder makes a folder with files, by name, the working directory. +func inTableFolder(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) +} + +var createTable = []string{"create-table", "-p", "p1", "-e", "main", "--name", "Plans"} + +// The header row gives each item's keys, each row after it is an item, and +// without --schema every column is searchable. +func TestATableComesFromACSVFile(t *testing.T) { + inTableFolder(t, map[string]string{ + // As Excel saves CSV UTF-8: a BOM, a quoted comma, CRLF and an empty row below. + "plans.csv": "\ufeffplan,price,includes\r\nStarter,$0,\"1 agent, 100 calls\"\r\nPro,$20,Unlimited agents\r\n,,\r\n", + "plans.tsv": "plan\tprice\nPro\t$20\n", + }) + type body struct { + Name string `json:"name"` + Items []map[string]any `json:"items"` + Schema map[string][]string `json:"schema"` + } + cases := []struct { + flags []string + want body + }{ + {[]string{"--csv", "plans.csv"}, body{ + Name: "Plans", + Items: []map[string]any{ + {"plan": "Starter", "price": "$0", "includes": "1 agent, 100 calls"}, + {"plan": "Pro", "price": "$20", "includes": "Unlimited agents"}, + }, + Schema: map[string][]string{"searchableFields": {"plan", "price", "includes"}}, + }}, + {[]string{"--schema", `{"searchableFields":["plan"],"metadataFields":["price"]}`, "--csv", "plans.tsv"}, body{ + Name: "Plans", + Items: []map[string]any{{"plan": "Pro", "price": "$20"}}, + Schema: map[string][]string{"searchableFields": {"plan"}, "metadataFields": {"price"}}, + }}, + } + for _, c := range cases { + url, bodies := tableServer(t) + _, stderr, err := runDocument(t, url, false, append(createTable, c.flags...)...) + if err != nil { + t.Fatalf("%v: %v\n%s", c.flags, err, stderr) + } + sent := bodies() + if len(sent) != 1 { + t.Fatalf("%v: sent %d requests", c.flags, len(sent)) + } + var got body + if err := json.Unmarshal([]byte(sent[0]), &got); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, c.want) { + t.Errorf("%v: sent %s\nwant %+v", c.flags, sent[0], c.want) + } + } +} + +// A file that isn't a table of rows is refused with exit 2 and a reason, and +// nothing is sent. +func TestACSVThatIsntATableIsRefused(t *testing.T) { + inTableFolder(t, map[string]string{ + "plans.csv": "plan,price\nPro,$20\n", + "ragged.csv": "plan,price\nPro\n", + "twice.csv": "plan,Plan,plan\nPro,x,y\n", + "noname.csv": "plan,\nPro,$20\n", + "header.csv": "plan,price\n", + "empty.csv": "", + "quote.csv": "plan\n\"Pro\n", + "plans.xlsx": "PK\x03\x04\xff\xfe\x00\x00", + "latin1.csv": "plan\nCaf\xe9\n", + }) + if err := os.Mkdir("sheets", 0o755); err != nil { + t.Fatal(err) + } + cases := []struct { + flags []string + want string + }{ + {[]string{"--csv", "ragged.csv"}, "line 2 of ragged.csv has 1 value, and its header row 2 columns"}, + {[]string{"--csv", "twice.csv"}, "twice.csv's header row names plan twice"}, + {[]string{"--csv", "noname.csv"}, "column 2 of noname.csv's header row has no name"}, + {[]string{"--csv", "header.csv"}, "header.csv has a header row and no rows under it"}, + {[]string{"--csv", "empty.csv"}, "empty.csv is empty"}, + {[]string{"--csv", "quote.csv"}, "quote.csv isn't valid CSV"}, + {[]string{"--csv", "plans.xlsx"}, "plans.xlsx isn't CSV text: it isn't UTF-8"}, + {[]string{"--csv", "latin1.csv"}, "latin1.csv isn't CSV text: it isn't UTF-8"}, + {[]string{"--csv", "missing.csv"}, "there is no file missing.csv to read for --csv"}, + {[]string{"--csv", "sheets"}, "sheets is a folder"}, + {[]string{"--csv", "plans.csv", "--items", `[{"plan":"Pro"}]`}, "--csv and --items both give the table's rows"}, + // A file name typed as --items, which takes JSON, points at --csv. + {[]string{"--items", "plans.csv", "--schema", `{"searchableFields":["plan"]}`}, "--csv plans.csv"}, + } + for _, c := range cases { + url, bodies := tableServer(t) + _, stderr, err := runDocument(t, url, false, append(createTable, c.flags...)...) + if code := output.ExitCode(err); code != output.ExitUsage { + t.Errorf("%v: exit %d, want %d\n%s", c.flags, code, output.ExitUsage, stderr) + } + if !strings.Contains(stderr, c.want) { + t.Errorf("%v: want %q in:\n%s", c.flags, c.want, stderr) + } + if strings.Contains(stderr, "@@") { + t.Errorf("%v: --csv takes a path, not text, so @@ means nothing to it:\n%s", c.flags, stderr) + } + if sent := bodies(); len(sent) != 0 { + t.Errorf("%v: nothing should be sent, got %v", c.flags, sent) + } + } +} diff --git a/internal/flagutil/textfile.go b/internal/flagutil/textfile.go index 49ca8bce..cbc2f3b3 100644 --- a/internal/flagutil/textfile.go +++ b/internal/flagutil/textfile.go @@ -90,7 +90,11 @@ func readText(cmd *cobra.Command, name, value string) (string, error) { case strings.HasPrefix(value, "@@"): return value[1:], nil case strings.HasPrefix(value, "@") && len(value) > 1: - return ReadTextFile(value[1:], "--"+name) + text, err := ReadTextFile(value[1:], "--"+name) + if errors.Is(err, os.ErrNotExist) { + return "", fmt.Errorf("%w; to give text that starts with @, write @@", err) + } + return text, err } return value, nil } @@ -106,7 +110,7 @@ func ReadTextFile(path, what string) (string, error) { info, err := os.Stat(path) switch { case errors.Is(err, os.ErrNotExist): - return "", fmt.Errorf("there is no file %s to read for %s; to give text that starts with @, write @@", path, what) + return "", noFile(fmt.Sprintf("there is no file %s to read for %s", path, what)) case err != nil: return "", fmt.Errorf("can't read %s for %s: %w", path, what, err) case info.IsDir(): @@ -119,6 +123,12 @@ func ReadTextFile(path, what string) (string, error) { return string(data), nil } +// noFile says there is no file to read; it is an os.ErrNotExist. +type noFile string + +func (e noFile) Error() string { return string(e) } +func (e noFile) Is(target error) bool { return target == os.ErrNotExist } + // textFromStdin reads the text piped in for --name -. func textFromStdin(cmd *cobra.Command, name string) (string, error) { if !HasStdinInput(cmd) { diff --git a/internal/flagutil/textfile_test.go b/internal/flagutil/textfile_test.go index 343cf50e..7d888730 100644 --- a/internal/flagutil/textfile_test.go +++ b/internal/flagutil/textfile_test.go @@ -48,7 +48,7 @@ func TestATextFlagReadsAFileOrStdin(t *testing.T) { func TestATextFlagSaysWhatItCouldntRead(t *testing.T) { dir := t.TempDir() for value, want := range map[string]string{ - "@" + filepath.Join(dir, "nope.md"): "there is no file", + "@" + filepath.Join(dir, "nope.md"): "nope.md to read for --prompt; to give text that starts with @, write @@", "@" + dir: "is a folder", "-": "stdin was empty", } { From 9706e2656059b12b0a8b0f2decd0e19dd6616d63 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:43:13 -0500 Subject: [PATCH 17/28] fix(document): a name that's taken points at --overwrite true A second `document create-text` of the same file came back 409 "file already exists", and vf's hints said "Use a different name, or change the one that exists". The fix was --overwrite true, which replaces the document in place, and nothing said so; the flag's help reads only "true or false", and its meaning was in --folder-id's. A 409 about a name on a document create that takes --overwrite and wasn't given it true now says the knowledge base already has a document with this name (this URL, for create-url), and "Add `--overwrite true` to replace it: it keeps its ID, and is processed again", then the list command. A conflict that isn't about the name, or a create already given --overwrite true, keeps the hints it had. Found by the round-4 sweep's agent-migrator and agent-ci testers. --- internal/output/doctype.go | 38 +++++++++++++++++++++++++--- internal/output/doctype_test.go | 44 +++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 3 deletions(-) diff --git a/internal/output/doctype.go b/internal/output/doctype.go index 1e0f113a..dae7f2dd 100644 --- a/internal/output/doctype.go +++ b/internal/output/doctype.go @@ -1,11 +1,16 @@ -// This file is not generated by Speakeasy. It explains a file the knowledge -// base won't take. +// This file is not generated by Speakeasy. It explains a document the +// knowledge base won't take: a file of a type it doesn't, or a name it has. // // `vf document create-text --file notes.rtf` came back "invalid document type" // with only the generic hints (--dry-run, --help), and nothing said that the // extension was the problem: vf labels an uploaded file by its extension, and // the knowledge base takes .txt, .md, .pdf and .docx files. A .md file failed // the same way until client/uploadtypes.go. +// +// And a second create of the same file came back 409 "file already exists", +// 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". package output @@ -19,8 +24,12 @@ import ( // documentTypes are the file types the knowledge base takes. const documentTypes = ".txt, .md, .pdf or .docx" -// explainDocumentType recognizes the API refusing an uploaded file's type. +// 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 := duplicateDocument(cmd, status, message); ok { + return why, next, true + } if status != 400 || !strings.Contains(strings.ToLower(message), "invalid document type") { return nil, nil, false } @@ -32,3 +41,26 @@ func explainDocumentType(cmd *cobra.Command, status int, message string) (why, n next = []string{"Save it as " + documentTypes + ", converting it if need be, then run it again"} 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. +func duplicateDocument(cmd *cobra.Command, status int, message string) (why, next []string, ok bool) { + if status != 409 || cmd == nil || !conflictIsAboutAName(message) { + return nil, nil, false + } + f := cmd.Flags().Lookup("overwrite") + if f == nil || strings.EqualFold(f.Value.String(), "true") { + return nil, nil, false + } + what := "name" + if cmd.Name() == "create-url" { + what = "URL" + } + why = []string{"The knowledge base already has a document with this " + what + ". Names and URLs are unique across the whole knowledge base, not per folder."} + next = []string{"Add `--overwrite true` to replace it: it keeps its ID, and is processed again"} + if list := listCommand(cmd); list != "" { + next = append(next, "`"+withScope(cmd, list)+"` shows what's there") + } + return why, next, true +} diff --git a/internal/output/doctype_test.go b/internal/output/doctype_test.go index 00f97523..2583c61a 100644 --- a/internal/output/doctype_test.go +++ b/internal/output/doctype_test.go @@ -29,3 +29,47 @@ func TestAnUnacceptedFileTypeIsExplained(t *testing.T) { t.Errorf("the generic hints don't help here:\n%s", got) } } + +// A create of a document whose name is taken says --overwrite true replaces +// it, unless it was given, or the command has no --overwrite. +func TestADuplicateDocumentSaysOverwriteReplacesIt(t *testing.T) { + withCredential(t, Credential{Kind: CredentialSession}) + command := func(name string, overwrite bool) *cobra.Command { + parent := &cobra.Command{Use: "document"} + cmd := &cobra.Command{Use: name, Run: func(*cobra.Command, []string) {}} + if overwrite { + cmd.Flags().String("overwrite", "", "") + } + parent.AddCommand(cmd, &cobra.Command{Use: "list", Run: func(*cobra.Command, []string) {}}) + return cmd + } + body := `{"message":"file already exists","code":409}` + explain := func(cmd *cobra.Command) string { + return joined(explainWith(cmd, apiError(409, body, nil), 409, body, noLookup)) + } + + for name, what := range map[string]string{"create-text": "this name", "create-table": "this name", "create-url": "this URL"} { + got := explain(command(name, true)) + for _, want := range []string{"already has a document with " + what, "Add `--overwrite true` to replace it", "`document list` shows what's there"} { + if !strings.Contains(got, want) { + t.Errorf("%s: missing %q in:\n%s", name, want, got) + } + } + if strings.Contains(got, "Use a different name") { + t.Errorf("%s: --overwrite is the way, not a new name:\n%s", name, got) + } + } + + given := command("create-text", true) + _ = given.Flags().Set("overwrite", "true") + if got := explain(given); strings.Contains(got, "--overwrite") { + t.Errorf("--overwrite true was given, so it can't be the fix:\n%s", got) + } + if got := explain(command("create", false)); strings.Contains(got, "--overwrite") { + t.Errorf("a command without --overwrite can't be told to use it:\n%s", got) + } + other := `{"message":"document is being processed","code":409}` + if got := joined(explainWith(command("create-text", true), apiError(409, other, nil), 409, other, noLookup)); strings.Contains(got, "--overwrite") { + t.Errorf("a conflict that isn't about the name isn't fixed by --overwrite:\n%s", got) + } +} From cbdedd813c0e518c0778985ea7e2ff8015d80d15 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:45:41 -0500 Subject: [PATCH 18/28] fix(document): create-text says it uploads a file `vf document create-text` was described as "Create a new document from raw text.", the API's summary, at the top of its help and its form, while its one required field is a file path. A newcomer with no file at hand canceled there, and a knowledge-base writer read "raw text" as a typed note, when it is how a Markdown or PDF file gets in. Its summary is now "Upload a file as a document", and its help says it uploads a text, Markdown, PDF or Word file, that the file's name becomes the document's name, that --overwrite true replaces the document of that name, and that a web page goes through create-url and rows of data through create-table. The summary in the OpenAPI spec, docs/ and the --usage schema still say "raw text"; they come from the spec. Found by the round-4 sweep's human-newcomer and human-kb testers. --- internal/cli/createtexthelp_test.go | 33 +++++++++++++++++++++++++ internal/cli/document/createtext.go | 3 ++- internal/cli/document/createtexthelp.go | 24 ++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 internal/cli/createtexthelp_test.go create mode 100644 internal/cli/document/createtexthelp.go diff --git a/internal/cli/createtexthelp_test.go b/internal/cli/createtexthelp_test.go new file mode 100644 index 00000000..ef9b14a8 --- /dev/null +++ b/internal/cli/createtexthelp_test.go @@ -0,0 +1,33 @@ +// This file is not generated by Speakeasy. It covers +// document/createtexthelp.go: create-text says it uploads a file. + +package cli + +import ( + "strings" + "testing" +) + +func TestCreateTextSaysItUploadsAFile(t *testing.T) { + url, _ := documentServer(t, success) + help, _, err := runDocument(t, url, false, "create-text", "--help") + if err != nil { + t.Fatal(err) + } + if strings.Contains(help, "raw text") { + t.Errorf("create-text takes a file, not raw text:\n%s", help) + } + for _, want := range []string{"Upload a file to the knowledge base as a document", ".txt", ".md", ".pdf", ".docx", "--overwrite true replaces"} { + if !strings.Contains(help, want) { + t.Errorf("missing %q in:\n%s", want, help) + } + } + + list, _, err := runDocument(t, url, false, "--help") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(list, "Upload a file as a document") { + t.Errorf("the command list should say create-text uploads a file:\n%s", list) + } +} diff --git a/internal/cli/document/createtext.go b/internal/cli/document/createtext.go index 69829103..1bbb5cda 100644 --- a/internal/cli/document/createtext.go +++ b/internal/cli/document/createtext.go @@ -44,7 +44,8 @@ func initCreateTextCmd(parent *cobra.Command) error { Aliases: []string{"cte"}, } flagutil.RegisterFlags(cmd, createTextCmdMeta) - addWait(cmd) // docready.go: --wait waits until the document is processed + addWait(cmd) // docready.go: --wait waits until the document is processed + describeCreateText(cmd) // createtexthelp.go: it uploads a file, not raw text if err := flagutil.ValidateMeta[operations.StableDocumentControllerCreateTextRequest](createTextCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create-text: %w", err) } diff --git a/internal/cli/document/createtexthelp.go b/internal/cli/document/createtexthelp.go new file mode 100644 index 00000000..bd1afc3c --- /dev/null +++ b/internal/cli/document/createtexthelp.go @@ -0,0 +1,24 @@ +// This file is not generated by Speakeasy. It says what `vf document +// create-text` takes: a file. +// +// The API's summary, "Create a new document from raw text.", heads its help +// and its form, and the form's one field asks for a file path. In the +// usability sweep a newcomer with no file at hand canceled there, and a +// knowledge-base writer read "raw text" as a typed note, when it is the way +// to upload a Markdown or PDF file. +// +// Hooked in by a line in createtext.go; internal/cli/createtexthelp_test.go +// covers it. + +package document + +import "github.com/spf13/cobra" + +// describeCreateText makes create-text's summary and help say it uploads a +// file. +func describeCreateText(cmd *cobra.Command) { + cmd.Short = "Upload a file as a document" + cmd.Long = "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. " + + "To add a web page, use create-url; for rows of data, create-table." +} From 1ef08dab14cc1936724cf5ba28a0d16e7b77deea Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:26:23 -0500 Subject: [PATCH 19/28] fix(home): update and delete keep the current project and environment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the home prompt, `agent update`, `document update` and `document delete` ignored the project chosen with `use project`. Any command named update*, delete* and so on asked again for every ID it could list, so a document delete opened a list of every project in the workspace, two of them named like the one in use, then an environment list with one row. Picking the wrong lookalike would change another team's agent. A command now asks again only for the ID that names what it changes: the project of `project delete`, the environment of `environment publish`. That is the flag whose noun is the command's group. The project and environment a change happens in come from the context, or are taken without asking when there is only one, or the main one, as for any other command, and each says so ("Using project … the current one"). The menu's note for --project-id follows: "uses … (current)". `environment publish`, `merge` and `update-traffic-split` now take the current project too; their environment is still always asked. Found by the round-4 sweep's human-newcomer and human-kb testers (R4 #8). --- internal/interactive/pickers.go | 32 +++++++-- internal/interactive/pickers_test.go | 101 ++++++++++++++++++++++++--- 2 files changed, 115 insertions(+), 18 deletions(-) diff --git a/internal/interactive/pickers.go b/internal/interactive/pickers.go index 94ecc240..84fe9aa0 100644 --- a/internal/interactive/pickers.go +++ b/internal/interactive/pickers.go @@ -168,7 +168,7 @@ func (p *picking) resolve(flag string) (value string, ok bool, err error) { picker := pickers[flag] // The home prompt's current one, unless the command changes or removes // what it picks: then the list asks, with the current one first. - if cur, ok := session.Get(flag); ok && !(p.bound[flag] && changesWhatItPicks(p.cmd)) { + if cur, ok := session.Get(flag); ok && !p.changes(flag) { fmt.Fprintln(p.out, p.u.Status(ui.StatusDone, "Using "+describe(picker.Noun, cur)+", the current one")) return p.set(flag, cur.Value) } @@ -251,9 +251,9 @@ func (p *picking) pick(flag string, picker Picker, needs map[string]string) (str case len(choices) == 0: fmt.Fprintln(p.out, p.u.Status(ui.StatusWarn, "No "+picker.Plural+" found")) return p.typeID(flag, picker) - case len(choices) == 1 && !(p.bound[flag] && changesWhatItPicks(p.cmd)): + case len(choices) == 1 && !p.changes(flag): return p.take(flag, picker, choices[0], "the only one"), nil - case !(p.bound[flag] && changesWhatItPicks(p.cmd)): + case !p.changes(flag): for _, c := range choices { if c.Default { return p.take(flag, picker, c, picker.DefaultIs), nil @@ -364,7 +364,7 @@ func FillNote(cmd *cobra.Command, flag string) string { switch { case !ok: return "" - case changesWhatItPicks(cmd): + case changesWhatItPicks(cmd, flag): return list // always asked, the current one first } if cur, ok := session.Get(flag); ok { @@ -380,9 +380,27 @@ func FillNote(cmd *cobra.Command, flag string) string { return list } -// changesWhatItPicks is whether the command changes or removes what its -// flags name, so a lone choice is shown rather than taken. -func changesWhatItPicks(cmd *cobra.Command) bool { +// changes is whether the command changes or removes what flag names: the +// flag is the command's own, not one picked on the way to it. +func (p *picking) changes(flag string) bool { + return p.bound[flag] && changesWhatItPicks(p.cmd, flag) +} + +// changesWhatItPicks is whether cmd changes or removes what flag names, so +// the current one, or a lone choice, is shown rather than taken: the project +// of `project delete`, the environment of `environment publish`. +// +// A flag that says only where the change happens is filled as for any +// other command. `document delete` and `agent update` change a document and +// an agent, not the project or environment they are in, so those come from +// the home prompt's context. Asking again listed every project in the +// workspace, lookalike names and all, for a project already chosen, and +// then an environment list with one row in it. +func changesWhatItPicks(cmd *cobra.Command, flag string) bool { + picker, ok := pickers[flag] + if !ok || !cmd.HasParent() || cmd.Parent().Name() != picker.Noun { + return false // what cmd changes is named by its group: project, environment + } for _, verb := range []string{"delete", "remove", "publish", "merge", "disconnect", "unassign", "revoke", "cancel", "update", "replace"} { if strings.HasPrefix(cmd.Name(), verb) { return true diff --git a/internal/interactive/pickers_test.go b/internal/interactive/pickers_test.go index 2e865620..0c7ab03f 100644 --- a/internal/interactive/pickers_test.go +++ b/internal/interactive/pickers_test.go @@ -51,7 +51,8 @@ func (f *fakePicker) register(flag, noun string, needs ...string) *fakePicker { } // pickSession is a picking for a command named name with the given string flags, -// whose lists pick choose(title) and whose inputs type typed. +// whose lists pick choose(title) and whose inputs type typed. A name of two +// words is a command in a group: "project delete". type pickSession struct { *picking out *bytes.Buffer @@ -62,7 +63,7 @@ type pickSession struct { } func newSession(name string, flags ...string) *pickSession { - cmd := &cobra.Command{Use: name} + cmd := command(name) for _, f := range flags { cmd.Flags().String(f, "", "") } @@ -84,6 +85,16 @@ func newSession(name string, flags ...string) *pickSession { return s } +// command is a command named name, in its group when name has two words. +func command(name string) *cobra.Command { + words := strings.Fields(name) + cmd := &cobra.Command{Use: words[len(words)-1]} + if len(words) > 1 { + (&cobra.Command{Use: words[0]}).AddCommand(cmd) + } + return cmd +} + func fields(flags ...string) []fieldInfo { var out []fieldInfo for _, f := range flags { @@ -111,7 +122,7 @@ func TestPickersRunInTheOrderTheyNeed(t *testing.T) { projects := (&fakePicker{choices: []Choice{{Value: "p1", Name: "Bot A"}, {Value: "p2", Name: "Bot B"}}}).register("project-id", "project", "workspace-id") envs := (&fakePicker{choices: []Choice{{Value: "production", Name: "Production"}}}).register("environment-alias", "environment", "project-id") - s := newSession("publish", "environment-alias", "name", "project-id") + s := newSession("environment publish", "environment-alias", "name", "project-id") s.picks["Project"] = "p2" s.picks["Environment"] = "production" rest, err := s.fill(fields("environment-alias", "name", "project-id")) @@ -146,9 +157,26 @@ func TestALoneChoiceIsTakenWhenNothingChanges(t *testing.T) { if len(s.shown) != 0 || flag(s, "workspace-id") != "w1" { t.Errorf("one workspace and a list command: take it. shown %q, flag %q", s.shown, flag(s, "workspace-id")) } - for _, verb := range []string{"delete", "publish", "merge", "update-traffic-split"} { - if !changesWhatItPicks(&cobra.Command{Use: verb}) { - t.Errorf("%s should always show the list", verb) + (&fakePicker{}).register("project-id", "project") + (&fakePicker{}).register("environment-alias", "environment") + for _, c := range []struct { + cmd, flag string + changes bool + }{ + {"project delete", "project-id", true}, + {"workspace update", "workspace-id", true}, + {"environment publish", "environment-alias", true}, + {"environment update-traffic-split", "environment-alias", true}, + // Where the change happens isn't what it changes. + {"environment publish", "project-id", false}, + {"document delete", "project-id", false}, + {"document update", "environment-alias", false}, + {"agent update", "project-id", false}, + {"phone-number delete", "workspace-id", false}, + {"project get", "project-id", false}, + } { + if got := changesWhatItPicks(command(c.cmd), c.flag); got != c.changes { + t.Errorf("%s --%s: changes what it picks %v, want %v", c.cmd, c.flag, got, c.changes) } } } @@ -292,7 +320,7 @@ func TestDeletingAsksWithTheCurrentOneFirst(t *testing.T) { (&fakePicker{choices: []Choice{{Value: "p1", Name: "Bot A"}, {Value: "p2", Name: "Bot B"}}}).register("project-id", "project") session.Set("project-id", "p2", "Bot B") - s := newSession("delete", "project-id") + s := newSession("project delete", "project-id") var first string s.choose = func(title, _ string, options []huh.Option[string], value *string) error { s.shown = append(s.shown, title) @@ -307,6 +335,54 @@ func TestDeletingAsksWithTheCurrentOneFirst(t *testing.T) { } } +// Updating or deleting a document, or updating the agent, changes something +// in the current project, not the project: the current project and +// environment are used, and only a list for what it changes would ask. The +// prompt used to list every project in the workspace (two of them named like +// the one in use) and then an environment list with one row. +func TestUpdateAndDeleteUseTheCurrentProject(t *testing.T) { + isolatePicks(t) + session.Start() + t.Cleanup(session.Stop) + projects := (&fakePicker{choices: []Choice{{Value: "p1", Name: "Northwind"}, {Value: "p2", Name: "Northwind Coffee Support"}, {Value: "p3", Name: "Northwind Coffee Support"}}}).register("project-id", "project") + envs := (&fakePicker{choices: []Choice{{Value: "main", Name: "Main", Default: true}}}).register("environment-alias", "environment", "project-id") + pickers["environment-alias"] = Picker{Noun: "environment", Plural: "environments", Needs: []string{"project-id"}, DefaultIs: "the main one", List: pickers["environment-alias"].List} + session.Set("project-id", "p1", "Northwind") + + // The lone environment is taken and becomes current, so the commands + // after the first take it from the context. + env := "Using environment Main (main), the only one" + for _, name := range []string{"document delete", "document update", "agent update"} { + s := newSession(name, "project-id", "environment-alias", "document-id") + rest, err := s.fill(fields("document-id", "project-id", "environment-alias")) + if err != nil { + t.Fatal(err) + } + if len(s.shown) != 0 || flag(s, "project-id") != "p1" || flag(s, "environment-alias") != "main" { + t.Errorf("%s: shown %q, project %q, environment %q", name, s.shown, flag(s, "project-id"), flag(s, "environment-alias")) + } + if !reflect.DeepEqual(names(rest), []string{"document-id"}) { + t.Errorf("%s: the form should ask only for what it changes, got %q", name, names(rest)) + } + if out := s.out.String(); !strings.Contains(out, "Using project Northwind (p1), the current one") || !strings.Contains(out, env) { + t.Errorf("%s: should say %q, said %q", name, env, out) + } + env = "Using environment Main (main), the current one" + } + if len(projects.calls) != 0 || len(envs.calls) != 1 { + t.Errorf("projects listed %d times, environments %d", len(projects.calls), len(envs.calls)) + } + + // Deleting the environment itself still asks which, the current one first. + del := newSession("environment delete", "project-id", "environment-alias") + if _, err := del.fill(fields("project-id", "environment-alias")); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(del.shown, []string{"Environment"}) || flag(del, "project-id") != "p1" { + t.Errorf("environment delete: shown %q, project %q", del.shown, flag(del, "project-id")) + } +} + // `use project` picks a project to make current, even when one is. func TestPickCurrentPicksAgain(t *testing.T) { isolatePicks(t) @@ -375,7 +451,7 @@ func TestTheMainEnvironmentIsTheDefault(t *testing.T) { t.Errorf("a read takes the main environment: flag %q, shown %q, said %q", flag(read, "environment-alias"), read.shown, read.out.String()) } - publish := newSession("publish", "environment-alias") + publish := newSession("environment publish", "environment-alias") publish.picks["Environment"] = "staging" if _, err := publish.fill(fields("environment-alias")); err != nil { t.Fatal(err) @@ -392,7 +468,7 @@ func TestFillNoteSaysWhatFillsAFlag(t *testing.T) { t.Cleanup(session.Stop) (&fakePicker{}).register("project-id", "project") pickers["environment-alias"] = Picker{Noun: "environment", Plural: "environments", DefaultIs: "the main one"} - read, publish := &cobra.Command{Use: "read-instructions"}, &cobra.Command{Use: "publish"} + read, publish, del := command("agent read-instructions"), command("environment publish"), command("project delete") for _, c := range []struct { cmd *cobra.Command @@ -411,8 +487,11 @@ func TestFillNoteSaysWhatFillsAFlag(t *testing.T) { if got := FillNote(read, "project-id"); got != "uses Help bot (current)" { t.Errorf("the current project: %q", got) } - if got := FillNote(publish, "project-id"); got != "you pick it from a list" { - t.Errorf("publishing asks even with a current project, so it says so: %q", got) + if got := FillNote(publish, "project-id"); got != "uses Help bot (current)" { + t.Errorf("publishing changes an environment, not the project it is in: %q", got) + } + if got := FillNote(del, "project-id"); got != "you pick it from a list" { + t.Errorf("deleting a project asks which even with a current one, so it says so: %q", got) } } From bb5789e3b72fa3ec4a0312ea91e3fb57eca34d63 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:34:40 -0500 Subject: [PATCH 20/28] fix(home): Ctrl-C just after Enter cancels the line, not vf MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the home prompt, Ctrl-C pressed within about 20 ms of Enter ended vf, history and context with it: `^C`, then the shell (killed by SIGINT, exit -2). The prompt hands the terminal back when Enter is read, so Ctrl-C is a signal again, but a line caught it only once its command tree was built. A Ctrl-C in that gap found nothing listening. Ctrl-C is now caught from before the first prompt until the prompt closes. One pressed at any moment after Enter goes to that line and cancels it ("✗ Canceled"), and the prompt comes back; one pressed before the prompt shows is dropped, so it can't cancel the next line. A Ctrl-C read in the same burst as the Enter reaches the prompt as a key, and used to be lost while the line ran to the end: the line is now not run, says Canceled, and stays in history. `use project` can be canceled the same way while its list loads. Found by the round-4 sweep's human-poweruser and fix-verifier testers (R4 #9). --- internal/cli/home.go | 86 ++++++++++++---- internal/cli/home_interrupt_test.go | 147 ++++++++++++++++++++++++++++ internal/cli/home_test.go | 3 +- internal/prompt/prompt.go | 16 +++ internal/prompt/prompt_test.go | 21 ++++ 5 files changed, 253 insertions(+), 20 deletions(-) create mode 100644 internal/cli/home_interrupt_test.go diff --git a/internal/cli/home.go b/internal/cli/home.go index 1f99f744..3efcf0db 100644 --- a/internal/cli/home.go +++ b/internal/cli/home.go @@ -75,14 +75,21 @@ func runPrompt(cmd *cobra.Command, u *ui.UI, out io.Writer, state signIn) error complete := prompt.CommandsFilling(cmd.Root(), homeWords, interactive.FillNote) histFile := historyPath() history := loadHistory(histFile) // history.go: kept across sessions + ints := catchInterrupts() // before the first prompt gives the terminal back + defer ints.stop() for { placeholder := placeholderFor(state) fmt.Fprintln(out) - line, ok, err := prompt.Read(prompt.Options{ + ints.drop() // a Ctrl-C from before the prompt was for a line that has ended + line, ok, err := readLine(prompt.Options{ UI: u, In: os.Stdin, Out: out, Width: ui.TerminalWidth(out), Complete: complete, History: history, Placeholder: placeholder, Keys: homeKeys, Context: session.Label(), }) + canceled := errors.Is(err, prompt.ErrCanceled) // Ctrl-C came in with the Enter + if canceled { + err = nil + } if err != nil || !ok { return err } @@ -95,6 +102,11 @@ func runPrompt(cmd *cobra.Command, u *ui.UI, out io.Writer, state signIn) error if len(history) == 0 || history[len(history)-1] != kept { history = append(history, kept) } + if canceled { // kept for ↑, but not run + saveHistory(histFile, kept) + fmt.Fprintln(os.Stderr, u.Status(ui.StatusFailed, "Canceled")) + continue + } args, err := prompt.SplitArgs(line) if err != nil { @@ -122,20 +134,25 @@ func runPrompt(cmd *cobra.Command, u *ui.UI, out io.Writer, state signIn) error continue } saveHistory(histFile, kept) + ctx, done := ints.line() if args[0] == "use" { - use(cmd, u, args[1:]) - continue + use(ctx, cmd, u, args[1:]) + } else { + runLine(ctx, u, args) } - runLine(u, args) + done() state = signInState(cmd) // a line may have signed in or out } } +// readLine reads the prompt's next line; a var so tests can type it. +var readLine = prompt.Read + // runLine runs one line as its own vf invocation: a fresh command tree, with // the agent mode and config of the last line cleared, so no flag or setting // leaks from one line into the next. Errors print as main prints them, and -// help is the prompt's shorter help (prompt_help.go). -func runLine(u *ui.UI, args []string) { +// help is the prompt's shorter help (prompt_help.go). Ctrl-C cancels ctx. +func runLine(ctx context.Context, u *ui.UI, args []string) { output.ResetAgentMode() output.SetFold(foldLines()) // a result taller than the screen folds (output/fold.go) defer output.SetFold(0) @@ -152,8 +169,6 @@ func runLine(u *ui.UI, args []string) { } setPromptHelp(root, u) root.SetArgs(args) - ctx, stop := interruptible() - defer stop() if cmd, err := unknownSubcommand(root, args); err != nil { _ = renderError(cmd, err) return @@ -193,8 +208,8 @@ var useLevels = map[string]string{ } // use shows the current workspace and project, picks a new one, or clears -// them: `use`, `use project`, `use clear`. -func use(cmd *cobra.Command, u *ui.UI, args []string) { +// them: `use`, `use project`, `use clear`. Ctrl-C cancels ctx. +func use(ctx context.Context, cmd *cobra.Command, u *ui.UI, args []string) { switch { case len(args) == 0: showCurrent(u) @@ -203,7 +218,10 @@ func use(cmd *cobra.Command, u *ui.UI, args []string) { fmt.Fprintln(os.Stderr, u.Status(ui.StatusDone, "Nothing is current now: commands ask again")) case len(args) == 1 && useLevels[args[0]] != "": output.ResetAgentMode() + prev := cmd.Context() + cmd.SetContext(ctx) // the lists load with it it, err := interactive.PickCurrent(cmd, useLevels[args[0]]) + cmd.SetContext(prev) switch { case err != nil && (errors.Is(err, huh.ErrUserAborted) || errors.Is(err, context.Canceled)): fmt.Fprintln(os.Stderr, u.Status(ui.StatusFailed, "Canceled")) @@ -245,18 +263,48 @@ func showCurrent(u *ui.UI) { // the prompt box under them, and never fewer than ten. func foldLines() int { return max(ui.TerminalHeight(os.Stdout)-6, 10) } -// interruptible is the context for one line. The first Ctrl-C cancels it, so -// the command stops and the prompt comes back instead of vf exiting. A second -// one, for a command that is not listening, exits vf as Ctrl-C always has. -func interruptible() (context.Context, func()) { +// interrupts is where Ctrl-C goes while the home prompt is open: it is +// caught from before the first prompt until the last. +// +// Each line used to start catching Ctrl-C only once its command tree was +// built, some milliseconds after the prompt had handed the terminal back. A +// Ctrl-C in that gap, pressed hard on the heels of Enter, found nothing +// listening and ended vf, history and context with it: `^C`, then the +// shell. Now one pressed at any moment after Enter goes to the line. +type interrupts struct{ sigs chan os.Signal } + +func catchInterrupts() *interrupts { + in := &interrupts{sigs: make(chan os.Signal, 1)} + signal.Notify(in.sigs, os.Interrupt) + return in +} + +func (in *interrupts) stop() { signal.Stop(in.sigs) } + +// drop forgets a Ctrl-C pressed before the prompt shows: it was meant for a +// line that has ended by now, not for the next one. +func (in *interrupts) drop() { + for { + select { + case <-in.sigs: + default: + return + } + } +} + +// line is the context for one line. The first Ctrl-C cancels it, so the +// command stops and the prompt comes back instead of vf exiting; one pressed +// before the command was listening cancels it as it starts. A second one, +// for a command that is not listening, exits vf as Ctrl-C always has. +func (in *interrupts) line() (context.Context, func()) { ctx, cancel := context.WithCancel(context.Background()) - sigs := make(chan os.Signal, 1) - signal.Notify(sigs, os.Interrupt) - done := make(chan struct{}) + done, ended := make(chan struct{}), make(chan struct{}) go func() { + defer close(ended) for pressed := false; ; pressed = true { select { - case <-sigs: + case <-in.sigs: if pressed { os.Exit(130) } @@ -267,8 +315,8 @@ func interruptible() (context.Context, func()) { } }() return ctx, func() { - signal.Stop(sigs) close(done) + <-ended // so the next line's Ctrl-C is its own cancel() } } diff --git a/internal/cli/home_interrupt_test.go b/internal/cli/home_interrupt_test.go new file mode 100644 index 00000000..14dd613b --- /dev/null +++ b/internal/cli/home_interrupt_test.go @@ -0,0 +1,147 @@ +// This file is not generated by Speakeasy. It covers how the home prompt +// (home.go) takes Ctrl-C pressed as, or just after, a line is entered. + +package cli + +import ( + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync/atomic" + "syscall" + "testing" + "time" + + "github.com/voiceflow/cli/internal/prompt" + "github.com/voiceflow/cli/internal/ui" +) + +// slowAPI answers anything after 5 seconds, or when the request is +// canceled, and counts the requests. +func slowAPI(t *testing.T) (*httptest.Server, *atomic.Int32) { + t.Helper() + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + select { + case <-r.Context().Done(): + case <-time.After(5 * time.Second): + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"project":{"id":"p1","name":"Slow"}}`)) + })) + t.Cleanup(srv.Close) + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", srv.URL) + return srv, &requests +} + +// typeLines has the prompt read lines, then leave; each line is read as +// entered, and then before(line) runs. +func typeLines(t *testing.T, before func(), lines ...string) { + t.Helper() + saved := readLine + t.Cleanup(func() { readLine = saved }) + readLine = func(prompt.Options) (string, bool, error) { + if len(lines) == 0 { + return "", false, nil + } + line := lines[0] + lines = lines[1:] + if before != nil { + before() + } + return line, true, nil + } +} + +// Ctrl-C pressed just after Enter, after the prompt had handed the terminal +// back and before the line's command was listening, ended vf: the signal +// found nothing to catch it. It must cancel only that line. +// +// The process gets a real SIGINT, which kills it when nothing catches it, so +// the test runs in a child process and checks how the child ended. +func TestCtrlCJustAfterEnterCancelsOnlyTheLine(t *testing.T) { + if os.Getenv("VF_TEST_CTRL_C_CHILD") == "1" { + ctrlCJustAfterEnter(t) + return + } + child := exec.Command(os.Args[0], "-test.run=^TestCtrlCJustAfterEnterCancelsOnlyTheLine$", "-test.v") + child.Env = append(os.Environ(), "VF_TEST_CTRL_C_CHILD=1") + out, err := child.CombinedOutput() + if err != nil { + t.Fatalf("vf didn't survive Ctrl-C just after Enter: %v\n%s", err, out) + } + if !strings.Contains(string(out), "Canceled") || !strings.Contains(string(out), "--- PASS") { + t.Errorf("the line should say it was canceled:\n%s", out) + } +} + +func ctrlCJustAfterEnter(t *testing.T) { + isolate(t) + slowAPI(t) + typeLines(t, func() { + // Ctrl-C hard on the heels of Enter: the terminal is cooked again, + // so it arrives as SIGINT, while the next line is still being set up. + _ = syscall.Kill(os.Getpid(), syscall.SIGINT) + time.Sleep(50 * time.Millisecond) + }, "project get -p p1 --agent-mode=false", "version") + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + start := time.Now() + if err := runPrompt(root, ui.Plain(), io.Discard, signIn{}); err != nil { + t.Fatal(err) + } + // The second line is version; its Ctrl-C cancels nothing that waits. + if took := time.Since(start); took > 3*time.Second { + t.Errorf("the line ran for %v: Ctrl-C didn't cancel it", took) + } +} + +// Ctrl-C read with the Enter, in one burst of input, reaches the prompt as a +// key, not a signal. The line is not run, says Canceled, and stays in +// history for ↑. +func TestCtrlCWithTheEnterCancelsTheLine(t *testing.T) { + home, _ := isolate(t) + _, requests := slowAPI(t) + saved := readLine + t.Cleanup(func() { readLine = saved }) + lines := 0 + readLine = func(prompt.Options) (string, bool, error) { + lines++ + if lines > 1 { + return "", false, nil + } + return "project get -p p1", true, prompt.ErrCanceled + } + stderr := filepath.Join(t.TempDir(), "stderr") + f, err := os.Create(stderr) + if err != nil { + t.Fatal(err) + } + saveErr := os.Stderr + os.Stderr = f + t.Cleanup(func() { os.Stderr = saveErr; f.Close() }) + + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + if err := runPrompt(root, ui.Plain(), io.Discard, signIn{}); err != nil { + t.Fatal(err) + } + os.Stderr = saveErr + said, _ := os.ReadFile(stderr) + if requests.Load() != 0 || !strings.Contains(string(said), "Canceled") { + t.Errorf("requests %d, said %q", requests.Load(), said) + } + if got := loadHistory(historyPath()); len(got) == 0 || got[len(got)-1] != "project get -p p1" { + t.Errorf("history in %s: %q", home, got) + } +} diff --git a/internal/cli/home_test.go b/internal/cli/home_test.go index a5b331e5..a97e52dc 100644 --- a/internal/cli/home_test.go +++ b/internal/cli/home_test.go @@ -4,6 +4,7 @@ package cli import ( "bytes" + "context" "os" "path/filepath" "strings" @@ -140,7 +141,7 @@ func TestSignInSurvivesALineThatSkipsSetup(t *testing.T) { t.Cleanup(func() { os.Stdout = stdout; devNull.Close() }) for _, line := range [][]string{{"workflow", "--help"}, {"--help"}, {"project", "list", "--no-such-flag"}} { - runLine(ui.Plain(), line) + runLine(context.Background(), ui.Plain(), line) if got := signInState(root); !got.signed { t.Errorf("after %q the prompt says %q", strings.Join(line, " "), got.text) } diff --git a/internal/prompt/prompt.go b/internal/prompt/prompt.go index ce8b0800..31d20b2a 100644 --- a/internal/prompt/prompt.go +++ b/internal/prompt/prompt.go @@ -3,6 +3,7 @@ package prompt import ( + "errors" "io" "strconv" "strings" @@ -38,6 +39,11 @@ type Options struct { // the selection. const maxRows = 8 +// ErrCanceled comes back with a line when Ctrl-C was pressed with the Enter +// that ran it, so close behind that both were read at once: the line is to +// be stopped, not run. +var ErrCanceled = errors.New("canceled as it was entered") + // Read shows the prompt and returns the line that was entered. ok is false // when the person left instead: Ctrl-D, or Ctrl-C twice, on an empty line. // @@ -52,6 +58,9 @@ func Read(opts Options) (line string, ok bool, err error) { return "", false, err } fm := final.(*model) + if fm.canceled { + return fm.line, true, ErrCanceled + } return fm.line, !fm.exited, nil } @@ -82,6 +91,7 @@ type model struct { hit int // the history line it found, or -1 done, exited bool + canceled bool // Ctrl-C came in with the Enter: ErrCanceled line string } @@ -131,6 +141,12 @@ func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } func (m *model) key(k tea.KeyMsg) (tea.Model, tea.Cmd) { + if m.done { + // A key read with the Enter that ran the line. Ctrl-C there means + // stop it, as it does a moment later, once the line runs. + m.canceled = m.canceled || (k.String() == "ctrl+c" && !m.exited) + return m, nil + } if m.searching { return m.searchKey(k) } diff --git a/internal/prompt/prompt_test.go b/internal/prompt/prompt_test.go index 30a943a2..791092b2 100644 --- a/internal/prompt/prompt_test.go +++ b/internal/prompt/prompt_test.go @@ -86,6 +86,27 @@ func TestEnterFinishesAWordThenRuns(t *testing.T) { } } +// Ctrl-C read in the same burst as the Enter that ran a line comes after +// the line is done. It stops the line, as Ctrl-C a moment later does; other +// keys change nothing. +func TestCtrlCWithTheEnterStopsTheLine(t *testing.T) { + m := testModel().typed("project list").press(enter, ctrlC) + if !m.done || m.exited || !m.canceled || m.line != "project list" { + t.Fatalf("done=%v exited=%v canceled=%v %q", m.done, m.exited, m.canceled, m.line) + } + if got := m.View(); got != "❯ project list\n" { + t.Errorf("the echo stays: %q", got) + } + m = testModel().typed("project list").press(enter).typed("x").press(tab) + if m.canceled || m.line != "project list" { + t.Errorf("canceled=%v %q", m.canceled, m.line) + } + m = testModel().press(ctrlC, ctrlC, ctrlC) + if !m.exited || m.canceled { + t.Errorf("Ctrl-C twice leaves; a third cancels nothing: exited=%v canceled=%v", m.exited, m.canceled) + } +} + func TestEnterRunsWhatTheMenuCannotHelpWith(t *testing.T) { // A flag's value: no menu, so Enter runs the line as typed. m := testModel().typed("project get --project-id abc").press(enter) From e6c844b74013e15abffe789b89cefbed51b2c337 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:39:07 -0500 Subject: [PATCH 21/28] fix(forms): Esc cancels a form, as Ctrl-C does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A form closed only on Ctrl-C, and nothing on it said so. People backed out with Esc, which the home prompt's own menu takes, and the form just stayed on screen (`┃ >`), in `document create-text` and in the project and environment lists alike. Esc now cancels a form too: "✗ Canceled", and nothing is sent. On a delete's Yes/No question it answers No. In a list being filtered with /, Esc keeps its meaning there: the first ends the filter, the next clears it, and only then does Esc close the list. One-line hooks in the generated interactive.go, and in pickers.go and confirm.go. Found by the round-4 sweep's human-newcomer and human-kb testers (R4 #39). --- internal/interactive/confirm.go | 7 +-- internal/interactive/esccancel.go | 42 +++++++++++++++ internal/interactive/esccancel_test.go | 73 ++++++++++++++++++++++++++ internal/interactive/interactive.go | 4 ++ internal/interactive/pickers.go | 3 +- 5 files changed, 125 insertions(+), 4 deletions(-) create mode 100644 internal/interactive/esccancel.go create mode 100644 internal/interactive/esccancel_test.go diff --git a/internal/interactive/confirm.go b/internal/interactive/confirm.go index dd423671..601e6402 100644 --- a/internal/interactive/confirm.go +++ b/internal/interactive/confirm.go @@ -23,13 +23,14 @@ func AskYesNo(ctx context.Context, title, note string) (bool, error) { width = 80 } yes := false - err = huh.NewForm(huh.NewGroup(huh.NewConfirm(). + form := huh.NewForm(huh.NewGroup(huh.NewConfirm(). Title(title). Description(note). Affirmative("Yes"). Negative("No"). - Value(&yes))). - WithOutput(os.Stderr). + Value(&yes))) + form = escCancels(form) // esccancel.go: Esc answers No, as Ctrl-C does + err = form.WithOutput(os.Stderr). WithWidth(width). WithTheme(formTheme()). WithShowHelp(false). diff --git a/internal/interactive/esccancel.go b/internal/interactive/esccancel.go new file mode 100644 index 00000000..e4812d59 --- /dev/null +++ b/internal/interactive/esccancel.go @@ -0,0 +1,42 @@ +// This file is not generated by Speakeasy. It lets Esc close a form, as +// Ctrl-C does. +// +// huh closes a form only on Ctrl-C, and the form doesn't say so. People +// back out with Esc, as they close the home prompt's menu, and the form +// just stayed on screen. Esc now cancels a form too ("✗ Canceled", nothing +// sent), unless the field in focus is using Esc right then: a list being +// filtered with /, where Esc first ends the filter, then clears it. + +package interactive + +import ( + "os" + + "github.com/charmbracelet/bubbles/key" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/huh" +) + +// escCancels has Esc cancel f, as Ctrl-C does. It sets f's program options, +// so it comes before any WithOutput or WithInput; f draws on stderr, as +// huh's forms do by default. +func escCancels(f *huh.Form) *huh.Form { + return f.WithProgramOptions(tea.WithOutput(os.Stderr), tea.WithFilter(escToQuit)) +} + +// escToQuit turns Esc into the Ctrl-C that cancels the form, unless the +// focused field has a key of its own on Esc at the moment. +func escToQuit(m tea.Model, msg tea.Msg) tea.Msg { + k, ok := msg.(tea.KeyMsg) + if !ok || k.Type != tea.KeyEsc { + return msg + } + if f, ok := m.(*huh.Form); ok { + for _, b := range f.KeyBinds() { + if b.Enabled() && key.Matches(k, b) { + return msg + } + } + } + return tea.KeyMsg{Type: tea.KeyCtrlC} +} diff --git a/internal/interactive/esccancel_test.go b/internal/interactive/esccancel_test.go new file mode 100644 index 00000000..b4680c84 --- /dev/null +++ b/internal/interactive/esccancel_test.go @@ -0,0 +1,73 @@ +// This file is not generated by Speakeasy. It covers esccancel.go. + +package interactive + +import ( + "errors" + "io" + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/huh" +) + +var escKey = tea.KeyMsg{Type: tea.KeyEsc} + +// keyName is the key msg is, as bubbletea names it: "esc", "ctrl+c". +func keyName(msg tea.Msg) string { + if k, ok := msg.(tea.KeyMsg); ok { + return k.String() + } + return "" +} + +// Esc on a form's field closes the form, as Ctrl-C does: nothing is asked +// further and nothing is sent. +func TestEscCancelsAForm(t *testing.T) { + var typed string + form := escCancels(huh.NewForm(huh.NewGroup(huh.NewInput().Title("File (required)").Value(&typed)))). + WithInput(strings.NewReader("faq\x1b")). + WithOutput(io.Discard). + WithTimeout(3 * time.Second) + if err := form.Run(); !errors.Is(err, huh.ErrUserAborted) { + t.Fatalf("Esc should cancel the form as Ctrl-C does, got %v", err) + } + + var yes bool + confirm := huh.NewForm(huh.NewGroup(huh.NewConfirm().Value(&yes))) + if got := keyName(escToQuit(confirm, escKey)); got != "ctrl+c" { + t.Errorf("Esc on a yes/no question: %v", got) + } + if got := keyName(escToQuit(confirm, tea.KeyMsg{Type: tea.KeyEnter})); got != "enter" { + t.Errorf("other keys go through: %v", got) + } +} + +// In a list being filtered with /, Esc is the list's: it ends the filter, +// then clears it. Only then does Esc close the form. +func TestEscInAFilteredListIsTheLists(t *testing.T) { + var picked string + form := huh.NewForm(huh.NewGroup(huh.NewSelect[string](). + Options(huh.NewOptions("Northwind", "Northwind Coffee Support", "Sales")...). + Value(&picked))) + form.Init() + press := func(msgs ...tea.Msg) { + for _, m := range msgs { + form.Update(escToQuit(form, m)) + } + } + press(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("/")}, tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("Co")}) + if got := keyName(escToQuit(form, escKey)); got != "esc" { + t.Fatalf("Esc while filtering ends the filter, got %v", got) + } + press(escKey) + if got := keyName(escToQuit(form, escKey)); got != "esc" { + t.Fatalf("Esc with a filter set clears it, got %v", got) + } + press(escKey) + if got := keyName(escToQuit(form, escKey)); got != "ctrl+c" { + t.Errorf("Esc with no filter closes the form, got %v", got) + } +} diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go index ab54a3d5..3e973362 100644 --- a/internal/interactive/interactive.go +++ b/internal/interactive/interactive.go @@ -278,6 +278,7 @@ func PromptAndSetFlags(cmd *cobra.Command, meta []flagutil.FlagMeta) error { WithWidth(width). WithTheme(theme). WithShowHelp(false) + form = escCancels(form) // esccancel.go: Esc cancels it, as Ctrl-C does if err := form.Run(); err != nil { return fmt.Errorf("interactive prompt: %w", err) @@ -313,6 +314,7 @@ func PromptAndSetFlags(cmd *cobra.Command, meta []flagutil.FlagMeta) error { WithWidth(width). WithTheme(theme). WithShowHelp(false) + confirmForm = escCancels(confirmForm) // esccancel.go: Esc cancels it, as Ctrl-C does if err := confirmForm.Run(); err != nil { return fmt.Errorf("interactive prompt: %w", err) @@ -324,6 +326,7 @@ func PromptAndSetFlags(cmd *cobra.Command, meta []flagutil.FlagMeta) error { WithWidth(width). WithTheme(theme). WithShowHelp(false) + optForm = escCancels(optForm) // esccancel.go: Esc cancels it, as Ctrl-C does if err := optForm.Run(); err != nil { return fmt.Errorf("interactive prompt: %w", err) @@ -630,6 +633,7 @@ func PromptForBodyJSON(cmd *cobra.Command, flagName, description string) error { WithWidth(formWidth()). WithTheme(formTheme()). WithShowHelp(false) + form = escCancels(form) // esccancel.go: Esc cancels it, as Ctrl-C does if err := form.Run(); err != nil { return fmt.Errorf("interactive prompt: %w", err) diff --git a/internal/interactive/pickers.go b/internal/interactive/pickers.go index 84fe9aa0..b750eaf6 100644 --- a/internal/interactive/pickers.go +++ b/internal/interactive/pickers.go @@ -347,8 +347,9 @@ func askInForm(title, desc string, value *string) error { } // runField runs one field in its own form, as PromptAndSetFlags runs each. +// Esc cancels it (esccancel.go). func runField(f huh.Field) error { - return huh.NewForm(huh.NewGroup(f)). + return escCancels(huh.NewForm(huh.NewGroup(f))). WithWidth(formWidth()). WithTheme(formTheme()). WithShowHelp(false). From 7b79a1a2e64096f193a68a7e197298a42e54f22e Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:46:27 -0500 Subject: [PATCH 22/28] fix(forms): a delete's question names what it deletes A delete asked "Delete document 6b0ddda34eb600496d834c6d?", and a person can't tell from an ID whether that is the holiday note or the FAQ. vf named the thing only when it was picked from a list or was current in the home prompt; a typed or pasted ID got the ID alone. Now, when a person is about to be asked and vf doesn't know the name, it reads the thing first, with one GET of the URL the DELETE goes to, and asks `Delete document "holiday-note.txt" (6b0d...)?`. A read that fails, is slow (5 s cap) or has no name leaves the ID alone. Pipes, scripts, agent mode, --yes and --dry-run are never asked, so they send the delete and nothing else, as before. The confirm hook in client/confirm.go now gets the command's client for that read; the read is in the new cli/confirmname.go. Found by the round-4 sweep's human-kb and human-poweruser testers (R4 #38). --- internal/cli/confirm.go | 29 ++++++---- internal/cli/confirm_test.go | 99 +++++++++++++++++++++++++++++++-- internal/cli/confirmname.go | 93 +++++++++++++++++++++++++++++++ internal/client/confirm.go | 8 ++- internal/client/confirm_test.go | 29 ++++++++-- 5 files changed, 236 insertions(+), 22 deletions(-) create mode 100644 internal/cli/confirmname.go diff --git a/internal/cli/confirm.go b/internal/cli/confirm.go index 59b0afe0..e7159b11 100644 --- a/internal/cli/confirm.go +++ b/internal/cli/confirm.go @@ -15,7 +15,8 @@ // terminal, agent mode is off, and --no-interactive isn't set. Scripts, CI, // agents and pipes run exactly as before, and --dry-run never asks, since it // sends nothing. The question comes after the pickers, so it can name what -// was picked, and before the request leaves (client/confirm.go). +// was picked, and before the request leaves (client/confirm.go). A name vf +// doesn't know yet is read first, with one GET (confirmname.go). // // Every command named delete or delete-* asks. They are found at startup, // so a delete the spec adds later asks too, without editing ~35 generated @@ -169,12 +170,14 @@ var askYesNo = interactive.AskYesNo var errNotConfirmed = fmt.Errorf("not confirmed: %w", context.Canceled) // confirmChange asks before cmd's first request that changes something, -// when cmd asks first. Anything but Yes sends nothing. -func confirmChange(cmd *cobra.Command, req *http.Request) error { +// when cmd asks first. Anything but Yes sends nothing. read is the client +// req goes out on, for reading the name of what it deletes. +func confirmChange(cmd *cobra.Command, req *http.Request, read client.HTTPClient) error { if !asks(cmd) { return nil } - title, note := "Delete "+deleteTarget(cmd)+"?", "This can't be undone." + lookUp := func(id string) string { return readName(req, read, id) } // confirmname.go + title, note := "Delete "+deleteTarget(cmd, lookUp)+"?", "This can't be undone." if isMerge(cmd) { title, note = mergeQuestion(cmd, req) } @@ -193,11 +196,12 @@ func confirmChange(cmd *cobra.Command, req *http.Request) error { var placeFlags = map[string]bool{"organization-id": true, "workspace-id": true, "project-id": true, "environment-alias": true} // deleteTarget names what cmd deletes: `project "Help bot" (p1)` when vf -// knows the name without asking the API, `variable v1` when it doesn't. -func deleteTarget(cmd *cobra.Command) string { +// knows the name, or lookUp finds it, `variable v1` when neither does. +// lookUp may be nil. +func deleteTarget(cmd *cobra.Command, lookUp func(id string) string) string { noun := deleteNoun(cmd) if f := idFlag(cmd, noun); f != nil { - return noun + " " + named(f.Name, f.Value.String()) + return noun + " " + named(f.Name, f.Value.String(), lookUp) } // No flag holds its own ID (a tool message is one slot of a tool), so // say what was given. @@ -244,14 +248,17 @@ func idFlag(cmd *cobra.Command, noun string) *pflag.Flag { } // named is `"Help bot" (p1)` when vf knows what value is called: it was -// picked from a list in this run, or is current in the home prompt. -// Otherwise it is the value alone. -func named(flag, value string) string { +// picked from a list in this run, or is current in the home prompt, or +// lookUp finds it. Otherwise it is the value alone. +func named(flag, value string, lookUp func(id string) string) string { name := interactive.PickedName(flag, value) if it, ok := session.Get(flag); name == "" && ok && it.Value == value && it.Name != value { name = it.Name } - if name == "" { + if name == "" && lookUp != nil { + name = lookUp(value) + } + if name == "" || name == value { return value } return `"` + name + `" (` + value + `)` diff --git a/internal/cli/confirm_test.go b/internal/cli/confirm_test.go index 9d0ad88d..835cad57 100644 --- a/internal/cli/confirm_test.go +++ b/internal/cli/confirm_test.go @@ -7,6 +7,7 @@ package cli import ( "bytes" "context" + "encoding/json" "errors" "io" "net/http" @@ -93,7 +94,8 @@ func TestADeleteAsksOnlyWhenSomeoneCanAnswer(t *testing.T) { asks bool sends []string }{ - {"at a terminal", true, nil, true, nil}, + // The question reads the project's name first (confirmname.go). + {"at a terminal", true, nil, true, []string{"GET /v1/stable/project/p1"}}, {"--yes", true, []string{"--yes"}, false, sent}, {"-y", true, []string{"-y"}, false, sent}, {"--dry-run", true, []string{"--dry-run"}, false, nil}, @@ -132,8 +134,8 @@ func TestYesSendsTheDelete(t *testing.T) { if want := []string{`Delete secret s1? This can't be undone.`}; !slices.Equal(*asked, want) { t.Errorf("asked %q, want %q", *asked, want) } - if got := requests(); len(got) != 1 || !strings.HasPrefix(got[0], "DELETE ") { - t.Errorf("Yes should send the delete, sent %q", got) + if got := requests(); !slices.Equal(got, []string{"GET /v1/stable/secret/s1", "DELETE /v1/stable/secret/s1"}) { + t.Errorf("Yes should send the delete, after reading the name for the question: sent %q", got) } } @@ -270,7 +272,7 @@ func TestTheQuestionNamesWhatItDeletes(t *testing.T) { if err := c.ParseFlags(rest); err != nil { t.Fatal(err) } - return deleteTarget(c) + return deleteTarget(c, nil) } for _, tc := range []struct { args []string @@ -300,3 +302,92 @@ func TestTheQuestionNamesWhatItDeletes(t *testing.T) { t.Errorf("another project's name isn't known, got %q", got) } } + +// A name vf doesn't know is read for the question, with one GET of what the +// delete goes to, and only when a person is asked: a script, a pipe or an +// agent sends the delete and nothing else. +func TestTheQuestionReadsANameItDoesntKnow(t *testing.T) { + var mu sync.Mutex + var sent []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + sent = append(sent, r.Method+" "+r.URL.Path) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && r.URL.Path == "/v1/stable/document/d1": + _, _ = io.WriteString(w, `{"document":{"id":"d1","data":{"type":"text","name":"holiday-note.txt"},"status":{"type":"SUCCESS"},"chunks":[]}}`) + case r.Method == http.MethodGet: + http.NotFound(w, r) + default: + _, _ = io.WriteString(w, `{"message":"Deleted."}`) + } + })) + t.Cleanup(srv.Close) + requests := func() []string { + mu.Lock() + defer mu.Unlock() + got := slices.Clone(sent) + sent = nil + return got + } + del := []string{"document", "delete", "--document-id", "d1", "-p", "p1", "-e", "main"} + + asked := answering(t, true, false) + if _, err := runAt(t, srv, del...); !errors.Is(err, context.Canceled) { + t.Fatalf("No should cancel: %v", err) + } + if want := `Delete document "holiday-note.txt" (d1)? This can't be undone.`; !slices.Equal(*asked, []string{want}) { + t.Errorf("asked %q, want %q", *asked, want) + } + if got := requests(); !slices.Equal(got, []string{"GET /v1/stable/document/d1"}) { + t.Errorf("one read for the name, and no delete after No: sent %q", got) + } + + // A read that finds nothing leaves the ID alone. + asked = answering(t, true, false) + _, _ = runAt(t, srv, "document", "delete", "--document-id", "d2", "-p", "p1", "-e", "main") + if want := "Delete document d2? This can't be undone."; !slices.Equal(*asked, []string{want}) { + t.Errorf("asked %q, want %q", *asked, want) + } + requests() + + for _, tc := range []struct { + name string + terminal bool + args []string + }{ + {"not at a terminal", false, nil}, + {"agent mode", true, []string{"--agent-mode"}}, + {"--yes", true, []string{"--yes"}}, + } { + asked := answering(t, tc.terminal, false) + if out, err := runAt(t, srv, append(slices.Clone(del), tc.args...)...); err != nil { + t.Fatalf("%s: %v\n%s", tc.name, err, out) + } + if got := requests(); len(*asked) != 0 || !slices.Equal(got, []string{"DELETE /v1/stable/document/d1"}) { + t.Errorf("%s: asked %q, sent %q; want the delete alone", tc.name, *asked, got) + } + } +} + +func TestNameInFindsTheThingRead(t *testing.T) { + for _, tc := range []struct { + body, want string + }{ + {`{"project":{"id":"p1","name":"Help bot"}}`, "Help bot"}, + {`{"document":{"id":"p1","data":{"name":"faq.md"}}}`, "faq.md"}, + {`{"document":{"id":"other","data":{"name":"faq.md"}}}`, ""}, // not the one asked for + {`{"message":"Deleted."}`, ""}, + {`{"a":{"name":"x"},"b":{"name":"y"}}`, ""}, // not one thing + {`{"state":{"variables":{}}}`, ""}, + } { + var body map[string]any + if err := json.Unmarshal([]byte(tc.body), &body); err != nil { + t.Fatal(err) + } + if got := nameIn(body, "p1"); got != tc.want { + t.Errorf("%s: %q, want %q", tc.body, got, tc.want) + } + } +} diff --git a/internal/cli/confirmname.go b/internal/cli/confirmname.go new file mode 100644 index 00000000..dff1aea8 --- /dev/null +++ b/internal/cli/confirmname.go @@ -0,0 +1,93 @@ +// This file is not generated by Speakeasy. It reads the name of what a +// delete is about to remove, so the question can name it (confirm.go). +// +// A delete asked "Delete document 6b0ddda34eb600496d834c6d?", and a person +// can't tell from an ID whether that is the holiday note or the FAQ. vf +// knows a name only when it was picked from a list or is current in the +// home prompt; a document's ID is typed or pasted. So, when a person is +// about to be asked and vf doesn't know the name, it reads the thing first: +// a GET of the URL the DELETE is going to, which for every delete in the +// API is where that one thing is read. The question then says +// `Delete document "holiday-note.txt" (6b0d…)?`. +// +// Only a question asked at a terminal reads it (confirm.go's asks): never +// a script, a pipe, agent mode or --yes, so they send exactly the requests +// they did. A read that fails, is slow, or has no name leaves the ID alone. + +package cli + +import ( + "context" + "encoding/json" + "io" + "net/http" + "time" + + "github.com/voiceflow/cli/internal/client" +) + +// readNameTimeout bounds the read, so a slow API delays the question only +// a little. +const readNameTimeout = 5 * time.Second + +// readName reads what del is about to delete with read, and returns its +// name, or "" when that can't be told. +func readName(del *http.Request, read client.HTTPClient, id string) string { + if read == nil || del.URL == nil { + return "" + } + ctx, cancel := context.WithTimeout(del.Context(), readNameTimeout) + defer cancel() + get, err := http.NewRequestWithContext(ctx, http.MethodGet, del.URL.String(), nil) + if err != nil { + return "" + } + get.Header = del.Header.Clone() // the same auth and -H headers + get.Header.Del("Content-Type") + res, err := read.Do(get) + if err != nil { + return "" + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return "" + } + var body map[string]any + if json.NewDecoder(io.LimitReader(res.Body, 8<<20)).Decode(&body) != nil { + return "" + } + return nameIn(body, id) +} + +// nameIn finds the name in a read's answer, which wraps the one thing read: +// {"project": {"id": …, "name": …}}, or for a document {"document": {"id": +// …, "data": {"name": …}}}. The thing must be the one with id, when it says +// which it is. +func nameIn(v map[string]any, id string) string { + for range 3 { + name, _ := v["name"].(string) + if data, ok := v["data"].(map[string]any); ok && name == "" { + name, _ = data["name"].(string) + } + if name != "" { + if got, ok := v["id"].(string); ok && got != id { + return "" + } + return name + } + var inner map[string]any + for _, x := range v { + if m, ok := x.(map[string]any); ok { + if inner != nil { + return "" // not one thing + } + inner = m + } + } + if inner == nil { + return "" + } + v = inner + } + return "" +} diff --git a/internal/client/confirm.go b/internal/client/confirm.go index f23fc6a3..50c6b787 100644 --- a/internal/client/confirm.go +++ b/internal/client/confirm.go @@ -18,8 +18,10 @@ import ( // BeforeChange, when set, runs before a command's first request that is not // a read. An error stops that request: nothing is sent, and the command gets -// the error back. -var BeforeChange func(cmd *cobra.Command, req *http.Request) error +// the error back. read sends a request of the hook's own, with the +// command's client but without asking again: a question that names what it +// deletes may have to read its name first. +var BeforeChange func(cmd *cobra.Command, req *http.Request, read HTTPClient) error // WrapClientForConfirm runs BeforeChange before the first request that // changes something. Reads go straight through: a picker's list comes before @@ -40,7 +42,7 @@ type confirmClient struct { func (c *confirmClient) Do(req *http.Request) (*http.Response, error) { if !c.asked && changes(req.Method) { c.asked = true - if err := BeforeChange(c.cmd, req); err != nil { + if err := BeforeChange(c.cmd, req, c.inner); err != nil { return nil, err } } diff --git a/internal/client/confirm_test.go b/internal/client/confirm_test.go index 0ed4df62..65703529 100644 --- a/internal/client/confirm_test.go +++ b/internal/client/confirm_test.go @@ -19,7 +19,7 @@ func (c *recordingClient) Do(req *http.Request) (*http.Response, error) { return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil } -func withBeforeChange(t *testing.T, hook func(*cobra.Command, *http.Request) error) { +func withBeforeChange(t *testing.T, hook func(*cobra.Command, *http.Request, HTTPClient) error) { t.Helper() saved := BeforeChange BeforeChange = hook @@ -40,7 +40,7 @@ func TestBeforeChangeRunsOnceBeforeTheFirstChange(t *testing.T) { cmd := &cobra.Command{Use: "delete"} cmd.Flags().Bool("dry-run", false, "") var hooked []string - withBeforeChange(t, func(_ *cobra.Command, req *http.Request) error { + withBeforeChange(t, func(_ *cobra.Command, req *http.Request, _ HTTPClient) error { hooked = append(hooked, req.Method) return nil }) @@ -59,11 +59,32 @@ func TestBeforeChangeRunsOnceBeforeTheFirstChange(t *testing.T) { } } +// The hook can read before it asks (the name of what a delete removes), +// with the command's own client, and that read doesn't ask again. +func TestBeforeChangeCanReadFirst(t *testing.T) { + cmd := &cobra.Command{Use: "delete"} + cmd.Flags().Bool("dry-run", false, "") + hooked := 0 + withBeforeChange(t, func(_ *cobra.Command, req *http.Request, read HTTPClient) error { + hooked++ + get, _ := http.NewRequest(http.MethodGet, req.URL.String(), nil) + _, err := read.Do(get) + return err + }) + inner := &recordingClient{} + if err := send(t, WrapClientForConfirm(cmd, inner), http.MethodDelete); err != nil { + t.Fatal(err) + } + if hooked != 1 || len(inner.sent) != 2 || inner.sent[0] != http.MethodGet || inner.sent[1] != http.MethodDelete { + t.Errorf("hooked %d times, sent %q", hooked, inner.sent) + } +} + func TestAnErrorFromBeforeChangeSendsNothing(t *testing.T) { cmd := &cobra.Command{Use: "delete"} cmd.Flags().Bool("dry-run", false, "") no := errors.New("no") - withBeforeChange(t, func(*cobra.Command, *http.Request) error { return no }) + withBeforeChange(t, func(*cobra.Command, *http.Request, HTTPClient) error { return no }) inner := &recordingClient{} if err := send(t, WrapClientForConfirm(cmd, inner), http.MethodDelete); !errors.Is(err, no) { t.Errorf("the hook's error should come back, got %v", err) @@ -77,7 +98,7 @@ func TestADryRunNeverAsks(t *testing.T) { cmd := &cobra.Command{Use: "delete"} cmd.Flags().Bool("dry-run", false, "") _ = cmd.Flags().Set("dry-run", "true") - withBeforeChange(t, func(*cobra.Command, *http.Request) error { + withBeforeChange(t, func(*cobra.Command, *http.Request, HTTPClient) error { t.Error("a dry run sends nothing, so it should not ask") return nil }) From 240288cb09cb1b70f67f6c64007cd9908173f1c3 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:21:33 -0500 Subject: [PATCH 23/28] fix(help): help, replies and warnings break between words at the terminal's edge vf wrote help, hints, warnings and agent replies as one long line each, and the terminal broke them wherever its edge fell: `--body - reads it f` / `rom stdin` in help, `maybe our menu or d` / `irections?` in a reply, at 70 columns and at 160. At a terminal they now break at spaces and continue under their own text: a flag's description under the description, a status line under its message, a reply under the reply. One wrapper (ui/wrap.go, built on the one read-prompt uses) does it for help, the home prompt's help, error explanations and their next steps, status lines such as the stale-build warning, agent replies and docs search results. A quoted command, a flag and its value, a command in the accent color, and the Usage and Examples sections stay whole, so what is copied still runs. Pipes, -o json and agent mode are not wrapped. Found by the round-4 sweep's human-poweruser, human-newcomer and human-kb testers. --- internal/cli/conversation/reply.go | 2 +- internal/cli/docs.go | 3 +- internal/cli/helpwrap.go | 88 +++++++++++ internal/cli/helpwrap_test.go | 132 ++++++++++++++++ internal/cli/prompt_help.go | 2 +- internal/cli/root.go | 1 + internal/output/explain.go | 2 +- internal/ui/lines.go | 1 + internal/ui/ui.go | 9 +- internal/ui/wrap.go | 243 +++++++++++++++++++++++++++++ internal/ui/wrap_test.go | 149 ++++++++++++++++++ 11 files changed, 626 insertions(+), 6 deletions(-) create mode 100644 internal/cli/helpwrap.go create mode 100644 internal/cli/helpwrap_test.go create mode 100644 internal/ui/wrap.go create mode 100644 internal/ui/wrap_test.go diff --git a/internal/cli/conversation/reply.go b/internal/cli/conversation/reply.go index 8d8778cd..a6509dab 100644 --- a/internal/cli/conversation/reply.go +++ b/internal/cli/conversation/reply.go @@ -286,7 +286,7 @@ func (t turn) write(cmd *cobra.Command, out io.Writer, debug bool) { if strings.HasPrefix(said, "[") { line = u.Accent(line) } - fmt.Fprintln(out, strings.TrimRight(lead+line, " ")) + fmt.Fprintln(out, strings.TrimRight(lead+u.Fit(line, len(label)), " ")) // ui/wrap.go: a long reply breaks between words, under itself } } if t.ended { diff --git a/internal/cli/docs.go b/internal/cli/docs.go index c91a38b6..4c854d80 100644 --- a/internal/cli/docs.go +++ b/internal/cli/docs.go @@ -142,11 +142,12 @@ func runDocsSearchCmd(cmd *cobra.Command, args []string) error { out, done := output.ResultWriter(cmd) // folds inside the home prompt defer done() + u := output.UI(cmd, cmd.OutOrStdout()) // at a terminal, a long title or snippet breaks between words for i, result := range results { if i > 0 { fmt.Fprint(out, "\n---\n\n") } - fmt.Fprintf(out, "Title: %s\nLink: %s\nPage: %s\nContent: %s\n", result.Title, result.Link, result.Page, result.Content) + fmt.Fprintf(out, "Title: %s\nLink: %s\nPage: %s\nContent: %s\n", u.Fit(result.Title, len("Title: ")), result.Link, result.Page, u.Fit(result.Content, len("Content: "))) } fmt.Fprintln(out, "\nRead a full page with: vf docs get ") return nil diff --git a/internal/cli/helpwrap.go b/internal/cli/helpwrap.go new file mode 100644 index 00000000..9ec9c91b --- /dev/null +++ b/internal/cli/helpwrap.go @@ -0,0 +1,88 @@ +// This file is not generated by Speakeasy. It wraps help to the terminal's +// width. +// +// Help came out as one line per flag and per paragraph, so the terminal +// broke each wherever its edge fell, mid-word (`--body - reads it f` / `rom +// stdin`, `[requi` / `red]`), at 72 columns and at 160 alike. At a terminal, +// help now breaks at spaces and continues under its own text: a flag's +// description under the description, a command's summary under the +// summary, an exit code's meaning under the meaning (ui/wrap.go). +// +// What is there to copy stays as written: the Usage, Aliases and Examples +// sections, and lines of the description that are indented, which are code +// or a table. Help to a pipe, and in agent mode, is not wrapped at all. + +package cli + +import ( + "bytes" + "io" + "regexp" + "strings" + + "github.com/charmbracelet/x/ansi" + "github.com/spf13/cobra" + "golang.org/x/term" + + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/ui" +) + +// helpHeading is a section's heading in help: "Usage:", "Required Flags:". +var helpHeading = regexp.MustCompile(`^[A-Z][A-Za-z ]*:$`) + +// asWritten are the help sections whose lines are there to copy. +var asWritten = map[string]bool{"Usage:": true, "Aliases:": true, "Examples:": true} + +// wrapHelp has every command's help wrap to the terminal's width. +func wrapHelp(root *cobra.Command) { + help := root.HelpFunc() + root.SetHelpFunc(func(cmd *cobra.Command, args []string) { + out := cmd.OutOrStdout() + writeWrapped(out, helpWidth(out), func(w io.Writer) { + cmd.SetOut(w) + defer cmd.SetOut(out) + help(cmd, args) + }) + }) +} + +// helpWidth is the width to wrap help written to w at: the terminal's, or +// 0 for a pipe and in agent mode. Tests stand in a terminal's width here. +var helpWidth = func(w io.Writer) int { + f, ok := w.(interface{ Fd() uintptr }) + if !ok || !term.IsTerminal(int(f.Fd())) || output.IsAgentMode() { + return 0 + } + return ui.TerminalWidth(w) +} + +// writeWrapped has write write help to out, wrapped to width; with width 0 +// it writes straight to out. +func writeWrapped(out io.Writer, width int, write func(io.Writer)) { + if width <= 0 { + write(out) + return + } + var buf bytes.Buffer + write(&buf) + 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). +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), " ") + switch { + case helpHeading.MatchString(plain): + section = plain + case asWritten[section]: + case section == "" && strings.HasPrefix(plain, " "): + default: + lines[i] = ui.WrapLine(line, width, ui.Hang(line)) + } + } + return strings.Join(lines, "\n") +} diff --git a/internal/cli/helpwrap_test.go b/internal/cli/helpwrap_test.go new file mode 100644 index 00000000..c269c88a --- /dev/null +++ b/internal/cli/helpwrap_test.go @@ -0,0 +1,132 @@ +// This file is not generated by Speakeasy. It covers helpwrap.go. + +package cli + +import ( + "bytes" + "io" + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" + "github.com/spf13/cobra" + "github.com/voiceflow/cli/internal/ui" +) + +// helpAt runs `vf --help` as if at a terminal width columns wide (0: +// a pipe), and returns what it printed. +func helpAt(t *testing.T, width int, args ...string) string { + t.Helper() + saved := helpWidth + helpWidth = func(io.Writer) int { return width } + t.Cleanup(func() { helpWidth = saved }) + root := testRoot(t) + var out bytes.Buffer + root.SetOut(&out) + root.SetErr(&out) + root.SetArgs(append(args, "--help")) + if err := root.Execute(); err != nil { + t.Fatal(err) + } + return out.String() +} + +// checkWrapped checks that wrapped is unwrapped broken between words: each +// line fits width outside the sections there to copy, and the words are +// the same words in the same order. +func checkWrapped(t *testing.T, unwrapped, wrapped string, width int) { + t.Helper() + section := "" + for _, line := range strings.Split(wrapped, "\n") { + 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. + code := asWritten[section] || (section == "" && strings.HasPrefix(line, " ")) + if !code && ansi.StringWidth(line) > width && len(strings.Fields(line)) > 1 { + t.Errorf("a line is wider than %d columns: %q", width, line) + } + } + if a, b := strings.Fields(unwrapped), strings.Fields(wrapped); strings.Join(a, " ") != strings.Join(b, " ") { + t.Errorf("wrapping changed the words:\n%s", wrapped) + } +} + +// 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. +func TestHelpBreaksBetweenWordsAtATerminal(t *testing.T) { + for _, args := range [][]string{{}, {"secret", "create"}, {"agent", "update"}, {"conversation", "send"}, {"secret"}} { + unwrapped := helpAt(t, 0, args...) + for _, width := range []int{60, 72, 100} { + got := helpAt(t, width, args...) + checkWrapped(t, unwrapped, got, width) + } + } + + got := helpAt(t, 72, "secret", "create") + if !strings.Contains(got, "--body - reads it from\n") && !strings.Contains(got, "--body - reads it from stdin") { + t.Errorf("--body's help should break at a space:\n%s", got) + } + lines := strings.Split(got, "\n") + for i, l := range lines { + if strings.HasPrefix(l, " --body string") { + col := strings.Index(l, "Request") + if next := lines[i+1]; ui.Hang(next) != col || strings.TrimSpace(next) == "" { + t.Errorf("--body's description should continue at column %d:\n%s\n%s", col, l, next) + } + } + } +} + +// What is there to copy stays as written, and help off a terminal is not +// wrapped at all. +func TestHelpKeepsCommandsAndPipesAsWritten(t *testing.T) { + got := helpAt(t, 40, "secret", "create") + for _, whole := range []string{" vf secret create [flags]", " vf secret create --project-id --name "} { + if !strings.Contains(got, whole+"\n") { + t.Errorf("%q should stay on one line:\n%s", whole, got) + } + } + if piped := helpAt(t, 0, "secret", "create"); !strings.Contains(piped, "--body - reads it from stdin; piped stdin is read on its own only when no body flag is given.") { + t.Errorf("help to a pipe should not be wrapped:\n%s", piped) + } +} + +// Every command's help fits a 72-column terminal, word for word. +func TestEveryCommandsHelpFits(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() + } + n := 0 + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + n++ + checkWrapped(t, render(c, 0), render(c, 72), 72) + for _, sub := range c.Commands() { + walk(sub) + } + } + walk(root) + if n < 300 { + t.Errorf("checked only %d commands", n) + } +} + +// Help inside the home prompt wraps the same way. +func TestPromptHelpBreaksBetweenWords(t *testing.T) { + saved := helpWidth + t.Cleanup(func() { helpWidth = saved }) + helpWidth = func(io.Writer) int { return 0 } + unwrapped := promptHelp(t, "secret", "create") + helpWidth = func(io.Writer) int { return 60 } + checkWrapped(t, unwrapped, promptHelp(t, "secret", "create"), 60) +} diff --git a/internal/cli/prompt_help.go b/internal/cli/prompt_help.go index 86c6e6f6..98d91374 100644 --- a/internal/cli/prompt_help.go +++ b/internal/cli/prompt_help.go @@ -30,7 +30,7 @@ func setPromptHelp(root *cobra.Command, u *ui.UI) { standard(cmd, args) return } - writePromptHelp(u, cmd.OutOrStdout(), cmd) + writeWrapped(cmd.OutOrStdout(), helpWidth(cmd.OutOrStdout()), func(w io.Writer) { writePromptHelp(u, w, cmd) }) // helpwrap.go: between words }) } diff --git a/internal/cli/root.go b/internal/cli/root.go index 8fd201c5..477bf3fb 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -247,6 +247,7 @@ func NewRootCommand() (*cobra.Command, error) { nameVFCommandsInHelp(rootCmd) // namehelp.go: vf's commands and flags, not MCP tools and API fields rootCmd.SetUsageTemplate(groupedUsageTemplate()) documentExitCodes(rootCmd) // exitcode.go: 'vf --help' lists the exit codes + wrapHelp(rootCmd) // helpwrap.go: help breaks between words at the terminal's edge return rootCmd, nil } diff --git a/internal/output/explain.go b/internal/output/explain.go index 03b0c253..f8ef0a79 100644 --- a/internal/output/explain.go +++ b/internal/output/explain.go @@ -488,7 +488,7 @@ func Render(cmd *cobra.Command, x Explanation) { if len(x.Next) > 0 { fmt.Fprintln(w, " "+u.Bold("Next:")) for _, step := range x.Next { - fmt.Fprintln(w, " "+styleCode(u, step)) + fmt.Fprintln(w, " "+u.Fit(styleCode(u, step), 4)) // ui/wrap.go: breaks between words at a terminal } } if x.Docs != "" { diff --git a/internal/ui/lines.go b/internal/ui/lines.go index 87f6a405..52709959 100644 --- a/internal/ui/lines.go +++ b/internal/ui/lines.go @@ -20,6 +20,7 @@ import ( func (u *UI) Under(lines ...string) string { var b strings.Builder for i, l := range lines { + l = u.Fit(l, 4) // wrap.go: a long line continues under itself if i == 0 { b.WriteString(" " + u.Muted(u.Glyph(Result)) + " " + l) continue diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 373835d1..05407472 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -41,18 +41,22 @@ type Options struct { // Decorate allows glyphs, and later boxes and motion: a person is // watching a terminal, not a script reading a pipe. Decorate bool + // Width is the width to wrap text at (wrap.go). Left 0, a UI that + // decorates a terminal takes the terminal's, and any other wraps nothing. + Width int } // UI renders text for one output stream. type UI struct { opts Options profile termenv.Profile + width int } // New returns a UI for w. The color depth (true color, 256 or 16) is -// detected from the environment; w only matters for that detection. +// detected from the environment, and the width to wrap at from w. func New(w io.Writer, opts Options) *UI { - return &UI{opts: opts, profile: profileFor(w, opts.Color)} + return &UI{opts: opts, profile: profileFor(w, opts.Color), width: terminalWidth(w, opts)} } // Plain returns a UI that emits neither color nor glyphs. @@ -239,6 +243,7 @@ func (u *UI) Status(kind Status, msg string) string { } return msg } + msg = u.Fit(msg, 2) // wrap.go: a long message continues under itself, not under the glyph switch kind { case StatusDone: return u.Success(Done.Symbol()) + " " + msg diff --git a/internal/ui/wrap.go b/internal/ui/wrap.go new file mode 100644 index 00000000..0a3c08b8 --- /dev/null +++ b/internal/ui/wrap.go @@ -0,0 +1,243 @@ +// This file is not generated by Speakeasy. It word-wraps the text vf prints +// for a person at a terminal. +// +// Help, hints, warnings and agent replies were written as one long line each, +// and the terminal broke them wherever its edge fell, mid-word: +// +// --body string Request body as JSON. --body - reads it f +// rom stdin; piped stdin is read on its own only when no … +// +// Here a line wider than the terminal breaks at spaces, and continues under +// its own text: a flag's description under the description, a status message +// under the message, a list item under the item, a reply under the reply. The +// breaking is flow (markdown.go), the wrapper read-prompt already uses. +// +// Only a person gets it. A UI decorating a terminal knows the terminal's +// width; anywhere else (a pipe, -o json, agent mode) its width is 0 and text +// stays exactly as written. And what a person copies still runs: a line that +// is a command is never broken, nor is a quoted command ('vf environment +// list'), a flag and its value (-o json), or a command in the accent color. + +package ui + +import ( + "io" + "regexp" + "strings" + "unicode/utf8" + + "github.com/charmbracelet/x/ansi" + "golang.org/x/term" +) + +// minRoom is the fewest columns a hanging indent leaves for text. Under it, +// a line continues under its plain indent instead. +const minRoom = 24 + +// glue joins the words of a phrase that must not break. flow breaks only at +// ASCII spaces, so it keeps a no-break space; Wrap turns it back after. +const glue = " " + +var ( + // flagTerm is a help row's flag and value name, and the gap after it: + // "-p, --project-id string ". + flagTerm = regexp.MustCompile(`^(?:-\S, )?--?[^\s,]+(?: \S+)? {2,}`) + // marker is a list item's or a status line's lead: "• ", "- ", "1. ", + // "⎿ ", "⚠ ". + marker = regexp.MustCompile(`^(?:[-*+•⎿✓✗⚠●⏺❯→›✻]|\d{1,3}[.)]) +`) + // termGap is a short term and the gap that sets its text apart, as in + // a command list or a reply: "agent ", "Agent ", "0 ". + termGap = regexp.MustCompile(`^\S+(?: \S+){0,2} {2,}`) + // flagWord is a flag as typed in prose: -o, --jq, --body-param.user. + flagWord = regexp.MustCompile(`^--?[A-Za-z][\w.-]*$`) + // sgr is a color or text-attribute escape; sgrReset ends one. + sgr = regexp.MustCompile(`\x1b\[[0-9;]*m`) + sgrReset = regexp.MustCompile(`\x1b\[0?m`) +) + +// Wrap breaks each line of text wider than width at spaces, continuing it +// under its own text (see Hang). A width of 0 or less leaves text as it is. +func Wrap(text string, width int) string { + if width <= 0 { + return text + } + lines := strings.Split(text, "\n") + for i, line := range lines { + lines[i] = WrapLine(line, width, Hang(line)) + } + return strings.Join(lines, "\n") +} + +// WrapLine breaks line, when it is wider than width, at spaces; the lines +// after the first start hang columns in. A line that is a command is left +// whole, and so is every line when width is 0 or less. +func WrapLine(line string, width, hang int) string { + if width <= 0 || ansi.StringWidth(line) <= width || IsCommand(line) { + return line + } + if width-hang < minRoom { + hang = indentOf(line) + if width-hang < minRoom { + hang = 0 + } + } + head, rest := cutAt(line, hang) + if strings.Contains(rest, glue) { + return line // a no-break space of its own would come back as a space + } + var b strings.Builder + for i, l := range flow([]mdPiece{{text: keepTogether(rest, width-hang)}}, width, hang) { + if i == 0 { + b.WriteString(head) + } else { + b.WriteString("\n" + strings.Repeat(" ", hang)) + } + b.WriteString(strings.ReplaceAll(plainText(l), glue, " ")) + } + return b.String() +} + +// Hang is the column the lines after line's first continue at: under a help +// row's description, after a list marker or status glyph, after a short +// term set apart by two spaces or more, and otherwise at line's own indent. +func Hang(line string) int { + plain := ansi.Strip(line) + text := strings.TrimLeft(plain, " ") + indent := len(plain) - len(text) + for _, lead := range []*regexp.Regexp{flagTerm, marker, termGap} { + if m := lead.FindString(text); m != "" && strings.TrimSpace(text[len(m):]) != "" { + return indent + ansi.StringWidth(m) + } + } + return indent +} + +// 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. +func IsCommand(line string) bool { + text := strings.TrimSpace(ansi.Strip(line)) + text = text[len(marker.FindString(text)):] + if !strings.HasPrefix(text, "vf ") && !strings.HasPrefix(text, "$ ") { + return false + } + for _, prose := range []string{". ", "; ", " ("} { + if strings.Contains(text, prose) { + return false + } + } + return !strings.HasSuffix(text, ".") && + (strings.Contains(text, " -") || strings.Contains(text, "<") || len(strings.Fields(text)) <= 4) +} + +// Width is how wide u wraps text: the terminal's width when u decorates one, +// and 0, for no wrapping, anywhere else. +func (u *UI) Width() int { return u.width } + +// Fit wraps s to fit the terminal after indent columns, where the caller +// prints it; the lines after the first start with indent spaces. Off a +// terminal it is s, as written. +func (u *UI) Fit(s string, indent int) string { + if u.width <= 0 { + return s + } + pad := strings.Repeat(" ", indent) + lines := strings.Split(s, "\n") + for i, line := range lines { + lines[i] = strings.TrimPrefix(WrapLine(pad+line, u.width, indent+Hang(line)), pad) + } + return strings.Join(lines, "\n"+pad) +} + +// terminalWidth is w's width when w is a terminal a person is watching, and +// 0 otherwise. +func terminalWidth(w io.Writer, opts Options) int { + if opts.Width > 0 || !opts.Decorate { + return opts.Width + } + if f, ok := w.(interface{ Fd() uintptr }); ok && term.IsTerminal(int(f.Fd())) { + return TerminalWidth(w) + } + return 0 +} + +// indentOf is how many spaces line starts with. +func indentOf(line string) int { + plain := ansi.Strip(line) + return len(plain) - len(strings.TrimLeft(plain, " ")) +} + +// cutAt splits s after its first col columns. An escape sequence goes with +// the text after it. +func cutAt(s string, col int) (head, rest string) { + w := 0 + for i := 0; i < len(s); { + if w >= col { + return s[:i], s[i:] + } + if loc := sgr.FindStringIndex(s[i:]); loc != nil && loc[0] == 0 { + i += loc[1] + continue + } + r, size := utf8.DecodeRuneInString(s[i:]) + w += ansi.StringWidth(string(r)) + i += size + } + 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). +func keepTogether(s string, room int) string { + words := strings.Split(s, " ") + 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 { + out = append(out, strings.Join(words[i:end+1], glue)) + i = end + continue + } + out = append(out, words[i]) + } + return strings.Join(out, " ") +} + +// 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]) + // 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 i + } + // A quoted command or flag. + for _, q := range []string{"'", "`"} { + inner, ok := strings.CutPrefix(plain, 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 + } + } + return i + } + // A flag and its value. + if flagWord.MatchString(plain) && i+1 < len(words) { + next := ansi.Strip(words[i+1]) + if next == "-" || (next != "" && !strings.HasPrefix(next, "-") && utf8.RuneCountInString(next) <= 20) { + return i + 1 + } + } + return i +} diff --git a/internal/ui/wrap_test.go b/internal/ui/wrap_test.go new file mode 100644 index 00000000..a2c56fb8 --- /dev/null +++ b/internal/ui/wrap_test.go @@ -0,0 +1,149 @@ +// This file is not generated by Speakeasy. It covers wrap.go. + +package ui + +import ( + "io" + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" +) + +// fitsAndKeepsWords checks that every line of got is at most width wide and +// that got says what was written, word for word, so no word was split. +func fitsAndKeepsWords(t *testing.T, written, got string, width int) { + t.Helper() + for _, line := range strings.Split(got, "\n") { + if w := ansi.StringWidth(line); w > width { + t.Errorf("line is %d columns, more than %d: %q", w, 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:\nwrote %q\n got %q", strings.Join(a, " "), strings.Join(b, " ")) + } +} + +// The terminal broke help mid-word: "--body - reads it f" / "rom stdin". +// A row now breaks at spaces, and continues under its description. +func TestAHelpRowWrapsUnderItsDescription(t *testing.T) { + row := " --body string 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." + got := Wrap(row, 72) + fitsAndKeepsWords(t, row, got, 72) + lines := strings.Split(got, "\n") + if len(lines) < 3 { + t.Fatalf("a 170-column row should take three lines at 72:\n%s", got) + } + col := strings.Index(lines[0], "Request") + for _, l := range lines[1:] { + if indentOf(l) != col { + t.Errorf("continuation should start under the description, at column %d:\n%s", col, got) + } + } + if !strings.Contains(got, "--body -") { + t.Errorf("a flag and its value should stay on one line:\n%s", got) + } +} + +// What a person copies has to run, so a quoted command, a flag and its +// value, and a line that is a command don't break. +func TestCommandsStayWhole(t *testing.T) { + text := "The environment's alias, such as main or dev; 'vf environment list' lists them, and -o json prints them for a script to read." + for width := 30; width <= 80; width++ { + got := Wrap(text, width) + fitsAndKeepsWords(t, text, got, width) + for _, whole := range []string{"'vf environment list'", "-o json"} { + if !strings.Contains(got, whole) { + t.Fatalf("at %d columns, %q was split:\n%s", width, whole, got) + } + } + } + cmd := " vf secret create --project-id 6b0ddce9886cc60fc4253ea1 --name weather_service_token --default-value abc" + if got := Wrap(cmd, 40); got != cmd { + t.Errorf("a command line should be left whole:\n%s", got) + } +} + +// A run in one color is how a terminal shows a command: it stays whole too. +func TestAColoredCommandStaysWhole(t *testing.T) { + u := New(io.Discard, Options{Color: true, Decorate: true, Width: 40}) + msg := "Sign in again with " + u.Accent("vf auth login --no-browser") + ", or set VF_TOKEN for this shell" + got := u.Fit(msg, 4) + fitsAndKeepsWords(t, msg, " "+got, 40) + if !strings.Contains(ansi.Strip(got), "vf auth login --no-browser") { + t.Errorf("the accented command was split:\n%s", ansi.Strip(got)) + } +} + +// A status line, the stale-build warning among them, continues under its +// message, not under the glyph. +func TestAStatusWrapsUnderItsMessage(t *testing.T) { + msg := "This turn ran an older build of the draft. vf has compiled it, so the next turn runs your latest edits." + got := New(io.Discard, Options{Decorate: true, Width: 70}).Status(StatusWarn, msg) + fitsAndKeepsWords(t, "⚠ "+msg, got, 70) + lines := strings.Split(got, "\n") + if len(lines) != 2 || !strings.HasPrefix(lines[1], " ") || strings.HasPrefix(lines[1], " ") { + t.Errorf("the second line should start under the message, at column 2:\n%s", got) + } +} + +// Under's lines continue under themselves, past the ⎿. +func TestUnderWrapsEachLine(t *testing.T) { + why := "The project's ID was given, but no environment with alias mian exists in it; the aliases are main and dev." + got := New(io.Discard, Options{Decorate: true, Width: 60}).Under(why, "Run 'vf environment list --project-id 6b0d' to see them") + fitsAndKeepsWords(t, "⎿ "+why+" Run 'vf environment list --project-id 6b0d' to see them", got, 60) + for _, l := range strings.Split(got, "\n")[1:] { + if indentOf(l) != 4 { + t.Errorf("every line after the first should start at column 4:\n%s", got) + } + } +} + +// Off a terminal (a pipe, -o json, agent mode) nothing is wrapped. +func TestNoWidthWrapsNothing(t *testing.T) { + long := strings.Repeat("word ", 40) + if got := New(io.Discard, Options{Decorate: true}).Status(StatusWarn, long); got != "⚠ "+long { + t.Errorf("a UI that isn't on a terminal should not wrap:\n%s", got) + } + if got := Plain().Fit(long, 2); got != long { + t.Errorf("Plain should not wrap:\n%s", got) + } + if got := Wrap(long, 0); got != long { + t.Errorf("width 0 should not wrap:\n%s", got) + } +} + +func TestHang(t *testing.T) { + for line, want := range map[string]int{ + " -p, --project-id string The project's ID": 28, + " --agent-mode Enable structured errors": 21, + " agent Configure the agent's instructions": 17, + "Agent We're open Sundays": 7, + " ⎿ The value is wrong": 4, + "• An item": 2, + "12. A step": 4, + " plain indented text": 4, + " 2 Usage error, caught before any request": 5, + "A sentence with no gap": 0, + } { + if got := Hang(line); got != want { + t.Errorf("Hang(%q) = %d, want %d", line, got, want) + } + } +} + +func TestIsCommand(t *testing.T) { + for line, want := range map[string]bool{ + " vf secret create --project-id --name ": true, + "$ vf project list -o json": true, + " vf auth login": true, + "• vf environment list --project-id 6b0d": true, + "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, + } { + if got := IsCommand(line); got != want { + t.Errorf("IsCommand(%q) = %v, want %v", line, got, want) + } + } +} From f50aea77eb66de3ddac3174f7d403991a09ddf08 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:27:12 -0500 Subject: [PATCH 24/28] fix(help): --usage describes each flag as --help does --usage printed the generator's text from the API spec, from before vf's own code ran, so it kept everything --help had fixed: 638 flags said only help="[required]", 66 "string value", 39 named a generated type, --workflow-id said "Copy its ID from voiceflow_workflow.list", and of 1648 flags only --yes had a shorthand, so -p and -e appeared nowhere. Each command's line now takes its summary, and each flag's line its help and shorthand, from the command tree as --help shows it. A hidden flag (--server) is left out, and a flag vf added (--no-interactive) is put in. The test that looks for the spec's backticks reads them from the generated schema now, since --usage no longer shows them. Found by the round-4 sweep's fix-verifier, agent-migrator and agent-builder testers. --- internal/cli/forms_test.go | 2 +- internal/cli/usagehelp_test.go | 121 ++++++++++++++++++++++++++ internal/usage/ownhelp.go | 154 ++++++++++++++++++++++++--------- test/flag-errors.test.ts | 22 +++-- 4 files changed, 253 insertions(+), 46 deletions(-) create mode 100644 internal/cli/usagehelp_test.go diff --git a/internal/cli/forms_test.go b/internal/cli/forms_test.go index 21fcb040..b3002414 100644 --- a/internal/cli/forms_test.go +++ b/internal/cli/forms_test.go @@ -76,7 +76,7 @@ func TestUsageShowsEachFormsJSON(t *testing.T) { if err := root.Execute(); err != nil { t.Fatal(err) } - if !strings.Contains(buf.String(), want) || !strings.Contains(buf.String(), `flag "--body-param " help="JSON value in one of 3 forms`) { + if !strings.Contains(buf.String(), want) || !strings.Contains(buf.String(), `flag "-b --body-param " help="JSON value in one of 3 forms`) { t.Errorf("%v lacks the forms' JSON", args) } } diff --git a/internal/cli/usagehelp_test.go b/internal/cli/usagehelp_test.go new file mode 100644 index 00000000..fa4867ea --- /dev/null +++ b/internal/cli/usagehelp_test.go @@ -0,0 +1,121 @@ +// This file is not generated by Speakeasy. It covers usage/ownhelp.go over +// the whole command tree: --usage describes each flag as --help does. + +package cli + +import ( + "bytes" + "regexp" + "strconv" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +var ( + kdlCmd = regexp.MustCompile(`^(\s*)cmd "([^"]+)" help=("(?:[^"\\]|\\.)*")`) + kdlFlag = regexp.MustCompile(`^\s*flag "(?:-(\S) )?--([^\s"]+)[^"]*" help=("(?:[^"\\]|\\.)*")`) + kdlClose = regexp.MustCompile(`^(\s*)\}$`) +) + +// usageOf runs `vf --usage` and returns what it printed. +func usageOf(t *testing.T, args ...string) string { + t.Helper() + root := testRoot(t) + var out bytes.Buffer + root.SetOut(&out) + root.SetArgs(append(args, "--usage")) + if err := root.Execute(); err != nil { + t.Fatal(err) + } + return out.String() +} + +// --usage kept the spec's text after help had moved on: 638 flags said +// help="[required]", 66 "string value", 39 named a generated type, +// `--workflow-id` "Copy its ID from voiceflow_workflow.list", and of 1648 +// flags only --yes had a shorthand. Every flag line now carries the help +// and the shorthand its flag has. +func TestUsageDescribesEachFlagAsHelpDoes(t *testing.T) { + root := testRoot(t) + schema := usageOf(t) + type open struct { + cmd *cobra.Command + indent string + } + var stack []open + checked, shorthands := 0, 0 + for _, line := range strings.Split(schema, "\n") { + if m := kdlCmd.FindStringSubmatch(line); m != nil { + parent := root + if len(stack) > 0 { + parent = stack[len(stack)-1].cmd + } + c, _, err := parent.Find([]string{m[2]}) + if err != nil || c == parent { + t.Fatalf("--usage names a command vf doesn't have: %s", line) + } + if help, _ := strconv.Unquote(m[3]); help != c.Short { + t.Errorf("%s: --usage says %q, help says %q", c.CommandPath(), help, c.Short) + } + if strings.HasSuffix(line, "{") { + stack = append(stack, open{cmd: c, indent: m[1]}) + } + continue + } + if m := kdlClose.FindStringSubmatch(line); m != nil && len(stack) > 0 && stack[len(stack)-1].indent == m[1] { + stack = stack[:len(stack)-1] + continue + } + m := kdlFlag.FindStringSubmatch(line) + if m == nil || len(stack) == 0 { + continue + } + c := stack[len(stack)-1].cmd + where := c.CommandPath() + " --" + m[2] + f := c.LocalFlags().Lookup(m[2]) + if f == nil || f.Hidden { + t.Errorf("%s: --usage lists a flag help doesn't", where) + continue + } + checked++ + if help, _ := strconv.Unquote(m[3]); help != f.Usage { + t.Errorf("%s: --usage says %q, help says %q", where, help, f.Usage) + } + if m[1] != f.Shorthand { + t.Errorf("%s: --usage gives shorthand %q, help gives %q", where, m[1], f.Shorthand) + } + if f.Shorthand != "" { + shorthands++ + } + } + if checked < 1500 || shorthands < 500 { + t.Errorf("checked %d flags, %d with a shorthand: too few to mean anything", checked, shorthands) + } + for _, stale := range []string{`help="string value"`, `help="boolean flag"`, "voiceflow_workflow.list", "_enum"} { + if strings.Contains(schema, stale) { + t.Errorf("--usage still says %s", stale) + } + } +} + +// A command's own --usage says what --help says too. +func TestACommandsUsageMatchesItsHelp(t *testing.T) { + got := usageOf(t, "agent", "add-workflow") + for _, want := range []string{ + `flag "-p --project-id " help="The project's ID: in Creator`, + `flag "-e --environment-alias " help="The environment's alias`, + "'vf workflow list'", + } { + if !strings.Contains(got, want) { + t.Errorf("agent add-workflow --usage lacks %q:\n%s", want, got) + } + } + if strings.Contains(got, "voiceflow_workflow.list") { + t.Errorf("agent add-workflow --usage names an MCP tool:\n%s", got) + } + if root := usageOf(t); !strings.Contains(root, `flag "--no-interactive" help="`) || strings.Contains(root, `flag "--server "`) { + t.Errorf("vf --usage should list --no-interactive, and not the hidden --server") + } +} diff --git a/internal/usage/ownhelp.go b/internal/usage/ownhelp.go index f28a1481..17d086cc 100644 --- a/internal/usage/ownhelp.go +++ b/internal/usage/ownhelp.go @@ -1,13 +1,20 @@ -// This file is not generated by Speakeasy. It lets a flag whose help vf -// writes at startup show that help in --usage too. +// This file is not generated by Speakeasy. It makes --usage describe each +// command and flag the way --help does. // -// The schemas in schema.go are fixed text from the API spec. A union's -// forms appear there as `{ type: string, testID: string, payload: object }`, -// and the flags that take each form (--body-param.user) not at all, so -// `--usage` couldn't say what a test turn's payload holds. flagutil writes -// each form's JSON into its flag's help (flagutil/forms.go) and marks the -// flag; when --usage is asked for, the schema takes the help from the flag, -// and gains a line for each marked flag it lacks. +// The schemas in schema.go are fixed text from the API spec, written before +// vf's own code runs. Everything that code does to a flag at startup was +// missing from --usage, though --help showed it: the descriptions it gives +// flags the spec left as "[required]", "string value" or a generated type +// name (flagutil/description.go), vf's names for the MCP tools and API +// fields the spec mentions (cli/namehelp.go), the -p and -e shorthands +// (flagutil/shorthands.go), and a union form's JSON (flagutil/forms.go). +// Counted over `vf --usage`: 638 flags said only help="[required]", and -p +// appeared nowhere. +// +// So when --usage is asked for, each command's line takes the command's +// summary, and each flag's line its help and shorthand, from the command +// tree as it stands: the flags --help shows. A flag vf hides or no longer +// has is left out, and one vf added that the schema lacks is added. package usage @@ -21,12 +28,19 @@ import ( "github.com/spf13/pflag" ) -// OwnHelp marks a flag whose help --usage takes from the flag itself. +// OwnHelp marks a flag whose help vf writes from the flag's types (a union +// form's JSON). The names in it are typed as they stand, so cli/namehelp.go +// leaves it alone. const OwnHelp = "vf:usage-own-help" -var usageFlagLine = regexp.MustCompile(`^(\s*)flag "(?:-\S )?(--[^\s"]+)`) +var ( + usageFlagLine = regexp.MustCompile(`^(\s*)flag "(?:-\S )?(--[^\s"]+)`) + usageFlagSpec = regexp.MustCompile(`^(\s*flag )"(?:-\S )?--[^\s"]+([^"]*)"`) + usageLeafLine = regexp.MustCompile(`^(\s*)cmd "([^"]+)"[^{]*$`) +) -// withOwnHelp gives schema, cmd's --usage, the help of each marked flag. +// withOwnHelp gives schema, cmd's --usage, the summaries and flags of the +// commands as they stand (see the top of this file). func withOwnHelp(cmd *cobra.Command, schema string) string { type block struct { cmd *cobra.Command @@ -34,32 +48,66 @@ func withOwnHelp(cmd *cobra.Command, schema string) string { has map[string]bool } var stack []block + // resolve is the command a cmd line names: the first line of a + // command's own schema is the command; the root's lines are its + // children. + resolve := func(name string) *cobra.Command { + switch { + case len(stack) > 0: + return subcommand(stack[len(stack)-1].cmd, name) + case cmd.HasParent(): + return cmd + } + return subcommand(cmd, name) + } + // The root's schema opens with vf's own flags, the global ones; those + // it lacks go after them, before the first command. + globals := map[string]bool{} + addGlobals := !cmd.HasParent() lines := strings.Split(schema, "\n") out := make([]string, 0, len(lines)) for _, line := range lines { + if addGlobals && len(stack) == 0 && (usageCmdLine.MatchString(line) || usageLeafLine.MatchString(line)) { + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + if !f.Hidden && f.Name != "help" && !globals["--"+f.Name] { + out = append(out, newFlagLine("", f)+" global=#true") + } + }) + addGlobals = false + } if m := usageCmdLine.FindStringSubmatch(line); m != nil { - var c *cobra.Command + c := resolve(m[2]) + if c != nil { + line = replaceHelp(line, c.Short) + } + stack = append(stack, block{cmd: c, indent: m[1], has: map[string]bool{}}) + } else if m := usageLeafLine.FindStringSubmatch(line); m != nil { + if c := resolve(m[2]); c != nil { + line = replaceHelp(line, c.Short) + } + } else if m := usageFlagLine.FindStringSubmatch(line); m != nil { + var owner *cobra.Command // nil: a block vf doesn't know, kept as written switch { case len(stack) > 0: - c = subcommand(stack[len(stack)-1].cmd, m[2]) - case cmd.HasParent(): - c = cmd // a command's own schema starts with itself - default: - c = subcommand(cmd, m[2]) // the root's starts with its children + owner = stack[len(stack)-1].cmd + stack[len(stack)-1].has[m[2]] = true + case !cmd.HasParent(): + owner = cmd // vf's own flags, the global ones + globals[m[2]] = true } - stack = append(stack, block{cmd: c, indent: m[1], has: map[string]bool{}}) - } else if m := usageFlagLine.FindStringSubmatch(line); m != nil && len(stack) > 0 { - top := stack[len(stack)-1] - top.has[m[2]] = true - if f := ownHelpFlag(top.cmd, m[2]); f != nil { - line = replaceHelp(line, f.Usage) + if owner != nil { + f := owner.LocalFlags().Lookup(strings.TrimPrefix(m[2], "--")) + if f == nil || f.Hidden { + continue + } + line = liveFlagLine(line, f) } } else if m := usageCloseLine.FindStringSubmatch(line); m != nil && len(stack) > 0 && stack[len(stack)-1].indent == m[1] { top := stack[len(stack)-1] if top.cmd != nil { top.cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { - if len(f.Annotations[OwnHelp]) > 0 && !f.Hidden && !top.has["--"+f.Name] { - out = append(out, fmt.Sprintf("%s flag %q help=%q", m[1], "--"+f.Name+" <"+strings.NewReplacer("-", "_", ".", "_").Replace(f.Name)+">", f.Usage)) + if !f.Hidden && f.Name != "help" && !top.has["--"+f.Name] { + out = append(out, newFlagLine(m[1]+" ", f)) } }) } @@ -70,6 +118,46 @@ func withOwnHelp(cmd *cobra.Command, schema string) string { return strings.Join(out, "\n") } +// liveFlagLine is a schema's flag line with f's shorthand and help. +func liveFlagLine(line string, f *pflag.Flag) string { + line = usageFlagSpec.ReplaceAllStringFunc(line, func(spec string) string { + m := usageFlagSpec.FindStringSubmatch(spec) + return m[1] + strconv.Quote(flagName(f)+m[2]) + }) + return replaceHelp(line, f.Usage) +} + +// newFlagLine is the schema line for a flag vf added that the schema lacks. +func newFlagLine(indent string, f *pflag.Flag) string { + spec := flagName(f) + kind := f.Value.Type() + if kind != "bool" { + placeholder := strings.NewReplacer("-", "_", ".", "_").Replace(f.Name) + if strings.HasSuffix(kind, "Slice") || strings.HasSuffix(kind, "Array") { + placeholder += "..." + } + spec += " <" + placeholder + ">" + } + line := fmt.Sprintf("%sflag %q help=%q", indent, spec, f.Usage) + switch { + case kind == "bool": + line += " default=#" + strconv.FormatBool(f.DefValue == "true") + case strings.HasSuffix(kind, "Slice") || strings.HasSuffix(kind, "Array"): + line += " var=#true" + case f.DefValue != "" && f.DefValue != "0": + line += fmt.Sprintf(" default=%q", f.DefValue) + } + return line +} + +// flagName is f as the schema names it: "-p --project-id", "--jq". +func flagName(f *pflag.Flag) string { + if f.Shorthand != "" && f.ShorthandDeprecated == "" { + return "-" + f.Shorthand + " --" + f.Name + } + return "--" + f.Name +} + // subcommand is parent's command named name, or nil. func subcommand(parent *cobra.Command, name string) *cobra.Command { if parent == nil { @@ -83,19 +171,7 @@ func subcommand(parent *cobra.Command, name string) *cobra.Command { return nil } -// ownHelpFlag is cmd's flag name when it is marked, or nil. -func ownHelpFlag(cmd *cobra.Command, name string) *pflag.Flag { - if cmd == nil { - return nil - } - f := cmd.LocalFlags().Lookup(strings.TrimPrefix(name, "--")) - if f == nil || len(f.Annotations[OwnHelp]) == 0 { - return nil - } - return f -} - -// replaceHelp gives a flag line help instead of the help it has. +// replaceHelp gives a schema line help instead of the help it has. func replaceHelp(line, help string) string { i := strings.Index(line, ` help="`) if i < 0 { diff --git a/test/flag-errors.test.ts b/test/flag-errors.test.ts index 338d52d7..2c7d1e17 100644 --- a/test/flag-errors.test.ts +++ b/test/flag-errors.test.ts @@ -15,6 +15,7 @@ // network. Requires: go build -o vf ./cmd/vf import { execa } from 'execa'; +import { readFile } from 'node:fs/promises'; import * as path from 'node:path'; import { beforeAll, describe, expect, it } from 'vitest'; @@ -185,15 +186,24 @@ interface BacktickedFlag { } /** - * Every flag whose description uses backticks, read from `vf --usage`: the KDL - * schema keeps each description exactly as the spec wrote it, where --help - * shows it after the CLI has rewritten it. + * The KDL schema the generator wrote for `vf` as a whole, from + * internal/usage/schema.go. It keeps each description exactly as the spec wrote + * it, where --help shows it after the CLI has rewritten it (and so does + * --usage, which takes each flag's help from the flag). */ +async function specSchema(): Promise { + const source = await readFile(path.resolve(__dirname, '..', 'internal', 'usage', 'schema.go'), 'utf8'); + const literal = source.match(/^\t"":\s+("(?:[^"\\]|\\.)*"),$/m)?.[1]; + if (literal === undefined) throw new Error('no schema for vf in internal/usage/schema.go'); + return JSON.parse(literal) as string; // the generator's Go string literal is valid JSON +} + +/** Every flag whose description, as the spec wrote it, uses backticks. */ async function backtickedFlags(): Promise { - const { stdout } = await run(['--usage']); + const schema = await specSchema(); const flags: BacktickedFlag[] = []; const blocks: Array = []; // one per open { }, null when it is not a command - for (const line of stdout.split('\n')) { + for (const line of schema.split('\n')) { if (/^\s*\}\s*$/.test(line)) { blocks.pop(); continue; @@ -218,7 +228,7 @@ describe('help shows the flag type, not a word from its description', () => { // come from the OpenAPI spec, where backticks are emphasis, so flags rendered // as `--version-param environmentAlias` with the quotes gone from the sentence. // - // The flags come from `vf --usage` rather than a hand-picked list. The list + // The flags come from the generated schema rather than a hand-picked list. The list // went stale on a regeneration: the spec dropped the backticks from its // flags' descriptions, and its checks kept passing on flags that no longer had // anything to check. From b1195e9e8f6061e6c1f2fe159d6ef5e55ce093a9 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:31:12 -0500 Subject: [PATCH 25/28] fix(help): a command's help names the global flags in one line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every --help ended with the 13 global flags in five sections, 20 to 35 lines that were the same on every page. On a 32-row terminal `vf secret --help` showed only global flags, with its subcommands scrolled away, and an agent read the same lines again for each command it looked up. A command's help now ends with one line, "-o, --jq, --dry-run, --no-interactive, … ('vf --help' lists all 13)", and 'vf --help' still lists and describes every one. Found by the round-4 sweep's human-poweruser and agent-migrator testers. --- internal/cli/globalflags.go | 55 ++++++++++++++++++++++++++++++++ internal/cli/globalflags_test.go | 45 ++++++++++++++++++++++++++ internal/cli/prompt_help_test.go | 4 +-- internal/cli/root.go | 1 + 4 files changed, 103 insertions(+), 2 deletions(-) create mode 100644 internal/cli/globalflags.go create mode 100644 internal/cli/globalflags_test.go diff --git a/internal/cli/globalflags.go b/internal/cli/globalflags.go new file mode 100644 index 00000000..99a6ef89 --- /dev/null +++ b/internal/cli/globalflags.go @@ -0,0 +1,55 @@ +// This file is not generated by Speakeasy. It keeps the global flags from +// burying a command's own help. +// +// Every command's --help ended with the 13 global flags, in five sections: +// 20 to 35 lines, the same on every page. On a 32-row terminal `vf secret +// --help` showed only global flags, its subcommands scrolled away, and an +// agent read the same lines again with each command it looked up. A +// command's help now names the most used of them in one line and points to +// 'vf --help', which still lists and describes every one. + +package cli + +import ( + "fmt" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// featuredGlobals are the global flags a command's help names, as people +// type them, in this order. +var featuredGlobals = []struct{ name, shown string }{ + {"output-format", "-o"}, + {"jq", "--jq"}, + {"dry-run", "--dry-run"}, + {"no-interactive", "--no-interactive"}, +} + +// foldGlobalFlags has every command's help name the global flags in one +// line. vf's own help lists its flags as its own, so it lists them all. +func foldGlobalFlags(*cobra.Command) { + cobra.AddTemplateFunc("groupedGlobalFlagUsages", globalFlagsLine) +} + +// globalFlagsLine is the Global Flags section of a command's help, for +// inherited, the global flags the command takes. +func globalFlagsLine(inherited *pflag.FlagSet) string { + total := 0 + inherited.VisitAll(func(f *pflag.Flag) { + if !f.Hidden { + total++ + } + }) + var named []string + for _, g := range featuredGlobals { + if f := inherited.Lookup(g.name); f != nil && !f.Hidden { + named = append(named, g.shown) + } + } + if len(named) < total { + named = append(named, "…") + } + return fmt.Sprintf("Global Flags:\n %s ('vf --help' lists all %d)", strings.Join(named, ", "), total) +} diff --git a/internal/cli/globalflags_test.go b/internal/cli/globalflags_test.go new file mode 100644 index 00000000..4d19a4e0 --- /dev/null +++ b/internal/cli/globalflags_test.go @@ -0,0 +1,45 @@ +// This file is not generated by Speakeasy. It covers globalflags.go. + +package cli + +import ( + "strings" + "testing" +) + +// The sections 'vf --help' lists the global flags in. +var globalFlagSections = []string{"Output:", "Authentication:", "Server:", "Network:", "Diagnostics:"} + +// Every --help repeated 20 to 35 lines of global flags; on a 32-row +// terminal `vf secret --help` showed nothing else. A command's help now +// names them in one line. +func TestACommandsHelpNamesTheGlobalFlagsInOneLine(t *testing.T) { + for _, args := range [][]string{{"secret"}, {"secret", "create"}, {"agent", "update"}, {"test", "run", "create-suite"}} { + got := helpAt(t, 0, args...) + for _, section := range globalFlagSections { + if strings.Contains(got, "\n"+section+"\n") { + t.Errorf("vf %s --help lists the global flags under %s:\n%s", strings.Join(args, " "), section, got) + } + } + const line = "Global Flags:\n -o, --jq, --dry-run, --no-interactive, … ('vf --help' lists all 13)\n" + if !strings.Contains(got, line) { + t.Errorf("vf %s --help should name the global flags in one line:\n%s", strings.Join(args, " "), got) + } + } + if got := helpAt(t, 0, "secret"); strings.Count(got, "\n") > 24 { + t.Errorf("vf secret --help should fit a 32-row terminal with room to spare, it has %d lines:\n%s", strings.Count(got, "\n"), got) + } +} + +// vf's own help still lists and describes every global flag. +func TestVfHelpListsEveryGlobalFlag(t *testing.T) { + got := helpAt(t, 0) + for _, want := range append(globalFlagSections, "--agent-mode", "--include-headers", "--token string", "-H, --header", "--usage") { + if !strings.Contains(got, want) { + t.Errorf("vf --help lacks %q:\n%s", want, got) + } + } + if strings.Contains(got, "Global Flags:") { + t.Errorf("vf --help should list the global flags as its own:\n%s", got) + } +} diff --git a/internal/cli/prompt_help_test.go b/internal/cli/prompt_help_test.go index a42f7bac..26a799c1 100644 --- a/internal/cli/prompt_help_test.go +++ b/internal/cli/prompt_help_test.go @@ -110,7 +110,7 @@ func TestHelpOutsideThePromptIsUnchanged(t *testing.T) { if err != nil { t.Fatal(err) } - if got := help(root, "environment", "publish"); !strings.Contains(got, "Output:") || !strings.Contains(got, "--jq string") { + if got := help(root, "environment", "publish"); !strings.Contains(got, "Global Flags:") || !strings.Contains(got, "--jq") { t.Errorf("help outside the prompt lost the global flags:\n%s", got) } @@ -119,7 +119,7 @@ func TestHelpOutsideThePromptIsUnchanged(t *testing.T) { t.Fatal(err) } output.InitAgentMode(root) - if got := help(root, "environment", "publish"); !strings.Contains(got, "Output:") || !strings.Contains(got, "--jq string") { + if got := help(root, "environment", "publish"); !strings.Contains(got, "Global Flags:") || !strings.Contains(got, "--jq") { t.Errorf("agent mode inside the prompt should get Cobra's help:\n%s", got) } } diff --git a/internal/cli/root.go b/internal/cli/root.go index 477bf3fb..e6c2c075 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -246,6 +246,7 @@ func NewRootCommand() (*cobra.Command, error) { nameVFCommandsInHelp(rootCmd) // namehelp.go: vf's commands and flags, not MCP tools and API fields rootCmd.SetUsageTemplate(groupedUsageTemplate()) + foldGlobalFlags(rootCmd) // globalflags.go: a command's help names the global flags in one line documentExitCodes(rootCmd) // exitcode.go: 'vf --help' lists the exit codes wrapHelp(rootCmd) // helpwrap.go: help breaks between words at the terminal's edge From 6ae0e1a8ad86a4a0d5a6b6a4d37f5584a68cafde Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:46:06 -0500 Subject: [PATCH 26/28] fix(help): help and messages say nothing meant for the MCP server What was wrong: text the spec and server write for the MCP server still reached vf's users. `secret create --help` said "MCP clients must omit the value", and four more commands told MCP clients what to do. `test run wait --run-ids` said "the IDs 'vf test run create' or create_many_runs returned", and its 404 named vf_test_create_many_runs: the rewrite found no command with "many" in it and left the name. Every analytics query's --version-scope named 'projectEnvironmentID', 'versionIDs' and 'environmentID', fields of the MCP tool's request that vf has no flag for. `document update` printed "voiceflow_document.get shows status PENDING": success messages were never rewritten, only errors. What changed: - flagutil/apinames.go: an MCP tool or operation that does many at once is the command that does one when vf has no other, and a command named twice in a row ("X or X") is said once. Help leaves out sentences and clauses addressed to MCP clients. - analytics/query/versionscope.go: --version-scope's help names --environment-alias, the flag vf has (one hook line in root.go). - output/messagenames.go: a result's top-level message names vf's commands and flags as an error's does, for pretty, yaml, table and toon output (one hook line in output.Result). JSON and --jq output stay as the server sent them. Tests: TestHelpSaysNothingMeantForTheMCPServer walks the whole tree; TestAResultsMessageNamesVFCommands and TestJSONKeepsTheServersMessage cover the message; TestVFNamesInMessage/TestVFNamesInHelp cover the rewrite. test/flag-errors.test.ts accepts two names said as one command and skips the description check for --version-scope, whose help vf now writes itself. --- internal/cli/analytics/query/root.go | 3 +- internal/cli/analytics/query/versionscope.go | 26 ++++++++ internal/cli/namehelp_test.go | 48 +++++++++++++++ internal/flagutil/apinames.go | 59 ++++++++++++++++-- internal/flagutil/apinames_test.go | 13 +++- internal/output/messagenames.go | 46 ++++++++++++++ internal/output/messagenames_test.go | 64 ++++++++++++++++++++ internal/output/output.go | 2 +- test/flag-errors.test.ts | 20 +++++- 9 files changed, 271 insertions(+), 10 deletions(-) create mode 100644 internal/cli/analytics/query/versionscope.go create mode 100644 internal/output/messagenames.go create mode 100644 internal/output/messagenames_test.go diff --git a/internal/cli/analytics/query/root.go b/internal/cli/analytics/query/root.go index 4449b88e..a05c6517 100644 --- a/internal/cli/analytics/query/root.go +++ b/internal/cli/analytics/query/root.go @@ -125,7 +125,8 @@ func InitQueryRoot(parent *cobra.Command) error { return err } - dateRanges(QueryCmd) // daterange.go: dates take a day, and a range is checked + dateRanges(QueryCmd) // daterange.go: dates take a day, and a range is checked + versionScopes(QueryCmd) // versionscope.go: --version-scope's help names vf's flags parent.AddCommand(QueryCmd) return nil } diff --git a/internal/cli/analytics/query/versionscope.go b/internal/cli/analytics/query/versionscope.go new file mode 100644 index 00000000..6e65aa97 --- /dev/null +++ b/internal/cli/analytics/query/versionscope.go @@ -0,0 +1,26 @@ +// This file is not generated by Speakeasy. It gives an analytics query's +// --version-scope help in vf's terms. +// +// The spec describes the field as the MCP tool takes it: "the live version +// and release history of 'projectEnvironmentID' … Takes precedence over +// 'versionIDs' and 'environmentID'". vf's queries have none of those; they +// take --environment-alias, so the help named three things a person could +// not pass. It now says what the flag covers with the flag vf has. + +package query + +import "github.com/spf13/cobra" + +// versionScopeHelp is --version-scope's help on a query that takes +// --environment-alias. +const versionScopeHelp = "Only published versions: the live version and every past release of the environment --environment-alias names, or of every environment without it. (options: published)" + +// versionScopes gives --version-scope, on each query under query that takes +// it and --environment-alias, help that names the flags vf has. +func versionScopes(query *cobra.Command) { + for _, c := range query.Commands() { + if c.Flags().Lookup("version-scope") != nil && c.Flags().Lookup("environment-alias") != nil { + ownHelp(c, "version-scope", versionScopeHelp) + } + } +} diff --git a/internal/cli/namehelp_test.go b/internal/cli/namehelp_test.go index 0a5210d3..43753a5c 100644 --- a/internal/cli/namehelp_test.go +++ b/internal/cli/namehelp_test.go @@ -60,6 +60,54 @@ func TestHelpNamesVFCommandsAndFlags(t *testing.T) { } } +// R4 #24: help still said "MCP clients must omit the value", "the IDs 'vf +// test run create' or create_many_runs returned", and that --version-scope +// "takes precedence over 'versionIDs' and 'environmentID'", fields of the +// MCP tool's request that vf has no flag for. +func TestHelpSaysNothingMeantForTheMCPServer(t *testing.T) { + root := testRoot(t) + manyOperation := regexp.MustCompile(`\b[a-z]+_many_[a-z]+\b`) + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + check := func(where, text string) { + for _, stale := range []string{"MCP client", "projectEnvironmentID", "versionIDs", "'environmentID'"} { + if strings.Contains(text, stale) { + t.Errorf("%s says %s: %s", where, stale, text) + } + } + if name := manyOperation.FindString(text); name != "" { + t.Errorf("%s names the MCP operation %s: %s", where, name, text) + } + } + check(c.CommandPath(), c.Short+"\n"+c.Long) + c.LocalFlags().VisitAll(func(f *pflag.Flag) { check(c.CommandPath()+" --"+f.Name, f.Usage) }) + } + walk(root) + + for _, tc := range []struct { + path []string + flag, want string + }{ + {[]string{"test", "run", "wait"}, "run-ids", "The runs to wait for: the IDs 'vf test run create' returned (each run's 'id'"}, + {[]string{"analytics", "query", "call-count"}, "version-scope", "every past release of the environment --environment-alias names"}, + {[]string{"secret", "create"}, "", "Create a new secret. The value, if given, is written to the vault and never returned."}, + {[]string{"mcp-server", "create"}, "", "by name with a {name} token."}, + {[]string{"phone-number", "create"}, "", "Create a new phone number."}, + } { + c := find(t, root, tc.path...) + help := c.Long + if tc.flag != "" { + help = c.Flags().Lookup(tc.flag).Usage + } + if !strings.Contains(help, tc.want) { + t.Errorf("vf %s %s: want %q in %q", strings.Join(tc.path, " "), tc.flag, tc.want, help) + } + } +} + // round-4 fix-verifier F2: the rename turned the kinds a form is named by, // goToBlock and callForward, into flag names, so the value to type in the // JSON was nowhere in help. A union's help from its types is left alone. diff --git a/internal/flagutil/apinames.go b/internal/flagutil/apinames.go index bdeb6aa2..0f29c3ca 100644 --- a/internal/flagutil/apinames.go +++ b/internal/flagutil/apinames.go @@ -19,7 +19,11 @@ // stays, as does one in a JSON shape ("{ testID: string }") or a list of // options, where it is a key or a value rather than a flag. // -// A name with no such command or flag is left as it is. +// A name with no such command or flag is left as it is. An MCP tool or +// operation that does several at once, create_many_runs, is the command that +// does one if vf has no other: `vf test run create`, said once where the text +// names both. Help also leaves out what the spec tells MCP clients ("MCP +// clients must omit the value"): vf is not one, so it only misleads. package flagutil @@ -40,8 +44,9 @@ func VFNamesInMessage(cmd *cobra.Command, message string) string { // VFNamesInHelp rewrites them in the help of cmd, or of its flag flag, with // commands in single quotes: pflag would read backticks as a placeholder. +// What the help tells MCP clients is left out. func VFNamesInHelp(cmd *cobra.Command, flag, text string) string { - return vfNames(cmd, text, "'", flag) + return withoutMCPClientNotes(vfNames(cmd, text, "'", flag)) } var ( @@ -52,6 +57,14 @@ var ( operation = regexp.MustCompile("[`']?\\b[a-z]+(?:_[a-z]+)+\\b[`']?") // apiField is a camelCase field name: environmentAlias, toolID, versionIDs. apiField = regexp.MustCompile("[`']?\\b[a-z][a-z0-9]*(?:[A-Z][A-Za-z0-9]*)+\\b[`']?") + // sameTwice is two commands joined, which may be one command twice once + // create_many_runs is `vf test run create`: "'vf test run create' or + // 'vf test run create' returned". + sameTwice = regexp.MustCompile("[`']vf [^`']+[`'](?:,? or |,? and |, )[`']vf [^`']+[`']") + // mcpClientClause and mcpClientNote are what the spec tells MCP clients: + // a clause after a semicolon, or a sentence. + mcpClientClause = regexp.MustCompile(`;[ \t]*[^.;\n]*\bMCP clients?\b[^.\n]*\.`) + mcpClientNote = regexp.MustCompile(`[ \t]*[^.\n]*\bMCP clients?\b[^.\n]*\.`) ) func vfNames(cmd *cobra.Command, text, quote, flag string) string { @@ -61,17 +74,24 @@ func vfNames(cmd *cobra.Command, text, quote, flag string) string { named := func(c *cobra.Command) string { return quote + c.CommandPath() + quote } text = renameEach(mcpTool, text, func(name string, _, _ int) (string, bool) { name = strings.TrimPrefix(strings.TrimPrefix(name, "voiceflow_"), "vf_") - if c := commandNamed(cmd.Root(), nameWords(name)); c != nil { + if c := orOne(nameWords(name), func(w []string) *cobra.Command { return commandNamed(cmd.Root(), w) }); c != nil { return named(c), true } return "", false }) text = renameEach(operation, text, func(name string, _, _ int) (string, bool) { - if c := operationOf(cmd, nameWords(name)); c != nil { + if c := orOne(nameWords(name), func(w []string) *cobra.Command { return operationOf(cmd, w) }); c != nil { return named(c), true } return "", false }) + text = sameTwice.ReplaceAllStringFunc(text, func(both string) string { + first := both[:strings.IndexByte(both[1:], both[0])+2] + if strings.HasSuffix(both, " "+first) { + return first + } + return both + }) literal := literalSpans(text) return renameEach(apiField, text, func(field string, start, end int) (string, bool) { before, after := strings.TrimRight(text[:start], "`'"), strings.TrimLeft(text[end:], "`'") @@ -129,6 +149,37 @@ func nameWords(name string) []string { return words } +// orOne is the command find finds for words or, when words do several at +// once (create many run) and it finds none, for the command that does one. +func orOne(words []string, find func([]string) *cobra.Command) *cobra.Command { + if c := find(words); c != nil { + return c + } + if i := slices.Index(words, "many"); i >= 0 { + return find(slices.Delete(slices.Clone(words), i, i+1)) + } + return nil +} + +// withoutMCPClientNotes is help without what it tells MCP clients. +func withoutMCPClientNotes(text string) string { + if !strings.Contains(text, "MCP client") { + return text + } + text = mcpClientClause.ReplaceAllString(text, ".") + var b strings.Builder + last := 0 + for _, loc := range mcpClientNote.FindAllStringIndex(text, -1) { + b.WriteString(text[last:loc[0]]) + last = loc[1] + if loc[0] == 0 || text[loc[0]-1] == '\n' { + last += len(text[last:]) - len(strings.TrimLeft(text[last:], " ")) + } + } + b.WriteString(text[last:]) + return strings.TrimSpace(b.String()) +} + // commandNamed is the command under root whose path has the words of an MCP // tool name, its group's words first (vf_now names no group, so nothing). // When no command has exactly those words, one with a word more will do if diff --git a/internal/flagutil/apinames_test.go b/internal/flagutil/apinames_test.go index 3254c4b0..357917ff 100644 --- a/internal/flagutil/apinames_test.go +++ b/internal/flagutil/apinames_test.go @@ -51,7 +51,12 @@ func TestVFNamesInMessage(t *testing.T) { {"agent patch-instructions", "oldString was not found in the current text.", "--old-string was not found in the current text."}, {"agent patch-instructions", "Without `environmentAlias` it writes main.", "Without --environment-alias it writes main."}, // Names with no command or flag stay. - {"test run wait", "vf_user_timezone, create_many_runs and testID stay.", "vf_user_timezone, create_many_runs and testID stay."}, + {"test run wait", "vf_user_timezone, create_many_widgets and testID stay.", "vf_user_timezone, create_many_widgets and testID stay."}, + // Many at once is the command that does one, said once where both + // are named: R4 #24's 404 and --run-ids help. + {"test run wait", "Pass the run IDs vf_test_create_run or vf_test_create_many_runs returned.", "Pass the run IDs `vf test run create` returned."}, + {"test run wait", "the IDs create_run or create_many_runs returned", "the IDs `vf test run create` returned"}, + {"test run wait", "Use vf_test_create_many_runs, then voiceflow_test.wait_suite.", "Use `vf test run create`, then `vf test run wait-suite`."}, // A key in JSON, a query string or a path is not a flag. {"agent patch-instructions", "Expected { oldString: string }", "Expected { oldString: string }"}, {"agent patch-instructions", "GET /x?environmentAlias=main", "GET /x?environmentAlias=main"}, @@ -76,6 +81,12 @@ func TestVFNamesInHelp(t *testing.T) { {"", "What warrants the 'maximumValue' score.", "What warrants the 'maximumValue' score."}, // Option values are values, not flags. {"", "The variant (options: versionVariant, other)", "The variant (options: versionVariant, other)"}, + // What the spec tells MCP clients is left out of help (R4 #24). + {"", "Create a new secret. The value is never returned. MCP clients must omit the value and create the secret empty.", "Create a new secret. The value is never returned."}, + {"", "Create a new phone number. MCP clients cannot call this — it belongs to the UI.", "Create a new phone number."}, + {"", "Values may reference a secret with a {name} token; MCP clients must send every header value with one.", "Values may reference a secret with a {name} token."}, + {"", "As on create, MCP clients must send a token.", ""}, + {"", "Lists MCP servers.\n\nMCP clients must page. Then read it.", "Lists MCP servers.\n\nThen read it."}, } for _, tc := range cases { if got := VFNamesInHelp(get, tc.flag, tc.in); got != tc.want { diff --git a/internal/output/messagenames.go b/internal/output/messagenames.go new file mode 100644 index 00000000..c94157c2 --- /dev/null +++ b/internal/output/messagenames.go @@ -0,0 +1,46 @@ +// This file is not generated by Speakeasy. It has a result's message name +// vf's commands and flags, as an error's does (hintfit.go). +// +// A write answers with a message written for the MCP server as much as for +// vf: `document update` said "It is being processed again, so +// voiceflow_document.get shows status PENDING", a tool vf has no command +// for, which an agent may then try to call. The message now says +// `vf document get`. JSON and --jq output stay as the server sent them. + +package output + +import ( + "reflect" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// vfNamesInResult is content with its message, a top-level string field +// named Message, naming vf's commands and cmd's flags. Content printed as +// JSON or through --jq is returned as it is. +func vfNamesInResult(cmd *cobra.Command, content any) any { + if jq, _ := flagutil.GetStringFlag(cmd, "jq"); jq != "" || resolveOutputFormat(cmd) == "json" { + return content + } + v, ok := derefToStruct(reflect.ValueOf(content)) + if !ok { + return content + } + message := v.FieldByName("Message") + if !message.IsValid() || message.Kind() != reflect.String { + return content + } + named := flagutil.VFNamesInMessage(cmd, message.String()) + if named == message.String() { + return content + } + copied := reflect.New(v.Type()) + copied.Elem().Set(v) + copied.Elem().FieldByName("Message").SetString(named) + if reflect.TypeOf(content).Kind() != reflect.Pointer { + return copied.Elem().Interface() + } + return copied.Interface() +} diff --git a/internal/output/messagenames_test.go b/internal/output/messagenames_test.go new file mode 100644 index 00000000..c1b49604 --- /dev/null +++ b/internal/output/messagenames_test.go @@ -0,0 +1,64 @@ +// This file is not generated by Speakeasy. It covers messagenames.go. + +package output + +import ( + "bytes" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/session" +) + +const updatedMessage = "Document d1 now holds the new content. It is being processed again, so voiceflow_document.get shows status PENDING until it is searchable." + +// documentUpdate is 'vf document update' beside 'vf document get', and what +// it printed for the server's answer, with flags set as given. +func documentUpdate(t *testing.T, flags ...string) string { + t.Helper() + session.Stop() + cmds := group("document") + update := &cobra.Command{Use: "update", RunE: func(*cobra.Command, []string) error { return nil }} + update.Flags().String("jq", "", "") + update.Flags().String("output-format", "pretty", "") + cmds["get"].Parent().AddCommand(update) + for i := 0; i+1 < len(flags); i += 2 { + if err := update.Flags().Set(flags[i], flags[i+1]); err != nil { + t.Fatal(err) + } + } + var out bytes.Buffer + update.SetOut(&out) + res := operations.StableDocumentControllerUpdateV2Response{StableUpdateResponse: &components.StableUpdateResponse{Message: updatedMessage}} + if err := Result(update, res); err != nil { + t.Fatal(err) + } + if res.StableUpdateResponse.Message != updatedMessage { + t.Errorf("the response itself changed: %q", res.StableUpdateResponse.Message) + } + return out.String() +} + +// `document update` said "voiceflow_document.get shows status PENDING", an +// MCP tool vf has no command for. Its message now names `vf document get`. +func TestAResultsMessageNamesVFCommands(t *testing.T) { + for _, format := range []string{"pretty", "yaml", "toon"} { + got := documentUpdate(t, "output-format", format) + if !strings.Contains(got, "`vf document get` shows status PENDING") || strings.Contains(got, "voiceflow_") { + t.Errorf("-o %s: the message should name `vf document get`:\n%s", format, got) + } + } +} + +// JSON and --jq output stay as the server sent them. +func TestJSONKeepsTheServersMessage(t *testing.T) { + for _, flags := range [][]string{{"output-format", "json"}, {"jq", ".message"}} { + if got := documentUpdate(t, flags...); !strings.Contains(got, "voiceflow_document.get") { + t.Errorf("%v: should print the message as sent:\n%s", flags, got) + } + } +} diff --git a/internal/output/output.go b/internal/output/output.go index 046f1375..7928c9df 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -223,7 +223,7 @@ func Result(cmd *cobra.Command, res interface{}) (err error) { } // === TYPED OUTPUT PATH === - content := extractResultContent(res) + content := vfNamesInResult(cmd, extractResultContent(res)) // messagenames.go: a message names vf's commands if content == nil && !includeHeaders { return nil } diff --git a/test/flag-errors.test.ts b/test/flag-errors.test.ts index 2c7d1e17..d43331fb 100644 --- a/test/flag-errors.test.ts +++ b/test/flag-errors.test.ts @@ -133,19 +133,31 @@ const API_NAME = /`?\b(?:[a-z]+(?:_[a-z]+)+(?:\.[a-z]+(?:_[a-z]+)*)?|[a-z][a-z0- * Matches a spec description as help shows it: backticks become quotes, and * an API name may have become the vf command or flag for it, as * voiceflow_workflow.list becomes 'vf workflow list' and `environmentAlias` - * --environment-alias (internal/flagutil/apinames.go). + * --environment-alias (internal/flagutil/apinames.go). Two names that are one + * command in vf are said once: "create_run or create_many_runs" is 'vf test + * run create'. */ function helpPattern(description: string): RegExp { const literal = (text: string) => squash(text.replaceAll('`', "'")).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); let pattern = ''; let last = 0; for (const name of description.matchAll(API_NAME)) { - pattern += `${literal(description.slice(last, name.index))}(?:${literal(name[0])}|'vf [a-z -]+'|--[\\w.-]+)`; + const between = description.slice(last, name.index); + const named = `(?:${literal(name[0])}|'vf [a-z -]+'|--[\\w.-]+)`; + pattern += last > 0 && /^(?:,? or |,? and |, )$/.test(between) ? `(?:${literal(between)}${named})?` : literal(between) + named; last = name.index + name[0].length; } return new RegExp(pattern + literal(description.slice(last))); } +/** + * Flags whose help vf writes itself, so --help doesn't hold the spec's text: + * the spec describes --version-scope with the MCP tool's fields + * (internal/cli/analytics/query/versionscope.go). Go's + * TestHelpSaysNothingMeantForTheMCPServer checks what they say. + */ +const OWN_HELP = new Set(['version-scope']); + /** The escapes a KDL string can hold, beyond \u{...}. */ const KDL_ESCAPES: Record = { n: '\n', r: '\r', t: '\t', b: '\b', f: '\f', s: ' ', '"': '"', '\\': '\\', '/': '/' }; @@ -242,6 +254,8 @@ describe('help shows the flag type, not a word from its description', () => { // Zero would leave the next case passing without checking anything. If the // spec really has stopped using backticks, this block can go. expect(flags.length).toBeGreaterThan(0); + // A flag vf no longer writes its own help for comes off OWN_HELP. + for (const name of OWN_HELP) expect(flags.some((flag) => flag.name === name), `--${name} is in OWN_HELP`).toBe(true); }); it('labels every one of them by its type and keeps its backticks as quotes', async () => { @@ -268,7 +282,7 @@ describe('help shows the flag type, not a word from its description', () => { if (label !== undefined && !TYPE_LABELS.has(label)) { problems.push(`${where}: labelled "${label}"`); } - if (!helpPattern(description).test(squash(entry))) { + if (!OWN_HELP.has(name) && !helpPattern(description).test(squash(entry))) { problems.push(`${where}: description changed: ${squash(entry).trim()}`); } } From 01fdce55612815ddfbaff8a8f3ef11b27b4a720d Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:56:01 -0500 Subject: [PATCH 27/28] fix(help): flags the spec left undescribed say what they are MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What was wrong: 176 flags said nothing in help but what kind of value they take. `agent update --prompt` and --instructions showed nothing; -n --name showed only "[required]" on eleven create commands; -s --settings and every tool flag said "JSON object"; --headers "list of values"; --overwrite and the other document options "true or false"; --limit and --offset nothing at all. The spec describes some of these on the SDK's fields but not on the flags. What changed: - flagutil/description.go: a JSON flag the spec described only as "JSON object", "list of values" or not at all says the JSON it takes, from the request's type: --settings is `JSON: { model?: string, maxTokens?: number, … }` (one hook line in jsonexample.go). The document options say what they do, from the spec's field docs, and that the LLM ones are deprecated and may be ignored. - cli/barehelp.go: a bare flag gets words written for its name (--name "The workflow's name.", --prompt "The global prompt, in full. 'vf agent patch-prompt' changes part of it.", --limit, --offset, --port-key, --integration, …) or else the description its namesake has on the command's counterpart: update-variant's --text from add-variant's (one hook line in root.go). Flags with no description but their kind: 176 → 27. --usage shows the same words, since it reads each flag's help. Tests: TestFlagsTheSpecLeftUndescribedSayWhatTheyAre and TestFewFlagsSayNothing (whole tree, at most 30), both failing without the change. A flag that reads its text from a file (flagutil/textfile.go) ends its help with how to: "@file reads the text from a file, and - from stdin." That ending says nothing about the flag, so it doesn't stop a description: `vf agent update --prompt` reads "The global prompt, in full. 'vf agent patch-prompt' changes part of it. @file reads the text from a file, and - from stdin." --- internal/cli/barehelp.go | 165 +++++++++++++++++++++++++++++++ internal/cli/barehelp_test.go | 108 ++++++++++++++++++++ internal/cli/root.go | 1 + internal/flagutil/description.go | 44 +++++++++ internal/flagutil/jsonexample.go | 1 + internal/flagutil/textfile.go | 11 +-- 6 files changed, 323 insertions(+), 7 deletions(-) create mode 100644 internal/cli/barehelp.go create mode 100644 internal/cli/barehelp_test.go diff --git a/internal/cli/barehelp.go b/internal/cli/barehelp.go new file mode 100644 index 00000000..7f5a73d9 --- /dev/null +++ b/internal/cli/barehelp.go @@ -0,0 +1,165 @@ +// This file is not generated by Speakeasy. It gives words to the flags the +// spec left undescribed. +// +// Help showed `-n, --name string [required]` on eleven create commands, +// and nothing at all after --prompt and --instructions on `agent update`, +// --limit and --offset on every paged read, or --text on `message +// update-variant`, whose namesake on add-variant the spec describes. A +// person had to guess; an agent sent whatever it guessed. Each such flag +// now says what it is: for the names below, words written for it, and +// otherwise the description its namesake has on the command's counterpart +// (update's from create, update-variant's from add-variant). JSON flags get +// their keys in flagutil/description.go, where the request's type is known. + +package cli + +import ( + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// describeBareFlags gives each flag the spec left undescribed, on every +// command under root, a description. +func describeBareFlags(root *cobra.Command) { + described := map[*pflag.Flag]string{} // set after the walk, so no flag copies another's new words + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + if !c.HasParent() { + return + } + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if f.Hidden || strings.Contains(f.Name, ".") || !bare(f.Usage) { + return + } + text := bareFlagHelp(c, f.Name) + if text == "" { + text = counterpartHelp(c, f.Name) + } + if text != "" { + described[f] = strings.TrimSpace(text + " " + f.Usage) + } + }) + } + walk(root) + for f, help := range described { + f.Usage = help + } +} + +// listHow is what help adds to a list flag: how to pass several values. +var listHow = []string{"Separate values with commas, repeat the flag, or pass a JSON array.", "Repeat the flag or pass a JSON array."} + +// bare is whether help usage says nothing but that the flag is required or +// how to pass a list. +func bare(help string) bool { + return core(help) == "" +} + +// 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)) + for _, how := range listHow { + help = strings.TrimSpace(strings.TrimSuffix(help, how)) + } + help = strings.TrimSpace(strings.TrimSuffix(help, "[required]")) + return strings.TrimSpace(strings.TrimPrefix(help, "[required]")) +} + +// counterpartHelp is the description flag name has on c's counterpart, the +// command that sets the same thing: create or add for update, and update +// for create or add, as add-variant is to update-variant. +func counterpartHelp(c *cobra.Command, name string) string { + verb, thing, _ := strings.Cut(c.Name(), "-") + var others []string + switch verb { + case "update": + others = []string{"create", "add"} + case "create", "add": + others = []string{"update"} + } + for _, other := range others { + if thing != "" { + other += "-" + thing + } + sibling, _, err := c.Parent().Find([]string{other}) + if err != nil || sibling == c.Parent() { + continue + } + if f := sibling.LocalFlags().Lookup(name); f != nil && !bare(f.Usage) { + return core(f.Usage) + } + } + return "" +} + +// bareFlagHelp is the description written for flag name on c. +func bareFlagHelp(c *cobra.Command, name string) string { + group := c.Parent().Name() + reads := strings.HasPrefix(c.Name(), "read-") // a page of numbered lines + // whole is how an update's text ends: it is sent in full, and the patch + // command, if there is one, changes part of it. + whole := func(it string) string { + if !strings.HasPrefix(c.Name(), "update") { + return "." + } + if p, _, err := c.Parent().Find([]string{"patch-" + name}); err == nil && p != c.Parent() { + return ", in full. '" + p.CommandPath() + "' changes part of " + it + "." + } + return ", in full." + } + switch { + case name == "name": + return "The " + thingOf(c) + "'s name." + case name == "description": + return "What the " + thingOf(c) + " is for." + case name == "prompt" && group == "agent": + return "The global prompt" + whole("it") + case name == "instructions" && group == "agent": + return "The main agent's routing instructions" + whole("them") + case name == "instructions" && group == "playbook": + return "The playbook's instructions" + whole("them") + case name == "limit" && reads: + return "The most lines to read." + case name == "offset" && reads: + return "The line to start at." + case name == "limit": + return "The most results to return." + case name == "offset": + return "How many results to skip." + case name == "exclude-id": + return "IDs to leave out of the results." + case name == "workspace-ids": + return "Only these workspaces, by ID." + case name == "integration": + return "The integration's identifier, from 'vf integration list'." + case name == "port-key": + return "The step's port, by its key: fail, for example, or a branch or path ID." + case name == "url" && group == "api-tool": + return "The URL the API tool calls." + } + return "" +} + +// thingOf is what c makes or changes: block for `workflow create-block`, +// API tool for `api-tool create`. +func thingOf(c *cobra.Command) string { + thing := c.Parent().Name() + if _, rest, ok := strings.Cut(c.Name(), "-"); ok { + thing = rest + } + words := strings.Split(thing, "-") + for i, w := range words { + if w == "api" || w == "mcp" { + words[i] = strings.ToUpper(w) + } + } + return strings.Join(words, " ") +} diff --git a/internal/cli/barehelp_test.go b/internal/cli/barehelp_test.go new file mode 100644 index 00000000..9d30c2e7 --- /dev/null +++ b/internal/cli/barehelp_test.go @@ -0,0 +1,108 @@ +// This file is not generated by Speakeasy. It covers barehelp.go and the +// JSON shapes flagutil/description.go gives undescribed JSON flags. + +package cli + +import ( + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// R4 #28: --prompt and --instructions said nothing, -n --name only +// "[required]", -s --settings "JSON object" and --overwrite "true or +// false". Each now says what it is. +func TestFlagsTheSpecLeftUndescribedSayWhatTheyAre(t *testing.T) { + root := testRoot(t) + for _, tc := range []struct { + path []string + flag, want string + }{ + {[]string{"agent", "update"}, "prompt", "The global prompt, in full. 'vf agent patch-prompt' changes part of it. " + flagutil.TextHelp}, + {[]string{"agent", "update"}, "instructions", "The main agent's routing instructions, in full. 'vf agent patch-instructions' changes part of them. " + flagutil.TextHelp}, + {[]string{"playbook", "create"}, "instructions", "The playbook's instructions. " + flagutil.TextHelp}, + {[]string{"workflow", "create"}, "name", "The workflow's name. [required]"}, + {[]string{"workflow", "update-block"}, "name", "The block's name."}, + {[]string{"api-tool", "create"}, "name", "The API tool's name. [required]"}, + {[]string{"agent", "read-prompt"}, "limit", "The most lines to read."}, + {[]string{"workflow", "link"}, "port-key", "The step's port, by its key: fail, for example, or a branch or path ID. [required]"}, + {[]string{"document", "create-text"}, "overwrite", "Replace the document with the same name or URL, if there is one. (true or false)"}, + } { + f := find(t, root, tc.path...).Flags().Lookup(tc.flag) + if f == nil || f.Usage != tc.want { + t.Errorf("vf %s --%s:\n got %q\nwant %q", strings.Join(tc.path, " "), tc.flag, helpOfFlag(f), tc.want) + } + } + + // A JSON flag says what JSON it takes. + for _, tc := range []struct { + path []string + flag string + keys []string + requiredEnd bool + }{ + {[]string{"playbook", "create"}, "settings", []string{"model?: string", "maxTokens?: number", "temperature?: number"}, false}, + {[]string{"agent", "update"}, "end-tool", []string{"enabled: boolean", "description: string"}, false}, + {[]string{"api-tool", "create"}, "headers", []string{"[{ key: string | null, value: string | null }]"}, false}, + {[]string{"workflow", "create-block"}, "steps", []string{"[{…}]"}, true}, + } { + f := find(t, root, tc.path...).Flags().Lookup(tc.flag) + if f == nil || !strings.HasPrefix(f.Usage, "JSON: ") || strings.HasSuffix(f.Usage, "[required]") != tc.requiredEnd { + t.Errorf("vf %s --%s should say the JSON it takes: %q", strings.Join(tc.path, " "), tc.flag, 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") + if !strings.HasPrefix(update.Usage, "Message text shown to the end user.") || !strings.HasPrefix(add.Usage, update.Usage) { + t.Errorf("message update-variant --text should say what add-variant's does:\n got %q\nfrom %q", update.Usage, add.Usage) + } +} + +// Of every command's flags, few still say nothing but their kind: 176 did. +func TestFewFlagsSayNothing(t *testing.T) { + var said []string + 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 !f.Hidden && !strings.Contains(f.Name, ".") && f.Name != "help" && shapeOnlyHelp(f.Usage) { + said = append(said, c.CommandPath()+" --"+f.Name) + } + }) + } + walk(testRoot(t)) + if len(said) > 30 { + t.Errorf("%d flags say nothing but their kind:\n%s", len(said), strings.Join(said, "\n")) + } +} + +// shapeOnlyHelp is whether help says nothing but what kind of value the +// flag takes, that it is required, or how to pass a list. +func shapeOnlyHelp(help string) bool { + switch core(help) { + case "", "JSON object", "true or false", "list of values": + return true + } + return false +} + +func helpOfFlag(f *pflag.Flag) string { + if f == nil { + return "" + } + return f.Usage +} diff --git a/internal/cli/root.go b/internal/cli/root.go index e6c2c075..840333fb 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -243,6 +243,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 + 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 rootCmd.SetUsageTemplate(groupedUsageTemplate()) diff --git a/internal/flagutil/description.go b/internal/flagutil/description.go index 8381ee21..ee08544b 100644 --- a/internal/flagutil/description.go +++ b/internal/flagutil/description.go @@ -43,10 +43,13 @@ package flagutil import ( + "reflect" "regexp" "strings" "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/usage" ) // flagDescription prepares an OpenAPI description for use as a pflag usage @@ -75,6 +78,16 @@ var commonFlags = map[string]string{ "timezone": "A time zone name, such as America/New_York.", "cursor": "The cursor the previous page returned, to get the next one.", "global": "The agent's own, not a playbook's.", + // A knowledge base document's options, which the spec describes on the + // SDK's fields but not on the flags: help said only "true or false". + "overwrite": "Replace the document with the same name or URL, if there is one.", + "single-chunk": "Store the whole document as one chunk, so retrieval returns it in full. One over about 30,000 characters is chunked as usual.", + "max-chunk-size": "Tokens per chunk, 500 to 1500 (a number; 1000 when left out). Smaller chunks answer faster from less context.", + "markdown-conversion": "Deprecated, and may be ignored: convert HTML to markdown before chunking. --single-chunk keeps a document whole.", + "llm-based-chunks": "Deprecated, and may be ignored: have an LLM split the content into sections by topic.", + "llm-generated-q": "Deprecated, and may be ignored: have an LLM write a question for each chunk and put it first.", + "llm-content-summarization": "Deprecated, and may be ignored: have an LLM summarize and rewrite the content for retrieval.", + "llm-prepend-context": "Deprecated, and may be ignored: have an LLM put a summary of the document's context before each chunk.", } // placeholders are what the generator writes for an undescribed field: its @@ -88,6 +101,13 @@ func describeFlag(m FlagMeta) FlagMeta { if m.Union != nil { u := *m.Union // the generated metadata is shared; leave it as it is u.TypeDescription = unionValues(u.TypeDescription) + // Errors name the values from the generated metadata, not this. + if text := commonFlags[m.FlagName]; text != "" && !u.Discriminated { + if u.TypeDescription == "true or false" { + text += " (true or false)" + } + u.TypeDescription = text + } u.Variants = append([]UnionVariantMeta(nil), u.Variants...) for i, v := range u.Variants { if generated, ok := strings.CutSuffix(v.Description, " variant as JSON"); ok && !strings.Contains(generated, " ") { @@ -146,6 +166,30 @@ func describe(name string, kind FlagKind, description string) string { return out } +// shapeOnly is what the generator writes for a JSON field it has no +// 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, … }`. +func describeShape(cmd *cobra.Command, name string, t reflect.Type) { + f := cmd.Flags().Lookup(name) + if f == nil { + return + } + text, required := strings.CutSuffix(strings.TrimSpace(f.Usage), "[required]") + shape := jsonShape(t) + if !shapeOnly[strings.TrimSpace(text)] || shape == "" { + return + } + f.Usage = "JSON: " + shape + 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 // generator writes with the enum's type name: // "JSON value (one of: boolean | StableDocumentController_createText_overwrite_enum)". diff --git a/internal/flagutil/jsonexample.go b/internal/flagutil/jsonexample.go index 86872891..cd37395d 100644 --- a/internal/flagutil/jsonexample.go +++ b/internal/flagutil/jsonexample.go @@ -42,6 +42,7 @@ func markJSONFlags(cmd *cobra.Command, t reflect.Type, meta []FlagMeta) { example := "" if ft, ok := fieldTypeAt(t, m.FieldPath); ok { example = jsonExample(ft, m.Annotations) + describeShape(cmd, m.FlagName, ft) // description.go: "JSON object" says less than its keys } _ = cmd.Flags().SetAnnotation(m.FlagName, TakesJSON, []string{example}) } diff --git a/internal/flagutil/textfile.go b/internal/flagutil/textfile.go index cbc2f3b3..e2bfdf07 100644 --- a/internal/flagutil/textfile.go +++ b/internal/flagutil/textfile.go @@ -25,8 +25,9 @@ import ( "github.com/spf13/pflag" ) -// textHelp is what a flag that reads text says about it. -const textHelp = "@file reads the text from a file, and - from stdin." +// TextHelp is what a flag that reads text says about it. A flag the spec left +// undescribed says only this until internal/cli/barehelp.go describes it. +const TextHelp = "@file reads the text from a file, and - from stdin." // textValue is a flag's value that reads @path and - before it is set. type textValue struct { @@ -55,11 +56,7 @@ func ReadsText(cmd *cobra.Command, names ...string) { continue } f.Value = &textValue{Value: f.Value, cmd: cmd, name: name} - if strings.TrimSpace(f.Usage) == "" { - f.Usage = "The text itself, @file to read it from a file, or - to read it from stdin." - } else { - f.Usage = strings.TrimSpace(f.Usage) + " " + textHelp - } + f.Usage = strings.TrimSpace(strings.TrimSpace(f.Usage) + " " + TextHelp) } } From d4d386d261bcbd0974e6fc1d21d39c41809e807c Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:28:54 -0500 Subject: [PATCH 28/28] fix(help): a list of commands says what each does, not its name again MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What was wrong: 251 summaries only restated the command's name, because the generator writes them from the operation's name. `vf conversation --help` listed "send Send" and "run-script Run script", `vf workflow --help` "get Get workflow", though each description says more ("Send message to a conversation", "Run a list of user messages as one new conversation"). A list of commands shows only the summary (R4 #45). What changed: - cli/summaries.go: where a command's Short restates its name and the first sentence of its description says more and fits on a line, that sentence is stored as the command's usage.Summary annotation. - usage/ownhelp.go: usage.Summary and usage.SummaryOf (the Summary, else Short). --usage describes each command by it. - Lists of commands use SummaryOf: Cobra's "Available Commands" (a "summary" template func in root.go), the home prompt's help (prompt_help.go) and its completion menu (prompt/complete.go), and the explorer's tree (explorer/tree.go). - Short itself is unchanged, so what is built from it stays as it was: a delete's question ("Delete prompt …?", not "Delete a prompt and its messages …?") and an error's title ("Couldn't send: …"). Summaries that only restate the name: 251 → 86 (165 now say more). Tests: TestASummarySaysMoreThanTheName (--help, --usage and the prompt's help) and TestCompleteCommandsBySummary fail without the change; TestASummaryLeavesShortAlone fails if the summary overwrites Short. usagehelp_test.go and prompt_help_test.go compare lists against SummaryOf. --- internal/cli/prompt_help.go | 3 +- internal/cli/prompt_help_test.go | 3 +- internal/cli/root.go | 6 ++ internal/cli/summaries.go | 109 +++++++++++++++++++++++++++++++ internal/cli/summaries_test.go | 103 +++++++++++++++++++++++++++++ internal/cli/usagehelp_test.go | 5 +- internal/explorer/tree.go | 3 +- internal/prompt/complete.go | 9 +-- internal/prompt/complete_test.go | 16 +++++ internal/usage/ownhelp.go | 19 +++++- 10 files changed, 265 insertions(+), 11 deletions(-) create mode 100644 internal/cli/summaries.go create mode 100644 internal/cli/summaries_test.go diff --git a/internal/cli/prompt_help.go b/internal/cli/prompt_help.go index 98d91374..91cb57eb 100644 --- a/internal/cli/prompt_help.go +++ b/internal/cli/prompt_help.go @@ -19,6 +19,7 @@ import ( "github.com/spf13/pflag" "github.com/voiceflow/cli/internal/output" "github.com/voiceflow/cli/internal/ui" + "github.com/voiceflow/cli/internal/usage" ) // setPromptHelp makes every command under root print the prompt's help, @@ -51,7 +52,7 @@ func writePromptHelp(u *ui.UI, w io.Writer, cmd *cobra.Command) { } fmt.Fprintln(w) for _, c := range children { - fmt.Fprintf(w, " %s %s\n", u.Accent(fmt.Sprintf("%-*s", width, c.Name())), u.Muted(c.Short)) + fmt.Fprintf(w, " %s %s\n", u.Accent(fmt.Sprintf("%-*s", width, c.Name())), u.Muted(usage.SummaryOf(c))) } if !cmd.HasParent() { // --help on its own is where the global flags are listed. diff --git a/internal/cli/prompt_help_test.go b/internal/cli/prompt_help_test.go index 26a799c1..04d8570e 100644 --- a/internal/cli/prompt_help_test.go +++ b/internal/cli/prompt_help_test.go @@ -11,6 +11,7 @@ import ( "github.com/spf13/cobra" "github.com/voiceflow/cli/internal/output" "github.com/voiceflow/cli/internal/ui" + "github.com/voiceflow/cli/internal/usage" ) // promptHelp runs `vf --help` with the prompt's help in place, as @@ -46,7 +47,7 @@ func TestPromptHelpForAGroupListsItsCommands(t *testing.T) { t.Errorf("help should open with what the group is for:\n%s", got) } for _, c := range helpChildren(workflow) { - if !strings.Contains(got, " "+c.Name()+" ") || !strings.Contains(got, c.Short) { + if !strings.Contains(got, " "+c.Name()+" ") || !strings.Contains(got, usage.SummaryOf(c)) { t.Errorf("help is missing %q:\n%s", c.Name(), got) } } diff --git a/internal/cli/root.go b/internal/cli/root.go index 840333fb..25381ba2 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -51,6 +51,7 @@ var rootCmd *cobra.Command func NewRootCommand() (*cobra.Command, error) { cobra.AddTemplateFunc("groupedFlagUsages", groupedFlagUsages) cobra.AddTemplateFunc("groupedGlobalFlagUsages", groupedGlobalFlagUsages) + cobra.AddTemplateFunc("summary", usage.SummaryOf) rootCmd := &cobra.Command{ Use: "vf", Short: "Build, test, and operate Voiceflow AI agents from your terminal", @@ -247,6 +248,7 @@ func NewRootCommand() (*cobra.Command, error) { nameVFCommandsInHelp(rootCmd) // namehelp.go: vf's commands and flags, not MCP tools and API fields rootCmd.SetUsageTemplate(groupedUsageTemplate()) + summarizeCommands(rootCmd) // summaries.go: a summary says more than the command's name foldGlobalFlags(rootCmd) // globalflags.go: a command's help names the global flags in one line documentExitCodes(rootCmd) // exitcode.go: 'vf --help' lists the exit codes wrapHelp(rootCmd) // helpwrap.go: help breaks between words at the terminal's edge @@ -507,5 +509,9 @@ func groupedUsageTemplate() string { replGlobal := ob + "groupedGlobalFlagUsages .InheritedFlags | trimTrailingWhitespaces" + cb result = strings.Replace(result, oldGlobal, replGlobal, 1) + // A list of commands says what each does by its summary, which may say + // more than its Short (summaries.go). + result = strings.ReplaceAll(result, ob+".Short"+cb, ob+"summary ."+cb) + return result } diff --git a/internal/cli/summaries.go b/internal/cli/summaries.go new file mode 100644 index 00000000..5661bc84 --- /dev/null +++ b/internal/cli/summaries.go @@ -0,0 +1,109 @@ +// This file is not generated by Speakeasy. It gives a command whose summary +// only restates its name the first sentence of its description instead, in +// lists of commands and --usage. +// +// The generator writes a summary from the operation's name, so 251 of vf's +// summaries said only that: `vf conversation --help` listed "send Send" +// and "run-script Run script", `vf workflow --help` "get Get workflow". +// The description beneath says more ("Send message to a conversation", "Run +// a list of user messages as one new conversation", "Get a workflow as +// blocks of steps, at most 50 blocks per page"), but a list of commands +// shows only the summary. Where the description's first sentence says +// something the name doesn't, and fits on a line, it is now the summary +// those lists, the home prompt's and --usage show (usage.Summary). The +// command's Short is unchanged: a delete's question ("Delete document …?") +// and an error's title ("Couldn't send") are built from it. + +package cli + +import ( + "regexp" + "strings" + + "github.com/spf13/cobra" + "github.com/voiceflow/cli/internal/usage" +) + +// maxSummary is the longest a description's first sentence may be to stand +// in for a summary: a summary shares its line with the command's name, and +// at a terminal wraps under itself (helpwrap.go). +const maxSummary = 100 + +// sentenceEnd is where a description's first sentence ends. +var sentenceEnd = regexp.MustCompile(`\.(?:\s|$)|\n`) + +// summaryFiller are words a summary may add to a command's name and still +// say nothing more: "Get a run by ID" for `test run get`. +var summaryFiller = map[string]bool{"a": true, "an": true, "the": true, "by": true, "id": true, "new": true, "one": true, "of": true, "its": true} + +// summarizeCommands gives each command under root whose summary restates +// its name the first sentence of its description as its usage.Summary, +// when that says more. +func summarizeCommands(root *cobra.Command) { + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + if c == root || !restatesName(c, c.Short) { + return + } + if first := firstSentence(c.Long); first != "" && !restatesName(c, first) { + if c.Annotations == nil { + c.Annotations = map[string]string{} + } + c.Annotations[usage.Summary] = first + } + } + walk(root) +} + +// clauseEnd is where a sentence's first clause ends. A comma may join the +// items of a list ("Change the name, the system text or …"), so it doesn't. +var clauseEnd = regexp.MustCompile(`; | — `) + +// firstSentence is text's first sentence, without its period, or, when +// that is longer than maxSummary, its first clause: "Create several blocks +// with their steps and links in one write" of "…; the server places them". +// It is "" when neither fits. +func firstSentence(text string) string { + text = strings.TrimSpace(text) + if loc := sentenceEnd.FindStringIndex(text); loc != nil { + text = strings.TrimSpace(text[:loc[0]]) + } + if len(text) > maxSummary { + loc := clauseEnd.FindStringIndex(text) + if loc == nil || loc[0] > maxSummary || len(strings.Fields(text[:loc[0]])) < 3 { + return "" + } + text = text[:loc[0]] + } + return text +} + +// restatesName is whether text says nothing but c's name: each of its +// words is a word of c's path, or filler. +func restatesName(c *cobra.Command, text string) bool { + name := map[string]bool{} + for _, w := range summaryWords(strings.TrimPrefix(c.CommandPath(), c.Root().Name()+" ")) { + name[w] = true + } + words := summaryWords(text) + for _, w := range words { + if !name[w] && !summaryFiller[w] { + return false + } + } + return len(words) > 0 +} + +// summaryWords are text's words, in lower case, without a plural s. +func summaryWords(text string) []string { + words := strings.FieldsFunc(strings.ToLower(text), func(r rune) bool { return (r < 'a' || r > 'z') && (r < '0' || r > '9') }) + for i, w := range words { + if len(w) > 3 { + words[i] = strings.TrimSuffix(w, "s") + } + } + return words +} diff --git a/internal/cli/summaries_test.go b/internal/cli/summaries_test.go new file mode 100644 index 00000000..a935c890 --- /dev/null +++ b/internal/cli/summaries_test.go @@ -0,0 +1,103 @@ +// This file is not generated by Speakeasy. It covers summaries.go. + +package cli + +import ( + "errors" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/usage" +) + +// R4 #45: 251 summaries restated the command's name: `vf conversation +// --help` listed "send Send" and "run-script Run script". Where the +// description says more, lists of commands now say that. +func TestASummarySaysMoreThanTheName(t *testing.T) { + root := testRoot(t) + for _, tc := range []struct { + path []string + want string + }{ + {[]string{"conversation", "send"}, "Send message to a conversation"}, + {[]string{"conversation", "run-script"}, "Run a list of user messages as one new conversation"}, + {[]string{"workflow", "get"}, "Get a workflow as blocks of steps, at most 50 blocks per page"}, + {[]string{"prompt", "update"}, "Change the name, the system text or the whole settings object of a prompt"}, + // A summary that says more than the name stays. + {[]string{"conversation", "state"}, "Read and change a user's conversation state"}, + // So does one whose description says no more. + {[]string{"test", "run", "get"}, "Get run"}, + } { + if got := usage.SummaryOf(find(t, root, tc.path...)); got != tc.want { + t.Errorf("vf %s: summary %q, want %q", strings.Join(tc.path, " "), got, tc.want) + } + } + + // Each list of commands says it: --help, --usage, the prompt's help. + if got := helpAt(t, 0, "conversation"); !strings.Contains(got, " send Send message to a conversation\n") { + t.Errorf("vf conversation --help should list send by what it does:\n%s", got) + } + if got := usageOf(t, "conversation"); !strings.Contains(got, `cmd "send" help="Send message to a conversation" {`) { + t.Errorf("vf conversation --usage should describe send by what it does:\n%s", got) + } + if got := promptHelp(t, "conversation"); !strings.Contains(got, "Send message to a conversation\n") { + t.Errorf("the prompt's help should list send by what it does:\n%s", got) + } + + restating := 0 + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + if c != root && restatesName(c, usage.SummaryOf(c)) { + restating++ + } + } + walk(root) + if restating > 100 { + t.Errorf("%d summaries still only restate their command's name", restating) + } +} + +// What is built from a command's Short, not shown in a list of it, stays +// as it was: a delete's question names what the command deletes, and an +// error's title what it was doing. +func TestASummaryLeavesShortAlone(t *testing.T) { + root := testRoot(t) + del := find(t, root, "prompt", "delete") + if usage.SummaryOf(del) != "Delete a prompt and its messages" { + t.Fatalf("vf prompt delete: summary %q; pick a command that has one", usage.SummaryOf(del)) + } + if del.Short != "Delete prompt" { + t.Errorf("vf prompt delete: Short %q, want %q", del.Short, "Delete prompt") + } + if got := deleteNoun(del); got != "prompt" { + t.Errorf("vf prompt delete asks to delete a %q, want %q", got, "prompt") + } + + send := find(t, root, "conversation", "send") + if send.Short != "Send" { + t.Errorf("vf conversation send: Short %q, want %q", send.Short, "Send") + } + if got := output.ExplainError(send, errors.New("boom")).Title; got != "Couldn't send: boom" { + t.Errorf("vf conversation send: error title %q, want %q", got, "Couldn't send: boom") + } +} + +func TestFirstSentence(t *testing.T) { + for in, want := range map[string]string{ + "Send message to a conversation.": "Send message to a conversation", + "Create a new secret. The value is never returned.": "Create a new secret", + "Rename a workflow.\n\nMore here.": "Rename a workflow", + "Create several blocks with their steps and links in one write; the server then places every one of them on the canvas for you.": "Create several blocks with their steps and links in one write", + strings.Repeat("word ", 30) + "end.": "", + "": "", + } { + if got := firstSentence(in); got != want { + t.Errorf("firstSentence(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/cli/usagehelp_test.go b/internal/cli/usagehelp_test.go index fa4867ea..aa834a48 100644 --- a/internal/cli/usagehelp_test.go +++ b/internal/cli/usagehelp_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/spf13/cobra" + "github.com/voiceflow/cli/internal/usage" ) var ( @@ -56,8 +57,8 @@ func TestUsageDescribesEachFlagAsHelpDoes(t *testing.T) { if err != nil || c == parent { t.Fatalf("--usage names a command vf doesn't have: %s", line) } - if help, _ := strconv.Unquote(m[3]); help != c.Short { - t.Errorf("%s: --usage says %q, help says %q", c.CommandPath(), help, c.Short) + if help, _ := strconv.Unquote(m[3]); help != usage.SummaryOf(c) { + t.Errorf("%s: --usage says %q, help says %q", c.CommandPath(), help, usage.SummaryOf(c)) } if strings.HasSuffix(line, "{") { stack = append(stack, open{cmd: c, indent: m[1]}) diff --git a/internal/explorer/tree.go b/internal/explorer/tree.go index 15b2bea3..aa2efcfd 100644 --- a/internal/explorer/tree.go +++ b/internal/explorer/tree.go @@ -9,6 +9,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/pflag" + "github.com/voiceflow/cli/internal/usage" ) // CommandNode represents a single item in the explorer tree. @@ -60,7 +61,7 @@ func buildNode(cmd *cobra.Command) CommandNode { node := CommandNode{ Name: cmd.Name(), FullPath: trimRootPath(cmd.CommandPath()), - Description: cmd.Short, + Description: usage.SummaryOf(cmd), LongDesc: cmd.Long, Example: cmd.Example, } diff --git a/internal/prompt/complete.go b/internal/prompt/complete.go index d96e5bfe..570f89ea 100644 --- a/internal/prompt/complete.go +++ b/internal/prompt/complete.go @@ -14,6 +14,7 @@ import ( "github.com/voiceflow/cli/internal/flagutil" "github.com/voiceflow/cli/internal/ui" + "github.com/voiceflow/cli/internal/usage" ) // Suggestion is one row of the menu. @@ -138,7 +139,7 @@ func subcommands(root, cmd *cobra.Command, partial token, cmdStart int, extra [] p := partial.text var prefix, contains []Suggestion for _, child := range visibleChildren(cmd) { - s := Suggestion{Label: child.Name(), Detail: child.Short, Group: hasSubcommands(child), From: partial.start} + s := Suggestion{Label: child.Name(), Detail: usage.SummaryOf(child), Group: hasSubcommands(child), From: partial.start} switch { case strings.HasPrefix(child.Name(), p) || hasAliasPrefix(child, p): prefix = append(prefix, s) @@ -173,7 +174,7 @@ func subcommands(root, cmd *cobra.Command, partial token, cmdStart int, extra [] } for _, word := range strings.Fields(path)[1:] { if strings.HasPrefix(word, p) { - deep = append(deep, Suggestion{Label: path, Detail: c.Short, Group: hasSubcommands(c), From: cmdStart}) + deep = append(deep, Suggestion{Label: path, Detail: usage.SummaryOf(c), Group: hasSubcommands(c), From: cmdStart}) return } } @@ -187,12 +188,12 @@ func subcommands(root, cmd *cobra.Command, partial token, cmdStart int, extra [] if len(out) == 0 && len(p) >= fuzzyMin { var cands []fuzzyCand for _, child := range visibleChildren(cmd) { - cands = append(cands, fuzzyCand{Suggestion{Label: child.Name(), Detail: child.Short, Group: hasSubcommands(child), From: partial.start}, 0}) + cands = append(cands, fuzzyCand{Suggestion{Label: child.Name(), Detail: usage.SummaryOf(child), Group: hasSubcommands(child), From: partial.start}, 0}) } if cmd == root && len(p) >= deepSearchMin { walk(root, func(c *cobra.Command, path string) { if strings.Contains(path, " ") { - cands = append(cands, fuzzyCand{Suggestion{Label: path, Detail: c.Short, Group: hasSubcommands(c), From: cmdStart}, 0}) + cands = append(cands, fuzzyCand{Suggestion{Label: path, Detail: usage.SummaryOf(c), Group: hasSubcommands(c), From: cmdStart}, 0}) } }) } diff --git a/internal/prompt/complete_test.go b/internal/prompt/complete_test.go index 5e4b4348..501ae579 100644 --- a/internal/prompt/complete_test.go +++ b/internal/prompt/complete_test.go @@ -11,6 +11,7 @@ import ( "github.com/voiceflow/cli/internal/flagutil" "github.com/voiceflow/cli/internal/ui" + "github.com/voiceflow/cli/internal/usage" ) // tree is a small command tree shaped like vf's: groups with operations @@ -308,3 +309,18 @@ func TestAStandInLeadsTheFlagsItGives(t *testing.T) { t.Errorf("with --action given: %v, want %v", got, rest) } } + +// R4 #45: the home prompt lists a command by its summary (usage.Summary) +// when one says more than its Short. +func TestCompleteCommandsBySummary(t *testing.T) { + root := tree() + get, _, _ := root.Find([]string{"project", "get"}) + get.Annotations = map[string]string{usage.Summary: "Get a project by ID, with its settings"} + got := map[string]string{} + for _, s := range Commands(root, nil)("project ") { + got[s.Label] = s.Detail + } + if got["get"] != "Get a project by ID, with its settings" || got["list"] != "List projects" { + t.Errorf("project's commands are listed as %q", got) + } +} diff --git a/internal/usage/ownhelp.go b/internal/usage/ownhelp.go index 17d086cc..759da63f 100644 --- a/internal/usage/ownhelp.go +++ b/internal/usage/ownhelp.go @@ -33,6 +33,21 @@ import ( // leaves it alone. const OwnHelp = "vf:usage-own-help" +// Summary marks a command whose Short only restates its name ("Send") with +// what lists of commands and --usage say it does instead +// (cli/summaries.go). Short itself is unchanged: a delete's question and an +// error's title are built from it. +const Summary = "vf:summary" + +// SummaryOf is what a list of commands says c does: its Summary, else its +// Short. +func SummaryOf(c *cobra.Command) string { + if s := c.Annotations[Summary]; s != "" { + return s + } + return c.Short +} + var ( usageFlagLine = regexp.MustCompile(`^(\s*)flag "(?:-\S )?(--[^\s"]+)`) usageFlagSpec = regexp.MustCompile(`^(\s*flag )"(?:-\S )?--[^\s"]+([^"]*)"`) @@ -78,12 +93,12 @@ func withOwnHelp(cmd *cobra.Command, schema string) string { if m := usageCmdLine.FindStringSubmatch(line); m != nil { c := resolve(m[2]) if c != nil { - line = replaceHelp(line, c.Short) + line = replaceHelp(line, SummaryOf(c)) } stack = append(stack, block{cmd: c, indent: m[1], has: map[string]bool{}}) } else if m := usageLeafLine.FindStringSubmatch(line); m != nil { if c := resolve(m[2]); c != nil { - line = replaceHelp(line, c.Short) + line = replaceHelp(line, SummaryOf(c)) } } else if m := usageFlagLine.FindStringSubmatch(line); m != nil { var owner *cobra.Command // nil: a block vf doesn't know, kept as written