@testsprite/testsprite-cli 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,12 +4,13 @@
4
4
  * single `test run <test-id> --wait` and the `test run --all --wait` batch.
5
5
  *
6
6
  * A `--wait` run presents its result in the formats CI consumes:
7
- * (a) a stable machine summary `{total, passed, failed, timedOut, runs[]}`
8
- * written to `--summary-file <path>` when requested,
7
+ * (a) a stable machine summary `{total, passed, failed, skipped, timedOut,
8
+ * runs[]}` written to `--summary-file <path>` when requested,
9
9
  * (b) a Markdown results table appended to `$GITHUB_STEP_SUMMARY` when
10
10
  * running under GitHub Actions,
11
- * (c) one `::error::` workflow-command line per non-passed run so failures
12
- * annotate the PR checks tab.
11
+ * (c) one workflow-command line per non-passed run so it annotates the PR
12
+ * checks tab — `::error::` for a dispatched run that failed or timed
13
+ * out, `::warning::` for a test that never dispatched.
13
14
  * Activation: `GITHUB_ACTIONS=true` in the environment, or the explicit
14
15
  * `--gh-output` flag (which forces the annotations even off-Actions, so the
15
16
  * behavior is previewable locally). All writes are best-effort: a broken
@@ -31,6 +32,14 @@ export interface CiSummary {
31
32
  total: number;
32
33
  passed: number;
33
34
  failed: number;
35
+ /**
36
+ * Requested tests that never dispatched (deferred / conflict / not_found /
37
+ * skipped / no_tests rows). Kept OUT of `failed`: `failed` claiming
38
+ * a test failed while the exit code says otherwise is the artifacts-disagree
39
+ * bug this field fixes. Non-dispatch still gates the exit where it should
40
+ * (deferred → 7, all-conflict → 6, all-not-found rerun → 4, zero-dispatch → 5).
41
+ */
42
+ skipped: number;
34
43
  timedOut: number;
35
44
  runs: CiRunRow[];
36
45
  }
@@ -41,11 +50,13 @@ export interface CiSummary {
41
50
  * after a timeout) reduces to an empty run list rather than a crash.
42
51
  *
43
52
  * Non-dispatched work (`deferred` / `conflicts` / `notFound`) is folded in as
