Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ Worth knowing before you script against the CLI:

- **`--version-param draft` runs what you are editing; `published` runs the live version.** A new project is created with a first release already in place, so either works immediately — you do not have to publish anything first.
- **`--action '{"type":"launch"}'` is optional.** Sending a `text` action straight away works; the runtime starts the conversation itself. The launch step is shown because it makes the first turn explicit.
- **A conversation with the draft runs your latest edits.** The draft runs as last compiled, so vf compiles it before `conversation run-script` and before a `send` with a `launch` action. If a later turn still ran an older build (you edited mid-conversation, or started with a `text` action), vf compiles right after it and warns, so the next turn runs the edits. `--no-compile` talks to the last build as it is; the published version is never compiled.
- **Pass `--output-format json` explicitly when piping.** Inside AI coding agents (`CLAUDECODE`, `CURSOR_AGENT`, …) the default output is TOON, not JSON.
- **Capture values with `--output-format json | jq -r`** — the built-in `--jq` flag emits JSON, so strings keep their quotes.
- **`vf whoami` is offline** — it shows which credential source is configured but does not validate the token. `vf workspace list` is the real check.
Expand Down
126 changes: 126 additions & 0 deletions internal/cli/autocompile_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// This file is not generated by Speakeasy. It covers
// conversation/autocompile.go: a conversation with the draft runs the latest
// edits.

package cli

import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"

"github.com/voiceflow/cli/internal/output"
)

// conversationServer answers compile with compileStatus, and a conversation
// with answer. It records each request as "compile" or "conversation".
func conversationServer(t *testing.T, compileStatus int, answer string) (url string, requests func() []string) {
t.Helper()
var mu sync.Mutex
var seen []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
mu.Lock()
defer mu.Unlock()
w.Header().Set("Content-Type", "application/json")
if strings.HasSuffix(r.URL.Path, "/compile") {
seen = append(seen, "compile")
w.WriteHeader(compileStatus)
io.WriteString(w, `{"message":"Environment compiled","durationMs":5}`)
return
}
seen = append(seen, "conversation")
io.WriteString(w, answer)
}))
t.Cleanup(srv.Close)
return srv.URL, func() []string {
mu.Lock()
defer mu.Unlock()
return append([]string(nil), seen...)
}
}

func runConversation(t *testing.T, url string, args ...string) (string, error) {
t.Helper()
t.Setenv("VF_TOKEN", "vfp_fake")
t.Setenv("VF_SERVER_URL", url)
t.Setenv("HOME", t.TempDir())
output.ResetAgentMode()
t.Cleanup(output.ResetAgentMode)
root, err := NewRootCommand()
if err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
root.SetOut(&buf)
root.SetErr(&buf)
root.SetIn(strings.NewReader(""))
root.SetArgs(append(append([]string{"conversation"}, args...), "--agent-mode=false", "--no-interactive"))
_, err = root.ExecuteC()
return buf.String(), err
}

const (
freshTurn = `{"traces":[],"needsRecompile":false}`
staleTurn = `{"traces":[],"needsRecompile":true}`
script = `{"userID":"u1","transcriptID":null,"needsRecompile":false,"turns":[],"notSent":[]}`
)

