From a076c945cc2ef87f8d29be6f8d6d4d92395b01f7 Mon Sep 17 00:00:00 2001 From: sanasarjanjughazyan <41446832+sanasarjanjughazyan@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:02:18 +0000 Subject: [PATCH] feat(test): run a test suite and wait for it in one command (COR-15957) (#52) Adds `--wait` to `vf test run create-suite`, so one command runs every test, a set of tests or the tests in some folders, waits until every run has finished, and exits non-zero unless every run passed. Linear: [COR-15957](https://linear.app/voiceflow/issue/COR-15957). The API side shipped in [creator-app #24901](https://app.graphite.com/github/pr/voiceflow/creator-app/24901), and the last regeneration added `create-suite`, `wait-suite` and `test folder list`. ## What changes - `--wait` starts the suite, then waits for it in 45-second calls to the suite wait endpoint (the API caps one wait at 120 seconds) until every run has finished. - `--max-wait` caps the total wait, 30 minutes by default. When it runs out, the suite keeps running, and the error names the `vf test run wait-suite` command to keep waiting and the `cancel` command to stop the runs. - Output: progress on stderr (the `bulkID` when the suite starts, then a line like `1 of 4 passed, 1 failed, 2 still going` whenever the counts change). The final wait result (counts, and the runs that did not pass with their failed checks) goes to stdout in whatever `--output-format` is set. - Exit code: 0 only when every run passed. 1 when a run failed or was canceled, or when `--max-wait` ran out. In agent mode those come as the usual error envelope, `test_suite_failed` or `test_suite_unfinished`, with hints, and progress comes as JSON events on stderr (`started` with the `bulkID`, `waiting`, `retrying`), like `vf auth login`, so all of stderr parses as JSON. - A wait that hits a 5xx, a 429, no answer or an answer cut off mid-body is retried up to 3 times, 5 seconds apart, so one dropped request does not end a long wait. - Once the suite has started, every failure names the `wait-suite` command that picks it up again, never "retry the command", which would start a second suite. An API error such as a 401 keeps its usual `error_type`, `status_code` and hints, and gets the resume command added. A failure after `--max-wait` has run out reports the last answer as unfinished. An answer that decodes to nothing stops the wait instead of being polled. Hints carry `--server-url` when it was passed, shell-quoted. - In agent mode, stderr is JSON from start to finish: anything not reported explicitly goes through one guard that renders it as the error envelope. - Each wait asks the API to hold for less when `--timeout` (flag, env or config) would otherwise cut the request off first. - `--test-ids` and `--folder-ids` also take comma-separated IDs, with or without `--wait`. They are generated as repeatable string arrays, so `--test-ids a,b` used to send the single ID `"a,b"` and get a 404. - IDs typed into the interactive prompt are split on commas too. - Before the suite starts (with `--dry-run` too), `--wait` checks `--max-wait`, refuses a `--timeout` under 10 seconds since no wait fits in it, and parses and compiles `--jq`, which would otherwise fail only after the whole wait. - Without `--wait` the generated command runs unchanged. `--max-wait` without `--wait` is refused. - `--usage` lists `--wait` and `--max-wait`, in `vf --usage` and every schema between it and `create-suite --usage`. - The token-format warning prints once per process rather than once per client, since `--wait` builds a client per wait so OAuth tokens refresh. Logic lives in a new hand-written `internal/cli/test/run/createsuite_wait.go`. The generated `createsuite.go` gets one line (`addCreateSuiteWait(cmd)`), which wraps its `RunE`. The new hand-written `internal/usage/extra_flags.go` adds hand-written flags to the generated `--usage` schemas. Unchanged: a flag value cobra cannot parse (`--max-wait abc`) still prints cobra's plain error, the same as for every vf command, before anything is sent. The per-wait deadline is set on the context, because the generated `operations.WithOperationTimeout` checks for retry support instead of timeout support, so it refuses every operation without retries, `WaitSuite` included. ## Tests - New `test/run-suite-wait.test.ts` (mock API), 22 tests. They cover: - Waiting through an unfinished answer and exiting 0; exiting 1 with the failed checks printed; `--max-wait` running out, with the keep-waiting hint. - Retries: a retried 502 and a retried cut-off answer. A 503 that outlasts the retries ends with the resume hint, not "retry the command". A failure after `--max-wait` reports the last answer. - Agent mode, where stderr has to be only JSON: progress events and the envelope; 401 and 404 keeping `authentication_error` / `not_found` plus the resume hint; an empty or `null` answer; a create answer with no `bulkID`; invalid flag values (`--max-wait`, `--timeout`, `--jq`); `--wait --dry-run` with a bad body. - Flags: `--jq` refused before start (syntax and unknown function); `--wait` checks under `--dry-run`; `--usage` at three levels; comma-separated `--test-ids` and `--folder-ids`. - These also catch a regeneration that drops the hook line. - New `createsuite_wait_test.go`: ID splitting, shell quoting of hint values, per-wait length within the API's 5 to 120 seconds and within `--timeout`, which errors are retried, the progress line. - `gofmt -l .` clean; `go test ./...` passes; behaviour tests (`VF_SKIP_INTEGRATION_TESTS=1 yarn test`): 127 passed; `yarn oxlint`: no new warnings. - An independent review traced every error return and stderr write in agent mode, with repros against a mock server. Its findings are fixed and covered above. - `go vet ./...` fails only on generated SDK files with unexported constant fields. It fails the same way on master (the `Vet` step is red on the last three master runs), and `go vet` is clean on the changed package. - Live against a dev env: a folder suite (1 run) and two tests passed as `--test-ids a,b`, both with `--wait`. Both finished in under 35 seconds and exited 0. - Not run: `speakeasy run`, to re-check that the hook line survives regeneration. The behaviour tests fail if it does not. --- internal/cli/test/run/createsuite.go | 1 + internal/cli/test/run/createsuite_wait.go | 585 ++++++++++++++++++ .../cli/test/run/createsuite_wait_test.go | 103 +++ internal/sdk/sdkinternal/hooks/teach.go | 12 +- internal/usage/extra_flags.go | 84 +++ test/run-suite-wait.test.ts | 415 +++++++++++++ 6 files changed, 1195 insertions(+), 5 deletions(-) create mode 100644 internal/cli/test/run/createsuite_wait.go create mode 100644 internal/cli/test/run/createsuite_wait_test.go create mode 100644 internal/usage/extra_flags.go create mode 100644 test/run-suite-wait.test.ts diff --git a/internal/cli/test/run/createsuite.go b/internal/cli/test/run/createsuite.go index 6ff346c2..59b823fc 100644 --- a/internal/cli/test/run/createsuite.go +++ b/internal/cli/test/run/createsuite.go @@ -38,6 +38,7 @@ func initCreateSuiteCmd(parent *cobra.Command) error { return fmt.Errorf("invalid metadata for create-suite: %w", err) } cmd.Flags().String("body", "", "Request body as JSON (alternative to individual flags). Can also be provided via stdin.") + addCreateSuiteWait(cmd) // --wait and comma-separated IDs; see createsuite_wait.go parent.AddCommand(cmd) return nil } diff --git a/internal/cli/test/run/createsuite_wait.go b/internal/cli/test/run/createsuite_wait.go new file mode 100644 index 00000000..e7106664 --- /dev/null +++ b/internal/cli/test/run/createsuite_wait.go @@ -0,0 +1,585 @@ +// This file is not generated by Speakeasy — it adds --wait to +// 'vf test run create-suite', so one command starts a suite, waits until every +// run in it has finished, prints the results and exits non-zero unless every +// run passed. CI can gate on the exit code, and a person or an agent does not +// have to repeat 'vf test run wait-suite' by hand. +// +// The API caps one wait at 120 seconds, because a request held open for the +// half hour a suite can take would be cut off by proxies and by agents' command +// timeouts. So the loop lives here: it waits in 45-second calls until the suite +// is done or --max-wait runs out. +// +// It also lets --test-ids and --folder-ids take comma-separated IDs. They are +// generated as repeatable string arrays, which do not split on commas, so +// '--test-ids a,b' used to send the single ID "a,b" and fail with a 404. +// +// Hooked in by one line in createsuite.go, which a regeneration could drop +// without anything failing to compile; test/run-suite-wait.test.ts covers it. + +package run + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net" + "net/url" + "strings" + "time" + + "github.com/itchyny/gojq" + "github.com/spf13/cobra" + "github.com/spf13/pflag" + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/config" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/sdk/models/sdkerrors" + "github.com/voiceflow/cli/internal/usage" +) + +const ( + suiteWaitFlag = "wait" + suiteMaxWaitFlag = "max-wait" + + suiteDefaultMaxWait = 30 * time.Minute + + // The API accepts 5 to 120 seconds per wait. 45 keeps each request well + // under the timeouts of proxies and agent harnesses. + suiteWaitCallSeconds = 45 + suiteWaitMinCallSeconds = 5 + // Headroom on top of the server-side wait before the request is abandoned. + suiteWaitRequestSlack = 30 * time.Second + // How much sooner than --timeout a wait asks the API to answer. + suiteWaitTimeoutHeadroom = 5 * time.Second + // The least time between two waits, should the API answer early without + // the suite being done. + suiteWaitMinInterval = 2 * time.Second + + suiteWaitRetries = 3 + suiteWaitRetryDelay = 5 * time.Second +) + +var suiteIDFlags = []string{"test-ids", "folder-ids"} + +// addCreateSuiteWait registers --wait and --max-wait on create-suite and wraps +// its RunE. Without --wait the generated command runs unchanged. +func addCreateSuiteWait(cmd *cobra.Command) { + cmd.Flags().Bool(suiteWaitFlag, false, + "Wait until every run in the suite has finished, then print the results. Exits non-zero unless every run passed.") + cmd.Flags().Duration(suiteMaxWaitFlag, suiteDefaultMaxWait, + "With --wait, how long to wait in total (e.g. 10m). The suite keeps running after that; keep waiting with 'vf test run wait-suite'.") + for _, name := range suiteIDFlags { + if flag := cmd.Flags().Lookup(name); flag != nil { + flag.Usage += " Separate IDs with commas or repeat the flag." + } + } + usage.AddFlags("test run create-suite", + usage.UsageFlag{Spec: "--" + suiteWaitFlag, Help: cmd.Flags().Lookup(suiteWaitFlag).Usage}, + usage.UsageFlag{Spec: "--" + suiteMaxWaitFlag + " ", Help: cmd.Flags().Lookup(suiteMaxWaitFlag).Usage}) + + cmd.Long += ` + +With --wait, the command waits until every run has finished, then prints the +suite's results: counts, and the runs that did not pass with their failed checks. +It exits 0 only when every run passed. It exits 1 when a run failed or was +canceled, or when --max-wait (30 minutes by default) ran out first.` + cmd.Example += ` + vf test run create-suite --project-id --environment-alias --all --wait + vf test run create-suite --project-id --environment-alias --test-ids , --wait + vf test run create-suite --project-id --environment-alias --folder-ids --wait --max-wait 10m` + + runCreateSuite := cmd.RunE + cmd.RunE = func(cmd *cobra.Command, args []string) error { + if usage.UsageRequested(cmd) { + return runCreateSuite(cmd, args) + } + wait, _ := flagutil.GetBoolFlag(cmd, suiteWaitFlag) + if cmd.Flags().Changed(suiteMaxWaitFlag) && !wait { + return suiteError(cmd, "invalid_flag_value", + fmt.Sprintf("--%s only applies with --%s", suiteMaxWaitFlag, suiteWaitFlag), + []string{fmt.Sprintf("Add --%s, or drop --%s", suiteWaitFlag, suiteMaxWaitFlag)}) + } + // Prompted here rather than in the generated RunE, so IDs typed into the + // prompt are split too. Once the flags are set, it does not prompt again. + if interactive.ShouldPrompt(cmd, createSuiteCmdMeta) { + if err := interactive.PromptAndSetFlags(cmd, createSuiteCmdMeta); err != nil { + return err + } + } + if err := splitSuiteIDFlags(cmd); err != nil { + return suiteError(cmd, "invalid_flag_value", err.Error(), nil) + } + if !wait { + return runCreateSuite(cmd, args) + } + opts, err := suiteWaitOptionsFrom(cmd) + if err != nil { + return err + } + if client.IsDryRun(cmd) { + return inAgentEnvelope(cmd, runCreateSuite(cmd, args)) + } + return inAgentEnvelope(cmd, runCreateSuiteAndWait(cmd, opts)) + } +} + +// inAgentEnvelope makes sure that in agent mode an error from --wait reaches +// stderr as the structured envelope, after the JSON progress events, and never +// as prose. Errors already printed (by output.Error or output.AgentModeError) +// have an empty message, the same thing main.go checks before printing, and +// flag-value errors are rendered by cli.Execute, so both are left alone. Every +// failure after the suite has started is reported explicitly, so what reaches +// this is a failure to start it. +func inAgentEnvelope(cmd *cobra.Command, err error) error { + var flagErr *flagutil.FlagValueError + if err == nil || err.Error() == "" || errors.As(err, &flagErr) || !output.IsAgentMode() { + return err + } + return output.AgentModeError(cmd, "test_suite_start_failed", err.Error(), nil) +} + +// splitSuiteIDFlags splits each value of --test-ids and --folder-ids on commas. +func splitSuiteIDFlags(cmd *cobra.Command) error { + for _, name := range suiteIDFlags { + flag := cmd.Flags().Lookup(name) + if flag == nil || !flag.Changed { + continue + } + values, ok := flag.Value.(pflag.SliceValue) + if !ok { + continue + } + if err := values.Replace(splitIDs(values.GetSlice())); err != nil { + return fmt.Errorf("invalid --%s: %w", name, err) + } + } + return nil +} + +func splitIDs(values []string) []string { + ids := make([]string, 0, len(values)) + for _, value := range values { + for _, id := range strings.Split(value, ",") { + if id = strings.TrimSpace(id); id != "" { + ids = append(ids, id) + } + } + } + return ids +} + +type suiteWaitOptions struct { + maxWait time.Duration + requestTimeout time.Duration +} + +// suiteWaitOptionsFrom checks the flags --wait depends on before the suite +// starts, so a mistake in them does not leave queued runs behind. +func suiteWaitOptionsFrom(cmd *cobra.Command) (suiteWaitOptions, error) { + maxWait, err := cmd.Flags().GetDuration(suiteMaxWaitFlag) + if err != nil { + return suiteWaitOptions{}, suiteError(cmd, "invalid_flag_value", err.Error(), nil) + } + if maxWait <= 0 { + return suiteWaitOptions{}, suiteError(cmd, "invalid_flag_value", + fmt.Sprintf("--%s must be more than zero, got %s", suiteMaxWaitFlag, maxWait), + []string{fmt.Sprintf("Pass a duration such as --%s 10m, or drop it to wait up to %s", suiteMaxWaitFlag, suiteDefaultMaxWait)}) + } + requestTimeout, err := globalRequestTimeout(cmd) + if err != nil { + return suiteWaitOptions{}, suiteError(cmd, "invalid_flag_value", err.Error(), + []string{"Pass a duration such as --timeout 2m, or drop --timeout"}) + } + if minTimeout := suiteWaitMinCallSeconds*time.Second + suiteWaitTimeoutHeadroom; requestTimeout > 0 && requestTimeout < minTimeout { + return suiteWaitOptions{}, suiteError(cmd, "invalid_flag_value", + fmt.Sprintf("--%s needs a --timeout of at least %s, since each wait holds the request for %ds or more; got %s", + suiteWaitFlag, minTimeout, suiteWaitMinCallSeconds, requestTimeout), + []string{fmt.Sprintf("Pass --timeout %s or more, or drop --timeout", minTimeout)}) + } + // The result is only printed once the suite has finished, so a --jq that + // cannot run would otherwise fail after the whole wait. Compiling catches + // unknown functions as well as syntax errors. + if expression, _ := flagutil.GetStringFlag(cmd, "jq"); expression != "" { + query, err := gojq.Parse(expression) + if err == nil { + _, err = gojq.Compile(query) + } + if err != nil { + return suiteWaitOptions{}, suiteError(cmd, "invalid_flag_value", fmt.Sprintf("invalid --jq expression %q: %v", expression, err), + []string{"Fix the expression, or drop --jq; nothing was started"}) + } + } + return suiteWaitOptions{maxWait: maxWait, requestTimeout: requestTimeout}, nil +} + +// runCreateSuiteAndWait starts the suite the way runCreateSuiteCmd does, then +// waits for it and reports the outcome. +func runCreateSuiteAndWait(cmd *cobra.Command, opts suiteWaitOptions) error { + maxWait := opts.maxWait + req, err := flagutil.BuildRequest[operations.StableTestRunControllerCreateSuiteRequest](cmd, createSuiteCmdMeta, "Body", "body") + if err != nil { + return err + } + s, err := client.NewClient(cmd) + if err != nil { + return err + } + sdkOpts, err := output.PrepareCallOpts(cmd) + if err != nil { + return err + } + if err := output.ValidateGlobalServerIndex(cmd, len(sdk.ServerList)); err != nil { + return err + } + + created, err := s.Test.Run.CreateSuite(cmd.Context(), *req, sdkOpts...) + if err != nil { + return output.Error(cmd, err) + } + target := suiteTarget{projectID: req.ProjectID, environmentAlias: req.EnvironmentAlias} + if serverURL, changed := flagutil.GetStringFlag(cmd, "server-url"); changed { + target.serverURL = serverURL + } + suite := created.GetStableTestRunSuiteResponse() + if suite == nil || suite.BulkID == "" { + return suiteError(cmd, "test_suite_wait_failed", "the API started the suite but returned no bulkID to wait for", + []string{fmt.Sprintf("Find the runs it started: vf test run search %s", target.flags())}) + } + target.bulkID = suite.BulkID + runs := "runs" + if len(suite.Runs) == 1 { + runs = "run" + } + resume := target.resume() + reportSuite(cmd, + fmt.Sprintf("Started suite %s with %d %s. Waiting up to %s for it to finish; if stopped early, keep waiting with: %s", + target.bulkID, len(suite.Runs), runs, maxWait, resume), + map[string]any{ + "status": "started", + "bulkID": target.bulkID, + "runs": len(suite.Runs), + "max_wait": maxWait.String(), + "hints": []string{ + "This command blocks until every run has finished, which can take many minutes, so run it in the background and read its output", + "If it is stopped early, keep waiting with: " + resume, + }, + }) + + waited, err := waitForSuite(cmd, target, sdkOpts, maxWait, opts.requestTimeout) + if err != nil { + return err + } + if err := output.Result(cmd, waited); err != nil { + if err.Error() == "" { + return err + } + return suiteError(cmd, "test_suite_output_failed", + fmt.Sprintf("suite %s stopped being waited on, but its results could not be printed: %v", target.bulkID, err), + []string{"Print them again with: " + resume}) + } + return suiteOutcome(cmd, target, waited.GetStableTestRunSuiteWaitResponse(), maxWait) +} + +type suiteTarget struct { + projectID string + environmentAlias string + bulkID string + serverURL string +} + +// flags are the flags a follow-up command needs to reach the same suite, +// quoted for a shell. +func (t suiteTarget) flags() string { + flags := fmt.Sprintf("--project-id %s --environment-alias %s", shellQuote(t.projectID), shellQuote(t.environmentAlias)) + if t.serverURL != "" { + flags += " --server-url " + shellQuote(t.serverURL) + } + return flags +} + +// resume is the command that keeps waiting on the suite. +func (t suiteTarget) resume() string { + return fmt.Sprintf("vf test run wait-suite %s --bulk-id %s", t.flags(), shellQuote(t.bulkID)) +} + +func shellQuote(value string) string { + if value != "" && strings.Trim(value, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.,:/@%+=") == "" { + return value + } + return "'" + strings.ReplaceAll(value, "'", `'\''`) + "'" +} + +// waitForSuite waits until the suite is done or maxWait has passed, and +// returns the last wait's response. Transient failures are retried, so one +// dropped request does not end a long wait, but a retry never waits past +// maxWait once there is a response to report. +// +// The client is rebuilt for every wait because that is when it resolves +// credentials: an OAuth access token that expires during a long suite is +// refreshed, as it is for any vf command, while a --token or VF_TOKEN still +// wins. +func waitForSuite( + cmd *cobra.Command, + target suiteTarget, + sdkOpts []operations.Option, + maxWait time.Duration, + requestTimeout time.Duration, +) (*operations.StableTestRunControllerWaitSuiteResponse, error) { + ctx := cmd.Context() + deadline := time.Now().Add(maxWait) + var last *operations.StableTestRunControllerWaitSuiteResponse + lastProgress := "" + failures := 0 + + for { + s, err := client.NewClient(cmd) + if err != nil { + return nil, suiteWaitFailed(cmd, target, err) + } + seconds := suiteWaitSeconds(time.Until(deadline), requestTimeout) + started := time.Now() + res, err := waitOnce(ctx, s, operations.StableTestRunControllerWaitSuiteRequest{ + ProjectID: target.projectID, + EnvironmentAlias: target.environmentAlias, + Body: components.StableTestRunSuiteWaitRequest{BulkID: target.bulkID, TimeoutSeconds: &seconds}, + }, sdkOpts) + if err != nil { + if ctx.Err() == nil && isTransientWaitError(err) && failures < suiteWaitRetries && time.Until(deadline) > 0 { + failures++ + delay := min(suiteWaitRetryDelay, time.Until(deadline)) + reason, _, _ := strings.Cut(err.Error(), "\n") + reportSuite(cmd, + fmt.Sprintf("Waiting for suite %s failed (%s). Retrying in %s.", target.bulkID, reason, delay.Round(time.Second)), + map[string]any{"status": "retrying", "bulkID": target.bulkID, "error": reason, "retry_in": delay.Round(time.Second).String()}) + if err := sleepContext(ctx, delay); err != nil { + return nil, suiteWaitFailed(cmd, target, err) + } + if time.Until(deadline) <= 0 && last != nil { + return last, nil + } + continue + } + if ctx.Err() != nil { + return nil, suiteWaitFailed(cmd, target, ctx.Err()) + } + if !isTransientWaitError(err) { + return nil, suiteAPIFailed(cmd, target, err) + } + // Out of time, the last answer is still the suite's state to report. + if time.Until(deadline) <= 0 && last != nil { + return last, nil + } + // Not output.Error, whose hint for these is to rerun the command, + // which would start another suite. + return nil, suiteWaitFailed(cmd, target, err) + } + failures = 0 + + // A body that decodes to nothing (null, {}) would otherwise read as + // "not done" and be polled until --max-wait. + result := res.GetStableTestRunSuiteWaitResponse() + if result == nil || result.BulkID == "" { + return nil, suiteWaitFailed(cmd, target, errors.New("the API returned no result")) + } + last = res + if result.Done || time.Until(deadline) <= 0 { + return res, nil + } + if progress := suiteProgress(result.Counts); progress != lastProgress { + lastProgress = progress + reportSuite(cmd, fmt.Sprintf("Suite %s: %s.", target.bulkID, progress), + map[string]any{"status": "waiting", "bulkID": target.bulkID, "counts": result.Counts}) + } + if pause := min(suiteWaitMinInterval-time.Since(started), time.Until(deadline)); pause > 0 { + if err := sleepContext(ctx, pause); err != nil { + return nil, suiteWaitFailed(cmd, target, err) + } + } + if time.Until(deadline) <= 0 { + return res, nil + } + } +} + +// waitOnce makes one wait request, abandoned if the API has not answered well +// after the time it was asked to hold. The deadline is set on the context +// because WithOperationTimeout refuses every operation that does not support +// retries, WaitSuite included. +func waitOnce( + ctx context.Context, + s *sdk.VoiceflowSDK, + req operations.StableTestRunControllerWaitSuiteRequest, + sdkOpts []operations.Option, +) (*operations.StableTestRunControllerWaitSuiteResponse, error) { + ctx, cancel := context.WithTimeout(ctx, time.Duration(*req.Body.TimeoutSeconds)*time.Second+suiteWaitRequestSlack) + defer cancel() + return s.Test.Run.WaitSuite(ctx, req, sdkOpts...) +} + +// globalRequestTimeout is the --timeout every request is held to, resolved +// the way the client resolves it, or zero when there is none. +func globalRequestTimeout(cmd *cobra.Command) (time.Duration, error) { + value, changed := flagutil.GetStringFlag(cmd, "timeout") + if !changed || value == "" { + value = config.GetString("timeout") + } + if value == "" { + return 0, nil + } + timeout, err := time.ParseDuration(value) + if err != nil { + return 0, fmt.Errorf("invalid --timeout value %q: %w", value, err) + } + return timeout, nil +} + +// suiteWaitSeconds is how long one wait asks the API to hold: 45 seconds, or +// less when --max-wait is nearly used up or --timeout would cut the request +// off first, but never under the 5 seconds the API needs at least. +func suiteWaitSeconds(remaining, requestTimeout time.Duration) int64 { + seconds := min(int64(suiteWaitCallSeconds), int64(math.Ceil(remaining.Seconds()))) + if requestTimeout > 0 { + seconds = min(seconds, int64((requestTimeout - suiteWaitTimeoutHeadroom).Seconds())) + } + return max(suiteWaitMinCallSeconds, seconds) +} + +// isTransientWaitError reports whether a failed wait is worth repeating: a +// rate limit, a server error, or a request that never got an answer. +func isTransientWaitError(err error) bool { + var apiErr *sdkerrors.SDKDefaultError + if errors.As(err, &apiErr) { + return apiErr.StatusCode == 429 || apiErr.StatusCode >= 500 + } + var urlErr *url.Error + var netErr net.Error + return errors.As(err, &urlErr) || errors.As(err, &netErr) || + errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, context.DeadlineExceeded) +} + +func suiteProgress(counts components.StableTestRunSuiteCounts) string { + parts := []string{fmt.Sprintf("%d of %d passed", counts.Passed, counts.Total)} + if counts.Failed > 0 { + parts = append(parts, fmt.Sprintf("%d failed", counts.Failed)) + } + if counts.Canceled > 0 { + parts = append(parts, fmt.Sprintf("%d canceled", counts.Canceled)) + } + return strings.Join(append(parts, fmt.Sprintf("%d still going", counts.Unfinished)), ", ") +} + +// suiteOutcome turns the final wait into the exit status: nil only when every +// run passed. +func suiteOutcome( + cmd *cobra.Command, + target suiteTarget, + result *components.StableTestRunSuiteWaitResponse, + maxWait time.Duration, +) error { + counts := result.Counts + if !result.Done { + return suiteError(cmd, "test_suite_unfinished", + fmt.Sprintf("%d of %d runs in suite %s were still going after %s", counts.Unfinished, counts.Total, target.bulkID, maxWait), + []string{ + "Keep waiting: " + target.resume(), + fmt.Sprintf("Stop them: vf test run cancel %s --run-ids (the runs still going are listed in the output)", target.flags()), + }) + } + if notPassed := counts.Failed + counts.Canceled; notPassed > 0 { + return suiteError(cmd, "test_suite_failed", + fmt.Sprintf("%d of %d runs in suite %s did not pass (%d failed, %d canceled)", + notPassed, counts.Total, target.bulkID, counts.Failed, counts.Canceled), + []string{fmt.Sprintf("Read a run's logs: vf test run get %s --run-id ", target.flags())}) + } + return nil +} + +// reportSuite writes a progress update to stderr: prose for a person, and in +// agent mode a JSON event, the way 'vf auth login' reports progress, so every +// byte an agent reads from stderr parses. +func reportSuite(cmd *cobra.Command, prose string, event map[string]any) { + out := cmd.ErrOrStderr() + if !output.IsAgentMode() { + fmt.Fprintln(out, prose) + return + } + data, err := json.MarshalIndent(event, "", " ") + if err != nil { + fmt.Fprintln(out, prose) + return + } + fmt.Fprintln(out, string(data)) +} + +// suiteWaitFailed reports a wait that stopped after the suite had started, +// with the command that picks it up again. +func suiteWaitFailed(cmd *cobra.Command, target suiteTarget, err error) error { + return suiteError(cmd, "test_suite_wait_failed", + fmt.Sprintf("stopped waiting for suite %s: %v", target.bulkID, err), + []string{"The suite keeps running; keep waiting with: " + target.resume()}) +} + +// suiteAPIFailed reports an API error that ended the wait the way any command +// reports one, keeping its error_type, status_code and hints, and adds the +// command that picks the suite up again once the error is dealt with. +func suiteAPIFailed(cmd *cobra.Command, target suiteTarget, err error) error { + resume := "The suite keeps running; once that is fixed, keep waiting with: " + target.resume() + stderr := cmd.ErrOrStderr() + if !output.IsAgentMode() { + reported := output.Error(cmd, err) + if reported.Error() == "" { + fmt.Fprintln(stderr, resume) + return reported + } + return errors.New(reported.Error() + "\n " + resume) + } + + var envelope bytes.Buffer + cmd.SetErr(&envelope) + reported := output.Error(cmd, err) + cmd.SetErr(stderr) + var fields map[string]any + if json.Unmarshal(envelope.Bytes(), &fields) != nil { + _, _ = stderr.Write(envelope.Bytes()) + return reported + } + hints, _ := fields["hints"].([]any) + fields["hints"] = append(hints, resume) + fields["bulkID"] = target.bulkID + data, _ := json.MarshalIndent(fields, "", " ") + fmt.Fprintln(stderr, string(data)) + return reported +} + +// suiteError reports a failure of --wait or of a suite. In agent mode that is +// the structured envelope every other failure uses; otherwise a message and +// hints on stderr. +func suiteError(cmd *cobra.Command, errorType, message string, hints []string) error { + if output.IsAgentMode() { + return output.AgentModeError(cmd, errorType, message, hints) + } + if len(hints) == 0 { + return errors.New(message) + } + return errors.New(message + "\n " + strings.Join(hints, "\n ")) +} + +func sleepContext(ctx context.Context, duration time.Duration) error { + timer := time.NewTimer(duration) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return nil + } +} diff --git a/internal/cli/test/run/createsuite_wait_test.go b/internal/cli/test/run/createsuite_wait_test.go new file mode 100644 index 00000000..a9887941 --- /dev/null +++ b/internal/cli/test/run/createsuite_wait_test.go @@ -0,0 +1,103 @@ +package run + +import ( + "context" + "errors" + "fmt" + "io" + "net/url" + "slices" + "testing" + "time" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/sdkerrors" +) + +func TestSplitIDsAcceptsCommasAndRepeatedFlags(t *testing.T) { + got := splitIDs([]string{"a,b", " c ", "d,,", ""}) + if want := []string{"a", "b", "c", "d"}; !slices.Equal(got, want) { + t.Fatalf("splitIDs = %q, want %q", got, want) + } +} + +func TestShellQuoteKeepsHintsPasteable(t *testing.T) { + cases := map[string]string{ + "6b05d5a960fbff504456c9d0": "6b05d5a960fbff504456c9d0", + "https://api.voiceflow.com": "https://api.voiceflow.com", + "http://host/my api": "'http://host/my api'", + "it's": `'it'\''s'`, + "$(rm -rf /)": "'$(rm -rf /)'", + "": "''", + } + for value, want := range cases { + if got := shellQuote(value); got != want { + t.Errorf("shellQuote(%q) = %s, want %s", value, got, want) + } + } +} + +func TestSuiteWaitSecondsStaysWithinWhatTheAPIAccepts(t *testing.T) { + cases := map[time.Duration]int64{ + 30 * time.Minute: 45, + 20 * time.Second: 20, + 1500 * time.Millisecond: 5, + 0: 5, + -time.Minute: 5, + } + for remaining, want := range cases { + if got := suiteWaitSeconds(remaining, 0); got != want { + t.Errorf("suiteWaitSeconds(%s) = %d, want %d", remaining, got, want) + } + } +} + +func TestSuiteWaitSecondsFitsInsideTheRequestTimeout(t *testing.T) { + cases := map[time.Duration]int64{ + 2 * time.Minute: 45, + 30 * time.Second: 25, + 3 * time.Second: 5, + } + for timeout, want := range cases { + if got := suiteWaitSeconds(30*time.Minute, timeout); got != want { + t.Errorf("suiteWaitSeconds with --timeout %s = %d, want %d", timeout, got, want) + } + } +} + +func TestOnlyTransientWaitErrorsAreRetried(t *testing.T) { + apiError := func(status int) error { + return fmt.Errorf("wait: %w", sdkerrors.NewSDKDefaultError("API error occurred", status, "{}", nil)) + } + cases := []struct { + name string + err error + want bool + }{ + {"server error", apiError(502), true}, + {"rate limited", apiError(429), true}, + {"no answer", &url.Error{Op: "Post", URL: "https://api", Err: errors.New("connection reset")}, true}, + {"request timed out", context.DeadlineExceeded, true}, + {"answer cut off", fmt.Errorf("error reading response body: %w", io.ErrUnexpectedEOF), true}, + {"suite not found", apiError(404), false}, + {"invalid request", apiError(422), false}, + {"anything else", errors.New("boom"), false}, + } + for _, c := range cases { + if got := isTransientWaitError(c.err); got != c.want { + t.Errorf("%s: isTransientWaitError = %t, want %t", c.name, got, c.want) + } + } +} + +func TestSuiteProgressNamesOnlyWhatHappened(t *testing.T) { + cases := map[string]components.StableTestRunSuiteCounts{ + "1 of 4 passed, 3 still going": {Total: 4, Passed: 1, Unfinished: 3}, + "1 of 4 passed, 1 failed, 1 canceled, 1 still going": {Total: 4, Passed: 1, Failed: 1, Canceled: 1, Unfinished: 1}, + } + for want, counts := range cases { + if got := suiteProgress(counts); got != want { + t.Errorf("suiteProgress = %q, want %q", got, want) + } + } +} diff --git a/internal/sdk/sdkinternal/hooks/teach.go b/internal/sdk/sdkinternal/hooks/teach.go index 26170cf5..374fa3ec 100644 --- a/internal/sdk/sdkinternal/hooks/teach.go +++ b/internal/sdk/sdkinternal/hooks/teach.go @@ -33,9 +33,11 @@ const ( tokenEnvVar = "VF_TOKEN" ) -type teachHook struct { - warnOnce sync.Once -} +// Once per process rather than per hook: a command that makes many requests +// builds a new client, and so a new hook, for each of them. +var tokenWarnOnce sync.Once + +type teachHook struct{} var _ beforeRequestHook = (*teachHook)(nil) var _ afterErrorHook = (*teachHook)(nil) @@ -85,11 +87,11 @@ func (h *teachHook) BeforeRequest(_ BeforeRequestContext, req *http.Request) (*h token := strings.TrimPrefix(authorization, "Bearer ") switch { case strings.HasPrefix(credential, "VF.DM."): - h.warnOnce.Do(func() { + tokenWarnOnce.Do(func() { fmt.Fprintf(os.Stderr, "Warning: the configured token looks like a legacy Dialog Manager API key (VF.DM....). The CLI needs a personal access token (vfp_...) — create one under Settings → Access tokens: %s\n", authDocsURL) }) case strings.TrimSpace(token) != token: - h.warnOnce.Do(func() { + tokenWarnOnce.Do(func() { fmt.Fprintln(os.Stderr, "Warning: the configured token has leading or trailing whitespace — the API will likely reject it.") }) } diff --git a/internal/usage/extra_flags.go b/internal/usage/extra_flags.go new file mode 100644 index 00000000..9b78a883 --- /dev/null +++ b/internal/usage/extra_flags.go @@ -0,0 +1,84 @@ +// This file is not generated by Speakeasy — it lets flags added in hand-written +// code appear in --usage. The schemas in schema.go are rendered from the API +// spec, so a flag such as create-suite's --wait is otherwise missing from them. + +package usage + +import ( + "fmt" + "regexp" + "strings" +) + +var ( + usageCmdLine = regexp.MustCompile(`^(\s*)cmd "([^"]+)".*\{$`) + usageCloseLine = regexp.MustCompile(`^(\s*)\}$`) +) + +// UsageFlag is a flag line for a --usage schema. +type UsageFlag struct { + // Name and placeholder as the schema shows them, e.g. "--max-wait ". + Spec string + Help string +} + +// AddFlags adds flags to the schema of the command at path (e.g. +// "test run create-suite") and to every parent schema that nests it, so +// 'vf --usage' shows them as well as 'vf test run create-suite --usage'. +// Adding a flag the schema already has does nothing. +func AddFlags(path string, flags ...UsageFlag) { + parts := strings.Fields(path) + for key, schema := range usageSchemas { + keyParts := strings.Fields(key) + if len(keyParts) > len(parts) || strings.Join(parts[:len(keyParts)], " ") != key { + continue + } + // A command's own schema starts with its own cmd line; the root's + // starts with its children's. + nested := parts + if len(keyParts) > 0 { + nested = parts[len(keyParts)-1:] + } + usageSchemas[key] = addFlagsToSchema(schema, nested, flags) + } +} + +func addFlagsToSchema(schema string, path []string, flags []UsageFlag) string { + lines := strings.Split(schema, "\n") + out := make([]string, 0, len(lines)+len(flags)) + var stack []usageCmd + for _, line := range lines { + if m := usageCmdLine.FindStringSubmatch(line); m != nil { + stack = append(stack, usageCmd{indent: m[1], name: m[2]}) + } else if m := usageCloseLine.FindStringSubmatch(line); m != nil && len(stack) > 0 && stack[len(stack)-1].indent == m[1] { + if stackMatches(stack, path) { + for _, flag := range flags { + flagLine := fmt.Sprintf("%s flag %q help=%q", m[1], flag.Spec, flag.Help) + if !strings.Contains(schema, flagLine) { + out = append(out, flagLine) + } + } + } + stack = stack[:len(stack)-1] + } + out = append(out, line) + } + return strings.Join(out, "\n") +} + +type usageCmd struct { + indent string + name string +} + +func stackMatches(stack []usageCmd, path []string) bool { + if len(stack) != len(path) { + return false + } + for i, entry := range stack { + if entry.name != path[i] { + return false + } + } + return true +} diff --git a/test/run-suite-wait.test.ts b/test/run-suite-wait.test.ts new file mode 100644 index 00000000..f6ee997c --- /dev/null +++ b/test/run-suite-wait.test.ts @@ -0,0 +1,415 @@ +// Tests for 'vf test run create-suite --wait' (internal/cli/test/run/ +// createsuite_wait.go): one command starts a suite, waits until every run has +// finished, and exits non-zero unless every run passed. Uses a local mock API. +// +// The command is hooked in by one line in the generated createsuite.go, so +// these tests are what notice a regeneration that drops it. +// +// Requires: go build -o vf ./cmd/vf + +import { execa } from 'execa'; +import * as http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import * as path from 'node:path'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +const VF = path.resolve(__dirname, '..', 'vf'); + +// Mirrors the list in internal/output/agentmode.go, so a stray one on the host +// does not flip the renderer. +const AGENT_ENV_VARS = [ + 'CLAUDECODE', 'CLAUDE_CODE', 'CURSOR_AGENT', 'CODEX', 'AIDER', 'CLINE', + 'WINDSURF_AGENT', 'GITHUB_COPILOT', 'AMAZON_Q', 'GEMINI_CODE_ASSIST', + 'SRC_CODY', 'FORCE_AGENT_MODE', +]; + +const BULK_ID = 'bulk-1'; +const SUITE_FLAGS = ['test', 'run', 'create-suite', '--project-id', 'p1', '--environment-alias', 'main']; + +type Counts = { total: number; passed: number; failed: number; canceled: number; unfinished: number }; +type Reply = { status: number; body: object | null; delayMs?: number }; + +// A reply status that makes the mock send headers and half a body, then drop +// the connection. +const TRUNCATE = -1; + +// Parses a stream of JSON values written one after another, failing on any +// text between them. +function jsonStream(text: string): any[] { + const values: any[] = []; + let rest = text.trim(); + while (rest) { + let end = 0; + let depth = 0; + let inString = false; + for (let i = 0; i < rest.length; i += 1) { + const char = rest[i]; + if (inString) { + if (char === '\\') i += 1; + else if (char === '"') inString = false; + } else if (char === '"') inString = true; + else if (char === '{') depth += 1; + else if (char === '}' && --depth === 0) { + end = i + 1; + break; + } + } + expect(end, `stderr is not only JSON:\n${text}`).toBeGreaterThan(0); + values.push(JSON.parse(rest.slice(0, end))); + rest = rest.slice(end).trim(); + } + return values; +} + +const run = (runID: string, status: string) => ({ + runID, + testID: `test-${runID}`, + status, + passedChecks: status === 'failed' ? 0 : null, + totalChecks: 1, + failReason: null, + failedChecks: status === 'failed' ? [{ checkID: 'c1', type: 'llm', reason: 'Did not greet the user' }] : [], +}); + +const waitReply = (counts: Counts, runs: object[] = []): Reply => ({ + status: 200, + body: { + bulkID: BULK_ID, + done: counts.unfinished === 0, + stoppedBy: counts.unfinished === 0 ? 'finished' : 'timeout', + waitedSeconds: 1, + counts, + runs, + }, +}); + +let server: http.Server; +let serverURL: string; +let createReply: object | null; +let waitReplies: Reply[]; +let requests: Array<{ path: string; body: any }>; + +beforeAll(async () => { + server = http.createServer((req, res) => { + let raw = ''; + req.on('data', (chunk) => (raw += chunk)); + req.on('end', () => { + const pathname = new URL(req.url ?? '/', 'http://mock').pathname; + requests.push({ path: pathname, body: raw ? JSON.parse(raw) : undefined }); + + const reply = (status: number, body: object | null) => { + res.writeHead(status, { 'content-type': 'application/json' }); + res.end(JSON.stringify(body)); + }; + if (pathname.endsWith('/test-run/suite')) { + return reply(201, createReply); + } + if (pathname.endsWith('/test-run/suite/wait')) { + const next = waitReplies.length > 1 ? waitReplies.shift()! : waitReplies[0]!; + if (next.status === TRUNCATE) { + res.writeHead(200, { 'content-type': 'application/json', 'content-length': '1000' }); + res.write('{"bulkID":'); + return res.socket?.destroy(); + } + return setTimeout(() => reply(next.status, next.body), next.delayMs ?? 0); + } + return reply(404, { statusCode: 404, message: 'Not found' }); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + serverURL = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); + +afterAll(async () => { + await new Promise((resolve) => server.close(() => resolve())); +}); + +beforeEach(() => { + requests = []; + createReply = { + bulkID: BULK_ID, + runs: [ + { id: 'r1', testID: 'test-r1', status: 'idle' }, + { id: 'r2', testID: 'test-r2', status: 'idle' }, + ], + }; + waitReplies = []; +}); + +function vf(args: string[], opts: { agentMode?: boolean } = {}) { + const env: Record = Object.fromEntries(AGENT_ENV_VARS.map((name) => [name, undefined])); + if (opts.agentMode) env.CLAUDECODE = '1'; + return execa({ reject: false, timeout: 25_000, stdin: 'ignore', env, extendEnv: true })(VF, [ + ...args, + '--token', 'vfp_x', + '--server-url', serverURL, + '--output-format', 'json', + ]); +} + +const waits = () => requests.filter((request) => request.path.endsWith('/suite/wait')); + +// The flags a follow-up command needs to reach the suite, --server-url +// included since vf() passes one. +const target = () => `--project-id p1 --environment-alias main --server-url ${serverURL}`; + +describe('create-suite --wait', () => { + it('waits until every run has finished and exits 0 when they all passed', async () => { + waitReplies = [ + waitReply({ total: 2, passed: 1, failed: 0, canceled: 0, unfinished: 1 }, [run('r2', 'running')]), + waitReply({ total: 2, passed: 2, failed: 0, canceled: 0, unfinished: 0 }), + ]; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait']); + + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ bulkID: BULK_ID, done: true, counts: { passed: 2 } }); + expect(result.stderr).toContain(`Started suite ${BULK_ID} with 2 runs`); + expect(result.stderr).toContain(`keep waiting with: vf test run wait-suite ${target()} --bulk-id ${BULK_ID}`); + expect(result.stderr).toContain('1 of 2 passed, 1 still going'); + expect(waits()).toHaveLength(2); + expect(waits()[0]!.body).toEqual({ bulkID: BULK_ID, timeoutSeconds: 45 }); + }); + + it('exits 1 when a run failed, after printing the failed checks', async () => { + waitReplies = [waitReply({ total: 2, passed: 1, failed: 1, canceled: 0, unfinished: 0 }, [run('r1', 'failed')])]; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait']); + + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout).runs[0].failedChecks[0].reason).toBe('Did not greet the user'); + expect(result.stderr).toContain(`1 of 2 runs in suite ${BULK_ID} did not pass (1 failed, 0 canceled)`); + expect(result.stderr).toContain(`vf test run get ${target()} --run-id `); + }); + + it('writes nothing but JSON to stderr in agent mode: progress events, then the error envelope', async () => { + waitReplies = [ + waitReply({ total: 2, passed: 1, failed: 0, canceled: 0, unfinished: 1 }, [run('r2', 'running')]), + waitReply({ total: 2, passed: 1, failed: 0, canceled: 1, unfinished: 0 }, [run('r2', 'canceled')]), + ]; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait'], { agentMode: true }); + + expect(result.exitCode).toBe(1); + const events = jsonStream(result.stderr); + expect(events.map((event) => event.status ?? event.error_type)).toEqual(['started', 'waiting', 'test_suite_failed']); + expect(events[0]).toMatchObject({ bulkID: BULK_ID, runs: 2 }); + expect(events[1]).toMatchObject({ counts: { passed: 1, unfinished: 1 } }); + expect(events[2]!.message).toContain('did not pass (0 failed, 1 canceled)'); + }); + + it('exits 1 with the command to keep waiting when --max-wait runs out first', async () => { + waitReplies = [waitReply({ total: 2, passed: 0, failed: 0, canceled: 0, unfinished: 2 }, [run('r1', 'running')])]; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait', '--max-wait', '3s']); + + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ done: false, counts: { unfinished: 2 } }); + expect(result.stderr).toContain(`2 of 2 runs in suite ${BULK_ID} were still going after 3s`); + expect(result.stderr).toContain(`vf test run wait-suite ${target()} --bulk-id ${BULK_ID}`); + expect(waits()[0]!.body.timeoutSeconds).toBe(5); + }); + + it('retries a wait that hit a server error', async () => { + waitReplies = [ + { status: 502, body: { statusCode: 502, message: 'Bad gateway' } }, + waitReply({ total: 2, passed: 2, failed: 0, canceled: 0, unfinished: 0 }), + ]; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait']); + + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stderr).toContain('Retrying in 5s'); + expect(waits()).toHaveLength(2); + }); + + it('retries a wait whose answer was cut off mid-body', async () => { + waitReplies = [ + { status: TRUNCATE, body: {} }, + waitReply({ total: 2, passed: 2, failed: 0, canceled: 0, unfinished: 0 }), + ]; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait']); + + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stderr).toContain('Retrying in 5s'); + expect(waits()).toHaveLength(2); + }); + + it('refuses a --timeout no wait fits in, before starting the suite', async () => { + const result = await vf([...SUITE_FLAGS, '--all', '--wait', '--timeout', '3s']); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('--wait needs a --timeout of at least 10s'); + expect(requests).toHaveLength(0); + }); + + it('refuses --max-wait without --wait', async () => { + const result = await vf([...SUITE_FLAGS, '--all', '--max-wait', '5m']); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('--max-wait only applies with --wait'); + expect(requests).toHaveLength(0); + }); + + it('stops with the agent-mode envelope on a wait answer that decodes to nothing, instead of polling it', async () => { + for (const body of [null, {}]) { + requests = []; + waitReplies = [{ status: 200, body }]; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait'], { agentMode: true }); + + expect(result.exitCode).toBe(1); + expect(waits()).toHaveLength(1); + const events = jsonStream(result.stderr); + expect(events.map((event) => event.status ?? event.error_type)).toEqual(['started', 'test_suite_wait_failed']); + expect(events[1]!.message).toContain(`stopped waiting for suite ${BULK_ID}: the API returned no result`); + expect(JSON.stringify(events[1]!.hints)).toContain(`vf test run wait-suite ${target()} --bulk-id ${BULK_ID}`); + } + }); + + it('keeps an API error structured, and says how to keep waiting rather than rerun, when a wait fails', async () => { + for (const [status, errorType] of [ + [401, 'authentication_error'], + [404, 'not_found'], + ] as const) { + requests = []; + waitReplies = [{ status, body: { statusCode: status, message: 'Nope' } }]; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait'], { agentMode: true }); + + expect(result.exitCode).toBe(1); + expect(waits()).toHaveLength(1); + const events = jsonStream(result.stderr); + expect(events.map((event) => event.status ?? event.error_type)).toEqual(['started', errorType]); + expect(events[1]).toMatchObject({ status_code: status, bulkID: BULK_ID }); + expect(events[1]!.hints.at(-1)).toContain(`keep waiting with: vf test run wait-suite ${target()} --bulk-id ${BULK_ID}`); + expect(JSON.stringify(events[1]!.hints)).not.toContain('retry the command'); + } + }); + + it('says how to keep waiting after an API error outside agent mode too', async () => { + waitReplies = [{ status: 404, body: { statusCode: 404, message: 'Nope' } }]; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait']); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('404'); + expect(result.stderr).toContain(`keep waiting with: vf test run wait-suite ${target()} --bulk-id ${BULK_ID}`); + }); + + it('says how to keep waiting, not to rerun, when a server error outlasts the retries', async () => { + waitReplies = [{ status: 503, body: { statusCode: 503, message: 'Unavailable' } }]; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait'], { agentMode: true }); + + expect(result.exitCode).toBe(1); + expect(waits()).toHaveLength(4); + const events = jsonStream(result.stderr); + expect(events.map((event) => event.status ?? event.error_type)).toEqual([ + 'started', 'retrying', 'retrying', 'retrying', 'test_suite_wait_failed', + ]); + expect(JSON.stringify(events.at(-1)!.hints)).toContain(`vf test run wait-suite ${target()} --bulk-id ${BULK_ID}`); + expect(JSON.stringify(events.at(-1)!.hints)).not.toContain('retry the command'); + }, 30_000); + + it('reports the last answer as unfinished when a wait fails after --max-wait ran out', async () => { + waitReplies = [ + waitReply({ total: 2, passed: 0, failed: 0, canceled: 0, unfinished: 2 }, [run('r1', 'running')]), + { status: 502, body: { statusCode: 502, message: 'Bad gateway' }, delayMs: 3500 }, + ]; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait', '--max-wait', '4s']); + + expect(result.exitCode).toBe(1); + expect(waits()).toHaveLength(2); + expect(result.stderr).not.toContain('Retrying'); + expect(JSON.parse(result.stdout)).toMatchObject({ done: false, counts: { unfinished: 2 } }); + expect(result.stderr).toContain(`were still going after 4s`); + }); + + it('does not wait on a started suite whose answer has no bulkID', async () => { + createReply = { runs: [] }; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait'], { agentMode: true }); + + expect(result.exitCode).toBe(1); + expect(waits()).toHaveLength(0); + const events = jsonStream(result.stderr); + expect(events.map((event) => event.error_type)).toEqual(['test_suite_wait_failed']); + expect(JSON.stringify(events[0]!.hints)).toContain(`vf test run search ${target()}`); + }); + + it('refuses a --jq that cannot run before starting the suite, not after the wait', async () => { + for (const jq of ['.counts |||', '.counts | no_such_function']) { + const result = await vf([...SUITE_FLAGS, '--all', '--wait', '--jq', jq]); + + expect(result.exitCode, jq).toBe(1); + expect(result.stderr).toContain('invalid --jq expression'); + } + expect(requests).toHaveLength(0); + }); + + it('checks the --wait flags under --dry-run too', async () => { + const result = await vf([...SUITE_FLAGS, '--all', '--wait', '--max-wait', '0s', '--dry-run']); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('--max-wait must be more than zero'); + expect(requests).toHaveLength(0); + }); + + it('keeps stderr JSON in agent mode when --wait --dry-run fails before sending', async () => { + const result = await vf([...SUITE_FLAGS, '--wait', '--dry-run', '--body', '{bad'], { agentMode: true }); + + expect(result.exitCode).toBe(1); + expect(jsonStream(result.stderr)).toHaveLength(1); + expect(requests).toHaveLength(0); + }); + + it('lists --wait and --max-wait in --usage, for create-suite and every command above it', async () => { + for (const args of [[...SUITE_FLAGS, '--usage'], ['test', 'run', '--usage'], ['--usage']]) { + const result = await vf(args); + + expect(result.exitCode, result.stderr).toBe(0); + const block = result.stdout.slice(result.stdout.indexOf('cmd "create-suite"')); + const createSuite = block.slice(0, block.search(/\n\s*\}\n/)); + expect(createSuite, args.join(' ')).toContain('flag "--wait"'); + expect(createSuite, args.join(' ')).toContain('flag "--max-wait "'); + expect(result.stdout.match(/flag "--wait"/g), args.join(' ')).toHaveLength(1); + } + }); + + it('reports invalid flag values with the agent-mode envelope', async () => { + for (const flags of [ + ['--max-wait', '5m'], + ['--wait', '--max-wait', '0s'], + ['--wait', '--timeout', '3s'], + ['--wait', '--timeout', 'abc'], + ['--wait', '--jq', '.counts |||'], + ]) { + const result = await vf([...SUITE_FLAGS, '--all', ...flags], { agentMode: true }); + + expect(result.exitCode, flags.join(' ')).toBe(1); + const events = jsonStream(result.stderr); + expect(events, flags.join(' ')).toHaveLength(1); + expect(events[0]!.error_type).toBe('invalid_flag_value'); + } + expect(requests).toHaveLength(0); + }); +}); + +describe('create-suite IDs', () => { + it('accepts comma-separated and repeated --test-ids, with or without --wait', async () => { + await vf([...SUITE_FLAGS, '--test-ids', 'a,b', '--test-ids', ' c ']); + + expect(requests[0]!.body).toEqual({ testIDs: ['a', 'b', 'c'] }); + }); + + it('accepts comma-separated --folder-ids', async () => { + waitReplies = [waitReply({ total: 2, passed: 2, failed: 0, canceled: 0, unfinished: 0 })]; + + await vf([...SUITE_FLAGS, '--folder-ids', 'f1,f2', '--wait']); + + expect(requests[0]!.body).toEqual({ folderIDs: ['f1', 'f2'] }); + }); +});