44
- * non-passed rows: those buckets already force a non-zero exit (deferred /
45
- * timeout → 7, all-conflict → 6) but were previously absent from the summary,
46
- * so a partial batch like `1 accepted passed + 1 deferred` read as "1/1 passed"
47
- * with no annotation. (`skippedFrontend` / `skippedIntegration` are NOT folded
48
- * in — they exit 0 and are the Action layer's allow-partial concern.)
53
+ * non-passed rows so a partial batch like `1 accepted passed + 1 deferred`
54
+ * cannot read as "1/1 passed" with no annotation — but it counts as `skipped`,
55
+ * never `failed`: whether non-dispatch fails the job is the exit-code
56
+ * gates' call, and a `failed` count the gates disagree with is exactly the
57
+ * artifacts-contradict-the-exit bug. (`skippedFrontend` / `skippedIntegration`
58
+ * are NOT folded in — they exit 0 and are the Action layer's allow-partial
59
+ * concern.)
49
60
  */
50
61
  export declare function summarizeAcceptedPayload(capturedJson: string, opts?: {
51
62
  notFoundNote?: string;
@@ -71,8 +82,11 @@ export declare function renderJobSummaryMarkdown(summary: CiSummary): string;
71
82
  /**
72
83
  * Emit the GitHub-native surfaces. Self-gating on the standard env vars:
73
84
  * `$GITHUB_STEP_SUMMARY` (a file path Actions provides) receives the Markdown
74
- * table; `GITHUB_ACTIONS=true` enables one `::error::` workflow command per
75
- * non-passed run on stdout (Actions parses workflow commands from stdout).
85
+ * table; `GITHUB_ACTIONS=true` enables one workflow command per non-passed run
86
+ * on stdout (Actions parses workflow commands from stdout) — `::error::` for a
87
+ * dispatched run that failed or timed out, `::warning::` for a test that never
88
+ * ran (deferred / conflict / not_found / skipped), so a red annotation always
89
+ * means a red-worthy outcome and never contradicts the exit code.
76
90
  * `force` (the `--gh-output` flag) emits the annotations even off-Actions;
77
91
  * the step summary still requires the env-provided file path to exist.
78
92
  * Both writes are best-effort: a broken summary file must not mask the gate.
@@ -1,4 +1,17 @@
1
1
  import { appendFileSync, writeFileSync } from 'node:fs';
2
+ /**
3
+ * Row statuses that mean "this test never ran" as opposed to "this run did not
4
+ * pass". They count as `skipped` in the summary (not `failed`) and annotate as
5
+ * `::warning::` (not `::error::`) so every CI surface tells the same story as
6
+ * the exit code.
7
+ */
8
+ const NON_DISPATCHED_STATUSES = new Set([
9
+ 'deferred',
10
+ 'conflict',
11
+ 'not_found',
12
+ 'skipped',
13
+ 'no_tests',
14
+ ]);
2
15
  /**
3
16
  * Reduce a non-dispatched bucket (`deferred` / `conflicts` / `notFound`) into
4
17
  * CI rows. Items are either bare testId strings (`notFound`) or
@@ -27,11 +40,13 @@ function bucketRows(bucket, status, note) {
27
40
  * after a timeout) reduces to an empty run list rather than a crash.
28
41
  *
29
42
  * Non-dispatched work (`deferred` / `conflicts` / `notFound`) is folded in as
30
- * non-passed rows: those buckets already force a non-zero exit (deferred /
31
- * timeout → 7, all-conflict → 6) but were previously absent from the summary,
32
- * so a partial batch like `1 accepted passed + 1 deferred` read as "1/1 passed"
33
- * with no annotation. (`skippedFrontend` / `skippedIntegration` are NOT folded
34
- * in — they exit 0 and are the Action layer's allow-partial concern.)
43
+ * non-passed rows so a partial batch like `1 accepted passed + 1 deferred`
44
+ * cannot read as "1/1 passed" with no annotation — but it counts as `skipped`,
45
+ * never `failed`: whether non-dispatch fails the job is the exit-code
46
+ * gates' call, and a `failed` count the gates disagree with is exactly the
47
+ * artifacts-contradict-the-exit bug. (`skippedFrontend` / `skippedIntegration`
48
+ * are NOT folded in — they exit 0 and are the Action layer's allow-partial
49
+ * concern.)
35
50
  */
36
51
  export function summarizeAcceptedPayload(capturedJson, opts = {}) {
37
52
  let parsed;
@@ -75,8 +90,9 @@ export function summarizeAcceptedPayload(capturedJson, opts = {}) {
75
90
  ];
76
91
  const passed = rows.filter(row => row.status === 'passed').length;
77
92
  const timedOut = rows.filter(row => row.status === 'timeout').length;
78
- const failed = rows.length - passed - timedOut;
79
- return { total: rows.length, passed, failed, timedOut, runs: rows };
93
+ const skipped = rows.filter(row => NON_DISPATCHED_STATUSES.has(row.status)).length;
94
+ const failed = rows.length - passed - timedOut - skipped;
95
+ return { total: rows.length, passed, failed, skipped, timedOut, runs: rows };
80
96
  }
81
97
  /**
82
98
  * Reduce a single `test run <test-id> --wait` result into the same CI summary
@@ -97,8 +113,9 @@ export function summarizeSingleRun(run) {
97
113
  };
98
114
  const passed = row.status === 'passed' ? 1 : 0;
99
115
  const timedOut = row.status === 'timeout' ? 1 : 0;
100
- const failed = 1 - passed - timedOut;
101
- return { total: 1, passed, failed, timedOut, runs: [row] };
116
+ const skipped = NON_DISPATCHED_STATUSES.has(row.status) ? 1 : 0;
117
+ const failed = 1 - passed - timedOut - skipped;
118
+ return { total: 1, passed, failed, skipped, timedOut, runs: [row] };
102
119
  }
103
120
  /**
104
121
  * Escape a value for a Markdown table cell. A raw `|` would break the column
@@ -147,7 +164,7 @@ export function renderJobSummaryMarkdown(summary) {
147
164
  return [
148
165
  '## TestSprite results',
149
166
  '',
150
- `**${summary.passed}/${summary.total} passed** (${summary.failed} failed, ${summary.timedOut} timed out)`,
167
+ `**${summary.passed}/${summary.total} passed** (${summary.failed} failed, ${summary.skipped} skipped, ${summary.timedOut} timed out)`,
151
168
  '',
152
169
  '| Test | Status | Run |',
153
170
  '| --- | --- | --- |',
@@ -195,8 +212,11 @@ function escapeCommandProperty(value) {
195
212
  /**
196
213
  * Emit the GitHub-native surfaces. Self-gating on the standard env vars:
197
214
  * `$GITHUB_STEP_SUMMARY` (a file path Actions provides) receives the Markdown
198
- * table; `GITHUB_ACTIONS=true` enables one `::error::` workflow command per
199
- * non-passed run on stdout (Actions parses workflow commands from stdout).
215
+ * table; `GITHUB_ACTIONS=true` enables one workflow command per non-passed run
216
+ * on stdout (Actions parses workflow commands from stdout) — `::error::` for a
217
+ * dispatched run that failed or timed out, `::warning::` for a test that never
218
+ * ran (deferred / conflict / not_found / skipped), so a red annotation always
219
+ * means a red-worthy outcome and never contradicts the exit code.
200
220
  * `force` (the `--gh-output` flag) emits the annotations even off-Actions;
201
221
  * the step summary still requires the env-provided file path to exist.
202
222
  * Both writes are best-effort: a broken summary file must not mask the gate.
@@ -227,7 +247,10 @@ export function emitGithubOutputs(summary, env, sinks, opts = {}) {
227
247
  // able to smuggle a second workflow command into the Actions stream.
228
248
  const title = `TestSprite ${escapeCommandProperty(row.title?.trim() || row.testId)}`;
229
249
  const message = escapeCommandData(`status=${row.status}${detail}${link}`);
230
- annotate(`::error title=${title}::${message}`);
250
+ // Severity mirrors the summary counters: never-dispatched rows are
251
+ // warnings (they may not even gate the exit), real failures are errors.
252
+ const severity = NON_DISPATCHED_STATUSES.has(row.status) ? 'warning' : 'error';
253
+ annotate(`::${severity} title=${title}::${message}`);
231
254
  }
232
255
  }
233
256
  }
@@ -67,6 +67,12 @@ export interface HttpClientOptions {
67
67
  onServerVersion?: (info: {
68
68
  minVersion?: string;
69
69
  }) => void;
70
+ /**
71
+ * Environment the client reads the optional `TESTSPRITE_CLIENT` tag from
72
+ * (see `client-tag.ts`) to build its User-Agent. Defaults to `process.env`;
73
+ * injectable so tests never depend on the developer's shell.
74
+ */
75
+ env?: NodeJS.ProcessEnv;
70
76
  /**
71
77
  * Per-request wall-clock timeout in milliseconds applied to every outgoing
72
78
  * fetch. The signal fires independently of any caller-supplied signal — the
@@ -205,6 +211,7 @@ export declare class HttpClient {
205
211
  private readonly requestTimeoutMs;
206
212
  private readonly shutdownSignal?;
207
213
  private readonly maxResponseBytes;
214
+ private readonly userAgent;
208
215
  constructor(options: HttpClientOptions);
209
216
  /** The resolved facade base URL (trailing slash trimmed). Read-only —
210
217
  * callers that bypass the client for a side-channel request (e.g. the
package/dist/lib/http.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import * as v from 'valibot';
3
3
  import { ApiError, InterruptError, RequestTimeoutError, TransportError } from './errors.js';
4
- import { VERSION } from '../version.js';
4
+ import { buildUserAgent } from './client-tag.js';
5
5
  import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_RESPONSE_SCHEMA, CANCEL_RUN_RESPONSE_SCHEMA, LIST_RUNS_RESPONSE_SCHEMA, RERUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TESTLIST_RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, TUNNEL_MINT_RESPONSE_SCHEMA, TUNNEL_STATUS_RESPONSE_SCHEMA, } from './response-schemas.js';
6
6
  /**
7
7
  * Default per-request timeout (120s). Comfortably covers every metadata/read
@@ -79,10 +79,13 @@ export class HttpClient {
79
79
  requestTimeoutMs;
80
80
  shutdownSignal;
81
81
  maxResponseBytes;
82
+ userAgent;
82
83
  constructor(options) {
83
84
  this.baseUrl = trimTrailingSlash(options.baseUrl);
84
85
  this.apiKey = options.apiKey;
85
86
  this.shutdownSignal = options.shutdownSignal;
87
+ // Resolved once: the tag is process-wide configuration, not per-request.
88
+ this.userAgent = buildUserAgent(options.env ?? process.env);
86
89
  this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
87
90
  this.sleep = options.sleep ?? defaultSleep;
88
91
  this.random = options.random ?? Math.random;
@@ -283,6 +286,8 @@ export class HttpClient {
283
286
  q.source = query.source;
284
287
  if (query.since !== undefined)
285
288
  q.since = query.since;
289
+ if (query.environment !== undefined)
290
+ q.environment = query.environment;
286
291
  return this.get(`/tests/${encodeURIComponent(testId)}/runs`, {
287
292
  query: q,
288
293
  signal: options.signal,
@@ -761,7 +766,7 @@ export class HttpClient {
761
766
  const headers = {
762
767
  'x-request-id': requestId,
763
768
  accept: 'application/json',
764
- 'user-agent': `testsprite-cli/${VERSION}`,
769
+ 'user-agent': this.userAgent,
765
770
  };
766
771
  // The CLI v1 facade authenticates via `x-api-key`.
767
772
  // (securitySchemes.ApiKeyAuth). Sending only Authorization Bearer would be
@@ -69,6 +69,38 @@ export declare function parseLocalPort(raw: string): number;
69
69
  * misunderstanding to correct immediately, not a request to forward.
70
70
  */
71
71
  export declare function normalizeLocalHost(raw: string | undefined): LoopbackHost;
72
+ /**
73
+ * `normalizeLocalHost` for a command whose alternative to `--local` is `--url`
74
+ * (`project create/update`, `project env create/update`) rather than
75
+ * `--target-url`, so the refusal names the flag that command actually has.
76
+ */
77
+ export declare function normalizeStoredLocalHost(raw: string | undefined): LoopbackHost;
78
+ /** The target `--local <port> [--local-host]` names on a project or environment write. */
79
+ export interface StoredLocalTarget {
80
+ host: LoopbackHost;
81
+ port: number;
82
+ }
83
+ /**
84
+ * Parse the `--local` / `--local-host` / `--url` trio a stored-target write
85
+ * takes. `--local` and `--url` are two spellings of one field, so both is a
86
+ * contradiction; `--local-host` only means something next to `--local`; the
87
+ * port is validated strictly because it becomes part of a URL runs are billed
88
+ * against. Returns the local target, or `undefined` when `--url` (or nothing)
89
+ * was given.
90
+ */
91
+ export declare function parseStoredLocalTarget(opts: {
92
+ local?: string;
93
+ localHost?: string;
94
+ url?: string;
95
+ }): StoredLocalTarget | undefined;
96
+ /**
97
+ * Refuse a stored-target write whose loopback port has nothing listening —
98
+ * the same check `project create --local` runs, so a typo in the port is
99
+ * caught before a row exists anywhere. `skipPreflight` is a pure no-op.
100
+ */
101
+ export declare function assertStoredLocalTargetListening(target: StoredLocalTarget, opts: {
102
+ skipPreflight?: boolean;
103
+ }, deps?: LocalPortProbeDeps): Promise<void>;
72
104
  /** `http://<host>:<port>`, with IPv6 bracketed as the URL grammar requires. */
73
105
  export declare function buildLocalTargetUrl(host: LoopbackHost, port: number): string;
74
106
  /**
@@ -73,6 +73,83 @@ export function normalizeLocalHost(raw) {
73
73
  }
74
74
  return match;
75
75
  }
76
+ /**
77
+ * `normalizeLocalHost` for a command whose alternative to `--local` is `--url`
78
+ * (`project create/update`, `project env create/update`) rather than
79
+ * `--target-url`, so the refusal names the flag that command actually has.
80
+ */
81
+ export function normalizeStoredLocalHost(raw) {
82
+ try {
83
+ return normalizeLocalHost(raw);
84
+ }
85
+ catch (err) {
86
+ if (err instanceof ApiError && typeof err.details?.reason === 'string') {
87
+ throw localValidationError('local-host', err.details.reason.replace('--target-url', '--url'), err.details.accepted);
88
+ }
89
+ throw err;
90
+ }
91
+ }
92
+ /**
93
+ * Parse the `--local` / `--local-host` / `--url` trio a stored-target write
94
+ * takes. `--local` and `--url` are two spellings of one field, so both is a
95
+ * contradiction; `--local-host` only means something next to `--local`; the
96
+ * port is validated strictly because it becomes part of a URL runs are billed
97
+ * against. Returns the local target, or `undefined` when `--url` (or nothing)
98
+ * was given.
99
+ */
100
+ export function parseStoredLocalTarget(opts) {
101
+ if (opts.local !== undefined && opts.url !== undefined) {
102
+ throw flagPairError('--local and --url are mutually exclusive');
103
+ }
104
+ if (opts.localHost !== undefined && opts.local === undefined) {
105
+ throw flagPairError('--local-host requires --local');
106
+ }
107
+ if (opts.local === undefined)
108
+ return undefined;
109
+ if (!/^\d+$/.test(opts.local)) {
110
+ throw flagPairError('--local must be a port number between 1 and 65535');
111
+ }
112
+ return { host: normalizeStoredLocalHost(opts.localHost), port: parseLocalPort(opts.local) };
113
+ }
114
+ function flagPairError(message) {
115
+ return ApiError.fromEnvelope({
116
+ error: {
117
+ code: 'VALIDATION_ERROR',
118
+ message: 'Invalid request.',
119
+ nextAction: message,
120
+ requestId: 'local',
121
+ details: { reason: 'missing_required_flag' },
122
+ },
123
+ });
124
+ }
125
+ /**
126
+ * Refuse a stored-target write whose loopback port has nothing listening —
127
+ * the same check `project create --local` runs, so a typo in the port is
128
+ * caught before a row exists anywhere. `skipPreflight` is a pure no-op.
129
+ */
130
+ export async function assertStoredLocalTargetListening(target, opts, deps = {}) {
131
+ if (opts.skipPreflight)
132
+ return;
133
+ const outcome = await probeLocalPort(target.host, target.port, deps);
134
+ if (outcome.verdict === 'refuse') {
135
+ const targetUrl = buildLocalTargetUrl(target.host, target.port);
136
+ throw ApiError.fromEnvelope({
137
+ error: {
138
+ code: 'VALIDATION_ERROR',
139
+ message: `Nothing is listening on ${targetUrl}. Start your app first, or pass --skip-preflight.`,
140
+ nextAction: 'Verify --local and --local-host match the app you want to test.',
141
+ requestId: 'local',
142
+ details: {
143
+ field: 'local',
144
+ reason: 'local-port-not-listening',
145
+ host: target.host,
146
+ port: target.port,
147
+ probeReason: outcome.reason,
148
+ },
149
+ },
150
+ });
151
+ }
152
+ }
76
153
  /** `http://<host>:<port>`, with IPv6 bracketed as the URL grammar requires. */
77
154
  export function buildLocalTargetUrl(host, port) {
78
155
  const authority = host.includes(':') ? `[${host}]` : host;
@@ -21,6 +21,22 @@ export declare function isOutputMode(value: unknown): value is OutputMode;
21
21
  * helper so the validation is uniform.
22
22
  */
23
23
  export declare function resolveOutputMode(raw: unknown): OutputMode;
24
+ /**
25
+ * Input to {@link Output.error} — the same 5-key shape as the hand-built
26
+ * envelopes in `index.ts`'s ApiError / InterruptError / RequestTimeoutError
27
+ * catch branches (`{error:{code,message,nextAction,requestId,details}}`).
28
+ * Only `code` and `message` are required; the rest default to the
29
+ * client-local values (`''`, `'local'`, `{}`) so every `--output json` error
30
+ * — regardless of which catch branch produced it — renders the identical
31
+ * envelope shape.
32
+ */
33
+ export interface ErrorEnvelopeInput {
34
+ code: string;
35
+ message: string;
36
+ nextAction?: string;
37
+ requestId?: string;
38
+ details?: Record<string, unknown>;
39
+ }
24
40
  export interface OutputStreams {
25
41
  /**
26
42
  * Line-oriented stdout writer. Each call is one logical line; the
@@ -66,5 +82,15 @@ export declare class Output {
66
82
  * contract.
67
83
  */
68
84
  writeChunk(text: string): Promise<void>;
69
- error(message: string): void;
85
+ /**
86
+ * Render a terminal error. JSON mode always emits the SAME 5-key envelope
87
+ * shape as the ApiError / InterruptError / RequestTimeoutError branches
88
+ * hand-build in `index.ts`'s catch (`{error:{code,message,nextAction,
89
+ * requestId,details}}`) — before this, the only two callers of
90
+ * this method (the plain-CLIError and uncaught-exception catch branches)
91
+ * fell through to a bare `{"error":"<message>"}` string, breaking the
92
+ * envelope contract that machine consumers (`--output json` scripts/CI/
93
+ * agents) rely on for every other error path.
94
+ */
95
+ error(input: ErrorEnvelopeInput): void;
70
96
  }
@@ -66,12 +66,31 @@ export class Output {
66
66
  async writeChunk(text) {
67
67
  await this.rawStdoutWrite(text);
68
68
  }
69
- error(message) {
69
+ /**
70
+ * Render a terminal error. JSON mode always emits the SAME 5-key envelope
71
+ * shape as the ApiError / InterruptError / RequestTimeoutError branches
72
+ * hand-build in `index.ts`'s catch (`{error:{code,message,nextAction,
73
+ * requestId,details}}`) — before this, the only two callers of
74
+ * this method (the plain-CLIError and uncaught-exception catch branches)
75
+ * fell through to a bare `{"error":"<message>"}` string, breaking the
76
+ * envelope contract that machine consumers (`--output json` scripts/CI/
77
+ * agents) rely on for every other error path.
78
+ */
79
+ error(input) {
70
80
  if (this.mode === 'json') {
71
- this.stderrWrite(JSON.stringify({ error: message }, null, 2));
81
+ const envelope = {
82
+ error: {
83
+ code: input.code,
84
+ message: input.message,
85
+ nextAction: input.nextAction ?? '',
86
+ requestId: input.requestId ?? 'local',
87
+ details: input.details ?? {},
88
+ },
89
+ };
90
+ this.stderrWrite(JSON.stringify(envelope, null, 2));
72
91
  return;
73
92
  }
74
- this.stderrWrite(`Error: ${message}`);
93
+ this.stderrWrite(`Error: ${input.message}`);
75
94
  }
76
95
  }
77
96
  /**
@@ -44,6 +44,18 @@ import * as v from 'valibot';
44
44
  function openWireLiteral() {
45
45
  return v.custom(value => typeof value === 'string');
46
46
  }
47
+ /**
48
+ * Mirrors `RunEnvironmentRef` (runs.types.ts): the environment a run resolved to.
49
+ * Optional + nullable everywhere it appears: absent on an older backend, `null`
50
+ * when the row carries no stamp — both mean "unknown" to every renderer.
51
+ */
52
+ const RUN_ENVIRONMENT_REF_SCHEMA = v.looseObject({
53
+ // Either half may be null: a backfilled row whose environment was deleted
54
+ // keeps the denormalised name but no id, and a pre-name row keeps the id only.
55
+ id: v.nullable(v.string()),
56
+ name: v.nullable(v.string()),
57
+ });
58
+ const OPTIONAL_ENVIRONMENT_SCHEMA = v.optional(v.nullable(RUN_ENVIRONMENT_REF_SCHEMA));
47
59
  // ---------------------------------------------------------------------------
48
60
  // GET /runs/{runId}
49
61
  // ---------------------------------------------------------------------------
@@ -87,6 +99,8 @@ export const RUN_RESPONSE_SCHEMA = v.looseObject({
87
99
  // when either is null (rule 3).
88
100
  codeVersion: v.nullish(v.string(), null),
89
101
  targetUrl: v.nullish(v.string(), null),
102
+ // The run's environment — optional with no default (rule 3, optional branch).
103
+ environment: OPTIONAL_ENVIRONMENT_SCHEMA,
90
104
  createdFrom: v.nullish(v.string(), null),
91
105
  failedStepIndex: v.nullish(v.number(), null),
92
106
  failureKind: v.nullish(v.string(), null),
@@ -161,6 +175,8 @@ export const TRIGGER_RUN_RESPONSE_SCHEMA = v.looseObject({
161
175
  enqueuedAt: v.string(),
162
176
  codeVersion: v.string(),
163
177
  targetUrl: v.string(),
178
+ // The run's environment — optional with no default (rule 3, optional branch).
179
+ environment: OPTIONAL_ENVIRONMENT_SCHEMA,
164
180
  // Server-built portal links (backend ≥ the run-links change). Optional
165
181
  // with no default (rule 3): an older backend omits them, and a V3 run
166
182
  // the server could not link stays ABSENT — the renderer prints a
@@ -306,6 +322,8 @@ const RUN_HISTORY_ITEM_SCHEMA = v.looseObject({
306
322
  // G1b fields: optional on the wire for back-compat with older backends.
307
323
  targetUrl: v.optional(v.nullable(v.string())),
308
324
  targetUrlSource: v.optional(v.nullable(openWireLiteral())),
325
+ // The run's environment — optional with no default.
326
+ environment: OPTIONAL_ENVIRONMENT_SCHEMA,
309
327
  });
310
328
  /** Mirrors `ListRunsResponse` (runs.types.ts): `GET /tests/{testId}/runs`. */
311
329
  export const LIST_RUNS_RESPONSE_SCHEMA = v.looseObject({
@@ -22,6 +22,21 @@ export interface TriggerRunBody {
22
22
  * dropping the field.
23
23
  */
24
24
  tunnelClientId?: string;
25
+ /**
26
+ * DEV-1305: the NAME of the project environment whose credentials, auto-auth
27
+ * and OTP settings this run should use (`unique(project_id, name)` server
28
+ * side). Absent → the project's default environment, exactly as before.
29
+ * Composes with `targetUrl`/`tunnelClientId`: those pick WHERE the browser
30
+ * goes, this picks WHOSE credentials it logs in with.
31
+ */
32
+ environment?: string;
33
+ }
34
+ /** The environment a run resolved to — its credentials, its config, its address. */
35
+ export interface RunEnvironmentRef {
36
+ /** `test_environment.id`; null when the row keeps only the denormalised name. */
37
+ id: string | null;
38
+ /** Environment name at seed time; null on an id-only row. */
39
+ name: string | null;
25
40
  }
26
41
  /**
27
42
  * Body sent to `POST /api/cli/v1/tests/{testId}/runs/rerun`.
@@ -34,6 +49,8 @@ export interface RerunRequest {
34
49
  autoHeal?: boolean;
35
50
  /** BE only: rerun only the named test without expanding the producer/teardown closure. */
36
51
  skipDependencies?: boolean;
52
+ /** See `TriggerRunBody.environment` — the named environment to replay against. */
53
+ environment?: string;
37
54
  }
38
55
  /** One closure member returned in `RerunResponse.closure.members[]`. */
39
56
  export interface RerunClosureMember {
@@ -103,6 +120,8 @@ export interface BatchRerunRequest {
103
120
  testIds: string[];
104
121
  autoHeal?: boolean;
105
122
  skipDependencies?: boolean;
123
+ /** See `TriggerRunBody.environment` — applied to every test in the batch. */
124
+ environment?: string;
106
125
  }
107
126
  /** One accepted run in the batch rerun response. */
108
127
  export interface BatchRerunAccepted {
@@ -166,6 +185,11 @@ export interface TriggerRunResponse {
166
185
  codeVersion: string;
167
186
  /** Resolved target URL (project default when --target-url absent). */
168
187
  targetUrl: string;
188
+ /**
189
+ * The environment this run resolved to. Absent on an older backend; `null`
190
+ * when the server resolved no environment row.
191
+ */
192
+ environment?: RunEnvironmentRef | null;
169
193
  /**
170
194
  * Portal deep link for the run's test, built by the server for the store
171
195
  * that dispatched it. Present-or-absent (never null): an older backend, a
@@ -244,6 +268,11 @@ export interface RunResponse {
244
268
  * (`RunEnvelope.targetUrl` is `[string, 'null']`).
245
269
  */
246
270
  targetUrl: string | null;
271
+ /**
272
+ * The environment this run resolved to. Absent on an older backend (or a
273
+ * V2-served run); `null` when the row names no environment.
274
+ */
275
+ environment?: RunEnvironmentRef | null;
247
276
  createdFrom: string | null;
248
277
  failedStepIndex: number | null;
249
278
  failureKind: string | null;
@@ -351,11 +380,15 @@ export interface RunHistoryItem {
351
380
  targetUrl?: string | null;
352
381
  /**
353
382
  * G1b — provenance of `targetUrl`.
354
- * - `'run'`: stamped at run-trigger time (authoritative).
383
+ * - `'run'`: stamped at run-trigger time (authoritative; V2).
355
384
  * - `'unresolved'`: backend could not resolve a URL for this run.
356
- * - `null` / absent: pre-G1b backend; treat as unknown.
385
+ * - `null`: a V3 run — the environment in `environment` IS the target and
386
+ * `targetUrl` is its address, so there is no separate provenance.
387
+ * - absent: pre-G1b backend; treat as unknown.
357
388
  */
358
389
  targetUrlSource?: 'run' | 'unresolved' | null;
390
+ /** The environment this run resolved to. Absent on older backends. */
391
+ environment?: RunEnvironmentRef | null;
359
392
  }
360
393
  /**
361
394
  * Pre-cutover metadata block present when the test has no CLI-tracked
@@ -396,6 +429,8 @@ export interface ListRunsQuery {
396
429
  source?: RunSource;
397
430
  /** ISO timestamp (after client-side duration parsing). */
398
431
  since?: string;
432
+ /** DEV-1306: only runs whose credentials came from this environment (by name). */
433
+ environment?: string;
399
434
  }
400
435
  /**
401
436
  * Body sent to `POST /api/cli/v1/tests/batch/run`.
@@ -406,6 +441,8 @@ export interface BatchRunFreshRequest {
406
441
  projectId: string;
407
442
  testIds?: string[];
408
443
  source: 'cli';
444
+ /** See `TriggerRunBody.environment` — applied to every test in the batch. */
445
+ environment?: string;
409
446
  }
410
447
  /** One accepted run in the batch fresh-run response. */
411
448
  export interface BatchRunFreshAccepted {
@@ -34,14 +34,22 @@ import { ApiError } from './errors.js';
34
34
  // the rest of `127.0.0.0/8`, which `--local` cannot dial by name at all. See
35
35
  // `'loopback-other'` below for that distinction.
36
36
  const LOCAL_DEV_RUNTIME_HINT = "This looks like a local-dev target. Run it with `testsprite test run <test-id> --local <port>` instead — it tunnels this machine's loopback address to the test runner (frontend tests only; requires an API key with the `run:tunnel` scope).";
37
- // Project/test creation happens before the caller necessarily has a test id
38
- // (and project create happens before they have a project at all). Lead those
39
- // callers through the required public project URL first, then name the per-run
40
- // loopback tunnel only after the test exists.
41
- const LOCAL_DEV_BOOTSTRAP_HINT = "TestSprite executes tests from the cloud, so a project's URL must be an internet-reachable address the runner can use. " +
42
- 'Set the project to its deployed or staging URL. ' +
43
- 'After a test exists, target an app on this machine for an individual run with ' +
44
- "`testsprite test run <test-id> --local <port>`; that tunnel is per-run and does not make localhost the project's URL.";
37
+ // Creation-time callers that take a per-run target (`test create
38
+ // --target-url`, which only applies with `--run`). A project or environment
39
+ // that names an app on this machine is created with `--local <port>`, so this
40
+ // says that instead of sending the reader after a public URL they may not have.
41
+ // It also serves the bind-all addresses (`0.0.0.0` / `::`), which are not
42
+ // loopback and are refused everywhere.
43
+ const LOCAL_DEV_BOOTSTRAP_HINT = 'TestSprite executes tests from the cloud, so the runner needs an address it can reach: ' +
44
+ 'a deployed or staging URL. For an app that only runs on this machine, create the project ' +
45
+ 'or environment with `--local <port>` instead of a URL, then run with ' +
46
+ '`testsprite test run <test-id> --local <port>`.';
47
+ /**
48
+ * `0.0.0.0` / `::` bind every interface, so an app listening there IS reachable
49
+ * on loopback — but the address itself is not loopback and the server refuses
50
+ * it as a stored URL. Naming the remedy is the whole point of the message.
51
+ */
52
+ const UNSPECIFIED_ADDRESS_REASON = 'the unspecified address (0.0.0.0 / ::) is not allowed — use 127.0.0.1 or ::1 instead';
45
53
  const LOCAL_PROJECT_CREATE_HINT = 'Use --local <port> instead of --url for an app on this machine. ' +
46
54
  'Local projects are frontend-only and require the V3 project platform.';
47
55
  const DEFAULT_TARGET_URL_CALLER = {
@@ -151,9 +159,15 @@ export function disallowedIpReason(host) {
151
159
  return addressFamily === 4 ? disallowedIpv4Reason(bare) : undefined;
152
160
  }
153
161
  function disallowedIpv4Reason(address) {
154
- // Unspecified — binds every interface, including loopback.
162
+ // Unspecified — binds every interface, including loopback. Named precisely
163
+ // rather than lumped in as "localhost" (DEV-1305): since a loopback URL is
164
+ // now a legitimate STORED target, calling `0.0.0.0` a localhost target
165
+ // produced a self-contradicting refusal — "localhost targets are not
166
+ // allowed" above a hint saying to use `localhost`. It is also simply not
167
+ // loopback: the server refuses it as a stored URL, so the accurate remedy is
168
+ // the loopback address the app is also reachable on.
155
169
  if (address === '0.0.0.0') {
156
- return { reason: 'localhost targets are not allowed', hintKind: 'loopback' };
170
+ return { reason: UNSPECIFIED_ADDRESS_REASON, hintKind: 'loopback' };
157
171
  }
158
172
  // Only the literal 127.0.0.1 is in `--local-host`'s exact accepted set.
159
173
  if (ipv4LoopbackBlocklist.check(address, 'ipv4')) {
@@ -323,8 +337,13 @@ function reclassifyEmbeddedIpv4(address, label) {
323
337
  * it on the way in rather than trusting every caller to.
324
338
  */
325
339
  function disallowedIpv6Reason(inner) {
326
- // Loopback (::1) and unspecified (::).
327
- if (inner === '::1' || inner === '::') {
340
+ // Unspecified (`::`) — see `disallowedIpv4Reason`'s note on why this is named
341
+ // separately from loopback.
342
+ if (inner === '::') {
343
+ return { reason: UNSPECIFIED_ADDRESS_REASON, hintKind: 'loopback' };
344
+ }
345
+ // Loopback (::1).
346
+ if (inner === '::1') {
328
347
  return { reason: 'localhost targets are not allowed', hintKind: 'loopback' };
329
348
  }
330
349
  // Embedded-IPv4 family, checked mapped → NAT64 → compatible. Standard /96