func TestAConversationWithTheDraftCompilesItFirst(t *testing.T) {
scope := []string{"-p", "p1", "-e", "main"}
send := append([]string{"send", "-u", "u1", "-v", "draft"}, scope...)
cases := []struct {
name string
answer string
args []string
want string
}{
{"run-script compiles first", script, append([]string{"run-script", "-m", `["hi"]`}, scope...), "compile conversation"},
{"run-script --no-compile", script, append([]string{"run-script", "-m", `["hi"]`, "--no-compile"}, scope...), "conversation"},
{"run-script on published", script, append([]string{"run-script", "-m", `["hi"]`, "--version-param", "published"}, scope...), "conversation"},
{"a launch compiles first", freshTurn, append(send, "-a", `{"type":"launch"}`), "compile conversation"},
{"a later turn doesn't", freshTurn, append(send, "-a", `{"type":"text","payload":"hi"}`), "conversation"},
{"a stale turn compiles after", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`), "conversation compile"},
{"a stale turn compiles after, -o json", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`, "-o", "json"), "conversation compile"},
{"a stale turn with --no-compile", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`, "--no-compile"), "conversation"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
url, requests := conversationServer(t, 200, c.answer)
out, err := runConversation(t, url, c.args...)
if err != nil {
t.Fatalf("%v\n%s", err, out)
}
if got := strings.Join(requests(), " "); got != c.want {
t.Errorf("requests = %q, want %q", got, c.want)
}
compiled := strings.Contains(c.want, "compile")
if says := strings.Contains(out, "Compiled the draft") || strings.Contains(out, "vf has compiled it"); says != compiled {
t.Errorf("compiled %v, but saying so is %v:\n%s", compiled, says, out)
}
if strings.Contains(c.name, "-o json") && !strings.Contains(out, `"needsRecompile":true`) {
t.Errorf("the answer wasn't printed as it came:\n%s", out)
}
})
}
}

// A draft that won't compile stops the script before it spends credits, and
// says how to run the last build anyway.
func TestADraftThatWontCompileStopsTheScript(t *testing.T) {
url, requests := conversationServer(t, 500, script)
out, err := runConversation(t, url, "run-script", "-m", `["hi"]`, "-p", "p1", "-e", "main")
if err == nil {
t.Fatal("no error")
}
if !strings.Contains(out, "Couldn't compile the draft") || !strings.Contains(out, "--no-compile") {
t.Errorf("the error doesn't say the compile failed, or how to skip it:\n%s", out)
}
if got := strings.Join(requests(), " "); got != "compile" {
t.Errorf("requests = %q, want only the compile", got)
}
}
153 changes: 153 additions & 0 deletions internal/cli/conversation/autocompile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// This file is not generated by Speakeasy. It has a conversation with the
// draft run the latest edits, by compiling the draft first.
//
// A conversation runs the environment's last compiled build, and nothing
// compiled it after an edit. So `agent update` then `conversation run-script`
// talked to the old agent: the usability sweep's agents and newcomers alike
// read the old replies as "my prompt and tool don't work", and spent credits
// on it. The only sign was `needsRecompile: true` atop hundreds of lines.
//
// Nothing says the draft is stale before a run, so vf compiles it whenever a
// conversation with the draft starts: before every run-script, and before a
// send that launches. A send later in a conversation keeps its build, but if
// its turn still ran a stale one, vf compiles right after and says so, so the
// next turn runs the edits. --no-compile runs whatever was last compiled.
// The published version is a release, and is never compiled.

package conversation

import (
"encoding/json"
"fmt"
"strings"
"time"

"github.com/spf13/cobra"

"github.com/voiceflow/cli/internal/client"
"github.com/voiceflow/cli/internal/output"
"github.com/voiceflow/cli/internal/sdk"
"github.com/voiceflow/cli/internal/sdk/models/components"
"github.com/voiceflow/cli/internal/sdk/models/operations"
"github.com/voiceflow/cli/internal/ui"
)

const noCompileFlag = "no-compile"

// addNoCompileFlag lets cmd run the draft as last compiled.
func addNoCompileFlag(cmd *cobra.Command) {
cmd.Flags().Bool(noCompileFlag, false, "Run the draft as last compiled. Without it, vf compiles the draft first when a conversation starts, so it runs your latest edits.")
}

// compileBeforeScript compiles the draft before run-script, which always
// starts a new conversation.
func compileBeforeScript(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableConversationControllerRunScriptRequest) error {
if req.Body.Version != nil && string(*req.Body.Version) != "draft" {
return nil
}
return compileDraft(cmd, s, req.ProjectID, req.EnvironmentAlias)
}

// compileBeforeSend compiles the draft before a send that launches a
// conversation.
func compileBeforeSend(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableConversationControllerSendRequest) error {
if string(req.Body.Version) != "draft" || actionType(req.Body.Action) != "launch" {
return nil
}
return compileDraft(cmd, s, req.ProjectID, req.EnvironmentAlias)
}

// compileAfterStaleSend reads a send's answer before it is printed. When the
// turn ran a stale build of the draft, the function it returns compiles the
// draft once the answer is printed, and says so.
func compileAfterStaleSend(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableConversationControllerSendRequest, res *operations.StableConversationControllerSendResponse) func() error {
none := func() error { return nil }
if res == nil || client.IsDryRun(cmd) || string(req.Body.Version) != "draft" || skipCompile(cmd) {
return none
}
answer := res.StableConversationSendResponse
if answer == nil {
answer = &components.StableConversationSendResponse{}
if !output.PeekJSON(res.HTTPMeta.Response, answer) {
return none
}
}
if !answer.NeedsRecompile {
return none
}
return func() error {
if err := compile(cmd, s, req.ProjectID, req.EnvironmentAlias); err != nil {
return err
}
warn(cmd, "This turn ran an older build of the draft. vf has compiled it, so the next turn runs your latest edits.")
return nil
}
}

// compileDraft compiles the draft of alias in projectID, and says it did.
func compileDraft(cmd *cobra.Command, s *sdk.VoiceflowSDK, projectID, alias string) error {
if skipCompile(cmd) {
return nil
}
start := time.Now()
if err := compile(cmd, s, projectID, alias); err != nil {
return err
}
if !client.IsDryRun(cmd) && !output.IsAgentMode() {
w := cmd.ErrOrStderr()
fmt.Fprintln(w, output.UI(cmd, w).Status(ui.StatusDone, fmt.Sprintf("Compiled the draft of %s (%.1fs), so this runs your latest edits", alias, time.Since(start).Seconds())))
}
return nil
}

func compile(cmd *cobra.Command, s *sdk.VoiceflowSDK, projectID, alias string) error {
ctx := client.WithSpinnerMessage(cmd.Context(), "Compiling the draft…")
_, err := s.Environment.Compile(ctx, operations.StableEnvironmentControllerCompileRequest{ProjectID: projectID, EnvironmentAlias: alias}, operations.WithSkipDeserialization())
if err != nil {
return compileFailed(cmd, err)
}
return nil
}

// compileFailed explains a compile that failed: the conversation didn't
// start, and --no-compile runs the last build instead.
func compileFailed(cmd *cobra.Command, err error) error {
x := output.ExplainError(cmd, err)
title := "Couldn't compile the draft, so the conversation didn't run"
if _, status, ok := strings.Cut(x.Title, " · "); ok {
title += " · " + status
}
x.Title = title
if status := output.StatusCode(err); status >= 400 && status < 500 && status != 401 && status != 403 && status != 404 {
// The agent, not the command's flags, is what didn't compile.
x.Why = []string{"Something in the agent's draft keeps it from compiling."}
x.Next = []string{"Fix what the message names in the agent, then run it again"}
}
x.Next = append(x.Next, "Add `--no-compile` to talk to the last build instead")
return output.Report(cmd, x, err)
}

func skipCompile(cmd *cobra.Command) bool {
skip, _ := cmd.Flags().GetBool(noCompileFlag)
return skip
}

// actionType is a send's action type: "launch", "text", "end"...
func actionType(action components.AnyRequest) string {
raw, err := json.Marshal(action)
if err != nil {
return ""
}
var a struct {
Type string `json:"type"`
}
_ = json.Unmarshal(raw, &a)
return a.Type
}

// warn says msg on stderr, in every mode: a stale turn matters to an agent
// as much as to a person.
func warn(cmd *cobra.Command, msg string) {
w := cmd.ErrOrStderr()
fmt.Fprintln(w, output.UI(cmd, w).Status(ui.StatusWarn, msg))
}
4 changes: 4 additions & 0 deletions internal/cli/conversation/runscript.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ func initRunScriptCmd(parent *cobra.Command) error {
Aliases: []string{"rs"},
}
flagutil.RegisterFlags(cmd, runScriptCmdMeta)
addNoCompileFlag(cmd) // autocompile.go: --no-compile
if err := flagutil.ValidateMeta[operations.StableConversationControllerRunScriptRequest](runScriptCmdMeta); err != nil {
return fmt.Errorf("invalid metadata for run-script: %w", err)
}
Expand Down Expand Up @@ -77,6 +78,9 @@ func runRunScriptCmd(cmd *cobra.Command, args []string) error {
if output.WantsRawJSON(cmd) {
sdkOpts = append(sdkOpts, operations.WithSkipDeserialization())
}
if err := compileBeforeScript(cmd, s, req); err != nil { // autocompile.go: the script runs the latest edits
return err
}
res, err := s.Conversation.RunScript(cmd.Context(), *req, sdkOpts...)
if err != nil {
return output.Error(cmd, err)
Expand Down
7 changes: 6 additions & 1 deletion internal/cli/conversation/send.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ func initSendCmd(parent *cobra.Command) error {
RunE: runSendCmd,
}
flagutil.RegisterFlags(cmd, sendCmdMeta)
addNoCompileFlag(cmd) // autocompile.go: --no-compile
if err := flagutil.ValidateMeta[operations.StableConversationControllerSendRequest](sendCmdMeta); err != nil {
return fmt.Errorf("invalid metadata for send: %w", err)
}
Expand Down Expand Up @@ -76,13 +77,17 @@ func runSendCmd(cmd *cobra.Command, args []string) error {
if output.WantsRawJSON(cmd) {
sdkOpts = append(sdkOpts, operations.WithSkipDeserialization())
}
if err := compileBeforeSend(cmd, s, req); err != nil { // autocompile.go: a new conversation runs the latest edits
return err
}
res, err := s.Conversation.Send(cmd.Context(), *req, sdkOpts...)
if err != nil {
return output.Error(cmd, err)
}

compiled := compileAfterStaleSend(cmd, s, req, res) // autocompile.go: a stale turn compiles the draft for the next
if err := output.Result(cmd, res); err != nil {
return err
}
return nil
return compiled()
}
Loading
Loading