From 5e1b79e267a704f79fc37f4ce791198d2a6a0a34 Mon Sep 17 00:00:00 2001 From: Sanasar Date: Wed, 25 Nov 2026 12:54:51 -0500 Subject: [PATCH 1/5] feat(test): run a test suite and wait for it in one command (COR-15957) Co-authored-by: Cursor --- internal/cli/test/run/createsuite.go | 1 + internal/cli/test/run/createsuite_wait.go | 380 ++++++++++++++++++ .../cli/test/run/createsuite_wait_test.go | 85 ++++ test/run-suite-wait.test.ts | 202 ++++++++++ 4 files changed, 668 insertions(+) create mode 100644 internal/cli/test/run/createsuite_wait.go create mode 100644 internal/cli/test/run/createsuite_wait_test.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..91508ea5 --- /dev/null +++ b/internal/cli/test/run/createsuite_wait.go @@ -0,0 +1,380 @@ +// 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 ( + "context" + "errors" + "fmt" + "math" + "net/url" + "strings" + "time" + + "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." + } + } + + 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 err := splitSuiteIDFlags(cmd); err != nil { + return err + } + wait, _ := flagutil.GetBoolFlag(cmd, suiteWaitFlag) + if cmd.Flags().Changed(suiteMaxWaitFlag) && !wait { + return fmt.Errorf("--%s only applies with --%s", suiteMaxWaitFlag, suiteWaitFlag) + } + if !wait || usage.UsageRequested(cmd) || client.IsDryRun(cmd) { + return runCreateSuite(cmd, args) + } + return runCreateSuiteAndWait(cmd) + } +} + +// 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 +} + +// runCreateSuiteAndWait starts the suite the way runCreateSuiteCmd does, then +// waits for it and reports the outcome. +func runCreateSuiteAndWait(cmd *cobra.Command) error { + maxWait, err := cmd.Flags().GetDuration(suiteMaxWaitFlag) + if err != nil { + return err + } + if maxWait <= 0 { + return fmt.Errorf("--%s must be more than zero, got %s", suiteMaxWaitFlag, maxWait) + } + if interactive.ShouldPrompt(cmd, createSuiteCmdMeta) { + if err := interactive.PromptAndSetFlags(cmd, createSuiteCmdMeta); err != nil { + return err + } + } + 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) + } + suite := created.GetStableTestRunSuiteResponse() + if suite == nil { + return errors.New("the API started the suite but returned no bulkID to wait for") + } + + target := suiteTarget{projectID: req.ProjectID, environmentAlias: req.EnvironmentAlias, bulkID: suite.BulkID} + runs := "runs" + if len(suite.Runs) == 1 { + runs = "run" + } + fmt.Fprintf(cmd.ErrOrStderr(), "Started suite %s with %d %s. Waiting up to %s for it to finish.\n", + target.bulkID, len(suite.Runs), runs, maxWait) + + waited, err := waitForSuite(cmd, s, target, sdkOpts, maxWait) + if err != nil { + return err + } + if err := output.Result(cmd, waited); err != nil { + return err + } + return suiteOutcome(cmd, target, waited.GetStableTestRunSuiteWaitResponse(), maxWait) +} + +type suiteTarget struct { + projectID string + environmentAlias string + bulkID string +} + +func (t suiteTarget) flags() string { + return fmt.Sprintf("--project-id %s --environment-alias %s", t.projectID, t.environmentAlias) +} + +// 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. +func waitForSuite( + cmd *cobra.Command, + s *sdk.VoiceflowSDK, + target suiteTarget, + sdkOpts []operations.Option, + maxWait time.Duration, +) (*operations.StableTestRunControllerWaitSuiteResponse, error) { + ctx := cmd.Context() + deadline := time.Now().Add(maxWait) + lastProgress := "" + failures := 0 + + requestTimeout, err := globalRequestTimeout(cmd) + if err != nil { + return nil, err + } + + for { + 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++ + fmt.Fprintf(cmd.ErrOrStderr(), "Waiting for suite %s failed (%v). Retrying in %s.\n", + target.bulkID, err, suiteWaitRetryDelay) + if err := sleepContext(ctx, suiteWaitRetryDelay); err != nil { + return nil, err + } + continue + } + return nil, output.Error(cmd, err) + } + failures = 0 + + result := res.GetStableTestRunSuiteWaitResponse() + if result == nil { + return nil, fmt.Errorf("the API returned no result while waiting for suite %s", target.bulkID) + } + if result.Done || time.Until(deadline) <= 0 { + return res, nil + } + if progress := suiteProgress(result.Counts); progress != lastProgress { + lastProgress = progress + fmt.Fprintf(cmd.ErrOrStderr(), "Suite %s: %s.\n", target.bulkID, progress) + } + if pause := min(suiteWaitMinInterval-time.Since(started), time.Until(deadline)); pause > 0 { + if err := sleepContext(ctx, pause); err != nil { + return nil, 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 + return errors.As(err, &urlErr) || 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{ + fmt.Sprintf("Keep waiting: vf test run wait-suite %s --bulk-id %s", target.flags(), target.bulkID), + 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 +} + +// suiteError reports a suite that did not pass. 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) + } + 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..27dfe138 --- /dev/null +++ b/internal/cli/test/run/createsuite_wait_test.go @@ -0,0 +1,85 @@ +package run + +import ( + "context" + "errors" + "fmt" + "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 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}, + {"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/test/run-suite-wait.test.ts b/test/run-suite-wait.test.ts new file mode 100644 index 00000000..9da888e7 --- /dev/null +++ b/test/run-suite-wait.test.ts @@ -0,0 +1,202 @@ +// 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 }; + +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 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) => { + res.writeHead(status, { 'content-type': 'application/json' }); + res.end(JSON.stringify(body)); + }; + if (pathname.endsWith('/test-run/suite')) { + return reply(201, { + bulkID: BULK_ID, + runs: [ + { id: 'r1', testID: 'test-r1', status: 'idle' }, + { id: 'r2', testID: 'test-r2', status: 'idle' }, + ], + }); + } + if (pathname.endsWith('/test-run/suite/wait')) { + const next = waitReplies.length > 1 ? waitReplies.shift()! : waitReplies[0]!; + return reply(next.status, next.body); + } + 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 = []; + 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')); + +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('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 --project-id p1 --environment-alias main --run-id '); + }); + + it('reports a failed suite with the agent-mode envelope', async () => { + waitReplies = [waitReply({ total: 2, passed: 1, failed: 0, canceled: 1, unfinished: 0 }, [run('r1', 'canceled')])]; + + const result = await vf([...SUITE_FLAGS, '--all', '--wait'], { agentMode: true }); + + expect(result.exitCode).toBe(1); + const envelope = JSON.parse(result.stderr.slice(result.stderr.indexOf('{'))); + expect(envelope.error_type).toBe('test_suite_failed'); + expect(envelope.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 --project-id p1 --environment-alias main --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('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); + }); +}); + +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'] }); + }); +}); From cbff7d1d01881704a0114bf8c5f6d4c1e2f85d8a Mon Sep 17 00:00:00 2001 From: Sanasar Date: Wed, 25 Nov 2026 13:06:07 -0500 Subject: [PATCH 2/5] fix(test): split prompted suite IDs, refuse a too-short --timeout, and keep retries within --max-wait (COR-15957) Co-authored-by: Cursor --- internal/cli/test/run/createsuite_wait.go | 50 +++++++++++++++-------- test/run-suite-wait.test.ts | 8 ++++ 2 files changed, 42 insertions(+), 16 deletions(-) diff --git a/internal/cli/test/run/createsuite_wait.go b/internal/cli/test/run/createsuite_wait.go index 91508ea5..f03d572e 100644 --- a/internal/cli/test/run/createsuite_wait.go +++ b/internal/cli/test/run/createsuite_wait.go @@ -91,14 +91,24 @@ canceled, or when --max-wait (30 minutes by default) ran out first.` runCreateSuite := cmd.RunE cmd.RunE = func(cmd *cobra.Command, args []string) error { - if err := splitSuiteIDFlags(cmd); err != nil { - return err + if usage.UsageRequested(cmd) { + return runCreateSuite(cmd, args) } wait, _ := flagutil.GetBoolFlag(cmd, suiteWaitFlag) if cmd.Flags().Changed(suiteMaxWaitFlag) && !wait { return fmt.Errorf("--%s only applies with --%s", suiteMaxWaitFlag, suiteWaitFlag) } - if !wait || usage.UsageRequested(cmd) || client.IsDryRun(cmd) { + // 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 err + } + if !wait || client.IsDryRun(cmd) { return runCreateSuite(cmd, args) } return runCreateSuiteAndWait(cmd) @@ -145,10 +155,15 @@ func runCreateSuiteAndWait(cmd *cobra.Command) error { if maxWait <= 0 { return fmt.Errorf("--%s must be more than zero, got %s", suiteMaxWaitFlag, maxWait) } - if interactive.ShouldPrompt(cmd, createSuiteCmdMeta) { - if err := interactive.PromptAndSetFlags(cmd, createSuiteCmdMeta); err != nil { - return err - } + // Checked before the suite starts, so a --timeout no wait can fit in does + // not leave queued runs behind. + requestTimeout, err := globalRequestTimeout(cmd) + if err != nil { + return err + } + if minTimeout := suiteWaitMinCallSeconds*time.Second + suiteWaitTimeoutHeadroom; requestTimeout > 0 && requestTimeout < minTimeout { + return fmt.Errorf("--%s needs a --timeout of at least %s, since each wait holds the request for %ds or more; got %s", + suiteWaitFlag, minTimeout, suiteWaitMinCallSeconds, requestTimeout) } req, err := flagutil.BuildRequest[operations.StableTestRunControllerCreateSuiteRequest](cmd, createSuiteCmdMeta, "Body", "body") if err != nil { @@ -183,7 +198,7 @@ func runCreateSuiteAndWait(cmd *cobra.Command) error { fmt.Fprintf(cmd.ErrOrStderr(), "Started suite %s with %d %s. Waiting up to %s for it to finish.\n", target.bulkID, len(suite.Runs), runs, maxWait) - waited, err := waitForSuite(cmd, s, target, sdkOpts, maxWait) + waited, err := waitForSuite(cmd, s, target, sdkOpts, maxWait, requestTimeout) if err != nil { return err } @@ -205,24 +220,22 @@ func (t suiteTarget) flags() string { // 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. +// dropped request does not end a long wait, but a retry never waits past +// maxWait once there is a response to report. func waitForSuite( cmd *cobra.Command, s *sdk.VoiceflowSDK, 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 - requestTimeout, err := globalRequestTimeout(cmd) - if err != nil { - return nil, err - } - for { seconds := suiteWaitSeconds(time.Until(deadline), requestTimeout) started := time.Now() @@ -234,11 +247,15 @@ func waitForSuite( if err != nil { if ctx.Err() == nil && isTransientWaitError(err) && failures < suiteWaitRetries && time.Until(deadline) > 0 { failures++ + delay := min(suiteWaitRetryDelay, time.Until(deadline)) fmt.Fprintf(cmd.ErrOrStderr(), "Waiting for suite %s failed (%v). Retrying in %s.\n", - target.bulkID, err, suiteWaitRetryDelay) - if err := sleepContext(ctx, suiteWaitRetryDelay); err != nil { + target.bulkID, err, delay.Round(time.Second)) + if err := sleepContext(ctx, delay); err != nil { return nil, err } + if time.Until(deadline) <= 0 && last != nil { + return last, nil + } continue } return nil, output.Error(cmd, err) @@ -249,6 +266,7 @@ func waitForSuite( if result == nil { return nil, fmt.Errorf("the API returned no result while waiting for suite %s", target.bulkID) } + last = res if result.Done || time.Until(deadline) <= 0 { return res, nil } diff --git a/test/run-suite-wait.test.ts b/test/run-suite-wait.test.ts index 9da888e7..4c29119a 100644 --- a/test/run-suite-wait.test.ts +++ b/test/run-suite-wait.test.ts @@ -176,6 +176,14 @@ describe('create-suite --wait', () => { 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']); From fd89c71ac4239a9cb88718df74f3529edfeffe02 Mon Sep 17 00:00:00 2001 From: Sanasar Date: Wed, 25 Nov 2026 13:16:38 -0500 Subject: [PATCH 3/5] fix(test): report suite progress as JSON events in agent mode, and retry cut-off answers (COR-15957) Co-authored-by: Cursor --- internal/cli/test/run/createsuite_wait.go | 46 +++++++++++-- .../cli/test/run/createsuite_wait_test.go | 2 + test/run-suite-wait.test.ts | 65 +++++++++++++++++-- 3 files changed, 102 insertions(+), 11 deletions(-) diff --git a/internal/cli/test/run/createsuite_wait.go b/internal/cli/test/run/createsuite_wait.go index f03d572e..ff6e548e 100644 --- a/internal/cli/test/run/createsuite_wait.go +++ b/internal/cli/test/run/createsuite_wait.go @@ -20,9 +20,12 @@ package run import ( "context" + "encoding/json" "errors" "fmt" + "io" "math" + "net" "net/url" "strings" "time" @@ -195,8 +198,18 @@ func runCreateSuiteAndWait(cmd *cobra.Command) error { if len(suite.Runs) == 1 { runs = "run" } - fmt.Fprintf(cmd.ErrOrStderr(), "Started suite %s with %d %s. Waiting up to %s for it to finish.\n", - target.bulkID, len(suite.Runs), runs, maxWait) + reportSuite(cmd, + fmt.Sprintf("Started suite %s with %d %s. Waiting up to %s for it to finish.", target.bulkID, len(suite.Runs), runs, maxWait), + 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", + fmt.Sprintf("If it is stopped early, keep waiting with: vf test run wait-suite %s --bulk-id %s", target.flags(), target.bulkID), + }, + }) waited, err := waitForSuite(cmd, s, target, sdkOpts, maxWait, requestTimeout) if err != nil { @@ -248,8 +261,9 @@ func waitForSuite( if ctx.Err() == nil && isTransientWaitError(err) && failures < suiteWaitRetries && time.Until(deadline) > 0 { failures++ delay := min(suiteWaitRetryDelay, time.Until(deadline)) - fmt.Fprintf(cmd.ErrOrStderr(), "Waiting for suite %s failed (%v). Retrying in %s.\n", - target.bulkID, err, delay.Round(time.Second)) + reportSuite(cmd, + fmt.Sprintf("Waiting for suite %s failed (%v). Retrying in %s.", target.bulkID, err, delay.Round(time.Second)), + map[string]any{"status": "retrying", "bulkID": target.bulkID, "error": err.Error(), "retry_in": delay.Round(time.Second).String()}) if err := sleepContext(ctx, delay); err != nil { return nil, err } @@ -272,7 +286,8 @@ func waitForSuite( } if progress := suiteProgress(result.Counts); progress != lastProgress { lastProgress = progress - fmt.Fprintf(cmd.ErrOrStderr(), "Suite %s: %s.\n", target.bulkID, 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 { @@ -336,7 +351,9 @@ func isTransientWaitError(err error) bool { return apiErr.StatusCode == 429 || apiErr.StatusCode >= 500 } var urlErr *url.Error - return errors.As(err, &urlErr) || errors.Is(err, context.DeadlineExceeded) + 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 { @@ -376,6 +393,23 @@ func suiteOutcome( 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)) +} + // suiteError reports a suite that did not pass. In agent mode that is the // structured envelope every other failure uses; otherwise a message and hints // on stderr. diff --git a/internal/cli/test/run/createsuite_wait_test.go b/internal/cli/test/run/createsuite_wait_test.go index 27dfe138..2322c384 100644 --- a/internal/cli/test/run/createsuite_wait_test.go +++ b/internal/cli/test/run/createsuite_wait_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "io" "net/url" "slices" "testing" @@ -61,6 +62,7 @@ func TestOnlyTransientWaitErrorsAreRetried(t *testing.T) { {"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}, diff --git a/test/run-suite-wait.test.ts b/test/run-suite-wait.test.ts index 4c29119a..a8d1e031 100644 --- a/test/run-suite-wait.test.ts +++ b/test/run-suite-wait.test.ts @@ -29,6 +29,38 @@ const SUITE_FLAGS = ['test', 'run', 'create-suite', '--project-id', 'p1', '--env type Counts = { total: number; passed: number; failed: number; canceled: number; unfinished: number }; type Reply = { status: number; body: object }; +// 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}`, @@ -79,6 +111,11 @@ beforeAll(async () => { } 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 reply(next.status, next.body); } return reply(404, { statusCode: 404, message: 'Not found' }); @@ -138,15 +175,20 @@ describe('create-suite --wait', () => { expect(result.stderr).toContain('vf test run get --project-id p1 --environment-alias main --run-id '); }); - it('reports a failed suite with the agent-mode envelope', async () => { - waitReplies = [waitReply({ total: 2, passed: 1, failed: 0, canceled: 1, unfinished: 0 }, [run('r1', 'canceled')])]; + 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 envelope = JSON.parse(result.stderr.slice(result.stderr.indexOf('{'))); - expect(envelope.error_type).toBe('test_suite_failed'); - expect(envelope.message).toContain('did not pass (0 failed, 1 canceled)'); + 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 () => { @@ -176,6 +218,19 @@ describe('create-suite --wait', () => { 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']); From 00b4d3a1c93d522b623c93d0c26308bbff44a291 Mon Sep 17 00:00:00 2001 From: Sanasar Date: Wed, 25 Nov 2026 13:26:23 -0500 Subject: [PATCH 4/5] fix(test): report suite flag errors as agent envelopes, and refresh credentials for each wait (COR-15957) Co-authored-by: Cursor --- internal/cli/test/run/createsuite_wait.go | 26 +++++++++++++++++------ test/run-suite-wait.test.ts | 12 +++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/internal/cli/test/run/createsuite_wait.go b/internal/cli/test/run/createsuite_wait.go index ff6e548e..3a13780c 100644 --- a/internal/cli/test/run/createsuite_wait.go +++ b/internal/cli/test/run/createsuite_wait.go @@ -99,7 +99,9 @@ canceled, or when --max-wait (30 minutes by default) ran out first.` } wait, _ := flagutil.GetBoolFlag(cmd, suiteWaitFlag) if cmd.Flags().Changed(suiteMaxWaitFlag) && !wait { - return fmt.Errorf("--%s only applies with --%s", suiteMaxWaitFlag, suiteWaitFlag) + 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. @@ -156,7 +158,9 @@ func runCreateSuiteAndWait(cmd *cobra.Command) error { return err } if maxWait <= 0 { - return fmt.Errorf("--%s must be more than zero, got %s", suiteMaxWaitFlag, maxWait) + return 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)}) } // Checked before the suite starts, so a --timeout no wait can fit in does // not leave queued runs behind. @@ -165,8 +169,10 @@ func runCreateSuiteAndWait(cmd *cobra.Command) error { return err } if minTimeout := suiteWaitMinCallSeconds*time.Second + suiteWaitTimeoutHeadroom; requestTimeout > 0 && requestTimeout < minTimeout { - return fmt.Errorf("--%s needs a --timeout of at least %s, since each wait holds the request for %ds or more; got %s", - suiteWaitFlag, minTimeout, suiteWaitMinCallSeconds, requestTimeout) + return 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)}) } req, err := flagutil.BuildRequest[operations.StableTestRunControllerCreateSuiteRequest](cmd, createSuiteCmdMeta, "Body", "body") if err != nil { @@ -211,7 +217,7 @@ func runCreateSuiteAndWait(cmd *cobra.Command) error { }, }) - waited, err := waitForSuite(cmd, s, target, sdkOpts, maxWait, requestTimeout) + waited, err := waitForSuite(cmd, target, sdkOpts, maxWait, requestTimeout) if err != nil { return err } @@ -235,9 +241,13 @@ func (t suiteTarget) flags() string { // 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, - s *sdk.VoiceflowSDK, target suiteTarget, sdkOpts []operations.Option, maxWait time.Duration, @@ -250,6 +260,10 @@ func waitForSuite( failures := 0 for { + s, err := client.NewClient(cmd) + if err != nil { + return nil, err + } seconds := suiteWaitSeconds(time.Until(deadline), requestTimeout) started := time.Now() res, err := waitOnce(ctx, s, operations.StableTestRunControllerWaitSuiteRequest{ diff --git a/test/run-suite-wait.test.ts b/test/run-suite-wait.test.ts index a8d1e031..fda41be9 100644 --- a/test/run-suite-wait.test.ts +++ b/test/run-suite-wait.test.ts @@ -246,6 +246,18 @@ describe('create-suite --wait', () => { expect(result.stderr).toContain('--max-wait only applies with --wait'); expect(requests).toHaveLength(0); }); + + 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']]) { + 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', () => { From 6a23cf1275a60f4735a12f26afe39703da4f441d Mon Sep 17 00:00:00 2001 From: Sanasar Date: Wed, 25 Nov 2026 14:03:06 -0500 Subject: [PATCH 5/5] fix(test): keep every create-suite --wait failure structured and resumable (COR-15957) - Every failure in agent mode reaches stderr as a JSON envelope, after the progress events; anything not reported explicitly is caught by one guard. - After the suite starts, failures say how to keep waiting (wait-suite) instead of to rerun, which would start a second suite. API errors keep their error_type, status_code and hints. - A wait answer that decodes to nothing stops instead of being polled until --max-wait; a failure after --max-wait reports the last answer. - --max-wait, --timeout and --jq (parsed and compiled) are checked before the suite starts, under --dry-run too. - Hints carry --server-url and are shell-quoted; the token warning prints once per process; --usage lists --wait and --max-wait at every level. Co-authored-by: Cursor --- internal/cli/test/run/createsuite_wait.go | 205 +++++++++++++++--- .../cli/test/run/createsuite_wait_test.go | 16 ++ internal/sdk/sdkinternal/hooks/teach.go | 12 +- internal/usage/extra_flags.go | 84 +++++++ test/run-suite-wait.test.ts | 168 ++++++++++++-- 5 files changed, 432 insertions(+), 53 deletions(-) create mode 100644 internal/usage/extra_flags.go diff --git a/internal/cli/test/run/createsuite_wait.go b/internal/cli/test/run/createsuite_wait.go index 3a13780c..e7106664 100644 --- a/internal/cli/test/run/createsuite_wait.go +++ b/internal/cli/test/run/createsuite_wait.go @@ -19,6 +19,7 @@ package run import ( + "bytes" "context" "encoding/json" "errors" @@ -30,6 +31,7 @@ import ( "strings" "time" + "github.com/itchyny/gojq" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/voiceflow/cli/internal/client" @@ -80,6 +82,9 @@ func addCreateSuiteWait(cmd *cobra.Command) { 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 += ` @@ -111,13 +116,35 @@ canceled, or when --max-wait (30 minutes by default) ran out first.` } } if err := splitSuiteIDFlags(cmd); err != nil { - return err + return suiteError(cmd, "invalid_flag_value", err.Error(), nil) } - if !wait || client.IsDryRun(cmd) { + if !wait { return runCreateSuite(cmd, args) } - return runCreateSuiteAndWait(cmd) + 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. @@ -150,30 +177,54 @@ func splitIDs(values []string) []string { return ids } -// runCreateSuiteAndWait starts the suite the way runCreateSuiteCmd does, then -// waits for it and reports the outcome. -func runCreateSuiteAndWait(cmd *cobra.Command) error { +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 err + return suiteWaitOptions{}, suiteError(cmd, "invalid_flag_value", err.Error(), nil) } if maxWait <= 0 { - return suiteError(cmd, "invalid_flag_value", + 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)}) } - // Checked before the suite starts, so a --timeout no wait can fit in does - // not leave queued runs behind. requestTimeout, err := globalRequestTimeout(cmd) if err != nil { - return err + 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 suiteError(cmd, "invalid_flag_value", + 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 @@ -194,18 +245,24 @@ func runCreateSuiteAndWait(cmd *cobra.Command) error { 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 { - return errors.New("the API started the suite but returned no bulkID to wait for") + 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 := suiteTarget{projectID: req.ProjectID, environmentAlias: req.EnvironmentAlias, bulkID: suite.BulkID} + 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.", target.bulkID, len(suite.Runs), runs, maxWait), + 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, @@ -213,16 +270,21 @@ func runCreateSuiteAndWait(cmd *cobra.Command) error { "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", - fmt.Sprintf("If it is stopped early, keep waiting with: vf test run wait-suite %s --bulk-id %s", target.flags(), target.bulkID), + "If it is stopped early, keep waiting with: " + resume, }, }) - waited, err := waitForSuite(cmd, target, sdkOpts, maxWait, requestTimeout) + waited, err := waitForSuite(cmd, target, sdkOpts, maxWait, opts.requestTimeout) if err != nil { return err } if err := output.Result(cmd, waited); err != nil { - return err + 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) } @@ -231,10 +293,29 @@ 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 { - return fmt.Sprintf("--project-id %s --environment-alias %s", t.projectID, t.environmentAlias) + 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 @@ -262,7 +343,7 @@ func waitForSuite( for { s, err := client.NewClient(cmd) if err != nil { - return nil, err + return nil, suiteWaitFailed(cmd, target, err) } seconds := suiteWaitSeconds(time.Until(deadline), requestTimeout) started := time.Now() @@ -275,24 +356,39 @@ func waitForSuite( 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 (%v). Retrying in %s.", target.bulkID, err, delay.Round(time.Second)), - map[string]any{"status": "retrying", "bulkID": target.bulkID, "error": err.Error(), "retry_in": delay.Round(time.Second).String()}) + 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, err + return nil, suiteWaitFailed(cmd, target, err) } if time.Until(deadline) <= 0 && last != nil { return last, nil } continue } - return nil, output.Error(cmd, err) + 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 { - return nil, fmt.Errorf("the API returned no result while waiting for suite %s", target.bulkID) + 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 { @@ -305,7 +401,7 @@ func waitForSuite( } if pause := min(suiteWaitMinInterval-time.Since(started), time.Until(deadline)); pause > 0 { if err := sleepContext(ctx, pause); err != nil { - return nil, err + return nil, suiteWaitFailed(cmd, target, err) } } if time.Until(deadline) <= 0 { @@ -394,7 +490,7 @@ func suiteOutcome( 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{ - fmt.Sprintf("Keep waiting: vf test run wait-suite %s --bulk-id %s", target.flags(), target.bulkID), + "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()), }) } @@ -424,13 +520,56 @@ func reportSuite(cmd *cobra.Command, prose string, event map[string]any) { fmt.Fprintln(out, string(data)) } -// suiteError reports a suite that did not pass. In agent mode that is the -// structured envelope every other failure uses; otherwise a message and hints -// on stderr. +// 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 ")) } diff --git a/internal/cli/test/run/createsuite_wait_test.go b/internal/cli/test/run/createsuite_wait_test.go index 2322c384..a9887941 100644 --- a/internal/cli/test/run/createsuite_wait_test.go +++ b/internal/cli/test/run/createsuite_wait_test.go @@ -21,6 +21,22 @@ func TestSplitIDsAcceptsCommasAndRepeatedFlags(t *testing.T) { } } +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, 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 index fda41be9..f6ee997c 100644 --- a/test/run-suite-wait.test.ts +++ b/test/run-suite-wait.test.ts @@ -27,7 +27,7 @@ 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 }; +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. @@ -85,6 +85,7 @@ const waitReply = (counts: Counts, runs: object[] = []): Reply => ({ let server: http.Server; let serverURL: string; +let createReply: object | null; let waitReplies: Reply[]; let requests: Array<{ path: string; body: any }>; @@ -96,18 +97,12 @@ beforeAll(async () => { 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) => { + 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, { - bulkID: BULK_ID, - runs: [ - { id: 'r1', testID: 'test-r1', status: 'idle' }, - { id: 'r2', testID: 'test-r2', status: 'idle' }, - ], - }); + return reply(201, createReply); } if (pathname.endsWith('/test-run/suite/wait')) { const next = waitReplies.length > 1 ? waitReplies.shift()! : waitReplies[0]!; @@ -116,7 +111,7 @@ beforeAll(async () => { res.write('{"bulkID":'); return res.socket?.destroy(); } - return reply(next.status, next.body); + return setTimeout(() => reply(next.status, next.body), next.delayMs ?? 0); } return reply(404, { statusCode: 404, message: 'Not found' }); }); @@ -131,6 +126,13 @@ afterAll(async () => { beforeEach(() => { requests = []; + createReply = { + bulkID: BULK_ID, + runs: [ + { id: 'r1', testID: 'test-r1', status: 'idle' }, + { id: 'r2', testID: 'test-r2', status: 'idle' }, + ], + }; waitReplies = []; }); @@ -147,6 +149,10 @@ function vf(args: string[], opts: { agentMode?: boolean } = {}) { 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 = [ @@ -159,6 +165,7 @@ describe('create-suite --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 }); @@ -172,7 +179,7 @@ describe('create-suite --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 --project-id p1 --environment-alias main --run-id '); + 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 () => { @@ -199,9 +206,7 @@ describe('create-suite --wait', () => { 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 --project-id p1 --environment-alias main --bulk-id ${BULK_ID}`, - ); + expect(result.stderr).toContain(`vf test run wait-suite ${target()} --bulk-id ${BULK_ID}`); expect(waits()[0]!.body.timeoutSeconds).toBe(5); }); @@ -247,8 +252,141 @@ describe('create-suite --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']]) { + 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);