-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathtest.ts
More file actions
10828 lines (10187 loc) · 432 KB
/
Copy pathtest.ts
File metadata and controls
10828 lines (10187 loc) · 432 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
createWriteStream,
existsSync,
readFileSync,
readdirSync,
statSync,
type WriteStream,
} from 'node:fs';
import { rename, stat, unlink } from 'node:fs/promises';
import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
import { randomUUID } from 'node:crypto';
import { Command } from 'commander';
import { openInBrowser } from '../lib/browser.js';
import {
emitDryRunBanner,
makeHttpClient,
parseRequestTimeoutFlag,
type CommonOptions as FactoryCommonOptions,
} from '../lib/client-factory.js';
import {
assertContextIntegrity,
buildMeta,
pickCodeExtension,
resolveBundleDir,
stepFilenamePrefix,
writeBundle,
type WriteBundleResult,
} from '../lib/bundle.js';
import { findSample, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
import {
assertJUnitReportOptions,
buildJUnitReport,
resolveBatchReportProjectId,
writeJUnitReportFile,
type JUnitReportFormat,
parseJUnitReportFormat,
type JUnitTestResult,
} from '../lib/junit-report.js';
import {
ApiError,
CLIError,
InterruptError,
RequestTimeoutError,
TransportError,
localValidationError,
} from '../lib/errors.js';
import { globalShutdown, type ShutdownHandle } from '../lib/interrupt.js';
import {
assertIdempotencyKey,
requireArrayLength,
requireEnum,
requireString,
} from '../lib/validate.js';
import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS } from '../lib/http.js';
import type { FetchImpl } from '../lib/http.js';
import type { HttpClient } from '../lib/http.js';
import { GLOBAL_OPTS_HINT, Output, resolveOutputMode, type OutputMode } from '../lib/output.js';
import {
fetchSinglePage,
paginate,
validatePaginationFlags,
type Page,
type PaginationFlags,
} from '../lib/pagination.js';
import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
import type {
RunResponse,
RunStatus,
RunStepDto,
TriggerRunResponse,
RerunResponse,
BatchRerunResponse,
BatchRerunAccepted,
BatchRerunClosureByProject,
RerunClosureMember,
ListRunsResponse,
RunHistoryItem,
RunSource,
BatchRunFreshResponse,
BatchRunFreshAccepted,
CancelRunResponse,
} from '../lib/runs.types.js';
import { RUN_SOURCES } from '../lib/runs.types.js';
import { assertNotLocal } from '../lib/target-url.js';
import {
formatTextTableRow,
measureTextColumns,
renderTextTable,
resolveTextColumns,
type TextTableColumn,
} from '../lib/text-table.js';
import { createTicker } from '../lib/ticker.js';
import { RateThrottle } from '../lib/rate-throttle.js';
import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
import { loadConfig } from '../lib/config.js';
import {
flakyExitCode,
renderFlakyText,
summarizeFlaky,
type FlakyAttempt,
type FlakyOutcome,
type FlakyReport,
} from '../lib/flaky.js';
/**
* `details` debug block per the CLI OpenAPI `Test` schema
* (M2.1 amendment). `processingStatus` / `testStatus` are the
* structured pair; either may be `null` when the source row has no
* analog (MCP rows have no separate processStatus). `rawStatus` is
* the deprecated pre-M2.1 mirror, kept one minor for callers that
* already parse it. All three are debug-only — automation depends on
* the typed top-level `status` field.
*/
export interface CliTestStatusDetails {
processingStatus: string | null;
testStatus: string | null;
rawStatus: string;
}
/**
* Public Test shape per the CLI OpenAPI `Test` schema.
* `details` is optional debug context — automation must depend only on
* the typed top-level fields. `createdFrom` takes one of the three
* documented values (`portal` | `mcp` | `cli`); anything else is a
* contract violation worth surfacing rather than silently coercing.
*/
export interface CliTest {
id: string;
projectId: string;
/**
* §6.2 / M2.1 piece 4 — human-friendly project name. `null` when
* project lookup wasn't possible (record missing, ownership
* boundary, or pre-M2.1 backend that never populated the field).
* Optional on the wire so older facades that don't ship the field
* still type-check; the renderer falls back to `projectId` when
* absent.
*/
projectName?: string | null;
name: string;
type: 'frontend' | 'backend';
createdFrom: 'portal' | 'mcp' | 'cli';
status: CliPublicStatus;
createdAt: string;
updatedAt: string;
/**
* M3.4 — number of FE plan steps, or `null` for BE tests and rows
* without plan steps. Optional on the wire so pre-M3.4 facades that
* don't ship it still type-check; text mode shows it only when present
* and non-null. The dedicated read path for recovering the current
* count after a `test plan put --expected-step-count` 412.
*/
planStepCount?: number | null;
/**
* M2.1: structured `processingStatus` / `testStatus` pair plus the
* deprecated `rawStatus` mirror. Pre-M2.1 servers may still emit
* `{ rawStatus }` only — keep the structured fields optional on
* the wire even though M2.1 servers always populate them. The CLI
* accepts both shapes.
*/
details?: Partial<CliTestStatusDetails>;
/**
* G1a — test priority label, e.g. "p0" | "p1" | "p2" | "p3".
* Optional on the wire: pre-G1a backends omit the field; `null` means
* no priority has been set. Text mode surfaces it only when truthy.
*/
priority?: string | null;
/**
* Backend-only dependency declarations that drive wave ordering.
* Optional on the wire so older facades that don't ship them still
* type-check; text mode surfaces them only when present/non-empty.
*/
produces?: string[] | null;
consumes?: string[] | null;
category?: string | null;
}
export type CliPublicStatus =
| 'draft'
| 'ready'
| 'queued'
| 'running'
| 'passed'
| 'failed'
| 'blocked'
| 'cancelled'
| 'unknown';
/**
* §6.3 TestCode wire shape. `code` is either the inline source body
* (when < 100 KB) or a presigned `https://` URL (when >= 100 KB). The
* caller distinguishes via {@link isPresignedCodeUrl}.
*/
export interface CliTestCode {
testId: string;
language: 'typescript' | 'javascript' | 'python';
framework: 'playwright' | 'pytest';
code: string;
codeVersion: string | null;
etag?: string | null;
}
/** §6.4 TestStep wire shape. `null` is "not known", not "absent". */
export interface CliTestStep {
testId: string;
stepIndex: number;
action: string;
description: string;
status: 'passed' | 'failed' | null;
screenshotUrl: string | null;
htmlSnapshotUrl: string | null;
runIdIfAvailable: string | null;
codeVersion: string | null;
capturedAt: string | null;
updatedAt: string;
/**
* §6.4 / M2.1 piece 4 — derived flag the facade owns. `true` only on
* step(s) that actually contributed to the test failure. `null`
* when the underlying backend row hasn't been classified yet (pre-
* M2.1 persistence). Optional on the wire so pre-M2.1 servers
* that don't emit the field still type-check.
*/
outcomeContributesToFailure?: boolean | null;
/**
* Per-step failure text, carried from `RunStepDto.error` on the run-scoped
* endpoint (`GET /runs/{id}?includeSteps=true`). Only present on `--run-id`
* responses; the cumulative `/tests/{id}/steps` rows do not carry it, so the
* field stays optional (additive, non-breaking for existing consumers).
*/
error?: string | null;
/**
* Wire step kind from `RunStepDto.type` on the run-scoped endpoint. Same
* availability rules as `error`. Named `stepType` to avoid colliding with
* the free-form `action` label above.
*/
stepType?: 'action' | 'assertion';
}
/**
* §6.5 failureKind enum (M2.1 piece 4 widened from six to nine values).
* The CLI accepts unrecognized strings from the wire as `unknown` so
* adding a future enum value (e.g. `quota_exceeded`) is non-breaking
* — agents must not switch on raw strings outside the enumerated set.
*/
export type CliFailureKind =
| 'assertion'
| 'assertion_blocked' // M2.1 piece 4
| 'routing_404' // M2.1 piece 4
| 'network_timeout' // M2.1 piece 4
| 'network'
| 'timeout'
| 'browser_crash'
| 'infra'
| 'unknown'
| null;
/** test VERDICT (the outcome of a completed run). */
export type CliVerdict = 'passed' | 'failed' | 'blocked';
/** execution LIFECYCLE (where the test is in its run lifecycle). */
export type CliExecutionStatus =
| 'draft'
| 'ready'
| 'queued'
| 'running'
| 'completed'
| 'cancelled'
| 'unknown';
/** §6.5 LatestResult wire shape. All correlation fields are required. */
export interface CliLatestResult {
testId: string;
status: CliPublicStatus;
startedAt: string | null;
finishedAt: string | null;
videoUrl: string | null;
failureAnalysisUrl: string | null;
snapshotId: string;
runIdIfAvailable: string | null;
codeVersion: string | null;
/**
* The target URL used for this run. May be `null` when `targetUrlSource`
* is `'unresolved'` (the stored run row had no target URL and the backend
* did not fall back to the project default).
*/
targetUrl: string | null;
/**
* D1 — provenance of `targetUrl`. Present on backends that have shipped
* the D1 fix; omitted on older backends (treat as unknown when absent).
*
* - `'run'` — URL was stored explicitly on the TestRun row.
* - `'project-default'` — URL came from the project's configured default.
* - `'unresolved'` — no URL on the run row AND no project default;
* `targetUrl` will be `null`.
* - `null` — backend sent the field explicitly as null
* (semantically equivalent to `'unresolved'`).
*/
targetUrlSource?: 'run' | 'project-default' | 'unresolved' | null;
failedStepIndex: number | null;
failureKind: CliFailureKind;
/**
* the test VERDICT only (`passed | failed | blocked`), or `null`
* when the latest run produced no verdict yet (never run / queued / running /
* cancelled). Lifecycle lives in `executionStatus`; `status` above is the
* legacy conflated field, retained for back-compat.
*/
verdict: CliVerdict | null;
/** the execution LIFECYCLE (terminal runs collapse to `completed`). */
executionStatus: CliExecutionStatus;
/**
* a human/agent-readable description of the latest run (replaces the
* former `{passed,failed,skipped}` count object).
*/
summary: string;
/**
* Captured stdout (`api_output`) from a backend-test execution.
* Present (possibly null) only for backend tests; omitted for FE/MCP and on
* older backends that omit them. Capped at 50 KB UTF-8 by the server.
*/
apiOutput?: string | null;
/**
* Python traceback from a backend-test execution (ends with the
* `ExceptionType: message` line). Present (possibly null) only for backend
* tests; omitted for FE/MCP and on older backends.
*/
trace?: string | null;
/**
* §6.5.1 (M2.1 piece 3) — inline failure analysis. Present when the
* caller passed `--include-analysis` (`?includeAnalysis=true` on
* the wire); absent on the byte-identical-to-pre-M2.1 default.
*/
analysis?: CliAnalysisBlock;
}
/**
* §6.5.1 (M2.1 piece 3) — analysis fields surfaced inline on
* `/result?includeAnalysis=true` and as the body of `/failure/summary`.
*
* Stable shape: ships even on passing/in-flight runs with every field
* inside `null`. `recommendedFixTarget` is `null` (not the always-
* `unknown` wrapper) when the analysis pipeline didn't fill it.
* `failureKind` mirrors `LatestResult.failureKind` for caller
* convenience. `snapshotId` mirrors the outer snapshot, so a caller
* comparing the inline analysis with a later `/failure` bundle can
* detect drift without a second round-trip.
*/
export interface CliAnalysisBlock {
rootCauseHypothesis: string | null;
recommendedFixTarget: CliFixTarget | null;
failureKind: CliFailureKind;
snapshotId: string;
/**
* L141 — set to `true` (JSON output only) when `rootCauseHypothesis`
* ends with `…` (U+2026), indicating the server truncated the text.
* Omitted when the field is null or untouched. This is a CLI-side
* observation; the server does not send this field. Full untruncated
* text requires backend support (backend follow-up).
*/
rootCauseHypothesisTruncated?: true;
/**
* L141 — set to `true` (JSON output only) when
* `recommendedFixTarget.rationale` ends with `…` (U+2026), indicating
* the server truncated the rationale. Omitted when not truncated.
*/
recommendedFixRationaleTruncated?: true;
}
/**
* §5.2 (M2.1 piece 3) — body of `GET /tests/{testId}/failure/summary`.
* One-screen agent triage answer: status + failureKind + analysis,
* no bundle. Sibling of `failure get` for cases where the agent's
* first pass doesn't need video / screenshots / DOM snapshots.
*/
export interface CliFailureSummary {
testId: string;
status: CliPublicStatus;
failureKind: CliFailureKind;
snapshotId: string;
rootCauseHypothesis: string | null;
recommendedFixTarget: CliFixTarget | null;
}
/** §6.7 narrow fix-target enum. Agents route on this; M2 emits 'unknown'. */
export type CliFixKind = 'code' | 'selector' | 'data' | 'env' | 'unknown';
export type CliEvidenceKind = 'screenshot' | 'snapshot' | 'log' | 'network' | 'console';
export interface CliFixTarget {
kind: CliFixKind;
reference: string | null;
rationale: string | null;
}
export interface CliEvidence {
kind: CliEvidenceKind;
/** 1-based step index — matches portal display. */
stepIndex: number;
/** Presigned S3 URL with shared 15-min TTL. */
url: string;
/**
* LLM-generated transcription per §6.1. The CLI emits whatever the
* facade returned — never edited or generated client-side.
*/
summary: string;
}
export interface CliFailureBlock {
rootCauseHypothesis: string | null;
/**
* §6.7 / M2.1 piece 3 visibility policy: `null` when the analysis
* pipeline didn't fill any of `kind` / `reference` / `rationale`.
* Pre-M2.1 the facade always emitted an `unknown` wrapper here;
* M2.1 drops it so agents route on `null` rather than parsing the
* always-unknown shape.
*/
recommendedFixTarget: CliFixTarget | null;
evidence: CliEvidence[];
/**
* Backend-test execution artifacts, surfaced on the failure block
* so triage has stdout + traceback next to the hypothesis (mirrors
* `result.apiOutput` / `result.trace`). Present (possibly null) only for
* backend failures; omitted for FE and on older backends.
*/
apiOutput?: string | null;
trace?: string | null;
}
/** §6.7 wire shape — one atomic snapshot of the latest failing run. */
export interface CliFailureContext {
snapshotId: string;
testId: string;
projectId: string;
result: CliLatestResult;
steps: CliTestStep[];
code: CliTestCode;
failure: CliFailureBlock;
}
export interface TestDeps {
env?: NodeJS.ProcessEnv;
credentialsPath?: string;
fetchImpl?: FetchImpl;
stdout?: (line: string) => void;
stderr?: (line: string) => void;
/**
* Raw stdout writer for streaming code bodies in `test code get`. No
* implicit newline; each call writes verbatim. Defaults to
* `process.stdout.write`. See `Output.writeChunk` for rationale.
*/
rawStdout?: (text: string) => void;
/**
* Injectable sleep function for the polling loop. Defaults to the
* `defaultSleep` in `poll.ts` (`setTimeout`-based). Inject an instant
* no-op in tests to avoid real delays.
*/
sleep?: (ms: number) => Promise<void>;
/**
* Graceful-detach coordinator for the `--wait` paths (DEV-331 piece 1).
* Defaults to the process-wide `globalShutdown`; tests inject their own
* controller and abort it to simulate Ctrl-C deterministically (same
* pattern as `sleep` / `fetchImpl`).
*/
shutdown?: ShutdownHandle;
}
/** The effective shutdown handle for a command invocation (DEV-331). */
function shutdownOf(deps: TestDeps): ShutdownHandle {
return deps.shutdown ?? globalShutdown;
}
/**
* The honest-detach stderr line (DEV-331 D1 — the heart of the ticket):
* a Ctrl-C detaches the local wait only; the server-side run keeps executing
* AND billing. Names both re-attach (`test wait`) and the real cancel
* (`test cancel`, piece 3) so the user always has a path to actually stop it.
*/
function interruptDetachMessage(err: InterruptError, runIds: string[]): string {
const subject =
runIds.length === 1
? `Run ${runIds[0]} is still executing on the server and will keep running (and billing) until it finishes.`
: `${runIds.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
return (
`Interrupted (${err.signal}). ${subject}\n` +
` Re-attach with: testsprite test wait ${runIds.join(' ')}\n` +
` Cancel with: testsprite test cancel ${runIds.join(' ')}`
);
}
type CommonOptions = FactoryCommonOptions;
interface ListOptions extends CommonOptions {
projectId: string;
type?: 'frontend' | 'backend';
createdFrom?: 'portal' | 'mcp' | 'cli';
/**
* §6.6 / M2.1 piece 2 — comma-separated list of public status
* values (e.g. `failed,blocked`). The CLI passes the raw string to
* the facade which validates token-by-token. Pre-validating client-
* side gives a friendlier error for typos like `--status fail`.
*/
status?: string;
pageSize?: number;
startingToken?: string;
maxItems?: number;
columns?: string;
noHeader?: boolean;
}
const TEST_TYPES: ReadonlyArray<'frontend' | 'backend'> = ['frontend', 'backend'];
// 'cli' added 2026-06-04 (dogfood): backend now stamps createFrom='cli' on
// tests created via `testsprite test create`, so the `--created-from cli`
// list filter must accept it. See backend-v2.0 CLI_CREATED_FROMS.
const CREATED_FROMS: ReadonlyArray<'portal' | 'mcp' | 'cli'> = ['portal', 'mcp', 'cli'];
/**
* §6.6 / M2.1 piece 2 — public status values accepted by the
* `--status` filter. Mirrors `CLI_PUBLIC_STATUSES` on the facade
* side (cli-tests.types.ts). Client-side validation gives a friendly
* error before the request hits the wire — the facade rejects the
* same set with VALIDATION_ERROR.
*/
const PUBLIC_STATUSES: ReadonlyArray<CliPublicStatus> = [
'draft',
'ready',
'queued',
'running',
'passed',
'failed',
'blocked',
'cancelled',
'unknown',
];
/**
* Internal helper: resolve the effective API URL from command opts.
* Mirrors the resolution logic in `makeHttpClient` so we can compute a
* `dashboardUrl` without accessing the private `client.baseUrl`.
* Calls `loadConfig` which reads the credentials file (cheap, cached by OS).
* Used only at the emit stage, AFTER the main request completes.
*/
function resolveApiUrl(opts: CommonOptions, deps: TestDeps = {}): string {
if (opts.dryRun) return opts.endpointUrl ?? 'https://api.testsprite.com';
const config = loadConfig({
profile: opts.profile,
endpointUrl: opts.endpointUrl,
env: (deps as { env?: NodeJS.ProcessEnv }).env,
credentialsPath: (deps as { credentialsPath?: string }).credentialsPath,
});
return config.apiUrl;
}
export async function runList(opts: ListOptions, deps: TestDeps = {}): Promise<Page<CliTest>> {
// Validate inputs before touching credentials so a missing `--project`
// surfaces as `VALIDATION_ERROR` (exit 5) rather than `AUTH_REQUIRED`
// (exit 3) when the caller also lacks a configured key. Order matters
// for the CLI error spec §2 — bad input is a caller bug, not an auth
// gate.
requireProjectId(opts.projectId);
const paginationFlags: PaginationFlags = validatePaginationFlags({
pageSize: opts.pageSize,
startingToken: opts.startingToken,
maxItems: opts.maxItems,
});
// M2.1 piece 2: validate `--status` tokens client-side before
// sending. Friendlier error than waiting for the server's 400 with
// a list of accepted tokens — and lets the user fix typos without
// a round trip.
validateStatusFilter(opts.status);
const out = makeOutput(opts.output, deps);
if (opts.output === 'text') {
resolveTextColumns(opts.columns, TEST_LIST_COLUMNS);
}
const client = makeClient(opts, deps);
// Match P2's "explicit pageSize ⇒ single-page" convention so an
// operator can grab one slice + cursor without auto-paging through a
// huge project.
const useSinglePage = opts.pageSize !== undefined && opts.maxItems === undefined;
const baseQuery: Record<string, string | number | boolean | undefined> = {
projectId: opts.projectId,
type: opts.type,
createdFrom: opts.createdFrom,
status: opts.status,
};
let page: Page<CliTest>;
if (useSinglePage) {
page = await fetchSinglePage<CliTest>(
client,
'/tests',
paginationFlags.pageSize!,
opts.startingToken,
baseQuery,
);
} else {
page = await paginate<CliTest>(
async ({ pageSize, cursor }) =>
client.get<Page<CliTest>>('/tests', {
query: { ...baseQuery, pageSize, cursor },
}),
paginationFlags,
);
}
out.print(page, data =>
renderTestListText(data as Page<CliTest>, { columns: opts.columns, noHeader: opts.noHeader }),
);
return page;
}
/**
* §6.X / M3.2 piece-2 `CreateTestResponse` shape. `codeVersion` is the
* monotonic stamp piece-1 added to FE/BE Portal rows; the CLI re-uses
* it as the `If-Match` etag on `test code put` (piece-4).
*/
export interface CliCreateTestResponse {
testId: string;
type: 'frontend' | 'backend';
codeVersion: string;
createdAt: string;
/**
* Non-fatal advisories from the backend (e.g. the BE auth guardrail
* flagging a hardcoded credential). Rendered on stderr; the create
* still succeeded.
*/
warnings?: string[];
}
export const CLI_CREATE_PRIORITIES = ['p0', 'p1', 'p2', 'p3'] as const;
export type CliCreatePriority = (typeof CLI_CREATE_PRIORITIES)[number];
/**
* 350 KB inline-code cap. Mirrors `MAX_INLINE_CODE_BYTES` in the backend
* (`CliTestsController`), which is sized to fit a full test row inside
* DDB's 400 KB item limit after metadata headroom. Enforced client-side
* as a pre-flight check so an obvious oversize file fails fast (exit 5)
* without spending a round-trip. The server enforces the same cap
* defensively. Lowered from 1 MB → 350 KB in backend PR #464; this CLI
* constant tracks it.
*/
const MAX_INLINE_CODE_BYTES = 350 * 1024;
interface CreateOptions extends CommonOptions {
projectId: string;
type: 'frontend' | 'backend';
name: string;
description?: string;
priority?: CliCreatePriority;
/** Source path to the test code. Read into memory; capped at 350 KB. */
codeFile: string;
/** Caller-supplied idempotency token; UUIDv4 minted client-side if absent. */
idempotencyKey?: string;
/** M3.3 chain: trigger a run after create. */
run?: boolean;
/** M3.3 chain: poll until terminal when `run` is true. */
wait?: boolean;
/** M3.3 chain: per-run timeout in seconds. */
timeout?: number;
/**
* M4 piece-2 — BE dependency authoring flags.
* `--produces <var>` (repeatable): variable names this test captures.
* Maps to wire field `produces` → backend serialises as `captures` JSON.
* Backend-only; supplying with --type frontend → exit 5 (FE has no wave model).
*/
produces?: string[];
/**
* `--needs <var>` (repeatable): variable names this test consumes.
* Maps to wire field `consumes`. Backend-only.
*/
needs?: string[];
/**
* `--category <str>`: free-text category. Use `teardown`/`cleanup` to mark
* a last-wave cleanup test in the wave planner. Backend-only.
*/
category?: string;
/**
* B2(c): true when --timeout was NOT explicitly set (the default is in
* effect). Threaded into RunTestRunOptions so the first-run hint fires.
*/
timeoutIsDefault?: boolean;
/** M3.3 chain: per-run target URL override. */
targetUrl?: string;
}
/**
* Chained `test create --run` / `test create --plan-from --run` derive the
* trigger idempotency key as `<createKey>:run`. Validate that derived key
* BEFORE the create POST so a near-limit user-supplied base key fails fast
* (exit 5) instead of creating the test and THEN rejecting the 257+ char
* derived run key — which would leave an orphan test with no run (codex #128
* P2). Auto-minted keys (no `--idempotency-key` supplied) are always short and
* thus exempt. `RUN_SUFFIX` must match the `:run` suffix appended in
* `runCreate` / `runCreateFromPlan` when chaining into `runTestRun`.
*/
function assertChainedRunKeyFits(
run: boolean | undefined,
idempotencyKey: string | undefined,
): void {
if (run !== true || idempotencyKey === undefined) return;
const RUN_SUFFIX = ':run';
if (idempotencyKey.length + RUN_SUFFIX.length > 256) {
throw localValidationError(
'idempotencyKey',
`must be at most ${256 - RUN_SUFFIX.length} characters when used with --run ` +
`(the chained trigger derives "<key>${RUN_SUFFIX}", which must stay within the 256-char limit)`,
undefined,
'flag',
);
}
}
/**
* B3 / Fix 4: best-effort duplicate-name advisory shared by `runCreate`
* and `runCreateFromPlan`. One-page lookup (pageSize=100) — not
* exhaustive but cheap. Silently swallows all errors; must never block
* or fail the caller's create.
*
* Skip when `projectId` or `name` is absent (e.g. plan not yet parsed)
* or when the caller is in dry-run mode.
*/
/** Short deadline for the advisory duplicate-name lookup (5 s). */
const DUP_NAME_ADVISORY_TIMEOUT_MS = 5_000;
async function emitDupNameAdvisoryIfNeeded(
client: HttpClient,
projectId: string | undefined,
name: string | undefined,
stderrFn: (line: string) => void,
): Promise<void> {
if (!projectId || !name) return;
// B: the advisory lookup must NEVER block the create critical path.
// Use an AbortController with a 5 s deadline. When the timer fires it
// calls ac.abort(), which causes client.get (via the `signal` option) to
// throw an AbortError — caught below and swallowed. This ensures a stalled
// or retrying listing endpoint can't delay an otherwise-healthy create by
// the full request-timeout (120 s) or multiple transport retries.
// No secondary setTimeout is used to avoid leaking timers in tests.
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), DUP_NAME_ADVISORY_TIMEOUT_MS);
try {
const listing = await client.get<{ items: CliTest[] }>(
`/tests?projectId=${encodeURIComponent(projectId)}&pageSize=100`,
{ signal: ac.signal },
);
const nameLower = name.toLowerCase();
const match = listing.items?.find(t => t.name.toLowerCase() === nameLower);
if (match) {
stderrFn(
`[advisory] A test named "${name}" already exists in this project (testId: ${match.id}). ` +
`Use \`testsprite test update ${match.id}\` to modify it, or proceed to create a duplicate.`,
);
}
} catch {
// Swallow — this is best-effort; must not block the create.
} finally {
clearTimeout(timer);
}
}
/**
* `test create --code-file <path>` — M3.2 piece-2 first mutation.
*
* Reads the file (with the same 350 KB pre-flight the server enforces)
* and POSTs to `/api/cli/v1/tests` with an `Idempotency-Key` header.
* Default key is `cli-create-<uuidv4>`; a caller-supplied
* `--idempotency-key` lets retry tooling pin the same key across
* attempts so a network blip doesn't double-create. The exact key sent
* is echoed to stderr at `--debug` so an operator can reuse it.
*
* Dry-run: the request still goes through `HttpClient.post`, but the
* `client-factory` swaps in `createDryRunFetch` so no network call
* happens — the caller sees the canned response shape from
* `src/lib/dry-run/samples.ts`. The `--debug` events emit the canonical
* request envelope (URL, method, headers including Idempotency-Key)
* so the user can verify what would be sent. Matches the M2 P6
* convention; no separate "envelope-only" output mode.
*/
export async function runCreate(
opts: CreateOptions,
deps: TestDeps = {},
): Promise<CliCreateTestResponse> {
// P1-2: validate idempotency key before any I/O — non-ASCII chars cause a
// ByteString TypeError at the HTTP transport layer (exit 10 UNAVAILABLE).
assertIdempotencyKey(opts.idempotencyKey);
// codex #128 P2: the `--run` chain derives `<key>:run` (see below); validate
// that derived key BEFORE the create POST so a near-limit base key fails fast
// (exit 5) instead of creating the test and THEN rejecting the 257+ char run
// key — which would orphan a created test with no run.
assertChainedRunKeyFits(opts.run, opts.idempotencyKey);
// Validate inputs before touching credentials or fs — matches the
// M2 read commands' "input gates first, then auth, then I/O" ordering.
requireProjectId(opts.projectId);
requireNonEmpty('name', opts.name);
// P1-3: client-side length checks matching server limits (name ≤200,
// description ≤2000) so the user gets instant, actionable errors instead
// of a cryptic server validation message.
if (opts.name !== undefined && opts.name.length > 200) {
throw localValidationError('name', 'must be at most 200 characters');
}
if (opts.description !== undefined && opts.description.length > 2000) {
throw localValidationError('description', 'must be at most 2000 characters');
}
// P2-11: extend the required-flag error message to suggest --plan-from for
// FE tests so operators who missed that flag get an actionable hint.
if (typeof opts.codeFile !== 'string' || opts.codeFile.length === 0) {
throw ApiError.fromEnvelope({
error: {
code: 'VALIDATION_ERROR',
message: 'Invalid request.',
nextAction:
'Flag `--code-file` is invalid: is required. ' +
'For frontend tests you can also supply the plan with `--plan-from <plan.json>` instead of a code file.',
requestId: 'local',
details: { field: 'codeFile', reason: 'is required' },
},
});
}
assertPythonCodeFile(opts.codeFile);
if (!['frontend', 'backend'].includes(opts.type)) {
throw localValidationError('type', 'must be one of: frontend, backend', [
'frontend',
'backend',
]);
}
if (opts.priority !== undefined && !CLI_CREATE_PRIORITIES.includes(opts.priority)) {
throw localValidationError('priority', `must be one of: ${CLI_CREATE_PRIORITIES.join(', ')}`, [
...CLI_CREATE_PRIORITIES,
]);
}
// M4 piece-2: --produces/--needs/--category are backend-only. FE plans have
// no wave model; fail-fast client-side to match the backend's 400 reject and
// save a round-trip.
if (opts.type === 'frontend') {
const depFlags: string[] = [];
if (opts.produces !== undefined && opts.produces.length > 0) depFlags.push('produces');
if (opts.needs !== undefined && opts.needs.length > 0) depFlags.push('needs');
if (opts.category !== undefined) depFlags.push('category');
if (depFlags.length > 0) {
// Pass the BARE flag name to localValidationError — its kind:'flag' branch
// adds the `--` prefix, so '--produces' would render as '----produces'.
const flagList = depFlags.map(f => `--${f}`);
const verb = depFlags.length === 1 ? 'is a backend-only flag' : 'are backend-only flags';
// No trailing period: localValidationError appends one after the reason.
throw localValidationError(
depFlags[0]!,
`${flagList.join(', ')} ${verb}; frontend plans have no wave model. ` +
`Remove ${flagList.join('/')} or use --type backend`,
);
}
}
// Dry-run path skips fs entirely so the operator can shake out the
// wire shape with a dummy `--code-file` (matches the M2 P6 dry-run
// contract — no real credentials, no real disk). The canned response
// from `src/lib/dry-run/samples.ts` echoes the same response shape
// a real call would produce.
const code = opts.dryRun ? DRY_RUN_PLACEHOLDER_CODE : readCodeFileGuarded(opts.codeFile);
const idempotencyKey = opts.idempotencyKey ?? `cli-create-${randomUUID()}`;
// Surface the idempotency key on stderr so an operator who hits a
// transport-level retry-budget exhaustion can re-run with the same
// `--idempotency-key`. Without this, a generated UUID dies inside the
// process and a retry would mint a fresh key — duplicating the test
// if the original POST reached the server before the retry budget
// ran out. Stderr (not stdout) keeps json-mode output clean.
if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
const stderr = deps.stderr ?? ((line: string) => process.stderr.write(`${line}\n`));
stderr(`idempotency-key: ${idempotencyKey}`);
}
const body: Record<string, unknown> = {
projectId: opts.projectId,
type: opts.type,
name: opts.name,
description: opts.description,
priority: opts.priority,
code,
};
// M4 piece-2: thread BE dependency fields into the POST body.
// Only include when non-empty so the wire stays clean for tests that
// don't declare any dependencies (undefined is omitted by JSON.stringify).
if (opts.produces !== undefined && opts.produces.length > 0) {
body.produces = opts.produces;
}
if (opts.needs !== undefined && opts.needs.length > 0) {
body.consumes = opts.needs;
}
if (opts.category !== undefined) {
body.category = opts.category;
}
if (opts.targetUrl !== undefined) {
assertNotLocal(opts.targetUrl);
}
// C1: --target-url is inert for backend tests (base URL is baked into the
// test code; the backend sandbox never receives targetUrl). Emit a
// pre-flight advisory so the user doesn't silently get the wrong env.
// Only fires when --run is also set, because targetUrl only matters at run
// time; a bare `test create --type backend --target-url` without --run does
// not execute the test, so the advisory would be confusing noise.
if (opts.type === 'backend' && opts.targetUrl !== undefined && opts.run === true) {
const stderrFn = deps.stderr ?? ((line: string) => process.stderr.write(`${line}\n`));
stderrFn(
"[advisory] --target-url has no effect for backend tests (a backend test's base URL is defined inside its code).",
);
}
const client = makeClient(opts, deps);
const out = makeOutput(opts.output, deps);
// B3: best-effort duplicate-name advisory. Skip under --dry-run.
if (!opts.dryRun) {
const stderrFn = deps.stderr ?? ((line: string) => process.stderr.write(`${line}\n`));
await emitDupNameAdvisoryIfNeeded(client, opts.projectId, opts.name, stderrFn);
}
const response = await client.post<CliCreateTestResponse>('/tests', {
body,
headers: { 'idempotency-key': idempotencyKey },
});
// Surface backend advisories (e.g. a hardcoded-credential warning for BE
// tests) on stderr so they reach the agent without polluting stdout JSON.
// Emitted before the --run early return so they always show.
emitResponseWarnings(response.warnings, deps);
// --run chain (M3.3 piece-3). Per codex round-1 P1: suppress the
// create's own print when chaining; `runTestRun` emits a single
// merged envelope `{ ...createResponse, run: <trigger|final> }` so
// `--output json` stays parseable for agents and scripts.
if (opts.run === true) {
const runIdempotencyKey = `${idempotencyKey}:run`;
// R3a: compute dashboardUrl before the early return so it flows into
// the merged { ...createContext, run } envelope in JSON mode and
// appears on the Dashboard: stderr line in text mode.
// R1: suppress under --dry-run (fake canned test id).
const chainDashboardUrl = opts.dryRun
? undefined
: resolvePortalUrl(resolveApiUrl(opts, deps), opts.projectId, response.testId);
const createContextWithUrl =
chainDashboardUrl !== undefined ? { ...response, dashboardUrl: chainDashboardUrl } : response;
await runTestRun(
{
...opts,
testId: response.testId,
idempotencyKey: runIdempotencyKey,
timeoutSeconds: opts.timeout ?? DEFAULT_RUN_TIMEOUT_SECONDS,
// B2(c): pass through whether --timeout was explicitly set.
// opts.timeout is already a parsed number (never undefined here) so we
// thread the dedicated flag rather than checking undefined again.
timeoutIsDefault: opts.timeoutIsDefault ?? false,
wait: opts.wait === true,
createContext: createContextWithUrl,
// Thread the known type so fast BE runs (terminal on first poll, where
// beFallbackUsed would be false) still render `steps: n/a (backend)`.
type: opts.type,
},
deps,
);
return response;
}
// Fix 5: emit dashboard deep-link when projectId + testId are known client-side
// (no extra network call — both come from opts / response).
// R1: suppress under --dry-run — the test id is a fake canned value
// (e.g. "test_dryrun_create_2026") and a live-looking URL would mislead.
const dashboardUrl = opts.dryRun
? undefined
: resolvePortalUrl(resolveApiUrl(opts, deps), opts.projectId, response.testId);
if (opts.output === 'json') {
out.print(dashboardUrl !== undefined ? { ...response, dashboardUrl } : response, data =>
renderCreateText(data as CliCreateTestResponse),
);
} else {
out.print(response, data => renderCreateText(data as CliCreateTestResponse));
if (dashboardUrl !== undefined) {
const stderrFn = deps.stderr ?? ((line: string) => process.stderr.write(`${line}\n`));
stderrFn(`Dashboard: ${dashboardUrl}`);
}
}
return response;
}
/**
* Stand-in `code` body used by `--dry-run`. The dry-run fetch impl
* never inspects the request body, so the value is just a placeholder
* — kept readable for debug-event captures.
*/
const DRY_RUN_PLACEHOLDER_CODE = '// dry-run placeholder code body';
function assertPythonCodeFile(path: string): void {
if (!path.toLowerCase().endsWith('.py')) {
throw localValidationError(
'code-file',
'must be a Python (.py) file — TestSprite runs all test code as Python ' +
'(frontend: Playwright for Python; backend: requests + pytest).',