From e24f9ec724f21194142865a7d65dd643167846c6 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:13:47 -0500 Subject: [PATCH 01/25] fix(forms): a flag that gives a field another way counts as given, so update --file doesn't ask for Content MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: human-kb:F1 (R8 #4, major): `document update --document-id 6b0f095239d66675defd5bf2 --file faq/refunds.md --wait` in the home prompt skipped the Yes/No and went straight into each field: "3 optional field(s)", then Folder Id, then "Content: The whole new text of a text or markdown document. It replaces the stored text…", then Metadata. "I pressed Enter three times without knowing whether that would wipe out the file." Cause: The form decides what was given from the command's generated metadata alone (interactive.isValueResolved: the meta flag's own Changed, an env var, config). --file is a hand-written flag (document/contentfile.go) whose text becomes --content only after the form, in contentFromFile. So changesNothingYet saw an update that changed nothing, and fillOptional walked every field, Content first. The same blind spot hit a union given through one of its forms: `tool update --tool-id t1 --body-param.function '{…}'` at a terminal asked for "Body Param" as if nothing gave it, and the field left empty failed with "the JSON ends too soon", nothing sent. Change: - flagutil/standin.go: GivenAnotherWay(cmd, name) is whether flags on the line give name's value: one that stands in for it, or one of its forms or fields (--body-param.function for --body-param). - interactive.isValueResolved counts that (a one-line hook), so the form neither asks for such a field nor takes the update for an empty one. - document update's --file stands in for --content (flagutil.StandIn), as --csv does for --items. vf already refused the two together; cmdcheck now knows it too. - prompt/complete.go: a flag something stands in for stays optional in the menu when it is optional (--content isn't marked required and doesn't lead), and goes once its stand-in is typed. suggested_test.go takes only stand-ins for required flags as the way to give them. Now the replay of the tester's line asks one question, "Fill in 2 optional field(s)?" (Metadata, Folder Id), and No sends the file's text. Tests: TestDocumentUpdateByFileDoesNotAskForContent, TestAnUpdateGivenThroughAFormDoesNotAskForTheUnion, TestAnOptionalFlagStoodInForStaysOptional. --- internal/cli/document/contentfile.go | 8 +++ internal/cli/suggested_test.go | 3 + internal/flagutil/standin.go | 12 ++++ internal/interactive/fileupdate_test.go | 83 +++++++++++++++++++++++++ internal/interactive/interactive.go | 2 +- internal/interactive/optionalfields.go | 5 +- internal/prompt/complete.go | 3 + internal/prompt/complete_test.go | 28 +++++++++ 8 files changed, 142 insertions(+), 2 deletions(-) create mode 100644 internal/interactive/fileupdate_test.go diff --git a/internal/cli/document/contentfile.go b/internal/cli/document/contentfile.go index 7b6460d7..e5532631 100644 --- a/internal/cli/document/contentfile.go +++ b/internal/cli/document/contentfile.go @@ -17,6 +17,13 @@ // 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. +// +// --file stands in for --content (flagutil/standin.go). At a terminal the +// form took --file for nothing given, and walked Folder Id, then Content +// ("The whole new text…"), then Metadata, one at a time; a writer pressed +// Enter three times not knowing whether that would wipe the file's text. +// Now the form doesn't ask for Content once --file gives it, and offers the +// other fields with one question. package document @@ -45,6 +52,7 @@ const contentFileFlag = "file" 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.") + flagutil.StandIn(cmd, contentFileFlag, "content") // standin.go: a form doesn't ask for the text --file gives 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" } diff --git a/internal/cli/suggested_test.go b/internal/cli/suggested_test.go index 68c5d228..a5c34a81 100644 --- a/internal/cli/suggested_test.go +++ b/internal/cli/suggested_test.go @@ -338,6 +338,9 @@ func requiredFlags(c *cobra.Command, csv string) (required, stand []flagArg) { if len(others) == 0 || f.Hidden || flagutil.StandInFor(c, others[0]) != f.Name { return } + if g := c.Flags().Lookup(others[0]); g == nil || !isRequired(g) { + return // `document update --file` gives --content, which is optional + } stand = append(stand, flagArg{f.Name, valueFor(f, csv)}) standing = append(standing, f.Name) }) diff --git a/internal/flagutil/standin.go b/internal/flagutil/standin.go index 46456a6f..5fcbb1d3 100644 --- a/internal/flagutil/standin.go +++ b/internal/flagutil/standin.go @@ -48,6 +48,18 @@ func StoodInFor(cmd *cobra.Command, names []string, name string) bool { return false } +// GivenAnotherWay is whether flags given on cmd's line give name's value, +// though name itself wasn't given: one that stands in for it (`document +// update --file` gives --content), or one of its forms or fields +// (--body-param.function gives --body-param). A form doesn't ask for it. +func GivenAnotherWay(cmd *cobra.Command, name string) bool { + given := false + cmd.Flags().Visit(func(f *pflag.Flag) { + given = given || slices.Contains(f.Annotations[StandsFor], name) || strings.HasPrefix(f.Name, name+".") + }) + return given +} + // StandInFor is the flag that stands in for name on cmd, the first StandIn // named when several do, or "" when none does. func StandInFor(cmd *cobra.Command, name string) string { diff --git a/internal/interactive/fileupdate_test.go b/internal/interactive/fileupdate_test.go new file mode 100644 index 00000000..b1896164 --- /dev/null +++ b/internal/interactive/fileupdate_test.go @@ -0,0 +1,83 @@ +// This file is not generated by Speakeasy. It covers flags that give a +// field another way (flagutil/standin.go) in the form: `document update +// --file` gives --content, and --body-param.function gives --body-param, so +// the form neither asks for the field nor walks the fields as if nothing +// were given. + +package interactive_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/interactive" +) + +// The round-8 human-kb tester's fix of a live fact, in the home prompt: +// `document update --document-id … --file faq/refunds.md --wait`. vf went +// straight into Folder Id, then Content ("The whole new text…"), then +// Metadata, as if no file had been given. Now --file counts as the new text: +// the form doesn't ask for Content, offers the other fields with one +// question, and No sends the file's text. +func TestDocumentUpdateByFileDoesNotAskForContent(t *testing.T) { + 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 about 10 business days.\n"), 0o644); err != nil { + t.Fatal(err) + } + t.Chdir(dir) + + asked := interactive.AnswerForm(t, nil, false) + sent, said, err := inTheHomePrompt(t, `{"message":"Document updated.","document":{"id":"6b0f095239d66675defd5bf2","data":{"type":"md","name":"refunds.md"},"status":{"type":"SUCCESS"}},"status":{"type":"SUCCESS"}}`, + "document", "update", "--document-id", "6b0f095239d66675defd5bf2", "--file", "faq/refunds.md", "--wait") + if err != nil { + t.Fatalf("%v\n%s", err, said) + } + for _, a := range *asked { + if a.Flag != "" { + t.Errorf("--file gives the new text, yet the form asked for %s (%q)", a.Flag, a.Title) + } + if strings.Contains(a.Description, "Content") { + t.Errorf("--file gives the new text, yet the form offered Content: %q", a.Description) + } + } + if len(*asked) > 1 { + t.Errorf("at most one question, whether to fill in the rest; asked %+v", *asked) + } + var patched bool + for _, r := range sent.all() { + if strings.HasPrefix(r, "PATCH ") { + patched = true + if !strings.Contains(r, `"content":"Refunds take about 10 business days.\n"`) { + t.Errorf("the update should send the file's text, sent %q", r) + } + } + } + if !patched { + t.Errorf("no update was sent: %q\n%s", sent.all(), said) + } +} + +// The same for a union given through one of its forms: `tool update +// --body-param.function '{…}'` at a terminal asked for "Body Param" as if +// nothing gave it, and the field left empty failed the command with "the +// JSON ends too soon", nothing sent. +func TestAnUpdateGivenThroughAFormDoesNotAskForTheUnion(t *testing.T) { + asked := interactive.AnswerForm(t, nil, false) + sent, said, err := inTheHomePrompt(t, `{"message":"Tool updated."}`, + "tool", "update", "--tool-id", "t1", "--body-param.function", `{"description":"Looks up an order"}`) + if err != nil { + t.Fatalf("%v\n%s", err, said) + } + if len(*asked) > 0 { + t.Errorf("--body-param.function gives --body-param, yet the form asked %+v", *asked) + } + requests := sent.all() + if len(requests) == 0 || !strings.HasPrefix(requests[0], "PATCH ") || !strings.Contains(requests[0], `"description":"Looks up an order"`) || !strings.Contains(requests[0], `"type":"function"`) { + t.Errorf("the update should send the function form, sent %q", requests) + } +} diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go index 1c7fc6b9..57b3276a 100644 --- a/internal/interactive/interactive.go +++ b/internal/interactive/interactive.go @@ -62,7 +62,7 @@ func ShouldPrompt(cmd *cobra.Command, meta []flagutil.FlagMeta) bool { // 2. Environment variable (if FlagMeta.EnvVar is set) // 3. Config file (if FlagMeta.ConfigKey is set) func isValueResolved(cmd *cobra.Command, m flagutil.FlagMeta) bool { - if f := cmd.Flags().Lookup(m.FlagName); f != nil && f.Changed { + if f := cmd.Flags().Lookup(m.FlagName); (f != nil && f.Changed) || flagutil.GivenAnotherWay(cmd, m.FlagName) { // flagutil/standin.go: --file gives --content, --body-param.function --body-param return true } if m.EnvVar != "" { diff --git a/internal/interactive/optionalfields.go b/internal/interactive/optionalfields.go index febc24f6..6e50cfe6 100644 --- a/internal/interactive/optionalfields.go +++ b/internal/interactive/optionalfields.go @@ -135,7 +135,10 @@ func inOrder(cmd *cobra.Command, optional []fieldInfo) [][]fieldInfo { // changesNothingYet is whether cmd is an update that nothing on its line, or // in its required fields, gives a value to change: answering No to its -// optional fields could only send an empty update. +// optional fields could only send an empty update. A flag that stands in for +// a field gives it (isValueResolved): `document update --file` gives the +// new text, and walking the fields from Content on, as round 8's human-kb +// tester was, read as if vf had ignored the file. func changesNothingYet(cmd *cobra.Command, meta []flagutil.FlagMeta) bool { if cmd.Name() != "update" && !strings.HasPrefix(cmd.Name(), "update-") { return false diff --git a/internal/prompt/complete.go b/internal/prompt/complete.go index 8a2e1a8d..14b451df 100644 --- a/internal/prompt/complete.go +++ b/internal/prompt/complete.go @@ -334,6 +334,9 @@ func flagsWhere(cmd *cobra.Command, partial token, used map[string]bool, fill Fi // 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 != "" { + if !isRequired(f) { + return "", used[stand] // --content stays optional, and goes once --file is typed + } return stand, used[stand] } for _, name := range f.Annotations[flagutil.StandsFor] { diff --git a/internal/prompt/complete_test.go b/internal/prompt/complete_test.go index 501ae579..4069dee1 100644 --- a/internal/prompt/complete_test.go +++ b/internal/prompt/complete_test.go @@ -4,7 +4,9 @@ package prompt import ( "reflect" + "slices" "sort" + "strings" "testing" "github.com/spf13/cobra" @@ -310,6 +312,32 @@ func TestAStandInLeadsTheFlagsItGives(t *testing.T) { } } +// `document update --file` stands in for --content, which is optional: both +// stay plain optional flags, neither marked required nor leading, and once +// --file is typed --content isn't offered. +func TestAnOptionalFlagStoodInForStaysOptional(t *testing.T) { + root := tree() + update := &cobra.Command{Use: "update", Run: func(*cobra.Command, []string) {}} + update.Flags().String("content", "", "The whole new text") + update.Flags().String("file", "", "A file whose text replaces it") + flagutil.StandIn(update, "file", "content") + root.AddCommand(update) + complete := Commands(root, nil) + + got := complete("update ") + if want := []string{"--content", "--file"}; !reflect.DeepEqual(labels(got), want) { + t.Fatalf("got %v, want %v", labels(got), want) + } + for _, s := range got { + if s.Required || strings.HasPrefix(s.Detail, "or --") { + t.Errorf("%s is optional: %+v", s.Label, s) + } + } + if got := labels(complete("update --file faq.md --")); slices.Contains(got, "--content") { + t.Errorf("with --file given, --content is still offered: %v", got) + } +} + // 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) { From bae6212e9d59ba51fd89a91a6827ca7d292d6484 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:24:13 -0500 Subject: [PATCH 02/25] fix(forms): a file flag's path is checked before any form or request, and says where vf looked MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: human-kb:F4 and dead end task 1 (R8 #5, major): `document create-text -e main --file faq --wait`, faq a folder, came up with "Fill in 12 optional field(s)?" first, then "✗ failed to read file for --file: read faq: is a directory", without the one-file-each hint vf has for --file given twice. human-newcomer:F2: the form's File field took northwind-faq.txt, asked "Fill in 12 optional field(s)?", and only then said "✗ failed to read file for --file: open northwind-faq.txt: no such file or directory", with Next only `vf document create-text --help`. "They don't know which folder the prompt is in." Cause: Nothing looked at the path until the request was built: flagutil.buildFileField opens it in BuildRequest, after the form (interactive.PromptAndSetFlags) and its optional-fields question. The hand-written file flags were read late too: document update --file after the form (contentFromFile). The errors were os.ReadFile's, with the path as typed, and the form's File field took any text. Change: - flagutil/filepaths.go: a flag that takes a file's path is marked (ReadsFile for --file on update and --csv; ValidateMeta marks the generated create-text --file). CheckFile says what is wrong with a path: no such file, naming the full path vf looked at; a folder; or unreadable. ReadTextFile (@file, --csv, update --file, --body @file) uses it, so its errors name the full path too. - cli/filecheck.go, hooked in root.go after the placeholder check: every marked flag on the line is checked as the command starts, before any picker, form or request, exit 2. A relative path's error names the folder vf runs in. A folder given to a create says it takes one file, with the line for each of the first three files in it when the file names the document (repeatedflags.go's hint, now shared); one given to an update names a file in it. - interactive/filefield.go: the form's field for such a flag refuses a path that names no file as it's typed, with the same words, before the optional fields are offered. The required fields now go through askField like the optional ones (a one-line change in interactive.go), so a test replays them too; AnswerForm runs each field's check. Tests: TestAFolderGivenAsFileIsRefusedBeforeTheForm, TestAMissingFileIsRefusedBeforeTheFormSayingWhereVFLooked, TestTheFormRefusesAPathThatNamesNoFile, TestAFileFlagsPathIsCheckedBeforeAnythingIsSent. --- internal/cli/document/contentfile.go | 1 + internal/cli/document/tablecsv.go | 1 + internal/cli/filecheck.go | 143 +++++++++++++++++++++++ internal/cli/filecheck_test.go | 51 ++++++++ internal/cli/repeatedflags.go | 2 +- internal/cli/root.go | 1 + internal/cli/tablecsv_test.go | 2 +- internal/flagutil/filepaths.go | 155 +++++++++++++++++++++++++ internal/flagutil/forms.go | 1 + internal/flagutil/textfile.go | 29 ++--- internal/interactive/export_test.go | 13 ++- internal/interactive/filecheck_test.go | 116 ++++++++++++++++++ internal/interactive/filefield.go | 46 ++++++++ internal/interactive/interactive.go | 11 +- 14 files changed, 539 insertions(+), 33 deletions(-) create mode 100644 internal/cli/filecheck.go create mode 100644 internal/cli/filecheck_test.go create mode 100644 internal/flagutil/filepaths.go create mode 100644 internal/interactive/filecheck_test.go create mode 100644 internal/interactive/filefield.go diff --git a/internal/cli/document/contentfile.go b/internal/cli/document/contentfile.go index e5532631..67e2a112 100644 --- a/internal/cli/document/contentfile.go +++ b/internal/cli/document/contentfile.go @@ -53,6 +53,7 @@ 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.") flagutil.StandIn(cmd, contentFileFlag, "content") // standin.go: a form doesn't ask for the text --file gives + flagutil.ReadsFile(cmd, contentFileFlag) // filepaths.go: a path that names no file fails before any form 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" } diff --git a/internal/cli/document/tablecsv.go b/internal/cli/document/tablecsv.go index d84a089a..04755fd4 100644 --- a/internal/cli/document/tablecsv.go +++ b/internal/cli/document/tablecsv.go @@ -44,6 +44,7 @@ const csvHint = "--csv reads a header row of column names, then one row per item 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") + flagutil.ReadsFile(cmd, csvFlag) // filepaths.go: a path that names no file fails before any form 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" } diff --git a/internal/cli/filecheck.go b/internal/cli/filecheck.go new file mode 100644 index 00000000..6e6e6341 --- /dev/null +++ b/internal/cli/filecheck.go @@ -0,0 +1,143 @@ +// This file is not generated by Speakeasy. It checks the files a command +// line names before anything is asked or sent. +// +// `vf document create-text -e main --file faq --wait`, faq a folder, asked +// "Fill in 12 optional field(s)?" first, and only after the answer said +// "failed to read file for --file: read faq: is a directory", with no word +// that vf adds one file at a time. A file that wasn't there failed the same +// way, as "open northwind-faq.txt: no such file or directory", naming no +// folder, and Next offered only --help (round-8 sweep, human-kb:F4, +// human-newcomer:F2). The file was opened only when the request was built. +// +// Now each flag that takes a file's path (flagutil/filepaths.go) is checked +// as the command starts, before any form, picker or request, exit 2. The +// error gives the full path vf looked at, and for a relative path the +// folder vf runs in. A folder given to a create says the command takes one +// file, and, when the file names the document, gives the line for each of +// the first few files in it, each runnable as written; one given to an +// update names a file in it. + +package cli + +import ( + "errors" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/usage" +) + +// checkFiles has every command under root check the files its line names, +// once root's own start has run. +func checkFiles(root *cobra.Command) { + pre := root.PersistentPreRunE + root.PersistentPreRunE = func(cmd *cobra.Command, args []string) error { + if pre != nil { + if err := pre(cmd, args); err != nil { + return err + } + } + if usage.UsageRequested(cmd) { + return nil + } + return filesGiven(cmd) + } +} + +// filesGiven reports the first file flag on cmd's line whose path names no +// file vf can read, or nil. +func filesGiven(cmd *cobra.Command) error { + var problem error + var flag string + cmd.Flags().Visit(func(f *pflag.Flag) { + if problem != nil || !flagutil.IsFileFlag(f) { + return + } + for _, path := range flagutil.PathsIn(f, f.Value.String()) { + if err := flagutil.CheckFile(path, "--"+f.Name); err != nil { + problem, flag = err, f.Name + return + } + } + }) + if problem == nil { + return nil + } + return output.Report(cmd, explainFile(cmd, flag, problem), output.WithExitCode(problem, output.ExitUsage)) +} + +// shownFiles is how many of a folder's files get a line of their own. +const shownFiles = 3 + +// explainFile says what is wrong with the path given for flag, where vf +// looked, and what to run instead. +func explainFile(cmd *cobra.Command, flag string, err error) output.Explanation { + x := output.Explanation{Type: "invalid_flag_value", Title: upperFirst(err.Error())} + var fe *flagutil.FileError + if !errors.As(err, &fe) { + return x + } + if fe.Dir != "" { + x.Why = []string{"vf reads a path that doesn't start with / or ~/ from the folder it runs in, " + fe.Dir + "."} + } + switch { + case fe.Folder: + x.Why = append(x.Why, "vf reads one file per run, and doesn't read a folder's files. Nothing was sent.") + files := filesIn(fe.Full) + if !strings.HasPrefix(cmd.Name(), "create") { + // An update has one document to change: a line per file + // would replace its text once for each. + if len(files) > 0 { + x.Next = []string{"Give --" + flag + " one file, such as " + filepath.Join(fe.Path, files[0])} + } + return x + } + x.Next = []string{oneFileEach(cmd)} + if flagutil.FlagChanged(cmd, "name") { + return x // each line would make another document of that name + } + for _, name := range files[:min(len(files), shownFiles)] { + x.Next = append(x.Next, "`"+strings.Join(append(typedLine(cmd, flag), "--"+flag, shellWord(filepath.Join(fe.Path, name))), " ")+"`") + } + if more := len(files) - shownFiles; more > 0 { + x.Next = append(x.Next, "… and the same for the other "+strconv.Itoa(more)+" file(s) in "+fe.Path) + } + case errors.Is(fe, os.ErrNotExist): + x.Why = append(x.Why, "Nothing was sent.") + x.Next = []string{"Give --" + flag + " the full path of a file that is there"} + if fe.Dir != "" { + x.Next = []string{"Give --" + flag + " the file's path from " + fe.Dir + ", or its full path"} + } + default: + x.Why = append(x.Why, "Nothing was sent.") + } + return x +} + +// oneFileEach says cmd takes one file per run. +func oneFileEach(cmd *cobra.Command) string { + return "`" + cmd.CommandPath() + "` takes one file: run it once for each file" +} + +// filesIn are the names of the files in dir that vf could read, in order, +// leaving out hidden ones and folders. +func filesIn(dir string) []string { + entries, err := os.ReadDir(dir) + if err != nil { + return nil + } + var names []string + for _, e := range entries { + if e.Type().IsRegular() && e.Name()[0] != '.' { + names = append(names, e.Name()) + } + } + return names +} diff --git a/internal/cli/filecheck_test.go b/internal/cli/filecheck_test.go new file mode 100644 index 00000000..361f1ead --- /dev/null +++ b/internal/cli/filecheck_test.go @@ -0,0 +1,51 @@ +// This file is not generated by Speakeasy. It covers filecheck.go outside +// the home prompt: in a script and in agent mode, a folder or a missing +// file is a usage error before anything is sent, and a folder given to an +// update names one file, not a line per file. + +package cli + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +func TestAFileFlagsPathIsCheckedBeforeAnythingIsSent(t *testing.T) { + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "faq"), 0o755); err != nil { + t.Fatal(err) + } + for _, f := range []string{"accounts.md", "billing.md"} { + if err := os.WriteFile(filepath.Join(dir, "faq", f), []byte("# "+f), 0o644); err != nil { + t.Fatal(err) + } + } + t.Chdir(dir) + wd, _ := os.Getwd() + + url, requests := documentServer(t, success) + _, stderr, err := runDocument(t, url, false, "update", "-p", "p1", "-e", "main", "--document-id", "d1", "--file", "faq") + if code := output.ExitCode(err); code != output.ExitUsage || len(requests()) > 0 { + t.Errorf("exit %d, sent %v\n%s", code, requests(), stderr) + } + if !strings.Contains(stderr, "Give --file one file, such as faq/accounts.md") || strings.Contains(stderr, "run it once for each file") { + t.Errorf("an update has one document to change, so it names one file:\n%s", stderr) + } + + stdout, stderr, err := runDocument(t, url, true, "create-text", "-p", "p1", "-e", "main", "--file", "northwind-faq.txt") + var got struct { + ErrorType string `json:"error_type"` + } + _ = json.Unmarshal([]byte(stdout+stderr), &got) + if code := output.ExitCode(err); code != output.ExitUsage || len(requests()) > 0 { + t.Errorf("exit %d, sent %v\n%s%s", code, requests(), stdout, stderr) + } + if want := "There is no file " + filepath.Join(wd, "northwind-faq.txt") + " to read for --file"; !strings.Contains(stdout+stderr, want) || got.ErrorType != "invalid_flag_value" { + t.Errorf("want %q, error_type invalid_flag_value, in:\n%s%s", want, stdout, stderr) + } +} diff --git a/internal/cli/repeatedflags.go b/internal/cli/repeatedflags.go index a04a764f..6ec1880b 100644 --- a/internal/cli/repeatedflags.go +++ b/internal/cli/repeatedflags.go @@ -94,7 +94,7 @@ func (e *repeatedFlagError) explain(cmd *cobra.Command) output.Explanation { Next: []string{"Give --" + e.flag + " once, with the value you mean"}, } if e.flag == "file" { - x.Next = []string{"`" + cmd.CommandPath() + "` takes one file: run it once for each file"} + x.Next = []string{oneFileEach(cmd)} // filecheck.go } return x } diff --git a/internal/cli/root.go b/internal/cli/root.go index 2355ed54..ae703b44 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -251,6 +251,7 @@ func NewRootCommand() (*cobra.Command, error) { nameVFCommandsInHelp(rootCmd) // namehelp.go: vf's commands and flags, not MCP tools and API fields explainMentions(rootCmd) // mentions.go: help says how to mention a tool, and a /name that names one warns refusePlaceholders(rootCmd) // placeholder.go: a suggested line's is refused, not sent + checkFiles(rootCmd) // filecheck.go: a --file that names no file fails before any form 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 diff --git a/internal/cli/tablecsv_test.go b/internal/cli/tablecsv_test.go index c7b30f00..7cc552aa 100644 --- a/internal/cli/tablecsv_test.go +++ b/internal/cli/tablecsv_test.go @@ -134,7 +134,7 @@ func TestACSVThatIsntATableIsRefused(t *testing.T) { {[]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", "missing.csv"}, "/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. diff --git a/internal/flagutil/filepaths.go b/internal/flagutil/filepaths.go new file mode 100644 index 00000000..fa653686 --- /dev/null +++ b/internal/flagutil/filepaths.go @@ -0,0 +1,155 @@ +// This file is not generated by Speakeasy. It finds the file a flag names +// before anything is asked or sent, and says where vf looked. +// +// `document create-text --file faq` asked "Fill in 12 optional field(s)?" +// and only then said "read faq: is a directory". A path typed into the +// form's File field that wasn't there failed after the form too, as "open +// northwind-faq.txt: no such file or directory", which names no folder; a +// newcomer who rarely uses a terminal doesn't know which folder vf runs in +// (round-8 sweep, human-newcomer:F2, human-kb:F4). The file was opened only +// when the request was built, after every question. +// +// Now a flag that takes a file's path is marked: ReadsFile marks a +// hand-written one (document update --file, create-table --csv), and +// ValidateMeta marks the generated ones (create-text --file). CheckFile says +// what is wrong with a path: there is no such file, with the full path vf +// looked at; it is a folder; or vf can't read it. internal/cli/filecheck.go +// checks the line's file flags before any form or request, and the form +// checks a path as it's typed (interactive/filefield.go). + +package flagutil + +import ( + "errors" + "io/fs" + "os" + "path/filepath" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// readsFileKey annotates a flag whose value is a file's path: "path" for +// one, "paths" for several separated by commas (a generated file-array +// flag, each perhaps with ;fileName=). +const readsFileKey = "vf:reads-file" + +// ReadsFile marks each named flag of cmd as taking a file's path, which is +// checked before anything is asked or sent. A flag cmd doesn't have is left +// out. +func ReadsFile(cmd *cobra.Command, names ...string) { + for _, name := range names { + if cmd.Flags().Lookup(name) != nil { + _ = cmd.Flags().SetAnnotation(name, readsFileKey, []string{"path"}) + } + } +} + +// markFileFlags marks meta's file flags as ReadsFile does. +func markFileFlags(cmd *cobra.Command, meta []FlagMeta) { + for _, m := range meta { + kind := map[FlagKind]string{FlagKindFile: "path", FlagKindFileArray: "paths"}[m.Kind] + if kind != "" && cmd.Flags().Lookup(m.FlagName) != nil { + _ = cmd.Flags().SetAnnotation(m.FlagName, readsFileKey, []string{kind}) + } + } +} + +// IsFileFlag is whether f takes a file's path. +func IsFileFlag(f *pflag.Flag) bool { + return f != nil && len(f.Annotations[readsFileKey]) > 0 +} + +// PathsIn are the paths value names for file flag f: the one, or for a +// flag that takes several, each, less any ;fileName=. +func PathsIn(f *pflag.Flag, value string) []string { + value = strings.TrimSpace(value) + if value == "" { + return nil + } + if a := f.Annotations[readsFileKey]; len(a) == 0 || a[0] != "paths" { + return []string{value} + } + var paths []string + for _, entry := range strings.Split(value, ",") { + entry, _, _ = strings.Cut(strings.TrimSpace(entry), ";fileName=") + if entry != "" { + paths = append(paths, entry) + } + } + return paths +} + +// FileError is what is wrong with the path given for a flag: there is no +// such file, it is a folder, or vf can't read it. +type FileError struct { + What string // what reads it: "--file" + Path string // the path as given + Full string // the path vf looked at + Dir string // the folder a relative Path is read from; "" for a full one + Folder bool // Full is a folder + Err error // why it couldn't be read, when it isn't a folder +} + +func (e *FileError) Error() string { + switch { + case e.Folder: + return e.Full + " is a folder; " + e.What + " reads a file" + case errors.Is(e.Err, fs.ErrNotExist): + return "there is no file " + e.Full + " to read for " + e.What + } + why := e.Err.Error() + var pathErr *fs.PathError + if errors.As(e.Err, &pathErr) { + why = pathErr.Err.Error() // "permission denied", without the path again + } + return "can't read " + e.Full + " for " + e.What + ": " + why +} + +// Unwrap is the error underneath, so errors.Is(err, os.ErrNotExist) holds +// for a file that isn't there. +func (e *FileError) Unwrap() error { return e.Err } + +// CheckFile is nil when path, ~/ for the home directory, names a file vf can +// read, and a *FileError saying what is wrong otherwise. what names what +// reads it, "--file". +func CheckFile(path, what string) error { + full, dir := FullPath(path) + e := &FileError{What: what, Path: path, Full: full, Dir: dir} + info, err := os.Stat(full) + switch { + case err != nil: + e.Err = err + return e + case info.IsDir(): + e.Folder = true + return e + } + f, err := os.Open(full) + if err != nil { + e.Err = err + return e + } + _ = f.Close() + return nil +} + +// FullPath is the path vf reads for path: ~/ is the home directory, and a +// relative path is read from the working folder, which dir names ("" for a +// path that isn't relative). +func FullPath(path string) (full, dir string) { + if rest, ok := strings.CutPrefix(path, "~/"); ok { + if home, err := os.UserHomeDir(); err == nil { + return filepath.Join(home, rest), "" + } + } + if filepath.IsAbs(path) { + return filepath.Clean(path), "" + } + wd, err := os.Getwd() + if err != nil { + return path, "" + } + return filepath.Join(wd, path), wd +} diff --git a/internal/flagutil/forms.go b/internal/flagutil/forms.go index 8723f1c2..2b343a3b 100644 --- a/internal/flagutil/forms.go +++ b/internal/flagutil/forms.go @@ -50,6 +50,7 @@ func describeForms(t reflect.Type, meta []FlagMeta) { markJSONFlags(cmd, t, meta) // jsonexample.go markTrueOrFalse(cmd, meta) // truefalse.go: a bare --overwrite means true markBodyFlags(cmd, t, meta) // bodyflags.go: an update that sets none of them is refused + markFileFlags(cmd, meta) // filepaths.go: a file flag's path is checked before anything is asked for _, m := range meta { if m.Kind != FlagKindUnion || m.Union == nil || !m.Union.Discriminated || len(m.Union.Variants) == 0 { continue diff --git a/internal/flagutil/textfile.go b/internal/flagutil/textfile.go index 46090bd3..80765039 100644 --- a/internal/flagutil/textfile.go +++ b/internal/flagutil/textfile.go @@ -29,7 +29,6 @@ import ( "fmt" "io/fs" "os" - "path/filepath" "strings" "github.com/spf13/cobra" @@ -206,34 +205,20 @@ func readSecret(cmd *cobra.Command, name, value string) (string, error) { // ReadTextFile reads the file at path, ~/ for the home directory, for the // flag named by what. Its error says which file and why. +// A path that names nothing gives the full path vf looked at +// (filepaths.go), so a relative one says which folder it was read from. 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 "", 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(): - return "", fmt.Errorf("%s is a folder; %s reads a file", path, what) + if err := CheckFile(path, what); err != nil { + return "", err } - data, err := os.ReadFile(path) + full, _ := FullPath(path) + data, err := os.ReadFile(full) if err != nil { - return "", fmt.Errorf("can't read %s for %s: %w", path, what, err) + return "", &FileError{What: what, Path: path, Full: full, Err: err} } 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 } - // exampleFiles name a file each flag might read, for its errors. Any other // flag reads prompt.md. var exampleFiles = map[string]string{ diff --git a/internal/interactive/export_test.go b/internal/interactive/export_test.go index a3a779c5..7cdf734a 100644 --- a/internal/interactive/export_test.go +++ b/internal/interactive/export_test.go @@ -5,6 +5,7 @@ package interactive import ( + "fmt" "strings" "testing" @@ -13,9 +14,11 @@ import ( // Asked is one thing the form asked: a field, by its flag, with the title // and description it showed; or a question whether to fill in more, with -// Flag empty. +// Flag empty. Refused is what the field said under the answer it wouldn't +// take; the person then pressed Esc. type Asked struct { Flag, Title, Description string + Refused string } // AnswerForm runs the form as at a terminal, answering each field with @@ -39,6 +42,14 @@ func AnswerForm(t *testing.T, answers map[string]string, more bool) *[]Asked { case f.binding.strVal != nil: *f.binding.strVal = answer } + if input, ok := f.field.(*huh.Input); ok && f.binding.strVal != nil { + input.Value(f.binding.strVal) + input.Blur() // runs its check, as Enter does + if err := input.Error(); err != nil { + (*asked)[len(*asked)-1].Refused = err.Error() + return fmt.Errorf("interactive prompt: %w", huh.ErrUserAborted) + } + } return nil } askMore = func(title, desc string, _ *huh.Theme, _ int) (bool, error) { diff --git a/internal/interactive/filecheck_test.go b/internal/interactive/filecheck_test.go new file mode 100644 index 00000000..a75601b7 --- /dev/null +++ b/internal/interactive/filecheck_test.go @@ -0,0 +1,116 @@ +// This file is not generated by Speakeasy. It covers cli/filecheck.go and +// filefield.go: a file flag's path is checked before any form or request, +// and a path typed into the form is checked as it's typed. + +package interactive_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/output" +) + +// inAFolder makes a working folder holding files, by path, and moves there. +// It returns the folder's path as vf sees it. +func inAFolder(t *testing.T, files ...string) string { + t.Helper() + dir := t.TempDir() + for _, f := range files { + if err := os.MkdirAll(filepath.Join(dir, filepath.Dir(f)), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, f), []byte("# "+f+"\n"), 0o644); err != nil { + t.Fatal(err) + } + } + t.Chdir(dir) + wd, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + return wd +} + +const added = `{"document":{"id":"d1","data":{"type":"md","name":"faq.md"},"status":{"type":"SUCCESS"}}}` + +// The round-8 human-kb tester tried to upload a folder: +// `document create-text -e main --file faq --wait`. A 12-field "Fill in +// optional fields?" came up first, and only after it vf said "read faq: is a +// directory". Now the folder is refused before any question, exit 2, with +// the line to run for each file in it. +func TestAFolderGivenAsFileIsRefusedBeforeTheForm(t *testing.T) { + wd := inAFolder(t, "faq/accounts.md", "faq/billing.md", "faq/refunds.md", "faq/holiday-note.txt") + asked := interactive.AnswerForm(t, nil, false) + sent, said, err := inTheHomePrompt(t, added, "document", "create-text", "-e", "main", "--file", "faq", "--wait") + if code := output.ExitCode(err); code != output.ExitUsage { + t.Errorf("exit %d, want %d\n%s", code, output.ExitUsage, said) + } + if len(*asked) > 0 { + t.Errorf("the folder should be refused before any question, asked %+v", *asked) + } + if got := sent.all(); len(got) > 0 { + t.Errorf("nothing should be sent, sent %q", got) + } + for _, want := range []string{ + filepath.Join(wd, "faq") + " is a folder; --file reads a file", + "vf document create-text' takes one file: run it once for each file", + "vf document create-text --environment-alias main --wait --file faq/accounts.md", + "vf document create-text --environment-alias main --wait --file faq/billing.md", + "the other 1 file(s) in faq", + } { + if !strings.Contains(said, want) { + t.Errorf("want %q in:\n%s", want, said) + } + } +} + +// The round-8 newcomer's missing file, given on the line: "open +// northwind-faq.txt: no such file or directory" came after the form and +// named no folder. Now it comes first and says where vf looked. +func TestAMissingFileIsRefusedBeforeTheFormSayingWhereVFLooked(t *testing.T) { + wd := inAFolder(t, "notes.md") + asked := interactive.AnswerForm(t, nil, false) + sent, said, err := inTheHomePrompt(t, added, "document", "create-text", "--file", "northwind-faq.txt") + if code := output.ExitCode(err); code != output.ExitUsage { + t.Errorf("exit %d, want %d\n%s", code, output.ExitUsage, said) + } + if len(*asked) > 0 || len(sent.all()) > 0 { + t.Errorf("nothing should be asked or sent: asked %+v, sent %q", *asked, sent.all()) + } + for _, want := range []string{ + "There is no file " + filepath.Join(wd, "northwind-faq.txt") + " to read for --file", + "from the folder it runs in, " + wd + ".", + "Nothing was sent.", + } { + if !strings.Contains(said, want) { + t.Errorf("want %q in:\n%s", want, said) + } + } +} + +// The same file typed into the form's File field: the field says so under +// it, with the full path, before "Fill in 12 optional field(s)?". +func TestTheFormRefusesAPathThatNamesNoFile(t *testing.T) { + wd := inAFolder(t, "notes.md") + asked := interactive.AnswerForm(t, map[string]string{"file": "northwind-faq.txt"}, false) + sent, said, _ := inTheHomePrompt(t, added, "document", "create-text") + var file *interactive.Asked + for i, a := range *asked { + if a.Flag == "" { + t.Errorf("the path should be refused before the form asks %q", a.Title) + } + if a.Flag == "file" { + file = &(*asked)[i] + } + } + if file == nil || !strings.Contains(file.Refused, "there is no file "+filepath.Join(wd, "northwind-faq.txt")) { + t.Fatalf("the File field should refuse the path, asked %+v\n%s", *asked, said) + } + if got := sent.all(); len(got) > 0 { + t.Errorf("nothing should be sent, sent %q", got) + } +} diff --git a/internal/interactive/filefield.go b/internal/interactive/filefield.go new file mode 100644 index 00000000..69d9c50a --- /dev/null +++ b/internal/interactive/filefield.go @@ -0,0 +1,46 @@ +// This file is not generated by Speakeasy. It has the form refuse a path +// that names no file as it's typed, not after the form. +// +// A newcomer typed northwind-faq.txt into `document create-text`'s File +// field. The form took it, asked "Fill in 12 optional field(s)?", and only +// when the request was built said "open northwind-faq.txt: no such file or +// directory" (round-8 sweep, human-newcomer:F2). Now the field of a flag +// that takes a file's path (flagutil/filepaths.go) says what is wrong under +// it, with the full path vf looked at, and waits for another; Esc cancels. + +package interactive + +import ( + "errors" + "strings" + + "github.com/charmbracelet/huh" + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// checksFile is field, for flag m of cmd, refusing a path that names no file +// vf can read when the flag takes a file's path. +func checksFile(cmd *cobra.Command, field huh.Field, m flagutil.FlagMeta) huh.Field { + f := cmd.Flags().Lookup(m.FlagName) + input, ok := field.(*huh.Input) + if !ok || !flagutil.IsFileFlag(f) { + return field + } + return input.Validate(func(s string) error { + paths := flagutil.PathsIn(f, s) + if len(paths) == 0 { + if m.Required { + return errors.New("required") + } + return nil + } + for _, path := range paths { + if err := flagutil.CheckFile(strings.TrimSpace(path), "--"+m.FlagName); err != nil { + return err + } + } + return nil + }) +} diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go index 57b3276a..12ef4d68 100644 --- a/internal/interactive/interactive.go +++ b/internal/interactive/interactive.go @@ -164,6 +164,7 @@ func fieldsToAsk(cmd *cobra.Command, meta []flagutil.FlagMeta) (required, option continue } field, binding := buildFormField(formMeta(cmd, m)) // optionalfields.go: help's words, and what the field takes + field = checksFile(cmd, field, m) // filefield.go: a path that names no file is refused as it's typed info := fieldInfo{field: field, binding: binding, name: flagDisplayName(m)} if m.Required { required = append(required, info) @@ -274,14 +275,8 @@ func PromptAndSetFlags(cmd *cobra.Command, meta []flagutil.FlagMeta) error { // Prompt required fields, one form per field if len(required) > 0 { for _, f := range required { - form := huh.NewForm(huh.NewGroup(f.field)). - 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) + if err := askField(f, theme, width); err != nil { // optionalfields.go: its own form, Esc cancels it; a test answers it + return err } } From d739d5497c0caf96bb3644bb7b76c5cf0fea5160 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:36:22 -0500 Subject: [PATCH 03/25] feat(document): create-text takes the text itself, typed or piped in, and its form asks for the text Why: a newcomer with the FAQ in their head, not in a file, couldn't get it into the knowledge base. The menu called create-text "Upload a file as a document", the form's one field asked for a File, and the name they typed there failed after the form (round-8 sweep, R8 #3, human-newcomer:F2). Design: the API takes a document as an uploaded file, so vf makes the file. --text takes the text (@file and - as every text flag), --file - reads the file from stdin, and either is uploaded as a .txt named by --name or by the text's first words. --text stands in for --file, so the line needs one of them ("needs --text (or --file)"), and the form, given neither, asks for the text in a box that takes several lines, with the name among the optional fields. The Text field refuses an @path that names no file, and a file's name typed as the text: one that is there says to write @ before it. --text with --file, empty --text, and an empty pipe exit 2 with nothing sent. Change: document/createtextinput.go adds --text, --name and --file -, hooked into createtext.go by three one-line hooks; createtexthelp.go says "Add text or a file to the knowledge base"; flagutil/filepaths.go lets a file flag take - for stdin; interactive/filefield.go checks text fields. "/know", "/upload", "/faq" and "/text" still lead to it. Tests: createtextinput_test.go, interactive/createtext_test.go. --- internal/cli/createtexthelp_test.go | 14 +- internal/cli/createtextinput_test.go | 168 ++++++++++++++++++ internal/cli/document/createtext.go | 7 +- internal/cli/document/createtexthelp.go | 16 +- internal/cli/document/createtextinput.go | 212 +++++++++++++++++++++++ internal/flagutil/filepaths.go | 39 ++++- internal/interactive/createtext_test.go | 81 +++++++++ internal/interactive/export_test.go | 23 ++- internal/interactive/filecheck_test.go | 20 ++- internal/interactive/filefield.go | 74 +++++++- 10 files changed, 612 insertions(+), 42 deletions(-) create mode 100644 internal/cli/createtextinput_test.go create mode 100644 internal/cli/document/createtextinput.go create mode 100644 internal/interactive/createtext_test.go diff --git a/internal/cli/createtexthelp_test.go b/internal/cli/createtexthelp_test.go index ef9b14a8..8c09d656 100644 --- a/internal/cli/createtexthelp_test.go +++ b/internal/cli/createtexthelp_test.go @@ -1,5 +1,5 @@ // This file is not generated by Speakeasy. It covers -// document/createtexthelp.go: create-text says it uploads a file. +// document/createtexthelp.go: create-text says what it adds, text or a file. package cli @@ -8,16 +8,14 @@ import ( "testing" ) -func TestCreateTextSaysItUploadsAFile(t *testing.T) { +func TestCreateTextSaysWhatItAdds(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"} { + for _, want := range []string{"Add a document to the knowledge base: text you type (--text), a file (--file: text, Markdown, PDF or Word), or text piped in (--file -).", + "--overwrite true replaces", "--text 'We are closed on December 25.' --name holiday-hours"} { if !strings.Contains(help, want) { t.Errorf("missing %q in:\n%s", want, help) } @@ -27,7 +25,7 @@ func TestCreateTextSaysItUploadsAFile(t *testing.T) { 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) + if !strings.Contains(list, "Add text or a file to the knowledge base") { + t.Errorf("the command list should say create-text adds text or a file:\n%s", list) } } diff --git a/internal/cli/createtextinput_test.go b/internal/cli/createtextinput_test.go new file mode 100644 index 00000000..9a432fad --- /dev/null +++ b/internal/cli/createtextinput_test.go @@ -0,0 +1,168 @@ +// This file is not generated by Speakeasy. It covers +// document/createtextinput.go: create-text takes the text itself, typed +// (--text) or piped in (--file -), and names the document. + +package cli + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/prompt" +) + +// uploads is a fake API that keeps the body of each document it is sent. +func uploads(t *testing.T) (url string, sent func() []string) { + t.Helper() + var mu sync.Mutex + var bodies []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + mu.Lock() + bodies = append(bodies, string(body)) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + io.WriteString(w, `{"document":{"id":"d1","data":{"type":"text","name":"holiday-hours.txt","canEdit":true},"status":{"type":"PENDING"}}}`) + })) + t.Cleanup(srv.Close) + return srv.URL, func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), bodies...) + } +} + +// createTextWith runs `vf document create-text -p p1 -e main` with args, +// stdin piped in, at no terminal. +func createTextWith(t *testing.T, url, stdin 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(stdin)) + mode := "--agent-mode=false" + if agent { + mode = "--agent-mode" + } + root.SetArgs(append(append([]string{"document", "create-text", "-p", "p1", "-e", "main"}, args...), mode, "--no-interactive")) + _, err = root.ExecuteC() + return out.String(), errOut.String(), err +} + +// The round-8 newcomer had the FAQ in their head, not in a file, and +// create-text took only --file (human-newcomer:F2). --text takes the text +// itself, sent as a text file named by --name. +func TestCreateTextTakesTheTextItself(t *testing.T) { + url, sent := uploads(t) + stdout, stderr, err := createTextWith(t, url, "", false, "--text", "We are closed on December 25.", "--name", "holiday-hours") + if err != nil { + t.Fatalf("%v\n%s%s", err, stdout, stderr) + } + bodies := sent() + if len(bodies) != 1 { + t.Fatalf("want one upload, sent %q", bodies) + } + for _, want := range []string{`filename="holiday-hours.txt"`, "\r\n\r\nWe are closed on December 25.\r\n"} { + if !strings.Contains(bodies[0], want) { + t.Errorf("want %q in the upload:\n%s", want, bodies[0]) + } + } + + // Without --name, the text's first words name it. + url, sent = uploads(t) + if _, stderr, err := createTextWith(t, url, "", false, "--text", "We are closed on December 25. Our hours are 9 to 5 every other day."); err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if body := strings.Join(sent(), ""); !strings.Contains(body, `filename="We are closed on December 25. Our hours.txt"`) { + t.Errorf("the text's first words should name it:\n%s", body) + } +} + +// --file - reads the file from stdin, as `cat faq.md | vf document +// create-text --file - --name faq`. +func TestCreateTextReadsTheFileFromStdin(t *testing.T) { + url, sent := uploads(t) + if _, stderr, err := createTextWith(t, url, "# FAQ\nQ: When are you open?\n", false, "--file", "-", "--name", "faq.md"); err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + body := strings.Join(sent(), "") + for _, want := range []string{`filename="faq.md"`, "# FAQ\nQ: When are you open?\n"} { + if !strings.Contains(body, want) { + t.Errorf("want %q in the upload:\n%s", want, body) + } + } + + // An empty pipe is refused before anything is sent. + url, sent = uploads(t) + _, stderr, err := createTextWith(t, url, "", false, "--file", "-") + if code := output.ExitCode(err); code != output.ExitUsage || len(sent()) > 0 { + t.Errorf("exit %d, sent %q; want exit %d and nothing sent", code, sent(), output.ExitUsage) + } + if !strings.Contains(stderr, "stdin was empty, and --file - reads the file from it") { + t.Errorf("want why in:\n%s", stderr) + } +} + +// Given neither, it says it needs the text or a file; given both, or empty +// text, what is wrong. Nothing is sent, exit 2. +func TestCreateTextSaysWhatItNeeds(t *testing.T) { + x := runWithStdin(t, "", "document", "create-text", "-p", "p1", "-e", "main") + if !strings.Contains(explained(x), "vf document create-text needs --text (or --file)") { + t.Errorf("got:\n%s", explained(x)) + } + cases := []struct { + args []string + want string + }{ + {[]string{"--text", "hi", "--file", "createtextinput_test.go"}, "--text and --file both give the document"}, + {[]string{"--text", " "}, "--text is empty"}, + } + for _, c := range cases { + url, sent := uploads(t) + stdout, stderr, err := createTextWith(t, url, "", true, c.args...) + if code := output.ExitCode(err); code != output.ExitUsage || len(sent()) > 0 { + t.Errorf("%q: exit %d, sent %q; want exit %d and nothing sent", c.args, code, sent(), output.ExitUsage) + } + if !strings.Contains(stdout+stderr, c.want) { + t.Errorf("%q: want %q in:\n%s%s", c.args, c.want, stdout, stderr) + } + } +} + +// The menu called create-text "Upload a file as a document" (R8 #3). It +// says now that it adds text too, and "/know", "/upload", "/faq" and +// "/text" still lead to it in the home prompt. +func TestTheMenuSaysCreateTextAddsText(t *testing.T) { + root := testRoot(t) + complete := prompt.Commands(root, nil) + for _, word := range []string{"/know", "/upload", "/faq", "/text"} { + found := false + for _, s := range complete(word) { + if s.Label == "document create-text" { + found = true + if s.Detail != "Add text or a file to the knowledge base" { + t.Errorf("%q: create-text is described %q", word, s.Detail) + } + } + } + if !found { + t.Errorf("%q doesn't offer document create-text", word) + } + } +} diff --git a/internal/cli/document/createtext.go b/internal/cli/document/createtext.go index 1bbb5cda..8fdf4d2b 100644 --- a/internal/cli/document/createtext.go +++ b/internal/cli/document/createtext.go @@ -46,6 +46,7 @@ func initCreateTextCmd(parent *cobra.Command) error { flagutil.RegisterFlags(cmd, createTextCmdMeta) addWait(cmd) // docready.go: --wait waits until the document is processed describeCreateText(cmd) // createtexthelp.go: it uploads a file, not raw text + addTextInput(cmd) // createtextinput.go: --text and --name, and --file - for stdin if err := flagutil.ValidateMeta[operations.StableDocumentControllerCreateTextRequest](createTextCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create-text: %w", err) } @@ -58,12 +59,12 @@ func runCreateTextCmd(cmd *cobra.Command, args []string) error { if usage.UsageRequested(cmd) { return usage.EmitSchema(cmd, cmd.OutOrStdout()) } - if interactive.ShouldPrompt(cmd, createTextCmdMeta) { - if err := interactive.PromptAndSetFlags(cmd, createTextCmdMeta); err != nil { + if interactive.ShouldPrompt(cmd, textFormMeta(cmd, createTextCmdMeta)) { // createtextinput.go: the form asks for the text + if err := interactive.PromptAndSetFlags(cmd, textFormMeta(cmd, createTextCmdMeta)); err != nil { return err } } - req, err := flagutil.BuildRequest[operations.StableDocumentControllerCreateTextRequest](cmd, createTextCmdMeta, "Body", "") + req, err := textAsFile(cmd, createTextCmdMeta) // createtextinput.go: flagutil.BuildRequest, with --text and --file - as the file uploaded if err != nil { return err } diff --git a/internal/cli/document/createtexthelp.go b/internal/cli/document/createtexthelp.go index bd1afc3c..52110fe2 100644 --- a/internal/cli/document/createtexthelp.go +++ b/internal/cli/document/createtexthelp.go @@ -1,5 +1,5 @@ // This file is not generated by Speakeasy. It says what `vf document -// create-text` takes: a file. +// create-text` takes: text, a file, or stdin. // // 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 @@ -14,11 +14,15 @@ package document import "github.com/spf13/cobra" -// describeCreateText makes create-text's summary and help say it uploads a -// file. +// describeCreateText makes create-text's summary and help say what it adds: +// text typed or piped in, or a file (createtextinput.go). +// +// Round 6 made it say "Upload a file as a document", which was true while +// --file was the only way in. In round 8 a newcomer with the FAQ in their +// head read that as no way to add typed text (human-newcomer:F2). 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. " + + cmd.Short = "Add text or a file to the knowledge base" + cmd.Long = textNote + + "A file's name becomes the document's name (--name gives another), 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." } diff --git a/internal/cli/document/createtextinput.go b/internal/cli/document/createtextinput.go new file mode 100644 index 00000000..b8bb0ffb --- /dev/null +++ b/internal/cli/document/createtextinput.go @@ -0,0 +1,212 @@ +// This file is not generated by Speakeasy. It lets `vf document create-text` +// add text you type, or text piped in, without making a file first. +// +// The API takes a document as an uploaded file, so create-text took only +// --file. A newcomer with the FAQ in their head, not in a file, had to make +// one before anything could go into the knowledge base; the menu called the +// command "Upload a file as a document", and the form's one field asked for +// a path (round-8 sweep, human-newcomer:F2 and dead end, task 3). +// +// Now --text takes the text itself (@file reads a file's text and - reads +// stdin, as every text flag does), and --file - reads the file from stdin. +// vf uploads either as a text file, named by --name, or by the text's first +// words when --name is left out. --text stands in for --file, and the form +// asks for the text when neither is given. Hooked in by lines in +// createtext.go; internal/cli/createtextinput_test.go covers them. + +package document + +import ( + "errors" + "os" + "path/filepath" + "slices" + "strings" + "unicode" + "unicode/utf8" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/usage" +) + +const ( + textFlag = "text" + nameFlag = "name" + fileFlag = "file" +) + +// addTextInput gives create-text --text and --name, and - for --file. +func addTextInput(cmd *cobra.Command) { + f := cmd.Flags() + f.String(textFlag, "", "The document's text, typed or pasted, in place of --file: vf uploads it as a text file.") + flagutil.ReadsText(cmd, textFlag) + f.String(nameFlag, "", "The document's name in the knowledge base. With --file it is the file's name; with --text or stdin, the text's first words.") + flagutil.StandIn(cmd, textFlag, fileFlag) // standin.go: --text gives what --file would, and leads + flagutil.ReadsFileFromStdin(cmd, fileFlag) + if file := f.Lookup(fileFlag); file != nil { + file.Usage = strings.Replace(file.Usage, "Path to file to upload", "The file to upload: text (.txt), Markdown (.md), PDF (.pdf) or Word (.docx). - reads it from stdin.", 1) + } + for _, name := range []string{textFlag, nameFlag} { + usage.AddFlags("document create-text", usage.UsageFlag{Spec: "--" + name + " ", Help: f.Lookup(name).Usage}) + } + cmd.Example = " vf document create-text --project-id --environment-alias --text 'We are closed on December 25.' --name holiday-hours" + + "\n vf document create-text --project-id --environment-alias --file faq.md" +} + +// textFormMeta is meta for the form at a terminal: given neither --file nor +// --text, it asks for the text, which takes @file for a file's, and offers +// a name among the optional fields. +func textFormMeta(cmd *cobra.Command, meta []flagutil.FlagMeta) []flagutil.FlagMeta { + if flagutil.FlagChanged(cmd, fileFlag) || flagutil.FlagChanged(cmd, textFlag) { + return meta + } + form := slices.DeleteFunc(slices.Clone(meta), func(m flagutil.FlagMeta) bool { return m.FlagName == fileFlag }) + // JSON, so the form gives it a box that takes several lines; the flag + // takes text, so the form says so (optionalfields.go). + text := flagutil.FlagMeta{FlagName: textFlag, Kind: flagutil.FlagKindJSON, Required: true} + name := flagutil.FlagMeta{FlagName: nameFlag, Kind: flagutil.FlagKindString, Optional: true} + return append(append(form[:2:2], text, name), form[2:]...) // after the project and environment +} + +// textAsFile builds the request from meta as flagutil.BuildRequest does, +// then makes the text of --text, or the stdin of --file -, the file it +// uploads, named by --name or the text's first words. --name renames a +// --file upload too. +func textAsFile(cmd *cobra.Command, meta []flagutil.FlagMeta) (*operations.StableDocumentControllerCreateTextRequest, error) { + build := func() (*operations.StableDocumentControllerCreateTextRequest, error) { + return flagutil.BuildRequest[operations.StableDocumentControllerCreateTextRequest](cmd, meta, "Body", "") + } + content, fromText, err := typedContent(cmd) + if err != nil { + return nil, err + } + if !fromText { + req, err := build() + if err == nil { + if name, given := flagutil.GetStringFlag(cmd, nameFlag); given && strings.TrimSpace(name) != "" { + req.Body.File.FileName = withExtension(name, filepath.Ext(req.Body.File.FileName)) + } + } + return req, err + } + // The request is built as for a file, an empty one, and the text put + // in its place: no file of the text is written to disk. + file := cmd.Flags().Lookup(fileFlag) + saved, changed := file.Value.String(), file.Changed + _ = file.Value.Set(os.DevNull) + file.Changed = true + req, err := build() + _ = file.Value.Set(saved) + file.Changed = changed + if err != nil { + return nil, err + } + name, given := flagutil.GetStringFlag(cmd, nameFlag) + if !given || strings.TrimSpace(name) == "" { + name = firstWords(string(content)) + } + req.Body.File = operations.File{FileName: withExtension(name, ".txt", ".md"), Content: content} + return req, nil +} + +// typedContent is the text of --text, or what --file - reads from stdin, +// and whether it is either. +func typedContent(cmd *cobra.Command) ([]byte, bool, error) { + text, given := flagutil.GetStringFlag(cmd, textFlag) + path, _ := flagutil.GetStringFlag(cmd, fileFlag) + switch { + case given && flagutil.FlagChanged(cmd, fileFlag): + return nil, false, refuseText(cmd, "--text and --file both give the document", nil, + "Pass one of them: --text takes the text, --file uploads a file") + case given: + if strings.TrimSpace(text) == "" { + return nil, false, refuseText(cmd, "--text is empty", []string{"A document needs some text. Nothing was sent."}, + "Give the text: --text 'We are closed on December 25.'") + } + if !utf8.ValidString(text) || strings.ContainsRune(text, 0) { + return nil, false, refuseText(cmd, "--text isn't text: it isn't UTF-8", []string{"@file reads a file's text, and this file has none, such as a PDF or Word file. Nothing was sent."}, + "Upload the file itself with --file") + } + return []byte(text), true, nil + case path == "-": + data, err := flagutil.ReadFileFromStdin(cmd, fileFlag) + if err != nil { + return nil, false, refuseText(cmd, err.Error(), []string{"Nothing was sent."}, "Pipe the text in: `cat faq.md | "+pipedLine(cmd)+" --file - --name faq`") + } + return data, true, nil + } + return nil, false, nil +} + +// pipedLine is the command with the project and environment given, so the +// line a pipe runs needs no terminal to ask for them. +func pipedLine(cmd *cobra.Command) string { + line := cmd.CommandPath() + for _, name := range []string{"project-id", "environment-alias"} { + if v, given := flagutil.GetStringFlag(cmd, name); given && v != "" { + if strings.ContainsAny(v, " '\"$`\\&|;<>()*?#~") { + v = "'" + strings.ReplaceAll(v, "'", `'\''`) + "'" + } + line += " --" + name + " " + v + } + } + return line +} + +// refuseText refuses the line, exit 2, as filecheck.go refuses a --file +// that names no file: nothing was sent. +func refuseText(cmd *cobra.Command, message string, why []string, next ...string) error { + err := errors.New(message) + return output.Report(cmd, output.Explanation{Type: "invalid_flag_value", Title: message, Why: why, Next: next}, output.WithExitCode(err, output.ExitUsage)) +} + +// withExtension is name ending in the first of exts, unless it ends in one +// of them already: "holiday-hours" is holiday-hours.txt, faq.md stays +// faq.md, and "Version 2.5" is Version 2.5.txt. +func withExtension(name string, exts ...string) string { + name = strings.TrimSpace(name) + for _, ext := range exts { + if strings.EqualFold(filepath.Ext(name), ext) { + return name + } + } + return name + exts[0] +} + +// firstWords is a name for a document from its text: the first line's +// first words, without the characters a file name can't hold. +func firstWords(text string) string { + const most = 40 + line, _, _ := strings.Cut(strings.TrimSpace(text), "\n") + line = strings.Map(func(r rune) rune { + switch { + case strings.ContainsRune(`/\:*?"<>|#`, r): + return -1 + case unicode.IsSpace(r): + return ' ' + } + return r + }, line) + name := "" + for _, word := range strings.Fields(line) { + if utf8.RuneCountInString(name)+1+utf8.RuneCountInString(word) > most && name != "" { + break + } + name = strings.TrimSpace(name + " " + word) + } + name = strings.TrimRight(name, ".,;!") + if name == "" { + return "text" + } + if utf8.RuneCountInString(name) > most { + name = string([]rune(name)[:most]) + } + return name +} + +// textNote is what create-text says it does, for its summary and help. +const textNote = "Add a document to the knowledge base: text you type (--text), a file (--file: text, Markdown, PDF or Word), or text piped in (--file -). " diff --git a/internal/flagutil/filepaths.go b/internal/flagutil/filepaths.go index fa653686..9f66eb50 100644 --- a/internal/flagutil/filepaths.go +++ b/internal/flagutil/filepaths.go @@ -21,6 +21,7 @@ package flagutil import ( "errors" + "fmt" "io/fs" "os" "path/filepath" @@ -56,6 +57,42 @@ func markFileFlags(cmd *cobra.Command, meta []FlagMeta) { } } +// fromStdinKey annotates a file flag whose - reads the file from stdin. +const fromStdinKey = "vf:file-from-stdin" + +// ReadsFileFromStdin marks file flag name of cmd as taking - for stdin: +// `document create-text --file -`. Its - is no path to check. +func ReadsFileFromStdin(cmd *cobra.Command, name string) { + if cmd.Flags().Lookup(name) != nil { + _ = cmd.Flags().SetAnnotation(name, fromStdinKey, []string{"true"}) + } +} + +// ReadFileFromStdin is the file piped in for flag name's -. +func ReadFileFromStdin(cmd *cobra.Command, name string) ([]byte, error) { + if !HasStdinInput(cmd) { + return nil, fmt.Errorf("--%s - reads the file from stdin, and nothing is piped in", name) + } + data, err := readStdinBounded(cmd.InOrStdin(), 0) + if err != nil { + return nil, fmt.Errorf("failed to read stdin for --%s -: %w", name, err) + } + if len(data) == 0 { + return nil, fmt.Errorf("%w, and --%s - reads the file from it", ErrStdinEmpty, name) + } + return data, nil +} + +// ReadsAtFile is whether text flag f reads @file and - (ReadsText, +// ReadsSecret), and whether it holds a secret. +func ReadsAtFile(f *pflag.Flag) (reads, secret bool) { + if f == nil { + return false, false + } + v, ok := f.Value.(*textValue) + return ok, ok && v.secret +} + // IsFileFlag is whether f takes a file's path. func IsFileFlag(f *pflag.Flag) bool { return f != nil && len(f.Annotations[readsFileKey]) > 0 @@ -65,7 +102,7 @@ func IsFileFlag(f *pflag.Flag) bool { // flag that takes several, each, less any ;fileName=. func PathsIn(f *pflag.Flag, value string) []string { value = strings.TrimSpace(value) - if value == "" { + if value == "" || (value == "-" && len(f.Annotations[fromStdinKey]) > 0) { return nil } if a := f.Annotations[readsFileKey]; len(a) == 0 || a[0] != "paths" { diff --git a/internal/interactive/createtext_test.go b/internal/interactive/createtext_test.go new file mode 100644 index 00000000..69208be2 --- /dev/null +++ b/internal/interactive/createtext_test.go @@ -0,0 +1,81 @@ +// This file is not generated by Speakeasy. It covers create-text's form +// (cli/document/createtextinput.go) and the Text field's checks +// (filefield.go): the form asks for the text itself. + +package interactive_test + +import ( + "path/filepath" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/interactive" +) + +// The round-8 newcomer ran create-text in the home prompt with the FAQ in +// their head. The form's one field asked for a File, and there was no way to +// type the text (human-newcomer:F2). Now it asks for the text, offers the +// name among the optional fields, and sends the text as a text file. +func TestCreateTextsFormAsksForTheText(t *testing.T) { + inAFolder(t) + asked := interactive.AnswerForm(t, map[string]string{"text": "We are closed on December 25."}, false) + // The fake API answers 200, not the 201 a create expects: what was + // sent is what counts here. + sent, _, _ := inTheHomePrompt(t, added, "document", "create-text") + var flags []string + for _, a := range *asked { + flags = append(flags, a.Flag) + if a.Flag == "text" && !strings.Contains(a.Description, "@file to read it from a file") { + t.Errorf("the Text field should say it takes @file: %+v", a) + } + } + if len(flags) == 0 || flags[0] != "text" || strings.Contains(strings.Join(flags, " "), "file") { + t.Errorf("the form should ask for the text first, and no file: asked %q", flags) + } + body := strings.Join(sent.all(), "\n") + for _, want := range []string{`filename="We are closed on December 25.txt"`, "We are closed on December 25."} { + if !strings.Contains(body, want) { + t.Errorf("want %q in what was sent:\n%s", want, body) + } + } +} + +// A file's name typed as the text: one that is there says to write @ before +// it, and @ before it sends the file's text, named by the file. +func TestTheTextFieldTakesAFileWithAnAt(t *testing.T) { + inAFolder(t, "northwind-faq.txt") + asked := interactive.AnswerForm(t, map[string]string{"text": "northwind-faq.txt"}, false) + sent, _, _ := inTheHomePrompt(t, added, "document", "create-text") + if refused := refusedFor(*asked, "text"); refused != "northwind-faq.txt is a file here: write @northwind-faq.txt to use its text" { + t.Errorf("refused %q", refused) + } + if len(sent.all()) > 0 { + t.Errorf("nothing should be sent, sent %q", sent.all()) + } + + asked = interactive.AnswerForm(t, map[string]string{"text": "@northwind-faq.txt"}, false) + sent, _, _ = inTheHomePrompt(t, added, "document", "create-text") + if refused := refusedFor(*asked, "text"); refused != "" { + t.Fatalf("refused %q", refused) + } + if body := strings.Join(sent.all(), "\n"); !strings.Contains(body, "# northwind-faq.txt") { + t.Errorf("the file's text should be sent:\n%s", body) + } + + wd := inAFolder(t) + asked = interactive.AnswerForm(t, map[string]string{"text": "@faq.md"}, false) + inTheHomePrompt(t, added, "document", "create-text") + if refused := refusedFor(*asked, "text"); refused != "there is no file "+filepath.Join(wd, "faq.md")+" to read for @ in --text" { + t.Errorf("refused %q", refused) + } +} + +// refusedFor is what the field for flag said under its answer. +func refusedFor(asked []interactive.Asked, flag string) string { + for _, a := range asked { + if a.Flag == flag { + return a.Refused + } + } + return "" +} diff --git a/internal/interactive/export_test.go b/internal/interactive/export_test.go index 7cdf734a..ff38e9c0 100644 --- a/internal/interactive/export_test.go +++ b/internal/interactive/export_test.go @@ -42,13 +42,24 @@ func AnswerForm(t *testing.T, answers map[string]string, more bool) *[]Asked { case f.binding.strVal != nil: *f.binding.strVal = answer } - if input, ok := f.field.(*huh.Input); ok && f.binding.strVal != nil { - input.Value(f.binding.strVal) - input.Blur() // runs its check, as Enter does - if err := input.Error(); err != nil { - (*asked)[len(*asked)-1].Refused = err.Error() - return fmt.Errorf("interactive prompt: %w", huh.ErrUserAborted) + var err error + switch field := f.field.(type) { + case *huh.Input: + if f.binding.strVal != nil { + field.Value(f.binding.strVal) + field.Blur() // runs its check, as Enter does + err = field.Error() } + case *huh.Text: + if f.binding.strVal != nil { + field.Value(f.binding.strVal) + field.Blur() + err = field.Error() + } + } + if err != nil { + (*asked)[len(*asked)-1].Refused = err.Error() + return fmt.Errorf("interactive prompt: %w", huh.ErrUserAborted) } return nil } diff --git a/internal/interactive/filecheck_test.go b/internal/interactive/filecheck_test.go index a75601b7..b9b3a121 100644 --- a/internal/interactive/filecheck_test.go +++ b/internal/interactive/filecheck_test.go @@ -92,23 +92,25 @@ func TestAMissingFileIsRefusedBeforeTheFormSayingWhereVFLooked(t *testing.T) { } } -// The same file typed into the form's File field: the field says so under -// it, with the full path, before "Fill in 12 optional field(s)?". +// The same file typed into the form: the form asks for the text now, and +// a file's name typed there is refused under it, with the full path vf +// looked at, before "Fill in optional field(s)?" (createtext_test.go has +// the rest). func TestTheFormRefusesAPathThatNamesNoFile(t *testing.T) { wd := inAFolder(t, "notes.md") - asked := interactive.AnswerForm(t, map[string]string{"file": "northwind-faq.txt"}, false) + asked := interactive.AnswerForm(t, map[string]string{"text": "northwind-faq.txt"}, false) sent, said, _ := inTheHomePrompt(t, added, "document", "create-text") - var file *interactive.Asked + var text *interactive.Asked for i, a := range *asked { if a.Flag == "" { - t.Errorf("the path should be refused before the form asks %q", a.Title) + t.Errorf("the name should be refused before the form asks %q", a.Title) } - if a.Flag == "file" { - file = &(*asked)[i] + if a.Flag == "text" { + text = &(*asked)[i] } } - if file == nil || !strings.Contains(file.Refused, "there is no file "+filepath.Join(wd, "northwind-faq.txt")) { - t.Fatalf("the File field should refuse the path, asked %+v\n%s", *asked, said) + if text == nil || !strings.Contains(text.Refused, "there is no file "+filepath.Join(wd, "northwind-faq.txt")) { + t.Fatalf("the Text field should refuse the file's name, asked %+v\n%s", *asked, said) } if got := sent.all(); len(got) > 0 { t.Errorf("nothing should be sent, sent %q", got) diff --git a/internal/interactive/filefield.go b/internal/interactive/filefield.go index 69d9c50a..83c17b23 100644 --- a/internal/interactive/filefield.go +++ b/internal/interactive/filefield.go @@ -7,34 +7,51 @@ // directory" (round-8 sweep, human-newcomer:F2). Now the field of a flag // that takes a file's path (flagutil/filepaths.go) says what is wrong under // it, with the full path vf looked at, and waits for another; Esc cancels. +// A text field does the same for @path, and for a file's name typed as the +// text, since create-text's form now asks for the text itself. package interactive import ( "errors" + "fmt" + "path/filepath" "strings" + "unicode" "github.com/charmbracelet/huh" "github.com/spf13/cobra" + "github.com/spf13/pflag" "github.com/voiceflow/cli/internal/flagutil" ) // checksFile is field, for flag m of cmd, refusing a path that names no file -// vf can read when the flag takes a file's path. +// vf can read when the flag takes a file's path, and, when it takes text, +// a file's name given as the text. func checksFile(cmd *cobra.Command, field huh.Field, m flagutil.FlagMeta) huh.Field { f := cmd.Flags().Lookup(m.FlagName) - input, ok := field.(*huh.Input) - if !ok || !flagutil.IsFileFlag(f) { + check := textCheck(m) + if flagutil.IsFileFlag(f) { + check = pathCheck(f, m) + } else if reads, secret := flagutil.ReadsAtFile(f); !reads || secret { return field } - return input.Validate(func(s string) error { + switch field := field.(type) { + case *huh.Input: + return field.Validate(check) + case *huh.Text: + return field.Validate(check) + } + return field +} + +// pathCheck refuses a path for file flag f that names no file vf can read. +func pathCheck(f *pflag.Flag, m flagutil.FlagMeta) func(string) error { + return func(s string) error { paths := flagutil.PathsIn(f, s) if len(paths) == 0 { - if m.Required { - return errors.New("required") - } - return nil + return required(m) } for _, path := range paths { if err := flagutil.CheckFile(strings.TrimSpace(path), "--"+m.FlagName); err != nil { @@ -42,5 +59,44 @@ func checksFile(cmd *cobra.Command, field huh.Field, m flagutil.FlagMeta) huh.Fi } } return nil - }) + } +} + +// textCheck refuses, for text flag m, an @path that names no file, and a +// file's name in place of the text: `document create-text`'s form asks for +// the text, and a newcomer who had a file typed its name (round-8 sweep, +// human-newcomer:F2). The name of a file that is there says to write @ before +// it; one with a document's extension that isn't there gives the full path +// vf looked at. +func textCheck(m flagutil.FlagMeta) func(string) error { + return func(s string) error { + text := strings.TrimSpace(s) + path, at := strings.CutPrefix(text, "@") + switch { + case text == "": + return required(m) + case at && !strings.HasPrefix(path, "@"): // @@ is a literal @ + return flagutil.CheckFile(strings.TrimSpace(path), "@ in --"+m.FlagName) + case strings.ContainsFunc(text, unicode.IsSpace) || !docExtensions[strings.ToLower(filepath.Ext(text))]: + return nil + case flagutil.CheckFile(text, "") == nil: + return fmt.Errorf("%s is a file here: write @%s to use its text", text, text) + } + full, _ := flagutil.FullPath(text) + return fmt.Errorf("there is no file %s: type the text itself, or @ and the path of a file that is there", full) + } +} + +// docExtensions are the extensions of files a person may mean as the text. +var docExtensions = map[string]bool{ + ".txt": true, ".md": true, ".markdown": true, ".pdf": true, ".doc": true, ".docx": true, + ".csv": true, ".json": true, ".html": true, ".htm": true, ".rtf": true, +} + +// required refuses an empty answer to required field m. +func required(m flagutil.FlagMeta) error { + if m.Required { + return errors.New("required") + } + return nil } From be6ac86f83499f28df8a59ae806461fae5aaaae3 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:43:19 -0500 Subject: [PATCH 04/25] fix(home): use project takes an ID or name, says what is wrong with a line, and a -p makes the project current when none is MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: in a second home prompt, which starts with nothing current, `use project 6b0f08fba7f5577610a3449f` said "use takes workspace, project, environment, organization or clear", naming the word they had typed. Both fell back to -p on every command, and the window's project stayed empty for six commands (round-8 sweep, R8 #2, human-newcomer:F1, human-kb:F5; open since round 3). Cause: `use` took a level's word alone, to open its picker; any second word fell to the default case, which printed the list of words. And only a create or a picker made anything current: a -p typed on a line is kept for that line (session.Unheld), even when nothing is current. Change: use.go. `use project` takes the project's ID (looked up, with its workspace) or name (the current workspace, then each of yours; two alike list a line for each), `use environment` an alias or name, `use workspace` and `use organization` an ID or name, and `use -p 6b0f…` as on a command line; a level alone still opens the picker. A line use can't take says what is wrong and gives a line that runs: `use projects 6b0f…` offers `use project 6b0f…`, a bare ID asks for a word before it, `use clear now` says clear takes nothing. A line that succeeds with -p while no project is current makes that project current, with its workspace and -e (both testers expected it; one already current is never moved, a dry run or a delete never adopts). The lines that say so add "in this window". Tests: use_test.go. --- internal/cli/home.go | 11 +- internal/cli/use.go | 346 +++++++++++++++++++++++++++++++++++++ internal/cli/use_test.go | 187 ++++++++++++++++++++ internal/output/created.go | 4 +- internal/ui/DESIGN.md | 2 +- 5 files changed, 544 insertions(+), 6 deletions(-) create mode 100644 internal/cli/use.go create mode 100644 internal/cli/use_test.go diff --git a/internal/cli/home.go b/internal/cli/home.go index f158494d..bfd7b58c 100644 --- a/internal/cli/home.go +++ b/internal/cli/home.go @@ -181,6 +181,7 @@ func runLine(ctx context.Context, u *ui.UI, args []string) { cmd, err := root.ExecuteContextC(ctx) switch { case err == nil: + adoptProject(ctx, cmd, u) // use.go: a -p typed while no project is current makes it current case err.Error() == "": // already reported, as in main case ctx.Err() != nil: fmt.Fprintln(os.Stderr, u.Status(ui.StatusFailed, "Canceled")) @@ -213,8 +214,10 @@ var useLevels = map[string]string{ } // use shows the current workspace and project, picks a new one, or clears -// them: `use`, `use project`, `use clear`. Ctrl-C cancels ctx. +// them: `use`, `use project`, `use project 6b0f…`, `use clear`. Ctrl-C +// cancels ctx. func use(ctx context.Context, cmd *cobra.Command, u *ui.UI, args []string) { + args = useWords(args) // use.go: `use -p 6b0f…` is `use project 6b0f…` switch { case len(args) == 0: showCurrent(u) @@ -233,10 +236,12 @@ func use(ctx context.Context, cmd *cobra.Command, u *ui.UI, args []string) { case err != nil: _ = renderError(cmd, err) case it.Value != "": - fmt.Fprintln(os.Stderr, u.Status(ui.StatusDone, "Using "+args[0]+" "+it.Name+" from now on")) + fmt.Fprintln(os.Stderr, u.Status(ui.StatusDone, "Using "+args[0]+" "+it.Name+" from now on in this window")) } + case len(args) > 1 && useLevels[args[0]] != "": + useOn(ctx, cmd, u, args[0], strings.Join(args[1:], " ")) // use.go: by ID or name default: - fmt.Fprintln(os.Stderr, u.Status(ui.StatusFailed, "use takes workspace, project, environment, organization or clear")) + output.Render(cmd, useProblem(args)) // use.go: what is wrong, and a line that runs } } diff --git a/internal/cli/use.go b/internal/cli/use.go new file mode 100644 index 00000000..7d9bc4c4 --- /dev/null +++ b/internal/cli/use.go @@ -0,0 +1,346 @@ +// This file is not generated by Speakeasy. It lets the home prompt's `use` +// take what to use on the line, and say what is wrong with a line it can't +// take. +// +// `use project 6b0f08fba7f5577610a3449f` said "use takes workspace, project, +// environment, organization or clear", naming the word that was typed: `use` +// took a level alone, and opened a picker for it. Two round-8 testers in a +// second home prompt, which starts with nothing current, couldn't tell what +// was wrong, and fell back to -p on every command, which didn't make the +// project current either (round-8 sweep, R8 #2, human-newcomer:F1, +// human-kb:F5; open since round 3). +// +// Now `use project` takes the project's ID or name, `use environment` the +// environment's alias or name, and `use workspace` and `use organization` +// an ID or name too; a level alone still opens the picker. A line `use` +// can't take says what is wrong and gives a line that runs. And a command +// run with -p while no project is current makes that project current +// (adoptProject): both testers expected it. A -p typed while one is current +// stays that line's alone (session.Unheld), so it never moves the project +// the person chose. + +package cli + +import ( + "context" + "fmt" + "net/http" + "os" + "regexp" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/session" + "github.com/voiceflow/cli/internal/ui" +) + +// useFlags are the flags `use` takes in place of a level's word: `use -p +// 6b0f…` as on a command line. +var useFlags = map[string]string{ + "-p": "project", "--project-id": "project", + "-e": "environment", "--environment-alias": "environment", + "-w": "workspace", "--workspace-id": "workspace", + "--organization-id": "organization", +} + +// useWords is args with a flag in place of a level's word read as the word: +// `use --project-id=6b0f…` is `use project 6b0f…`. +func useWords(args []string) []string { + if len(args) == 0 { + return args + } + first, value, hasValue := strings.Cut(args[0], "=") + word, ok := useFlags[first] + if !ok { + return args + } + words := []string{word} + if hasValue { + words = append(words, value) + } + return append(words, args[1:]...) +} + +// anID is what a Voiceflow ID looks like: a project's, 24 hex digits. +var anID = regexp.MustCompile(`^[0-9a-f]{24}$`) + +// useOn makes value, an ID or name, current for level word. +func useOn(ctx context.Context, cmd *cobra.Command, u *ui.UI, word, value string) { + output.ResetAgentMode() + prev := cmd.Context() + cmd.SetContext(ctx) + defer cmd.SetContext(prev) + var x *output.Explanation + var err error + switch word { + case "project": + x, err = useProject(ctx, cmd, value) + case "environment": + x, err = useEnvironment(ctx, cmd, value) + default: + x, err = useListed(ctx, cmd, useLevels[word], value) + } + switch { + case err != nil && ctx.Err() != nil: + fmt.Fprintln(os.Stderr, u.Status(ui.StatusFailed, "Canceled")) + case err != nil: + _ = renderError(cmd, err) + case x != nil: + output.Render(cmd, *x) + default: + it, _ := session.Get(useLevels[word]) + fmt.Fprintln(os.Stderr, u.Status(ui.StatusDone, "Using "+called(word, it)+" from now on in this window")) + } +} + +// called is "project Help bot (p1)", or "project p1" when vf knows no name. +func called(noun string, it session.Item) string { + if it.Name == "" || it.Name == it.Value { + return noun + " " + it.Value + } + return noun + " " + it.Name + " (" + it.Value + ")" +} + +// useProject makes the project with ID or name value current, with its +// workspace. An ID is looked up; a name is looked for in the current +// workspace, then in each of yours. +func useProject(ctx context.Context, cmd *cobra.Command, value string) (*output.Explanation, error) { + if anID.MatchString(value) { + s, err := client.NewClient(cmd) + if err != nil { + return nil, err + } + res, err := s.Project.Get(client.WithSpinnerMessage(ctx, "Finding project "+value+"…"), + operations.StableProjectControllerGetRequest{ProjectID: value}, headers(cmd)...) + switch { + case output.StatusCode(err) == http.StatusNotFound: + return &output.Explanation{Type: "not_found", Title: "There is no project " + value + " that you can open", + Next: []string{"`use project` lists your projects to pick one"}}, nil + case err != nil: + return nil, err + case res.StableProjectResponse != nil: + p := res.StableProjectResponse.Project + session.Set("workspace-id", p.WorkspaceID, workspaceName(ctx, cmd, p.WorkspaceID)) + session.Set("project-id", p.ID, p.Name) + return nil, nil + } + } + + type found struct{ id, name, workspace, workspaceName string } + var matches []found + search := func(workspace, name string) error { + choices, err := listProjects(ctx, cmd, map[string]string{"workspace-id": workspace}) + for _, c := range choices { + if c.Value == value || strings.EqualFold(c.Name, value) { + matches = append(matches, found{c.Value, c.Name, workspace, name}) + } + } + return err + } + where := "your workspaces" + if cur, ok := session.Get("workspace-id"); ok { + if err := search(cur.Value, cur.Name); err != nil { + return nil, err + } + where = "workspace " + cur.Name + } + if len(matches) == 0 { + workspaces, err := listWorkspaces(ctx, cmd, "Loading your workspaces…") + if err != nil { + return nil, err + } + for _, w := range workspaces { + if cur, ok := session.Get("workspace-id"); ok && cur.Value == w.ID { + continue // looked in already + } + if err := search(w.ID, w.Name); err != nil { + return nil, err + } + } + where = "your workspaces" + } + switch len(matches) { + case 0: + return &output.Explanation{Type: "not_found", Title: "No project in " + where + " is named or has the ID " + quoteIt(value), + Next: []string{"`use project` lists your projects to pick one"}}, nil + case 1: + m := matches[0] + session.Set("workspace-id", m.workspace, m.workspaceName) + session.Set("project-id", m.id, m.name) + return nil, nil + } + x := &output.Explanation{Type: "ambiguous", Title: fmt.Sprintf("%d projects are named %s", len(matches), quoteIt(value)), + Why: []string{"Use one by its ID:"}} + for _, m := range matches { + x.Next = append(x.Next, "`use project "+m.id+"` in workspace "+m.workspaceName) + } + return x, nil +} + +// useEnvironment makes the current project's environment with alias or name +// value current. +func useEnvironment(ctx context.Context, cmd *cobra.Command, value string) (*output.Explanation, error) { + project, ok := session.Get("project-id") + if !ok { + return &output.Explanation{Type: "missing_flag", Title: "use environment needs a current project first", + Why: []string{"An environment belongs to one project, and none is current in this window."}, + Next: []string{"`use project` picks a project, then `use environment " + value + "`"}}, nil + } + choices, err := listEnvironments(ctx, cmd, map[string]string{"project-id": project.Value}) + if err != nil { + return nil, err + } + for _, c := range choices { + if c.Value == value || strings.EqualFold(c.Name, value) { + session.Set("environment-alias", c.Value, c.Name) + return nil, nil + } + } + x := &output.Explanation{Type: "not_found", Title: called("Project", project) + " has no environment " + quoteIt(value)} + for _, c := range choices[:min(len(choices), 5)] { + x.Next = append(x.Next, "`use environment "+c.Value+"` "+c.Name) + } + return x, nil +} + +// useListed makes the workspace or organization with ID or name value +// current, from the list its picker shows. +func useListed(ctx context.Context, cmd *cobra.Command, flag, value string) (*output.Explanation, error) { + list := listWorkspaceChoices + if flag == "organization-id" { + list = listOrganizations + } + choices, err := list(ctx, cmd, nil) + if err != nil { + return nil, err + } + noun := session.Nouns[flag] + var matches []interactive.Choice + for _, c := range choices { + if c.Value == value || strings.EqualFold(c.Name, value) { + matches = append(matches, c) + } + } + switch len(matches) { + case 0: + return &output.Explanation{Type: "not_found", Title: "None of your " + noun + "s is named or has the ID " + quoteIt(value), + Next: []string{"`use " + noun + "` lists them to pick one"}}, nil + case 1: + session.Set(flag, matches[0].Value, matches[0].Name) + return nil, nil + } + x := &output.Explanation{Type: "ambiguous", Title: fmt.Sprintf("%d %ss are named %s", len(matches), noun, quoteIt(value)), + Why: []string{"Use one by its ID:"}} + for _, m := range matches { + x.Next = append(x.Next, "`use "+noun+" "+m.Value+"` "+m.Detail) + } + return x, nil +} + +// workspaceName is workspace's name, or "" when vf can't list it. +func workspaceName(ctx context.Context, cmd *cobra.Command, workspace string) string { + workspaces, err := listWorkspaces(ctx, cmd, "Loading your workspaces…") + if err != nil { + return "" + } + for _, w := range workspaces { + if w.ID == workspace { + return w.Name + } + } + return "" +} + +// quoteIt is s in double quotes. +func quoteIt(s string) string { return `"` + s + `"` } + +// useClear are the words that clear what is current. +var useClear = []string{"clear", "none", "--clear"} + +// useProblem says what is wrong with a `use` line, and what runs instead. +func useProblem(args []string) output.Explanation { + first, rest := args[0], strings.Join(args[1:], " ") + switch { + case contains(useClear, first): + return output.Explanation{Type: "invalid_args", Title: "use " + first + " takes nothing after it", + Next: []string{"`use " + first + "` makes nothing current"}} + case anID.MatchString(first) && rest == "": + return output.Explanation{Type: "invalid_args", Title: "use needs a word before " + first + ": project, environment, workspace or organization", + Next: []string{"`use project " + first + "` makes that project current"}} + } + x := output.Explanation{Type: "invalid_args", Title: "use has no " + quoteIt(first) + ": it takes project, environment, workspace, organization or clear"} + if level := nearLevel(first); level != "" { + line := strings.TrimSpace("use " + level + " " + rest) + x.Next = []string{"`" + line + "`"} + return x + } + x.Next = []string{"`use project` lists your projects to pick one", "`use` shows what is current"} + return x +} + +// nearLevel is the level word w was likely meant as: "projects", "proj" +// and "Project" are project. +func nearLevel(w string) string { + w = strings.ToLower(strings.TrimLeft(w, "-")) + for level := range useLevels { + if len(w) >= 3 && (strings.HasPrefix(level, w) || strings.HasPrefix(w, level)) { + return level + } + } + return "" +} + +func contains(list []string, s string) bool { + for _, x := range list { + if x == s { + return true + } + } + return false +} + +// adoptProject makes the project a successful line typed with -p current, +// when no project is: the round-8 testers passed -p on every command in a +// second home prompt and expected it to stick. Its environment comes with +// it. A dry run, a delete, and a project vf can't find leave it as it was; +// so does a line while a project is current, which keeps its -p for itself. +func adoptProject(ctx context.Context, cmd *cobra.Command, u *ui.UI) { + if _, ok := session.Get("project-id"); ok || cmd == nil || !session.Active() { + return + } + f := cmd.Flags().Lookup("project-id") + if f == nil || !f.Changed || f.Value.String() == "" || client.IsDryRun(cmd) || strings.HasPrefix(cmd.Name(), "delete") { + return + } + id := f.Value.String() + name, workspace := "", "" + if s, err := client.NewClient(cmd); err == nil { + res, err := s.Project.Get(ctx, operations.StableProjectControllerGetRequest{ProjectID: id}, headers(cmd)...) + switch { + case err != nil && output.StatusCode(err) == http.StatusNotFound: + return + case err == nil && res.StableProjectResponse != nil: + name, workspace = res.StableProjectResponse.Project.Name, res.StableProjectResponse.Project.WorkspaceID + } + } + if workspace != "" { + session.Set("workspace-id", workspace, workspaceName(ctx, cmd, workspace)) + } + session.Set("project-id", id, name) + if e := cmd.Flags().Lookup("environment-alias"); e != nil && e.Changed && e.Value.String() != "" { + session.Set("environment-alias", e.Value.String(), "") + } + if output.ForAPerson(cmd) { + it, _ := session.Get("project-id") + call := it.Name + if call == "" { + call = it.Value + } + fmt.Fprintln(os.Stderr, u.Fit(u.Muted(call+" is now your current project in this window: later commands use it. ")+u.Accent("use")+u.Muted(" changes it."), 0)) // ui/wrap.go: breaks between words + } +} diff --git a/internal/cli/use_test.go b/internal/cli/use_test.go new file mode 100644 index 00000000..f24fc5ae --- /dev/null +++ b/internal/cli/use_test.go @@ -0,0 +1,187 @@ +// This file is not generated by Speakeasy. It covers use.go: the home +// prompt's `use` takes an ID or name on the line, says what is wrong with +// a line it can't take, and a -p typed while no project is current makes it +// current. + +package cli + +import ( + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" + + "github.com/voiceflow/cli/internal/ui" +) + +const ( + newcomerProject = "6b0f08fba7f5577610a3449f" + otherProject = "6b0f090ca7f5577610a344a9" +) + +// twoWorkspaces is a fake API with two workspaces, a project in each named +// alike, and one more, each with a main and a production environment. +func twoWorkspaces(t *testing.T) { + t.Helper() + projects := map[string]string{ + "w1": `{"id":"` + newcomerProject + `","name":"sweep-human-newcomer-1","workspaceID":"w1"},{"id":"6b0f000000000000000000a1","name":"Northwind Coffee","workspaceID":"w1"}`, + "w2": `{"id":"` + otherProject + `","name":"Northwind Coffee","workspaceID":"w2"}`, + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + path := r.URL.Path + switch { + case path == "/v1/stable/workspace": + io.WriteString(w, `{"workspaces":[{"id":"w1","name":"Sweep","organizationID":"o1"},{"id":"w2","name":"Other","organizationID":"o1"}]}`) + case path == "/v1/stable/project": + io.WriteString(w, `{"projects":[`+projects[r.URL.Query().Get("workspaceID")]+`]}`) + case strings.HasPrefix(path, "/v1/stable/project/"): + id := strings.TrimPrefix(path, "/v1/stable/project/") + for ws, list := range projects { + if strings.Contains(list, `"id":"`+id+`"`) { + name := "sweep-human-newcomer-1" + if id == otherProject { + name = "Northwind Coffee" + } + io.WriteString(w, `{"project":{"id":"`+id+`","name":"`+name+`","workspaceID":"`+ws+`"}}`) + return + } + } + w.WriteHeader(http.StatusNotFound) + io.WriteString(w, `{"message":"Project not found"}`) + case path == "/v1/stable/environment": + io.WriteString(w, `{"environments":[{"id":"e1","name":"Main","alias":"main","isMain":true},{"id":"e2","name":"Production","alias":"production","isMain":false}]}`) + default: + w.WriteHeader(http.StatusNotFound) + io.WriteString(w, `{"message":"no route"}`) + } + })) + t.Cleanup(srv.Close) + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", srv.URL) +} + +// inASecondWindow types lines into a new home prompt, which starts with +// nothing current, and returns what it said on stderr. +func inASecondWindow(t *testing.T, lines ...string) string { + t.Helper() + isolate(t) + twoWorkspaces(t) + typeLines(t, nil, lines...) + path := filepath.Join(t.TempDir(), "stderr") + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + saved := os.Stderr + os.Stderr = f + t.Cleanup(func() { os.Stderr = saved; 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 = saved + said, _ := os.ReadFile(path) + return strings.Join(strings.Fields(ansi.Strip(string(said))), " ") +} + +// The round-8 newcomer's line in a second window, `use project `, said +// "use takes workspace, project, environment, organization or clear". It +// makes the project current now, with its workspace; so does its name, and +// `use environment` takes an alias. +func TestUseProjectTakesAnIDOrAName(t *testing.T) { + said := inASecondWindow(t, "use project "+newcomerProject, "use") + for _, want := range []string{ + "Using project sweep-human-newcomer-1 (" + newcomerProject + ") from now on in this window", + "Current: workspace Sweep w1 project sweep-human-newcomer-1 " + newcomerProject, + } { + if !strings.Contains(said, want) { + t.Errorf("want %q in:\n%s", want, said) + } + } + if strings.Contains(said, "use takes") { + t.Errorf("the line was refused:\n%s", said) + } + + said = inASecondWindow(t, "use project sweep-human-newcomer-1", "use environment production", "use") + for _, want := range []string{ + "Using project sweep-human-newcomer-1 (" + newcomerProject + ") from now on in this window", + "Using environment Production (production) from now on in this window", + "project sweep-human-newcomer-1 " + newcomerProject + " environment Production production", + } { + if !strings.Contains(said, want) { + t.Errorf("want %q in:\n%s", want, said) + } + } + + // -p as on a command line, and a name two workspaces have. + said = inASecondWindow(t, "use -p "+otherProject, "use clear", "use project Northwind Coffee") + for _, want := range []string{ + "Using project Northwind Coffee (" + otherProject + ") from now on in this window", + `2 projects are named "Northwind Coffee"`, + "'use project 6b0f000000000000000000a1' in workspace Sweep", + "'use project " + otherProject + "' in workspace Other", + } { + if !strings.Contains(said, want) { + t.Errorf("want %q in:\n%s", want, said) + } + } +} + +// A line `use` can't take says what is wrong with it, and gives a line +// that runs, not the list of words it takes alone. +func TestUseSaysWhatIsWrongWithALine(t *testing.T) { + cases := []struct{ line, want, next string }{ + {"use projects " + newcomerProject, `use has no "projects"`, "use project " + newcomerProject}, + {"use " + newcomerProject, "use needs a word before " + newcomerProject + ": project, environment, workspace or organization", "use project " + newcomerProject}, + {"use clear now", "use clear takes nothing after it", "use clear"}, + {"use nosuch", `use has no "nosuch"`, "use project"}, + {"use environment main", "use environment needs a current project first", "use project"}, + {"use project 6b0fffffffffffffffffffff", "There is no project 6b0fffffffffffffffffffff that you can open", "use project"}, + {"use project Nowhere", `No project in your workspaces is named or has the ID "Nowhere"`, "use project"}, + {"use environment staging", `has no environment "staging"`, "use environment production"}, + } + for _, c := range cases { + lines := []string{c.line} + if strings.Contains(c.line, "staging") { + lines = []string{"use project " + newcomerProject, c.line} + } + said := inASecondWindow(t, lines...) + if !strings.Contains(said, c.want) || !strings.Contains(said, c.next) { + t.Errorf("%q: want %q and %q in:\n%s", c.line, c.want, c.next, said) + } + } +} + +// Both testers then passed -p on every command, and the window's project +// stayed empty for six commands. A line with -p that runs while no project +// is current makes it current; while one is, the -p is that line's alone. +func TestAProjectTypedWithPBecomesCurrentWhenNoneIs(t *testing.T) { + said := inASecondWindow(t, "project get -p "+newcomerProject+" --agent-mode=false", "use") + for _, want := range []string{ + "sweep-human-newcomer-1 is now your current project in this window", + "Current: workspace Sweep w1 project sweep-human-newcomer-1 " + newcomerProject, + } { + if !strings.Contains(said, want) { + t.Errorf("want %q in:\n%s", want, said) + } + } + + said = inASecondWindow(t, "use project "+newcomerProject, "project get -p "+otherProject+" --agent-mode=false", "use") + if !strings.Contains(said, "project sweep-human-newcomer-1 "+newcomerProject) || strings.Contains(said, "Northwind Coffee is now your current") { + t.Errorf("a -p typed while a project is current shouldn't change it:\n%s", said) + } + + said = inASecondWindow(t, "project get -p 6b0fffffffffffffffffffff --agent-mode=false", "use") + if !strings.Contains(said, "Nothing is current yet") { + t.Errorf("a project that wasn't found shouldn't become current:\n%s", said) + } +} diff --git a/internal/output/created.go b/internal/output/created.go index 39bb1d5e..985e0daa 100644 --- a/internal/output/created.go +++ b/internal/output/created.go @@ -11,7 +11,7 @@ // Next: // vf agent read-instructions read its agent's instructions // vf environment list its environments -// Help bot is now your current project: later commands use it. 'use' changes it. +// Help bot is now your current project in this window: later commands use it. 'use' changes it. // // The lines are status, on stderr, and only for a person reading pretty // output: JSON, --jq, agent mode and a pipe get the result alone. @@ -80,7 +80,7 @@ func afterResult(cmd *cobra.Command, res interface{}) func() { if call == "" { call = id } - fmt.Fprintln(os.Stderr, u.Fit(u.Muted(call+" is now your current "+group+": later commands use it. ")+u.Accent("use")+u.Muted(" changes it."), 0)) // ui/wrap.go: breaks between words + fmt.Fprintln(os.Stderr, u.Fit(u.Muted(call+" is now your current "+group+" in this window: later commands use it. ")+u.Accent("use")+u.Muted(" changes it."), 0)) // ui/wrap.go: breaks between words } } } diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index 87db592b..47de948c 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -280,7 +280,7 @@ Next: vf agent read-instructions read its agent's instructions vf environment list its environments vf project get see it -Help bot is now your current project: later commands use it. use changes it. +Help bot is now your current project in this window: later commands use it. use changes it. ╭─ workspace Acme › project Help bot ─────────────────────────────╮ │ ❯ Try "agent read-instructions" │ From 26a1bc00f823d938b8a17beac4fe044d8f126564 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:48:03 -0500 Subject: [PATCH 05/25] fix(forms): a write given all it needs runs without "Fill in N optional field(s)?", and deprecated fields aren't offered MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: `agent update --instructions "…"` in the home prompt, with a current project, asked "Fill in 15 optional field(s)?" under three header lines that stayed above "✓ Agent updated."; every create given its required flags asked the same, six times for each tester, and they answered No each time. Five of create-text's twelve optional fields were deprecated (round-8 sweep, R8 #39, human-newcomer:F5, human-kb:F4). Cause: the form opens whenever a required flag isn't on the line, and the home prompt's current project and environment are filled in by the pickers inside it. Once they were, the form went on to offer the optional fields, by design ("a command given something on its line asks first"), though nothing had been asked; and it offered every optional field, deprecated ones too. Change: when the pickers took every required value without asking and the line gives something to send, the form returns before its header and the offer (optionalfields.go givesAll, one hook in interactive.go). An update given nothing still starts on its fields, and a form that asked something still offers the rest after it. A field whose help says Deprecated isn't offered (one hook in fieldsToAsk). The header is no longer printed in the case reported; one over a form that asked stays. Tests: optionalfields_test.go TestGivenAllItNeedsAWriteRunsWithoutAsking, TestAFormThatAskedOffersTheRest. --- internal/interactive/interactive.go | 5 +- internal/interactive/optionalfields.go | 32 +++++++++++- internal/interactive/optionalfields_test.go | 55 ++++++++++++++++----- 3 files changed, 77 insertions(+), 15 deletions(-) diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go index 12ef4d68..3917b0f7 100644 --- a/internal/interactive/interactive.go +++ b/internal/interactive/interactive.go @@ -160,7 +160,7 @@ func formTheme() *huh.Theme { func fieldsToAsk(cmd *cobra.Command, meta []flagutil.FlagMeta) (required, optional []fieldInfo) { offers := offersOptional(cmd) for _, m := range meta { - if isValueResolved(cmd, m) || (!m.Required && !offers) { + if isValueResolved(cmd, m) || (!m.Required && (!offers || deprecated(cmd, m))) { // optionalfields.go: a deprecated field isn't offered continue } field, binding := buildFormField(formMeta(cmd, m)) // optionalfields.go: help's words, and what the field takes @@ -265,6 +265,9 @@ func PromptAndSetFlags(cmd *cobra.Command, meta []flagutil.FlagMeta) error { if err != nil { return err } + if !announced && len(required) == 0 && givesAll(cmd, meta) { // optionalfields.go: given all it needs, with nothing asked, it runs + return nil + } if len(required) > 0 || len(optional) > 0 { announce(len(required), len(optional)) } diff --git a/internal/interactive/optionalfields.go b/internal/interactive/optionalfields.go index 6e50cfe6..7600ffd4 100644 --- a/internal/interactive/optionalfields.go +++ b/internal/interactive/optionalfields.go @@ -20,7 +20,9 @@ // that take text come first, then the other plain ones (numbers, lists, yes // or no), then JSON. Once one is filled in, the rest are offered with one // question, and No sends what was given. A command given something on its -// line asks first, as before, with No chosen. Each field says what help says +// line asks first, as before, with No chosen, once the form has asked +// something; given all it needs with nothing asked, it runs (givesAll). +// Each field says what help says // about its flag and what it takes: text as text, true or false as a choice, // "(JSON)" only for JSON whose words don't say so. A field Enter skips says // that too. @@ -133,6 +135,34 @@ func inOrder(cmd *cobra.Command, optional []fieldInfo) [][]fieldInfo { return out } +// givesAll is whether cmd's line gives all it needs and something to send, +// once the pickers have taken the current project and environment without +// asking. Then the form doesn't offer the optional fields: round 8's +// testers were asked "Fill in 15 optional field(s)?" after `agent update +// --instructions "…"`, and after every create given its required flags, six +// times each, and answered No every time; the form's header stayed above +// the result (human-newcomer:F5, human-kb:F4). A field the form asks for +// keeps the offer after it: the person is filling in a form by then. +func givesAll(cmd *cobra.Command, meta []flagutil.FlagMeta) bool { + if f := cmd.Flags().Lookup("body"); f != nil && f.Changed { + return true + } + for _, m := range meta { + if _, picked := pickers[m.FlagName]; !picked && isValueResolved(cmd, m) { + return true + } + } + return false +} + +// deprecated is whether flag m's help says it is deprecated, so the form +// doesn't offer it: five of create-text's twelve optional fields were +// (human-newcomer:F5). +func deprecated(cmd *cobra.Command, m flagutil.FlagMeta) bool { + f := cmd.Flags().Lookup(m.FlagName) + return f != nil && (f.Deprecated != "" || strings.HasPrefix(f.Usage, "Deprecated")) +} + // changesNothingYet is whether cmd is an update that nothing on its line, or // in its required fields, gives a value to change: answering No to its // optional fields could only send an empty update. A flag that stands in for diff --git a/internal/interactive/optionalfields_test.go b/internal/interactive/optionalfields_test.go index 870e3add..6f6ad2c3 100644 --- a/internal/interactive/optionalfields_test.go +++ b/internal/interactive/optionalfields_test.go @@ -126,24 +126,53 @@ func TestAnUpdateLeftEmptyAsksNoQuestion(t *testing.T) { } } -// A command given something to send still asks first, with No chosen, and -// a flag that takes true or false is a choice labelled as one, not JSON. -func TestGivenSomethingTheFormAsksFirst(t *testing.T) { - asked := interactive.AnswerForm(t, nil, true) - _, said, err := inTheHomePrompt(t, `{"message":"Agent updated."}`, "agent", "update", "--prompt", "You are Northwind's barista.") - if err != nil { - t.Fatalf("%v\n%s", err, said) - } - if len(*asked) == 0 || (*asked)[0].Title != "Fill in 15 optional field(s)?" || !strings.HasPrefix((*asked)[0].Description, "Instructions, ") { - t.Fatalf("given --prompt, the form should ask first, the instructions first, got %+v", *asked) +// Round 8's newcomer gave `agent update --instructions "…"` in the home +// prompt, with a current project, and was asked "Fill in 15 optional +// field(s)?" over three header lines that stayed above the result; all six +// of human-kb's creates, given every required flag, asked the same +// (human-newcomer:F5, human-kb:F4). Given all it needs, with nothing asked, +// a write now runs: no header, no question. +func TestGivenAllItNeedsAWriteRunsWithoutAsking(t *testing.T) { + for _, line := range [][]string{ + {"agent", "update", "--instructions", "Greet the caller by name."}, + {"document", "create-text", "--file", "optionalfields_test.go"}, + } { + asked := interactive.AnswerForm(t, nil, true) + sent, said, _ := inTheHomePrompt(t, `{"message":"Agent updated."}`, line...) + if len(*asked) > 0 { + t.Errorf("%q: nothing should be asked, asked %+v", line, *asked) + } + if strings.Contains(said, "optional field(s)") { + t.Errorf("%q: the form's header shouldn't show:\n%s", line, said) + } + if len(sent.all()) != 1 { + t.Errorf("%q: want it sent, sent %q", line, sent.all()) + } } +} - asked = interactive.AnswerForm(t, nil, true) - _, said, _ = inTheHomePrompt(t, `{"document":{"id":"d1","data":{"type":"md","name":"faq.md"},"status":{"type":"SUCCESS"}}}`, - "document", "create-text", "--file", "optionalfields_test.go") +// A form that asked something offers the optional fields after it, with +// No chosen, leaving out the deprecated ones (five of create-text's twelve); +// a flag that takes true or false is a choice labelled as one, not JSON. +func TestAFormThatAskedOffersTheRest(t *testing.T) { + asked := interactive.AnswerForm(t, map[string]string{"text": "We are closed on December 25."}, true) + _, said, _ := inTheHomePrompt(t, `{"document":{"id":"d1","data":{"type":"md","name":"faq.md"},"status":{"type":"SUCCESS"}}}`, + "document", "create-text") labels := map[string]string{} + var offer string for _, a := range *asked { labels[a.Flag] = a.Description + if a.Flag == "" { + offer = a.Title + } + } + if offer != "Fill in 8 optional field(s)?" { + t.Errorf("after the text, the 8 optional fields that aren't deprecated should be offered, got %q\n%s", offer, said) + } + for _, flag := range []string{"llm-based-chunks", "llm-generated-q", "llm-content-summarization", "llm-prepend-context", "markdown-conversion"} { + if _, ok := labels[flag]; ok { + t.Errorf("deprecated --%s was offered", flag) + } } if d := labels["overwrite"]; strings.Contains(d, "JSON") || !strings.Contains(d, "(true or false)") || !strings.Contains(d, "Yes No > Skip") { t.Errorf("--overwrite takes true or false, as a choice: %q\n%s", d, said) From f632f3fc225dcd7661618e411fdc4e2705e105f8 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:18:20 -0500 Subject: [PATCH 06/25] fix(output): --strict after a create or a patch never says to run it again MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: agent-builder:F2: `vf playbook create --name warranty --instructions '… Use `check_warranty` to verify.' --strict` ended "Then run this command again: a {token} binds when the field is written, not later". Run again, it made a second playbook: "`vf playbook list` then showed 6b0f0a2ba7f5577610a34af4 warranty and 6b0f0a2be41a42d04c14dc2c warranty". fix-verifier:N1: after `playbook patch-instructions … --strict` and the `vf variable create` the hint offered, the same patch again said "Replaced 1 occurrence at line 1. rc=0", and read-instructions showed the inserted sentence twice. Both exited 0 (R8 #7). Cause: 3c8217d gave output/strict.go's unboundNext one last line for every --strict command, written for `agent update`: run again, an update writes the same text over itself. A create or an add run again makes a second one, and a patch inserts its new text again. What binds a {token} is a write of its field: the API keeps a name that matches nothing as literal text ("then write the field again with the same {token}"), and each patch or update of a prompt or instructions resolves the whole text again (the spec: "The WHOLE document is re-resolved on every patch"). A compile builds from what was stored. A patch can't rewrite the text unchanged: the API refuses one whose old and new strings are the same. Change: - After a create, Next names what it made and writes the text there with an update, as it was typed: `vf playbook update --playbook-id 6b0f… --project-id p1 --environment-alias main --instructions @returns.md --strict`, then "Don't run this command again: it would make a second playbook". Text a hint can't hold on one line (a backtick, a line break, stdin, --body) gets the ID and the words instead. flagutil's text flags keep what was typed (@returns.md) for this. - After a patch: "Don't run this patch again: its new text is saved already", that the next patch or update binds it, and the read that shows the text. - After another add, not to run it again, and to write it with an update. An update keeps "Then run this command again". - A /name kept as plain text (mentions.go) said "then save the text again"; after a create or a patch it now says not to run it again. Tests: TestStrictNeverOffersTheWriteAgain replays the create (from a file and typed) and the patch against a fake API, runs every command Next offers as written, and fails when the playbook is created or patched a second time; TestStrictSlashNameAfterAPatchSaysNotToRunItAgain. --- internal/cli/mentions.go | 12 +- internal/cli/strictagain_test.go | 172 ++++++++++++++++++++++++++ internal/flagutil/textfile.go | 17 ++- internal/output/strict.go | 13 +- internal/output/strictagain.go | 202 +++++++++++++++++++++++++++++++ 5 files changed, 409 insertions(+), 7 deletions(-) create mode 100644 internal/cli/strictagain_test.go create mode 100644 internal/output/strictagain.go diff --git a/internal/cli/mentions.go b/internal/cli/mentions.go index 9273b070..113e11f7 100644 --- a/internal/cli/mentions.go +++ b/internal/cli/mentions.go @@ -127,7 +127,7 @@ func plainMentions(cmd *cobra.Command, flags []string) error { Type: "unresolved_references", Title: title, Why: append(why, "The change was saved: --strict fails the command, it doesn't undo it."), - Next: []string{"Put each name in backticks in place of its / or @, then save the text again"}, + Next: []string{plainMentionsNext(cmd)}, } return output.Report(cmd, x, output.WithExitCode(errors.New(title), output.ExitFailure)) } @@ -135,6 +135,16 @@ func plainMentions(cmd *cobra.Command, flags []string) error { return nil } +// plainMentionsNext is --strict's Next for a /name: how to save it in +// backticks. A create or a patch run again would write its text twice +// (output/strictagain.go), so for one it says so. +func plainMentionsNext(cmd *cobra.Command) string { + if strings.HasPrefix(cmd.Name(), "update") { + return "Put each name in backticks in place of its / or @, then save the text again" + } + return "Put each name in backticks in place of its / or @ with a patch or an update. Don't run this command again: it would write the text a second time" +} + // usageAsked is whether cmd was run for its --usage schema, which writes // nothing. func usageAsked(cmd *cobra.Command) bool { diff --git a/internal/cli/strictagain_test.go b/internal/cli/strictagain_test.go new file mode 100644 index 00000000..d118008d --- /dev/null +++ b/internal/cli/strictagain_test.go @@ -0,0 +1,172 @@ +// This file is not generated by Speakeasy. It covers output/strictagain.go: +// --strict's Next lines never make a create or a patch happen twice. + +package cli + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/voiceflow/cli/internal/cmdcheck" +) + +// strictAPI answers the round-8 testers' --strict writes as the API did, +// and records each request as "METHOD /path body". +func strictAPI(t *testing.T) (url string, calls 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, r.Method+" "+r.URL.Path+" "+string(body)) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPost && r.URL.Path == "/v2/stable/playbook": + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"playbook":{"id":"6b0f0a2ba7f5577610a34af4","name":"warranty","instructions":"Help with warranty claims. Use ` + "`check_warranty`" + ` to verify.","instructionsLineCount":1,` + stamp + `},` + + `"unresolvedMentions":[{"path":"instructions","mention":"check_warranty"}]}`)) + case r.Method == http.MethodPatch && r.URL.Path == "/v2/stable/playbook/pb1/instructions": + _, _ = w.Write([]byte(`{"message":"Replaced 1 occurrence at line 1.","replacements":1,"totalLines":1,` + + `"diff":"@@ -1,1 +1,1 @@\n-Standard shipping takes 5 business days.\n+Standard shipping takes 5 business days. Use /issue_refund_label and {customer_email} when asked for a label.",` + + `"unresolvedReferences":[{"path":"instructions","token":"customer_email","reason":"unknown"}]}`)) + case r.Method == http.MethodPatch && r.URL.Path == "/v2/stable/playbook/6b0f0a2ba7f5577610a34af4": + _, _ = w.Write([]byte(`{"message":"Playbook updated."}`)) + case r.Method == http.MethodGet && r.URL.Path == "/v2/stable/playbook/pb1/instructions": + _, _ = w.Write([]byte(`{"content":"1\tStandard shipping takes 5 business days.","offset":1,"returnedLines":1,"totalLines":1,"totalCharacters":40,"hasMore":false,"nextOffset":null}`)) + case r.Method == http.MethodPost && r.URL.Path == "/v2/stable/variable": + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"variable":{"id":"v1","name":"customer_email","color":"#515A63",` + stamp + `}}`)) + 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...) + } +} + +// suggestedLines are the `vf …` commands in out's Next lines, which +// print them in 'single quotes': the rest of a hint after 'vf, to the +// quote that ends the hint or comes before " shows". +func suggestedLines(out string) []string { + var found []string + for _, line := range strings.Split(out, "\n") { + line = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(line), `",`)) + line = strings.TrimSuffix(line, `"`) + i := strings.Index(line, "'vf ") + if i < 0 { + continue + } + rest := line[i+1:] + if j := strings.Index(rest, "' shows"); j >= 0 { + rest = rest[:j] + } else { + rest = strings.TrimSuffix(rest, "'") + } + found = append(found, rest) + } + return found +} + +// R8 #7 (agent-builder:F2, fix-verifier:N1): --strict's Next ended "Then +// run this command again: a {token} binds when the field is written". +// After `playbook create` that made a second playbook named warranty, and +// after `playbook patch-instructions` it saved the inserted sentence twice, +// both with exit 0. Each scenario is replayed here and every command its +// Next offers is run as written: none may create the playbook or patch the +// instructions again. The create's Next writes the text to the playbook it +// made, with an update. +func TestStrictNeverOffersTheWriteAgain(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + withFiles(t, map[string]string{"returns.md": "Help with warranty claims. Use `check_warranty` to verify.\n"}) + tree := testRoot(t) + create := []string{"playbook", "create", "-p", "p1", "-e", "main", "--name", "warranty", "--strict"} + patch := []string{"playbook", "patch-instructions", "-p", "p1", "-e", "main", "--playbook-id", "pb1", "--strict", + "--old-string", "Standard shipping takes 5 business days.", + "--new-string", "Standard shipping takes 5 business days. Use /issue_refund_label and {customer_email} when asked for a label."} + scenarios := []struct { + name string + line []string + update bool // whether Next must offer the update of the playbook made + }{ + {"create from a file", append(create[:len(create):len(create)], "--instructions", "@returns.md"), true}, + {"create with the text typed", append(create[:len(create):len(create)], "--instructions", "Help with warranty claims. Use `check_warranty` to verify."), false}, + {"patch", patch, false}, + } + for _, s := range scenarios { + for _, mode := range []string{"--agent-mode=false", "--agent-mode=true"} { + url, calls := strictAPI(t) + out, err := runLineIn(t, "", append(append([]string{}, s.line...), "--no-interactive", "--server-url", url, mode)...) + if err == nil { + t.Errorf("%s %s: --strict should fail:\n%s", s.name, mode, out) + } + if strings.Contains(out, "Then run this command again") || !strings.Contains(out, "Don't run this") { + t.Errorf("%s %s: Next should say not to run it again:\n%s", s.name, mode, out) + } + if s.line[1] == "create" && !strings.Contains(out, "playbook 6b0f0a2ba7f5577610a34af4, which this command made") { + t.Errorf("%s %s: Next should name the playbook it made:\n%s", s.name, mode, out) + } + lines := suggestedLines(out) + updated := false + for _, line := range lines { + if problems := cmdcheck.Check(tree, line, cmdcheck.Options{Complete: true}); len(problems) > 0 { + t.Errorf("%s %s: %s: %v", s.name, mode, line, problems) + continue + } + if strings.HasPrefix(line, "vf "+s.line[0]+" "+s.line[1]+" ") { + t.Errorf("%s %s: Next offers the write again: %s", s.name, mode, line) + continue + } + words, _ := cmdcheck.Words(line) + if _, err := runLineIn(t, "", append(words[1:], "--server-url", url, mode)...); err != nil { + t.Errorf("%s %s: %s: %v", s.name, mode, line, err) + } + updated = updated || strings.HasPrefix(line, "vf playbook update --playbook-id 6b0f0a2ba7f5577610a34af4 ") + } + if updated != s.update { + t.Errorf("%s %s: Next offers the update %v, want %v: %q", s.name, mode, updated, s.update, lines) + } + if strings.Contains(out, "Then run this command again") { // as the testers did + _, _ = runLineIn(t, "", append(append([]string{}, s.line...), "--no-interactive", "--server-url", url, mode)...) + } + writes := 0 + for _, call := range calls() { + if strings.HasPrefix(call, "POST /v2/stable/playbook ") || strings.HasPrefix(call, "PATCH /v2/stable/playbook/pb1/instructions ") { + writes++ + } + if strings.HasPrefix(call, "PATCH /v2/stable/playbook/6b0f0a2ba7f5577610a34af4 ") && !strings.Contains(call, `"instructions":"Help with warranty claims. Use `+"`check_warranty`"+` to verify.\n"`) { + t.Errorf("%s %s: the update should write the file's text again: %s", s.name, mode, call) + } + } + if writes != 1 { + t.Errorf("%s %s: the playbook was created or patched %d times, running Next as written: %q", s.name, mode, writes, calls()) + } + } + } +} + +// The same for a /name kept as plain text (mentions.go): its Next was +// "…then save the text again", which after a patch saves the text twice. +func TestStrictSlashNameAfterAPatchSaysNotToRunItAgain(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + for _, mode := range []string{"--agent-mode=false", "--agent-mode=true"} { + url, _ := mentionServer(t) + out, err := runLineIn(t, "", "agent", "patch-instructions", "-p", "p1", "-e", "main", "--old-string", "x", + "--new-string", "Hand off to /Returns.", "--strict", "--server-url", url, "--no-interactive", mode) + if err == nil || !strings.Contains(out, "Don't run this command again") || strings.Contains(out, "then save the text again") { + t.Errorf("%s: %v\n%s", mode, err, out) + } + } +} diff --git a/internal/flagutil/textfile.go b/internal/flagutil/textfile.go index 80765039..d6e9e20e 100644 --- a/internal/flagutil/textfile.go +++ b/internal/flagutil/textfile.go @@ -58,15 +58,29 @@ func TakesText(f *pflag.Flag) bool { return reads || len(f.Annotations[takesText]) > 0 } +// Typed is what f was given, as typed: @prompt.md for a flag that read the +// file, - for one that read stdin, or the text. It is "" for any other +// flag, and for a secret, whose value is never repeated. After a create, +// --strict's Next writes the text again with an update +// (output/strictagain.go), and @prompt.md says it in a word. +func Typed(f *pflag.Flag) string { + if v, ok := f.Value.(*textValue); ok && !v.secret { + return v.typed + } + return "" +} + // textValue is a flag's value that reads @path and - before it is set. type textValue struct { pflag.Value cmd *cobra.Command name string - secret bool // a secret: see ReadsSecret + secret bool // a secret: see ReadsSecret + typed string // what was given, @path or - or the text, before it was read } func (v *textValue) Set(s string) error { + v.typed = s read := readText if v.secret { read = readSecret @@ -141,6 +155,7 @@ func SetText(cmd *cobra.Command, name, text string) error { if err := tv.Value.Set(text); err != nil { return err } + tv.typed = "" // the text itself, read from nothing f.Changed = true return nil } diff --git a/internal/output/strict.go b/internal/output/strict.go index fe59bab7..9933116f 100644 --- a/internal/output/strict.go +++ b/internal/output/strict.go @@ -74,13 +74,13 @@ func strictVerdict(cmd *cobra.Command, res interface{}) func(*error) { quietUnbound(cmd, res) return func(err *error) { if *err == nil { - *err = unbound(cmd, a) + *err = unbound(cmd, a, res) } } } -// unbound reports the {tokens} and mentions in a that didn't bind. -func unbound(cmd *cobra.Command, a unboundAnswer) error { +// unbound reports the {tokens} and mentions in a, res's, that didn't bind. +func unbound(cmd *cobra.Command, a unboundAnswer, res interface{}) error { var names, why []string for _, r := range a.UnresolvedReferences { names = append(names, "{"+r.Token+"}") @@ -99,7 +99,7 @@ func unbound(cmd *cobra.Command, a unboundAnswer) error { Type: "unresolved_references", Title: title, Why: why, - Next: unboundNext(cmd, a), + Next: unboundNext(cmd, a, res), }, errors.New(title)) } @@ -110,7 +110,7 @@ var variableName = regexp.MustCompile(`^\w{1,64}$`) // creates each variable a {token} names that has none, then to write the // field again, since a {token} binds when it is written. It was one line // of prose, "Create the variable, entity or tool it names, …". -func unboundNext(cmd *cobra.Command, a unboundAnswer) []string { +func unboundNext(cmd *cobra.Command, a unboundAnswer, res interface{}) []string { var next []string seen := map[string]bool{} for _, r := range a.UnresolvedReferences { @@ -122,6 +122,9 @@ func unboundNext(cmd *cobra.Command, a unboundAnswer) []string { if len(a.UnresolvedMentions) > 0 { next = append(next, "Fix a mention's spelling, or attach the tool, playbook or workflow it names") } + if again := writeAgain(cmd, res, a, len(next) == 0); again != nil { + return append(next, again...) // strictagain.go: a create or a patch run again would write it twice + } if len(next) == 0 { return []string{"Fix the {token}, then write the field again"} } diff --git a/internal/output/strictagain.go b/internal/output/strictagain.go new file mode 100644 index 00000000..cf8cc253 --- /dev/null +++ b/internal/output/strictagain.go @@ -0,0 +1,202 @@ +// This file is not generated by Speakeasy. It ends --strict's Next lines +// (strict.go) for a write that, run again, would happen twice: a create, an +// add or a patch. +// +// When a {token} or a mention didn't bind, Next ended "Then run this +// command again: a {token} binds when the field is written, not later". +// That holds for an update, which writes the same text over itself. The +// round-8 sweep followed it after a create and after a patch (R8 #7): +// `playbook create --name warranty … --strict`, run again, made a second +// playbook named warranty (agent-builder:F2), and `playbook +// patch-instructions … --strict`, run again, saved the inserted sentence +// twice (fix-verifier:N1). Both exited 0. +// +// What binds a {token} is a write of its field: the API resolves the text +// it is sent and keeps a name that matches nothing as literal text ("…then +// write the field again with the same {token}"). A patch and an update of a +// prompt or instructions read the whole text again, so the next one binds +// it; a compile doesn't, as it builds from what was stored. A patch can't +// write the text unchanged: the API refuses one whose old and new strings +// are the same. +// +// So now: +// - after a create, Next names what it made and writes the text there +// again with an update, the text as it was typed: `vf playbook update +// --playbook-id 6b0f… --project-id p1 --environment-alias main +// --instructions @returns.md --strict`. Text that can't go on a line of +// a hint (it holds a backtick or a line break, or came from stdin or +// --body) gets the words and the ID instead. It says not to run the +// create again. +// - after a patch, Next says the text is saved and not to run the patch +// again, that the next patch or update binds it, and offers the read +// that shows the text. +// - after any other add, it says not to run it again, and to write the +// text again with an update. +// +// An update's Next is as it was: run again, it writes the same text over +// itself, which binds it. + +package output + +import ( + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// maxRetyped is the longest text typed on the command line that a hint +// writes again in full. +const maxRetyped = 300 + +// writeAgain is the rest of --strict's Next lines after the commands that +// create what a's references name, when running cmd again would write its +// text twice; nil for an update, which writes it over itself. fix is +// whether the text itself has to change: no reference names a variable to +// create or a tool to attach. +func writeAgain(cmd *cobra.Command, res interface{}, a unboundAnswer, fix bool) []string { + name := cmd.Name() + if cmd.Parent() == nil || strings.HasPrefix(name, "update") { + return nil + } + if field, ok := strings.CutPrefix(name, "patch-"); ok { + return patchAgain(cmd, field, fix) + } + var lines []string + if fix { + lines = append(lines, "Fix the {token} in the text") + } + if name != "create" { + return append(lines, + "Then write the text again with an update of what this command wrote: a {token} binds when the field is written, not later", + "Don't run this command again: it would write it a second time") + } + group := cmd.Parent().Name() + noun := nounOf(group) + obj := createdObject(extractResultContent(res), group) + id := firstString(obj, "id") + again := "Don't run this command again: it would make a second " + noun + switch line := updateLine(cmd, sibling(cmd, "update"), id, obj, a, fix); { + case id == "": + return append(lines, "Then write the text again with an update of the "+noun+" this command made: a {token} binds when the field is written, not later", again) + case line != "": + return append(lines, "Then write it again to "+noun+" "+id+", which this command made: `"+line+"`", again) + } + return append(lines, "Then write the text again to "+noun+" "+id+", which this command made, with an update: a {token} binds when the field is written, not later", again) +} + +// patchAgain is writeAgain for a patch of field: its new text is saved, and +// the next write of the field binds it. +func patchAgain(cmd *cobra.Command, field string, fix bool) []string { + lines := []string{"Don't run this patch again: its new text is saved already", + "Once what it names exists, the next patch or update of the " + field + " binds it: each one reads the whole text again"} + if fix { + lines[1] = "Fix the {token} with a patch of the {token} itself" + } + if read := sibling(cmd, "read-"+field); read != nil { + lines = append(lines, "`"+withScope(cmd, read.CommandPath()+alsoNeeded(cmd, read, "", nil))+"` shows the "+field+" as saved") // hintfit.go, nextneeds.go: with -p, -e and the --playbook-id the patch had + } + return lines +} + +// updateLine is the update that writes the fields a's references are in to +// id, as cmd, the create that made it, was given them, or "" when one +// can't be written on a hint's line: it was in --body or a JSON flag the +// update lacks, it came from stdin, or it holds a backtick or a line break. +// With fix, the text has to change, so only a file, edited first, will do. +func updateLine(cmd, update *cobra.Command, id string, obj map[string]interface{}, a unboundAnswer, fix bool) string { + idFlag := cmd.Parent().Name() + "-id" + if id == "" || update == nil || update.Flags().Lookup(idFlag) == nil || update.Flags().Lookup(StrictFlag) == nil { + return "" + } + var paths []string + for _, r := range a.UnresolvedReferences { + paths = append(paths, r.Path) + } + for _, m := range a.UnresolvedMentions { + paths = append(paths, m.Path) + } + var text strings.Builder + written := map[string]bool{} + for _, path := range paths { + f := flagOfPath(cmd, path) + if f == nil || !f.Changed || update.Flags().Lookup(f.Name) == nil { + return "" + } + if written[f.Name] { + continue + } + written[f.Name] = true + value, ok := retyped(f, fix) + if !ok { + return "" + } + text.WriteString(" --" + f.Name + " " + value) + } + if len(written) == 0 { + return "" + } + return withScope(cmd, update.CommandPath()+" --"+idFlag+" "+id+alsoNeeded(cmd, update, idFlag, obj)) + text.String() + " --" + StrictFlag // hintfit.go: with -p and -e +} + +// flagOfPath is cmd's flag for the field a reference's path starts with: +// --instructions for "instructions", --system for "system.content". +func flagOfPath(cmd *cobra.Command, path string) *pflag.Flag { + top := path + if i := strings.IndexAny(top, ".["); i >= 0 { + top = top[:i] + } + var found *pflag.Flag + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + if found == nil && !f.Hidden && (f.Name == top || fieldOf(f.Name) == top) { + found = f + } + }) + return found +} + +// retyped is f's value as a word of a command line that gives it again: +// @returns.md as it was typed, or the text, quoted. It is false for text +// read from stdin, and for text a hint can't show on one line. +func retyped(f *pflag.Flag, fix bool) (string, bool) { + typed := flagutil.Typed(f) // flagutil/textfile.go: @returns.md, -, or the text + if file, ok := strings.CutPrefix(typed, "@"); ok && file != "" && !strings.HasPrefix(file, "@") { + return textArg(typed), true + } + if fix || typed == "-" { + return "", false + } + text := typed + if text == "" { + text = f.Value.String() + if flagutil.TakesText(f) && (strings.HasPrefix(text, "@") || text == "-") { + return "", false // text from a form that a line would read as a file + } + } + if text == "" || len(text) > maxRetyped || strings.ContainsAny(text, "`\r\n") { + return "", false + } + return textArg(text), true +} + +// textArg is s as one shell word: as it is when nothing in it is special to +// a shell, and in single quotes otherwise, where $ and { stay as typed. +func textArg(s string) string { + if s != "" && strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.,:/@%+=") == "" { + return s + } + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} + +// nounOf is a command group as a noun: "API tool" for api-tool. +func nounOf(group string) string { + words := strings.Split(group, "-") + for i, w := range words { + if w == "api" || w == "mcp" { + words[i] = strings.ToUpper(w) + } + } + return strings.Join(words, " ") +} From 1d0ac57de36ceb39d7a820e4b915ee3155a97a45 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:32:27 -0500 Subject: [PATCH 07/25] fix(tool): refuse a captureInputVariables entry keyed by an input's name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: agent-migrator:F4 created a function tool with `"captureInputVariables":{"orderId":{"variableOrEntityID":""}}` and agent-builder:F1 updated one with `{"order_number":{…}}`. Both saved with exit 0, and the tool ran with orderId "1234", but the variable stayed 0. `tool create --help` showed only `captureInputVariables?: { : … }`, and vf checked inputVariables and captureResponse but not this map. Cause: the key is the input's ID, not its name. When the agent compiles, a function tool's entry is looked up by the function input's ID (compileAgentToolFunctionCaptureInputVariables) and an API tool's by the API tool input's ID; any other key is skipped without a word. Only MCP and integration tools key it by name. The API's own description ("a map of tool input names") says otherwise, and help gave no key at all. Change: - Help says what each form keys it by: `` for the function and API forms, `` for MCP and integration, with a paragraph after captureResponse's. Create's and update's examples send an entry keyed by the same `` as inputVariables. - A function or API tool's entry keyed by an input's name is refused before anything is sent, on create and update (exit 2, invalid_body). The request's own inputVariables give the ID; otherwise a function tool's key that is neither is checked against the function's inputs (an update first reads which function the tool runs). The refusal gives the line that sends the entry under the input's ID, or, for a key that names no input, lists the inputs and the line that lists them. A dry run, or a read that fails, checks the request alone. - Not done: naming an unset `{variable}` in --strict or `vf context`. `vf context` isn't on this branch, and what sets a variable (launch variables, workflow set steps, state updates, entities, system variables) is beyond what vf reads, so the check would misfire. Tests: TestAnInputCaptureKeyedByNameIsRefusedBeforeItIsSent replays both testers' requests (create, update, agent mode, dry run, an API tool), and runs each fix through cmdcheck and then against the fake API; TestAnInputCaptureOfNoInputNamesTheInputs, TestAnInputCaptureKeyedByIDIsSent, TestToolHelpSaysWhatKeysInputCaptures. --- internal/cli/tool/create.go | 2 +- internal/cli/tool/inputcapture.go | 261 ++++++++++++++++++++++++++ internal/cli/tool/update.go | 2 +- internal/cli/tool/wiring.go | 9 +- internal/cli/toolinputcapture_test.go | 150 +++++++++++++++ 5 files changed, 419 insertions(+), 5 deletions(-) create mode 100644 internal/cli/tool/inputcapture.go create mode 100644 internal/cli/toolinputcapture_test.go diff --git a/internal/cli/tool/create.go b/internal/cli/tool/create.go index c3fdc5dc..164122bf 100644 --- a/internal/cli/tool/create.go +++ b/internal/cli/tool/create.go @@ -63,7 +63,7 @@ func runCreateCmd(cmd *cobra.Command, args []string) error { if err != nil { return err } - if err := refuseEmptyCreateCaptures(cmd, s, req); err != nil { // capture.go: a captureResponse entry with no output ID + if err := refuseCreateCaptures(cmd, s, req); err != nil { // capture.go, inputcapture.go: a captureResponse entry with no output ID, a captureInputVariables entry keyed by an input's name return err } sdkOpts, err := output.PrepareCallOpts(cmd) diff --git a/internal/cli/tool/inputcapture.go b/internal/cli/tool/inputcapture.go new file mode 100644 index 00000000..bb00c389 --- /dev/null +++ b/internal/cli/tool/inputcapture.go @@ -0,0 +1,261 @@ +// This file is not generated by Speakeasy. It says what a tool's +// captureInputVariables is keyed by, and stops a function or API tool from +// saving an entry keyed by an input's name. +// +// A captureInputVariables entry copies what the agent passes to one of the +// tool's inputs into a variable as well. Help showed only +// `captureInputVariables?: { : {…} }`, and the API describes it as "a +// map of tool input names". Two round-8 testers keyed it by the input's +// name, as inputVariables is: {"orderId":{"variableOrEntityID":"…"}} +// (agent-migrator:F4) and {"order_number":{…}} (agent-builder:F1). Both +// saved with exit 0, and the tool ran with orderId "1234", but the variable +// stayed 0. When the agent is compiled, a function tool's entry is looked +// up by the function input's ID and an API tool's by the API tool input's +// ID, and an entry under any other key is skipped without a word. Only an +// MCP or integration tool's is keyed by the input's name. +// +// Help now says so, with an example. A function or API tool's entry keyed +// by an input's name is refused before anything is sent (exit 2): the +// request's own inputVariables, keyed by name, give the input's ID, so the +// refusal gives the line that sends the entry under it. A function tool's +// key that is neither is checked against the function's inputs, read from +// the API (an update first reads which function the tool runs): one of +// their names gets the same line, and a key that names none of them is +// refused with the inputs listed. A dry run reads nothing, and a read that +// fails mustn't stop a write: then only the request's own inputs are +// checked. + +package tool + +import ( + "errors" + "maps" + "slices" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk" + "github.com/voiceflow/cli/internal/sdk/models/operations" +) + +// inputCaptureShape is how help writes a form's captureInputVariables. +const inputCaptureShape = "captureInputVariables?: { : { variableOrEntityID: string | null, captureType?: string } }" + +// inputCapturesHelp is what create's and update's help say of a tool's +// captureInputVariables. +const inputCapturesHelp = "To keep what the agent passes to an input as well, add a captureInputVariables entry, with the variable to set as variableOrEntityID. " + + "A function tool keys it by the input's ID (its functionInputVariableID, not its name), an API tool by its apiToolInputVariableID, " + + "and an MCP or integration tool by the input's name. The API saves an entry keyed otherwise but never sets its variable, " + + "so vf refuses a function or API tool's entry keyed by an input's name." + +// inputCaptureKeys are what each form's captureInputVariables is keyed by, +// as help writes it. +var inputCaptureKeys = map[string]string{"api": "", "function": "", "mcp": "", "integration": ""} + +// inputIDField is the field of an inputVariables entry that holds the +// input's ID, for the forms whose captureInputVariables is keyed by it. +var inputIDField = map[string]string{"function": "functionInputVariableID", "api": "apiToolInputVariableID"} + +// explainInputCaptures gives create's or update's help what each form's +// captureInputVariables is keyed by. Their examples (wiring.go) send one. +func explainInputCaptures(cmd *cobra.Command) { + cmd.Long += "\n\n" + inputCapturesHelp + for form, key := range inputCaptureKeys { + if f := cmd.Flags().Lookup("body-param." + form); f != nil { + f.Usage = strings.Replace(f.Usage, inputCaptureShape, strings.Replace(inputCaptureShape, "", key, 1), 1) + } + } +} + +// refuseCreateCaptures refuses a create whose captureResponse or +// captureInputVariables would save an entry that never sets its variable. +func refuseCreateCaptures(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableToolControllerCreateV2Request) error { + if err := refuseEmptyCreateCaptures(cmd, s, req); err != nil { // capture.go + return err + } + return refuseNamedCreateInputCaptures(cmd, s, req) +} + +// refuseUpdateCaptures is refuseCreateCaptures for an update. +func refuseUpdateCaptures(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableToolControllerUpdateV2Request) error { + if err := refuseEmptyUpdateCaptures(cmd, s, req); err != nil { // capture.go + return err + } + return refuseNamedUpdateInputCaptures(cmd, s, req) +} + +// functionInputs reads a function tool's inputs when a key needs them: the +// inputs, the command that lists them, and whether they were read. +type functionInputs func() (inputs []functionInput, list string, read bool) + +// refuseNamedCreateInputCaptures refuses a function or API tool's create +// whose captureInputVariables entry is keyed by an input's name, before it +// is sent. +func refuseNamedCreateInputCaptures(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableToolControllerCreateV2Request) error { + scope := []string{"--project-id", shellWord(req.ProjectID), "--environment-alias", shellWord(req.EnvironmentAlias)} + line := func(form string) func(body string) string { + return func(body string) string { + return strings.Join(append([]string{"vf tool create"}, append(scope, "--body-param."+form, shellWord(body))...), " ") + } + } + switch body := req.Body; { + case body.StableToolCreateRequestV2Function != nil: + fn := body.StableToolCreateRequestV2Function + read := func() ([]functionInput, string, bool) { + list := strings.Join(append([]string{"vf function variable list --function-id", shellWord(fn.FunctionID)}, scope...), " ") + if client.IsDryRun(cmd) || fn.FunctionID == "" { + return nil, list, false + } + inputs, _, ok := functionVariables(cmd, s, req.ProjectID, req.EnvironmentAlias, fn.FunctionID) + return inputs, list, ok + } + return refuseNamedInputCaptures(cmd, "function", fn, read, line("function")) + case body.StableToolCreateRequestV2API != nil: + return refuseNamedInputCaptures(cmd, "api", body.StableToolCreateRequestV2API, nil, line("api")) + } + return nil +} + +// refuseNamedUpdateInputCaptures refuses a function or API tool's update +// that would set a captureInputVariables entry keyed by an input's name, +// before it is sent. +func refuseNamedUpdateInputCaptures(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableToolControllerUpdateV2Request) error { + scope := []string{"--project-id", shellWord(req.ProjectID), "--environment-alias", shellWord(req.EnvironmentAlias)} + line := func(form string) func(body string) string { + return func(body string) string { + return strings.Join(append([]string{"vf tool update --tool-id", shellWord(req.ToolID)}, append(scope, "--body-param."+form, shellWord(body))...), " ") + } + } + switch body := req.Body; { + case body.StableToolUpdateRequestV2Function != nil: + read := func() ([]functionInput, string, bool) { + list := strings.Join(append([]string{"vf tool get --tool-id", shellWord(req.ToolID), "--type function"}, scope...), " ") + if client.IsDryRun(cmd) { + return nil, list, false + } + functionID := readFunctionID(cmd, s, req) // capture.go + if functionID == "" { + return nil, list, false + } + list = strings.Join(append([]string{"vf function variable list --function-id", shellWord(functionID)}, scope...), " ") + inputs, _, ok := functionVariables(cmd, s, req.ProjectID, req.EnvironmentAlias, functionID) + return inputs, list, ok + } + return refuseNamedInputCaptures(cmd, "function", body.StableToolUpdateRequestV2Function, read, line("function")) + case body.StableToolUpdateRequestV2API != nil: + return refuseNamedInputCaptures(cmd, "api", body.StableToolUpdateRequestV2API, nil, line("api")) + } + return nil +} + +// refuseNamedInputCaptures refuses sent, a form whose captureInputVariables +// entry isn't keyed by an input's ID. Its own inputVariables say which +// names are inputs, and their IDs; read gives the function's inputs, when a +// key is neither (nil for an API tool, whose keys are checked against the +// request alone). line is the command that sends a body. +func refuseNamedInputCaptures(cmd *cobra.Command, form string, sent any, read functionInputs, line func(body string) string) error { + body, ok := formJSON(sent) // capture.go + if !ok { + return nil + } + captures, _ := body["captureInputVariables"].(map[string]any) + ids, byName := map[string]bool{}, map[string]string{} + inputs, _ := body["inputVariables"].(map[string]any) + for name, entry := range inputs { + if e, ok := entry.(map[string]any); ok { + if id, _ := e[inputIDField[form]].(string); id != "" { + ids[id], byName[name] = true, id + } + } + } + named := map[string]string{} // a key that is an input's name, and the input's ID + var unknown []string + for key, entry := range captures { + switch id, isName := byName[key]; { + case entry == nil || ids[key]: // null removes the entry + case isName: + named[key] = id + default: + unknown = append(unknown, key) + } + } + var fnInputs []functionInput + list, checked := "", false + if len(unknown) > 0 && read != nil { + fnInputs, list, checked = read() + } + if checked { + known := map[string]bool{} + for _, in := range fnInputs { + known[in.ID] = true + } + unknown = slices.DeleteFunc(unknown, func(key string) bool { + for _, in := range fnInputs { + if in.Name == key { + named[key] = in.ID + return true + } + } + return known[key] + }) + } else { + unknown = nil // nothing says what they are + } + if len(named) == 0 && len(unknown) == 0 { + return nil + } + explained := namedCapturesReport(form, captures, named, unknown, fnInputs, list, body, line) + return output.Report(cmd, explained, errors.New(explained.Title)) +} + +// namedCapturesReport says that captures' entries named are keyed by an +// input's name, and unknown by no input of the function's at all, and gives +// the line that sends body with them fixed, or the one that lists inputs. +func namedCapturesReport(form string, captures map[string]any, named map[string]string, unknown []string, inputs []functionInput, list string, body map[string]any, line func(body string) string) output.Explanation { + keys := slices.Sorted(maps.Keys(named)) + slices.Sort(unknown) + bad := append(append([]string{}, keys...), unknown...) + slices.Sort(bad) + field := inputIDField[form] + noun := map[string]string{"function": "A function", "api": "An API"}[form] + var title string + switch { + case len(unknown) == 0 && len(keys) == 1: + title = "captureInputVariables." + keys[0] + " is keyed by the input's name, not its ID" + case len(unknown) == 0: + title = "captureInputVariables entries " + strings.Join(keys, ", ") + " are keyed by the inputs' names, not their IDs" + case len(bad) == 1: + title = "captureInputVariables." + bad[0] + " names none of the function's inputs" + default: + title = "captureInputVariables entries " + strings.Join(bad, ", ") + " aren't keyed by the function's input IDs" + } + why := []string{noun + " tool's captureInputVariables entry is keyed by the input's ID, its " + field + ", not its name. " + + "The API saves an entry under any other key but never sets its variable, so nothing was sent."} + var next []string // a line with quoted JSON goes without `…`, which would quote it again + switch { + case len(unknown) == 0: + for _, key := range keys { + if _, both := captures[named[key]]; !both { + captures[named[key]] = captures[key] + } + delete(captures, key) + } + next = append(next, "Send it keyed by the input's ID: "+line(compactJSON(body))) + case len(inputs) == 0: + why = append(why, "The function takes no inputs, so there is nothing to capture.") + for _, key := range bad { + delete(captures, key) + } + if len(captures) == 0 { + delete(body, "captureInputVariables") + } + next = append(next, "Send it without them: "+line(compactJSON(body))) + default: + why = append(why, "The function's inputs: "+outputList(inputs)+".") // capture.go: name (ID) + next = append(next, "`"+list+"` lists the function's inputs: key each entry by one's ID") + } + return output.Explanation{Type: "invalid_body", Title: title, Why: why, Next: next} +} diff --git a/internal/cli/tool/update.go b/internal/cli/tool/update.go index c90d032b..461faad1 100644 --- a/internal/cli/tool/update.go +++ b/internal/cli/tool/update.go @@ -64,7 +64,7 @@ func runUpdateCmd(cmd *cobra.Command, args []string) error { if err != nil { return err } - if err := refuseEmptyUpdateCaptures(cmd, s, req); err != nil { // capture.go: a captureResponse entry with no output ID + if err := refuseUpdateCaptures(cmd, s, req); err != nil { // capture.go, inputcapture.go: a captureResponse entry with no output ID, a captureInputVariables entry keyed by an input's name return err } sdkOpts, err := output.PrepareCallOpts(cmd) diff --git a/internal/cli/tool/wiring.go b/internal/cli/tool/wiring.go index 9e417dfa..3d602944 100644 --- a/internal/cli/tool/wiring.go +++ b/internal/cli/tool/wiring.go @@ -59,16 +59,19 @@ func explainInputs(cmd *cobra.Command) { 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"}},` + - `"captureResponse":{"order_status":{"functionOutputVariableID":"","variableOrEntityID":""}}}'` + `"captureResponse":{"order_status":{"functionOutputVariableID":"","variableOrEntityID":""}},` + + `"captureInputVariables":{"":{"variableOrEntityID":""}}}'` 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":""}}}'` + `'{"inputVariables":{"order_number":{"functionInputVariableID":""}},` + + `"captureInputVariables":{"":{"variableOrEntityID":""}}}'` } if f := cmd.Flags().Lookup("body-param.function"); f != nil { f.Usage = strings.Replace(f.Usage, collapsedInputs, inputEntry, 1) } - explainCaptures(cmd) // capture.go: and its captureResponse entries + explainCaptures(cmd) // capture.go: and its captureResponse entries + explainInputCaptures(cmd) // inputcapture.go: and what its captureInputVariables is keyed by } // wiring is what the check reads of a function tool. diff --git a/internal/cli/toolinputcapture_test.go b/internal/cli/toolinputcapture_test.go new file mode 100644 index 00000000..d70ff494 --- /dev/null +++ b/internal/cli/toolinputcapture_test.go @@ -0,0 +1,150 @@ +// This file is not generated by Speakeasy. It covers tool/inputcapture.go: +// a function or API tool's captureInputVariables entry keyed by an input's +// name is refused before it is sent, with a line that sends it keyed by the +// input's ID and runs as written. + +package cli + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/cmdcheck" +) + +// R8 #6 (agent-migrator:F4, agent-builder:F1): both testers keyed a +// function tool's captureInputVariables by the input's name, as +// inputVariables is. The API saved it, vf exited 0, and the variable was +// never set: the entry is looked up by the input's ID. Each request is +// replayed against toolCaptureServer, whose lookup_order takes order_number. +func TestAnInputCaptureKeyedByNameIsRefusedBeforeItIsSent(t *testing.T) { + scope := []string{"-p", "p1", "-e", "main"} + byName := `"captureInputVariables":{"order_number":{"variableOrEntityID":"` + statusVar + `"}}` + // agent-migrator's create: the request's own inputVariables say which ID order_number has. + create := `{"functionID":"` + lookupOrder + `","target":{"global":true},"description":"Looks up the status of a customer order by its order ID",` + + `"inputVariables":{"order_number":{"functionInputVariableID":"` + orderNumber + `","description":"The order ID the customer gives","required":true}},` + byName + `}` + // agent-builder's update: only the function's inputs, read, do. + update := `{` + byName + `}` + api := `{"apiToolID":"6b0f0a00a7f5577610a30001","target":{"global":true},` + + `"inputVariables":{"order_number":{"apiToolInputVariableID":"6b0f0a00a7f5577610a30002"}},` + byName + `}` + cases := []struct { + name string + agent bool + args []string + requests string // what the refused command sent + fix string // what the line given sends + key string // the key it sends the entry under + }{ + {"create", false, append([]string{"create"}, append(scope, "--body-param.function", create)...), "", "POST /v2/stable/tool", orderNumber}, + {"create, agent mode", true, append([]string{"create"}, append(scope, "--body-param.function", create)...), "", "POST /v2/stable/tool", orderNumber}, + {"create, dry run", false, append([]string{"create"}, append(scope, "--body-param.function", create, "--dry-run")...), "", "POST /v2/stable/tool", orderNumber}, + {"update", false, append([]string{"update", "--tool-id", newTool}, append(scope, "--body-param.function", update)...), + "GET /v2/stable/tool/" + newTool + ", GET /v1/stable/function-variable", "PATCH /v2/stable/tool/" + newTool, orderNumber}, + {"update, agent mode", true, append([]string{"update", "--tool-id", newTool}, append(scope, "--body-param.function", update)...), + "GET /v2/stable/tool/" + newTool + ", GET /v1/stable/function-variable", "PATCH /v2/stable/tool/" + newTool, orderNumber}, + {"API tool create", false, append([]string{"create"}, append(scope, "--body-param.api", api)...), "", "POST /v2/stable/tool", "6b0f0a00a7f5577610a30002"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + url, requests, _ := toolCaptureServer(t, `{}`) + _, stderr, err := runTool(t, url, c.agent, c.args...) + if err == nil || ExitCode(err) != 2 { + t.Fatalf("err %v (exit %d), want a usage error:\n%s", err, ExitCode(err), stderr) + } + if got := strings.Join(requests(), ", "); got != c.requests { + t.Errorf("requests:\n got %s\nwant %s", got, c.requests) + } + if !strings.Contains(stderr, "captureInputVariables.order_number is keyed by the input's name, not its ID") || + !strings.Contains(stderr, "nothing was sent") { + t.Errorf("stderr doesn't say why:\n%s", stderr) + } + if c.agent { + var x struct { + Type string `json:"error_type"` + } + if err := json.Unmarshal([]byte(stderr), &x); err != nil || x.Type != "invalid_body" { + t.Errorf("stderr isn't one JSON error of type invalid_body (%v):\n%s", err, stderr) + } + } + line := fixLine(t, stderr) + if problems := cmdcheck.Check(testRoot(t), line, cmdcheck.Options{Complete: true}); len(problems) > 0 { + t.Fatalf("the fix %q doesn't run as written: %v", line, problems) + } + // The fix runs, and sends the entry keyed by the input's ID. + url, requests, bodies := toolCaptureServer(t, `{}`) + words := shellWords(t, line) + if _, stderr, err := runTool(t, url, false, words[2:]...); err != nil { + t.Fatalf("the fix %q failed: %v\n%s", line, err, stderr) + } else if strings.Contains(stderr, "captureInputVariables") { + t.Errorf("the fix still complains:\n%s", stderr) + } + if got := requests(); !strings.Contains(strings.Join(got, ", "), c.fix) { + t.Errorf("the fix sent %v, want %s", got, c.fix) + } + sent := strings.Join(bodies(), "\n") + if !strings.Contains(sent, `"captureInputVariables":{"`+c.key+`":{"variableOrEntityID":"`+statusVar+`"}}`) { + t.Errorf("the fix sent:\n%s", sent) + } + }) + } +} + +// A key that is neither an input's ID nor its name: vf names the +// function's inputs and the line that lists them. +func TestAnInputCaptureOfNoInputNamesTheInputs(t *testing.T) { + url, requests, _ := toolCaptureServer(t, `{}`) + _, stderr, err := runTool(t, url, false, "update", "--tool-id", newTool, "-p", "p1", "-e", "main", "--body-param.function", + `{"captureInputVariables":{"orderId":{"variableOrEntityID":"`+statusVar+`"}}}`) + if ExitCode(err) != 2 || strings.Contains(strings.Join(requests(), ", "), "PATCH") { + t.Fatalf("err %v, requests %v:\n%s", err, requests(), stderr) + } + if !strings.Contains(stderr, "captureInputVariables.orderId names none of the function's inputs") || + !strings.Contains(stderr, "order_number ("+orderNumber+")") { + t.Errorf("stderr:\n%s", stderr) + } + line := fixLine(t, stderr) + if line != "vf function variable list --function-id "+lookupOrder+" --project-id p1 --environment-alias main" { + t.Errorf("line: %s", line) + } + if problems := cmdcheck.Check(testRoot(t), line, cmdcheck.Options{Complete: true}); len(problems) > 0 { + t.Errorf("%q doesn't run as written: %v", line, problems) + } +} + +// An entry keyed by the input's ID is sent, as is one sent as null, which +// removes it. +func TestAnInputCaptureKeyedByIDIsSent(t *testing.T) { + for _, body := range []string{ + `{"captureInputVariables":{"` + orderNumber + `":{"variableOrEntityID":"` + statusVar + `"}}}`, + `{"captureInputVariables":{"order_number":null}}`, + } { + url, requests, _ := toolCaptureServer(t, `{}`) + if _, stderr, err := runTool(t, url, false, "update", "--tool-id", newTool, "-p", "p1", "-e", "main", "--body-param.function", body); err != nil { + t.Errorf("%s: %v\n%s", body, err, stderr) + } + if !strings.Contains(strings.Join(requests(), ", "), "PATCH /v2/stable/tool/"+newTool) { + t.Errorf("%s: requests %v", body, requests()) + } + } +} + +func TestToolHelpSaysWhatKeysInputCaptures(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) + for form, key := range map[string]string{"function": "", "api": "", "mcp": "", "integration": ""} { + if f := c.Flags().Lookup("body-param." + form); f == nil || !strings.Contains(f.Usage, "captureInputVariables?: { "+key+": { variableOrEntityID") { + t.Errorf("%s --body-param.%s: %v", verb, form, f) + } + } + if !strings.Contains(c.Long, "A function tool keys it by the input's ID (its functionInputVariableID, not its name)") { + t.Errorf("%s Long: %s", verb, c.Long) + } + if !strings.Contains(c.Example, `"captureInputVariables":{"":{"variableOrEntityID":`) { + t.Errorf("%s Example: %s", verb, c.Example) + } + } +} From ad2124b55937ea644d094ddc5fe7b30c876cc0a2 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:44:34 -0500 Subject: [PATCH 08/25] fix(scripting): a JSON flag whose keys were all dropped sends nothing, so an empty update is refused MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: fix-verifier:N10 ran `vf agent update -p … -e main --llm '{"temperature":0.3}'`, at a terminal and with --dry-run: ⚠ --llm has keys vf agent update doesn't take, so they weren't sent: temperature ✓ Agent updated. --dry-run body: { "llm": {} } Exit 0, and nothing changed. The key the API takes is llm.defaults.temperature. Cause: the SDK decodes --llm into an llm object and drops temperature, which that object has no field for (flagutil/unknownkeys.go names it). The object is still set, empty, so the body is {"llm":{}}. ff70cc5's check for an update that sets nothing (client/emptyupdate.go) looks for `{}` only, so it let this through. The same key in --body ({"llm":{"temperature":…}}) did the same. Change: - An object given with keys, every one of which was dropped, is left out of the request as if it hadn't been given (flagutil/droppedkeys.go): a JSON flag's own value, and an object at any depth of --body, stdin or a JSON flag. An object given as {} is still sent. So this update is now `{}` and refused before it is sent, dry run included: exit 2, nothing_to_update. - A dropped key that names one field one or two levels down is a near match. The warning says where it goes: "temperature is a key of defaults" and "--llm '{"defaults":{"temperature":0.3}}' sends it there". - The refusal (output/droppedupdate.go) says "--llm set no field: vf agent update doesn't take temperature." and "--llm takes temperature as defaults.temperature.", and gives the line that sends it there: `vf agent update --llm '{"defaults":{"temperature":0.3}}' --project-id p1 --environment-alias main`. With no near match it says what the flag takes instead. --body with no near match keeps ff70cc5's message. - A key dropped beside keys that are taken: the rest is sent without it. Tests: TestAnUpdateWhoseKeysWereAllDroppedIsNotSent replays N10 (--llm and --body, human and agent, real and --dry-run), and runs each line given through cmdcheck and then against the fake API, which gets {"llm":{"defaults":{"temperature":0.3}}}. TestADroppedKeyBesideOthersIsLeftOut, TestADroppedKeyWithNoMatchSaysWhatTheFlagTakes. Each fails with the hooks reverted. --- internal/cli/droppedupdate_test.go | 127 ++++++++++++ internal/flagutil/droppedkeys.go | 321 +++++++++++++++++++++++++++++ internal/flagutil/metadata.go | 2 +- internal/flagutil/unknownkeys.go | 1 + internal/output/droppedupdate.go | 77 +++++++ internal/output/emptyupdate.go | 3 + 6 files changed, 530 insertions(+), 1 deletion(-) create mode 100644 internal/cli/droppedupdate_test.go create mode 100644 internal/flagutil/droppedkeys.go create mode 100644 internal/output/droppedupdate.go diff --git a/internal/cli/droppedupdate_test.go b/internal/cli/droppedupdate_test.go new file mode 100644 index 00000000..130d4a54 --- /dev/null +++ b/internal/cli/droppedupdate_test.go @@ -0,0 +1,127 @@ +// This file is not generated by Speakeasy. It covers flagutil/droppedkeys.go +// and output/droppedupdate.go: a JSON value whose keys were all dropped +// isn't sent as {}, so an update it leaves empty is refused, with the line +// that sends each key where the API takes it. + +package cli + +import ( + "encoding/json" + "io" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/cmdcheck" + "github.com/voiceflow/cli/internal/output" +) + +// stderrHints are the hints of each JSON object an agent got on stderr, or +// stderr's lines for a person. +func stderrHints(t *testing.T, stderr string, agent bool) []string { + t.Helper() + if !agent { + return strings.Split(stderr, "\n") + } + var hints []string + dec := json.NewDecoder(strings.NewReader(stderr)) + for { + var x struct { + Hints []string `json:"hints"` + } + if err := dec.Decode(&x); err == io.EOF { + return hints + } else if err != nil { + t.Fatalf("stderr isn't JSON objects: %v\n%s", err, stderr) + } + hints = append(hints, x.Hints...) + } +} + +// sendLine is the line after "Send it there: " in what stderr says. +func sendLine(t *testing.T, stderr string, agent bool) string { + t.Helper() + for _, h := range stderrHints(t, stderr, agent) { + if _, line, ok := strings.Cut(h, "Send it there: "); ok { + return strings.TrimSpace(line) + } + } + t.Fatalf("no line sends it:\n%s", stderr) + return "" +} + +// R8 #54 (fix-verifier:N10): `agent update --llm '{"temperature":0.3}'` +// warned that temperature isn't a key --llm takes, then sent `{"llm": {}}` +// and said "✓ Agent updated." with exit 0, at a terminal and with +// --dry-run. Now nothing is sent: exit 2, nothing_to_update, naming +// defaults.temperature, with a line that sends it there and runs. The same +// key in --body is the same update. +func TestAnUpdateWhoseKeysWereAllDroppedIsNotSent(t *testing.T) { + cases := []struct { + args []string + sent string // what the line given sends + }{ + {[]string{"agent", "update", "-p", "p1", "-e", "main", "--llm", `{"temperature":0.3}`}, `{"llm":{"defaults":{"temperature":0.3}}}`}, + {[]string{"agent", "update", "-p", "p1", "-e", "main", "--body", `{"llm":{"temperature":0.3}}`}, `{"llm":{"defaults":{"temperature":0.3}}}`}, + } + for _, c := range cases { + for _, agent := range []bool{false, true} { + for _, dry := range []bool{false, true} { + args := c.args + if dry { + args = append(append([]string{}, args...), "--dry-run") + } + stdout, stderr, bodies, err := runUpdate(t, agent, args...) + if len(bodies) != 0 { + t.Errorf("%v: sent %q", args, bodies) + } + if code := output.ExitCode(err); code != output.ExitUsage { + t.Errorf("%v: exit %d, want %d (err %v)", args, code, output.ExitUsage, err) + } + if strings.Contains(stdout+stderr, "updated") || strings.Contains(stderr, "[DRY-RUN] Body") { + t.Errorf("%v: it says it was sent:\n%s%s", args, stdout, stderr) + } + for _, want := range []string{"nothing to change", "temperature as ", "defaults.temperature", "nothing was sent"} { + if !strings.Contains(stderr, want) { + t.Errorf("%v: stderr lacks %q:\n%s", args, want, stderr) + } + } + if agent && !strings.Contains(stderr, `"error_type": "nothing_to_update"`) { + t.Errorf("%v: no nothing_to_update:\n%s", args, stderr) + } + line := sendLine(t, stderr, agent) + if problems := cmdcheck.Check(testRoot(t), line, cmdcheck.Options{Complete: true}); len(problems) > 0 { + t.Fatalf("%v: %q doesn't run as written: %v", args, line, problems) + } + _, stderr, bodies, err = runUpdate(t, false, shellWords(t, line)[1:]...) + if err != nil || len(bodies) != 1 || !strings.HasSuffix(bodies[0], " "+c.sent) { + t.Errorf("%v: %s sent %q (err %v)\n%s", args, line, bodies, err, stderr) + } + } + } + } +} + +// A dropped key among keys that are taken: the rest is sent, without the +// key, and the warning says where it goes. +func TestADroppedKeyBesideOthersIsLeftOut(t *testing.T) { + _, stderr, bodies, err := runUpdate(t, false, "agent", "update", "-p", "p1", "-e", "main", "--llm", `{"temperature":0.3,"priorityProcessing":true}`) + if err != nil || len(bodies) != 1 || !strings.HasSuffix(bodies[0], ` {"llm":{"priorityProcessing":true}}`) { + t.Fatalf("sent %q (err %v)\n%s", bodies, err, stderr) + } + if !strings.Contains(stderr, `temperature is a key of defaults`) || + !strings.Contains(stderr, `--llm '{"defaults":{"temperature":0.3},"priorityProcessing":true}' sends it there`) { + t.Errorf("stderr:\n%s", stderr) + } +} + +// A key that is nowhere further down: what --llm takes, and no line. +func TestADroppedKeyWithNoMatchSaysWhatTheFlagTakes(t *testing.T) { + _, stderr, bodies, err := runUpdate(t, false, "agent", "update", "-p", "p1", "-e", "main", "--llm", `{"temp":0.3}`) + if len(bodies) != 0 || output.ExitCode(err) != output.ExitUsage { + t.Fatalf("sent %q (err %v)\n%s", bodies, err, stderr) + } + if !strings.Contains(stderr, "--llm set no field: vf agent update doesn't take temp.") || + !strings.Contains(stderr, "--llm takes: priorityProcessing, defaults.") || strings.Contains(stderr, "Send it there") { + t.Errorf("stderr:\n%s", stderr) + } +} diff --git a/internal/flagutil/droppedkeys.go b/internal/flagutil/droppedkeys.go new file mode 100644 index 00000000..580711f1 --- /dev/null +++ b/internal/flagutil/droppedkeys.go @@ -0,0 +1,321 @@ +// This file is not generated by Speakeasy. It keeps an object whose every +// key was dropped from being sent as {}, and says where a dropped key goes. +// +// `vf agent update --llm '{"temperature":0.3}'` warned that --llm doesn't +// take temperature (unknownkeys.go), then sent `{"llm": {}}` and printed +// "✓ Agent updated." (fix-verifier:N10). The SDK had decoded the flag into +// an llm object with nothing in it, and an object, even an empty one, is a +// field, so the check for an update that sets nothing +// (client/emptyupdate.go, which looks for `{}`) let it through. Nothing +// changed, and a script read exit 0. The key the API takes is +// llm.defaults.temperature. +// +// Now an object given with keys, every one of which was dropped, is left +// out of the request, as though it hadn't been given: a JSON flag's own +// value, or {"llm":{"temperature":0.3}} in --body. An update left with no +// field is then refused before it is sent, as nothing_to_update (exit 2). +// A dropped key that is the name of a field one or two levels down, in one +// place only, is a near match: the warning says where it goes, and the +// refusal (output/droppedupdate.go) gives the line that sends it there. + +package flagutil + +import ( + "bytes" + "encoding/json" + "reflect" + "strings" + + "github.com/spf13/cobra" +) + +// Dropped is what a JSON value given to a command lost to keys the +// request has no field for. +type Dropped struct { + Source string `json:"source"` // --llm, --body or stdin + Keys []string `json:"keys"` // temperature, or llm.temperature in --body + Moved map[string]string `json:"moved,omitempty"` // a key, and where the request takes it: defaults.temperature + Fixed string `json:"fixed,omitempty"` // the value given, with every key moved there + Takes []string `json:"takes,omitempty"` // "--llm takes: priorityProcessing, defaults" + Given string `json:"given"` // the value as given +} + +// droppedKey is the command annotation that holds what cmd's JSON values +// lost, as a JSON list of Dropped. +const droppedKey = "vf:dropped-keys" + +// maxFixed is the longest value a hint gives again with its keys moved. +const maxFixed = 300 + +// DroppedKeys is what the JSON flags of this run of cmd lost to keys its +// request has no field for, in the order they were read. A note from an +// earlier run of the same command, in a test, is told apart by the value +// given; stdin's are left out, as one can't be. +func DroppedKeys(cmd *cobra.Command) []Dropped { + var all, now []Dropped + if data := cmd.Annotations[droppedKey]; data != "" { + _ = json.Unmarshal([]byte(data), &all) + } + for _, d := range all { + if f := cmd.Flags().Lookup(strings.TrimPrefix(d.Source, "--")); f != nil && f.Changed && f.Value.String() == d.Given { + now = append(now, d) + } + } + return now +} + +// afterDropped is called once the keys found in data, the JSON given as +// source and decoded into into, have been warned of. It leaves out each +// object below into that they emptied, notes them on cmd, and returns the +// warning's hints for those that are a near match. +func afterDropped(cmd *cobra.Command, source string, data []byte, node any, into reflect.Value, found []unknownKey) []string { + clearEmptied(node, into, false) + d := Dropped{Source: source, Moved: map[string]string{}, Given: string(data)} + fixed, _ := decodeNumbers(data) + said := map[string]bool{} + for _, k := range found { + d.Keys = append(d.Keys, k.path) + parent, key := "", k.path + if i := strings.LastIndex(k.path, "."); i >= 0 { + parent, key = k.path[:i], k.path[i+1:] + } + label := parent + " takes: " + if parent == "" { + label = source + " takes: " + if source == "stdin" { + label = "The body takes: " + } + } + if keys := keysOf(k.in); keys != "" && !said[parent] { + said[parent] = true + d.Takes = append(d.Takes, label+keys) + } + if strings.Contains(k.path, "[]") { + continue + } + if near := nearMatches(k.in, key); len(near) == 1 { + to := joinPath(parent, near[0]) + if moveKey(fixed, k.path, to) { + d.Moved[k.path] = to + } + } + } + if len(d.Moved) == len(d.Keys) { + if text := compact(fixed); text != "" && len(text) <= maxFixed && !strings.ContainsAny(text, "`\n") { + d.Fixed = text + } + } + record(cmd, d) + var hints []string + for _, from := range sortedKeys(d.Moved) { + to := d.Moved[from] + hints = append(hints, to[strings.LastIndex(to, ".")+1:]+" is a key of "+to[:strings.LastIndex(to, ".")]) + } + if d.Fixed != "" && source != "stdin" { + hints = append(hints, source+" "+singleQuoted(d.Fixed)+" sends "+plural(len(d.Moved), "it", "them")+" there") + } + return hints +} + +// singleQuoted is s as one shell word in single quotes. +func singleQuoted(s string) string { + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} + +// plural is one for n of 1, else many. +func plural(n int, one, many string) string { + if n == 1 { + return one + } + return many +} + +// record notes d on cmd. +func record(cmd *cobra.Command, d Dropped) { + data, err := json.Marshal(append(DroppedKeys(cmd), d)) + if err != nil { + return + } + if cmd.Annotations == nil { + cmd.Annotations = map[string]string{} + } + cmd.Annotations[droppedKey] = string(data) +} + +// warnUnknownFlagKeys is warnUnknownKeys for a JSON flag's value, decoded +// into field: when every key it was given was dropped, the field is left +// out too, rather than sent as {}. +func warnUnknownFlagKeys(cmd *cobra.Command, source string, data []byte, field reflect.Value) { + warnUnknownKeys(cmd, source, data, field) + if node, err := decodeNumbers(data); err == nil { + clearEmptied(node, field, true) + } +} + +// clearEmptied zeroes each value below v, and v itself with self, that +// node, an object, gave keys for that were all dropped or emptied in turn. +// It reports whether node was emptied. A map, a union and a type that keeps +// keys it has no field for are left as they are. +func clearEmptied(node any, v reflect.Value, self bool) bool { + obj, ok := node.(map[string]any) + if !ok || len(obj) == 0 || !v.IsValid() { + return false + } + inner := v + for { + switch { + case inner.Kind() == reflect.Ptr || inner.Kind() == reflect.Interface: + if inner.IsNil() { + return false + } + inner = inner.Elem() + continue + case inner.Kind() == reflect.Map && inner.Type().Key().Kind() == reflect.Bool && inner.Type().Elem().Kind() == reflect.Ptr: + // optionalnullable.OptionalNullable[T] is a map[bool]*T. + inner = inner.MapIndex(reflect.ValueOf(true)) + if !inner.IsValid() { + return false + } + continue + } + break + } + t := inner.Type() + if inner.Kind() != reflect.Struct || isScalarStruct(t) || isUnion(t) { + return false + } + fields, open := jsonFields(t) + if open { + return false + } + emptied := true + for _, key := range sortedKeys(obj) { + i, ok := fields[key] + if !ok && !implementsUnmarshaler(t) { + i, ok = fieldFold(fields, key) + } + if ok && !clearEmptied(obj[key], inner.Field(i), true) { + emptied = false + } + } + if emptied && self && v.CanSet() { + v.Set(reflect.Zero(v.Type())) + } + return emptied +} + +// nearMatches are the paths to a field named key one or two levels below +// struct t: defaults.temperature for temperature in an agent's llm. +func nearMatches(t reflect.Type, key string) []string { + var found []string + var walk func(t reflect.Type, prefix string, depth int) + walk = func(t reflect.Type, prefix string, depth int) { + t = structOf(t) + if t == nil || depth > 2 { + return + } + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + name := jsonName(f) + if !f.IsExported() || name == "-" || f.Tag.Get("additionalProperties") == "true" { + continue + } + if depth > 0 && strings.EqualFold(name, key) { + found = append(found, prefix+name) + } + walk(f.Type, prefix+name+".", depth+1) + } + } + walk(t, "", 0) + return found +} + +// structOf is the struct t holds, through pointers and OptionalNullable, or +// nil for anything else: a scalar, a map, a list or a union. +func structOf(t reflect.Type) reflect.Type { + for { + switch { + case t.Kind() == reflect.Ptr: + t = t.Elem() + continue + case t.Kind() == reflect.Map && t.Key().Kind() == reflect.Bool && t.Elem().Kind() == reflect.Ptr: + t = t.Elem().Elem() + continue + } + break + } + if t.Kind() != reflect.Struct || isScalarStruct(t) || isUnion(t) { + return nil + } + return t +} + +// moveKey moves the value at path from in node to path to, making the +// objects on the way. It is false, and node is left as it was, when either +// path runs through something that isn't an object or to is taken. +func moveKey(node any, from, to string) bool { + src, key, ok := objectAt(node, from, false) + if !ok { + return false + } + value, ok := src[key] + if !ok { + return false + } + if dst, last, ok := objectAt(node, to, false); ok { + if _, taken := dst[last]; taken { + return false + } + } + dst, last, ok := objectAt(node, to, true) + if !ok { + return false + } + delete(src, key) + dst[last] = value + return true +} + +// objectAt is the object in node that holds path's last key, and that key. +// With create, the objects on the way that are missing are made. +func objectAt(node any, path string, create bool) (map[string]any, string, bool) { + parts := strings.Split(path, ".") + obj, ok := node.(map[string]any) + if !ok { + return nil, "", false + } + for _, part := range parts[:len(parts)-1] { + next, exists := obj[part] + if !exists && create { + inner := map[string]any{} + obj[part] = inner + obj = inner + continue + } + if obj, ok = next.(map[string]any); !ok { + return nil, "", false + } + } + return obj, parts[len(parts)-1], true +} + +// decodeNumbers decodes data, keeping each number as it was written. +func decodeNumbers(data []byte) (any, error) { + dec := json.NewDecoder(bytes.NewReader(data)) + dec.UseNumber() + var node any + err := dec.Decode(&node) + return node, err +} + +// compact is node as JSON on one line, with <, > and & as they are, its +// object keys sorted. +func compact(node any) string { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if enc.Encode(node) != nil { + return "" + } + return strings.TrimSpace(buf.String()) +} diff --git a/internal/flagutil/metadata.go b/internal/flagutil/metadata.go index ebd381d7..9f2d0c28 100644 --- a/internal/flagutil/metadata.go +++ b/internal/flagutil/metadata.go @@ -879,7 +879,7 @@ func buildJSONField(cmd *cobra.Command, v reflect.Value, m FlagMeta) error { } field.Set(target.Elem()) } - warnUnknownKeys(cmd, "--"+m.FlagName, []byte(val), field) // unknownkeys.go: say which keys the SDK dropped + warnUnknownFlagKeys(cmd, "--"+m.FlagName, []byte(val), field) // unknownkeys.go, droppedkeys.go: say which keys the SDK dropped, and send no {} for a value they emptied return nil } diff --git a/internal/flagutil/unknownkeys.go b/internal/flagutil/unknownkeys.go index f7159d2e..77c1aaf7 100644 --- a/internal/flagutil/unknownkeys.go +++ b/internal/flagutil/unknownkeys.go @@ -79,6 +79,7 @@ func warnUnknownKeys(cmd *cobra.Command, source string, data []byte, into reflec w.Hints = append(w.Hints, parent+" takes: "+keys) } } + w.Hints = append(w.Hints, afterDropped(cmd, source, data, node, into, found)...) // droppedkeys.go: leave out what they emptied, and say where a key goes w.Hints = append(w.Hints, helpListsFields(cmd)) emitWarning(cmd, w) } diff --git a/internal/output/droppedupdate.go b/internal/output/droppedupdate.go new file mode 100644 index 00000000..c0c80428 --- /dev/null +++ b/internal/output/droppedupdate.go @@ -0,0 +1,77 @@ +// This file is not generated by Speakeasy. It explains an update that sets +// no field because the keys a JSON flag was given were all dropped. +// +// `vf agent update --llm '{"temperature":0.3}'` sent `{"llm": {}}` and +// printed "✓ Agent updated." (fix-verifier:N10): --llm takes temperature +// only under defaults. The empty llm is now left out +// (flagutil/droppedkeys.go), so the update is refused as nothing_to_update +// (emptyupdate.go), whose "No flag set a field" would be wrong: --llm was +// given. This says what was dropped and what the flag takes instead, and, +// when each key dropped is the name of a field further down, gives the line +// that sends it there. + +package output + +import ( + "slices" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// explainDroppedUpdate fills x, nothing_to_update's explanation, when a +// JSON flag's keys were all dropped. It is false when none were, and for +// --body unless its keys go further down: emptyupdate.go says what --body +// sets. +func explainDroppedUpdate(cmd *cobra.Command, x *Explanation) bool { + dropped := slices.DeleteFunc(flagutil.DroppedKeys(cmd), func(d flagutil.Dropped) bool { + return d.Source == "--body" && d.Fixed == "" + }) + if len(dropped) == 0 { + return false + } + path := cmd.CommandPath() + for _, d := range dropped { + x.Why = append(x.Why, d.Source+" set no field: "+path+" doesn't take "+strings.Join(d.Keys, ", ")+".") + if len(d.Moved) == 0 { + for _, takes := range d.Takes { + x.Why = append(x.Why, takes+".") + } + } + for _, from := range d.Keys { + if to, ok := d.Moved[from]; ok { + x.Why = append(x.Why, d.Source+" takes "+to[strings.LastIndex(to, ".")+1:]+" as "+to+".") + } + } + } + x.Why = append(x.Why, "The API refuses an update with no fields, so nothing was sent.") + if d := dropped[0]; len(dropped) == 1 && d.Fixed != "" { + x.Next = append(x.Next, "Send "+pluralWord(len(d.Moved), "it", "them")+" there: "+lineWith(cmd, strings.TrimPrefix(d.Source, "--"), d.Fixed)) // a line with quoted JSON goes without `…`, which would quote it again + } + x.Next = append(x.Next, "`"+path+" --help` shows the JSON its flags take") + return true +} + +// lineWith is cmd as it was given, with the flags it needs and flag set to +// value: `vf agent update --project-id p1 --environment-alias main --llm '…'`. +func lineWith(cmd *cobra.Command, flag, value string) string { + line := cmd.CommandPath() + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + required := f.Annotations["speakeasy:required"] + if f.Changed && f.Name != flag && len(required) > 0 && required[0] == "true" && !slices.Contains(scopeFlags, f.Name) { + line += " --" + f.Name + " " + textArg(f.Value.String()) // strictagain.go + } + }) + return withScope(cmd, line+" --"+flag+" "+textArg(value)) // hintfit.go: with -p and -e as given +} + +// pluralWord is one for n of 1, else many. +func pluralWord(n int, one, many string) string { + if n == 1 { + return one + } + return many +} diff --git a/internal/output/emptyupdate.go b/internal/output/emptyupdate.go index 0e39f285..aba5c6c7 100644 --- a/internal/output/emptyupdate.go +++ b/internal/output/emptyupdate.go @@ -37,6 +37,9 @@ func explainNothingToUpdate(cmd *cobra.Command, err error) (Explanation, bool) { } path := cmd.CommandPath() x := Explanation{Type: "nothing_to_update", Title: action(cmd) + " · nothing to change", Docs: docsFor(cmd)} + if explainDroppedUpdate(cmd, &x) { // droppedupdate.go: a JSON flag whose keys were all dropped + return x, true + } if flagutil.FlagChanged(cmd, "body") { x.Why = append(x.Why, "--body had none of the fields "+path+" sets.") } else { From 361466512c206d87d2ff1518acb65a47931f175a Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:50:40 -0500 Subject: [PATCH 09/25] =?UTF-8?q?fix(output):=20a=20patch=20at=20a=20termi?= =?UTF-8?q?nal=20ends=20with=20a=20=E2=9C=93=20line,=20the=20lines=20it=20?= =?UTF-8?q?changed=20and=20the=20read=20that=20shows=20them?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: human-newcomer:F4 ran `vf agent patch-instructions -p … --old-string "…" --new-string "…"` at a 70-column terminal and got the answer as a record: diff: | @@ -1,1 +1,1 @@ -Greet the customer as Northwind Coffee support and ask how you can ... message: Replaced 1 occurrence at line 1. replacements: 1 totalLines: 1 No ✓ line and no Next. `@@ -1,1 +1,1 @@` and totalLines meant nothing to them, and the message was in the middle. Cause: an update's answer is only a message, which done.go prints as a ✓ line, and updated.go adds Next for "update" and "publish". A patch's answer has a message, a diff and counts, so neither applied, and it went to the generic record printer. `agent patch-prompt`, `playbook patch-instructions` and `function patch-code` answer the same way. Change: - At a terminal with pretty output, those four patches print (patched.go): ✓ Replaced 1 occurrence at line 1 in the agent's instructions. - Greet the customer as Northwind Coffee support and ask how you can help. + Greet the customer as Northwind Coffee support, by name, and ask how you can help. Next: vf agent read-instructions --project-id p1 --environment-alias main see the instructions now The diff loses its hunk headers; several hunks each start "at line N:". Next is the field's read, with -p, -e and --playbook-id as given, or `vf function get --function-id …` for code, which has no read. - JSON, YAML, TOON, --jq, agent mode and a pipe get the API's answer as before. An answer naming a reference or mention that didn't bind prints as before too, as an update's does. Tests: TestAPatchAtATerminalSaysWhatChangedAndHowToReadIt replays F4 and the other three patches, and runs each Next line through cmdcheck; it fails with the hooks reverted. TestAPatchsAnswerIsUnchangedOffATerminalsPrettyOutput covers -o json, -o yaml, --jq, agent mode and an unbound reference. --- internal/output/created.go | 2 +- internal/output/output.go | 3 + internal/output/patched.go | 148 ++++++++++++++++++++++++++++++++ internal/output/patched_test.go | 117 +++++++++++++++++++++++++ 4 files changed, 269 insertions(+), 1 deletion(-) create mode 100644 internal/output/patched.go create mode 100644 internal/output/patched_test.go diff --git a/internal/output/created.go b/internal/output/created.go index 985e0daa..3832aec2 100644 --- a/internal/output/created.go +++ b/internal/output/created.go @@ -53,7 +53,7 @@ func afterResult(cmd *cobra.Command, res interface{}) func() { return afterChange(cmd, res) // updated.go: a ✓ line and Next, as a create has case "create", "clone", "duplicate": default: - return noop + return afterPatch(cmd, res) // patched.go: a patch's Next, or nothing } group := cmd.Parent().Name() obj := createdObject(extractResultContent(res), group) diff --git a/internal/output/output.go b/internal/output/output.go index e3c84e8d..c1265222 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -290,6 +290,9 @@ func Result(cmd *cobra.Command, res interface{}) (err error) { if writeDone(cmd, out, content) { // done.go: an update's or a delete's message, as a ✓ line return nil } + if writePatched(cmd, out, content) { // patched.go: a patch's answer, as a ✓ line and the lines it changed + return nil + } if writeListTable(cmd, out, content) { // listtable.go: document list at a terminal, a line per document return nil } diff --git a/internal/output/patched.go b/internal/output/patched.go new file mode 100644 index 00000000..946c7a77 --- /dev/null +++ b/internal/output/patched.go @@ -0,0 +1,148 @@ +// This file is not generated by Speakeasy. It ends a patch of a prompt, +// instructions or code the way an update ends (updated.go, done.go): a ✓ +// line, the lines it changed, and the read that shows the result. +// +// `vf agent patch-instructions --old-string … --new-string …` at a terminal +// printed the API's answer as a record (human-newcomer:F4, R8 #56): +// +// diff: | +// @@ -1,1 +1,1 @@ +// -Greet the customer as Northwind Coffee support and ask how you can +// ... +// message: Replaced 1 occurrence at line 1. +// replacements: 1 +// totalLines: 1 +// +// `@@ -1,1 +1,1 @@` and totalLines meant nothing to a support lead, the +// message was in the middle, and nothing said how to read the result. Now, +// for a person reading pretty output at a terminal: +// +// ✓ Replaced 1 occurrence at line 1 in the agent's instructions. +// - Greet the customer as Northwind Coffee support and ask how you can help. +// + Greet the customer as Northwind Coffee support, by name, and ask how you can help. +// Next: +// vf agent read-instructions --project-id p1 --environment-alias main see the instructions now +// +// `agent patch-prompt`, `playbook patch-instructions` and `function +// patch-code` answer the same way, and end the same way. JSON, YAML, --jq, +// agent mode and a pipe get the answer as the API sent it. An answer that +// names references or mentions that didn't bind prints as before, as an +// update's does: the warnings and --strict speak to those. + +package output + +import ( + "io" + "os" + "regexp" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/ui" +) + +// patchKeys are the keys of a patch's answer; the last two are left out +// when every reference and mention bound. +var patchKeys = map[string]bool{"message": true, "replacements": true, "diff": true, "totalLines": true, "unresolvedReferences": true, "unresolvedMentions": true} + +// hunkStart is where a diff's hunk starts in the text as it now is: 12 in +// `@@ -12,2 +12,3 @@`. +var hunkStart = regexp.MustCompile(`^@@ -\d+(?:,\d+)? \+(\d+)`) + +// patched is the field cmd, a patch, wrote and its answer's message and +// diff, when content is such an answer. +func patched(cmd *cobra.Command, content interface{}) (field, message, diff string, ok bool) { + field, isPatch := strings.CutPrefix(cmd.Name(), "patch-") + if !isPatch || cmd.Parent() == nil { + return "", "", "", false + } + v, err := jsonValue(content) + m, isObject := v.(map[string]interface{}) + if err != nil || !isObject { + return "", "", "", false + } + for k, val := range m { + if !patchKeys[k] { + return "", "", "", false + } + if list, isList := val.([]interface{}); strings.HasPrefix(k, "unresolved") && val != nil && (!isList || len(list) > 0) { + return "", "", "", false // what didn't bind prints as before + } + } + message, _ = m["message"].(string) + diff, _ = m["diff"].(string) + if strings.TrimSpace(message) == "" { + return "", "", "", false + } + return field, strings.TrimSpace(message), diff, true +} + +// writePatched writes a patch's answer as a ✓ line and the lines it +// changed, when a person is reading pretty output at a terminal. It +// reports whether it did; if not, the answer prints as before. +func writePatched(cmd *cobra.Command, out io.Writer, content interface{}) bool { + u := UI(cmd, cmd.OutOrStdout()) + field, message, diff, ok := patched(cmd, content) + if !u.Decorated() || !ok { + return false + } + line := strings.TrimSuffix(message, ".") + " in the " + nounOf(cmd.Parent().Name()) + "'s " + field + "." // strictagain.go: "API tool" for api-tool + text := u.Status(ui.StatusDone, line) + "\n" + for _, l := range diffLines(u, diff) { + text += l + "\n" + } + io.WriteString(out, text) //nolint:errcheck // a terminal write + return true +} + +// diffLines are diff's changed lines as a person reads them: "- " before a +// line taken out and "+ " before one put in, with no hunk headers. When +// there are several hunks, each starts with the line it is at. +func diffLines(u *ui.UI, diff string) []string { + lines := strings.Split(strings.TrimRight(diff, "\n"), "\n") + hunks := 0 + for _, l := range lines { + if strings.HasPrefix(l, "@@") { + hunks++ + } + } + var out []string + for _, l := range lines { + switch { + case strings.HasPrefix(l, "@@"): + if m := hunkStart.FindStringSubmatch(l); m != nil && hunks > 1 { + out = append(out, " "+u.Muted("at line "+m[1]+":")) + } + case strings.HasPrefix(l, "-"): + out = append(out, " "+u.Error("- "+u.Fit(l[1:], 4))) + case strings.HasPrefix(l, "+"): + out = append(out, " "+u.Success("+ "+u.Fit(l[1:], 4))) + case strings.HasPrefix(l, " "): + out = append(out, " "+u.Muted(" "+u.Fit(l[1:], 4))) + case strings.HasPrefix(l, `\`): // "\ No newline at end of file" + case l != "": + out = append(out, " "+u.Fit(l, 2)) + } + } + return out +} + +// afterPatch returns what prints once a patch's answer has: the read that +// shows what it wrote, or the get when there is no read. +func afterPatch(cmd *cobra.Command, res interface{}) func() { + field, _, _, ok := patched(cmd, extractResultContent(res)) + if !ok || !announces(cmd) { + return func() {} + } + tip := ui.Tip{Does: "see the " + field + " now"} + read := sibling(cmd, "read-"+field) // updated.go + if read == nil { + read, tip.Does = sibling(cmd, "get"), "see it now" + } + if read == nil { + return func() {} + } + tip.Command = withScope(cmd, read.CommandPath()+alsoNeeded(cmd, read, "", nil)) // hintfit.go, nextneeds.go: with -p, -e and the --playbook-id the patch had + return func() { writeNext(UI(cmd, os.Stderr), []ui.Tip{tip}) } +} diff --git a/internal/output/patched_test.go b/internal/output/patched_test.go new file mode 100644 index 00000000..98a35d45 --- /dev/null +++ b/internal/output/patched_test.go @@ -0,0 +1,117 @@ +// This file is not generated by Speakeasy. It covers patched.go: a patch of +// a prompt, instructions or code ends at a terminal with a ✓ line, the lines +// it changed and the read that shows them, and prints as before anywhere +// else. + +package output_test + +import ( + "strings" + "testing" + + "github.com/voiceflow/cli/internal/cmdcheck" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" +) + +// newcomerPatch is the answer human-newcomer:F4 got. +var newcomerPatch = &components.StableInstructionsPatchResponseV2{ + Message: "Replaced 1 occurrence at line 1.", Replacements: 1, TotalLines: 1, + Diff: "@@ -1,1 +1,1 @@\n-Greet the customer as Northwind Coffee support and ask how you can help.\n" + + "+Greet the customer as Northwind Coffee support, by name, and ask how you can help.", +} + +// R8 #56 (human-newcomer:F4): `agent patch-instructions` at a terminal +// printed the answer as a record, `@@ -1,1 +1,1 @@` and totalLines +// included, with no ✓ line and no Next. Each patch of text now ends as an +// update does. +func TestAPatchAtATerminalSaysWhatChangedAndHowToReadIt(t *testing.T) { + root := newRoot(t) + for _, c := range []struct { + line string + res interface{} + done string + next string + }{ + {`vf agent patch-instructions -p 6b0f08fba7f5577610a3449f -e main --old-string "ask how you can help" --new-string "by name, and ask how you can help"`, + &operations.StableAgentControllerPatchInstructionsV2Response{StableInstructionsPatchResponseV2: newcomerPatch}, + "✓ Replaced 1 occurrence at line 1 in the agent's instructions.\n", + "vf agent read-instructions --project-id 6b0f08fba7f5577610a3449f --environment-alias main"}, + {`vf agent patch-prompt -p p1 -e main --old-string "x" --new-string "y"`, + &operations.StableAgentControllerPatchPromptV2Response{StableInstructionsPatchResponseV2: newcomerPatch}, + "✓ Replaced 1 occurrence at line 1 in the agent's prompt.\n", + "vf agent read-prompt --project-id p1 --environment-alias main"}, + {`vf playbook patch-instructions -p p1 -e main --playbook-id pb1 --old-string "x" --new-string "y"`, + &operations.StablePlaybookControllerPatchInstructionsV2Response{StableInstructionsPatchResponseV2: newcomerPatch}, + "✓ Replaced 1 occurrence at line 1 in the playbook's instructions.\n", + "vf playbook read-instructions --playbook-id pb1 --project-id p1 --environment-alias main"}, + {`vf function patch-code -p p1 -e main --function-id f1 --old-string "x" --new-string "y"`, + &operations.StableFunctionControllerPatchCodeResponse{StableFunctionCodePatchResponse: &components.StableFunctionCodePatchResponse{ + Message: "Replaced 1 occurrence at line 1.", Replacements: 1, TotalLines: 1, Diff: newcomerPatch.Diff}}, + "✓ Replaced 1 occurrence at line 1 in the function's code.\n", + "vf function get --function-id f1 --project-id p1 --environment-alias main"}, + } { + stdout, stderr := atATerminal(t, root, c.line, c.res) + if !strings.HasPrefix(stdout, c.done) { + t.Errorf("%s: stdout should start %q:\n%s", c.line, c.done, stdout) + } + for _, want := range []string{ + " - Greet the customer as Northwind Coffee support and ask how you can help.\n", + " + Greet the customer as Northwind Coffee support, by name, and ask how you can help.\n", + } { + if !strings.Contains(stdout, want) { + t.Errorf("%s: stdout lacks %q:\n%s", c.line, want, stdout) + } + } + for _, not := range []string{"@@", "totalLines", "replacements", "message:"} { + if strings.Contains(stdout, not) { + t.Errorf("%s: stdout has %q:\n%s", c.line, not, stdout) + } + } + next := nextLines(stderr) + if len(next) != 1 || next[0] != c.next { + t.Errorf("%s: Next %q, want %q\n%s", c.line, next, c.next, stderr) + continue + } + if problems := cmdcheck.Check(root, next[0], cmdcheck.Options{Complete: true}); len(problems) > 0 { + t.Errorf("%s: %q doesn't run as written: %v", c.line, next[0], problems) + } + root = newRoot(t) // the flags set stay set + } +} + +// JSON, YAML, --jq and an agent get the answer as the API sent it, and an +// answer naming a reference that didn't bind prints as before. +func TestAPatchsAnswerIsUnchangedOffATerminalsPrettyOutput(t *testing.T) { + res := &operations.StableAgentControllerPatchInstructionsV2Response{StableInstructionsPatchResponseV2: newcomerPatch} + base := `vf agent patch-instructions -p p1 -e main --old-string "x" --new-string "y"` + for _, c := range []struct{ flags, want string }{ + {"-o json", `"totalLines":1`}, + {"-o yaml", "totalLines: 1"}, + {"--jq .diff", "@@ -1,1 +1,1 @@"}, + } { + stdout, stderr := atATerminal(t, newRoot(t), base+" "+c.flags, res) + if stderr != "" || strings.Contains(stdout, "✓") || !strings.Contains(stdout, c.want) { + t.Errorf("%s: want the answer alone, got stdout %q, stderr %q", c.flags, stdout, stderr) + } + } + + root := newRoot(t) + t.Setenv("CLAUDECODE", "1") + output.ResetAgentMode() + output.InitAgentMode(root) + t.Cleanup(output.ResetAgentMode) + stdout, stderr := atATerminal(t, root, base, res) + output.ResetAgentMode() + if stderr != "" || strings.Contains(stdout, "✓") || !strings.Contains(stdout, "totalLines") { + t.Errorf("agent mode: want the answer alone, got stdout %q, stderr %q", stdout, stderr) + } + + unbound := *newcomerPatch + unbound.UnresolvedReferences = []components.StableUnresolvedReference{{Path: "instructions", Token: "customer_email", Reason: "unknown"}} + stdout, _ = atATerminal(t, newRoot(t), base, &operations.StableAgentControllerPatchInstructionsV2Response{StableInstructionsPatchResponseV2: &unbound}) + if strings.Contains(stdout, "✓") || !strings.Contains(stdout, "customer_email") { + t.Errorf("unbound: want the record, got %q", stdout) + } +} From 216a4ec924bc3cedda38c558845f5fd57202f410 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:09:35 -0500 Subject: [PATCH 10/25] fix(session): a send at a terminal says how to go on in the session and end it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: fix-verifier N3 (R8 #13), a new user's first send in the home prompt: "Started session s-7gusfw6l (the current one)", the greeting and the reply, then "(no Next:)". "A person who started via send doesn't learn vf session end exists, or that the next send continues the same session." One-shot sends at a terminal printed none either. Cause: only start printed the two Next lines (sessionstart.go, when it doesn't go on to a chat). runSessionSend's person branch printed the turn and returned. Change: after a turn a person sent, Next gives `vf session send … ""` and `vf session end …`, with -s when the session isn't the current one, and `vf session start …` when the turn ended the conversation. The send line is refused as written (placeholder.go), and the end line runs as written; the test runs both. JSON and agent output are unchanged: the answer's session field already says which session it was, and a step on every turn would cost an agent tokens on every turn. --- internal/cli/conversation/sessionsend.go | 31 +++++- internal/cli/session_test.go | 3 +- internal/cli/sessionnext_test.go | 120 +++++++++++++++++++++++ 3 files changed, 152 insertions(+), 2 deletions(-) create mode 100644 internal/cli/sessionnext_test.go diff --git a/internal/cli/conversation/sessionsend.go b/internal/cli/conversation/sessionsend.go index b2f01436..70078e41 100644 --- a/internal/cli/conversation/sessionsend.go +++ b/internal/cli/conversation/sessionsend.go @@ -13,6 +13,7 @@ // (autocompile.go): when it starts a conversation, or vf edited the draft // since its last compile. It prints as `conversation send`'s does; JSON and // TOON add the session's ID, and the launch's turn when send started one. +// At a terminal, Next says how to go on in the session and how to end it. package conversation @@ -30,6 +31,7 @@ import ( "github.com/voiceflow/cli/internal/sdk/models/components" "github.com/voiceflow/cli/internal/sdk/models/operations" "github.com/voiceflow/cli/internal/sessions" + "github.com/voiceflow/cli/internal/ui" "github.com/voiceflow/cli/internal/usage" ) @@ -109,7 +111,11 @@ func runSessionSend(cmd *cobra.Command, args []string) error { } if forAPerson(cmd) { writeTurn(cmd, t) - return compiled() + if err := compiled(); err != nil { + return err + } + sendNext(cmd, scope, rec.ID, readTurn(t.traces, t.stale).ended) + return nil } fields := map[string]any{"session": rec.ID} if launch != nil && launch.answer != nil { @@ -121,6 +127,29 @@ func runSessionSend(cmd *cobra.Command, args []string) error { return compiled() } +// sendNext says, after a turn a person sent, how to go on in session id and +// how to end it, as start's Next does: a one-shot send at a terminal, or in +// the home prompt, was the turn and nothing more, so someone whose send had +// started the session never learnt that the next send goes on in it, or +// that `vf session end` exists. A conversation the turn ended gets a fresh +// start instead. -s is named when id isn't the current session. Scripts and +// agents get none: the answer's session field says which session it was, +// and a step on every turn would cost them tokens on every turn. +func sendNext(cmd *cobra.Command, scope sessionScope, id string, ended bool) { + named := "" + if current, _ := sessions.Current(scope.ProjectID, scope.EnvironmentAlias); current.ID != id { + named = id + } + if ended { + writeNext(cmd, ui.Tip{Command: sessionCommand("start", scope, ""), Does: "Start a fresh one"}) + return + } + writeNext(cmd, + ui.Tip{Command: sessionCommand("send", scope, named) + ` ""`, Does: "Say the next thing"}, + ui.Tip{Command: sessionCommand("end", scope, named), Does: "End it, and find its transcript"}, + ) +} + // talk sends action in session rec, compiling the draft first when rule B // says to, and remembers the buttons the reply offers. compiled compiles // after a turn that missed an edit, and warns. diff --git a/internal/cli/session_test.go b/internal/cli/session_test.go index 0737858c..c008996a 100644 --- a/internal/cli/session_test.go +++ b/internal/cli/session_test.go @@ -508,8 +508,9 @@ func TestEverySessionNextLineRuns(t *testing.T) { _, endErr, _ := api.session(home, false, "end", "-s", "x") _, noneErr, _ := api.session(t.TempDir(), false, "get") _, buttonErr, _ := api.session(home, false, "send", "--button", "Nope") + _, sendErr, _ := api.session(home, false, "send", "hi") checked := 0 - for _, text := range []string{startErr, endErr, noneErr, buttonErr} { + for _, text := range []string{startErr, endErr, noneErr, buttonErr, sendErr} { for _, line := range append(quotedCommands(text), nextLines(text)...) { checked++ for _, problem := range cmdcheck.Check(tree, line, cmdcheck.Options{Keep: []string{"project-id"}, Complete: true}) { diff --git a/internal/cli/sessionnext_test.go b/internal/cli/sessionnext_test.go new file mode 100644 index 00000000..af945045 --- /dev/null +++ b/internal/cli/sessionnext_test.go @@ -0,0 +1,120 @@ +// This file is not generated by Speakeasy. It covers what `vf session send` +// and `vf session end` say to do next (conversation/sessionsend.go, +// sessionend.go), and that each line runs as written. + +package cli + +import ( + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/prompt" +) + +// nextCommands are the commands under a "Next:" line in text, whether what +// each does is beside it or under it. +func nextCommands(text string) []string { + _, block, ok := strings.Cut(text, "Next:\n") + if !ok { + return nil + } + var lines []string + for _, row := range strings.Split(block, "\n") { + if !strings.HasPrefix(row, " ") { + break + } + if row = strings.TrimSpace(row); strings.HasPrefix(row, "vf ") { + command, _, _ := strings.Cut(row, " ") + lines = append(lines, command) + } + } + return lines +} + +// runNext runs a Next line as written, in home. +func runNext(t *testing.T, api *sessionAPI, home, line string) (stdout, stderr string, err error) { + t.Helper() + args, splitErr := prompt.SplitArgs(line) + if splitErr != nil || len(args) < 2 || args[0] != "vf" { + t.Fatalf("not a vf line: %q", line) + } + return runInHome(t, home, api.url, false, args[1:]...) +} + +// fix-verifier:N3 (R8 #13): a new user's first `session send` in the home +// prompt started a session, and printed the greeting and the reply, then +// nothing: no line to go on in the session, or to end it. At a terminal a +// send now ends with the two, as start does, and each runs as written: the +// send's "" is refused as a placeholder, and the end ends it. +func TestASendSaysHowToGoOnAndToEnd(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + + out, errOut, err := api.session(home, false, "send", "Hi!", "How", "long", "do", "refunds", "take?") + if err != nil { + t.Fatalf("%v\n%s%s", err, out, errOut) + } + id := sessionIDRE.FindString(out) + if !strings.Contains(out, "Started session "+id) { + t.Fatalf("the send should have started a session:\n%s", out) + } + next := nextCommands(errOut) + want := []string{`vf session send -p p1 -e main ""`, "vf session end -p p1 -e main"} + if strings.Join(next, "\n") != strings.Join(want, "\n") { + t.Fatalf("after a send, Next is\n%s\nwant\n%s\n(stderr:\n%s)", strings.Join(next, "\n"), strings.Join(want, "\n"), errOut) + } + + // The send line as written is refused, and sends nothing. + api.requests() + _, errOut, err = runNext(t, api, home, next[0]) + if seen, _ := api.requests(); output.ExitCode(err) != output.ExitUsage || len(seen) > 0 || !strings.Contains(errOut, "a placeholder") { + t.Errorf("`%s` as written: exit %d, sent %q\n%s", next[0], output.ExitCode(err), seen, errOut) + } + + // The next send goes on in the session, and says so again. + out, errOut, err = api.session(home, false, "send", "And on Sunday?") + if seen, users := api.requests(); err != nil || strings.Join(seen, ", ") != "text And on Sunday?" || users[0] != id { + t.Errorf("the second send sent %q as %v: %v\n%s", seen, users, err, errOut) + } + if got := nextCommands(errOut); strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("the second send's Next is %q\n%s%s", got, out, errOut) + } + + // A session -s names that isn't the current one is named in each line. + _, errOut, _ = api.session(home, false, "send", "-s", "ci-run-7", "hi") + api.requests() + if got := strings.Join(nextCommands(errOut), "\n"); !strings.Contains(got, `vf session send -s ci-run-7 -p p1 -e main ""`) || !strings.Contains(got, "vf session end -s ci-run-7 -p p1 -e main") { + t.Errorf("another session's Next:\n%s", errOut) + } + + // The end line as written ends the session. + api.searches = []string{searchAnswer(searchRow{"t-1", id, 0})} + out, errOut, err = runNext(t, api, home, next[1]) + if seen, users := api.requests(); err != nil || len(seen) < 1 || seen[0] != "end" || users[0] != id || !strings.Contains(out, "Ended session "+id) { + t.Errorf("`%s` as written: sent %q as %v: %v\n%s%s", next[1], seen, users, err, out, errOut) + } + + // Scripts and agents get the session in the answer, and no steps. + out, errOut, err = api.session(t.TempDir(), true, "send", "hi") + if err != nil || strings.Contains(out+errOut, "Next") || strings.Contains(out+errOut, "") || !strings.Contains(out, "session: s-") { + t.Errorf("agent mode: %v\n%s%s", err, out, errOut) + } +} + +// A turn that ended the conversation offers a fresh start, not a turn in +// it. +func TestASendThatEndsOffersAFreshStart(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + if _, errOut, err := api.session(home, false, "start"); err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + out, errOut, err := api.session(home, false, "send", "--action", `{"type":"end"}`) + if err != nil { + t.Fatalf("%v\n%s%s", err, out, errOut) + } + if got := strings.Join(nextCommands(errOut), "\n"); got != "vf session start -p p1 -e main" { + t.Errorf("after the conversation ended, Next is %q:\n%s%s", got, out, errOut) + } +} From 05866e47b9b866e7c42c138d7f812cbc4070a579 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:16:29 -0500 Subject: [PATCH 11/25] fix(session): end's Next reads the transcript, then scores it with an evaluation that exists MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: human-newcomer F10 and fix-verifier N5 (R8 #51). /end printed "Next: vf evaluation run -e -t 6b0f0a4b… Run an evaluation on it". The newcomer had no evaluation and "didn't know what one is"; reading the transcript, the natural next step, wasn't offered. In a project with one evaluation and in one with none, the line run as written gave exit 4, "No evaluation exists with ID ." Cause: sayEnded (sessionend.go) printed one fixed tip with an placeholder, which 841271c leaves for the API to refuse; vf never looked at which evaluations the project has. Change: Next leads with `vf transcript get -t -p …`. Then, for a person only, vf lists the project's evaluations (one GET) in the background as the end goes out, so the end takes no longer: with one, Next is `vf evaluation run -e -t -p …`, naming it; with several, `vf evaluation list -p …`; with none, `vf evaluation create --help`; if the list fails or takes over 1.5 s, `vf evaluation list -p …`. The same goes for /end in the chat and `run-script --end`. JSON, agent mode and dry runs print no Next and send no list. confirm.go reads its asked flag only for a change, so a read beside another request doesn't race it. --- internal/cli/conversation/sessionchat.go | 3 +- internal/cli/conversation/sessionend.go | 95 ++++++++++++++++++++-- internal/cli/conversation/sessionscript.go | 3 +- internal/cli/session_test.go | 21 ++++- internal/cli/sessionnext_test.go | 85 +++++++++++++++++++ internal/cli/sessionscript_test.go | 2 +- internal/client/confirm.go | 2 +- 7 files changed, 197 insertions(+), 14 deletions(-) diff --git a/internal/cli/conversation/sessionchat.go b/internal/cli/conversation/sessionchat.go index bf697214..4d97532b 100644 --- a/internal/cli/conversation/sessionchat.go +++ b/internal/cli/conversation/sessionchat.go @@ -76,11 +76,12 @@ func chat(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, sco case said == "": continue case said == endCommand: + evals := lookUpEvaluations(cmd, s, opts, scope.ProjectID) // sessionend.go: for the Next line _, transcript, err := endSession(cmd, s, opts, scope, rec, "Ended with /end in vf session", "") if err != nil { return err } - sayEnded(cmd, scope, rec.ID, transcript) + sayEnded(cmd, scope, rec.ID, transcript, evals) return nil case said == newCommand: next, err := startAgain(cmd, s, opts, scope, rec) diff --git a/internal/cli/conversation/sessionend.go b/internal/cli/conversation/sessionend.go index b1f11b6b..e8afc5ff 100644 --- a/internal/cli/conversation/sessionend.go +++ b/internal/cli/conversation/sessionend.go @@ -10,12 +10,22 @@ // The live check found it at once, 0.47 s after the end; vf looks again for // up to 5 s before saying it isn't there yet, and still exits 0, since the // session did end. +// +// At a terminal, Next led with `vf evaluation run -e -t …`, +// which run as written fails "No evaluation exists with ID +// ", and a newcomer with no evaluation didn't know what one +// was (round 8: human-newcomer F10, fix-verifier N5). Next now leads with +// reading the transcript. Then, as the end goes out, vf lists the project's +// evaluations beside it (one GET, at a terminal only, so the end takes no +// longer): with one, Next runs it on the transcript by its ID; with more, +// it lists them; with none, it says how to make one. package conversation import ( "context" "fmt" + "sync" "time" "github.com/spf13/cobra" @@ -70,6 +80,7 @@ func runSessionEnd(cmd *cobra.Command, args []string) error { if err != nil { return err } + evals := lookUpEvaluations(cmd, s, opts, scope.ProjectID) res, transcript, err := endSession(cmd, s, opts, scope, rec, "Ended with vf session end", "") if err != nil { return err @@ -82,7 +93,7 @@ func runSessionEnd(cmd *cobra.Command, args []string) error { ended(result, transcript) return output.Result(cmd, result) } - sayEnded(cmd, scope, rec.ID, transcript) + sayEnded(cmd, scope, rec.ID, transcript, evals) return nil } @@ -125,9 +136,9 @@ func ended(result map[string]any, transcript string) { } } -// sayEnded tells a person session id ended, and gives its transcript with -// the evaluation to run on it. -func sayEnded(cmd *cobra.Command, scope sessionScope, id, transcript string) { +// sayEnded tells a person session id ended, and gives its transcript: how +// to read it, and how to score it with the evaluations evals finds. +func sayEnded(cmd *cobra.Command, scope sessionScope, id, transcript string, evals evaluations) { out := cmd.OutOrStdout() u := output.UI(cmd, out) if transcript == "" { @@ -136,10 +147,78 @@ func sayEnded(cmd *cobra.Command, scope sessionScope, id, transcript string) { return } fmt.Fprintln(out, u.Status(ui.StatusDone, "Ended session "+id+" "+u.Glyph(ui.Separator)+" transcript "+transcript)) - writeNext(cmd, ui.Tip{ - Command: "vf evaluation run -e -t " + transcript + session.Scope(scope.ProjectID, ""), - Does: "Run an evaluation on it", - }) + project := session.Scope(scope.ProjectID, "") + writeNext(cmd, + ui.Tip{Command: "vf transcript get -t " + transcript + project, Does: "Read the conversation"}, + scoreTip(transcript, project, evals), + ) +} + +// scoreTip is the step that scores transcript with an evaluation: the +// project's one, by its ID; or, with more or with none, the command that +// lists them or makes one. +func scoreTip(transcript, project string, evals evaluations) ui.Tip { + list, ok := evals() + switch { + case ok && len(list) == 1: + return ui.Tip{ + Command: "vf evaluation run -e " + shellWord(list[0].ID) + " -t " + transcript + project, + Does: "Score it with your evaluation " + quoted(list[0].Name), + } + case ok && len(list) == 0: + return ui.Tip{Command: "vf evaluation create --help", Does: "Make an evaluation, to score conversations like this one"} + case ok: + return ui.Tip{Command: "vf evaluation list" + project, Does: fmt.Sprintf("Pick one of your %d evaluations to score it with", len(list))} + } + return ui.Tip{Command: "vf evaluation list" + project, Does: "The evaluations you can score it with"} +} + +// evaluations waits for the project's evaluations, as lookUpEvaluations +// finds them; ok is false when it couldn't. +type evaluations func() (list []components.StableEvaluationSummary, ok bool) + +// evaluationsWait is the longest vf waits for the project's evaluations +// after a session ends. The list usually comes back before the end and the +// transcript search do. +var evaluationsWait = 1500 * time.Millisecond + +// lookUpEvaluations starts to list the project's evaluations, for the Next +// a person reads once the session ended, and returns what waits for them. +// It goes out beside the end, so it adds no wait of its own; scripts, +// agents and dry runs print no Next, and send nothing for it. +func lookUpEvaluations(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, projectID string) evaluations { + if client.IsDryRun(cmd) || !output.ForAPerson(cmd) { + return func() ([]components.StableEvaluationSummary, bool) { return nil, false } + } + type found struct { + list []components.StableEvaluationSummary + ok bool + } + done := make(chan found, 1) + go func() { + ctx, cancel := context.WithTimeout(client.WithoutSpinner(cmd.Context()), evaluationsWait) + defer cancel() + res, err := s.Evaluation.List(ctx, operations.StableEvaluationControllerListV2Request{ProjectID: projectID}, opts...) + if err != nil || res == nil { + done <- found{} + return + } + answer := res.StableEvaluationListResponseV2 + if answer == nil { + answer = &components.StableEvaluationListResponseV2{} + if !output.PeekJSON(res.HTTPMeta.Response, answer) { + done <- found{} + return + } + } + done <- found{answer.Evaluations, true} + }() + var once sync.Once + var result found + return func() ([]components.StableEvaluationSummary, bool) { + once.Do(func() { result = <-done }) + return result.list, result.ok + } } // notFoundYet says the transcript wasn't there when vf looked. diff --git a/internal/cli/conversation/sessionscript.go b/internal/cli/conversation/sessionscript.go index b4c8f756..f5524254 100644 --- a/internal/cli/conversation/sessionscript.go +++ b/internal/cli/conversation/sessionscript.go @@ -95,6 +95,7 @@ func scriptDone(cmd *cobra.Command, s *sdk.VoiceflowSDK, wait *turnWait, req *op return err } known, _ := answer["transcriptID"].(string) + evals := lookUpEvaluations(cmd, s, opts, scope.ProjectID) // sessionend.go: for the Next line _, transcript, err := endSession(cmd, s, opts, scope, rec, "Ended with vf session run-script --end", known) if err != nil { return err @@ -110,7 +111,7 @@ func scriptDone(cmd *cobra.Command, s *sdk.VoiceflowSDK, wait *turnWait, req *op if err := output.Result(cmd, res); err != nil { return err } - sayEnded(cmd, scope, id, transcript) + sayEnded(cmd, scope, id, transcript, evals) return nil } diff --git a/internal/cli/session_test.go b/internal/cli/session_test.go index c008996a..5fd6d94f 100644 --- a/internal/cli/session_test.go +++ b/internal/cli/session_test.go @@ -43,11 +43,17 @@ type sessionAPI struct { openRuns bool // version is the version the last turn asked for. version string + // evaluations answers an evaluation list, which a person's end sends + // beside the end action: it isn't in seen, whose order it would make + // random. evalLists counts them, and evalStatus fails them. + evaluations string + evalLists int + evalStatus int } func newSessionAPI(t *testing.T) *sessionAPI { t.Helper() - api := &sessionAPI{t: t, state: noneState, searches: []string{`{"transcripts":[],"returned":0,"hasMore":false}`}} + api := &sessionAPI{t: t, state: noneState, searches: []string{`{"transcripts":[],"returned":0,"hasMore":false}`}, evaluations: `{"evaluations":[]}`} srv := httptest.NewServer(http.HandlerFunc(api.serve)) t.Cleanup(srv.Close) api.url = srv.URL @@ -155,6 +161,17 @@ func (api *sessionAPI) serve(w http.ResponseWriter, r *http.Request) { } w.WriteHeader(http.StatusCreated) io.WriteString(w, `{"result":{"cost":0.001,"value":true,"reason":"Polite.","transcriptID":"`+req.TranscriptID+`"}}`) + case r.URL.Path == "/v2/stable/evaluation" && r.Method == http.MethodGet: + api.mu.Lock() + api.evalLists++ + answer, status := api.evaluations, api.evalStatus + api.mu.Unlock() + if status != 0 { + w.WriteHeader(status) + io.WriteString(w, `{"message":"Something went wrong"}`) + return + } + io.WriteString(w, answer) case strings.HasPrefix(r.URL.Path, "/v2/stable/transcript/") && r.Method == http.MethodGet: say("transcript get") io.WriteString(w, api.transcript) @@ -227,7 +244,7 @@ func TestASessionStartsTalksAndEnds(t *testing.T) { if seen, _ := api.requests(); strings.Join(seen, ", ") != "end, search" { t.Errorf("end sent %q", seen) } - if !strings.Contains(out, "Ended session "+id+" | transcript t-1") || !strings.Contains(errOut, "vf evaluation run -e -t t-1 -p p1") { + if !strings.Contains(out, "Ended session "+id+" | transcript t-1") || !strings.Contains(errOut, "vf transcript get -t t-1 -p p1") { t.Errorf("end printed:\n%s%s", out, errOut) } diff --git a/internal/cli/sessionnext_test.go b/internal/cli/sessionnext_test.go index af945045..6449fd7e 100644 --- a/internal/cli/sessionnext_test.go +++ b/internal/cli/sessionnext_test.go @@ -10,6 +10,7 @@ import ( "github.com/voiceflow/cli/internal/output" "github.com/voiceflow/cli/internal/prompt" + "github.com/voiceflow/cli/internal/sessions" ) // nextCommands are the commands under a "Next:" line in text, whether what @@ -118,3 +119,87 @@ func TestASendThatEndsOffersAFreshStart(t *testing.T) { t.Errorf("after the conversation ended, Next is %q:\n%s%s", got, out, errOut) } } + +// fix-verifier:N5 and human-newcomer:F10 (R8 #51): /end's Next was +// `vf evaluation run -e -t …`, in a project with one +// evaluation and in one with none, and run as written it failed: exit 4, +// "No evaluation exists with ID ." The newcomer had no +// evaluation, and wanted to read the conversation. Next now leads with the +// transcript; then the one evaluation by its ID, or the list, or how to make +// one. Each runs as written. +func TestEndSaysHowToReadAndScoreTheTranscript(t *testing.T) { + for _, c := range []struct { + name, evaluations string + status int + score string + }{ + {"one evaluation", `{"evaluations":[{"id":"ev-polite","name":"Polite","type":"boolean","enabled":true,"default":false,"description":null}]}`, 0, "vf evaluation run -e ev-polite -t t-1 -p p1"}, + {"none", `{"evaluations":[]}`, 0, "vf evaluation create --help"}, + {"three", `{"evaluations":[{"id":"a","name":"A","type":"boolean","enabled":true,"default":false,"description":null},{"id":"b","name":"B","type":"boolean","enabled":true,"default":false,"description":null},{"id":"c","name":"C","type":"boolean","enabled":true,"default":false,"description":null}]}`, 0, "vf evaluation list -p p1"}, + {"a list that failed", "", 500, "vf evaluation list -p p1"}, + } { + t.Run(c.name, func(t *testing.T) { + api := newSessionAPI(t) + api.evaluations, api.evalStatus = c.evaluations, c.status + home := t.TempDir() + if _, errOut, err := api.session(home, false, "start"); err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + id, _ := currentID() + api.requests() + api.searches = []string{searchAnswer(searchRow{"t-1", id, 0})} + out, errOut, err := api.session(home, false, "end") + if err != nil { + t.Fatalf("%v\n%s%s", err, out, errOut) + } + if seen, _ := api.requests(); strings.Join(seen, ", ") != "end, search" { + t.Errorf("end sent %q, and the evaluation list beside them", seen) + } + want := []string{"vf transcript get -t t-1 -p p1", c.score} + got := nextCommands(errOut) + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Fatalf("end's Next is\n%s\nwant\n%s\n(stderr:\n%s)", strings.Join(got, "\n"), strings.Join(want, "\n"), errOut) + } + if c.name == "one evaluation" && !strings.Contains(errOut, `"Polite"`) { + t.Errorf("the step should name the evaluation:\n%s", errOut) + } + api.transcript = `{"transcript":{"id":"t-1","sessionID":"` + id + `","turns":[]}}` + api.evaluations, api.evalStatus = `{"evaluations":[]}`, 0 // the API is back + for _, line := range want { + _, errOut, err := runNext(t, api, home, line) + if err != nil { + t.Errorf("`%s` as written: %v\n%s", line, err, errOut) + } + } + seen, _ := api.requests() + if !strings.Contains(strings.Join(seen, ", "), "transcript get") { + t.Errorf("the transcript line sent %q", seen) + } + if c.name == "one evaluation" && !strings.Contains(strings.Join(seen, ", "), "evaluate t-1") { + t.Errorf("the evaluation line sent %q", seen) + } + }) + } +} + +// Scripts and agents get no Next, so end sends nothing to look evaluations +// up; nor does a dry run. +func TestEndLooksUpEvaluationsOnlyForAPerson(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + api.searches = []string{searchAnswer(searchRow{"t-1", "ci-1", 0})} + for _, args := range [][]string{{"end", "-s", "ci-1", "-o", "json"}, {"end", "-s", "ci-1", "--dry-run"}} { + if _, errOut, err := api.session(home, true, args...); err != nil { + t.Fatalf("%v: %v\n%s", args, err, errOut) + } + } + if api.evalLists != 0 { + t.Errorf("end listed evaluations %d times for an agent", api.evalLists) + } +} + +// currentID is the current session of p1/main. +func currentID() (string, bool) { + s, ok := sessions.Current("p1", "main") + return s.ID, ok +} diff --git a/internal/cli/sessionscript_test.go b/internal/cli/sessionscript_test.go index 215c67bf..f884129c 100644 --- a/internal/cli/sessionscript_test.go +++ b/internal/cli/sessionscript_test.go @@ -66,7 +66,7 @@ func TestAScriptWithEndGivesItsTranscript(t *testing.T) { if seen, _ := api.requests(); strings.Join(seen, ", ") != "compile, script, end, search" { t.Errorf("sent %q", seen) } - if !strings.Contains(out, "Ended session u-api | transcript t-found") || !strings.Contains(errOut, "vf evaluation run -e -t t-found -p p1") { + if !strings.Contains(out, "Ended session u-api | transcript t-found") || !strings.Contains(errOut, "vf transcript get -t t-found -p p1") { t.Errorf("printed:\n%s%s", out, errOut) } if _, ok := sessions.Current("p1", "main"); ok { diff --git a/internal/client/confirm.go b/internal/client/confirm.go index 50c6b787..b90749d4 100644 --- a/internal/client/confirm.go +++ b/internal/client/confirm.go @@ -40,7 +40,7 @@ type confirmClient struct { } func (c *confirmClient) Do(req *http.Request) (*http.Response, error) { - if !c.asked && changes(req.Method) { + if changes(req.Method) && !c.asked { // a read, which may go beside another request, never touches asked c.asked = true if err := BeforeChange(c.cmd, req, c.inner); err != nil { return nil, err From aeec35199eb6f6dc5bca3a23ee04b9ce763409fa Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:21:46 -0500 Subject: [PATCH 12/25] fix(session): a turn that runs an edit says so, and that earlier replies can still steer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: human-newcomer F3 (R8 #12, dead end in task 5). After `agent patch-instructions` in a second window, the open chat's next reply still ended "Anything else I can help with?", and "nothing on screen told me". "I can't tell whether the old turns in the conversation steered the model or the old configuration was used." /new picked up the edit. Cause: the configuration wasn't old. Rule B reads the edit mark at every turn (compilesFirst → sessions.Edited reads sessions.json), so the next chat turn compiled first; the new test makes the edit from another process, through the API, and sees `compile` before that turn. What steered the reply was the conversation's own earlier replies, and the chat said nothing about either. Change: a turn that compiles an edit first, in a session already going, prints one muted line before its reply: "This turn runs your edit. Earlier replies in this session can still steer the agent: /new starts fresh." (a one-shot send names 'vf session start …' instead). Rule B compiles once per edit, so the line comes once. A turn that answers needsRecompile (an edit vf didn't make) ran the old build, so its existing warning after the reply says the same about earlier replies. Agent and JSON output are unchanged. --- internal/cli/conversation/autocompile.go | 20 +++- internal/cli/conversation/session.go | 3 + internal/cli/conversation/sessionchat.go | 8 +- internal/cli/conversation/sessionsend.go | 25 ++++- internal/cli/session_test.go | 8 +- internal/cli/sessionchat_test.go | 112 +++++++++++++++++++++++ 6 files changed, 167 insertions(+), 9 deletions(-) diff --git a/internal/cli/conversation/autocompile.go b/internal/cli/conversation/autocompile.go index 357b97cd..936a048a 100644 --- a/internal/cli/conversation/autocompile.go +++ b/internal/cli/conversation/autocompile.go @@ -199,9 +199,19 @@ const staleTurn = "This turn ran the build from before an edit made elsewhere or // compileAfterStaleTurn is compileAfterStaleSend for an answer already // read, whose needsRecompile is stale. func compileAfterStaleTurn(cmd *cobra.Command, s *sdk.VoiceflowSDK, version string, stale bool, projectID, alias string) func() error { + return compileAfterStaleSessionTurn(cmd, s, version, stale, projectID, alias, "") +} + +// compileAfterStaleSessionTurn is compileAfterStaleTurn for a turn in a +// session going, whose warning ends with steer: what its earlier replies +// can still do, and how to start fresh (steerNote). +func compileAfterStaleSessionTurn(cmd *cobra.Command, s *sdk.VoiceflowSDK, version string, stale bool, projectID, alias, steer string) func() error { if !stale || client.IsDryRun(cmd) || version != "draft" || skipCompile(cmd) { return func() error { return nil } } + if steer != "" { + steer = " " + steer + } return func() error { ctx := client.WithSpinnerMessage(cmd.Context(), compilingMessage) if err := compile(ctx, s, projectID, alias); err != nil { @@ -212,11 +222,19 @@ func compileAfterStaleTurn(cmd *cobra.Command, s *sdk.VoiceflowSDK, version stri warn(cmd, staleTurn+" vf couldn't compile the draft after it ("+compileError(cmd, err)+"), so your next turn compiles it first.") return nil } - warn(cmd, staleTurn+" vf compiled it, so your next turn runs it.") + warn(cmd, staleTurn+" vf compiled it, so your next turn runs it."+steer) return nil } } +// steerNote says that a session's earlier replies can still steer the +// agent after an edit, and that fresh starts a session without them: "/new" +// in the chat, a start command elsewhere. A turn that runs an edit prints it +// once, and so does the warning after a turn that missed one. +func steerNote(fresh string) string { + return "Earlier replies in this session can still steer the agent: " + fresh + " starts fresh." +} + func compile(ctx context.Context, s *sdk.VoiceflowSDK, projectID, alias string) error { _, err := s.Environment.Compile(ctx, operations.StableEnvironmentControllerCompileRequest{ProjectID: projectID, EnvironmentAlias: alias}, operations.WithSkipDeserialization()) return err diff --git a/internal/cli/conversation/session.go b/internal/cli/conversation/session.go index fef3971c..5cd93d6c 100644 --- a/internal/cli/conversation/session.go +++ b/internal/cli/conversation/session.go @@ -225,6 +225,9 @@ type sessionTurn struct { answer map[string]any // nil in a dry run traces []map[string]any stale bool + // ranEdit: the turn compiled the draft first, after an edit, and was no + // launch: it runs the edit in a conversation already going. + ranEdit bool } // takeTurn sends req with wait's context, ends the wait, and reads the diff --git a/internal/cli/conversation/sessionchat.go b/internal/cli/conversation/sessionchat.go index 4d97532b..8066c249 100644 --- a/internal/cli/conversation/sessionchat.go +++ b/internal/cli/conversation/sessionchat.go @@ -12,7 +12,10 @@ // agents aren't at a terminal, and get the commands' usual output. // // The line is the home prompt's (internal/prompt), with / and ? typed as -// text. Each turn compiles as send's does (autocompile.go: rule B). +// text. Each turn compiles as send's does (autocompile.go: rule B), and one +// that compiles an edit made since, from this window or another, says so +// before its reply: the earlier replies can still steer the agent, and /new +// starts fresh. // internal/cli/sessionchat_test.go covers it. package conversation @@ -98,8 +101,9 @@ func chat(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, sco } else if pressed != said { note(cmd, "Pressed "+quoted(pressed)) } - t, compiled, err := talk(cmd, s, opts, scope, rec, action) + t, compiled, err := talk(cmd, s, opts, scope, rec, action, newCommand) if err == nil { + sayRanEdit(cmd, t, newCommand) writeTurn(cmd, t) rec.Buttons = t.buttons() err = compiled() diff --git a/internal/cli/conversation/sessionsend.go b/internal/cli/conversation/sessionsend.go index 70078e41..6726605e 100644 --- a/internal/cli/conversation/sessionsend.go +++ b/internal/cli/conversation/sessionsend.go @@ -105,11 +105,12 @@ func runSessionSend(cmd *cobra.Command, args []string) error { out := cmd.OutOrStdout() fmt.Fprintln(out, output.UI(cmd, out).Bold("You ")+said) } - t, compiled, err := talk(cmd, s, opts, scope, rec, action) + t, compiled, err := talk(cmd, s, opts, scope, rec, action, "'"+sessionCommand("start", scope, "")+"'") if err != nil { return err } if forAPerson(cmd) { + sayRanEdit(cmd, t, "'"+sessionCommand("start", scope, "")+"'") writeTurn(cmd, t) if err := compiled(); err != nil { return err @@ -152,20 +153,34 @@ func sendNext(cmd *cobra.Command, scope sessionScope, id string, ended bool) { // talk sends action in session rec, compiling the draft first when rule B // says to, and remembers the buttons the reply offers. compiled compiles -// after a turn that missed an edit, and warns. -func talk(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, scope sessionScope, rec sessions.Session, action components.AnyRequest) (t *sessionTurn, compiled func() error, err error) { +// after a turn that missed an edit, and warns. fresh is how to start a +// session afresh, for what talk says after an edit (steerNote). +func talk(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, scope sessionScope, rec sessions.Session, action components.AnyRequest, fresh string) (t *sessionTurn, compiled func() error, err error) { req := sendRequest(scope, rec.ID, rec.Version, action) giveEndReason(req, "Ended with vf session send") // endaction.go starts := actionType(req.Body.Action) == string(components.LaunchRequestTypeLaunch) - wait, err := startTurn(cmd, s, compilesFirst(cmd, rec.Version, starts, scope.ProjectID, scope.EnvironmentAlias), scope.ProjectID, scope.EnvironmentAlias) // autocompile.go: rule B + compiles := compilesFirst(cmd, rec.Version, starts, scope.ProjectID, scope.EnvironmentAlias) // autocompile.go: rule B + wait, err := startTurn(cmd, s, compiles, scope.ProjectID, scope.EnvironmentAlias) if err != nil { return nil, nil, err } if t, err = takeTurn(cmd, s, opts, wait, req); err != nil { return nil, nil, err } + t.ranEdit = compiles && !starts rememberButtons(cmd, scope, rec.ID, t) - return t, compileAfterStaleTurn(cmd, s, rec.Version, t.stale, scope.ProjectID, scope.EnvironmentAlias), nil // autocompile.go: an edit the turn missed + return t, compileAfterStaleSessionTurn(cmd, s, rec.Version, t.stale, scope.ProjectID, scope.EnvironmentAlias, steerNote(fresh)), nil // autocompile.go: an edit the turn missed +} + +// sayRanEdit says, for a person and before the reply, that turn t compiled +// an edit first and runs it, and what the session's earlier replies can +// still do: an edit made from another window reached the chat's next turn, +// but the reply kept the old ending, and nothing said why (round 8: +// human-newcomer F3). Rule B compiles once per edit, so it says this once. +func sayRanEdit(cmd *cobra.Command, t *sessionTurn, fresh string) { + if t.ranEdit { + note(cmd, "This turn runs your edit. "+steerNote(fresh)) + } } // oneThingToSay checks that send was given one thing to say: a message, diff --git a/internal/cli/session_test.go b/internal/cli/session_test.go index 5fd6d94f..4e58edec 100644 --- a/internal/cli/session_test.go +++ b/internal/cli/session_test.go @@ -6,6 +6,7 @@ package cli import ( "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" @@ -49,6 +50,8 @@ type sessionAPI struct { evaluations string evalLists int evalStatus int + // stale has a text turn answer needsRecompile: an edit vf didn't make. + stale bool } func newSessionAPI(t *testing.T) *sessionAPI { @@ -131,7 +134,10 @@ func (api *sessionAPI) serve(w http.ResponseWriter, r *http.Request) { var text string _ = json.Unmarshal(req.Action.Payload, &text) say("text " + text) - io.WriteString(w, `{"needsRecompile":false,"traces":[{"type":"text","payload":{"message":"We're open 9 to 5."}}]}`) + api.mu.Lock() + stale := api.stale + api.mu.Unlock() + fmt.Fprintf(w, `{"needsRecompile":%v,"traces":[{"type":"text","payload":{"message":"We're open 9 to 5."}}]}`, stale) case typ == "end": say("end") io.WriteString(w, `{"needsRecompile":false,"traces":[{"type":"end"}]}`) diff --git a/internal/cli/sessionchat_test.go b/internal/cli/sessionchat_test.go index 51bfbd6b..583cfd0c 100644 --- a/internal/cli/sessionchat_test.go +++ b/internal/cli/sessionchat_test.go @@ -6,6 +6,8 @@ package cli import ( + "os" + "os/exec" "strings" "testing" @@ -105,3 +107,113 @@ func TestCtrlDLeavesTheSessionGoing(t *testing.T) { t.Errorf("the current session is %q, want the fresh one, %s", current.ID, fresh) } } + +// secondWindow is set in the child process that makes the edit, as a second +// vf window would. +const secondWindow = "VF_TEST_SECOND_WINDOW" + +// human-newcomer:F3 (R8 #12): an edit made from a second vf window, while +// the chat was open in the first; the chat's next reply kept the old ending, +// and nothing on screen said what had run. Rule B reads the edit mark at +// each turn, so the next turn compiles first: this checks it, with the edit +// made by another process, through the API. That turn now says, once and +// before its reply, that it runs the edit and that the earlier replies can +// still steer the agent, with /new to start fresh. +func TestAnEditFromAnotherWindowReachesTheChatsNextTurn(t *testing.T) { + if os.Getenv(secondWindow) != "" { + // The second window: `vf agent patch-instructions …`, as the + // newcomer typed it. + _, errOut, err := runInHome(t, os.Getenv("HOME"), os.Getenv("VF_SERVER_URL"), false, + "agent", "patch-instructions", "-p", "p1", "-e", "main", + "--old-string", "Anything else I can help with?", "--new-string", "Have a great coffee day!") + if err != nil { + t.Fatalf("the edit: %v\n%s", err, errOut) + } + return + } + api := newSessionAPI(t) + home := t.TempDir() + savedChats, savedRead := conversation.Chats, conversation.ReadLine + t.Cleanup(func() { conversation.Chats, conversation.ReadLine = savedChats, savedRead }) + conversation.Chats = func(*cobra.Command) bool { return true } + lines := []string{"How much is a latte?", "How much is a flat white?", "And a mocha?"} + conversation.ReadLine = func(o prompt.Options) (string, bool, error) { + if len(lines) == 0 { + return "", false, nil + } + if len(lines) == 2 { + edit := exec.Command(os.Args[0], "-test.run=^TestAnEditFromAnotherWindowReachesTheChatsNextTurn$", "-test.count=1") + edit.Env = append(os.Environ(), secondWindow+"=1", "HOME="+home, "VF_SERVER_URL="+api.url, "VF_TOKEN=vfp_fake") + if out, err := edit.CombinedOutput(); err != nil { + t.Fatalf("the second window's edit: %v\n%s", err, out) + } + } + line := lines[0] + lines = lines[1:] + return line, true, nil + } + + out, errOut, err := api.session(home, false, "start") + if err != nil { + t.Fatalf("%v\n%s%s", err, out, errOut) + } + seen, _ := api.requests() + var turns []string + for _, s := range seen { + if s == "compile" || s == "launch" || strings.HasPrefix(s, "text ") || strings.Contains(s, "instructions") { + turns = append(turns, s) + } + } + want := "compile, launch, text How much is a latte?, PATCH /v2/stable/agent/instructions, compile, text How much is a flat white?, text And a mocha?" + if got := strings.Join(turns, ", "); got != want { + t.Fatalf("the chat sent\n %s\nwant the turn after the other window's edit to compile first:\n %s", got, want) + } + note := "This turn runs your edit. Earlier replies in this session can still steer the agent: /new starts fresh." + if strings.Count(out, note) != 1 { + t.Fatalf("the turn after the edit should say once that it runs it:\n%s", out) + } + before, after, _ := strings.Cut(out, note) + if strings.Count(before, "We're open 9 to 5.") != 1 || strings.Count(after, "We're open 9 to 5.") != 2 { + t.Errorf("the note should come before the second reply, and only there:\n%s", out) + } +} + +// A one-shot send that compiles an edit first says the same, with the +// command that starts fresh; one that doesn't compile says nothing of it. +func TestASendAfterAnEditSaysItRunsIt(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + if _, errOut, err := api.session(home, false, "start"); err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + if _, errOut, err := api.session(home, false, "send", "hi"); err != nil || strings.Contains(errOut, "runs your edit") { + t.Fatalf("a plain turn: %v\n%s", err, errOut) + } + if _, errOut, err := runInHome(t, home, api.url, false, "agent", "update", "--instructions", "Be brief.", "-p", "p1", "-e", "main"); err != nil { + t.Fatalf("the edit: %v\n%s", err, errOut) + } + api.requests() + out, errOut, err := api.session(home, false, "send", "hi") + if seen, _ := api.requests(); err != nil || strings.Join(seen, ", ") != "compile, text hi" { + t.Fatalf("sent %q: %v\n%s", seen, err, errOut) + } + want := "This turn runs your edit. Earlier replies in this session can still steer the agent: 'vf session start -p p1 -e main' starts fresh.\nAgent We're open 9 to 5." + if !strings.Contains(out, want) { + t.Errorf("printed:\n%s", out) + } + if out, _, _ := api.session(home, true, "send", "hi"); strings.Contains(out, "runs your edit") { + t.Errorf("agent mode:\n%s", out) + } + + // An edit vf didn't make: the turn ran the old build, so vf compiles + // after it, and its warning says the same about the earlier replies. + api.stale = true + api.requests() + _, errOut, err = api.session(home, false, "send", "hi") + if seen, _ := api.requests(); err != nil || strings.Join(seen, ", ") != "text hi, compile" { + t.Fatalf("sent %q: %v\n%s", seen, err, errOut) + } + if !strings.Contains(errOut, "vf compiled it, so your next turn runs it. Earlier replies in this session can still steer the agent: 'vf session start -p p1 -e main' starts fresh.") { + t.Errorf("the stale turn's warning:\n%s", errOut) + } +} From 95289ce9932c7def663f9b32ef49035f593db472 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:26:46 -0500 Subject: [PATCH 13/25] fix(session): Ctrl-C during a chat turn in a shell stops the turn, not vf MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: fix-verifier N2 (R8 #50). In `vf session send`'s chat at a terminal, Ctrl-C about 0.7 s into "What is your return window?": "✻ Waiting for the agent… 0s · ctrl-c stops waiting, not the turn^C" and "[vf exited with code -2] (killed by SIGINT; nothing more printed)", though `session get` showed the message and the agent's reply. The person left without knowing the session was still open, or how to return. Cause: while a turn is out the terminal is the shell's again, so Ctrl-C is a SIGINT, and nothing in a shell catches it: Go's default ends the process. sessionchat.go only handled a canceled cmd.Context(), which the home prompt's own catch (home.go) provides and a shell doesn't. Change: the chat catches SIGINT while a line runs (signal.NotifyContext around the turn, /end and /new), so a Ctrl-C cancels the turn's request: canceled.go then says "Canceled. Nothing was sent." (during the compile) or "Stopped waiting for the agent, but the message may have reached it" with the `vf session get …` that shows it, and the You line comes back armed (prompt.Options.Armed), so one more Ctrl-C, or Ctrl-D, leaves with the "is still going" line. In the home prompt the line ends as before. The test runs the chat in a child process that gets a real SIGINT during a compile and during a turn; without the change the child dies of it. --- internal/cli/conversation/canceled.go | 3 +- internal/cli/conversation/sessionchat.go | 42 +++++++++++- internal/cli/session_test.go | 30 +++++++++ internal/cli/sessionchat_test.go | 86 ++++++++++++++++++++++++ internal/prompt/prompt.go | 5 +- internal/prompt/prompt_test.go | 23 +++++++ 6 files changed, 186 insertions(+), 3 deletions(-) diff --git a/internal/cli/conversation/canceled.go b/internal/cli/conversation/canceled.go index 89da9770..54186f86 100644 --- a/internal/cli/conversation/canceled.go +++ b/internal/cli/conversation/canceled.go @@ -23,7 +23,8 @@ // exit 1, as any other cancel. // // In a shell, Ctrl-C ends vf itself (exit 130, nothing printed), so there -// is no claim to correct there. +// is no claim to correct there, except in the chat at a terminal, which +// catches it while a turn runs (sessionchat.go) and says the same. package conversation diff --git a/internal/cli/conversation/sessionchat.go b/internal/cli/conversation/sessionchat.go index 8066c249..b3961c83 100644 --- a/internal/cli/conversation/sessionchat.go +++ b/internal/cli/conversation/sessionchat.go @@ -11,6 +11,13 @@ // still going, and one line says how to come back to it. Scripts and // agents aren't at a terminal, and get the commands' usual output. // +// While a turn is out, the terminal is the shell's again, so Ctrl-C is a +// signal, and in a shell it ended vf on the spot: no word that the message +// had reached the agent, or that the session was still going (round 8: +// fix-verifier N2). The chat catches it while a line runs: the turn stops, +// canceled.go says whether the message went out, and the You line comes +// back, armed, so one more Ctrl-C (or Ctrl-D) leaves with the session going. +// // The line is the home prompt's (internal/prompt), with / and ? typed as // text. Each turn compiles as send's does (autocompile.go: rule B), and one // that compiles an edit made since, from this window or another, says so @@ -21,8 +28,11 @@ package conversation import ( + "context" "errors" "fmt" + "os" + "os/signal" "strings" "github.com/spf13/cobra" @@ -58,13 +68,15 @@ func chat(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, sco u := output.UI(cmd, out) sep := " " + ui.Separator.Symbol() + " " var history []string + armed := false // a Ctrl-C stopped the last turn, so one more leaves for { line, ok, err := ReadLine(prompt.Options{ UI: u, In: cmd.InOrStdin(), Out: out, Width: ui.TerminalWidth(out), History: history, Text: true, Label: "You", Placeholder: "Say something to the agent", Footer: endCommand + " ends the session" + sep + newCommand + " starts a fresh one" + sep + "ctrl-d leaves it going", - Context: "session " + rec.ID, + Context: "session " + rec.ID, Armed: armed, }) + armed = false if errors.Is(err, prompt.ErrCanceled) { continue } @@ -79,15 +91,19 @@ func chat(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, sco case said == "": continue case said == endCommand: + stop := catchCtrlC(cmd) evals := lookUpEvaluations(cmd, s, opts, scope.ProjectID) // sessionend.go: for the Next line _, transcript, err := endSession(cmd, s, opts, scope, rec, "Ended with /end in vf session", "") + stop() if err != nil { return err } sayEnded(cmd, scope, rec.ID, transcript, evals) return nil case said == newCommand: + stop := catchCtrlC(cmd) next, err := startAgain(cmd, s, opts, scope, rec) + stop() if err != nil { return err } @@ -101,6 +117,7 @@ func chat(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, sco } else if pressed != said { note(cmd, "Pressed "+quoted(pressed)) } + stop := catchCtrlC(cmd) t, compiled, err := talk(cmd, s, opts, scope, rec, action, newCommand) if err == nil { sayRanEdit(cmd, t, newCommand) @@ -108,6 +125,10 @@ func chat(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, sco rec.Buttons = t.buttons() err = compiled() } + if stop() { + armed = true // canceled.go has said whether the message went out + continue + } if err != nil && cmd.Context().Err() != nil { leaveGoing(cmd, scope, rec.ID) // Ctrl-C stopped the turn, and vf return err @@ -118,6 +139,25 @@ func chat(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, sco } } +// catchCtrlC has a Ctrl-C, until stop, cancel what cmd waits on instead of +// ending vf, and stop says whether one did. In the home prompt, whose own +// catch cancels the whole line (cli/home.go), cmd's context ends with it, +// and stop says false: the chat ends with the line, as it did. +func catchCtrlC(cmd *cobra.Command) (stop func() (pressed bool)) { + parent := cmd.Context() + if parent == nil { + parent = context.Background() + } + ctx, cancel := signal.NotifyContext(parent, os.Interrupt) + cmd.SetContext(ctx) + return func() bool { + pressed := ctx.Err() != nil && parent.Err() == nil + cancel() + cmd.SetContext(parent) + return pressed + } +} + // startAgain ends session rec, and starts a fresh one as the current one. func startAgain(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, scope sessionScope, rec sessions.Session) (sessions.Session, error) { _, transcript, err := endSession(cmd, s, opts, scope, rec, "Ended with /new in vf session", "") diff --git a/internal/cli/session_test.go b/internal/cli/session_test.go index 4e58edec..90eb49e3 100644 --- a/internal/cli/session_test.go +++ b/internal/cli/session_test.go @@ -10,9 +10,11 @@ import ( "io" "net/http" "net/http/httptest" + "os" "regexp" "strings" "sync" + "syscall" "testing" "time" @@ -52,6 +54,28 @@ type sessionAPI struct { evalStatus int // stale has a text turn answer needsRecompile: an edit vf didn't make. stale bool + // ctrlC names requests ("compile", "text") during which the person + // presses Ctrl-C, once each: the API gets the request, then the process + // gets SIGINT, and the answer waits until vf gives up on it. + ctrlC map[string]bool +} + +// pressCtrlC is SIGINT to this process during the request r, when the test +// asked for one during a request of its kind. It reports whether it sent one. +func (api *sessionAPI) pressCtrlC(kind string, r *http.Request) bool { + api.mu.Lock() + press := api.ctrlC[kind] + delete(api.ctrlC, kind) + api.mu.Unlock() + if !press { + return false + } + _ = syscall.Kill(os.Getpid(), syscall.SIGINT) + select { + case <-r.Context().Done(): + case <-time.After(5 * time.Second): + } + return true } func newSessionAPI(t *testing.T) *sessionAPI { @@ -90,6 +114,9 @@ func (api *sessionAPI) serve(w http.ResponseWriter, r *http.Request) { switch { case strings.HasSuffix(r.URL.Path, "/compile"): say("compile") + if api.pressCtrlC("compile", r) { + return + } io.WriteString(w, `{"message":"Environment compiled","durationMs":5}`) case strings.HasSuffix(r.URL.Path, "/variables"): var req struct{ Variables json.RawMessage } @@ -134,6 +161,9 @@ func (api *sessionAPI) serve(w http.ResponseWriter, r *http.Request) { var text string _ = json.Unmarshal(req.Action.Payload, &text) say("text " + text) + if api.pressCtrlC("text", r) { + return + } api.mu.Lock() stale := api.stale api.mu.Unlock() diff --git a/internal/cli/sessionchat_test.go b/internal/cli/sessionchat_test.go index 583cfd0c..26655831 100644 --- a/internal/cli/sessionchat_test.go +++ b/internal/cli/sessionchat_test.go @@ -217,3 +217,89 @@ func TestASendAfterAnEditSaysItRunsIt(t *testing.T) { t.Errorf("the stale turn's warning:\n%s", errOut) } } + +// ctrlCChild is set in the child process the Ctrl-C test runs the chat in. +const ctrlCChild = "VF_TEST_CHAT_CTRL_C_CHILD" + +// fix-verifier:N2 (R8 #50): in a shell, Ctrl-C while the chat waited for a +// reply ended vf at once, by SIGINT, with nothing printed, though the +// message had reached the agent and the session was still going. Now a +// Ctrl-C stops the turn and says what became of the message, as `session +// send` does in the home prompt; the You line comes back armed, so the next +// Ctrl-C leaves, with the line that says how to come back. +// +// SIGINT kills a process nothing catches, so the chat runs in a child +// process, which gets a real one during each turn, and this checks how the +// child ended. +func TestCtrlCDuringAChatTurnStopsTheTurnNotVf(t *testing.T) { + if os.Getenv(ctrlCChild) != "" { + ctrlCDuringAChatTurn(t) + return + } + child := exec.Command(os.Args[0], "-test.run=^TestCtrlCDuringAChatTurnStopsTheTurnNotVf$", "-test.v", "-test.count=1") + child.Env = append(os.Environ(), ctrlCChild+"=1") + out, err := child.CombinedOutput() + if err != nil { + t.Fatalf("vf didn't survive Ctrl-C during a chat turn: %v\n%s", err, out) + } + if !strings.Contains(string(out), "--- PASS") { + t.Errorf("the child didn't pass:\n%s", out) + } +} + +func ctrlCDuringAChatTurn(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + savedChats, savedRead := conversation.Chats, conversation.ReadLine + t.Cleanup(func() { conversation.Chats, conversation.ReadLine = savedChats, savedRead }) + conversation.Chats = func(*cobra.Command) bool { return true } + var armed []bool + lines := []string{"Is there a student discount?", "What is your return window?"} + conversation.ReadLine = func(o prompt.Options) (string, bool, error) { + armed = append(armed, o.Armed) + if len(lines) == 0 { + return "", false, nil // the second Ctrl-C + } + if len(lines) == 2 { + // An edit, so the first turn compiles first; Ctrl-C comes + // during the compile, and then during the second's turn. + api.ctrlC = map[string]bool{"compile": true} + _ = sessions.MarkEdited("p1", "main") + } else { + api.ctrlC = map[string]bool{"text": true} + } + line := lines[0] + lines = lines[1:] + return line, true, nil + } + + out, errOut, err := api.session(home, false, "start") + if err != nil { + t.Fatalf("the chat should end as the person left it: %v\n%s%s", err, out, errOut) + } + seen, users := api.requests() + want := "compile, launch, compile, compile, text What is your return window?" + if got := strings.Join(seen, ", "); got != want { + t.Errorf("sent %q, want %q", got, want) + } + id := users[1] + for _, said := range []string{ + "Canceled. Nothing was sent.", + "Stopped waiting for the agent, but the message may have reached it", + "vf session get --session " + id, + "Session " + id + " is still going: 'vf session send -p p1 -e main' at a terminal goes back to it.", + } { + if !strings.Contains(errOut, said) { + t.Errorf("missing %q:\n%s", said, errOut) + } + } + if strings.Index(errOut, "Nothing was sent") > strings.Index(errOut, "may have reached it") { + t.Errorf("the compile's Ctrl-C should come first:\n%s", errOut) + } + if want := []bool{false, true, true}; len(armed) != 3 || armed[0] || !armed[1] || !armed[2] { + t.Errorf("the You line came back armed %v, want %v: after each Ctrl-C, one more leaves", armed, want) + } + if current, _ := sessions.Current("p1", "main"); current.ID != id { + t.Errorf("the session should still be the current one: %q", current.ID) + } +} diff --git a/internal/prompt/prompt.go b/internal/prompt/prompt.go index 29e6753a..9e8fcff3 100644 --- a/internal/prompt/prompt.go +++ b/internal/prompt/prompt.go @@ -40,6 +40,9 @@ type Options struct { Text bool Footer string Label string + // Armed starts the line as if Ctrl-C had been pressed on it once, so + // one more leaves: the chat's Ctrl-C that stopped a turn was the first. + Armed bool } // maxRows is how many suggestions the menu shows at once; it scrolls with @@ -117,7 +120,7 @@ func newModel(o Options) *model { in.Cursor.SetMode(cursor.CursorStatic) in.Focus() m := &model{ui: o.UI, input: in, width: o.Width, complete: o.Complete, keys: o.Keys, context: o.Context, history: o.History, histAt: len(o.History), - text: o.Text, footerText: o.Footer, label: o.Label} + text: o.Text, footerText: o.Footer, label: o.Label, armed: o.Armed} m.resize() return m } diff --git a/internal/prompt/prompt_test.go b/internal/prompt/prompt_test.go index c78f83ce..89ca2b89 100644 --- a/internal/prompt/prompt_test.go +++ b/internal/prompt/prompt_test.go @@ -576,3 +576,26 @@ func TestATextLineTypesSlashAndLabelsItsEcho(t *testing.T) { t.Errorf("? should be typed: %q, help %v", m.input.Value(), m.help) } } + +// A line Armed starts as if Ctrl-C had been pressed on it once: the chat's +// Ctrl-C that stopped a turn was the first, so one more leaves. Typing +// disarms it, as it does a Ctrl-C pressed on the line. +func TestAnArmedLineLeavesOnOneCtrlC(t *testing.T) { + armed := func() *model { + return newModel(Options{ + UI: ui.New(io.Discard, ui.Options{Decorate: true}), Width: 80, + Text: true, Label: "You", Footer: "/end ends the session", Armed: true, + }) + } + m := armed() + if view := m.View(); !strings.Contains(view, "Press Ctrl-C again to exit") { + t.Errorf("an armed line says one more Ctrl-C leaves:\n%s", view) + } + if m.press(ctrlC); !m.exited { + t.Error("one Ctrl-C should leave an armed line") + } + m = armed().typed("x").press(ctrlC).press(ctrlC) + if m.exited || !strings.Contains(m.View(), "Press Ctrl-C again to exit") { + t.Errorf("typing disarms it: exited=%v\n%s", m.exited, m.View()) + } +} From dd1c9a845a7a99da0c2bf88f710db2be7dda8ef7 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:34:59 -0500 Subject: [PATCH 14/25] fix(session): the chat's lines break between words, and its footer fits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: fix-verifier N7 and human-poweruser F7 (R8 #53). At 100 columns Ctrl-D's "Session … is still going: 'vf session send -p … -e main' at a terminal goes back to it." broke mid-word, "termin" / "al"; at 72 the footer under the chat's box was cut, "ctrl-d leaves it goi". Cause: the leave line and the chat's notes were printed as one muted string, whatever the width, so the terminal broke them where the column ran out; the footer was one fixed 72-column string, and the prompt's renderer truncates a line wider than the terminal. Change: the leave line, note() (the ran-edit and "Pressed" lines), the "N other traces" line and a send's You echo go through ui.Fit, so they break between words with a quoted command kept whole on its line; the footer is the longest of three that fits the width ("/end ends it · /new starts over · ctrl-d leaves it going" at 60 to 73 columns). The test runs a send and a chat under script(1) at 60, 72, 80 and 100 columns, with a 24-character project ID, and checks every line but a command fits. --- internal/cli/conversation/reply.go | 4 +- internal/cli/conversation/session.go | 14 +- internal/cli/conversation/sessionchat.go | 30 ++++- internal/cli/conversation/sessionsend.go | 4 +- internal/cli/sessionwidth_test.go | 160 +++++++++++++++++++++++ 5 files changed, 202 insertions(+), 10 deletions(-) create mode 100644 internal/cli/sessionwidth_test.go diff --git a/internal/cli/conversation/reply.go b/internal/cli/conversation/reply.go index a6509dab..da2a23b1 100644 --- a/internal/cli/conversation/reply.go +++ b/internal/cli/conversation/reply.go @@ -293,6 +293,8 @@ func (t turn) write(cmd *cobra.Command, out io.Writer, debug bool) { fmt.Fprintln(out, u.Muted("The conversation ended.")) } if len(t.hidden) > 0 && !debug { - fmt.Fprintln(out, u.Muted(t.hiddenNote()+" "+u.Glyph(ui.Separator)+" --show-debug shows them")) + for _, line := range strings.Split(u.Fit(t.hiddenNote()+" "+u.Glyph(ui.Separator)+" --show-debug shows them", 0), "\n") { + fmt.Fprintln(out, u.Muted(line)) + } } } diff --git a/internal/cli/conversation/session.go b/internal/cli/conversation/session.go index 5cd93d6c..0e16548c 100644 --- a/internal/cli/conversation/session.go +++ b/internal/cli/conversation/session.go @@ -26,6 +26,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "slices" "strings" @@ -347,8 +348,17 @@ func forAPerson(cmd *cobra.Command) bool { // note prints a muted line for a person, under the turn. func note(cmd *cobra.Command, line string) { - out := cmd.OutOrStdout() - fmt.Fprintln(out, output.UI(cmd, out).Muted(line)) + sayMuted(cmd, cmd.OutOrStdout(), line) +} + +// sayMuted prints text muted on w, broken between words to fit the +// terminal, which broke a long line mid-word ("termin" / "al", round 8: +// fix-verifier N7). A quoted command stays whole (ui/wrap.go). +func sayMuted(cmd *cobra.Command, w io.Writer, text string) { + u := output.UI(cmd, w) + for _, line := range strings.Split(u.Fit(text, 0), "\n") { + fmt.Fprintln(w, u.Muted(line)) + } } // writeNext says what to run next, on stderr, as an update's Next does. diff --git a/internal/cli/conversation/sessionchat.go b/internal/cli/conversation/sessionchat.go index b3961c83..21a1364a 100644 --- a/internal/cli/conversation/sessionchat.go +++ b/internal/cli/conversation/sessionchat.go @@ -35,6 +35,7 @@ import ( "os/signal" "strings" + "github.com/charmbracelet/x/ansi" "github.com/spf13/cobra" "github.com/voiceflow/cli/internal/interactive" @@ -66,15 +67,14 @@ const ( func chat(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, scope sessionScope, rec sessions.Session) error { out := cmd.OutOrStdout() u := output.UI(cmd, out) - sep := " " + ui.Separator.Symbol() + " " var history []string armed := false // a Ctrl-C stopped the last turn, so one more leaves for { + width := ui.TerminalWidth(out) line, ok, err := ReadLine(prompt.Options{ - UI: u, In: cmd.InOrStdin(), Out: out, Width: ui.TerminalWidth(out), History: history, + UI: u, In: cmd.InOrStdin(), Out: out, Width: width, History: history, Text: true, Label: "You", Placeholder: "Say something to the agent", - Footer: endCommand + " ends the session" + sep + newCommand + " starts a fresh one" + sep + "ctrl-d leaves it going", - Context: "session " + rec.ID, Armed: armed, + Footer: chatFooter(width), Context: "session " + rec.ID, Armed: armed, }) armed = false if errors.Is(err, prompt.ErrCanceled) { @@ -216,6 +216,24 @@ func leaveGoing(cmd *cobra.Command, scope sessionScope, id string) { if current, _ := sessions.Current(scope.ProjectID, scope.EnvironmentAlias); current.ID != id { back = sessionCommand("send", scope, id) } - w := cmd.ErrOrStderr() - fmt.Fprintln(w, output.UI(cmd, w).Muted("Session "+id+" is still going: '"+back+"' at a terminal goes back to it.")) + sayMuted(cmd, cmd.ErrOrStderr(), "Session "+id+" is still going: '"+back+"' at a terminal goes back to it.") +} + +// chatFooter is the muted line under the chat's empty box: the most of it +// that fits width columns, after the box's two-space indent. The terminal +// cut the whole of it at 72 columns: "ctrl-d leaves it goi" (round 8: +// fix-verifier N7). +func chatFooter(width int) string { + sep := " " + ui.Separator.Symbol() + " " + footers := []string{ + endCommand + " ends the session" + sep + newCommand + " starts a fresh one" + sep + "ctrl-d leaves it going", + endCommand + " ends it" + sep + newCommand + " starts over" + sep + "ctrl-d leaves it going", + endCommand + " ends" + sep + newCommand + " restarts" + sep + "ctrl-d leaves", + } + for _, footer := range footers { + if width <= 0 || 2+ansi.StringWidth(footer) <= width { + return footer + } + } + return footers[len(footers)-1] } diff --git a/internal/cli/conversation/sessionsend.go b/internal/cli/conversation/sessionsend.go index 6726605e..37abe6cb 100644 --- a/internal/cli/conversation/sessionsend.go +++ b/internal/cli/conversation/sessionsend.go @@ -103,7 +103,9 @@ func runSessionSend(cmd *cobra.Command, args []string) error { sayCurrent(cmd, "Started session", rec.ID) writeTurn(cmd, launch) out := cmd.OutOrStdout() - fmt.Fprintln(out, output.UI(cmd, out).Bold("You ")+said) + u := output.UI(cmd, out) + const label = "You " + fmt.Fprintln(out, u.Bold(label)+u.Fit(said, len(label))) // breaks between words, under itself, as the reply does } t, compiled, err := talk(cmd, s, opts, scope, rec, action, "'"+sessionCommand("start", scope, "")+"'") if err != nil { diff --git a/internal/cli/sessionwidth_test.go b/internal/cli/sessionwidth_test.go new file mode 100644 index 00000000..28a8876d --- /dev/null +++ b/internal/cli/sessionwidth_test.go @@ -0,0 +1,160 @@ +// This file is not generated by Speakeasy. It covers how the session +// commands' lines fit a terminal (conversation/sessionchat.go, session.go): +// a send, then a chat that runs an edit and is left going with Ctrl-D, at +// 60, 72, 80 and 100 columns. The test runs itself again under script(1), +// which gives it a terminal, as donetty_test.go does, and is skipped where +// script isn't installed. + +package cli + +import ( + "fmt" + "os" + "os/exec" + "regexp" + "runtime" + "strconv" + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/cli/conversation" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/prompt" + "github.com/voiceflow/cli/internal/sessions" + "github.com/voiceflow/cli/internal/ui" +) + +const chatAtWidths = "VF_TEST_CHAT_AT_WIDTHS" + +// A project ID as long as a real one: the line that says how to come back +// names it. +const longProject = "6a67842584dac97c7626ebaa" + +var chatWidths = []int{60, 72, 80, 100} + +// fix-verifier:N7 (R8 #53): at 100 columns, Ctrl-D's "Session … is still +// going: '…' at a terminal goes back to it." broke mid-word, "termin" / +// "al", and at 72 the footer under the chat's box was cut: "ctrl-d leaves +// it goi". The chat's own lines now break between words, the quoted command +// whole, and the footer says as much as fits. +func TestTheChatsLinesFitTheTerminal(t *testing.T) { + if os.Getenv(chatAtWidths) != "" { + chatAtEachWidth(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=^TestTheChatsLinesFitTheTerminal$", "-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(), chatAtWidths+"=1", "TERM=xterm", "NO_COLOR=1") + out, err := cmd.CombinedOutput() + got := terminalText(string(out)) + if err != nil { + t.Errorf("the child: %v", err) // and its lines are checked all the same + } + parts := regexp.MustCompile(`=== (\d+) columns\n`).Split(got, -1) + if len(parts) != len(chatWidths)+1 { + t.Fatalf("want a part per width:\n%s", got) + } + for i, width := range chatWidths { + part := parts[i+1] + for _, line := range strings.Split(part, "\n") { + // A command is left whole, to copy (ui/wrap.go), and so + // is a line of one word. + if ansi.StringWidth(line) > width && !ui.IsCommand(line) && len(strings.Fields(line)) > 1 { + t.Errorf("at %d columns, a line is wider: %q", width, line) + } + } + flat := strings.Join(strings.Fields(part), " ") + for _, said := range []string{ + "You How long do refunds take for an order that shipped last week but hasn't arrived yet?", + "This turn runs your edit. Earlier replies in this session can still steer the agent: /new starts fresh.", + "is still going: 'vf session send -p " + longProject + " -e main' at a terminal goes back to it.", + } { + if !strings.Contains(flat, said) { + t.Errorf("at %d columns, missing %q:\n%s", width, said, part) + } + } + if !strings.Contains(part, "'vf session send -p "+longProject+" -e main'") { + t.Errorf("at %d columns, the command to come back should be whole on its line:\n%s", width, part) + } + } + for _, line := range strings.Split(got, "\n") { + if strings.Contains(line, "sessionwidth_test.go") { + t.Error("the child: " + strings.TrimSpace(line)) + } + } +} + +// terminalText is what a terminal shows of out: each line as the last +// carriage return left it, with no escape sequences. +func terminalText(out string) string { + lines := strings.Split(strings.ReplaceAll(out, "\r\n", "\n"), "\n") + for i, line := range lines { + if j := strings.LastIndex(line, "\r"); j >= 0 { + line = line[j+1:] + } + lines[i] = strings.TrimRight(ansi.Strip(line), " ") + } + return strings.Join(lines, "\n") +} + +// chatAtEachWidth, at each width, sends a message that starts a session, +// then chats in it: the first line runs an edit made since, and then the +// person leaves with Ctrl-D. stdout and stderr are the terminal script gave +// the test. +func chatAtEachWidth(t *testing.T) { + api := newSessionAPI(t) + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", api.url) + savedChats, savedRead := conversation.Chats, conversation.ReadLine + t.Cleanup(func() { conversation.Chats, conversation.ReadLine = savedChats, savedRead }) + run := func(args ...string) { + output.ResetAgentMode() + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + root.SetArgs(append(args, "-p", longProject, "-e", "main", "--agent-mode=false", "--no-interactive")) + if err := renderError(root.ExecuteC()); err != nil { + t.Errorf("%v: %v", args, err) + } + } + for _, width := range chatWidths { + t.Setenv("HOME", t.TempDir()) + t.Setenv("COLUMNS", strconv.Itoa(width)) + fmt.Printf("=== %d columns\n", width) + + conversation.Chats = func(*cobra.Command) bool { return false } + run("session", "send", "How long do refunds take for an order that shipped last week but hasn't arrived yet?") + + conversation.Chats = func(*cobra.Command) bool { return true } + lines := []string{"Are you open on Sunday?"} + conversation.ReadLine = func(o prompt.Options) (string, bool, error) { + if o.Width != width || 2+ansi.StringWidth(o.Footer) > width || !strings.Contains(o.Footer, "/end") || !strings.Contains(o.Footer, "/new") || !strings.Contains(o.Footer, "ctrl-d") { + t.Errorf("at %d columns (the line has %d), the footer under the box is %d wide: %q", width, o.Width, 2+ansi.StringWidth(o.Footer), o.Footer) + } + if len(lines) == 0 { + return "", false, nil + } + _ = sessions.MarkEdited(longProject, "main") // an edit from another window + line := lines[0] + lines = lines[1:] + return line, true, nil + } + run("session", "send") + } +} From b909c151debc91fa7a19fec53cc3bd45b531be09 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:38:51 -0500 Subject: [PATCH 15/25] fix(home): "chat", "talk" and "conversation" select session start, and "chat" finds widget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: fix-verifier N4 (R8 #49). In the home prompt, typing `chat` (also `talk`, `conversation`) listed "❯ session end End the session, and find its transcript" selected, then run-script, send, start: Enter ended a session instead of starting one. `chat` no longer listed `widget` ("Configure the web chat widget…"), which round 7 found for it. Cause: intents.go collected an intent's commands into a set, and matching sorted them by name, so "session end" came first. The summary search, which found `widget` by "chat" in its summary, runs only when nothing else matched, and the session intent now always matched. Change: an intent's commands come in the order it lists them (sessions: start, send, end, run-script; the document list is in name order, so its menus are as before), and "chat" lists `widget` after the session commands. The test types each word into the real command tree's menu and checks the rows in order. --- internal/cli/sessionhide_test.go | 32 +++++++++++++++++++++++++++++++ internal/prompt/intents.go | 33 +++++++++++++++++++++----------- 2 files changed, 54 insertions(+), 11 deletions(-) diff --git a/internal/cli/sessionhide_test.go b/internal/cli/sessionhide_test.go index 20499e23..a6deffcd 100644 --- a/internal/cli/sessionhide_test.go +++ b/internal/cli/sessionhide_test.go @@ -71,3 +71,35 @@ func TestSessionIsListedWhereConversationWas(t *testing.T) { t.Errorf("conversation --help: %v\n%s", err, out) } } + +// fix-verifier:N4 (R8 #49): in the home prompt, "chat", "talk" and +// "conversation" listed the session commands by name, so `session end` was +// the one selected, and Enter ended a session; and "chat" no longer found +// `widget`, the web chat, as it had in round 7. Now `session start` leads, +// then send, end and run-script, and "chat" lists widget after them. +func TestTheWordsForTalkingLeadWithStartingASession(t *testing.T) { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + talking := []string{"session start", "session send", "session end", "session run-script"} + for _, c := range []struct { + typed string + want []string + }{ + {"chat", append(append([]string{}, talking...), "widget")}, + {"/chat", append(append([]string{}, talking...), "widget")}, + {"talk", talking}, + {"conversation", talking}, + {"conv", talking}, + {"session", append([]string{"session"}, talking...)}, // the group, by its name, first + } { + var got []string + for _, s := range prompt.Commands(root, nil)(c.typed) { + got = append(got, s.Label) + } + if strings.Join(got, " | ") != strings.Join(c.want, " | ") { + t.Errorf("the menu for %q is\n %s\nwant\n %s", c.typed, strings.Join(got, " | "), strings.Join(c.want, " | ")) + } + } +} diff --git a/internal/prompt/intents.go b/internal/prompt/intents.go index 8c4a011c..40c6b2d3 100644 --- a/internal/prompt/intents.go +++ b/internal/prompt/intents.go @@ -22,11 +22,16 @@ // // Round 8 hid `vf conversation` behind `vf session`, so "conversation", and // the words people use for talking to the agent ("chat", "talk"), find the -// session commands. +// session commands. Sorted by name they led with `session end`, so Enter on +// "chat" ended a session, and "chat" no longer found `widget`, the web chat, +// which its summary had found (round 8: fix-verifier N4). An intent's +// commands now come in the order it lists them, the likeliest first, and +// "chat" lists `widget` after the session commands. package prompt import ( + "maps" "slices" "strings" @@ -36,12 +41,14 @@ import ( ) // addingDocuments are the commands that add to the knowledge base. -var addingDocuments = []string{"document create-text", "document create-url", "document create-table"} +var addingDocuments = []string{"document create-table", "document create-text", "document create-url"} -// talking are the commands that talk to the agent. +// talking are the commands that talk to the agent, in the order a person +// reaches for them: start one, go on in it, end it, script one. var talking = []string{"session start", "session send", "session end", "session run-script"} -// intents are words people type for a task, and the commands that do it. +// intents are words people type for a task, and the commands that do it, +// in the order the menu offers them. var intents = map[string][]string{ "upload": addingDocuments, "add": addingDocuments, @@ -52,7 +59,7 @@ var intents = map[string][]string{ "website": {"document create-url"}, "spreadsheet": {"document create-table"}, - "chat": talking, + "chat": append(slices.Clone(talking), "widget"), // the web chat, which its summary found (R8 #49) "talk": talking, "session": talking, "conversation": talking, // hidden behind session (round 8) @@ -63,20 +70,24 @@ var intents = map[string][]string{ const intentMin = 2 // byIntent is the commands for the intents p starts, skipping those already -// offered. +// offered, in the order the intents list them. func byIntent(root *cobra.Command, p string, from int, offered []Suggestion) []Suggestion { if len(p) < intentMin { return nil } - want := map[string]bool{} - for word, paths := range intents { + var want []string + for _, word := range slices.Sorted(maps.Keys(intents)) { if strings.HasPrefix(word, strings.ToLower(p)) { - for _, path := range paths { - want[path] = true + for _, path := range intents[word] { + if !slices.Contains(want, path) { + want = append(want, path) + } } } } - return matching(root, from, offered, func(_ *cobra.Command, path string) bool { return want[path] }) + out := matching(root, from, offered, func(_ *cobra.Command, path string) bool { return slices.Contains(want, path) }) + slices.SortStableFunc(out, func(a, b Suggestion) int { return slices.Index(want, a.Label) - slices.Index(want, b.Label) }) + return out } // addedWith is the commands in other groups that add to what group works From 500160f8fb7b2a5a99829b6b08cedac791dc9707 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:44:00 -0500 Subject: [PATCH 16/25] docs(session): the compile rule names the clients a compile changes, and the web chat takes a publish MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: fix-verifier N6 (R8 #52). `vf link` said "Run 'vf environment compile' only for other clients (the web chat, the raw API) after edits made outside vf", while `vf widget get-snippet` said "⚠ The widget serves the published version… Nothing has been published since", and its snippet has versionVariant 'published'. An agent may compile to "update the web chat" and see no change; and vf's own edits reach a raw-API draft client only once something compiles. Cause: round 8's wording of the rule (the r7-1 patch for link.go and outline.go) lumped the widget in with draft clients. The widget snippet pins the published version unless made with --version-param draft (widget/getsnippet.go); only clients that run the draft, such as the Dialog Manager API with the draft's version ID, run it as last compiled. Neither send's help nor the README said what such clients need. Change: send's help (autocompile.go) and the README's compile bullet say that clients outside vf that run the draft need 'vf environment compile' after an edit unless a vf session has started or taken a turn since, and that the web chat widget serves the published version by default, so an edit reaches it with 'vf environment publish'. docs/vf_session_send.md is regenerated. The same correction for link.go and outline.go, which are on other branches, is in the round's r7-1.patch. The test reads send's help and the README for the rule. --- README.md | 2 +- docs/vf_session_send.md | 2 ++ internal/cli/compilerule_test.go | 44 ++++++++++++++++++++++++ internal/cli/conversation/autocompile.go | 8 +++++ 4 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 internal/cli/compilerule_test.go diff --git a/README.md b/README.md index 49f2c97c..a2e0c42e 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ Worth knowing before you script against the CLI: - **A session talks to the draft, what you are editing; `vf session start -v published` talks to 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. - **vf remembers the current session** for each project and environment, so `send`, `get`, `update` and `end` need no ID, and a `send` with none going starts one. `-s ` names another. A session's ID is its conversation's user ID: `vf transcript search --session ` lists its transcripts, and `vf evaluation run --session ` evaluates its newest. `vf session run-script` runs a list of messages as a fresh session. At a terminal, `vf session start` goes on to a chat, a turn a line, until `/end`; Ctrl-D leaves the session going, and `vf session send` with no message goes back to it. (`vf conversation`, which took a user ID, a version and an action in JSON on every turn, still runs for the scripts that use it.) -- **A session with the draft runs your latest edits.** The draft runs as last compiled, so vf compiles it when a session starts (`session start`, `session run-script`, a `send` that starts one), and before a turn after vf itself edited the draft (`vf agent update`, `vf playbook update`, …). Other turns don't compile. A compile takes about half a second. If the draft won't compile, vf says why and sends nothing (`error_type` `compile_failed`, exit 1). An edit made elsewhere, or while a turn runs, can miss that turn; vf then compiles after it and warns, so the next turn runs it. A conversation already going can still be swayed by its earlier replies: to try an edit cleanly, start a new session. `--no-compile` talks to the last build as it is; the published version is never compiled. +- **A session with the draft runs your latest edits.** The draft runs as last compiled, so vf compiles it when a session starts (`session start`, `session run-script`, a `send` that starts one), and before a turn after vf itself edited the draft (`vf agent update`, `vf playbook update`, …). Other turns don't compile. A compile takes about half a second. If the draft won't compile, vf says why and sends nothing (`error_type` `compile_failed`, exit 1). An edit made elsewhere, or while a turn runs, can miss that turn; vf then compiles after it and warns, so the next turn runs it. A conversation already going can still be swayed by its earlier replies: to try an edit cleanly, start a new session. `--no-compile` talks to the last build as it is; the published version is never compiled. Clients outside vf that run the draft, such as the Dialog Manager API with the draft's version ID, run it as last compiled: after an edit, run `vf environment compile`, unless a vf session with the draft has started or taken a turn since. The web chat widget serves the published version by default, so an edit reaches it with `vf environment publish`. - **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/docs/vf_session_send.md b/docs/vf_session_send.md index 1071d3a4..7a59ca52 100644 --- a/docs/vf_session_send.md +++ b/docs/vf_session_send.md @@ -14,6 +14,8 @@ With the draft, vf compiles it when a conversation starts, and before a turn whe An edit made elsewhere, in Creator or by another client, can miss a turn. Then vf compiles after it, and warns: the next turn runs the edit. --no-compile runs the draft as last compiled. The published version is never compiled. +Clients outside vf that run the draft, such as the Dialog Manager API with the draft's version ID, run it as last compiled: after an edit, run 'vf environment compile', unless a vf session with the draft has started or taken a turn since. The web chat widget serves the published version by default, so an edit reaches it with 'vf environment publish'. + The agent gets your edits on its next turn, but in a conversation already going its earlier replies can still sway it. To try an edit cleanly, start a new session: 'vf session start'. ``` diff --git a/internal/cli/compilerule_test.go b/internal/cli/compilerule_test.go new file mode 100644 index 00000000..c5113a29 --- /dev/null +++ b/internal/cli/compilerule_test.go @@ -0,0 +1,44 @@ +// This file is not generated by Speakeasy. It covers the compile rule as +// send's help (conversation/autocompile.go) and the README state it for +// clients outside vf. + +package cli + +import ( + "os" + "strings" + "testing" +) + +// fix-verifier:N6 (R8 #52): round 8's rule said "Run 'vf environment +// compile' only for other clients (the web chat, the raw API) after edits +// made outside vf", but `vf widget get-snippet` warned "The widget serves +// the published version", and its snippet pins versionVariant 'published': +// an agent that compiled to update the web chat saw no change. And vf's own +// edits reach a raw-API draft client only once something compiles. The rule +// now names the clients a compile changes, when they need one, and that the +// web chat takes a publish. +func TestTheCompileRuleNamesTheClientsACompileChanges(t *testing.T) { + help, _, err := runInHome(t, t.TempDir(), newSessionAPI(t).url, false, "session", "send", "--help") + if err != nil { + t.Fatal(err) + } + readme, err := os.ReadFile("../../README.md") + if err != nil { + t.Fatal(err) + } + for name, text := range map[string]string{"send --help": help, "README.md": string(readme)} { + flat := strings.ReplaceAll(strings.Join(strings.Fields(text), " "), "`", "'") + for _, rule := range []string{ + "Clients outside vf that run the draft, such as the Dialog Manager API with the draft's version ID, run it as last compiled: after an edit, run 'vf environment compile', unless a vf session with the draft has started or taken a turn since.", + "The web chat widget serves the published version by default, so an edit reaches it with 'vf environment publish'.", + } { + if !strings.Contains(flat, rule) { + t.Errorf("%s should say %q", name, rule) + } + } + if strings.Contains(flat, "(the web chat, the raw API)") { + t.Errorf("%s still says the web chat takes a compile", name) + } + } +} diff --git a/internal/cli/conversation/autocompile.go b/internal/cli/conversation/autocompile.go index 936a048a..0952fafc 100644 --- a/internal/cli/conversation/autocompile.go +++ b/internal/cli/conversation/autocompile.go @@ -34,6 +34,12 @@ // line, so the next turn, from vf or anywhere else, runs the edit. // --no-compile runs whatever was last compiled. The published version is a // release, and is never compiled. +// +// Clients outside vf that run the draft (the Dialog Manager API with the +// draft's version ID) run it as last compiled, so send's help says when +// they need 'vf environment compile'. Round 8 said the web chat did, but +// the widget serves the published version unless its snippet is made with +// --version-param draft (fix-verifier N6). package conversation @@ -95,6 +101,8 @@ const sendCompiles = `With the draft, vf compiles it when a conversation starts, An edit made elsewhere, in Creator or by another client, can miss a turn. Then vf compiles after it, and warns: the next turn runs the edit. --no-compile runs the draft as last compiled. The published version is never compiled. +Clients outside vf that run the draft, such as the Dialog Manager API with the draft's version ID, run it as last compiled: after an edit, run 'vf environment compile', unless a vf session with the draft has started or taken a turn since. The web chat widget serves the published version by default, so an edit reaches it with 'vf environment publish'. + The agent gets your edits on its next turn, but in a conversation already going its earlier replies can still sway it. To try an edit cleanly, start a new session: 'vf session start'.` // turnWait is the wait for one turn, a send or a script: one spinner line, From e73be4e9c1c8367e870878afa3ef45240ea1f78a Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:49:09 -0500 Subject: [PATCH 17/25] fix(session): run-script's answer says session, and a reused -s starts clean as start's does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What testers saw: fix-verifier N9 (R8 #89). `vf session run-script … --messages '[…]'` in agent mode answered `userID: script-6437ba49-…`, where start, send, get and end all say `session:`; an agent that parses .session got nothing. Its help: "-s … another name for --user-id" and "-u … A reused ID keeps the variables an earlier conversation with it left", but `session start -s`: "One used before starts over: vf ends its conversation and clears its state first." Cause: session run-script is conversation's run-script with -s and --end added (sessionscript.go). It printed the API's answer as it came, with userID and no session, and passed a reused ID straight to the API, which keeps the ID's variables and, with no end action before, its transcript (round-8 probe, facts 3 and 6); -u's help is conversation's, which says so. Change: in the session group, an ID given with -s or -u is cleared before the script as start clears one (state get; an end if a conversation is going; state delete): up to three requests, only when an ID is given. The answer for scripts and agents carries session beside userID, which stays for scripts that read it. -s, -u and the long help say a reused ID starts over; `conversation run-script` is unchanged. The generated runscript.go's hook line now calls startScript, which compiles and then clears. docs/vf_session_run-script.md is regenerated. --- docs/vf_session_run-script.md | 6 ++- internal/cli/conversation/runscript.go | 2 +- internal/cli/conversation/sessionscript.go | 63 ++++++++++++++++++++-- internal/cli/conversation/sessionstart.go | 7 ++- internal/cli/sessionscript_test.go | 62 +++++++++++++++++++++ 5 files changed, 132 insertions(+), 8 deletions(-) diff --git a/docs/vf_session_run-script.md b/docs/vf_session_run-script.md index 457c1dc8..50f3442b 100644 --- a/docs/vf_session_run-script.md +++ b/docs/vf_session_run-script.md @@ -8,6 +8,8 @@ Run a list of user messages as one new conversation, and make it the current ses With the draft, vf compiles it first, so the script runs your latest edits. 'vf session send' goes on from the script's last turn; --end ends the session after the script instead, and finds its transcript, for 'vf evaluation run'. +-s reuses a session ID, such as a phone number the agent expects: as with 'vf session start -s', vf ends the conversation it had and clears its state first, so the script starts clean. + ``` vf session run-script [flags] ``` @@ -30,8 +32,8 @@ vf session run-script [flags] -m, --messages string The user messages to send, in order, after the launch. A message is typed text, as a string or { "text": "…" }, or a button press, as { "button": "