@testsprite/testsprite-cli 0.8.0 → 0.10.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.
@@ -12,6 +12,37 @@ import { assertNotLocal } from '../lib/target-url.js';
12
12
  import { renderTextTable, resolveTextColumns } from '../lib/text-table.js';
13
13
  import { assertIdempotencyKey } from '../lib/validate.js';
14
14
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
15
+ /** Attribute names are interpolated into CSS selectors by the engine — keep them plain. */
16
+ const TEST_ID_ATTRIBUTE_NAME = /^[A-Za-z_][\w.:-]*$/;
17
+ const TEST_ID_ATTRIBUTES_MAX = 10;
18
+ /**
19
+ * Parse `--test-id-attributes <list>`: a comma-separated, ordered list of DOM
20
+ * attribute names. Trims, drops empties and duplicates (first occurrence
21
+ * wins — order is the priority), rejects invalid names. Exported for tests.
22
+ */
23
+ export function parseTestIdAttributesFlag(raw, flagName) {
24
+ const seen = new Set();
25
+ const attrs = [];
26
+ for (const part of raw.split(',')) {
27
+ const name = part.trim();
28
+ if (!name)
29
+ continue;
30
+ if (name.length > 64 || !TEST_ID_ATTRIBUTE_NAME.test(name)) {
31
+ throw localValidationError(`--${flagName}: '${name}' is not a valid attribute name (letters, digits, '_', '-', '.', ':'; must not start with a digit).`);
32
+ }
33
+ if (!seen.has(name)) {
34
+ seen.add(name);
35
+ attrs.push(name);
36
+ }
37
+ }
38
+ if (attrs.length === 0) {
39
+ throw localValidationError(`--${flagName} needs at least one attribute name, e.g. --${flagName} data-element,data-testid`);
40
+ }
41
+ if (attrs.length > TEST_ID_ATTRIBUTES_MAX) {
42
+ throw localValidationError(`--${flagName} accepts at most ${TEST_ID_ATTRIBUTES_MAX} attribute names.`);
43
+ }
44
+ return attrs;
45
+ }
15
46
  export async function runList(opts, deps = {}) {
16
47
  const out = makeOutput(opts.output, deps);
17
48
  const paginationFlags = validatePaginationFlags({
@@ -81,7 +112,11 @@ export async function runCreate(opts, deps = {}) {
81
112
  // P2-7: guard --url against localhost/RFC1918/non-http(s) (same rules as
82
113
  // `test create --target-url`). Applies to both FE (required) and BE (optional).
83
114
  if (opts.targetUrl !== undefined) {
84
- assertNotLocal(opts.targetUrl);
115
+ assertNotLocal(opts.targetUrl, {
116
+ field: 'url',
117
+ helpCommand: 'testsprite project create',
118
+ hintContext: 'bootstrap',
119
+ });
85
120
  }
86
121
  if (opts.type === 'frontend' && !opts.targetUrl) {
87
122
  throw localValidationError('--url is required for --type frontend');
@@ -130,12 +165,19 @@ export async function runCreate(opts, deps = {}) {
130
165
  ...(opts.username !== undefined ? { username: opts.username } : {}),
131
166
  ...(password !== undefined ? { password } : {}),
132
167
  ...(opts.instruction !== undefined ? { instruction: opts.instruction } : {}),
168
+ ...(opts.testIdAttributes !== undefined ? { testIdAttributes: opts.testIdAttributes } : {}),
133
169
  };
134
170
  const client = makeClient(opts, deps);
135
- const rawCreated = await client.post('/projects', {
136
- body,
137
- headers: { 'idempotency-key': idempotencyKey },
138
- });
171
+ let rawCreated;
172
+ try {
173
+ rawCreated = await client.post('/projects', {
174
+ body,
175
+ headers: { 'idempotency-key': idempotencyKey },
176
+ });
177
+ }
178
+ catch (err) {
179
+ throw translateUnsupportedTestIdAttributes(err, body.testIdAttributes !== undefined);
180
+ }
139
181
  // Normalize whichever id field name the backend actually
140
182
  // sent onto BOTH `projectId` and `id`, so JSON consumers keyed on either
141
183
  // name keep working regardless of which one the live response used.
@@ -209,7 +251,14 @@ export async function runUpdate(opts, deps = {}) {
209
251
  }
210
252
  // P2-7: guard --url against localhost/RFC1918/non-http(s).
211
253
  if (opts.targetUrl !== undefined) {
212
- assertNotLocal(opts.targetUrl);
254
+ assertNotLocal(opts.targetUrl, {
255
+ field: 'url',
256
+ helpCommand: 'testsprite project update',
257
+ hintContext: 'bootstrap',
258
+ });
259
+ }
260
+ if (opts.testIdAttributes !== undefined && opts.clearTestIdAttributes) {
261
+ throw localValidationError('--test-id-attributes and --clear-test-id-attributes are mutually exclusive.');
213
262
  }
214
263
  const passwordSupplied = opts.password !== undefined || opts.passwordFile !== undefined;
215
264
  const mutableFields = {
@@ -218,12 +267,14 @@ export async function runUpdate(opts, deps = {}) {
218
267
  username: opts.username !== undefined,
219
268
  password: passwordSupplied,
220
269
  instruction: opts.instruction !== undefined,
270
+ testIdAttributes: opts.testIdAttributes !== undefined || opts.clearTestIdAttributes === true,
221
271
  };
222
272
  const presentFieldNames = Object.entries(mutableFields)
223
273
  .filter(([, present]) => present)
224
274
  .map(([field]) => field);
225
275
  if (presentFieldNames.length === 0) {
226
- throw localValidationError('At least one mutable flag is required: --name, --url, --username, --password/--password-file, or --instruction.');
276
+ throw localValidationError('At least one mutable flag is required: --name, --url, --username, --password/--password-file, ' +
277
+ '--instruction, --test-id-attributes, or --clear-test-id-attributes.');
227
278
  }
228
279
  if (opts.dryRun) {
229
280
  // DEV-247: emit the banner here (this path returns before makeClient() does).
@@ -261,13 +312,21 @@ export async function runUpdate(opts, deps = {}) {
261
312
  username: opts.username,
262
313
  password,
263
314
  instruction: opts.instruction,
315
+ // `null` clears the list server-side (same convention as `test update --clear-step-timeout`).
316
+ testIdAttributes: opts.clearTestIdAttributes ? null : opts.testIdAttributes,
264
317
  };
265
318
  const body = Object.fromEntries(Object.entries(bodyFields).filter(([, v]) => v !== undefined));
266
319
  const client = makeClient(opts, deps);
267
- const rawUpdated = await client.patch(`/projects/${encodeURIComponent(opts.projectId)}`, {
268
- body,
269
- headers: { 'idempotency-key': idempotencyKey },
270
- });
320
+ let rawUpdated;
321
+ try {
322
+ rawUpdated = await client.patch(`/projects/${encodeURIComponent(opts.projectId)}`, {
323
+ body,
324
+ headers: { 'idempotency-key': idempotencyKey },
325
+ });
326
+ }
327
+ catch (err) {
328
+ throw translateUnsupportedTestIdAttributes(err, 'testIdAttributes' in body);
329
+ }
271
330
  // Normalize whichever id field name the backend actually
272
331
  // sent onto BOTH `projectId` and `id`, so JSON consumers keyed on either
273
332
  // name keep working regardless of which one the live response used.
@@ -750,7 +809,10 @@ function assertSafePresignedUploadUrl(uploadUrl, facadeBaseUrl) {
750
809
  * is `isLoopbackFacade`). */
751
810
  function isLocalUrl(url) {
752
811
  try {
753
- assertNotLocal(url);
812
+ assertNotLocal(url, {
813
+ field: 'upload-url',
814
+ helpCommand: 'testsprite project docs upload',
815
+ });
754
816
  return false;
755
817
  }
756
818
  catch {
@@ -882,6 +944,8 @@ export function createProjectCommand(deps = {}) {
882
944
  .option('--password <pw>', 'optional auth password (use --password-file for non-interactive)')
883
945
  .option('--password-file <path>', 'read password from file instead of inline flag')
884
946
  .option('--instruction <text>', 'optional FE plan-gen instruction hint')
947
+ .option('--test-id-attributes <list>', 'comma-separated DOM attributes the engine should prefer as locators, highest priority first ' +
948
+ '(e.g. data-element,data-testid). Unique values are exported as page.locator(\'[attr="…"]\').')
885
949
  .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
886
950
  .addHelpText('after', GLOBAL_OPTS_HINT)
887
951
  .action(async (cmdOpts, command) => {
@@ -906,6 +970,9 @@ export function createProjectCommand(deps = {}) {
906
970
  password: cmdOpts.password,
907
971
  passwordFile: cmdOpts.passwordFile,
908
972
  instruction: cmdOpts.instruction,
973
+ testIdAttributes: cmdOpts.testIdAttributes !== undefined
974
+ ? parseTestIdAttributesFlag(cmdOpts.testIdAttributes, 'test-id-attributes')
975
+ : undefined,
909
976
  idempotencyKey: cmdOpts.idempotencyKey,
910
977
  }, deps);
911
978
  });
@@ -918,6 +985,9 @@ export function createProjectCommand(deps = {}) {
918
985
  .option('--password <pw>', 'new auth password')
919
986
  .option('--password-file <path>', 'read new password from file')
920
987
  .option('--instruction <text>', 'new FE plan-gen instruction hint')
988
+ .option('--test-id-attributes <list>', 'comma-separated DOM attributes the engine should prefer as locators, highest priority first ' +
989
+ '(e.g. data-element,data-testid); replaces the current list')
990
+ .option('--clear-test-id-attributes', 'remove the test-id attribute list (engine falls back to data-testid)', false)
921
991
  .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
922
992
  .addHelpText('after', GLOBAL_OPTS_HINT)
923
993
  .action(async (projectId, cmdOpts, command) => {
@@ -930,6 +1000,10 @@ export function createProjectCommand(deps = {}) {
930
1000
  password: cmdOpts.password,
931
1001
  passwordFile: cmdOpts.passwordFile,
932
1002
  instruction: cmdOpts.instruction,
1003
+ testIdAttributes: cmdOpts.testIdAttributes !== undefined
1004
+ ? parseTestIdAttributesFlag(cmdOpts.testIdAttributes, 'test-id-attributes')
1005
+ : undefined,
1006
+ clearTestIdAttributes: cmdOpts.clearTestIdAttributes,
933
1007
  idempotencyKey: cmdOpts.idempotencyKey,
934
1008
  }, deps);
935
1009
  });
@@ -1181,6 +1255,12 @@ function renderProjectText(p) {
1181
1255
  ? `targetUrl: ${p.targetUrl}`
1182
1256
  : `targetUrl: (not set — set one with: testsprite project update ${p.id} --url <url>)`);
1183
1257
  }
1258
+ // Presence-keyed like targetUrl: older backends don't report the field at all.
1259
+ if ('testIdAttributes' in p) {
1260
+ lines.push(p.testIdAttributes && p.testIdAttributes.length > 0
1261
+ ? `testIdAttrs: ${p.testIdAttributes.join(', ')} (locator priority, highest first)`
1262
+ : `testIdAttrs: (not set — engine default data-testid; set with: testsprite project update ${p.id} --test-id-attributes <list>)`);
1263
+ }
1184
1264
  return lines.join('\n');
1185
1265
  }
1186
1266
  /**
@@ -1227,6 +1307,32 @@ function requireDocsProjectId(projectId, deps) {
1227
1307
  return envValue;
1228
1308
  throw localValidationError('--project <id> is required; pass --project <id> or set TESTSPRITE_PROJECT_ID');
1229
1309
  }
1310
+ /**
1311
+ * A backend that predates the testIdAttributes field answers a PATCH/POST that
1312
+ * carries it with a generic 400 whose `details.accepted` list omits the field
1313
+ * ("at least one field must be provided …" — misleading, since a field WAS
1314
+ * provided). Translate that into an honest UNSUPPORTED so the user learns the
1315
+ * real cause instead of re-reading their own command.
1316
+ */
1317
+ function translateUnsupportedTestIdAttributes(err, sentTestIdAttributes) {
1318
+ if (!sentTestIdAttributes || !(err instanceof ApiError) || err.code !== 'VALIDATION_ERROR')
1319
+ return err;
1320
+ const accepted = err.details?.accepted;
1321
+ if (!Array.isArray(accepted) || accepted.includes('testIdAttributes'))
1322
+ return err;
1323
+ return ApiError.fromEnvelope({
1324
+ error: {
1325
+ code: 'UNSUPPORTED',
1326
+ message: 'This backend does not support test-id attributes yet.',
1327
+ nextAction: 'The server accepted fields: ' +
1328
+ accepted.join(', ') +
1329
+ '. `--test-id-attributes` / `--clear-test-id-attributes` need a backend that knows the ' +
1330
+ '`testIdAttributes` field; retry once it is deployed, or drop the flag.',
1331
+ requestId: err.requestId,
1332
+ details: { reason: 'test_id_attributes_unsupported_backend', accepted },
1333
+ },
1334
+ });
1335
+ }
1230
1336
  function localValidationError(message) {
1231
1337
  return ApiError.fromEnvelope({
1232
1338
  error: {
@@ -2,12 +2,12 @@ import { Command } from 'commander';
2
2
  import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
3
3
  import { type WriteBundleResult } from '../lib/bundle.js';
4
4
  import { type JUnitReportFormat, type JUnitTestResult } from '../lib/junit-report.js';
5
- import { ApiError } from '../lib/errors.js';
5
+ import { ApiError, InterruptError } from '../lib/errors.js';
6
6
  import { type ShutdownHandle } from '../lib/interrupt.js';
7
7
  import type { FetchImpl } from '../lib/http.js';
8
8
  import { type Page } from '../lib/pagination.js';
9
9
  import type { CliGetPlansResponse } from '../lib/plans.types.js';
10
- import type { RunResponse, TriggerRunResponse, RerunResponse, BatchRerunResponse, ListRunsResponse, RunSource, BatchRunFreshResponse, CancelRunResponse } from '../lib/runs.types.js';
10
+ import type { RunResponse, RunStatus, TriggerRunResponse, RerunResponse, BatchRerunResponse, ListRunsResponse, RunSource, BatchRunFreshResponse, CancelRunResponse } from '../lib/runs.types.js';
11
11
  import { type LoopbackHost } from '../lib/local-target.js';
12
12
  import { type TunnelClientHandle } from '../lib/tunnel-session.js';
13
13
  import { type TunnelClientOptions } from '../vendor/tunnel-client/index.js';
@@ -59,6 +59,12 @@ export interface CliTest {
59
59
  * count after a `test plan put --expected-step-count` 412.
60
60
  */
61
61
  planStepCount?: number | null;
62
+ /**
63
+ * Full FE plan steps when the single-test read endpoint provides them.
64
+ * Optional/nullable for older backends and test types without plan steps;
65
+ * JSON output preserves the wire objects unchanged.
66
+ */
67
+ planSteps?: CliPlanStep[] | null;
62
68
  /**
63
69
  * M2.1: structured `processingStatus` / `testStatus` pair plus the
64
70
  * deprecated `rawStatus` mirror. Pre-M2.1 servers may still emit
@@ -341,14 +347,37 @@ export interface TestDeps {
341
347
  */
342
348
  createTunnelClient?: (options: TunnelClientOptions) => TunnelClientHandle;
343
349
  }
350
+ /**
351
+ * How a `--local` run's wait ended while the run was still non-terminal.
352
+ * `tunnel-lost` is the one that is not a detach at all — it is the tunnel
353
+ * dying under a run that is otherwise fine.
354
+ */
355
+ export type TunnelDetachReason = 'interrupt' | 'timeout' | 'request-timeout' | 'rate-limited' | 'tunnel-lost' | 'poll-error';
344
356
  /** What happened when we tried to stop a doomed tunnel run. */
345
357
  export type TunnelCancelOutcome = 'cancelled' | 'already-terminal' | 'failed' | 'skipped';
358
+ export interface TunnelDetach {
359
+ runId: string;
360
+ testId: string;
361
+ localPort: number;
362
+ reason: TunnelDetachReason;
363
+ cancel: TunnelCancelOutcome;
364
+ terminalStatus?: RunStatus;
365
+ }
346
366
  /** Tunnel-specific interrupt outcome consumed by the top-level JSON renderer. */
347
367
  export interface TunnelInterruptDetach {
348
368
  runId: string;
349
369
  cancel: TunnelCancelOutcome;
350
370
  nextAction: string;
351
371
  }
372
+ /**
373
+ * The stderr line for a tunnel run whose wait is ending.
374
+ *
375
+ * Deliberately NOT built from `stillRunningAndBillingSubject`: that sentence
376
+ * is true for an ordinary run and false here, and the whole point of D1 (a)
377
+ * is that the four detach paths stop telling a tunnel user something untrue.
378
+ */
379
+ export declare function tunnelDetachMessage(detach: TunnelDetach, interrupt?: InterruptError): string;
380
+ export declare function tunnelInterruptNextAction(detach: TunnelDetach, err: InterruptError): string;
352
381
  type CommonOptions = FactoryCommonOptions;
353
382
  interface ListOptions extends CommonOptions {
354
383
  projectId?: string;
@@ -716,7 +745,7 @@ export interface CliCreateFromPlanResponse extends CliCreateTestResponse {
716
745
  * Caveat: the pinned tag only resolves once that version is actually
717
746
  * released — a locally-built/pre-release checkout may see a 404 until then.
718
747
  */
719
- export declare const PLAN_SCHEMA_URL = "https://raw.githubusercontent.com/TestSprite/testsprite-cli/v0.8.0/schemas/plan.schema.json";
748
+ export declare const PLAN_SCHEMA_URL = "https://raw.githubusercontent.com/TestSprite/testsprite-cli/v0.10.0/schemas/plan.schema.json";
720
749
  /**
721
750
  * The SINGLE canonical example plan. This
722
751
  * exact value (via `PLAN_TEMPLATE_TEXT` below) is:
@@ -93,6 +93,54 @@ function stillRunningAndBillingSubject(runIds) {
93
93
  ? `Run ${ids[0]} is still executing on the server and will keep running (and billing) until it finishes.`
94
94
  : `${ids.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
95
95
  }
96
+ const TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE = 'Passing --no-cancel-on-interrupt keeps the run executing without its tunnel; it cannot ' +
97
+ 'reach your app and is still billed.';
98
+ function tunnelRerunCommand(detach) {
99
+ return `testsprite test run ${detach.testId} --local ${detach.localPort}`;
100
+ }
101
+ /** Minimum wall-clock gap between adopted-client liveness reads. */
102
+ const BORROWED_TUNNEL_LIVENESS_INTERVAL_MS = 15_000;
103
+ /**
104
+ * Build the adopted-tunnel liveness observation that runs on non-terminal
105
+ * poll ticks. The first tick reads immediately; later ticks share one
106
+ * wall-clock cadence regardless of how hot the run-poll loop is.
107
+ *
108
+ * Only two observations are conclusive: an explicit offline response and a
109
+ * 404. Every inability to read the state is unknown rather than dead, because
110
+ * declaring a borrowed tunnel lost on our own network/backend failure would
111
+ * turn an observation outage into a false run failure.
112
+ */
113
+ function makeBorrowedTunnelLivenessCheck(args) {
114
+ let lastCheckAtMs;
115
+ return async (signal) => {
116
+ const now = Date.now();
117
+ if (lastCheckAtMs !== undefined && now - lastCheckAtMs < BORROWED_TUNNEL_LIVENESS_INTERVAL_MS) {
118
+ return;
119
+ }
120
+ // Record the attempt before awaiting it so retries belong to the next
121
+ // interval even when this read fails or stalls until its deadline.
122
+ lastCheckAtMs = now;
123
+ let dead;
124
+ try {
125
+ const observed = await args.client.getTunnelStatus(args.clientId, {
126
+ signal,
127
+ // This observation owns its 15-second cadence. A 5xx, 429, timeout,
128
+ // or network failure is unknown and must wait for the next interval.
129
+ retry: false,
130
+ });
131
+ // The Rust service has emitted title-cased values (notably "Online")
132
+ // in production before; status comparisons must therefore ignore case.
133
+ dead = observed.status.toLowerCase() === 'offline';
134
+ }
135
+ catch (err) {
136
+ // The HTTP observation is authoritative here. Even a malformed 5xx
137
+ // envelope carrying NOT_FOUND is still an unknown server-side read.
138
+ dead = err instanceof ApiError && err.httpStatus === 404;
139
+ }
140
+ if (dead)
141
+ throw new TunnelLostError('owner-gone', args.runId);
142
+ };
143
+ }
96
144
  /**
97
145
  * Stop a tunnel run that can no longer succeed.
98
146
  *
@@ -100,9 +148,9 @@ function stillRunningAndBillingSubject(runIds) {
100
148
  * non-terminal. Unlike an ordinary run — where DEV-331 deliberately decided a
101
149
  * Ctrl-C detaches and leaves the run to finish — a tunnel run's target lives
102
150
  * behind a tunnel this process is holding open, so the moment we exit the
103
- * Lambda's browser starts getting connection failures. Leaving it running
104
- * bills the user for a guaranteed failure, which is exactly the case
105
- * `--cancel-on-interrupt` was scoped for.
151
+ * Lambda's browser can start getting connection failures. The run may already
152
+ * have completed or been billed, so the cancellation message states only the
153
+ * observed cancel outcome and the cancelled-verdict semantics.
106
154
  *
107
155
  * The cancel is issued through a DETACHED client: the normal one composes the
108
156
  * process shutdown signal into every fetch, and on the interrupt path that
@@ -135,10 +183,17 @@ async function cancelDoomedTunnelRun(args) {
135
183
  * is true for an ordinary run and false here, and the whole point of D1 (a)
136
184
  * is that the four detach paths stop telling a tunnel user something untrue.
137
185
  */
138
- function tunnelDetachMessage(detach) {
186
+ export function tunnelDetachMessage(detach, interrupt) {
139
187
  const { runId, reason, cancel } = detach;
188
+ if (reason === 'interrupt' && cancel === 'cancelled') {
189
+ return (`Interrupted${interrupt ? ` by ${interrupt.signal}` : ''}. Run ${runId} was reaching your ` +
190
+ `machine through a tunnel that closes with this process, so it was cancelled (exit ` +
191
+ `${interrupt?.exitCode ?? 130}). The run may already have been billed; a cancelled run's ` +
192
+ `verdict is discarded. Start a new run with: ${tunnelRerunCommand(detach)}. ` +
193
+ TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE);
194
+ }
140
195
  const cause = {
141
- interrupt: 'Interrupted',
196
+ interrupt: `Interrupted${interrupt ? ` by ${interrupt.signal}` : ''}`,
142
197
  timeout: `Timed out waiting for run ${runId}`,
143
198
  'request-timeout': 'Request timed out',
144
199
  'rate-limited': 'Rate limited by the server (HTTP 429)',
@@ -148,17 +203,19 @@ function tunnelDetachMessage(detach) {
148
203
  const doom = reason === 'tunnel-lost'
149
204
  ? `Run ${runId} was reaching your machine through that tunnel, and the run's proxy credential ` +
150
205
  `names the client that just went away, so it cannot be restored for this run.`
151
- : `Run ${runId} was reaching your machine through a tunnel that closes with this process, so ` +
152
- `it cannot finish.`;
206
+ : `Run ${runId} was reaching your machine through a tunnel that closes with this process.`;
153
207
  const outcome = {
154
- cancelled: ' Cancelled it, so no further credits are spent on a guaranteed failure.',
208
+ cancelled: " Cancelled it. The run may already have been billed; a cancelled run's verdict is discarded.",
155
209
  'already-terminal': ' It had already finished server-side; there was nothing to cancel.',
156
210
  failed: ` Could NOT cancel it from here — stop it with: testsprite test cancel ${runId}`,
157
- skipped: ` Left it running (--no-cancel-on-interrupt); stop it with: testsprite test cancel ${runId}`,
211
+ skipped: ` It was not cancelled — stop it now with: testsprite test cancel ${runId}`,
158
212
  };
159
- return (`${cause[reason]}. ${doom}\n` +
213
+ const message = `${cause[reason]}. ${doom}\n` +
160
214
  `${outcome[cancel]}\n` +
161
- ` Start it again with --local when you're ready; a retry mints a fresh tunnel.`);
215
+ ` Start a new run with: ${tunnelRerunCommand(detach)}.`;
216
+ return cancel === 'cancelled' || cancel === 'skipped'
217
+ ? `${message}\n ${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE}`
218
+ : message;
162
219
  }
163
220
  /**
164
221
  * The `hint` lines under a partial run envelope.
@@ -187,28 +244,32 @@ function detachPartialStatus(detach) {
187
244
  return 'cancelled';
188
245
  return detach.terminalStatus ?? 'running';
189
246
  }
190
- function tunnelInterruptNextAction(detach) {
247
+ export function tunnelInterruptNextAction(detach, err) {
248
+ const rerun = tunnelRerunCommand(detach);
191
249
  if (detach.cancel === 'cancelled') {
192
- return (`Run ${detach.runId} was cancelled and its tunnel was closed. ` +
193
- 'Start it again with --local when you are ready.');
250
+ return (`Run ${detach.runId} was cancelled after ${err.signal} (exit ${err.exitCode}) and its ` +
251
+ `tunnel was closed. ` +
252
+ "The run may already have been billed; a cancelled run's verdict is discarded. " +
253
+ `Start a new run with: ${rerun}. ${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE}`);
194
254
  }
195
255
  if (detach.cancel === 'already-terminal') {
196
256
  return (`Run ${detach.runId} had already finished` +
197
257
  (detach.terminalStatus ? ` with status ${detach.terminalStatus}` : '') +
198
- '; its tunnel was closed. Start a new --local run if you need to test again.');
258
+ ` when ${err.signal} interrupted the wait; its tunnel was closed. Start a new run with: ` +
259
+ `${rerun}.`);
199
260
  }
200
261
  if (detach.cancel === 'skipped') {
201
- return (`The tunnel for run ${detach.runId} was closed, but cancellation was disabled. ` +
202
- `Stop the run with: testsprite test cancel ${detach.runId}; then start it again with --local.`);
262
+ return (`Start a new run with: ${rerun}, after stopping run ${detach.runId} with: testsprite test ` +
263
+ `cancel ${detach.runId}. ${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE}`);
203
264
  }
204
- return (`The tunnel for run ${detach.runId} was closed and automatic cancellation failed. ` +
205
- `Stop the run with: testsprite test cancel ${detach.runId}; then start it again with --local.`);
265
+ return (`Start a new run with: ${rerun}, after stopping run ${detach.runId} with: testsprite test ` +
266
+ `cancel ${detach.runId}; automatic cancellation after ${err.signal} failed.`);
206
267
  }
207
268
  function attachTunnelInterruptDetach(err, detach) {
208
269
  err.tunnelDetach = {
209
270
  runId: detach.runId,
210
271
  cancel: detach.cancel,
211
- nextAction: tunnelInterruptNextAction(detach),
272
+ nextAction: tunnelInterruptNextAction(detach, err),
212
273
  };
213
274
  }
214
275
  const TEST_TYPES = ['frontend', 'backend'];
@@ -506,7 +567,11 @@ export async function runCreate(opts, deps = {}) {
506
567
  body.category = opts.category;
507
568
  }
508
569
  if (opts.targetUrl !== undefined) {
509
- assertNotLocal(opts.targetUrl);
570
+ assertNotLocal(opts.targetUrl, {
571
+ field: 'target-url',
572
+ helpCommand: 'testsprite test create',
573
+ hintContext: 'bootstrap',
574
+ });
510
575
  }
511
576
  // C1: --target-url is inert for backend tests (base URL is baked into the
512
577
  // test code; the backend sandbox never receives targetUrl). Emit a
@@ -1690,7 +1755,11 @@ export async function runCreateFromPlan(opts, deps = {}) {
1690
1755
  assertChainedRunKeyFits(opts.run, opts.idempotencyKey);
1691
1756
  requireNonEmpty('plan-from', opts.planFrom);
1692
1757
  if (opts.targetUrl !== undefined) {
1693
- assertNotLocal(opts.targetUrl);
1758
+ assertNotLocal(opts.targetUrl, {
1759
+ field: 'target-url',
1760
+ helpCommand: 'testsprite test create',
1761
+ hintContext: 'bootstrap',
1762
+ });
1694
1763
  }
1695
1764
  const plan = readPlanFromGuarded(opts.planFrom, { ignoredFlags: opts.ignoredFlags });
1696
1765
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
@@ -2087,7 +2156,11 @@ export async function runCreateBatch(opts, deps = {}) {
2087
2156
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
2088
2157
  }
2089
2158
  if (opts.targetUrl !== undefined) {
2090
- assertNotLocal(opts.targetUrl);
2159
+ assertNotLocal(opts.targetUrl, {
2160
+ field: 'target-url',
2161
+ helpCommand: 'testsprite test create-batch',
2162
+ hintContext: 'bootstrap',
2163
+ });
2091
2164
  }
2092
2165
  const stderrFnEarly = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2093
2166
  const specs = opts.planFromDir !== undefined && opts.planFromDir !== ''
@@ -4612,6 +4685,11 @@ function renderTriggerRunText(r) {
4612
4685
  lines.push(`codeVersion ${r.codeVersion}`);
4613
4686
  if (r.targetUrl !== null)
4614
4687
  lines.push(`targetUrl ${r.targetUrl}`);
4688
+ // Same line the run card prints after `--wait` (`renderRunResponseText`), so a
4689
+ // bare `test run <id>` shows where to look without a second command. Only
4690
+ // when the server sent one — absent means it had no correct link to give.
4691
+ if (r.dashboardUrl)
4692
+ lines.push(`dashboard ${r.dashboardUrl}`);
4615
4693
  return lines.join('\n');
4616
4694
  }
4617
4695
  /**
@@ -4668,7 +4746,11 @@ export async function runTestRun(opts, deps = {}) {
4668
4746
  'fail. Remove --local, or let the command wait');
4669
4747
  }
4670
4748
  if (opts.targetUrl !== undefined) {
4671
- assertNotLocal(opts.targetUrl);
4749
+ assertNotLocal(opts.targetUrl, {
4750
+ field: 'target-url',
4751
+ helpCommand: 'testsprite test run',
4752
+ hintContext: 'runtime',
4753
+ });
4672
4754
  }
4673
4755
  const localHost = opts.localHost ?? DEFAULT_LOCAL_HOST;
4674
4756
  const localTargetUrl = opts.localPort !== undefined ? buildLocalTargetUrl(localHost, opts.localPort) : undefined;
@@ -4963,7 +5045,7 @@ export async function runTestRun(opts, deps = {}) {
4963
5045
  // Backend-test fallback (dogfood L1888): BE run rows never finalize, so
4964
5046
  // resolve the verdict from the testId record once it's terminal.
4965
5047
  let beFallbackUsed = false;
4966
- const resolveAlternate = makeBackendWaitFallback({
5048
+ const resolveBackendAlternate = makeBackendWaitFallback({
4967
5049
  client,
4968
5050
  resolveTestId: () => opts.testId,
4969
5051
  resolveNotBefore: () => triggerResponse.enqueuedAt,
@@ -4974,6 +5056,26 @@ export async function runTestRun(opts, deps = {}) {
4974
5056
  `Read full detail with: testsprite test result ${testId}`);
4975
5057
  },
4976
5058
  });
5059
+ const checkBorrowedTunnelLiveness = tunnelSession?.adopted
5060
+ ? makeBorrowedTunnelLivenessCheck({
5061
+ // Liveness failures are deliberately silent even under --verbose or
5062
+ // --debug: they are unknown observations, not user-facing events.
5063
+ client: makeClient({ ...clientOpts, debug: false, verbose: false }, { ...deps, stderr: () => { } }),
5064
+ clientId: tunnelSession.clientId,
5065
+ runId: triggerResponse.runId,
5066
+ })
5067
+ : undefined;
5068
+ // `resolveAlternate` is called only after a non-terminal run tick. Keeping
5069
+ // the async borrowed-client read here prevents terminal runs from paying an
5070
+ // extra GET and ensures any conclusive loss is caught by this command's
5071
+ // normal detach/teardown path. Owned runs receive the original callback
5072
+ // object unchanged and issue no liveness request.
5073
+ const resolveAlternate = checkBorrowedTunnelLiveness === undefined
5074
+ ? resolveBackendAlternate
5075
+ : async (run, elapsedMs, signal) => {
5076
+ await checkBorrowedTunnelLiveness(signal);
5077
+ return resolveBackendAlternate(run, elapsedMs, signal);
5078
+ };
4977
5079
  // Keeps the elapsed counter moving between long-poll returns (~25s apart).
4978
5080
  // Armed only when the ticker redraws in place (its own TTY / NO_COLOR call).
4979
5081
  const live = createLiveRunProgress(ticker);
@@ -5019,6 +5121,8 @@ export async function runTestRun(opts, deps = {}) {
5019
5121
  });
5020
5122
  return {
5021
5123
  runId: triggerResponse.runId,
5124
+ testId: opts.testId,
5125
+ localPort: opts.localPort,
5022
5126
  reason,
5023
5127
  cancel: cancel.outcome,
5024
5128
  ...(cancel.terminalStatus !== undefined ? { terminalStatus: cancel.terminalStatus } : {}),
@@ -5183,7 +5287,7 @@ export async function runTestRun(opts, deps = {}) {
5183
5287
  return lines.join('\n');
5184
5288
  });
5185
5289
  stderrFn(detach
5186
- ? tunnelDetachMessage(detach)
5290
+ ? tunnelDetachMessage(detach, err)
5187
5291
  : interruptDetachMessage(err, [triggerResponse.runId]));
5188
5292
  if (detach !== undefined)
5189
5293
  attachTunnelInterruptDetach(err, detach);
@@ -6022,7 +6126,10 @@ export async function runTestRunAll(opts, deps = {}) {
6022
6126
  // Both stay undefined for unknown API hosts (resolvePortalBase contract).
6023
6127
  const batchApiUrl = resolveApiUrl(opts, deps);
6024
6128
  const batchPortalBase = resolvePortalBase(batchApiUrl);
6025
- const projectDashboardUrl = batchPortalBase === undefined
6129
+ // The project-level closing link is resolved AFTER the trigger (below): the
6130
+ // server now carries it for a V3-served batch, and `resolveDashboardUrl`'s
6131
+ // absent-vs-present rule decides whether this legacy template still applies.
6132
+ const legacyProjectDashboardUrl = () => batchPortalBase === undefined
6026
6133
  ? undefined
6027
6134
  : `${batchPortalBase}/dashboard/tests/${encodeURIComponent(projectId)}`;
6028
6135
  const withBatchDashboardUrl = (item) => {
@@ -6089,6 +6196,13 @@ export async function runTestRunAll(opts, deps = {}) {
6089
6196
  ...(testIds !== undefined ? { testIds } : {}),
6090
6197
  source: 'cli',
6091
6198
  }, { idempotencyKey });
6199
+ // Project-level "watch it here" link. A V3 backend sends it (string, or
6200
+ // `null` when no single page exists — e.g. a `--all` that fanned out over
6201
+ // several sibling projects); an older backend / the V2 engine omits the key,
6202
+ // and only then does the client's legacy `/dashboard/tests/{projectId}`
6203
+ // template apply — for a V3 reader that shape bounced onto a route that does
6204
+ // not exist, which is why the server took it over.
6205
+ const { dashboardUrl: projectDashboardUrl } = resolveDashboardUrl(batchResp, legacyProjectDashboardUrl);
6092
6206
  // Mutable: D3 deferred-retry loop may append to `accepted`, drain `deferred`,
6093
6207
  // and accumulate additional `conflicts` discovered during retries.
6094
6208
  let accepted = batchResp.accepted.slice();
@@ -6888,6 +7002,8 @@ export async function runTestRerun(opts, deps = {}) {
6888
7002
  if (r.closure) {
6889
7003
  lines.push(`closure ${r.closure.members.length} members (${r.closure.addedProducers.length} producers added)`);
6890
7004
  }
7005
+ if (r.dashboardUrl)
7006
+ lines.push(`dashboard ${r.dashboardUrl}`);
6891
7007
  return lines.join('\n');
6892
7008
  });
6893
7009
  return rerunResp;
@@ -9530,8 +9646,20 @@ function renderTestText(t) {
9530
9646
  // M3.4: surface plan-step count when the facade ships it (FE tests).
9531
9647
  // Lets an operator read the current count — e.g. to recover after a
9532
9648
  // `test plan put --expected-step-count` 412 — without a JSON round-trip.
9533
- if (typeof t.planStepCount === 'number') {
9534
- lines.push(`planSteps: ${t.planStepCount}`);
9649
+ const planSteps = Array.isArray(t.planSteps) ? t.planSteps : undefined;
9650
+ const planStepCount = typeof t.planStepCount === 'number' ? t.planStepCount : planSteps?.length;
9651
+ if (typeof planStepCount === 'number') {
9652
+ lines.push(`planSteps: ${planStepCount}`);
9653
+ }
9654
+ if (planSteps) {
9655
+ planSteps.forEach((step, index) => {
9656
+ if (typeof step !== 'object' || step === null)
9657
+ return;
9658
+ const fields = step;
9659
+ const type = typeof fields.type === 'string' ? fields.type : 'step';
9660
+ const description = typeof fields.description === 'string' ? fields.description : '(no description)';
9661
+ lines.push(` ${index + 1}. [${type}] ${description}`);
9662
+ });
9535
9663
  }
9536
9664
  if (typeof t.stepTimeoutMs === 'number') {
9537
9665
  lines.push(`stepTimeout: ${t.stepTimeoutMs} ms (applies to every step)`);