@testsprite/testsprite-cli 0.13.0 → 0.15.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.
Files changed (81) hide show
  1. package/README.md +54 -49
  2. package/dist/commands/ci.d.ts +66 -17
  3. package/dist/commands/ci.js +466 -104
  4. package/dist/commands/doctor.d.ts +3 -0
  5. package/dist/commands/doctor.js +62 -20
  6. package/dist/commands/init.js +17 -3
  7. package/dist/commands/project-env.d.ts +11 -1
  8. package/dist/commands/project-env.js +399 -61
  9. package/dist/commands/project-sign-in.d.ts +60 -0
  10. package/dist/commands/project-sign-in.js +289 -0
  11. package/dist/commands/project.d.ts +9 -0
  12. package/dist/commands/project.js +82 -28
  13. package/dist/commands/schedule.d.ts +12 -0
  14. package/dist/commands/schedule.js +175 -5
  15. package/dist/commands/test.d.ts +126 -30
  16. package/dist/commands/test.js +1928 -447
  17. package/dist/commands/testlist.d.ts +10 -5
  18. package/dist/commands/testlist.js +170 -30
  19. package/dist/commands/tunnel.js +11 -5
  20. package/dist/index.js +17 -38
  21. package/dist/lib/agent-targets.d.ts +8 -3
  22. package/dist/lib/agent-targets.js +15 -4
  23. package/dist/lib/ci-run.d.ts +11 -0
  24. package/dist/lib/ci-run.js +34 -0
  25. package/dist/lib/client-factory.d.ts +35 -1
  26. package/dist/lib/client-factory.js +21 -10
  27. package/dist/lib/config.d.ts +1 -0
  28. package/dist/lib/config.js +1 -1
  29. package/dist/lib/credentials.d.ts +0 -1
  30. package/dist/lib/credentials.js +51 -14
  31. package/dist/lib/dry-run/samples.js +95 -1
  32. package/dist/lib/environment-tunnel.d.ts +109 -0
  33. package/dist/lib/environment-tunnel.js +465 -0
  34. package/dist/lib/errors.js +12 -1
  35. package/dist/lib/first-suite-hint.d.ts +55 -0
  36. package/dist/lib/first-suite-hint.js +101 -0
  37. package/dist/lib/gh-output.d.ts +62 -4
  38. package/dist/lib/gh-output.js +152 -7
  39. package/dist/lib/github-context.d.ts +21 -0
  40. package/dist/lib/github-context.js +153 -0
  41. package/dist/lib/http.d.ts +12 -1
  42. package/dist/lib/http.js +9 -1
  43. package/dist/lib/junit-report.d.ts +11 -7
  44. package/dist/lib/junit-report.js +13 -7
  45. package/dist/lib/local-target.d.ts +13 -3
  46. package/dist/lib/local-target.js +47 -12
  47. package/dist/lib/output.js +15 -1
  48. package/dist/lib/plan-poll.js +3 -4
  49. package/dist/lib/plans.types.d.ts +1 -1
  50. package/dist/lib/redact.d.ts +38 -0
  51. package/dist/lib/redact.js +140 -0
  52. package/dist/lib/render-error.d.ts +19 -5
  53. package/dist/lib/render-error.js +31 -0
  54. package/dist/lib/response-schemas.d.ts +5 -1
  55. package/dist/lib/response-schemas.js +54 -0
  56. package/dist/lib/runs.types.d.ts +115 -1
  57. package/dist/lib/target-url.js +5 -5
  58. package/dist/lib/telemetry.d.ts +31 -8
  59. package/dist/lib/telemetry.js +55 -7
  60. package/dist/lib/testlist.types.d.ts +1 -0
  61. package/dist/lib/ticker.d.ts +9 -0
  62. package/dist/lib/ticker.js +18 -0
  63. package/dist/lib/tunnel-session.d.ts +3 -4
  64. package/dist/lib/tunnel-session.js +3 -4
  65. package/dist/lib/v3-advisory.js +0 -1
  66. package/dist/vendor/tunnel-client/client.d.ts +15 -8
  67. package/dist/vendor/tunnel-client/client.js +477 -407
  68. package/dist/vendor/tunnel-client/config.d.ts +5 -5
  69. package/dist/vendor/tunnel-client/config.js +5 -5
  70. package/dist/vendor/tunnel-client/index.d.ts +4 -4
  71. package/dist/vendor/tunnel-client/index.js +4 -4
  72. package/dist/vendor/tunnel-client/types.d.ts +19 -34
  73. package/dist/vendor/tunnel-client/types.js +1 -0
  74. package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
  75. package/dist/vendor/tunnel-client/ws-compat.js +70 -12
  76. package/dist/version.d.ts +1 -1
  77. package/dist/version.js +1 -1
  78. package/package.json +1 -1
  79. package/schemas/plan.schema.json +2 -2
  80. package/skills/testsprite-ci.skill.md +154 -0
  81. package/skills/testsprite-onboard.skill.md +4 -4
@@ -1,3 +1,6 @@
1
+ import { recordTelemetryTunnelOpened } from '../lib/telemetry.js';
2
+ import { parseLoopbackTargetUrl } from '../lib/local-target.js';
3
+ import { resolveEnvironmentRunTarget, readEnvironmentPreflight, ENVIRONMENT_PREFLIGHT_TIMEOUT_MS, assertNoTunnelOptions, severalIdsWithoutTunnel, quoteEnvironmentName, groupEnvironmentTargets, emitEnvironmentDispatchPartial, tunnelScopeError, withEnvironmentTunnel, } from '../lib/environment-tunnel.js';
1
4
  import { closeSync, createWriteStream, existsSync, fstatSync, openSync, readFileSync, readSync, readdirSync, statSync, } from 'node:fs';
2
5
  import { rename, stat, unlink } from 'node:fs/promises';
3
6
  import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
@@ -9,17 +12,19 @@ import { assertContextIntegrity, buildMeta, pickCodeExtension, pickVideoExtensio
9
12
  import { findSample, findSampleOrThrow, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
10
13
  import { assertJUnitReportOptions, buildJUnitReport, durationSecondsBetween, resolveBatchReportProjectId, skippedJUnitResultsFromSummary, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
11
14
  import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, isAuthCode, localValidationError, } from '../lib/errors.js';
15
+ import { emptyProjectHint, emptyProjectNextStep } from '../lib/first-suite-hint.js';
12
16
  import { globalShutdown } from '../lib/interrupt.js';
13
- import { defaultSleep } from '../lib/poll-support.js';
17
+ import { defaultSleep, sleepUnlessInterrupted } from '../lib/poll-support.js';
14
18
  import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
15
19
  import { isStandingRateLimit, REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, } from '../lib/http.js';
16
20
  import { VERSION } from '../version.js';
17
21
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
18
22
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
19
23
  import { isTerminalStatus, pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
20
- import { batchOutcomeCounts, recordBatchOutcome, recordTelemetryExtras, } from '../lib/telemetry.js';
24
+ import { batchOutcomeCounts, ciRefusalOutcome, recordBatchOutcome, recordTelemetryExtras, } from '../lib/telemetry.js';
21
25
  import { PlanGenerationTimeoutError, runGenerationLadder } from '../lib/plan-poll.js';
22
26
  import { resolveWaitFailure, waitMemberError } from '../lib/wait-exit.js';
27
+ import { resolveCiRunFailure } from '../lib/ci-run.js';
23
28
  import { RUN_SOURCES } from '../lib/runs.types.js';
24
29
  import { classifyBillingRefusal } from '../lib/billing-refusal.js';
25
30
  import { allConflictsInFlight, billingConflictLink, insufficientCreditsConflictError, isAllCreditsRefusal, isPausedRefusal, pausedConflictError, summarizeConflicts, } from '../lib/conflict-reason.js';
@@ -35,7 +40,7 @@ import { createTicker } from '../lib/ticker.js';
35
40
  import { RateThrottle } from '../lib/rate-throttle.js';
36
41
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
37
42
  import { emitTargetUrlMismatchAdvisory } from '../lib/v3-advisory.js';
38
- import { emitCiArtifacts, isNonDispatchedStatus, summarizeAcceptedPayload, summarizeSingleRun, } from '../lib/gh-output.js';
43
+ import { emitCiArtifacts, isNonDispatchedStatus, emitCiStepOutputs, reconcileExecutionReportMarkdown, summarizeAcceptedPayload, summarizeSingleRun, emitExecutionReportOutputs, } from '../lib/gh-output.js';
39
44
  import { loadConfig, resolveProfileName } from '../lib/config.js';
40
45
  import { historyRetentionNote } from '../lib/history-retention.js';
41
46
  import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
@@ -97,11 +102,22 @@ function stillRunningAndBillingSubject(runIds) {
97
102
  ? `Run ${ids[0]} is still executing on the server and will keep running (and billing) until it finishes.`
98
103
  : `${ids.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
99
104
  }
100
- const TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE = 'Passing --no-cancel-on-interrupt keeps the run executing without its tunnel; it cannot ' +
101
- 'reach your app and is still billed.';
105
+ const TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE = 'Passing --no-cancel-on-interrupt keeps the run going in the cloud, and it is still billed. ' +
106
+ 'The tunnel is closed, so steps that still need your machine will fail; the run can still ' +
107
+ 'pass if it no longer needs to load anything from your machine.';
108
+ function tunnelInterruptOptOutConsequence(detach) {
109
+ if (detach.cancel !== 'skipped')
110
+ return TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE;
111
+ return (`${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE} Check the verdict later with ` +
112
+ `testsprite test result ${detach.testId} or testsprite test wait ${detach.runId}.`);
113
+ }
102
114
  function tunnelRerunCommand(detach) {
103
- return (`testsprite test run ${detach.testId} --local ${detach.localPort}` +
104
- (detach.localHost !== DEFAULT_LOCAL_HOST ? ` --local-host ${detach.localHost}` : '') +
115
+ return (`testsprite test run ${detach.testId}` +
116
+ (detach.environment ? ` --env ${quoteEnvironmentName(detach.environment)}` : '') +
117
+ (detach.automatic
118
+ ? ''
119
+ : ` --local ${detach.localPort}` +
120
+ (detach.localHost !== DEFAULT_LOCAL_HOST ? ` --local-host ${detach.localHost}` : '')) +
105
121
  (detach.reason === 'timeout' ? ' --timeout 1800' : ''));
106
122
  }
107
123
  /** Minimum wall-clock gap between adopted-client liveness reads. */
@@ -210,7 +226,7 @@ export function tunnelDetachMessage(detach, interrupt) {
210
226
  `machine through a tunnel that closes with this process, so it was cancelled (exit ` +
211
227
  `${interrupt?.exitCode ?? 130}). The run may already have been billed; a cancelled run's ` +
212
228
  `verdict is discarded. Start a new run with: ${tunnelRerunCommand(detach)}. ` +
213
- TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE);
229
+ tunnelInterruptOptOutConsequence(detach));
214
230
  }
215
231
  const cause = {
216
232
  interrupt: `Interrupted${interrupt ? ` by ${interrupt.signal}` : ''}`,
@@ -234,7 +250,7 @@ export function tunnelDetachMessage(detach, interrupt) {
234
250
  `${outcome[cancel]}\n` +
235
251
  ` Start a new run with: ${tunnelRerunCommand(detach)}.`;
236
252
  return cancel === 'cancelled' || cancel === 'skipped'
237
- ? `${message}\n ${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE}`
253
+ ? `${message}\n ${tunnelInterruptOptOutConsequence(detach)}`
238
254
  : message;
239
255
  }
240
256
  /**
@@ -273,7 +289,7 @@ export function tunnelInterruptNextAction(detach, err) {
273
289
  return (`Run ${detach.runId} was cancelled after ${err.signal} (exit ${err.exitCode}) and its ` +
274
290
  `tunnel was closed. ` +
275
291
  "The run may already have been billed; a cancelled run's verdict is discarded. " +
276
- `Start a new run with: ${rerun}. ${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE}`);
292
+ `Start a new run with: ${rerun}. ${tunnelInterruptOptOutConsequence(detach)}`);
277
293
  }
278
294
  if (detach.cancel === 'already-terminal') {
279
295
  return (`Run ${detach.runId} had already finished` +
@@ -283,7 +299,7 @@ export function tunnelInterruptNextAction(detach, err) {
283
299
  }
284
300
  if (detach.cancel === 'skipped') {
285
301
  return (`Start a new run with: ${rerun}, after stopping run ${detach.runId} with: testsprite test ` +
286
- `cancel ${detach.runId}. ${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE}`);
302
+ `cancel ${detach.runId}. ${tunnelInterruptOptOutConsequence(detach)}`);
287
303
  }
288
304
  return (`Start a new run with: ${rerun}, after stopping run ${detach.runId} with: testsprite test ` +
289
305
  `cancel ${detach.runId}; automatic cancellation after ${err.signal} failed.`);
@@ -337,9 +353,14 @@ function resolveApiUrl(opts, deps = {}) {
337
353
  return config.apiUrl;
338
354
  }
339
355
  export async function runList(opts, deps = {}) {
340
- // Keep malformed filters ahead of authentication, but check credentials
341
- // before the required project so a first-time caller sees the setup action.
356
+ // The CLI error spec (§2) puts bad input (exit 5) ahead of authentication
357
+ // (exit 3), and the filter validation below keeps that order. `--project` is
358
+ // the one deliberate exception: with no credentials at all, being sent to
359
+ // `testsprite setup` beats being told about a flag you cannot use yet, so the
360
+ // required project is checked only after the client is built. With a key
361
+ // configured, a missing `--project` still exits 5 as before.
342
362
  const projectId = resolveProjectId(opts.projectId, deps);
363
+ const environment = normalizeEnvironmentName(opts.environment);
343
364
  const paginationFlags = validatePaginationFlags({
344
365
  pageSize: opts.pageSize,
345
366
  startingToken: opts.startingToken,
@@ -365,20 +386,111 @@ export async function runList(opts, deps = {}) {
365
386
  type: opts.type,
366
387
  createdFrom: opts.createdFrom,
367
388
  status: opts.status,
389
+ ...(environment !== undefined ? { environment } : {}),
368
390
  };
369
391
  let page;
370
- if (useSinglePage) {
371
- page = await fetchSinglePage(client, '/tests', paginationFlags.pageSize, opts.startingToken, baseQuery);
392
+ try {
393
+ if (useSinglePage) {
394
+ page = await fetchSinglePage(client, '/tests', paginationFlags.pageSize, opts.startingToken, baseQuery);
395
+ }
396
+ else {
397
+ page = await paginate(async ({ pageSize, cursor }) => client.get('/tests', {
398
+ query: { ...baseQuery, pageSize, cursor },
399
+ }), paginationFlags);
400
+ }
372
401
  }
373
- else {
374
- page = await paginate(async ({ pageSize, cursor }) => client.get('/tests', {
375
- query: { ...baseQuery, pageSize, cursor },
376
- }), paginationFlags);
402
+ catch (err) {
403
+ if (err instanceof InterruptError)
404
+ throw err;
405
+ if (err instanceof ApiError &&
406
+ err.code === 'VALIDATION_ERROR' &&
407
+ err.getDetail('field') === 'environment' &&
408
+ Array.isArray(err.getDetail('available')) &&
409
+ environment !== undefined) {
410
+ const available = err.getDetail('available').filter((name) => typeof name === 'string');
411
+ if (available.length > 0 && !err.nextAction.includes(available.join(', '))) {
412
+ const hint = `Flag \`--env\` is invalid: unknown environment '${environment}'; use one of: ${available.join(', ')}.`;
413
+ throw new ApiError({
414
+ code: err.code,
415
+ message: err.message,
416
+ nextAction: err.nextAction ? `${hint} ${err.nextAction}` : hint,
417
+ requestId: err.requestId,
418
+ details: err.details,
419
+ }, err.httpStatus, err.retryAfterMs);
420
+ }
421
+ }
422
+ throw err;
423
+ }
424
+ if (environment !== undefined) {
425
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
426
+ if (opts.output === 'text' && opts.noHeader) {
427
+ stderr(`Frontend test status requested for environment '${environment}'.`);
428
+ }
429
+ if (page.items.length > 0 &&
430
+ !page.items.some(test => test.headlineEnvironment !== undefined || test.statusByEnvironment !== undefined)) {
431
+ // An older server ignores `environment` and returns unfiltered
432
+ // statuses; printing them would look like a filtered answer.
433
+ throw ApiError.fromEnvelope({
434
+ error: {
435
+ code: 'UNSUPPORTED',
436
+ message: 'This server does not support `test list --env` yet.',
437
+ nextAction: 'Run the command without --env, or retry after the server is upgraded.',
438
+ requestId: 'local',
439
+ details: {},
440
+ },
441
+ });
442
+ }
443
+ }
444
+ out.print(page, data => renderTestListText(data, {
445
+ columns: opts.columns,
446
+ noHeader: opts.noHeader,
447
+ environment,
448
+ }));
449
+ // An EMPTY project — nothing narrowed the page, no further page —
450
+ // is where a new user without a coding agent stalls. One stderr hint, text
451
+ // mode only, so stdout stays exactly "No tests." for pipes.
452
+ if (opts.output !== 'json' &&
453
+ page.items.length === 0 &&
454
+ !page.nextToken &&
455
+ opts.startingToken === undefined &&
456
+ opts.type === undefined &&
457
+ opts.createdFrom === undefined &&
458
+ opts.status === undefined) {
459
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
460
+ stderrFn(emptyProjectHint(projectId));
377
461
  }
378
- out.print(page, data => renderTestListText(data, { columns: opts.columns, noHeader: opts.noHeader }));
379
462
  return page;
380
463
  }
381
464
  export const CLI_CREATE_PRIORITIES = ['p0', 'p1', 'p2', 'p3'];
465
+ /** Priority spellings accepted as input; reads return High/Medium/Low. */
466
+ export const CLI_PRIORITY_INPUTS = [...CLI_CREATE_PRIORITIES, 'high', 'medium', 'low'];
467
+ const PRIORITY_WIRE = {
468
+ p0: 'p0',
469
+ high: 'p0',
470
+ p1: 'p1',
471
+ medium: 'p1',
472
+ p2: 'p2',
473
+ low: 'p2',
474
+ p3: 'p2',
475
+ };
476
+ /**
477
+ * Normalise a priority input (p0-p3 or high/medium/low, any case) to the
478
+ * p0/p1/p2 wire value every backend accepts; p3 folds into p2 (Low).
479
+ * Returns undefined for anything else.
480
+ */
481
+ export function normalizePriority(raw) {
482
+ if (typeof raw !== 'string')
483
+ return undefined;
484
+ const key = raw.trim().toLowerCase();
485
+ // Own-property lookup: inherited names such as `constructor` must not pass as priorities.
486
+ return Object.hasOwn(PRIORITY_WIRE, key) ? PRIORITY_WIRE[key] : undefined;
487
+ }
488
+ /** Throws the standard enum error unless `raw` is an accepted priority input. */
489
+ function assertPriorityInput(field, raw, kind = 'field') {
490
+ if (normalizePriority(raw) === undefined) {
491
+ throw localValidationError(field, `must be one of: ${CLI_PRIORITY_INPUTS.join(', ')} (case-insensitive)`, [...CLI_PRIORITY_INPUTS], kind);
492
+ }
493
+ }
382
494
  /**
383
495
  * 350 KB inline-code cap. Mirrors `MAX_INLINE_CODE_BYTES` in the backend
384
496
  * (`CliTestsController`), which is sized to fit a full test row inside
@@ -460,6 +572,59 @@ async function emitDupNameAdvisoryIfNeeded(client, projectId, name, stderrFn) {
460
572
  clearTimeout(timer);
461
573
  }
462
574
  }
575
+ async function resolveCreationTargets(opts, deps, tests) {
576
+ const targets = new Map();
577
+ if (opts.dryRun || deps.environmentTunnel)
578
+ return targets;
579
+ const client = makeClient(opts, deps);
580
+ const cache = deps.environmentCache ?? new Map();
581
+ for (const test of new Map(tests.filter(test => test.type !== 'backend').map(test => [test.projectId, test])).values()) {
582
+ const target = await resolveEnvironmentRunTarget({
583
+ client,
584
+ knownTest: test,
585
+ environment: normalizeEnvironmentName(opts.environment),
586
+ targetUrl: opts.targetUrl,
587
+ noWait: opts.noWait,
588
+ cache,
589
+ stderr: deps.stderr ?? (line => process.stderr.write(`${line}\n`)),
590
+ });
591
+ if (target)
592
+ targets.set(test.projectId, target);
593
+ }
594
+ return targets;
595
+ }
596
+ /** A late failure must retain created IDs in the command's normal result envelope. */
597
+ async function withCreatedReceipt(opts, deps, receipt, operation) {
598
+ let printed = false;
599
+ try {
600
+ return await operation({
601
+ ...deps,
602
+ stdout: line => {
603
+ printed = true;
604
+ (deps.stdout ?? (text => process.stdout.write(`${text}\n`)))(line);
605
+ },
606
+ });
607
+ }
608
+ catch (err) {
609
+ if (!printed) {
610
+ const error = err instanceof ApiError
611
+ ? { code: err.code, message: err.message, exitCode: err.exitCode, details: err.details }
612
+ : {
613
+ code: 'UNSUPPORTED',
614
+ message: err instanceof Error ? err.message : String(err),
615
+ exitCode: err instanceof CLIError ? err.exitCode : 1,
616
+ };
617
+ const data = receipt;
618
+ const payload = data.results
619
+ ? {
620
+ results: data.results.map(row => row.status === 'created' ? { ...row, status: 'error', error } : row),
621
+ }
622
+ : { ...data, run: { testId: data.testId, status: 'error', error } };
623
+ makeOutput(opts.output, deps).print(payload, () => JSON.stringify(payload));
624
+ }
625
+ throw err;
626
+ }
627
+ }
463
628
  /**
464
629
  * `test create --code-file <path>` — M3.2 piece-2 first mutation.
465
630
  *
@@ -526,11 +691,8 @@ export async function runCreate(opts, deps = {}) {
526
691
  'backend',
527
692
  ]);
528
693
  }
529
- if (opts.priority !== undefined && !CLI_CREATE_PRIORITIES.includes(opts.priority)) {
530
- throw localValidationError('priority', `must be one of: ${CLI_CREATE_PRIORITIES.join(', ')}`, [
531
- ...CLI_CREATE_PRIORITIES,
532
- ]);
533
- }
694
+ if (opts.priority !== undefined)
695
+ assertPriorityInput('priority', opts.priority);
534
696
  // M4 piece-2: --produces/--needs/--category are backend-only. FE plans have
535
697
  // no wave model; fail-fast client-side to match the backend's 400 reject and
536
698
  // save a round-trip.
@@ -574,7 +736,7 @@ export async function runCreate(opts, deps = {}) {
574
736
  type: opts.type,
575
737
  name: opts.name,
576
738
  description: opts.description,
577
- priority: opts.priority,
739
+ priority: normalizePriority(opts.priority),
578
740
  code,
579
741
  };
580
742
  if (opts.stepTimeoutMs !== undefined) {
@@ -592,7 +754,7 @@ export async function runCreate(opts, deps = {}) {
592
754
  if (opts.category !== undefined) {
593
755
  body.category = opts.category;
594
756
  }
595
- if (opts.targetUrl !== undefined) {
757
+ if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
596
758
  assertNotLocal(opts.targetUrl, {
597
759
  field: 'target-url',
598
760
  helpCommand: 'testsprite test create',
@@ -621,6 +783,7 @@ export async function runCreate(opts, deps = {}) {
621
783
  // so this exact URL is never probed twice.
622
784
  if (opts.type !== 'backend' &&
623
785
  opts.targetUrl !== undefined &&
786
+ !parseLoopbackTargetUrl(opts.targetUrl) &&
624
787
  opts.run === true &&
625
788
  !opts.dryRun) {
626
789
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
@@ -631,6 +794,13 @@ export async function runCreate(opts, deps = {}) {
631
794
  shutdown: shutdownOf(deps),
632
795
  }, stderrFn);
633
796
  }
797
+ deps = { ...deps, environmentCache: deps.environmentCache ?? new Map() };
798
+ if (opts.run && !opts.dryRun && !deps.environmentTunnel) {
799
+ const targets = await resolveCreationTargets(opts, deps, [{ type: opts.type, projectId }]);
800
+ if (targets.size) {
801
+ return withEnvironmentTunnel({ ...opts, maxConcurrency: 1, timeoutSeconds: opts.timeout ?? DEFAULT_RUN_TIMEOUT_SECONDS }, deps, [...targets.values()], 'test create --run', context => runCreate({ ...opts, idempotencyKey, wait: true, skipPreflight: true }, { ...deps, environmentTunnel: context, creationTargets: targets }));
802
+ }
803
+ }
634
804
  const client = makeClient(opts, deps);
635
805
  const out = makeOutput(opts.output, deps);
636
806
  // B3: best-effort duplicate-name advisory. Skip under --dry-run.
@@ -685,7 +855,7 @@ export async function runCreate(opts, deps = {}) {
685
855
  // `undefined` when unmapped) via `createContextWithUrl` above.
686
856
  runDashboardStderrFn(`Dashboard: ${createContextWithUrl.dashboardUrl}`);
687
857
  }
688
- await runTestRun({
858
+ await withCreatedReceipt(opts, deps, createContextWithUrl, runDeps => runTestRun({
689
859
  ...opts,
690
860
  testId: response.testId,
691
861
  idempotencyKey: runIdempotencyKey,
@@ -699,11 +869,13 @@ export async function runCreate(opts, deps = {}) {
699
869
  // Thread the known type so fast BE runs (terminal on first poll, where
700
870
  // beFallbackUsed would be false) still render `steps: n/a (backend)`.
701
871
  type: opts.type,
872
+ knownTest: { type: opts.type, projectId },
702
873
  // The preflight above (or its explicit --skip-preflight opt-out)
703
874
  // already ran against this exact URL before the create POST — never
704
875
  // probe it a second time here.
705
- skipPreflight: true,
706
- }, deps);
876
+ skipPreflight: opts.skipPreflight === true ||
877
+ (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)),
878
+ }, runDeps));
707
879
  return response;
708
880
  }
709
881
  // Emit dashboard deep-link when projectId + testId are known client-side
@@ -873,10 +1045,9 @@ const MAX_PLAN_STEPS_BODY_BYTES = 256 * 1024;
873
1045
  * trip and matches the piece-6 spec's "server-side routing" decision.
874
1046
  *
875
1047
  * Concurrency: FE has no `codeVersion`, so updates are last-writer-
876
- * wins by default. Pass `--expected-step-count <N>` to set
877
- * `If-Match-Step-Count`; the server rejects with 412 if the current
878
- * array length differs. Useful for defensive callers who want to
879
- * detect concurrent edits without a separate read.
1048
+ * wins unless `--expected-step-count <N>` is passed, which sets
1049
+ * `If-Match-Step-Count`; the server rejects with 412 if the array length
1050
+ * differs.
880
1051
  *
881
1052
  * Idempotency: `cli-plan-put-<uuid>` is the default key, surfaced to
882
1053
  * stderr so a transport retry can pin it.
@@ -919,10 +1090,25 @@ export async function runPlanPut(opts, deps = {}) {
919
1090
  },
920
1091
  }, 412);
921
1092
  }
922
- const response = await client.put(`/tests/${encodeURIComponent(opts.testId)}/plan-steps`, {
923
- body: { planSteps },
924
- headers,
925
- });
1093
+ let response;
1094
+ try {
1095
+ response = await client.put(`/tests/${encodeURIComponent(opts.testId)}/plan-steps`, {
1096
+ body: opts.force === true ? { planSteps, force: true } : { planSteps },
1097
+ headers,
1098
+ });
1099
+ }
1100
+ catch (err) {
1101
+ if (err instanceof ApiError && err.getDetail('reason') === 'structured_loss') {
1102
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1103
+ const losing = err.getDetail('losing');
1104
+ const indexes = err.getDetail('stepIndexes');
1105
+ const where = Array.isArray(indexes)
1106
+ ? ` (step ${indexes.map(i => (typeof i === 'number' ? i + 1 : String(i))).join(', ')})`
1107
+ : '';
1108
+ stderr(`${typeof losing === 'number' ? losing : 'Some'} step(s) would lose their structured fields${where}.`);
1109
+ }
1110
+ throw err;
1111
+ }
926
1112
  out.print(response, data => renderPlanPutText(data));
927
1113
  return response;
928
1114
  }
@@ -1225,11 +1411,8 @@ export async function runUpdate(opts, deps = {}) {
1225
1411
  if (opts.description !== undefined && opts.description.length > 2000) {
1226
1412
  throw localValidationError('description', 'must be at most 2000 characters');
1227
1413
  }
1228
- if (opts.priority !== undefined && !CLI_CREATE_PRIORITIES.includes(opts.priority)) {
1229
- throw localValidationError('priority', `must be one of: ${CLI_CREATE_PRIORITIES.join(', ')}`, [
1230
- ...CLI_CREATE_PRIORITIES,
1231
- ]);
1232
- }
1414
+ if (opts.priority !== undefined)
1415
+ assertPriorityInput('priority', opts.priority);
1233
1416
  if (opts.stepTimeoutMs !== undefined && opts.clearStepTimeout === true) {
1234
1417
  throw localValidationError('step-timeout', '--step-timeout and --clear-step-timeout are mutually exclusive');
1235
1418
  }
@@ -1279,7 +1462,7 @@ export async function runUpdate(opts, deps = {}) {
1279
1462
  if (hasDescription)
1280
1463
  body.description = opts.description;
1281
1464
  if (hasPriority)
1282
- body.priority = opts.priority;
1465
+ body.priority = normalizePriority(opts.priority);
1283
1466
  if (hasProduces)
1284
1467
  body.produces = opts.produces;
1285
1468
  if (hasNeeds)
@@ -1957,7 +2140,7 @@ export async function runCreateFromPlan(opts, deps = {}) {
1957
2140
  // of orphaning a created test with no run.
1958
2141
  assertChainedRunKeyFits(opts.run, opts.idempotencyKey);
1959
2142
  requireNonEmpty('plan-from', opts.planFrom);
1960
- if (opts.targetUrl !== undefined) {
2143
+ if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
1961
2144
  assertNotLocal(opts.targetUrl, {
1962
2145
  field: 'target-url',
1963
2146
  helpCommand: 'testsprite test create',
@@ -2003,7 +2186,7 @@ export async function runCreateFromPlan(opts, deps = {}) {
2003
2186
  type: plan.type,
2004
2187
  name: plan.name,
2005
2188
  description: plan.description,
2006
- priority: plan.priority,
2189
+ priority: normalizePriority(plan.priority),
2007
2190
  planSteps: plan.planSteps,
2008
2191
  };
2009
2192
  // Pre-charge reachability preflight — before the create POST
@@ -2012,7 +2195,10 @@ export async function runCreateFromPlan(opts, deps = {}) {
2012
2195
  // plans already threw above), so no type gate is needed. The delegated
2013
2196
  // `runTestRun` call in the --run chain below sets `skipPreflight: true`
2014
2197
  // so this exact URL is never probed twice.
2015
- if (opts.targetUrl !== undefined && opts.run === true && !opts.dryRun) {
2198
+ if (opts.targetUrl !== undefined &&
2199
+ !parseLoopbackTargetUrl(opts.targetUrl) &&
2200
+ opts.run === true &&
2201
+ !opts.dryRun) {
2016
2202
  await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, {
2017
2203
  fetchImpl: deps.fetchImpl,
2018
2204
  proxyActive: isProxyAgentActive(),
@@ -2020,6 +2206,15 @@ export async function runCreateFromPlan(opts, deps = {}) {
2020
2206
  shutdown: shutdownOf(deps),
2021
2207
  }, stderrFn);
2022
2208
  }
2209
+ deps = { ...deps, environmentCache: deps.environmentCache ?? new Map() };
2210
+ if (opts.run && !opts.dryRun && !deps.environmentTunnel) {
2211
+ const targets = await resolveCreationTargets(opts, deps, [
2212
+ { type: plan.type, projectId: plan.projectId },
2213
+ ]);
2214
+ if (targets.size) {
2215
+ return withEnvironmentTunnel({ ...opts, maxConcurrency: 1, timeoutSeconds: opts.timeout ?? DEFAULT_RUN_TIMEOUT_SECONDS }, deps, [...targets.values()], 'test create --run', context => runCreateFromPlan({ ...opts, idempotencyKey, wait: true, skipPreflight: true }, { ...deps, environmentTunnel: context, creationTargets: targets }));
2216
+ }
2217
+ }
2023
2218
  const client = makeClient(opts, deps);
2024
2219
  const out = makeOutput(opts.output, deps);
2025
2220
  // Fix 4: best-effort duplicate-name advisory — same semantics as runCreate.
@@ -2053,9 +2248,11 @@ export async function runCreateFromPlan(opts, deps = {}) {
2053
2248
  if (planDashboardSuppressed) {
2054
2249
  emitDashboardLinkSuppressedAdvisory(response.testId, stderrFn);
2055
2250
  }
2056
- return runTestRun({
2251
+ return withCreatedReceipt(opts, deps, responseWithDashboardUrl, runDeps => runTestRun({
2057
2252
  ...opts,
2058
2253
  testId: response.testId,
2254
+ type: plan.type,
2255
+ knownTest: { type: plan.type, projectId: plan.projectId },
2059
2256
  idempotencyKey: runIdempotencyKey,
2060
2257
  timeoutSeconds: opts.timeout ?? DEFAULT_RUN_TIMEOUT_SECONDS,
2061
2258
  // B2(c): thread through whether --timeout was explicitly set so the
@@ -2065,8 +2262,9 @@ export async function runCreateFromPlan(opts, deps = {}) {
2065
2262
  createContext: responseWithDashboardUrl,
2066
2263
  // Already preflighted above (or explicitly skipped) — don't probe
2067
2264
  // the same URL twice.
2068
- skipPreflight: true,
2069
- }, deps).then(() => response);
2265
+ skipPreflight: opts.skipPreflight === true ||
2266
+ (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)),
2267
+ }, runDeps)).then(() => response);
2070
2268
  }
2071
2269
  if (opts.output === 'json') {
2072
2270
  out.print(responseWithDashboardUrl, data => renderCreateText(data));
@@ -2203,7 +2401,7 @@ function assertPlanShape(parsed, context = {}) {
2203
2401
  throw localValidationError(`${prefix}description`, 'must be a string when present', undefined, 'field');
2204
2402
  }
2205
2403
  if (obj.priority !== undefined) {
2206
- requireEnum(`${prefix}priority`, obj.priority, CLI_CREATE_PRIORITIES);
2404
+ assertPriorityInput(`${prefix}priority`, obj.priority);
2207
2405
  }
2208
2406
  // `planSteps` missing is the single most common agent
2209
2407
  // hallucination: LLMs (Copilot included) reliably nest steps under
@@ -2267,7 +2465,7 @@ function collectPlanIssues(parsed, context = {}) {
2267
2465
  issues.push({ field: `${prefix}description`, reason: 'must be a string when present' });
2268
2466
  }
2269
2467
  if (obj.priority !== undefined) {
2270
- check(() => requireEnum(`${prefix}priority`, obj.priority, CLI_CREATE_PRIORITIES));
2468
+ check(() => assertPriorityInput(`${prefix}priority`, obj.priority));
2271
2469
  }
2272
2470
  check(() => requireArrayLength(`${prefix}planSteps`, obj.planSteps, {
2273
2471
  min: 1,
@@ -2339,7 +2537,7 @@ export async function runCreateBatch(opts, deps = {}) {
2339
2537
  (opts.maxConcurrency < 1 || opts.maxConcurrency > MAX_BATCH_CONCURRENCY)) {
2340
2538
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
2341
2539
  }
2342
- if (opts.targetUrl !== undefined) {
2540
+ if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
2343
2541
  assertNotLocal(opts.targetUrl, {
2344
2542
  field: 'target-url',
2345
2543
  helpCommand: 'testsprite test create-batch',
@@ -2376,7 +2574,9 @@ export async function runCreateBatch(opts, deps = {}) {
2376
2574
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2377
2575
  stderrFn(`idempotency-key: ${idempotencyKey}`);
2378
2576
  }
2379
- const body = { tests: specs };
2577
+ const body = {
2578
+ tests: specs.map(spec => spec.priority === undefined ? spec : { ...spec, priority: normalizePriority(spec.priority) }),
2579
+ };
2380
2580
  const bodyBytes = Buffer.byteLength(JSON.stringify(body), 'utf8');
2381
2581
  if (bodyBytes > MAX_BATCH_BODY_BYTES) {
2382
2582
  throw ApiError.fromEnvelope({
@@ -2389,6 +2589,25 @@ export async function runCreateBatch(opts, deps = {}) {
2389
2589
  },
2390
2590
  });
2391
2591
  }
2592
+ deps = { ...deps, environmentCache: deps.environmentCache ?? new Map() };
2593
+ if (opts.run && !opts.dryRun && !deps.environmentTunnel) {
2594
+ const targets = await resolveCreationTargets(opts, deps, specs.map(spec => ({ type: spec.type, projectId: spec.projectId })));
2595
+ if (targets.size) {
2596
+ if ((opts.maxConcurrency ?? 5) > 10)
2597
+ throw localValidationError('max-concurrency', 'tunnel runs support at most 10 concurrent runs (default 5)');
2598
+ return withEnvironmentTunnel({
2599
+ ...opts,
2600
+ maxConcurrency: opts.maxConcurrency ?? 5,
2601
+ timeoutSeconds: opts.timeoutSeconds ?? DEFAULT_RUN_TIMEOUT_SECONDS,
2602
+ }, deps, [...targets.values()], 'test create-batch --run', context => runCreateBatch({
2603
+ ...opts,
2604
+ idempotencyKey,
2605
+ wait: true,
2606
+ maxConcurrency: opts.maxConcurrency ?? 5,
2607
+ skipPreflight: true,
2608
+ }, { ...deps, environmentTunnel: context, creationTargets: targets }));
2609
+ }
2610
+ }
2392
2611
  const client = makeClient(opts, deps);
2393
2612
  const out = makeOutput(opts.output, deps);
2394
2613
  const response = await client.post('/tests/batch', {
@@ -2510,9 +2729,18 @@ export async function runCreateBatch(opts, deps = {}) {
2510
2729
  else if (opts.output !== 'json') {
2511
2730
  out.print(enrichedResponse, data => renderBatchText(data));
2512
2731
  }
2732
+ deps = {
2733
+ ...deps,
2734
+ createdTests: new Map(response.results.flatMap(row => {
2735
+ const spec = specs[row.specIndex];
2736
+ return row.testId && spec
2737
+ ? [[row.testId, { type: spec.type, projectId: spec.projectId }]]
2738
+ : [];
2739
+ })),
2740
+ };
2513
2741
  // --run: fan out a trigger for each created test, then emit results.
2514
2742
  if (opts.run === true) {
2515
- await runBatchRun(opts, response, client, out, deps, opts.dryRun ? undefined : testIdToDashboardState);
2743
+ await withCreatedReceipt(opts, deps, response, runDeps => runBatchRun(opts, response, runDeps.environmentTunnel?.client ?? client, makeOutput(opts.output, runDeps), runDeps, opts.dryRun ? undefined : testIdToDashboardState));
2516
2744
  // runBatchRun handles its own exit-code logic via CLIError.
2517
2745
  // Return the create response to satisfy the return type; callers that
2518
2746
  // inspect the return value only do so when not using --run.
@@ -2585,6 +2813,44 @@ testIdToDashboardState) {
2585
2813
  out.print(envelope);
2586
2814
  return;
2587
2815
  }
2816
+ if (deps.environmentTunnel && deps.creationTargets) {
2817
+ deps.environmentTunnel.targets = new Map(testIds.flatMap(id => {
2818
+ const known = deps.createdTests?.get(id);
2819
+ const target = known ? deps.creationTargets.get(known.projectId) : undefined;
2820
+ return target ? [[id, target]] : [];
2821
+ }));
2822
+ }
2823
+ if (!deps.environmentTunnel) {
2824
+ const targets = new Map();
2825
+ const cache = deps.environmentCache ?? new Map();
2826
+ for (const testId of testIds) {
2827
+ const target = await resolveEnvironmentRunTarget({
2828
+ client,
2829
+ testId,
2830
+ knownTest: deps.createdTests?.get(testId),
2831
+ environment: normalizeEnvironmentName(opts.environment),
2832
+ targetUrl: opts.targetUrl,
2833
+ noWait: opts.noWait,
2834
+ verbose: opts.verbose || opts.debug,
2835
+ stderr: stderrFn,
2836
+ cache,
2837
+ });
2838
+ if (target)
2839
+ targets.set(testId, target);
2840
+ }
2841
+ if (targets.size) {
2842
+ const maxConcurrency = opts.maxConcurrency ?? 5;
2843
+ if (maxConcurrency > 10)
2844
+ throw localValidationError('max-concurrency', 'tunnel runs support at most 10 concurrent runs (default 5)');
2845
+ return withEnvironmentTunnel({
2846
+ ...opts,
2847
+ requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true, timeoutSeconds }),
2848
+ }, deps, [...targets.values()], 'test create-batch --run', context => {
2849
+ context.targets = targets;
2850
+ return runBatchRun({ ...opts, wait: true, maxConcurrency }, createResponse, context.client, out, { ...deps, environmentTunnel: context }, testIdToDashboardState);
2851
+ });
2852
+ }
2853
+ }
2588
2854
  // Pre-charge reachability preflight, ONCE for the whole batch
2589
2855
  // before the fan-out — not once per item (mirrors the "fire once per
2590
2856
  // invocation" contract Finding 2 already established for the target-url
@@ -2593,7 +2859,7 @@ testIdToDashboardState) {
2593
2859
  // `type: "backend"` spec always fails create-time server validation, so
2594
2860
  // it never reaches this fan-out at all — see the `beIndexes` warning in
2595
2861
  // `runCreateBatch`).
2596
- if (opts.targetUrl !== undefined) {
2862
+ if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
2597
2863
  await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, {
2598
2864
  fetchImpl: deps.fetchImpl,
2599
2865
  proxyActive: isProxyAgentActive(),
@@ -2611,6 +2877,7 @@ testIdToDashboardState) {
2611
2877
  // matching comment in `runTestRun` for why this replaced the old
2612
2878
  // `v3Enabled`-assumption probe.
2613
2879
  let targetUrlAdvisoryPrinted = false;
2880
+ let fanOutStopped = false;
2614
2881
  /**
2615
2882
  * Client-side sliding-window throttle: caps outgoing triggers at
2616
2883
  * BATCH_RUN_RATE_LIMIT (50) per BATCH_RUN_RATE_WINDOW_MS (60 s), sitting
@@ -2638,6 +2905,7 @@ testIdToDashboardState) {
2638
2905
  // partial reads it because a member's runId is local to triggerOne until
2639
2906
  // the poll settles.
2640
2907
  const dispatchedRunIds = new Map();
2908
+ const pendingTriggers = new Set();
2641
2909
  async function triggerOne(testId) {
2642
2910
  // Mint a fresh idempotency key per run — MUST NOT reuse the create key.
2643
2911
  const runIdempotencyKey = `cli-batch-run-${randomUUID()}`;
@@ -2707,18 +2975,41 @@ testIdToDashboardState) {
2707
2975
  }
2708
2976
  await sleepUntilOrInterrupt(clampedWait, shutdown.signal, sleepFn);
2709
2977
  }
2978
+ if (fanOutStopped && deps.environmentTunnel) {
2979
+ return { testId, runId: '', status: 'not_dispatched', codeVersion: '' };
2980
+ }
2710
2981
  try {
2711
- const result = await client.triggerRunWithMeta(testId, {
2982
+ const dispatch = client
2983
+ .triggerRunWithMeta(testId, {
2712
2984
  source: 'cli',
2713
2985
  ...(opts.targetUrl ? { targetUrl: opts.targetUrl } : {}),
2986
+ ...(deps.environmentTunnel?.targets?.has(testId)
2987
+ ? {
2988
+ targetUrl: deps.environmentTunnel.targets.get(testId).targetUrl,
2989
+ tunnelClientId: deps.environmentTunnel.clientId,
2990
+ }
2991
+ : {}),
2714
2992
  ...(opts.environment !== undefined ? { environment: opts.environment.trim() } : {}),
2715
2993
  },
2716
2994
  // retryOnRateLimit: false — the outer retry loop is the SOLE owner of
2717
2995
  // rate-limit handling for the batch path. Allowing the HTTP layer to add
2718
2996
  // up to 3 internal retries per outer attempt would multiply trigger
2719
2997
  // POSTs per spec (e.g. 50×3 = 150/min), blowing the server's 60/min cap.
2720
- { idempotencyKey: runIdempotencyKey, retryOnRateLimit: false });
2721
- triggerResponse = result.body;
2998
+ { idempotencyKey: runIdempotencyKey, retryOnRateLimit: false })
2999
+ .then(async (result) => {
3000
+ if (result.body.runId)
3001
+ dispatchedRunIds.set(testId, result.body.runId);
3002
+ if (deps.environmentTunnel?.targets?.has(testId))
3003
+ await deps.environmentTunnel.confirm(result.body, [result.body.runId], false);
3004
+ return result;
3005
+ });
3006
+ pendingTriggers.add(dispatch);
3007
+ try {
3008
+ triggerResponse = (await dispatch).body;
3009
+ }
3010
+ finally {
3011
+ pendingTriggers.delete(dispatch);
3012
+ }
2722
3013
  // Fire the response-driven mismatch advisory at most once for the
2723
3014
  // whole batch. Synchronous check-and-set (no `await` between the
2724
3015
  // two) so two members whose triggers resolve in the same tick
@@ -2761,7 +3052,12 @@ testIdToDashboardState) {
2761
3052
  runId: '',
2762
3053
  status: 'error',
2763
3054
  codeVersion: '',
2764
- error: { code: err.code, message: err.message, exitCode: err.exitCode },
3055
+ error: {
3056
+ code: err.code,
3057
+ message: err.message,
3058
+ exitCode: err.exitCode,
3059
+ details: err.details,
3060
+ },
2765
3061
  };
2766
3062
  }
2767
3063
  if (outerRateLimitAttempt < BATCH_RUN_RATE_MAX_OUTER_RETRIES) {
@@ -2798,11 +3094,19 @@ testIdToDashboardState) {
2798
3094
  runId: '',
2799
3095
  status: 'error',
2800
3096
  codeVersion: '',
2801
- error: { code: err.code, message: err.message, exitCode: err.exitCode },
3097
+ error: {
3098
+ code: err.code,
3099
+ message: err.message,
3100
+ exitCode: err.exitCode,
3101
+ details: err.details,
3102
+ },
2802
3103
  };
2803
3104
  }
2804
3105
  // Reuse the same CONFLICT + --wait auto-resume logic as single-test run.
2805
- if (opts.wait && err instanceof ApiError && err.code === 'CONFLICT') {
3106
+ if (opts.wait &&
3107
+ !deps.environmentTunnel?.targets?.has(testId) &&
3108
+ err instanceof ApiError &&
3109
+ err.code === 'CONFLICT') {
2806
3110
  const conflictReason = err.getDetail('reason', (v) => typeof v === 'string' && v.length > 0);
2807
3111
  const currentRunId = err.getDetail('currentRunId', (v) => typeof v === 'string' && v.length > 0);
2808
3112
  if (conflictReason === 'run_in_flight' && currentRunId !== undefined) {
@@ -2853,6 +3157,7 @@ testIdToDashboardState) {
2853
3157
  code: apiErr?.code ?? 'INTERNAL',
2854
3158
  message: err instanceof Error ? err.message : String(err),
2855
3159
  exitCode: apiErr?.exitCode ?? 1,
3160
+ ...(apiErr ? { details: apiErr.details } : {}),
2856
3161
  },
2857
3162
  };
2858
3163
  }
@@ -2863,8 +3168,8 @@ testIdToDashboardState) {
2863
3168
  // a member's runId is otherwise local until its poll settles.
2864
3169
  if (triggerResponse.runId)
2865
3170
  dispatchedRunIds.set(testId, triggerResponse.runId);
2866
- if (!opts.wait) {
2867
- // No-wait path: return the trigger response as-is.
3171
+ if (!opts.wait || (fanOutStopped && deps.environmentTunnel)) {
3172
+ // Retain late trigger receipts without starting another poll during cleanup.
2868
3173
  if (opts.output !== 'json') {
2869
3174
  stderrFn(`[batch-run] ${testId} — triggered (runId: ${triggerResponse.runId}, status: ${triggerResponse.status})`);
2870
3175
  }
@@ -2881,6 +3186,16 @@ testIdToDashboardState) {
2881
3186
  // polling. Math.max(1, ...) would otherwise convert 0 ms → 1 s poll.
2882
3187
  const rem = remainingMs();
2883
3188
  if (opts.wait && rem <= 0) {
3189
+ if (deps.environmentTunnel?.targets?.has(testId)) {
3190
+ fanOutStopped = true;
3191
+ throw new ApiError({
3192
+ code: 'UNSUPPORTED',
3193
+ message: `Timed out after ${timeoutSeconds}s before polling run ${triggerResponse.runId}.`,
3194
+ nextAction: `Inspect cancellation with testsprite test cancel ${triggerResponse.runId}.`,
3195
+ requestId: 'local',
3196
+ details: { runId: triggerResponse.runId },
3197
+ });
3198
+ }
2884
3199
  return {
2885
3200
  testId,
2886
3201
  runId: triggerResponse.runId,
@@ -2901,6 +3216,7 @@ testIdToDashboardState) {
2901
3216
  finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
2902
3217
  timeoutSeconds: remainingSeconds,
2903
3218
  sleep: deps.sleep,
3219
+ onTick: run => deps.environmentTunnel?.onPoll(run),
2904
3220
  shutdown: shutdownOf(deps),
2905
3221
  onTransition: opts.verbose
2906
3222
  ? (msg) => stderrFn(`[batch-run][verbose] ${testId}: ${msg}`)
@@ -2908,6 +3224,21 @@ testIdToDashboardState) {
2908
3224
  });
2909
3225
  }
2910
3226
  catch (err) {
3227
+ // An unobserved tunnel run still occupies a slot until cleanup settles.
3228
+ if (deps.environmentTunnel?.targets?.has(testId)) {
3229
+ fanOutStopped = true;
3230
+ if (err instanceof TimeoutError) {
3231
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
3232
+ throw new ApiError({
3233
+ code: 'UNSUPPORTED',
3234
+ message: err.message,
3235
+ nextAction: `Inspect cancellation with testsprite test cancel ${triggerResponse.runId}.`,
3236
+ requestId: 'local',
3237
+ details: { runId: triggerResponse.runId },
3238
+ });
3239
+ }
3240
+ throw err;
3241
+ }
2911
3242
  // Interrupt rejects the fan-out — see the trigger-stage catch above.
2912
3243
  if (err instanceof InterruptError)
2913
3244
  throw err;
@@ -2951,6 +3282,7 @@ testIdToDashboardState) {
2951
3282
  code: apiErr?.code ?? 'INTERNAL',
2952
3283
  message: err instanceof Error ? err.message : String(err),
2953
3284
  exitCode: apiErr?.exitCode ?? 1,
3285
+ ...(apiErr ? { details: apiErr.details } : {}),
2954
3286
  },
2955
3287
  };
2956
3288
  }
@@ -2976,7 +3308,7 @@ testIdToDashboardState) {
2976
3308
  try {
2977
3309
  await new Promise((resolve, reject) => {
2978
3310
  function startNext() {
2979
- while (inFlight < concurrencyLimit && nextIdx < testIds.length) {
3311
+ while (!fanOutStopped && inFlight < concurrencyLimit && nextIdx < testIds.length) {
2980
3312
  const testId = testIds[nextIdx++];
2981
3313
  inFlight++;
2982
3314
  triggerOne(testId)
@@ -2987,7 +3319,10 @@ testIdToDashboardState) {
2987
3319
  if (inFlight === 0 && nextIdx >= testIds.length)
2988
3320
  resolve();
2989
3321
  })
2990
- .catch(reject);
3322
+ .catch(err => {
3323
+ fanOutStopped = true;
3324
+ reject(err);
3325
+ });
2991
3326
  }
2992
3327
  }
2993
3328
  startNext();
@@ -2996,10 +3331,12 @@ testIdToDashboardState) {
2996
3331
  });
2997
3332
  }
2998
3333
  catch (fanOutErr) {
3334
+ if (deps.environmentTunnel)
3335
+ await Promise.allSettled([...pendingTriggers]);
2999
3336
  // Graceful detach: leave stdout parseable — settled members keep
3000
3337
  // their real status, unfinished ones are marked running — then rethrow so
3001
3338
  // index.ts exits 128+signum.
3002
- if (fanOutErr instanceof InterruptError) {
3339
+ if (fanOutErr instanceof InterruptError || deps.environmentTunnel) {
3003
3340
  const settled = new Map(batchRunResults.map(r => [r.testId, r]));
3004
3341
  // Members mid-poll have no settled result yet — their runId comes from
3005
3342
  // the dispatchedRunIds map recorded at trigger time.
@@ -3013,12 +3350,14 @@ testIdToDashboardState) {
3013
3350
  const unfinished = partialResults
3014
3351
  .filter(r => r.status === 'running' && r.runId)
3015
3352
  .map(r => r.runId);
3016
- if (unfinished.length > 0) {
3353
+ if (unfinished.length > 0 && fanOutErr instanceof InterruptError) {
3017
3354
  fanOutErr.runWaitContext = true;
3018
- stderrFn(interruptDetachMessage(fanOutErr, unfinished));
3355
+ stderrFn(deps.environmentTunnel
3356
+ ? `Interrupted (${fanOutErr.signal}). The owned tunnel is closing; cancellation will be requested for unfinished tunnel runs.`
3357
+ : interruptDetachMessage(fanOutErr, unfinished));
3019
3358
  }
3020
- else {
3021
- stderrFn(`Interrupted (${fanOutErr.signal}). Already-triggered runs keep executing (and billing) server-side; ` +
3359
+ else if (fanOutErr instanceof InterruptError) {
3360
+ stderrFn(`Interrupted (${fanOutErr.signal}). ${deps.environmentTunnel ? 'The owned tunnel is closing; inspect already-triggered runs' : 'Already-triggered runs keep executing (and billing) server-side'}; ` +
3022
3361
  `check them with: testsprite test list`);
3023
3362
  }
3024
3363
  }
@@ -4209,7 +4548,40 @@ export async function runResult(opts, deps = {}) {
4209
4548
  const printData = opts.output === 'json' && result.analysis !== undefined
4210
4549
  ? { ...result, analysis: annotateAnalysisTruncation(result.analysis) }
4211
4550
  : result;
4551
+ // Print the latest result first: the optional default-environment line below
4552
+ // costs up to two reads, and a slow read or Ctrl-C must not withhold it.
4212
4553
  out.print(printData, data => renderResultText(data));
4554
+ if (opts.output !== 'json' && result.environment) {
4555
+ try {
4556
+ const readOptions = {
4557
+ retry: false,
4558
+ signal: AbortSignal.timeout(ENVIRONMENT_PREFLIGHT_TIMEOUT_MS),
4559
+ };
4560
+ const test = await client.get(`/tests/${encodeURIComponent(opts.testId)}`, readOptions);
4561
+ if (test.projectId &&
4562
+ test.headlineEnvironment?.id !== result.environment.id &&
4563
+ test.statusByEnvironment?.some(status => status.environmentId !== result.environment?.id)) {
4564
+ // A missing default result lets the headline fall back to another environment.
4565
+ const listing = await client.get(`/projects/${encodeURIComponent(test.projectId)}/env`, readOptions);
4566
+ const defaultEnvironment = listing.environments?.find(environment => environment.isDefault);
4567
+ const defaultStatus = defaultEnvironment?.id
4568
+ ? test.statusByEnvironment.find(status => status.environmentId === defaultEnvironment.id)
4569
+ : undefined;
4570
+ if (defaultEnvironment?.name &&
4571
+ defaultStatus &&
4572
+ defaultStatus.environmentId !== result.environment.id) {
4573
+ const line = `Default environment ${defaultEnvironment.name}: ${defaultStatus.status} ` +
4574
+ `(testsprite test result ${opts.testId} --history --env ${quoteEnvironmentName(defaultEnvironment.name)})`;
4575
+ out.print(line, text => String(text));
4576
+ }
4577
+ }
4578
+ }
4579
+ catch (err) {
4580
+ if (err instanceof InterruptError)
4581
+ throw err;
4582
+ // Optional context must never prevent displaying the latest result.
4583
+ }
4584
+ }
4213
4585
  return result;
4214
4586
  }
4215
4587
  // ---------------------------------------------------------------------------
@@ -4852,7 +5224,7 @@ function withRunDashboardUrl(run, apiUrl) {
4852
5224
  * atomic — no per-step breakdown exists; showing `0/0 (passed=0, failed=0)`
4853
5225
  * reads like a no-op rather than a passing/failing atomic result).
4854
5226
  */
4855
- function renderRunResponseText(run, { isBackend = false } = {}) {
5227
+ export function renderRunResponseText(run, { isBackend = false } = {}) {
4856
5228
  // P2-9: omit null fields (codeVersion/targetUrl) to match renderResultText
4857
5229
  // convention — literal "null" in text output confuses human operators.
4858
5230
  const lines = [
@@ -4901,6 +5273,9 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
4901
5273
  // is an absent breakdown, not a breakdown of zero steps, so say that.
4902
5274
  lines.push(`steps n/a (no per-step breakdown reported)`);
4903
5275
  }
5276
+ if (run.replay?.path === 'refused') {
5277
+ lines.push(`replay refused${run.replay.reason ? ` (${run.replay.reason})` : ''}`);
5278
+ }
4904
5279
  // Closing pointer: where to inspect this run in the Portal (video, steps,
4905
5280
  // screenshots). Present only when withRunDashboardUrl could resolve it.
4906
5281
  if (run.dashboardUrl)
@@ -4985,77 +5360,6 @@ function normalizeEnvironmentName(raw) {
4985
5360
  }
4986
5361
  return name;
4987
5362
  }
4988
- /** Check a local run's test type and named environment before minting a tunnel. */
4989
- async function preflightLocalRunTest(args) {
4990
- const { client, testId, environment, localPort, opts, deps } = args;
4991
- let test = args.knownTest;
4992
- if (test === undefined) {
4993
- try {
4994
- test = await client.get(`/tests/${encodeURIComponent(testId)}`);
4995
- }
4996
- catch (err) {
4997
- if (err instanceof InterruptError)
4998
- throw err;
4999
- const message = `Cannot read test ${testId} for --local preflight.`;
5000
- if (err instanceof ApiError) {
5001
- if (err.httpStatus !== 403 && err.httpStatus !== 404 && !(err instanceof TransportError)) {
5002
- throw err;
5003
- }
5004
- throw new ApiError({
5005
- code: err.code,
5006
- message,
5007
- nextAction: 'Check the test ID and read:tests permission, then retry.',
5008
- requestId: err.requestId,
5009
- details: {},
5010
- }, err.httpStatus);
5011
- }
5012
- if (err instanceof RequestTimeoutError)
5013
- throw err;
5014
- throw new CLIError(message);
5015
- }
5016
- }
5017
- if (test.type === 'backend') {
5018
- throw localValidationError('local', `backend tests don't open a browser; the tunnel is not used. Run: testsprite test run ${testId}`);
5019
- }
5020
- if (environment === undefined)
5021
- return;
5022
- let listing;
5023
- try {
5024
- listing = await client.get(`/projects/${encodeURIComponent(test.projectId)}/env`);
5025
- }
5026
- catch (err) {
5027
- if (err instanceof InterruptError)
5028
- throw err;
5029
- if (!(err instanceof TransportError) &&
5030
- !(err instanceof RequestTimeoutError) &&
5031
- !(err instanceof ApiError &&
5032
- (err.httpStatus === 403 || err.httpStatus === 404 || (err.httpStatus ?? 0) >= 500))) {
5033
- throw err;
5034
- }
5035
- if (opts.verbose || opts.debug) {
5036
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
5037
- stderr('[verbose] environment preflight skipped: project environments unavailable; the server will validate this run.');
5038
- }
5039
- }
5040
- if (listing === undefined)
5041
- return;
5042
- const selected = listing.environments.find(row => row.name === environment);
5043
- if (selected === undefined) {
5044
- const available = listing.environments.map(row => row.name).sort();
5045
- throw localValidationError('env', `unknown environment '${environment}'; use one of: ${available.join(', ')}`, available);
5046
- }
5047
- let isLoopback = false;
5048
- try {
5049
- normalizeLocalHost(new URL(selected.url).hostname);
5050
- isLoopback = true;
5051
- }
5052
- catch {
5053
- // A public environment cannot be reached through this local tunnel.
5054
- }
5055
- if (!isLoopback) {
5056
- throw localValidationError('local', `This environment has a public URL. Run testsprite test run ${testId} --env ${environment} without --local, or testsprite test run ${testId} --local ${localPort} without --env.`);
5057
- }
5058
- }
5059
5363
  /**
5060
5364
  * Validate the `--timeout` flag value. Returns a clamped integer in
5061
5365
  * range [1, 3600], or the default when absent.
@@ -5132,6 +5436,71 @@ reported) {
5132
5436
  }
5133
5437
  stderrFn(`[advisory] --no-auto-heal was not applied by the server — ${label} may re-author drifted code.`);
5134
5438
  }
5439
+ function assertFreshRunWaitOptions(opts, batchPath) {
5440
+ assertJUnitReportOptions({ ...opts, wait: opts.wait === true, batchPath });
5441
+ if (opts.ghOutput === true && !opts.wait)
5442
+ throw localValidationError('gh-output', '--gh-output requires --wait (it reduces the terminal run result). Add --wait.');
5443
+ if (opts.summaryFile !== undefined && !opts.wait)
5444
+ throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
5445
+ }
5446
+ function isSameLoopbackPort(url, port) {
5447
+ try {
5448
+ return parseLoopbackTargetUrl(url)?.port === port;
5449
+ }
5450
+ catch {
5451
+ return false;
5452
+ }
5453
+ }
5454
+ /**
5455
+ * The environment half of the 409 auto-resume gate, shared by the single run
5456
+ * and the `--all` batch: may the in-flight run stand in for the run this
5457
+ * invocation asked for? Resolves to the `--env` flag naming the verified
5458
+ * environment for a later retry (undefined when the run recorded none), or
5459
+ * throws `incompatibleRun(reason)`.
5460
+ *
5461
+ * `undefined` (no key at all) is a V2 run or a backend that predates
5462
+ * environments on run reads; `null` is a V3 row that explicitly names no
5463
+ * environment, OR one whose environment lookup failed and was swallowed
5464
+ * server-side. Only the former may attach unverified — treating `null` the
5465
+ * same way would let a failed lookup slip through the gate it exists to
5466
+ * enforce.
5467
+ */
5468
+ async function verifyInFlightRunEnvironment(inFlightRun, environment, listEnvironments, incompatibleRun) {
5469
+ const inFlightEnvironment = inFlightRun.environment;
5470
+ if (inFlightEnvironment === undefined) {
5471
+ if (environment !== undefined) {
5472
+ // --env was requested but this in-flight run has nothing recorded to
5473
+ // verify it against.
5474
+ throw incompatibleRun('its environment could not be verified');
5475
+ }
5476
+ // Restored 0.12.0 path: no environment recorded, none requested — attach.
5477
+ return undefined;
5478
+ }
5479
+ if (inFlightEnvironment === null ||
5480
+ typeof inFlightEnvironment.id !== 'string' ||
5481
+ inFlightEnvironment.id.length === 0) {
5482
+ throw incompatibleRun('its environment could not be verified');
5483
+ }
5484
+ let currentEnvironment;
5485
+ try {
5486
+ const listing = await listEnvironments(inFlightRun.projectId);
5487
+ currentEnvironment = listing.environments.find(row => environment === undefined ? row.isDefault : row.name === environment);
5488
+ }
5489
+ catch (listErr) {
5490
+ if (listErr instanceof InterruptError)
5491
+ throw listErr;
5492
+ throw incompatibleRun('its environment could not be verified');
5493
+ }
5494
+ if (typeof currentEnvironment?.id !== 'string' || currentEnvironment.id.length === 0) {
5495
+ // The listing succeeded but named nothing we can compare against — that
5496
+ // is unverified, not a proven mismatch.
5497
+ throw incompatibleRun('its environment could not be verified');
5498
+ }
5499
+ if (currentEnvironment.id !== inFlightEnvironment.id) {
5500
+ throw incompatibleRun('its environment does not match the requested environment');
5501
+ }
5502
+ return `--env ${currentEnvironment.name}`;
5503
+ }
5135
5504
  export async function runTestRun(opts, deps = {}) {
5136
5505
  assertIdempotencyKey(opts.idempotencyKey);
5137
5506
  const environment = normalizeEnvironmentName(opts.environment);
@@ -5139,29 +5508,56 @@ export async function runTestRun(opts, deps = {}) {
5139
5508
  // must happen before a client is even constructed, because the guarantee
5140
5509
  // this feature sells is that a doomed `--local` run never gets a run row,
5141
5510
  // a credit spend, or a tunnel credential.
5142
- const isTunnelRun = opts.localPort !== undefined;
5143
- if (isTunnelRun && opts.targetUrl !== undefined) {
5511
+ let isTunnelRun = opts.localPort !== undefined ||
5512
+ (opts.targetUrl !== undefined && parseLoopbackTargetUrl(opts.targetUrl) !== undefined);
5513
+ if (opts.localPort !== undefined && opts.targetUrl !== undefined) {
5144
5514
  throw localValidationError('local', '--local and --target-url are mutually exclusive: --local runs against your own machine ' +
5145
5515
  'through a tunnel, --target-url runs against an address the test runner can already ' +
5146
5516
  'reach. Pass one');
5147
5517
  }
5148
- if (isTunnelRun && !opts.wait) {
5518
+ if (opts.localPort !== undefined && !opts.wait) {
5149
5519
  // The tunnel's lifetime IS this process's lifetime, so a no-wait tunnel
5150
5520
  // run dooms itself the instant the command returns. The command wiring
5151
5521
  // forces --wait; this covers a programmatic caller that did not.
5152
5522
  throw localValidationError('local', '--local runs cannot detach: the tunnel closes when this command exits, so the run would ' +
5153
5523
  'fail. Remove --local, or let the command wait');
5154
5524
  }
5155
- if (opts.targetUrl !== undefined) {
5525
+ if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
5156
5526
  assertNotLocal(opts.targetUrl, {
5157
5527
  field: 'target-url',
5158
5528
  helpCommand: 'testsprite test run',
5159
5529
  hintContext: 'runtime',
5160
5530
  });
5161
5531
  }
5162
- const localHost = opts.localHost ?? DEFAULT_LOCAL_HOST;
5163
- const localTargetUrl = opts.localPort !== undefined ? buildLocalTargetUrl(localHost, opts.localPort) : undefined;
5164
- const effectiveTargetUrl = localTargetUrl ?? opts.targetUrl;
5532
+ if (!isTunnelRun && (opts.noWait || opts.type === 'backend' || opts.targetUrl !== undefined))
5533
+ assertNoTunnelOptions(opts);
5534
+ let localHost = opts.localHost ?? DEFAULT_LOCAL_HOST;
5535
+ let localTargetUrl = opts.localPort !== undefined ? buildLocalTargetUrl(localHost, opts.localPort) : undefined;
5536
+ let effectiveTargetUrl = localTargetUrl ?? opts.targetUrl;
5537
+ if (opts.dryRun && !isTunnelRun && !opts.noWait && opts.targetUrl === undefined) {
5538
+ try {
5539
+ const target = await resolveEnvironmentRunTarget({
5540
+ client: makeClient({ ...opts, dryRun: false }, deps),
5541
+ testId: opts.testId,
5542
+ knownTest: opts.knownTest,
5543
+ environment,
5544
+ dryRun: true,
5545
+ stderr: deps.stderr ?? (line => process.stderr.write(`${line}\n`)),
5546
+ });
5547
+ if (target) {
5548
+ isTunnelRun = true;
5549
+ localHost = target.host;
5550
+ effectiveTargetUrl = target.targetUrl;
5551
+ opts = { ...opts, wait: true };
5552
+ }
5553
+ }
5554
+ catch (err) {
5555
+ if (err instanceof InterruptError)
5556
+ throw err;
5557
+ }
5558
+ }
5559
+ if (opts.dryRun && !isTunnelRun)
5560
+ assertNoTunnelOptions(opts);
5165
5561
  if (opts.dryRun) {
5166
5562
  const client = makeClient(opts, deps);
5167
5563
  const out = makeOutput(opts.output, deps);
@@ -5216,18 +5612,49 @@ export async function runTestRun(opts, deps = {}) {
5216
5612
  // D4: under --wait, raise the per-request timeout to cover --timeout so a
5217
5613
  // slow trigger/long-poll under load isn't falsely cut at the 120s default.
5218
5614
  const requestTimeoutMs = resolveWaitRequestTimeoutMs(opts);
5219
- const clientOpts = { ...opts, requestTimeoutMs };
5220
- const client = makeClient(clientOpts, deps);
5221
- if (isTunnelRun) {
5222
- await preflightLocalRunTest({
5615
+ let clientOpts = { ...opts, requestTimeoutMs };
5616
+ let client;
5617
+ try {
5618
+ client = makeClient(clientOpts, deps);
5619
+ }
5620
+ catch (err) {
5621
+ assertFreshRunWaitOptions(opts, false);
5622
+ throw err;
5623
+ }
5624
+ const resolvedTarget = deps.environmentTunnel?.targets?.get(opts.testId) ??
5625
+ (opts.knownTest ? deps.creationTargets?.get(opts.knownTest.projectId) : undefined) ??
5626
+ (await resolveEnvironmentRunTarget({
5223
5627
  client,
5224
5628
  testId: opts.testId,
5629
+ knownTest: opts.knownTest,
5225
5630
  environment,
5226
5631
  localPort: opts.localPort,
5227
- opts,
5228
- deps,
5229
- });
5632
+ localHost: opts.localHost,
5633
+ targetUrl: opts.targetUrl,
5634
+ tunnelClientId: opts.tunnelClientId,
5635
+ noWait: opts.noWait,
5636
+ verbose: opts.verbose || opts.debug,
5637
+ stderr: deps.stderr ?? (line => process.stderr.write(`${line}\n`)),
5638
+ cache: deps.environmentCache,
5639
+ }));
5640
+ isTunnelRun = resolvedTarget !== undefined;
5641
+ if (!isTunnelRun)
5642
+ assertNoTunnelOptions(opts);
5643
+ if (resolvedTarget) {
5644
+ localHost = resolvedTarget.host;
5645
+ localTargetUrl = resolvedTarget.targetUrl;
5646
+ effectiveTargetUrl = resolvedTarget.targetUrl;
5647
+ opts = {
5648
+ ...opts,
5649
+ wait: true,
5650
+ timeoutSeconds: opts.timeoutIsDefault
5651
+ ? DEFAULT_LOCAL_RUN_TIMEOUT_SECONDS
5652
+ : opts.timeoutSeconds,
5653
+ };
5654
+ clientOpts = { ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) };
5655
+ client = makeClient(clientOpts, deps);
5230
5656
  }
5657
+ assertFreshRunWaitOptions(opts, false);
5231
5658
  const tunnelRequestTimeoutMs = isTunnelRun
5232
5659
  ? resolveRequestTimeoutMs(clientOpts, deps.env ?? process.env)
5233
5660
  : undefined;
@@ -5249,14 +5676,17 @@ export async function runTestRun(opts, deps = {}) {
5249
5676
  // this one is conclusive — the dial it performs is the same raw loopback
5250
5677
  // connect the tunnel client will make from this same process — so it
5251
5678
  // refuses rather than advises.
5252
- await assertLocalPortListening(localHost, opts.localPort, { skipPreflight: opts.skipPreflight }, stderrFn);
5679
+ await assertLocalPortListening(localHost, resolvedTarget.port, {
5680
+ skipPreflight: opts.skipPreflight,
5681
+ ...(resolvedTarget.automatic ? { environmentName: resolvedTarget.environmentName } : {}),
5682
+ }, stderrFn);
5253
5683
  if (isProxyAgentActive()) {
5254
5684
  stderrFn('[advisory] An HTTP proxy is configured for this process. The tunnel control channel ' +
5255
5685
  `honours it, but ${TUNNEL_DATA_PLANE_PROXY_BYPASS_DESCRIPTION} — if the ` +
5256
5686
  'run cannot reach your machine, an egress proxy is the first thing to rule out.');
5257
5687
  }
5258
5688
  }
5259
- else if (opts.targetUrl !== undefined) {
5689
+ else if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
5260
5690
  await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, {
5261
5691
  fetchImpl: deps.fetchImpl,
5262
5692
  proxyActive: isProxyAgentActive(),
@@ -5275,22 +5705,24 @@ export async function runTestRun(opts, deps = {}) {
5275
5705
  try {
5276
5706
  if (isTunnelRun) {
5277
5707
  try {
5278
- tunnelSession = await openTunnelSession({
5279
- log: stderrFn,
5280
- logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error',
5281
- onMinted: minted => stderrFn(`[tunnel] Minted tunnel client ${minted.clientId}; connecting…`),
5282
- onFatal: () => {
5283
- // Surfaced to the poll loop through `onTick` below; a remint cannot
5284
- // rescue this run (see `lib/tunnel-session.ts`).
5285
- },
5286
- ...(opts.tunnelClientId !== undefined
5287
- ? { adopt: { clientId: opts.tunnelClientId, expiresAt: '' } }
5288
- : {}),
5289
- }, {
5290
- mint: async (ttlSeconds) => withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, mintClient => mintClient.mintTunnel({ ...(ttlSeconds ? { ttlSeconds } : {}) })),
5291
- destroy: async (clientId) => deleteTunnelForCleanup(opts, deps, clientId),
5292
- createClient: shutdownAwareTunnelClientFactory(deps.createTunnelClient ?? (options => new TunnelClient(options)), shutdown.signal),
5293
- });
5708
+ tunnelSession =
5709
+ deps.environmentTunnel?.session ??
5710
+ (await openTunnelSession({
5711
+ log: stderrFn,
5712
+ logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error',
5713
+ onMinted: minted => stderrFn(`[tunnel] Minted tunnel client ${minted.clientId}; connecting…`),
5714
+ onFatal: () => {
5715
+ // Surfaced to the poll loop through `onTick` below; a remint cannot
5716
+ // rescue this run (see `lib/tunnel-session.ts`).
5717
+ },
5718
+ ...(opts.tunnelClientId !== undefined
5719
+ ? { adopt: { clientId: opts.tunnelClientId, expiresAt: '' } }
5720
+ : {}),
5721
+ }, {
5722
+ mint: async (ttlSeconds) => withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, mintClient => mintClient.mintTunnel({ ...(ttlSeconds ? { ttlSeconds } : {}) })),
5723
+ destroy: async (clientId) => deleteTunnelForCleanup(opts, deps, clientId),
5724
+ createClient: shutdownAwareTunnelClientFactory(deps.createTunnelClient ?? (options => new TunnelClient(options)), shutdown.signal),
5725
+ }));
5294
5726
  }
5295
5727
  catch (err) {
5296
5728
  // `openTunnelSession` converts a client-start rejection to UNAVAILABLE
@@ -5298,8 +5730,9 @@ export async function runTestRun(opts, deps = {}) {
5298
5730
  // initiating signal so the documented interrupt exit code is retained.
5299
5731
  if (shutdown.signal.aborted)
5300
5732
  throw shutdown.signal.reason;
5301
- throw err;
5733
+ throw tunnelScopeError(err);
5302
5734
  }
5735
+ recordTelemetryTunnelOpened(!tunnelSession.adopted);
5303
5736
  if (!tunnelSession.adopted) {
5304
5737
  stderrFn(`[tunnel] Reaching ${localTargetUrl} through TestSprite (client ${tunnelSession.clientId}).`);
5305
5738
  }
@@ -5365,7 +5798,6 @@ export async function runTestRun(opts, deps = {}) {
5365
5798
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
5366
5799
  // Set only when a verified environment names a concrete retry — the
5367
5800
  // no-environment-recorded attach path has nothing to name.
5368
- let retryFlags;
5369
5801
  const incompatibleRun = (reason) => new ApiError({
5370
5802
  code: 'CONFLICT',
5371
5803
  message: `Conflict: run ${currentRunId} is already in flight; ${reason}. This invocation cannot attach to it.`,
@@ -5382,60 +5814,7 @@ export async function runTestRun(opts, deps = {}) {
5382
5814
  throw readErr;
5383
5815
  throw incompatibleRun('its environment could not be verified');
5384
5816
  }
5385
- const inFlightEnvironment = inFlightRun.environment;
5386
- // `undefined` (no key at all) is a V2 run or a backend that predates
5387
- // environments on run reads; `null` is a V3 row that explicitly names no
5388
- // environment, OR one whose environment lookup failed and was
5389
- // swallowed server-side. Only the former may attach unverified —
5390
- // treating `null` the same way would let a failed lookup slip
5391
- // through the gate it exists to enforce.
5392
- if (inFlightEnvironment === undefined) {
5393
- if (environment !== undefined) {
5394
- // --env was requested but this in-flight run has nothing
5395
- // recorded to verify it against.
5396
- throw incompatibleRun('its environment could not be verified');
5397
- }
5398
- // Restored 0.12.0 path: no environment recorded, none requested — attach.
5399
- }
5400
- else if (inFlightEnvironment === null ||
5401
- typeof inFlightEnvironment.id !== 'string' ||
5402
- inFlightEnvironment.id.length === 0) {
5403
- throw incompatibleRun('its environment could not be verified');
5404
- }
5405
- else {
5406
- let currentEnvironment;
5407
- try {
5408
- const listing = await client.get(`/projects/${encodeURIComponent(inFlightRun.projectId)}/env`);
5409
- currentEnvironment = listing.environments.find(row => environment === undefined ? row.isDefault : row.name === environment);
5410
- }
5411
- catch (listErr) {
5412
- if (listErr instanceof InterruptError)
5413
- throw listErr;
5414
- throw incompatibleRun('its environment could not be verified');
5415
- }
5416
- if (typeof currentEnvironment?.id !== 'string' || currentEnvironment.id.length === 0) {
5417
- // The listing succeeded but named nothing we can compare against —
5418
- // that is unverified, not a proven mismatch.
5419
- throw incompatibleRun('its environment could not be verified');
5420
- }
5421
- if (currentEnvironment.id !== inFlightEnvironment.id) {
5422
- throw incompatibleRun('its environment does not match the requested environment');
5423
- }
5424
- retryFlags = `--env ${currentEnvironment.name}`;
5425
- try {
5426
- const target = new URL(currentEnvironment.url);
5427
- const host = normalizeLocalHost(target.hostname);
5428
- if (target.protocol === 'http:' || target.protocol === 'https:') {
5429
- const port = target.port || (target.protocol === 'https:' ? '443' : '80');
5430
- retryFlags += ` --local ${port}`;
5431
- if (host !== DEFAULT_LOCAL_HOST)
5432
- retryFlags += ` --local-host ${host}`;
5433
- }
5434
- }
5435
- catch {
5436
- // Public environments need only --env on a later run.
5437
- }
5438
- }
5817
+ const retryFlags = await verifyInFlightRunEnvironment(inFlightRun, environment, projectId => client.get(`/projects/${encodeURIComponent(projectId)}/env`), incompatibleRun);
5439
5818
  // If the caller supplied --target-url, verify the in-flight run targets
5440
5819
  // the same URL. A mismatch means we would be reporting a different
5441
5820
  // environment's results as if our requested environment was tested.
@@ -5486,7 +5865,7 @@ export async function runTestRun(opts, deps = {}) {
5486
5865
  `). Auto-resuming wait on in-flight run. ` +
5487
5866
  `To run it again, cancel it with ` +
5488
5867
  `testsprite test cancel ${currentRunId}, or wait for it to finish; ` +
5489
- `then re-trigger${retryFlags ? ` with ${retryFlags}` : ''}.`);
5868
+ `then re-trigger${retryFlags ? ` with testsprite test run ${opts.testId} ${retryFlags}` : ''}.`);
5490
5869
  triggerResponse = {
5491
5870
  runId: currentRunId,
5492
5871
  status: 'queued',
@@ -5527,7 +5906,13 @@ export async function runTestRun(opts, deps = {}) {
5527
5906
  // for backend tests") already covers this case at create time.
5528
5907
  if (effectiveTargetUrl !== undefined &&
5529
5908
  opts.type !== 'backend' &&
5530
- triggerResponse.targetUrl !== effectiveTargetUrl) {
5909
+ triggerResponse.targetUrl !== effectiveTargetUrl &&
5910
+ !(
5911
+ // `--local <port>` never named a URL: the shorthand's host is the CLI's
5912
+ // own default, so an echo that differs only in loopback spelling
5913
+ // (localhost vs 127.0.0.1) is not an unapplied `--target-url`.
5914
+ opts.localPort !== undefined &&
5915
+ isSameLoopbackPort(triggerResponse.targetUrl, resolvedTarget?.port ?? opts.localPort))) {
5531
5916
  emitTargetUrlMismatchAdvisory(stderrFn, effectiveTargetUrl, triggerResponse.targetUrl);
5532
5917
  }
5533
5918
  if (!opts.wait) {
@@ -5628,8 +6013,10 @@ export async function runTestRun(opts, deps = {}) {
5628
6013
  return {
5629
6014
  runId: triggerResponse.runId,
5630
6015
  testId: opts.testId,
5631
- localPort: opts.localPort,
6016
+ localPort: resolvedTarget.port,
5632
6017
  localHost,
6018
+ automatic: resolvedTarget.automatic,
6019
+ environment,
5633
6020
  reason,
5634
6021
  ...(borrowedOwnerGone ? { ownerGone: true } : {}),
5635
6022
  cancel: cancel.outcome,
@@ -5900,7 +6287,8 @@ export async function runTestRun(opts, deps = {}) {
5900
6287
  // client whose ref'd heartbeat timer keeps the process alive after the
5901
6288
  // command has printed its last line.
5902
6289
  try {
5903
- await tunnelSession?.close();
6290
+ if (!deps.environmentTunnel)
6291
+ await tunnelSession?.close();
5904
6292
  }
5905
6293
  finally {
5906
6294
  disarmTunnelLifecycle?.();
@@ -6557,7 +6945,7 @@ export async function writeBatchJUnitReportIfRequested(opts, results, nameByTest
6557
6945
  const enriched = results.map(r => ({
6558
6946
  ...r,
6559
6947
  name: nameByTestId?.get(r.testId) ?? (r.testTitle?.trim() ? r.testTitle : undefined) ?? r.name,
6560
- durationSeconds: r.durationSeconds ?? durationSecondsBetween(r.startedAt, r.finishedAt),
6948
+ durationSeconds: r.durationSeconds ?? durationSecondsBetween(r.startedAt, r.finishedAt, r.createdAt),
6561
6949
  }));
6562
6950
  const xml = buildJUnitReport({
6563
6951
  suiteName,
@@ -6591,6 +6979,154 @@ async function cancelRunsBestEffort(client, runIds, stderrFn, label) {
6591
6979
  }
6592
6980
  }
6593
6981
  }
6982
+ /**
6983
+ * One line telling a backend-project batch what the integration phase will do
6984
+ * after the wave. Undefined when the backend sent no summary (older backend,
6985
+ * frontend project, or nothing to say).
6986
+ */
6987
+ function formatIntegrationSummary(integration) {
6988
+ if (integration === undefined || !integration.runsAfterWave)
6989
+ return undefined;
6990
+ const parts = [];
6991
+ if (integration.existing > 0) {
6992
+ parts.push(`${integration.existing} existing integration test${integration.existing !== 1 ? 's' : ''} run after this wave (0.2 credits each)`);
6993
+ }
6994
+ if (integration.mayGenerate)
6995
+ parts.push('new ones may be generated on a first run');
6996
+ if (parts.length === 0)
6997
+ return undefined;
6998
+ return `Integration phase: ${parts.join('; ')}.`;
6999
+ }
7000
+ const EXECUTION_REPORT_DEFAULT_TIMEOUT_SECONDS = 60;
7001
+ const EXECUTION_REPORT_DEFAULT_RETRY_SECONDS = 5;
7002
+ /**
7003
+ * Fetch the execution report — the content the GitHub App posts as its PR
7004
+ * comment — for the one execution this CI batch dispatched into.
7005
+ *
7006
+ * Best-effort by contract: the local results table is the fallback, so an
7007
+ * older backend (404), a report that is not ready within the budget, a
7008
+ * report for some other execution, or any other failure returns `undefined`
7009
+ * with one stderr line. An interrupt while waiting (the request or the retry
7010
+ * sleep — the scope is armed across both, so a first signal is a graceful
7011
+ * stop, not an immediate exit) also falls back, and is handed back in
7012
+ * `interrupted`: the batch is already finished, so its summary and outputs are
7013
+ * written first, then the caller rethrows it so the exit is the signal's
7014
+ * code. Reads nothing when `--no-execution-report`
7015
+ * was passed, when a run timed out (the execution is not terminal, so the
7016
+ * report could only arrive late), or unless EVERY accepted row names the same
7017
+ * execution (an older backend omits the id; a batch spanning several
7018
+ * executions gets one report per execution as a follow-up — a report for one
7019
+ * of them would read as the whole batch's).
7020
+ */
7021
+ async function fetchExecutionReport(client, accepted, results, opts, deps, stderrFn) {
7022
+ if (opts.ci?.executionReport === false || accepted.length === 0)
7023
+ return {};
7024
+ const executionIds = new Set(accepted.map(a => a.executionId));
7025
+ if (executionIds.size !== 1)
7026
+ return {};
7027
+ const executionId = [...executionIds][0];
7028
+ if (typeof executionId !== 'string' || executionId.length === 0)
7029
+ return {};
7030
+ if (results.some(r => r.status === 'timeout')) {
7031
+ stderrFn('[ci run] a run timed out, so the execution is not finished; the job summary uses the local results table');
7032
+ return {};
7033
+ }
7034
+ const timeoutSeconds = opts.ci?.executionReportTimeoutSeconds ?? EXECUTION_REPORT_DEFAULT_TIMEOUT_SECONDS;
7035
+ const deadlineMs = Date.now() + timeoutSeconds * 1000;
7036
+ const ac = new AbortController();
7037
+ const timer = setTimeout(() => ac.abort(), timeoutSeconds * 1000);
7038
+ const sleepFn = deps.sleep ?? defaultSleep;
7039
+ const shutdown = shutdownOf(deps);
7040
+ // Every `pollRunUntilTerminal` has disarmed by now, so without this scope a
7041
+ // SIGINT/SIGTERM during the retry sleep would take the signal handler's
7042
+ // disarmed path and exit at once — no summary, no outputs.
7043
+ const disarm = shutdown.arm();
7044
+ try {
7045
+ for (;;) {
7046
+ // No automatic retries: the deadline below is the only retry policy.
7047
+ const res = await client.getExecutionReport(executionId, { signal: ac.signal, retry: false });
7048
+ if (res.ready && res.report && typeof res.markdown === 'string') {
7049
+ if (res.report.executionId !== executionId) {
7050
+ stderrFn(`[ci run] execution report names execution ${res.report.executionId}, not ${executionId}; the job summary uses the local results table`);
7051
+ return {};
7052
+ }
7053
+ return { ready: { report: res.report, markdown: res.markdown } };
7054
+ }
7055
+ const remainingMs = deadlineMs - Date.now();
7056
+ if (remainingMs <= 0)
7057
+ break;
7058
+ const retrySeconds = Math.max(1, res.retryAfterSeconds ?? EXECUTION_REPORT_DEFAULT_RETRY_SECONDS);
7059
+ // Interruptible: a SIGINT/SIGTERM here means "stop waiting for the
7060
+ // report", not "drop the finished batch's summary and outputs".
7061
+ await sleepUnlessInterrupted(sleepFn, Math.min(remainingMs, retrySeconds * 1000), shutdown.signal);
7062
+ if (Date.now() >= deadlineMs)
7063
+ break;
7064
+ }
7065
+ stderrFn(`[ci run] execution report not ready within ${timeoutSeconds}s; the job summary uses the local results table`);
7066
+ }
7067
+ catch (err) {
7068
+ if (err instanceof InterruptError) {
7069
+ stderrFn('[ci run] interrupted while waiting for the execution report; the job summary uses the local results table');
7070
+ return { interrupted: err };
7071
+ }
7072
+ stderrFn(`[ci run] execution report unavailable (${err instanceof Error ? err.message : String(err)}); the job summary uses the local results table`);
7073
+ }
7074
+ finally {
7075
+ clearTimeout(timer);
7076
+ disarm();
7077
+ }
7078
+ return {};
7079
+ }
7080
+ /** Publish all CI surfaces from one summary before applying the CI gate. */
7081
+ async function finishCiBatch(payload, opts, deps, nameByTestId, executionError,
7082
+ /** The accepted rows with poll timing, for the JUnit report only. */
7083
+ junitResults = payload.accepted,
7084
+ /** The server's execution report, when the backend provided one in time. */
7085
+ executionReport) {
7086
+ // A CI gate that dispatched nothing is its own funnel outcome (green only
7087
+ // with --allow-empty); the gated case is recorded by the caller, which holds
7088
+ // the execution id.
7089
+ if (payload.accepted.length === 0)
7090
+ recordTelemetryExtras({ ciRunOutcome: 'empty' });
7091
+ const summary = summarizeAcceptedPayload(JSON.stringify(payload), {
7092
+ foldSkippedBuckets: true,
7093
+ notFoundNote: 'test not found (not dispatched)',
7094
+ });
7095
+ if (executionReport)
7096
+ summary.executionReport = executionReport.report;
7097
+ const io = {
7098
+ env: deps.env ?? process.env,
7099
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
7100
+ stderr: deps.stderr ?? ((line) => process.stderr.write(`${line}\n`)),
7101
+ };
7102
+ makeOutput(opts.output, deps).print({ ...payload, summary }, () => `CI run: ${summary.passed}/${summary.total} passed, ${summary.failed} failed, ` +
7103
+ `${summary.skipped} skipped, ${summary.timedOut} timed out`);
7104
+ emitCiArtifacts(summary, opts, io, 'ci run', {
7105
+ markdown: executionReport
7106
+ ? reconcileExecutionReportMarkdown(summary, executionReport)
7107
+ : undefined,
7108
+ });
7109
+ emitCiStepOutputs(summary, io);
7110
+ if (executionReport)
7111
+ emitExecutionReportOutputs(executionReport, io);
7112
+ let reportError;
7113
+ try {
7114
+ // Same rows as `test run --all`: every non-dispatched member is a skipped
7115
+ // testcase, so the report never claims a partial batch ran in full.
7116
+ await writeBatchJUnitReportIfRequested(opts, [...junitResults, ...skippedJUnitResultsFromSummary(summary, payload.accepted)], nameByTestId);
7117
+ }
7118
+ catch (err) {
7119
+ reportError = err;
7120
+ io.stderr(`[ci run] could not write the JUnit report: ${err instanceof Error ? err.message : String(err)}`);
7121
+ }
7122
+ if (executionError)
7123
+ throw executionError;
7124
+ const failure = resolveCiRunFailure(summary, payload.accepted, { ...opts, failOnSkipped: opts.ci?.failOnSkipped }, payload.conflicts);
7125
+ if (failure)
7126
+ throw failure;
7127
+ if (reportError)
7128
+ throw reportError;
7129
+ }
6594
7130
  /** Human explanation for a zero-dispatch batch, from what the engine skipped. */
6595
7131
  function zeroDispatchReason(skippedFrontend, skippedIntegration) {
6596
7132
  const parts = [];
@@ -6618,7 +7154,12 @@ function zeroDispatchReason(skippedFrontend, skippedIntegration) {
6618
7154
  * `reason` is the human explanation shown in the annotation and the throw.
6619
7155
  */
6620
7156
  async function finishZeroDispatchBatch(params) {
6621
- const { reason, skipped, allowEmpty, opts, deps, stderrFn, label = 'run' } = params;
7157
+ const { reason, skipped, allowEmpty, opts, deps, stderrFn, label = 'run', emptyProject = false, projectId, local, } = params;
7158
+ // Text mode only: under --output json neither the error envelope's message
7159
+ // nor stderr carries the sentence (review feedback).
7160
+ const nextStep = emptyProject && projectId !== undefined && opts.output !== 'json'
7161
+ ? emptyProjectNextStep(projectId, local)
7162
+ : undefined;
6622
7163
  const runs = skipped.length > 0
6623
7164
  ? skipped.map(testId => ({ testId, status: 'skipped', error: reason }))
6624
7165
  : [{ testId: '(no tests)', status: 'no_tests', error: reason }];
@@ -6655,10 +7196,15 @@ async function finishZeroDispatchBatch(params) {
6655
7196
  }
6656
7197
  if (allowEmpty) {
6657
7198
  stderrFn(`[${label}] 0 tests dispatched (${reason}); --allow-empty set — exiting 0.`);
7199
+ if (nextStep !== undefined)
7200
+ stderrFn(`[hint] ${nextStep}`);
6658
7201
  return;
6659
7202
  }
7203
+ // The pointer rides inside the message so it prints AFTER "Error:", in
7204
+ // reading order — a CLIError has no nextAction slot of its own.
6660
7205
  throw new CLIError(`No tests were dispatched — ${reason}. A CI gate that passes on zero tests is unsafe; ` +
6661
- `pass --allow-empty to exit 0 intentionally.`, 5);
7206
+ `pass --allow-empty to exit 0 intentionally.` +
7207
+ (nextStep !== undefined ? ` ${nextStep}` : ''), 5);
6662
7208
  }
6663
7209
  /**
6664
7210
  * `test run --all --project <id>` — M4 piece-2.
@@ -6672,6 +7218,8 @@ export async function runTestRunAll(opts, deps = {}) {
6672
7218
  const environment = normalizeEnvironmentName(opts.environment);
6673
7219
  const projectId = resolveProjectId(opts.projectId, deps);
6674
7220
  requireProjectId(projectId);
7221
+ // Carry the resolved id into reports, including when it came from the env.
7222
+ opts = { ...opts, projectId };
6675
7223
  if (!Number.isInteger(opts.maxConcurrency) ||
6676
7224
  opts.maxConcurrency < 1 ||
6677
7225
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
@@ -6681,13 +7229,43 @@ export async function runTestRunAll(opts, deps = {}) {
6681
7229
  report: opts.report,
6682
7230
  reportFile: opts.reportFile,
6683
7231
  reportSuiteName: opts.reportSuiteName,
6684
- wait: opts.wait,
7232
+ wait: opts.wait || (!opts.dryRun && !opts.noWait),
6685
7233
  batchPath: true,
6686
7234
  });
6687
7235
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
6688
7236
  const out = makeOutput(opts.output, deps);
7237
+ if (opts.dryRun && opts.targetUrl === undefined && !opts.noWait) {
7238
+ let target;
7239
+ try {
7240
+ target = await resolveEnvironmentRunTarget({
7241
+ client: makeClient({ ...opts, dryRun: false }, deps),
7242
+ projectId,
7243
+ environment,
7244
+ dryRun: true,
7245
+ stderr: stderrFn,
7246
+ });
7247
+ }
7248
+ catch (err) {
7249
+ if (err instanceof InterruptError)
7250
+ throw err;
7251
+ }
7252
+ if (target) {
7253
+ await runTestRunLocalBatch({
7254
+ ...opts,
7255
+ all: true,
7256
+ testIds: [],
7257
+ projectId,
7258
+ resolvedTarget: target,
7259
+ skipPreflight: true,
7260
+ cancelOnInterrupt: true,
7261
+ allowEmpty: opts.allowEmpty === true,
7262
+ }, deps);
7263
+ return undefined;
7264
+ }
7265
+ }
6689
7266
  // --- Dry-run path ---
6690
7267
  if (opts.dryRun) {
7268
+ assertNoTunnelOptions(opts);
6691
7269
  // This path returns before makeClient() fires the banner, so emit it
6692
7270
  // here — otherwise the canned sample can be mistaken for a live response.
6693
7271
  emitDryRunBanner(stderrFn);
@@ -6708,21 +7286,54 @@ export async function runTestRunAll(opts, deps = {}) {
6708
7286
  idempotencyKey,
6709
7287
  ...(opts.wait ? { thenPoll: '/api/cli/v1/runs/<run-id>?waitSeconds=25' } : {}),
6710
7288
  };
6711
- if (opts.report === 'junit' && opts.reportFile !== undefined) {
7289
+ if (!opts.ci && opts.report === 'junit' && opts.reportFile !== undefined) {
6712
7290
  await writeJUnitReportFile(opts.reportFile, sampleJUnitReportXml(opts.projectId, opts.reportSuiteName));
6713
7291
  }
6714
- out.print(opts.targetUrl !== undefined ? envelope : (batchRunSample ?? envelope));
7292
+ out.print(opts.ci || opts.targetUrl !== undefined ? envelope : (batchRunSample ?? envelope));
6715
7293
  return undefined;
6716
7294
  }
6717
7295
  // Probe once before dispatch. A preview still warming up can use
6718
7296
  // --skip-preflight; ambiguous probe results warn without blocking.
6719
- if (opts.targetUrl !== undefined) {
7297
+ if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
6720
7298
  await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
6721
7299
  }
6722
7300
  // D4: under --wait, raise per-request timeout to cover --timeout.
6723
7301
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
6724
7302
  // `--env` gate — see `runTestRun`. Before the test-set enumeration so a
6725
7303
  // gated batch makes no billable call at all.
7304
+ const environmentCache = deps.environmentCache ?? new Map();
7305
+ const automaticTarget = opts.environmentResolutionComplete
7306
+ ? undefined
7307
+ : await resolveEnvironmentRunTarget({
7308
+ client,
7309
+ cache: environmentCache,
7310
+ projectId,
7311
+ environment,
7312
+ targetUrl: opts.targetUrl,
7313
+ noWait: opts.noWait,
7314
+ stderr: stderrFn,
7315
+ });
7316
+ if (automaticTarget) {
7317
+ await runTestRunLocalBatch({
7318
+ ...opts,
7319
+ testIds: [],
7320
+ all: true,
7321
+ projectId,
7322
+ localPort: automaticTarget.port,
7323
+ localHost: automaticTarget.host,
7324
+ resolvedTarget: automaticTarget,
7325
+ timeoutSeconds: opts.timeoutIsDefault
7326
+ ? DEFAULT_LOCAL_RUN_TIMEOUT_SECONDS
7327
+ : opts.timeoutSeconds,
7328
+ skipPreflight: opts.skipPreflight === true,
7329
+ cancelOnInterrupt: opts.cancelOnInterrupt !== false,
7330
+ allowEmpty: opts.allowEmpty === true,
7331
+ maxConcurrency: opts.concurrencyIsDefault ? 5 : opts.maxConcurrency,
7332
+ }, { ...deps, environmentCache });
7333
+ return undefined;
7334
+ }
7335
+ assertNoTunnelOptions(opts);
7336
+ assertFreshRunWaitOptions(opts, true);
6726
7337
  // Portal deep links for batch output: every test in the batch belongs to
6727
7338
  // opts.projectId, so per-item dashboardUrl needs no extra wire data. The
6728
7339
  // project-level URL closes out text-mode output ("watch the wave here").
@@ -6760,11 +7371,52 @@ export async function runTestRunAll(opts, deps = {}) {
6760
7371
  ...(opts.autoHeal === false ? { autoHeal: false } : {}),
6761
7372
  ...(environment !== undefined ? { environment } : {}),
6762
7373
  ...(opts.targetUrl !== undefined ? { targetUrl: opts.targetUrl } : {}),
7374
+ ...(opts.admission !== undefined ? { admission: opts.admission } : {}),
7375
+ ...(opts.previewName !== undefined ? { previewName: opts.previewName } : {}),
7376
+ ...(opts.githubTrigger !== undefined ? { githubTrigger: opts.githubTrigger } : {}),
6763
7377
  };
7378
+ /**
7379
+ * The fields a dispatch leg must see echoed back. An older backend strips
7380
+ * what it does not know and runs anyway — against the wrong target, with a
7381
+ * cut batch, or as a plain override where a preview environment was asked
7382
+ * for — so each is confirmed exactly, on every leg.
7383
+ */
7384
+ function unhonoredDispatchFields(response) {
7385
+ const out = [];
7386
+ if (opts.targetUrl !== undefined && response.targetUrl !== opts.targetUrl) {
7387
+ out.push({
7388
+ field: 'targetUrl',
7389
+ reason: 'target-url-not-honored',
7390
+ message: 'This backend did not confirm --target-url on the batch run; the accepted runs may have used another URL.',
7391
+ nextAction: 'Use a backend that supports batch target URL overrides, or retry without --target-url.',
7392
+ });
7393
+ }
7394
+ if (opts.admission !== undefined && response.admission !== opts.admission) {
7395
+ out.push({
7396
+ field: 'admission',
7397
+ reason: 'admission-not-honored',
7398
+ message: 'This backend did not confirm the single-execution admission mode; the batch may have been cut to the per-key budget.',
7399
+ nextAction: 'Use a backend that supports ci run (v0.20.0 or later).',
7400
+ });
7401
+ }
7402
+ if (opts.previewName !== undefined && response.previewName !== opts.previewName) {
7403
+ out.push({
7404
+ field: 'previewName',
7405
+ reason: 'preview-not-honored',
7406
+ message: 'This backend did not confirm the CI preview environment; the accepted runs may have run as a plain target override instead of in github-pr-<N>.',
7407
+ nextAction: 'Use a backend that supports ci run (v0.20.0 or later).',
7408
+ });
7409
+ }
7410
+ return out;
7411
+ }
6764
7412
  async function assertBatchTargetEcho(response, previouslyAccepted) {
6765
- if (opts.targetUrl === undefined || response.targetUrl === opts.targetUrl)
7413
+ const unhonored = unhonoredDispatchFields(response);
7414
+ if (unhonored.length === 0)
6766
7415
  return;
6767
- const message = 'This backend did not confirm --target-url on the batch run; the accepted runs may have used another URL.';
7416
+ const { field, reason, message, nextAction } = unhonored[0];
7417
+ // Every unhonored echo means a backend that predates the CI contract.
7418
+ if (opts.ci)
7419
+ recordTelemetryExtras({ ciRunOutcome: 'refused_admission' });
6768
7420
  // Only this response's runs are unconfirmed. Runs an earlier leg confirmed
6769
7421
  // keep running against the right URL; they are reported as not awaited,
6770
7422
  // never cancelled.
@@ -6773,7 +7425,7 @@ export async function runTestRunAll(opts, deps = {}) {
6773
7425
  const confirmed = dedupeBatchRunFreshAccepted([...previouslyAccepted]).deduped.filter(item => !unconfirmedIds.has(item.runId));
6774
7426
  await cancelRunsBestEffort(client, unconfirmed.map(item => item.runId), stderrFn, 'run');
6775
7427
  if (opts.wait) {
6776
- const notAwaited = 'Not awaited: the batch stopped because a later dispatch did not confirm --target-url. ' +
7428
+ const notAwaited = `Not awaited: the batch stopped because a later dispatch did not confirm ${field}. ` +
6777
7429
  'This run was confirmed and is still running; read it with testsprite test wait <run-id>.';
6778
7430
  const summary = summarizeAcceptedPayload(JSON.stringify({
6779
7431
  accepted: [
@@ -6792,11 +7444,15 @@ export async function runTestRunAll(opts, deps = {}) {
6792
7444
  summary.failed = 1;
6793
7445
  summary.runs.push({ testId: '(batch)', status: 'error', error: message });
6794
7446
  }
6795
- emitCiArtifacts(summary, opts, {
7447
+ const io = {
6796
7448
  env: deps.env ?? process.env,
6797
7449
  stdout: deps.stdout ?? (line => process.stdout.write(`${line}\n`)),
6798
7450
  stderr: stderrFn,
6799
- }, 'run');
7451
+ };
7452
+ emitCiArtifacts(summary, opts, io, 'run');
7453
+ // `ci run` promises its step outputs before the exit code, refusal included.
7454
+ if (opts.ci)
7455
+ emitCiStepOutputs(summary, io);
6800
7456
  try {
6801
7457
  await writeBatchJUnitReportIfRequested(opts, summary.runs.map(row => ({
6802
7458
  testId: row.testId,
@@ -6815,9 +7471,9 @@ export async function runTestRunAll(opts, deps = {}) {
6815
7471
  error: {
6816
7472
  code: 'UNSUPPORTED',
6817
7473
  message,
6818
- nextAction: 'Use a backend that supports batch target URL overrides, or retry without --target-url.',
7474
+ nextAction,
6819
7475
  requestId: 'local',
6820
- details: { field: 'targetUrl', reason: 'target-url-not-honored' },
7476
+ details: { field, reason },
6821
7477
  },
6822
7478
  });
6823
7479
  }
@@ -6838,13 +7494,18 @@ export async function runTestRunAll(opts, deps = {}) {
6838
7494
  testIds = filtered.map(t => t.id);
6839
7495
  if (testIds.length === 0) {
6840
7496
  stderrFn(`No tests found in project ${projectId} matching --filter "${opts.nameFilter}" — nothing to run.`);
6841
- out.print({
7497
+ const emptyResponse = {
6842
7498
  accepted: [],
6843
7499
  conflicts: [],
6844
7500
  deferred: [],
6845
7501
  skippedFrontend: [],
6846
7502
  skippedIntegration: [],
6847
- });
7503
+ };
7504
+ if (opts.ci) {
7505
+ await finishCiBatch({ ...emptyResponse, accepted: [] }, opts, deps);
7506
+ return undefined;
7507
+ }
7508
+ out.print(emptyResponse);
6848
7509
  // Zero-dispatch (a --filter that matched nothing): emit the CI artifacts
6849
7510
  // and fail unless --allow-empty, so a renamed test can't turn a filtered
6850
7511
  // gate permanently green. Returns here only under --allow-empty.
@@ -6862,15 +7523,40 @@ export async function runTestRunAll(opts, deps = {}) {
6862
7523
  }
6863
7524
  // When no --filter, omit testIds → server runs ALL tests in the project
6864
7525
  // (BE tests on the legacy V2 wave engine; FE + BE on the V3 unified engine).
6865
- const batchResp = await client.triggerBatchRunFresh({
6866
- projectId,
6867
- ...(testIds !== undefined ? { testIds } : {}),
6868
- ...dispatchFields,
6869
- }, { idempotencyKey });
7526
+ let batchResp;
7527
+ try {
7528
+ batchResp = await client.triggerBatchRunFresh({
7529
+ projectId,
7530
+ ...(testIds !== undefined ? { testIds } : {}),
7531
+ ...dispatchFields,
7532
+ }, { idempotencyKey });
7533
+ }
7534
+ catch (err) {
7535
+ // A whole-batch refusal under `ci run` is a funnel outcome — every API
7536
+ // refusal gets one (validation by the server's `details.reason`, 402/403
7537
+ // as billing, the rest as other).
7538
+ if (opts.ci && err instanceof ApiError) {
7539
+ recordTelemetryExtras({ ciRunOutcome: ciRefusalOutcome(err) });
7540
+ }
7541
+ throw err;
7542
+ }
6870
7543
  // Shared across every dispatch this invocation makes — see the `reported` param.
6871
7544
  const optOutReported = new Set();
6872
7545
  warnIfOptOutIgnored(opts.autoHeal, batchResp.autoHeal, stderrFn, 'these runs', optOutReported);
6873
7546
  await assertBatchTargetEcho(batchResp, []);
7547
+ if (opts.ci && batchResp.accepted.length > 0) {
7548
+ // Recorded as soon as the dispatch is confirmed, not after the wait: a job
7549
+ // cancelled mid-wait (a re-push under shape B's concurrency group, a manual
7550
+ // cancel, the runner's timeout) exits through InterruptError, and the
7551
+ // `abort` event must still say the gate dispatched and which execution
7552
+ // keeps running. `reportReady` is added once the report wait finishes.
7553
+ const dispatchedExecutionIds = new Set(batchResp.accepted.map(a => a.executionId));
7554
+ const dispatchedExecutionId = dispatchedExecutionIds.size === 1 ? [...dispatchedExecutionIds][0] : undefined;
7555
+ recordTelemetryExtras({
7556
+ ciRunOutcome: 'gated',
7557
+ ...(typeof dispatchedExecutionId === 'string' ? { executionId: dispatchedExecutionId } : {}),
7558
+ });
7559
+ }
6874
7560
  // Project-level "watch it here" link. A V3 backend sends it (string, or
6875
7561
  // `null` when no single page exists — e.g. a `--all` that fanned out over
6876
7562
  // several sibling projects); an older backend / the V2 engine omits the key,
@@ -6883,7 +7569,9 @@ export async function runTestRunAll(opts, deps = {}) {
6883
7569
  let accepted = batchResp.accepted.slice();
6884
7570
  let deferred = batchResp.deferred.slice();
6885
7571
  let conflicts = batchResp.conflicts.slice();
6886
- const { skippedFrontend, skippedIntegration } = batchResp;
7572
+ const skippedFrontend = batchResp.skippedFrontend.slice();
7573
+ const skippedIntegration = batchResp.skippedIntegration.slice();
7574
+ let retryError;
6887
7575
  // Print advisory for skipped FE tests.
6888
7576
  if (skippedFrontend.length > 0) {
6889
7577
  stderrFn(`[advisory] ${skippedFrontend.length} frontend test${skippedFrontend.length !== 1 ? 's' : ''} skipped — the batch run endpoint uses the BE-only wave engine. ` +
@@ -6900,6 +7588,9 @@ export async function runTestRunAll(opts, deps = {}) {
6900
7588
  if (deferred.length > 0) {
6901
7589
  stderrFn(`Rate-deferred testIds (retry later): ${deferred.map(d => d.testId).join(' ')}`);
6902
7590
  }
7591
+ const integrationLine = formatIntegrationSummary(batchResp.integration);
7592
+ if (integrationLine !== undefined)
7593
+ stderrFn(integrationLine);
6903
7594
  stderrFn(`Dispatched ${accepted.length} test${accepted.length !== 1 ? 's' : ''}` +
6904
7595
  `${skippedFrontend.length > 0 ? ` (${skippedFrontend.length} FE skipped)` : ''}` +
6905
7596
  `${conflicts.length > 0 ? ` (${conflicts.length} conflict${conflicts.length !== 1 ? 's' : ''})` : ''}` +
@@ -6918,6 +7609,7 @@ export async function runTestRunAll(opts, deps = {}) {
6918
7609
  deferred,
6919
7610
  skippedFrontend,
6920
7611
  skippedIntegration,
7612
+ ...(batchResp.integration !== undefined ? { integration: batchResp.integration } : {}),
6921
7613
  };
6922
7614
  out.print(printResp, data => {
6923
7615
  const r = data;
@@ -6990,6 +7682,10 @@ export async function runTestRunAll(opts, deps = {}) {
6990
7682
  opts,
6991
7683
  deps,
6992
7684
  stderrFn,
7685
+ emptyProject: skippedFrontend.length === 0 &&
7686
+ skippedIntegration.length === 0 &&
7687
+ opts.nameFilter === undefined,
7688
+ projectId,
6993
7689
  });
6994
7690
  }
6995
7691
  // [P2] Return post-retry state so programmatic callers and the create-chain
@@ -7007,7 +7703,7 @@ export async function runTestRunAll(opts, deps = {}) {
7007
7703
  // deadline check below is the real stop), scaled to the timeout so it never
7008
7704
  // caps a legitimate long wait.
7009
7705
  const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
7010
- const batchDeadlineMs = Date.now() + opts.timeoutSeconds * 1000;
7706
+ const batchDeadlineMs = deps.environmentTunnel?.deadlineMs ?? Date.now() + opts.timeoutSeconds * 1000;
7011
7707
  // finding 1: reserve a poll window so the deferred-retry loop can't consume the
7012
7708
  // ENTIRE --timeout and leave the fan-out poll with nothing — which would report
7013
7709
  // already-finished runs as timeouts (exit 7) instead of their real verdicts
@@ -7065,6 +7761,8 @@ export async function runTestRunAll(opts, deps = {}) {
7065
7761
  if (err instanceof ApiError &&
7066
7762
  (err.code === 'UNSUPPORTED' || err.code === 'PRECONDITION_FAILED'))
7067
7763
  throw err;
7764
+ if (opts.ci)
7765
+ retryError = err;
7068
7766
  // If the retry itself errors, surface it and stop retrying.
7069
7767
  stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
7070
7768
  break;
@@ -7077,6 +7775,8 @@ export async function runTestRunAll(opts, deps = {}) {
7077
7775
  const newlyAccepted = retryResp.accepted;
7078
7776
  const newlyDeferred = retryResp.deferred;
7079
7777
  const newlyConflicted = retryResp.conflicts;
7778
+ skippedFrontend.push(...retryResp.skippedFrontend);
7779
+ skippedIntegration.push(...retryResp.skippedIntegration);
7080
7780
  if (newlyAccepted.length > 0) {
7081
7781
  stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyAccepted.length} test${newlyAccepted.length !== 1 ? 's' : ''} now accepted.`);
7082
7782
  // A retry asks only for the still-deferred ids but can come back with
@@ -7096,7 +7796,7 @@ export async function runTestRunAll(opts, deps = {}) {
7096
7796
  }
7097
7797
  deferred = newlyDeferred;
7098
7798
  if (deferred.length === 0) {
7099
- stderrFn(`[deferred-retry] attempt ${attempt}: all previously-deferred tests accepted.`);
7799
+ stderrFn(`[deferred-retry] attempt ${attempt}: no tests remain rate-deferred.`);
7100
7800
  }
7101
7801
  }
7102
7802
  // Gap B: an already-running case is not a dead end under --wait. A conflict
@@ -7104,8 +7804,10 @@ export async function runTestRunAll(opts, deps = {}) {
7104
7804
  // (auto-resume) — the "concurrent job already started this test" case should
7105
7805
  // wait for that run's result, not fail the batch. Conflicts without a
7106
7806
  // resolvable in-flight run stay hard (nothing to wait on).
7107
- const resumableConflicts = conflicts.filter(c => c.currentRunId);
7108
- const hardConflicts = conflicts.filter(c => !c.currentRunId);
7807
+ // An in-flight run may belong to another deployment/environment. CI can
7808
+ // only use runs accepted by this invocation to judge its own change.
7809
+ const resumableConflicts = opts.ci ? [] : conflicts.filter(c => c.currentRunId);
7810
+ const hardConflicts = opts.ci ? conflicts : conflicts.filter(c => !c.currentRunId);
7109
7811
  // Only hard conflicts remain "conflicts" for the final accounting/exit; the
7110
7812
  // resumable ones become polled results below.
7111
7813
  conflicts = hardConflicts;
@@ -7122,14 +7824,38 @@ export async function runTestRunAll(opts, deps = {}) {
7122
7824
  // many-in-flight-conflicts scenario finding 1 is about, so a serial N round-trip
7123
7825
  // fetch (with no deadline bound) would eat the budget finding 1's fix protects.
7124
7826
  const resolveSignal = AbortSignal.timeout(Math.max(1, batchDeadlineMs - Date.now()));
7125
- const resumableEntries = await Promise.all(resumableConflicts.map(async (c) => {
7827
+ // One environment listing per project for the whole batch (the gate below
7828
+ // compares environment ids, not names, so it needs the project's list).
7829
+ const envListings = new Map();
7830
+ const listEnvironments = (projectId) => {
7831
+ let listing = envListings.get(projectId);
7832
+ if (!listing) {
7833
+ listing = client.get(`/projects/${encodeURIComponent(projectId)}/env`, { signal: resolveSignal });
7834
+ envListings.set(projectId, listing);
7835
+ }
7836
+ return listing;
7837
+ };
7838
+ const resumedOrRefused = await Promise.all(resumableConflicts.map(async (c) => {
7126
7839
  const inFlightRunId = c.currentRunId;
7840
+ // The same gate the single run applies before adopting a 409: an
7841
+ // in-flight run on another environment (a PR gate's `github-pr-N`
7842
+ // clone, say) or another target URL is somebody else's run, and its
7843
+ // verdict must not be reported as this invocation's. Refused runs stay
7844
+ // hard conflicts — polled by nobody here — instead of being attached.
7845
+ const refused = (reason) => ({
7846
+ refused: {
7847
+ ...c,
7848
+ reason: 'in_flight',
7849
+ message: `not attached: ${reason}`,
7850
+ },
7851
+ });
7127
7852
  // Conservative default if the run can't be read: floor at NOW (never the
7128
7853
  // epoch) so the fallback still can't accept an older run's result.
7129
7854
  let notBefore = new Date().toISOString();
7130
7855
  let startedBy;
7856
+ let inFlight;
7131
7857
  try {
7132
- const inFlight = await client.getRun(inFlightRunId, { signal: resolveSignal });
7858
+ inFlight = await client.getRun(inFlightRunId, { signal: resolveSignal });
7133
7859
  if (inFlight.createdAt)
7134
7860
  notBefore = inFlight.createdAt;
7135
7861
  startedBy = inFlight.source || inFlight.createdFrom || undefined;
@@ -7139,9 +7865,46 @@ export async function runTestRunAll(opts, deps = {}) {
7139
7865
  throw err;
7140
7866
  // keep the conservative now() floor (fetch failed or the signal aborted)
7141
7867
  }
7868
+ if (inFlight) {
7869
+ try {
7870
+ await verifyInFlightRunEnvironment(inFlight, opts.environment, listEnvironments, reason => new ApiError({
7871
+ code: 'CONFLICT',
7872
+ message: reason,
7873
+ nextAction: `testsprite test wait ${inFlightRunId}`,
7874
+ requestId: '',
7875
+ details: { reason: 'run_in_flight', currentRunId: inFlightRunId },
7876
+ }));
7877
+ }
7878
+ catch (err) {
7879
+ if (err instanceof InterruptError)
7880
+ throw err;
7881
+ if (err instanceof ApiError && err.code === 'CONFLICT')
7882
+ return refused(err.message);
7883
+ throw err;
7884
+ }
7885
+ if (opts.targetUrl !== undefined && inFlight.targetUrl !== opts.targetUrl) {
7886
+ return refused(`it targets ${inFlight.targetUrl || 'an unreported URL'}, not ${opts.targetUrl}`);
7887
+ }
7888
+ }
7889
+ else if (opts.environment !== undefined || opts.targetUrl !== undefined) {
7890
+ // An environment or target was asked for and the run could not be
7891
+ // read: unverified, so not ours to attach to (fail closed, as the
7892
+ // single run does).
7893
+ return refused('its environment could not be verified');
7894
+ }
7142
7895
  stderrFn(`[auto-resume] ${c.testId} — polling in-flight run ${inFlightRunId}${startedBy ? ` (started by ${startedBy})` : ''} to a verdict instead of failing`);
7143
- return { testId: c.testId, runId: inFlightRunId, enqueuedAt: notBefore };
7896
+ return { entry: { testId: c.testId, runId: inFlightRunId, enqueuedAt: notBefore } };
7144
7897
  }));
7898
+ const resumableEntries = [];
7899
+ for (const outcome of resumedOrRefused) {
7900
+ if ('entry' in outcome) {
7901
+ resumableEntries.push(outcome.entry);
7902
+ }
7903
+ else {
7904
+ stderrFn(`[auto-resume] ${outcome.refused.testId} — in-flight run ${outcome.refused.currentRunId} ${outcome.refused.message?.replace(/^not attached: /, '')}; not attaching (testsprite test wait ${outcome.refused.currentRunId} to follow it)`);
7905
+ conflicts.push(outcome.refused);
7906
+ }
7907
+ }
7145
7908
  // --wait: fan-out poll each accepted run by its runId, PLUS each auto-resumed
7146
7909
  // in-flight run. Every accepted entry carries a real runId (the backend routes
7147
7910
  // slot-claim failures to conflicts[]); the resumed entries reuse the existing
@@ -7163,14 +7926,20 @@ export async function runTestRunAll(opts, deps = {}) {
7163
7926
  deferred,
7164
7927
  skippedFrontend,
7165
7928
  skippedIntegration,
7929
+ ...(batchResp.integration !== undefined ? { integration: batchResp.integration } : {}),
7166
7930
  };
7167
- out.print(finalResp);
7931
+ if (!opts.ci)
7932
+ out.print(finalResp);
7168
7933
  recordBatchOutcome({
7169
7934
  accepted: accepted.length,
7170
7935
  conflicts,
7171
7936
  deferred: deferred.length,
7172
7937
  skipped: skippedFrontend.length + skippedIntegration.length,
7173
7938
  });
7939
+ if (opts.ci) {
7940
+ await finishCiBatch({ ...finalResp, accepted: [] }, opts, deps, undefined, retryError);
7941
+ return { ...batchResp, ...finalResp };
7942
+ }
7174
7943
  // Nothing to poll: surface deferred (rate-limit → exit 7) or all-conflict (exit 6),
7175
7944
  // mirroring the non-wait path so `--wait` never silently exits 0 on a no-op batch.
7176
7945
  // Emit the deferred/conflict summary + annotations first so CI shows them (the
@@ -7218,6 +7987,10 @@ export async function runTestRunAll(opts, deps = {}) {
7218
7987
  opts,
7219
7988
  deps,
7220
7989
  stderrFn,
7990
+ emptyProject: skippedFrontend.length === 0 &&
7991
+ skippedIntegration.length === 0 &&
7992
+ opts.nameFilter === undefined,
7993
+ projectId,
7221
7994
  });
7222
7995
  // [P2] Return post-retry state (reached only under --allow-empty).
7223
7996
  return { ...batchResp, accepted, deferred, conflicts };
@@ -7225,6 +7998,7 @@ export async function runTestRunAll(opts, deps = {}) {
7225
7998
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
7226
7999
  const concurrencyLimit = opts.maxConcurrency;
7227
8000
  const freshRunResults = [];
8001
+ const reportTiming = new Map();
7228
8002
  // Single deadline shared across the whole fan-out (codex): each queued poll
7229
8003
  // gets the time REMAINING against this batch deadline, not a fresh full
7230
8004
  // `timeoutSeconds`. Without this, runs that wait behind `--max-concurrency`
@@ -7256,6 +8030,11 @@ export async function runTestRunAll(opts, deps = {}) {
7256
8030
  shutdown: shutdownOf(deps),
7257
8031
  resolveAlternate: lastResortAlternate,
7258
8032
  });
8033
+ reportTiming.set(runId, {
8034
+ createdAt: finalRun.createdAt,
8035
+ startedAt: finalRun.startedAt,
8036
+ finishedAt: finalRun.finishedAt,
8037
+ });
7259
8038
  return {
7260
8039
  testId: entry.testId,
7261
8040
  testTitle: finalRun.testTitle ?? null,
@@ -7268,11 +8047,22 @@ export async function runTestRunAll(opts, deps = {}) {
7268
8047
  ...(typeof finalRun.executionUrl === 'string'
7269
8048
  ? { executionUrl: finalRun.executionUrl }
7270
8049
  : {}),
8050
+ ...(opts.ci && finalRun.error
8051
+ ? { error: { code: 'INTERNAL', message: finalRun.error, exitCode: 1 } }
8052
+ : {}),
7271
8053
  };
7272
8054
  }
7273
8055
  catch (err) {
7274
8056
  if (err instanceof InterruptError)
7275
8057
  throw err;
8058
+ if (opts.ci && err instanceof ApiError) {
8059
+ return {
8060
+ testId: entry.testId,
8061
+ runId,
8062
+ status: 'error',
8063
+ error: { code: err.code, message: err.message, exitCode: err.exitCode },
8064
+ };
8065
+ }
7276
8066
  if (err instanceof TimeoutError)
7277
8067
  deps.onWaitTimeout?.({ reason: 'wait_timeout' });
7278
8068
  // fall through to the timeout result below
@@ -7304,6 +8094,11 @@ export async function runTestRunAll(opts, deps = {}) {
7304
8094
  onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`)),
7305
8095
  resolveAlternate,
7306
8096
  });
8097
+ reportTiming.set(runId, {
8098
+ createdAt: finalRun.createdAt,
8099
+ startedAt: finalRun.startedAt,
8100
+ finishedAt: finalRun.finishedAt,
8101
+ });
7307
8102
  return {
7308
8103
  testId: entry.testId,
7309
8104
  testTitle: finalRun.testTitle ?? null,
@@ -7316,6 +8111,9 @@ export async function runTestRunAll(opts, deps = {}) {
7316
8111
  ...(typeof finalRun.executionUrl === 'string'
7317
8112
  ? { executionUrl: finalRun.executionUrl }
7318
8113
  : {}),
8114
+ ...(opts.ci && finalRun.error
8115
+ ? { error: { code: 'INTERNAL', message: finalRun.error, exitCode: 1 } }
8116
+ : {}),
7319
8117
  startedAt: finalRun.startedAt,
7320
8118
  finishedAt: finalRun.finishedAt,
7321
8119
  };
@@ -7425,6 +8223,7 @@ export async function runTestRunAll(opts, deps = {}) {
7425
8223
  deferred,
7426
8224
  skippedFrontend,
7427
8225
  skippedIntegration,
8226
+ ...(batchResp.integration !== undefined ? { integration: batchResp.integration } : {}),
7428
8227
  summary: {
7429
8228
  passed,
7430
8229
  failed,
@@ -7438,8 +8237,15 @@ export async function runTestRunAll(opts, deps = {}) {
7438
8237
  ? await buildTestNameMap(client, opts.projectId)
7439
8238
  : undefined;
7440
8239
  const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
7441
- await writeBatchJUnitReportIfRequested(opts, [...freshRunResults, ...skippedJUnitResultsFromSummary(ciSummary)], freshNameMap);
7442
- out.print(jsonPayload);
8240
+ // JUnit rows carry the poll timing the stdout envelope deliberately omits.
8241
+ const timedResults = freshRunResults.map(r => ({
8242
+ ...r,
8243
+ ...(r.runId ? reportTiming.get(r.runId) : {}),
8244
+ }));
8245
+ if (!opts.ci) {
8246
+ await writeBatchJUnitReportIfRequested(opts, [...timedResults, ...skippedJUnitResultsFromSummary(ciSummary, freshRunResults)], freshNameMap);
8247
+ out.print(jsonPayload);
8248
+ }
7443
8249
  recordBatchOutcome({
7444
8250
  accepted: accepted.length,
7445
8251
  conflicts,
@@ -7447,6 +8253,38 @@ export async function runTestRunAll(opts, deps = {}) {
7447
8253
  skipped: skippedFrontend.length + skippedIntegration.length,
7448
8254
  results: freshRunResults,
7449
8255
  });
8256
+ if (opts.ci) {
8257
+ // The report is read before the envelope prints so it lands in `--output
8258
+ // json`, `--summary-file` and the job summary alike.
8259
+ const { ready: executionReport, interrupted } = await fetchExecutionReport(client, accepted, freshRunResults, opts, deps, stderrFn);
8260
+ // Telemetry: the gate ran; name the execution (when the batch names exactly
8261
+ // one) so the event joins to the server's report, and whether that report
8262
+ // made it into the job summary.
8263
+ const gatedExecutionIds = new Set(accepted.map(a => a.executionId));
8264
+ const gatedExecutionId = gatedExecutionIds.size === 1 ? [...gatedExecutionIds][0] : undefined;
8265
+ if (accepted.length > 0) {
8266
+ recordTelemetryExtras({
8267
+ ciRunOutcome: 'gated',
8268
+ ...(typeof gatedExecutionId === 'string' ? { executionId: gatedExecutionId } : {}),
8269
+ reportReady: executionReport !== undefined,
8270
+ });
8271
+ }
8272
+ let gateError;
8273
+ try {
8274
+ await finishCiBatch(jsonPayload, opts, deps, freshNameMap, retryError, timedResults, executionReport);
8275
+ }
8276
+ catch (err) {
8277
+ gateError = err;
8278
+ }
8279
+ // The summary and outputs are written either way; a signal that cut the
8280
+ // report wait short still ends the process with its own exit code (130/143),
8281
+ // never the gate's 0.
8282
+ if (interrupted)
8283
+ throw interrupted;
8284
+ if (gateError !== undefined)
8285
+ throw gateError;
8286
+ return { ...batchResp, accepted, deferred, conflicts, skippedFrontend, skippedIntegration };
8287
+ }
7450
8288
  // CI-native output layer (issue #99): emitted before the gate throws below so
7451
8289
  // the artifacts land even when the batch exits non-zero. The summary file is a
7452
8290
  // machine artifact written regardless of --output mode; stdout stays owned by
@@ -7522,15 +8360,79 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7522
8360
  const environment = normalizeEnvironmentName(opts.environment);
7523
8361
  if (!Number.isInteger(opts.maxConcurrency) ||
7524
8362
  opts.maxConcurrency < 1 ||
7525
- opts.maxConcurrency > 10) {
8363
+ (opts.maxConcurrency > 10 &&
8364
+ !opts.concurrencyIsDefault &&
8365
+ (opts.localPort !== undefined ||
8366
+ opts.resolvedTarget !== undefined ||
8367
+ (opts.targetUrl !== undefined && parseLoopbackTargetUrl(opts.targetUrl) !== undefined)))) {
7526
8368
  throw localValidationError('max-concurrency', 'with --local, --max-concurrency must be between 1 and 10 (every run shares this machine and its one tunnel; the default is 5)');
7527
8369
  }
7528
8370
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
7529
8371
  const out = makeOutput(opts.output, deps);
7530
- const targetUrl = buildLocalTargetUrl(opts.localHost, opts.localPort);
8372
+ let targetUrl = opts.resolvedTarget?.targetUrl ??
8373
+ opts.targetUrl ??
8374
+ (opts.localPort !== undefined
8375
+ ? buildLocalTargetUrl(opts.localHost ?? DEFAULT_LOCAL_HOST, opts.localPort)
8376
+ : undefined);
7531
8377
  const projectId = opts.all ? resolveProjectId(opts.projectId, deps) : opts.projectId;
7532
8378
  if (opts.all)
7533
8379
  requireProjectId(projectId);
8380
+ if (opts.localPort === undefined &&
8381
+ targetUrl !== undefined &&
8382
+ !parseLoopbackTargetUrl(targetUrl)) {
8383
+ if (!opts.all)
8384
+ severalIdsWithoutTunnel();
8385
+ assertNoTunnelOptions(opts);
8386
+ }
8387
+ const dryRunTargets = new Map();
8388
+ const automaticDryRun = opts.dryRun && targetUrl === undefined;
8389
+ if (automaticDryRun) {
8390
+ const targets = [];
8391
+ try {
8392
+ const client = makeClient({ ...opts, dryRun: false }, deps);
8393
+ const cache = deps.environmentCache ?? new Map();
8394
+ if (opts.all) {
8395
+ const target = await resolveEnvironmentRunTarget({
8396
+ client,
8397
+ projectId,
8398
+ environment,
8399
+ noWait: opts.noWait,
8400
+ tunnelClientId: opts.tunnelClientId,
8401
+ dryRun: true,
8402
+ cache,
8403
+ stderr: stderrFn,
8404
+ });
8405
+ if (target)
8406
+ targets.push(target);
8407
+ }
8408
+ for (const testId of opts.testIds) {
8409
+ const target = await resolveEnvironmentRunTarget({
8410
+ client,
8411
+ testId,
8412
+ projectId,
8413
+ environment,
8414
+ noWait: opts.noWait,
8415
+ tunnelClientId: opts.tunnelClientId,
8416
+ dryRun: true,
8417
+ cache,
8418
+ stderr: stderrFn,
8419
+ });
8420
+ if (target) {
8421
+ targets.push(target);
8422
+ dryRunTargets.set(testId, target);
8423
+ }
8424
+ }
8425
+ }
8426
+ catch (err) {
8427
+ if (err instanceof InterruptError)
8428
+ throw err;
8429
+ }
8430
+ if (!targets.length) {
8431
+ assertNoTunnelOptions(opts);
8432
+ severalIdsWithoutTunnel();
8433
+ }
8434
+ targetUrl = targets[0].targetUrl;
8435
+ }
7534
8436
  if (opts.dryRun) {
7535
8437
  emitDryRunBanner(stderrFn);
7536
8438
  const runs = (opts.all ? ['<each frontend test in the project>'] : opts.testIds).map(testId => ({
@@ -7538,8 +8440,12 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7538
8440
  path: `/api/cli/v1/tests/${testId}/runs`,
7539
8441
  body: {
7540
8442
  source: 'cli',
7541
- targetUrl,
7542
- tunnelClientId: opts.tunnelClientId ?? '<minted at run time>',
8443
+ ...(automaticDryRun && !opts.all && !dryRunTargets.has(testId)
8444
+ ? {}
8445
+ : {
8446
+ targetUrl: dryRunTargets.get(testId)?.targetUrl ?? targetUrl,
8447
+ tunnelClientId: opts.tunnelClientId ?? '<minted at run time>',
8448
+ }),
7543
8449
  ...(opts.autoHeal === false ? { autoHeal: false } : {}),
7544
8450
  ...(environment !== undefined ? { environment } : {}),
7545
8451
  },
@@ -7561,21 +8467,6 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7561
8467
  };
7562
8468
  const client = makeClient(clientOpts, deps);
7563
8469
  const tunnelRequestTimeoutMs = resolveRequestTimeoutMs(clientOpts, deps.env ?? process.env);
7564
- const probeLocalPort = async () => {
7565
- await assertLocalPortListening(opts.localHost, opts.localPort, { skipPreflight: opts.skipPreflight }, stderrFn);
7566
- if (isProxyAgentActive())
7567
- stderrFn('[advisory] An HTTP proxy is configured for this process. The tunnel control channel ' +
7568
- `honours it, but ${TUNNEL_DATA_PLANE_PROXY_BYPASS_DESCRIPTION} — if the ` +
7569
- 'run cannot reach your machine, an egress proxy is the first thing to rule out.');
7570
- };
7571
- // The local port is probed before anything leaves this machine — before the
7572
- // project's test list is even read — so a dead dev server costs nothing.
7573
- // `--all --allow-empty` is the exception: it explicitly accepts a project
7574
- // with nothing to run, and that answer must not depend on a server this
7575
- // invocation may never use, so its probe waits until there is a test to run.
7576
- const probeAfterListing = opts.all && opts.allowEmpty;
7577
- if (!probeAfterListing)
7578
- await probeLocalPort();
7579
8470
  const skipped = [];
7580
8471
  let tests = opts.testIds.map(id => ({ id }));
7581
8472
  const knownTests = new Map();
@@ -7590,18 +8481,77 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7590
8481
  const omitted = page.items.length - filtered.length;
7591
8482
  if (omitted > 0)
7592
8483
  stderrFn(`--filter: skipped ${omitted} test${omitted !== 1 ? 's' : ''} whose name does not contain "${opts.nameFilter}".`);
7593
- skipped.push(...filtered
7594
- .filter(t => t.type !== 'frontend')
7595
- .map(t => ({ testId: t.id, reason: 'backend-test' })));
7596
- if (skipped.length > 0)
7597
- stderrFn(`[advisory] ${skipped.length} backend test(s) skipped — --local runs frontend tests only.`);
7598
- tests = filtered
7599
- .filter(t => t.type === 'frontend')
7600
- .map(t => {
8484
+ tests = filtered.map(t => {
7601
8485
  knownTests.set(t.id, { type: t.type, projectId: t.projectId ?? projectId });
7602
8486
  return { id: t.id, name: t.name };
7603
8487
  });
7604
8488
  }
8489
+ const targets = new Map();
8490
+ const cache = new Map();
8491
+ for (const test of tests) {
8492
+ let known = knownTests.get(test.id);
8493
+ if (!known) {
8494
+ try {
8495
+ known = await readEnvironmentPreflight(client, `/tests/${encodeURIComponent(test.id)}`);
8496
+ }
8497
+ catch (err) {
8498
+ if (err instanceof InterruptError)
8499
+ throw err;
8500
+ if (opts.localPort !== undefined)
8501
+ throw err;
8502
+ }
8503
+ }
8504
+ const target = (known?.projectId === projectId && known?.type !== 'backend'
8505
+ ? opts.resolvedTarget
8506
+ : undefined) ??
8507
+ (await resolveEnvironmentRunTarget({
8508
+ client,
8509
+ testId: test.id,
8510
+ knownTest: known,
8511
+ skipTestLookup: true,
8512
+ includeBackend: opts.all || (opts.localPort === undefined && opts.targetUrl === undefined),
8513
+ environment,
8514
+ localPort: opts.localPort,
8515
+ localHost: opts.localHost,
8516
+ targetUrl: opts.targetUrl,
8517
+ noWait: opts.noWait,
8518
+ tunnelClientId: opts.tunnelClientId,
8519
+ verbose: opts.verbose || opts.debug,
8520
+ stderr: stderrFn,
8521
+ cache,
8522
+ }));
8523
+ if (target && known?.type === 'backend') {
8524
+ skipped.push({ testId: test.id, reason: 'backend-test' });
8525
+ }
8526
+ else if (target)
8527
+ targets.set(test.id, target);
8528
+ }
8529
+ const firstTarget = targets.values().next().value;
8530
+ if (!firstTarget && !(opts.all && tests.length === 0) && skipped.length === 0) {
8531
+ assertNoTunnelOptions(opts);
8532
+ if (!opts.all)
8533
+ severalIdsWithoutTunnel();
8534
+ return void (await runTestRunAll({
8535
+ ...opts,
8536
+ projectId: projectId,
8537
+ wait: opts.wait === true,
8538
+ environmentResolutionComplete: true,
8539
+ }, deps));
8540
+ }
8541
+ if (skipped.length)
8542
+ stderrFn(`[advisory] ${skipped.length} backend test(s) skipped — tunnel runs frontend tests only.`);
8543
+ assertFreshRunWaitOptions({ ...opts, wait: true }, true);
8544
+ tests = tests.filter(test => !skipped.some(row => row.testId === test.id));
8545
+ targetUrl = firstTarget?.targetUrl;
8546
+ opts = { ...opts, maxConcurrency: opts.concurrencyIsDefault ? 5 : opts.maxConcurrency };
8547
+ if (opts.maxConcurrency > 10)
8548
+ throw localValidationError('max-concurrency', 'tunnel runs support at most 10 concurrent runs (default 5)');
8549
+ for (const target of new Map([...targets.values()].map(target => [target.targetUrl, target])).values()) {
8550
+ await assertLocalPortListening(target.host, target.port, {
8551
+ skipPreflight: opts.skipPreflight,
8552
+ ...(target.automatic ? { environmentName: target.environmentName } : {}),
8553
+ }, stderrFn);
8554
+ }
7605
8555
  const results = tests.map(t => ({
7606
8556
  testId: t.id,
7607
8557
  ...(t.name !== undefined ? { testTitle: t.name } : {}),
@@ -7612,6 +8562,7 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7612
8562
  // start/finish timestamps; it stays out of the JSON, which only reports what
7613
8563
  // the server said.
7614
8564
  const clientSeconds = new WeakMap();
8565
+ const reportCreatedAt = new WeakMap();
7615
8566
  const batchSummary = () => {
7616
8567
  const passed = results.filter(r => r.status === 'passed').length;
7617
8568
  const timedOut = results.filter(r => r.status === 'timeout').length;
@@ -7652,7 +8603,11 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7652
8603
  stderr: stderrFn,
7653
8604
  }, 'run');
7654
8605
  await writeBatchJUnitReportIfRequested(opts, [
7655
- ...results.map(r => ({ ...r, status: r.runId === undefined ? 'skipped' : r.status })),
8606
+ ...results.map(r => ({
8607
+ ...r,
8608
+ createdAt: reportCreatedAt.get(r),
8609
+ status: r.runId === undefined ? 'skipped' : r.status,
8610
+ })),
7656
8611
  ...skipped.map(s => ({ testId: s.testId, status: 'skipped' })),
7657
8612
  ]);
7658
8613
  };
@@ -7708,22 +8663,20 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7708
8663
  opts,
7709
8664
  deps,
7710
8665
  stderrFn,
8666
+ // A project with only backend tests is not empty: they were skipped, not absent.
8667
+ emptyProject: opts.all && skipped.length === 0 && opts.nameFilter === undefined,
8668
+ projectId,
8669
+ local: {
8670
+ // An automatic target was resolved from a saved environment; its port
8671
+ // is that environment's, so the suggestion names the environment.
8672
+ ...(opts.resolvedTarget?.automatic ? {} : { host: opts.localHost, port: opts.localPort }),
8673
+ targetUrl: opts.targetUrl,
8674
+ environment: opts.environment ??
8675
+ (opts.resolvedTarget?.automatic ? opts.resolvedTarget.environmentName : undefined),
8676
+ },
7711
8677
  });
7712
8678
  return;
7713
8679
  }
7714
- if (probeAfterListing)
7715
- await probeLocalPort();
7716
- for (const test of tests) {
7717
- await preflightLocalRunTest({
7718
- client,
7719
- testId: test.id,
7720
- environment,
7721
- localPort: opts.localPort,
7722
- opts,
7723
- deps,
7724
- knownTest: knownTests.get(test.id),
7725
- });
7726
- }
7727
8680
  const shutdown = shutdownOf(deps);
7728
8681
  const disarm = shutdown.arm();
7729
8682
  const poolAbort = new AbortController();
@@ -7777,10 +8730,11 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7777
8730
  // partial result (every test `not-run`); the session helper has already
7778
8731
  // deleted a minted binding.
7779
8732
  if (!shutdown.signal.aborted)
7780
- throw err;
8733
+ throw tunnelScopeError(err);
7781
8734
  setAbort(shutdown.signal.reason);
7782
8735
  }
7783
8736
  if (session !== undefined) {
8737
+ recordTelemetryTunnelOpened(!session.adopted);
7784
8738
  stderrFn(`[tunnel] Reaching ${targetUrl} through TestSprite (client ${session.clientId}).`);
7785
8739
  stderrFn(`Running ${results.length} tests through one tunnel, up to ${opts.maxConcurrency} at a time.`);
7786
8740
  const liveSession = session;
@@ -7808,15 +8762,19 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7808
8762
  if (abortReason !== undefined)
7809
8763
  return;
7810
8764
  const fatalBeforeTrigger = liveSession.fatalReason();
7811
- if (fatalBeforeTrigger) {
8765
+ if (fatalBeforeTrigger && targets.has(row.testId)) {
7812
8766
  setAbort(new TunnelLostError(fatalBeforeTrigger, '', liveSession.fatalMessage()), fatalBeforeTrigger);
7813
8767
  return;
7814
8768
  }
7815
8769
  triggerStartedAtMs = Date.now();
7816
8770
  const triggering = withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, triggerClient => triggerClient.triggerRunWithMeta(row.testId, {
7817
8771
  source: 'cli',
7818
- targetUrl,
7819
- tunnelClientId: liveSession.clientId,
8772
+ ...(targets.has(row.testId)
8773
+ ? {
8774
+ targetUrl: targets.get(row.testId).targetUrl,
8775
+ tunnelClientId: liveSession.clientId,
8776
+ }
8777
+ : {}),
7820
8778
  ...(opts.autoHeal === false ? { autoHeal: false } : {}),
7821
8779
  ...(environment !== undefined ? { environment } : {}),
7822
8780
  }, { idempotencyKey: key }));
@@ -7830,7 +8788,8 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7830
8788
  row.runId = response.runId;
7831
8789
  row.status = 'running';
7832
8790
  activeRows.add(index);
7833
- unsettled.add(row);
8791
+ if (targets.has(row.testId))
8792
+ unsettled.add(row);
7834
8793
  activeRuns++;
7835
8794
  peakInFlight = Math.max(peakInFlight, activeRuns);
7836
8795
  stderrFn(`[${index + 1}/${results.length}] ${row.testId} → run ${row.runId}`);
@@ -7874,7 +8833,9 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7874
8833
  try {
7875
8834
  if (abortReason !== undefined)
7876
8835
  return;
7877
- if (liveSession.adopted && checkBorrowedLiveness === undefined) {
8836
+ if (targets.has(row.testId) &&
8837
+ liveSession.adopted &&
8838
+ checkBorrowedLiveness === undefined) {
7878
8839
  checkBorrowedLiveness = makeBorrowedTunnelLivenessCheck({
7879
8840
  client: livenessClient,
7880
8841
  clientId: liveSession.clientId,
@@ -7893,14 +8854,14 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7893
8854
  onTick: (run, elapsedMs) => {
7894
8855
  if (abortReason !== undefined)
7895
8856
  throw abortReason;
7896
- if (!isTerminalStatus(run.status)) {
8857
+ if (targets.has(row.testId) && !isTerminalStatus(run.status)) {
7897
8858
  const fatal = liveSession.fatalReason();
7898
8859
  if (fatal)
7899
8860
  throw new TunnelLostError(fatal, row.runId, liveSession.fatalMessage());
7900
8861
  }
7901
8862
  ticker.update(formatRunProgressLine(run, elapsedMs, `(${row.testId})`));
7902
8863
  },
7903
- ...(checkBorrowedLiveness
8864
+ ...(targets.has(row.testId) && checkBorrowedLiveness
7904
8865
  ? {
7905
8866
  resolveAlternate: async (_run, _elapsed, signal) => {
7906
8867
  await checkBorrowedLiveness(signal);
@@ -7913,6 +8874,7 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7913
8874
  unsettled.delete(row);
7914
8875
  row.testTitle = finalRun.testTitle ?? row.testTitle;
7915
8876
  row.projectId = finalRun.projectId;
8877
+ reportCreatedAt.set(row, finalRun.createdAt);
7916
8878
  row.startedAt = finalRun.startedAt;
7917
8879
  row.finishedAt = finalRun.finishedAt;
7918
8880
  if (typeof finalRun.dashboardUrl === 'string')
@@ -7958,7 +8920,7 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7958
8920
  // An owned run cannot finish once this process closes its tunnel, so a
7959
8921
  // run the batch stops waiting for is cancelled — unless the caller
7960
8922
  // opted out, exactly as the single-run path honours it.
7961
- if (!liveSession.adopted) {
8923
+ if (!liveSession.adopted && targets.has(row.testId)) {
7962
8924
  const cancel = await cancelDoomedTunnelRun({
7963
8925
  runId: row.runId,
7964
8926
  enabled: opts.cancelOnInterrupt,
@@ -8088,6 +9050,16 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8088
9050
  const waits = results.filter(r => r.runId && r.status === 'running').map(r => r.runId);
8089
9051
  if (waits.length)
8090
9052
  stderrFn(`Runs may still finish: testsprite test wait ${waits.join(' ')}`);
9053
+ if (abortReason instanceof InterruptError &&
9054
+ opts.cancelOnInterrupt === false &&
9055
+ session?.adopted === false &&
9056
+ waits.length) {
9057
+ stderrFn(tunnelInterruptOptOutConsequence({
9058
+ cancel: 'skipped',
9059
+ testId: results.find(r => r.runId === waits[0]).testId,
9060
+ runId: waits.join(' '),
9061
+ }));
9062
+ }
8091
9063
  if (session !== undefined)
8092
9064
  stderrFn(`Tunnel ${session.clientId}: ${unfinished.filter(r => r.cancel === 'cancelled').length} run(s) cancelled, ${waits.length} still running.`);
8093
9065
  if (lostReason !== undefined)
@@ -8138,11 +9110,7 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8138
9110
  * Batch / `--all`: `POST /tests/batch/rerun` → per-test runIds. With
8139
9111
  * `--wait`, fan-out poll under `--max-concurrency`. `deferred[]` → exit 7.
8140
9112
  */
8141
- export async function runTestRerun(opts, deps = {}) {
8142
- assertIdempotencyKey(opts.idempotencyKey);
8143
- const environment = normalizeEnvironmentName(opts.environment);
8144
- const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
8145
- const out = makeOutput(opts.output, deps);
9113
+ function validateRerunOptions(opts) {
8146
9114
  // -------------------------------------------------------------------------
8147
9115
  // Input validation
8148
9116
  // -------------------------------------------------------------------------
@@ -8194,7 +9162,7 @@ export async function runTestRerun(opts, deps = {}) {
8194
9162
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
8195
9163
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
8196
9164
  }
8197
- const isSingle = !opts.all && opts.testIds.length === 1;
9165
+ const isSingle = !opts.all && !opts.batchResolved && opts.testIds.length === 1;
8198
9166
  assertJUnitReportOptions({
8199
9167
  report: opts.report,
8200
9168
  reportFile: opts.reportFile,
@@ -8202,6 +9170,85 @@ export async function runTestRerun(opts, deps = {}) {
8202
9170
  wait: opts.wait,
8203
9171
  batchPath: !isSingle,
8204
9172
  });
9173
+ if (opts.ghOutput === true && (isSingle || !opts.wait))
9174
+ throw localValidationError('gh-output', '--gh-output requires a batch rerun with --wait (--all or 2+ test ids). Remove --gh-output, or add --all --wait.');
9175
+ if (opts.summaryFile !== undefined && (isSingle || !opts.wait))
9176
+ throw localValidationError('summary-file', '--summary-file requires a batch rerun with --wait (--all or 2+ test ids). Remove --summary-file, or add --all --wait.');
9177
+ return isSingle;
9178
+ }
9179
+ export async function runTestRerun(opts, deps = {}) {
9180
+ assertIdempotencyKey(opts.idempotencyKey);
9181
+ validateRerunOptions({ ...opts, wait: opts.wait || (!opts.dryRun && !opts.noWait) });
9182
+ if (opts.dryRun || deps.environmentTunnel || opts.testIds.length === 0 || opts.all)
9183
+ return runTestRerunCore(opts, deps);
9184
+ let client;
9185
+ try {
9186
+ client = makeClient(opts, deps);
9187
+ }
9188
+ catch (err) {
9189
+ validateRerunOptions(opts);
9190
+ throw err;
9191
+ }
9192
+ const stderr = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
9193
+ const targets = new Map();
9194
+ const backend = [];
9195
+ const cache = new Map();
9196
+ for (const testId of opts.testIds) {
9197
+ let knownTest = opts.knownTests?.get(testId);
9198
+ try {
9199
+ if (!knownTest)
9200
+ knownTest = await readEnvironmentPreflight(client, `/tests/${encodeURIComponent(testId)}`);
9201
+ }
9202
+ catch (err) {
9203
+ if (err instanceof InterruptError)
9204
+ throw err;
9205
+ }
9206
+ const target = await resolveEnvironmentRunTarget({
9207
+ client,
9208
+ testId,
9209
+ knownTest,
9210
+ skipTestLookup: true,
9211
+ includeBackend: opts.testIds.length > 1 || opts.batchResolved,
9212
+ environment: normalizeEnvironmentName(opts.environment),
9213
+ noWait: opts.noWait,
9214
+ verbose: opts.verbose || opts.debug,
9215
+ stderr,
9216
+ cache,
9217
+ });
9218
+ if (target && knownTest?.type === 'backend')
9219
+ backend.push(testId);
9220
+ else if (target)
9221
+ targets.set(testId, target);
9222
+ }
9223
+ if (!targets.size)
9224
+ return runTestRerunCore(opts, deps);
9225
+ const maxConcurrency = opts.concurrencyIsDefault ? 5 : opts.maxConcurrency;
9226
+ if (maxConcurrency > 10)
9227
+ throw localValidationError('max-concurrency', 'tunnel runs support at most 10 concurrent runs (default 5)');
9228
+ return withEnvironmentTunnel({
9229
+ ...opts,
9230
+ maxConcurrency,
9231
+ requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }),
9232
+ }, deps, [...targets.values()], 'test rerun', context => {
9233
+ context.targets = targets;
9234
+ context.skipped = backend.map(testId => ({ testId, reason: 'backend-test' }));
9235
+ if (backend.length)
9236
+ stderr(`[advisory] ${backend.length} backend test(s) skipped — tunnel runs frontend tests only.`);
9237
+ return runTestRerunCore({
9238
+ ...opts,
9239
+ testIds: opts.testIds.filter(id => !backend.includes(id)),
9240
+ batchResolved: opts.batchResolved || opts.testIds.length > 1,
9241
+ wait: true,
9242
+ maxConcurrency,
9243
+ }, { ...deps, environmentTunnel: context });
9244
+ });
9245
+ }
9246
+ async function runTestRerunCore(opts, deps = {}) {
9247
+ assertIdempotencyKey(opts.idempotencyKey);
9248
+ const environment = normalizeEnvironmentName(opts.environment);
9249
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
9250
+ const out = makeOutput(opts.output, deps);
9251
+ const isSingle = validateRerunOptions(opts.all && !opts.dryRun && !opts.noWait ? { ...opts, wait: true } : opts);
8205
9252
  // -------------------------------------------------------------------------
8206
9253
  // Pre-flight: auto-heal + Free-tier hint (best-effort, non-blocking)
8207
9254
  // -------------------------------------------------------------------------
@@ -8253,7 +9300,8 @@ export async function runTestRerun(opts, deps = {}) {
8253
9300
  }
8254
9301
  // D4: under --wait, raise the per-request timeout to cover --timeout so a
8255
9302
  // slow rerun trigger / long-poll under load isn't cut at the 120s default.
8256
- const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
9303
+ const client = deps.environmentTunnel?.client ??
9304
+ makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
8257
9305
  // `--env` gate — see `runTestRun`. Before the type probe and every dispatch.
8258
9306
  const idempotencyKey = opts.idempotencyKey ?? `cli-rerun-${randomUUID()}`;
8259
9307
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
@@ -8292,6 +9340,12 @@ export async function runTestRerun(opts, deps = {}) {
8292
9340
  try {
8293
9341
  rerunResp = await client.triggerRerun(testId, {
8294
9342
  source: 'cli',
9343
+ ...(deps.environmentTunnel?.targets?.has(testId)
9344
+ ? {
9345
+ tunnelClientId: deps.environmentTunnel.clientId,
9346
+ targetUrl: deps.environmentTunnel.targets.get(testId).targetUrl,
9347
+ }
9348
+ : {}),
8295
9349
  // Always send the effective boolean, including an explicit `false`
8296
9350
  // opt-out — the server defaults an ABSENT field to heal-on, so
8297
9351
  // omitting the key on opt-out silently discarded --no-auto-heal.
@@ -8299,6 +9353,7 @@ export async function runTestRerun(opts, deps = {}) {
8299
9353
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
8300
9354
  ...(environment !== undefined ? { environment } : {}),
8301
9355
  }, { idempotencyKey });
9356
+ await deps.environmentTunnel?.confirm(rerunResp, [rerunResp.runId]);
8302
9357
  }
8303
9358
  catch (err) {
8304
9359
  if (err instanceof ApiError && err.code === 'CONFLICT') {
@@ -8443,7 +9498,10 @@ export async function runTestRerun(opts, deps = {}) {
8443
9498
  sleep: deps.sleep,
8444
9499
  shutdown: shutdownOf(deps),
8445
9500
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
8446
- onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `[${member.role}]`)),
9501
+ onTick: (run, elapsedMs) => {
9502
+ deps.environmentTunnel?.onPoll(run);
9503
+ ticker.update(formatRunProgressLine(run, elapsedMs, `[${member.role}]`));
9504
+ },
8447
9505
  resolveAlternate,
8448
9506
  });
8449
9507
  return { kind: 'terminal', run: finalRun };
@@ -8719,7 +9777,10 @@ export async function runTestRerun(opts, deps = {}) {
8719
9777
  sleep: deps.sleep,
8720
9778
  shutdown: shutdownOf(deps),
8721
9779
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
8722
- onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, '(replay)')),
9780
+ onTick: (run, elapsedMs) => {
9781
+ deps.environmentTunnel?.onPoll(run);
9782
+ ticker.update(formatRunProgressLine(run, elapsedMs, '(replay)'));
9783
+ },
8723
9784
  resolveAlternate,
8724
9785
  });
8725
9786
  }
@@ -8736,15 +9797,21 @@ export async function runTestRerun(opts, deps = {}) {
8736
9797
  return [
8737
9798
  `runId ${p.runId}`,
8738
9799
  `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
8739
- `hint Re-attach with: testsprite test wait ${p.runId}`,
9800
+ deps.environmentTunnel
9801
+ ? `hint The owned tunnel is closing; inspect cancellation with testsprite test cancel ${p.runId}`
9802
+ : `hint Re-attach with: testsprite test wait ${p.runId}`,
8740
9803
  ].join('\n');
8741
9804
  });
8742
9805
  throw ApiError.fromEnvelope({
8743
9806
  error: {
8744
9807
  code: 'UNSUPPORTED',
8745
9808
  message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${rerunResp.runId}. ` +
8746
- stillRunningAndBillingSubject(rerunResp.runId),
8747
- nextAction: `Resume polling: testsprite test wait ${rerunResp.runId}, or cancel it: testsprite test cancel ${rerunResp.runId}`,
9809
+ (deps.environmentTunnel
9810
+ ? 'The owned tunnel is closing; cancellation will be requested.'
9811
+ : stillRunningAndBillingSubject(rerunResp.runId)),
9812
+ nextAction: deps.environmentTunnel
9813
+ ? `Inspect cancellation: testsprite test cancel ${rerunResp.runId}. Start a new run: testsprite test run ${testId}${environment ? ` --env ${quoteEnvironmentName(environment)}` : ''}.`
9814
+ : `Resume polling: testsprite test wait ${rerunResp.runId}, or cancel it: testsprite test cancel ${rerunResp.runId}`,
8748
9815
  requestId: 'local',
8749
9816
  details: { runId: rerunResp.runId, timeoutSeconds: opts.timeoutSeconds },
8750
9817
  },
@@ -8760,12 +9827,16 @@ export async function runTestRerun(opts, deps = {}) {
8760
9827
  return [
8761
9828
  `runId ${p.runId}`,
8762
9829
  `status ${p.status} (request timed out)`,
8763
- `hint Re-attach with: testsprite test wait ${p.runId}`,
9830
+ deps.environmentTunnel
9831
+ ? `hint The owned tunnel is closing; inspect cancellation with testsprite test cancel ${p.runId}`
9832
+ : `hint Re-attach with: testsprite test wait ${p.runId}`,
8764
9833
  `hint Cancel with: testsprite test cancel ${p.runId}`,
8765
9834
  ].join('\n');
8766
9835
  });
8767
- stderrFn(`Request timed out. ${stillRunningAndBillingSubject(rerunResp.runId)} ` +
8768
- `Re-attach with: testsprite test wait ${rerunResp.runId}, or cancel with: testsprite test cancel ${rerunResp.runId}`);
9836
+ stderrFn(`Request timed out. ${deps.environmentTunnel ? 'The owned tunnel is closing; cancellation will be requested.' : stillRunningAndBillingSubject(rerunResp.runId)} ` +
9837
+ (deps.environmentTunnel
9838
+ ? `Inspect cancellation with testsprite test cancel ${rerunResp.runId}.`
9839
+ : `Re-attach with: testsprite test wait ${rerunResp.runId}, or cancel with: testsprite test cancel ${rerunResp.runId}`));
8769
9840
  throw err;
8770
9841
  }
8771
9842
  // RATE_LIMITED during polling — see the matching comment in runTestRun.
@@ -8779,11 +9850,15 @@ export async function runTestRerun(opts, deps = {}) {
8779
9850
  return [
8780
9851
  `runId ${p.runId}`,
8781
9852
  `status ${p.status} (rate limited by the server)`,
8782
- `hint Re-attach with: testsprite test wait ${p.runId}`,
9853
+ deps.environmentTunnel
9854
+ ? `hint The owned tunnel is closing; inspect cancellation with testsprite test cancel ${p.runId}`
9855
+ : `hint Re-attach with: testsprite test wait ${p.runId}`,
8783
9856
  `hint Cancel with: testsprite test cancel ${p.runId}`,
8784
9857
  ].join('\n');
8785
9858
  });
8786
- stderrFn(rateLimitedDetachMessage(err, [rerunResp.runId]));
9859
+ stderrFn(deps.environmentTunnel
9860
+ ? `The owned tunnel is closing; cancellation will be requested. Inspect with testsprite test cancel ${rerunResp.runId}.`
9861
+ : rateLimitedDetachMessage(err, [rerunResp.runId]));
8787
9862
  throw err;
8788
9863
  }
8789
9864
  // Graceful detach on SIGINT/SIGTERM — see runTestRun.
@@ -8795,11 +9870,15 @@ export async function runTestRerun(opts, deps = {}) {
8795
9870
  return [
8796
9871
  `runId ${p.runId}`,
8797
9872
  `status ${p.status} (interrupted)`,
8798
- `hint Re-attach with: testsprite test wait ${p.runId}`,
9873
+ deps.environmentTunnel
9874
+ ? `hint The owned tunnel is closing; inspect cancellation with testsprite test cancel ${p.runId}`
9875
+ : `hint Re-attach with: testsprite test wait ${p.runId}`,
8799
9876
  `hint Cancel with: testsprite test cancel ${p.runId}`,
8800
9877
  ].join('\n');
8801
9878
  });
8802
- stderrFn(interruptDetachMessage(err, [rerunResp.runId]));
9879
+ stderrFn(deps.environmentTunnel
9880
+ ? `Interrupted (${err.signal}). Cancellation will be requested for ${rerunResp.runId} before the owned tunnel closes.`
9881
+ : interruptDetachMessage(err, [rerunResp.runId]));
8803
9882
  err.runWaitContext = true;
8804
9883
  throw err;
8805
9884
  }
@@ -8828,6 +9907,7 @@ export async function runTestRerun(opts, deps = {}) {
8828
9907
  // Batch / --all rerun path
8829
9908
  // -------------------------------------------------------------------------
8830
9909
  let testIds = opts.testIds;
9910
+ let knownTests = opts.knownTests;
8831
9911
  if (opts.all) {
8832
9912
  // Validate --status filter before any network call.
8833
9913
  if (opts.statusFilter !== undefined) {
@@ -8875,7 +9955,9 @@ export async function runTestRerun(opts, deps = {}) {
8875
9955
  }
8876
9956
  }
8877
9957
  testIds = allTests.map(t => t.id);
9958
+ knownTests = new Map(allTests.map(t => [t.id, { type: t.type, projectId: t.projectId ?? opts.projectId }]));
8878
9959
  if (testIds.length === 0) {
9960
+ validateRerunOptions(opts);
8879
9961
  stderrFn(`No tests found in project ${opts.projectId} matching filters — nothing to rerun.`);
8880
9962
  out.print({ accepted: [], deferred: [], conflicts: [], closure: { byProject: [] } });
8881
9963
  // Zero-dispatch: emit the CI artifacts and fail with exit 5 unless
@@ -8902,13 +9984,32 @@ export async function runTestRerun(opts, deps = {}) {
8902
9984
  // safe) and aggregate accepted/deferred/conflicts/closure into a single
8903
9985
  // synthetic BatchRerunResponse that downstream --wait / exit-code logic
8904
9986
  // can treat as one result.
9987
+ if (opts.all && !deps.environmentTunnel) {
9988
+ return runTestRerun({
9989
+ ...opts,
9990
+ testIds,
9991
+ idempotencyKey,
9992
+ all: false,
9993
+ batchResolved: true,
9994
+ knownTests,
9995
+ nameFilter: undefined,
9996
+ statusFilter: undefined,
9997
+ skipTerminal: undefined,
9998
+ allowEmpty: undefined,
9999
+ }, deps);
10000
+ }
8905
10001
  const chunks = [];
8906
10002
  for (let i = 0; i < testIds.length; i += MAX_BATCH_RERUN_IDS) {
8907
10003
  chunks.push(testIds.slice(i, i + MAX_BATCH_RERUN_IDS));
8908
10004
  }
8909
10005
  if (chunks.length === 0)
8910
10006
  chunks.push([]); // defensive: empty list handled above
8911
- let chunkResponses;
10007
+ if (deps.environmentTunnel?.targets) {
10008
+ const grouped = chunks.flatMap(chunk => groupEnvironmentTargets(chunk, deps.environmentTunnel.targets, deps.environmentTunnel.maxConcurrency));
10009
+ chunks.splice(0, chunks.length, ...grouped);
10010
+ }
10011
+ let chunkResponses = [];
10012
+ let waitingForCapacity = false;
8912
10013
  try {
8913
10014
  // Dispatch chunks one at a time, NOT via Promise.all. BE producer/
8914
10015
  // teardown closure dedup happens per-request, server-side. Two chunks
@@ -8928,9 +10029,20 @@ export async function runTestRerun(opts, deps = {}) {
8928
10029
  ? idempotencyKey.slice(0, 256 - chunkSuffix.length)
8929
10030
  : idempotencyKey;
8930
10031
  const chunkKey = `${chunkBase}${chunkSuffix}`;
10032
+ if (deps.environmentTunnel?.targets?.has(chunk[0])) {
10033
+ waitingForCapacity = true;
10034
+ await deps.environmentTunnel.waitForCapacity(chunk.length);
10035
+ waitingForCapacity = false;
10036
+ }
8931
10037
  const chunkResp = await client.triggerBatchRerun({
8932
10038
  source: 'cli',
8933
10039
  testIds: chunk,
10040
+ ...(deps.environmentTunnel?.targets?.has(chunk[0])
10041
+ ? {
10042
+ tunnelClientId: deps.environmentTunnel.clientId,
10043
+ targetUrl: deps.environmentTunnel.targets.get(chunk[0]).targetUrl,
10044
+ }
10045
+ : {}),
8934
10046
  // Always send the effective boolean, including an explicit `false`
8935
10047
  // opt-out — see the matching comment on the single-rerun call site.
8936
10048
  autoHeal: effectiveAutoHeal,
@@ -8938,16 +10050,20 @@ export async function runTestRerun(opts, deps = {}) {
8938
10050
  ...(environment !== undefined ? { environment } : {}),
8939
10051
  }, { idempotencyKey: chunkKey });
8940
10052
  chunkResponses.push(chunkResp);
10053
+ if (deps.environmentTunnel?.targets?.has(chunk[0]))
10054
+ await deps.environmentTunnel.confirm(chunkResp, chunkResp.accepted.map(row => row.runId));
8941
10055
  }
8942
10056
  }
8943
10057
  catch (err) {
10058
+ if (deps.environmentTunnel && chunkResponses.length)
10059
+ await emitEnvironmentDispatchPartial(chunkResponses, testIds, opts, deps, 'rerun', err, deps.environmentTunnel);
8944
10060
  // D2 (dogfood): the batch endpoint rejects the WHOLE request when any id is
8945
10061
  // unresolvable (unknown, cross-tenant, or never ran cleanly), so one bad id
8946
10062
  // aborts the batch with NOT_FOUND. Replace the bare exit-4 with an
8947
10063
  // actionable hint. (Server-side partial-accept of unknown ids — a
8948
10064
  // `notFound[]` in the batch response so good ids still run — is a tracked
8949
10065
  // backend follow-up.)
8950
- if (err instanceof ApiError && err.code === 'NOT_FOUND') {
10066
+ if (!waitingForCapacity && err instanceof ApiError && err.code === 'NOT_FOUND') {
8951
10067
  throw ApiError.fromEnvelope({
8952
10068
  error: {
8953
10069
  code: 'NOT_FOUND',
@@ -8969,6 +10085,7 @@ export async function runTestRerun(opts, deps = {}) {
8969
10085
  const { deduped: dedupedAccepted, dropped: duplicateAccepted } = dedupeBatchRerunAccepted(chunkResponses.flatMap(r => r.accepted));
8970
10086
  warnDroppedDuplicateRuns(dedupedAccepted, duplicateAccepted, stderrFn);
8971
10087
  const batchResp = {
10088
+ ...(deps.environmentTunnel?.skipped?.length ? { skipped: deps.environmentTunnel.skipped } : {}),
8972
10089
  accepted: dedupedAccepted,
8973
10090
  deferred: chunkResponses.flatMap(r => r.deferred),
8974
10091
  conflicts: chunkResponses.flatMap(r => r.conflicts),
@@ -9031,6 +10148,22 @@ export async function runTestRerun(opts, deps = {}) {
9031
10148
  const deferredIds = deferred.map(d => d.testId).join(' ');
9032
10149
  stderrFn(`nextAction: testsprite test rerun ${deferredIds}`);
9033
10150
  }
10151
+ const emitRetryPartial = async (error, responses = []) => {
10152
+ if (!deps.environmentTunnel)
10153
+ return;
10154
+ const retried = new Set(responses
10155
+ .flatMap(response => [...response.accepted, ...response.conflicts, ...response.deferred])
10156
+ .map(row => row.testId));
10157
+ await emitEnvironmentDispatchPartial([
10158
+ {
10159
+ accepted,
10160
+ conflicts,
10161
+ deferred: deferred.filter(row => !retried.has(row.testId)),
10162
+ notFound,
10163
+ },
10164
+ ...responses,
10165
+ ], testIds, opts, deps, 'rerun', error, deps.environmentTunnel);
10166
+ };
9034
10167
  // D3: budget-driven deferred-retry loop for rerun --all (only under --wait).
9035
10168
  // Re-dispatches still-deferred tests until they all clear OR the --timeout
9036
10169
  // budget is exhausted — a busy pool drains within the user's own timeout
@@ -9040,7 +10173,7 @@ export async function runTestRerun(opts, deps = {}) {
9040
10173
  // through to the existing exit-7 path. `maxDeferredAttempts` is a pure runaway
9041
10174
  // backstop (the deadline check below is the real stop), scaled to the timeout.
9042
10175
  const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
9043
- const batchDeadlineMs = Date.now() + opts.timeoutSeconds * 1000;
10176
+ const batchDeadlineMs = deps.environmentTunnel?.deadlineMs ?? Date.now() + opts.timeoutSeconds * 1000;
9044
10177
  // finding 1: reserve a poll window so the deferred-retry loop can't consume the
9045
10178
  // ENTIRE --timeout and leave the fan-out poll with nothing — which would report
9046
10179
  // already-finished runs as timeouts (exit 7) instead of their real verdicts
@@ -9059,7 +10192,16 @@ export async function runTestRerun(opts, deps = {}) {
9059
10192
  // POLL_RESERVE_MS, so the difference is always positive).
9060
10193
  const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs - POLL_RESERVE_MS);
9061
10194
  stderrFn(`[deferred-retry] attempt ${attempt} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
9062
- await sleepFn(sleepMs);
10195
+ try {
10196
+ if (deps.environmentTunnel)
10197
+ await sleepUntilOrInterrupt(sleepMs, shutdownOf(deps).signal, sleepFn);
10198
+ else
10199
+ await sleepFn(sleepMs);
10200
+ }
10201
+ catch (err) {
10202
+ await emitRetryPartial(err);
10203
+ throw err;
10204
+ }
9063
10205
  const remainingAfterSleep = batchDeadlineMs - Date.now();
9064
10206
  if (remainingAfterSleep <= POLL_RESERVE_MS) {
9065
10207
  stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
@@ -9071,12 +10213,15 @@ export async function runTestRerun(opts, deps = {}) {
9071
10213
  for (let i = 0; i < retryIds.length; i += MAX_BATCH_RERUN_IDS) {
9072
10214
  retryChunks.push(retryIds.slice(i, i + MAX_BATCH_RERUN_IDS));
9073
10215
  }
9074
- let retryChunkResponses;
10216
+ if (deps.environmentTunnel?.targets) {
10217
+ const grouped = retryChunks.flatMap(chunk => groupEnvironmentTargets(chunk, deps.environmentTunnel.targets, deps.environmentTunnel.maxConcurrency));
10218
+ retryChunks.splice(0, retryChunks.length, ...grouped);
10219
+ }
10220
+ const retryChunkResponses = [];
9075
10221
  try {
9076
10222
  // Sequential, same reason as the initial dispatch above: concurrent
9077
10223
  // chunks racing on per-request server-side closure dedup can
9078
10224
  // double-trigger a shared BE producer/teardown.
9079
- retryChunkResponses = [];
9080
10225
  for (let idx = 0; idx < retryChunks.length; idx++) {
9081
10226
  const chunk = retryChunks[idx];
9082
10227
  // [P2] Bound the derived key to ≤256 chars. Caller-supplied keys may
@@ -9097,9 +10242,18 @@ export async function runTestRerun(opts, deps = {}) {
9097
10242
  // still-deferred, inviting a duplicate rerun on the user's next
9098
10243
  // invocation. The per-request timeout still bounds it; the sleeps +
9099
10244
  // poll stay deadline-aware.
10245
+ if (deps.environmentTunnel?.targets?.has(chunk[0]))
10246
+ await deps.environmentTunnel.waitForCapacity(chunk.length);
9100
10247
  const retryChunkResp = await client.triggerBatchRerun({
9101
10248
  source: 'cli',
9102
10249
  testIds: chunk,
10250
+ ...(environment !== undefined ? { environment } : {}),
10251
+ ...(deps.environmentTunnel?.targets?.has(chunk[0])
10252
+ ? {
10253
+ tunnelClientId: deps.environmentTunnel.clientId,
10254
+ targetUrl: deps.environmentTunnel.targets.get(chunk[0]).targetUrl,
10255
+ }
10256
+ : {}),
9103
10257
  // Always send the effective boolean, including an explicit
9104
10258
  // `false` opt-out — see the matching comment on the initial
9105
10259
  // dispatch call site above.
@@ -9107,9 +10261,15 @@ export async function runTestRerun(opts, deps = {}) {
9107
10261
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
9108
10262
  }, { idempotencyKey: retryKey });
9109
10263
  retryChunkResponses.push(retryChunkResp);
10264
+ if (deps.environmentTunnel?.targets?.has(chunk[0]))
10265
+ await deps.environmentTunnel.confirm(retryChunkResp, retryChunkResp.accepted.map(row => row.runId));
9110
10266
  }
9111
10267
  }
9112
10268
  catch (err) {
10269
+ if (deps.environmentTunnel) {
10270
+ await emitRetryPartial(err, retryChunkResponses);
10271
+ throw err;
10272
+ }
9113
10273
  if (err instanceof InterruptError)
9114
10274
  throw err;
9115
10275
  stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
@@ -9285,6 +10445,7 @@ export async function runTestRerun(opts, deps = {}) {
9285
10445
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
9286
10446
  const concurrencyLimit = opts.maxConcurrency;
9287
10447
  const rerunResults = [];
10448
+ const reportTiming = new Map();
9288
10449
  // sleepFn is declared above in the D3 deferred-retry section (shared by fan-out).
9289
10450
  async function pollAccepted(entry) {
9290
10451
  const resolveAlternate = makeBackendWaitFallback({
@@ -9305,9 +10466,17 @@ export async function runTestRerun(opts, deps = {}) {
9305
10466
  sleep: deps.sleep,
9306
10467
  shutdown: shutdownOf(deps),
9307
10468
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
9308
- onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`)),
10469
+ onTick: (run, elapsedMs) => {
10470
+ deps.environmentTunnel?.onPoll(run);
10471
+ ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`));
10472
+ },
9309
10473
  resolveAlternate,
9310
10474
  });
10475
+ reportTiming.set(entry.runId, {
10476
+ createdAt: finalRun.createdAt,
10477
+ startedAt: finalRun.startedAt,
10478
+ finishedAt: finalRun.finishedAt,
10479
+ });
9311
10480
  return {
9312
10481
  testId: entry.testId,
9313
10482
  testTitle: finalRun.testTitle ?? null,
@@ -9323,6 +10492,8 @@ export async function runTestRerun(opts, deps = {}) {
9323
10492
  };
9324
10493
  }
9325
10494
  catch (err) {
10495
+ if (deps.environmentTunnel && err instanceof TunnelLostError)
10496
+ throw err;
9326
10497
  if (err instanceof TimeoutError) {
9327
10498
  deps.onWaitTimeout?.({ reason: 'wait_timeout' });
9328
10499
  return {
@@ -9400,7 +10571,13 @@ export async function runTestRerun(opts, deps = {}) {
9400
10571
  // Graceful detach: stdout stays parseable — settled members
9401
10572
  // keep their real status, unfinished ones are marked running — and the
9402
10573
  // honest stderr line names every runId still executing (and billing).
9403
- if (fanOutErr instanceof InterruptError) {
10574
+ if (deps.environmentTunnel) {
10575
+ ticker.finalize();
10576
+ await emitEnvironmentDispatchPartial([{ accepted, deferred, conflicts, notFound }], testIds, opts, deps, 'rerun', fanOutErr, deps.environmentTunnel);
10577
+ if (fanOutErr instanceof InterruptError)
10578
+ fanOutErr.runWaitContext = true;
10579
+ }
10580
+ else if (fanOutErr instanceof InterruptError) {
9404
10581
  ticker.finalize(`Batch rerun — interrupted (${fanOutErr.signal})`);
9405
10582
  const settled = new Map(rerunResults.map(r => [r.runId, r]));
9406
10583
  const partialResults = accepted.map((e) => settled.get(e.runId) ?? { testId: e.testId, runId: e.runId, status: 'running' });
@@ -9408,7 +10585,9 @@ export async function runTestRerun(opts, deps = {}) {
9408
10585
  const unfinished = accepted.filter(e => !settled.has(e.runId)).map(e => e.runId);
9409
10586
  if (unfinished.length > 0) {
9410
10587
  fanOutErr.runWaitContext = true;
9411
- stderrFn(interruptDetachMessage(fanOutErr, unfinished));
10588
+ stderrFn(deps.environmentTunnel
10589
+ ? `Interrupted (${fanOutErr.signal}). Cancellation will be requested for unfinished tunnel runs before the owned tunnel closes.`
10590
+ : interruptDetachMessage(fanOutErr, unfinished));
9412
10591
  }
9413
10592
  }
9414
10593
  throw fanOutErr;
@@ -9419,6 +10598,7 @@ export async function runTestRerun(opts, deps = {}) {
9419
10598
  const timedOut = rerunResults.filter(r => r.status === 'timeout').length;
9420
10599
  stderrFn(`Batch rerun complete: ${passed}/${accepted.length} passed, ${failed} failed/blocked, ${timedOut} timed out`);
9421
10600
  const jsonPayload = {
10601
+ ...(deps.environmentTunnel?.skipped?.length ? { skipped: deps.environmentTunnel.skipped } : {}),
9422
10602
  accepted: rerunResults,
9423
10603
  // [P2] Use post-retry mutable vars, not the stale initial batchResp fields.
9424
10604
  // batchResp.deferred/conflicts reflect only the INITIAL response; after D3
@@ -9453,7 +10633,7 @@ export async function runTestRerun(opts, deps = {}) {
9453
10633
  const rerunNameMap = opts.report === 'junit' && opts.reportFile !== undefined
9454
10634
  ? await buildTestNameMap(client, opts.projectId)
9455
10635
  : undefined;
9456
- await writeBatchJUnitReportIfRequested(opts, rerunResults, rerunNameMap);
10636
+ await writeBatchJUnitReportIfRequested(opts, rerunResults.map(r => ({ ...r, ...(r.runId ? reportTiming.get(r.runId) : {}) })), rerunNameMap);
9457
10637
  out.print(jsonPayload);
9458
10638
  // CI-native output layer (issue #99): batch-rerun parity with `run --all`.
9459
10639
  // Emitted before the exit-code gates below so the summary file / annotations
@@ -9705,7 +10885,7 @@ const SKIP_PREFLIGHT_HELP = 'skip the pre-charge reachability probe for a target
9705
10885
  'from the Lambda that executes the test, so it can occasionally be wrong (e.g. an IP allowlist ' +
9706
10886
  'that permits the Lambda but not this machine); use this flag when you know better. Zero network ' +
9707
10887
  'calls when set.';
9708
- const TARGET_URL_HELP = "frontend tests only: use the environment already pointing at this URL's origin, or a temporary one TestSprite deletes when the run finishes; with --env, use its settings against this URL";
10888
+ const TARGET_URL_HELP = "frontend tests only: use the environment already pointing at this URL's origin, or a temporary one TestSprite deletes when the run finishes; with --env, use its settings against this URL; loopback URLs open a tunnel automatically";
9709
10889
  export function createTestCommand(deps = {}) {
9710
10890
  const test = new Command('test').description('Inspect TestSprite tests');
9711
10891
  test
@@ -9718,6 +10898,7 @@ export function createTestCommand(deps = {}) {
9718
10898
  // below raises `ApiError(VALIDATION_ERROR)` so JSON consumers can read
9719
10899
  // `error.code` and the exit code matches the catalog.
9720
10900
  .option('--project <id>', 'project id (returned by `testsprite project list`)')
10901
+ .option('--env <name>', 'show frontend test statuses for the named project environment')
9721
10902
  .option('--type <type>', 'filter by test type (frontend|backend)')
9722
10903
  .option('--created-from <source>', 'filter by where the test was authored (portal|mcp|cli)')
9723
10904
  .option('--status <list>', 'filter by normalized status (comma-separated). One of: draft, ready, queued, running, passed, failed, blocked, cancelled, unknown')
@@ -9740,6 +10921,7 @@ export function createTestCommand(deps = {}) {
9740
10921
  await runList({
9741
10922
  ...resolveCommonOptions(command, deps.env),
9742
10923
  projectId: cmdOpts.project,
10924
+ environment: cmdOpts.env,
9743
10925
  type: parseEnumFlag(cmdOpts.type, 'type', TEST_TYPES),
9744
10926
  createdFrom: parseEnumFlag(cmdOpts.createdFrom, 'created-from', CREATED_FROMS),
9745
10927
  status: cmdOpts.status,
@@ -9764,7 +10946,7 @@ export function createTestCommand(deps = {}) {
9764
10946
  .option('--type <type>', 'frontend|backend')
9765
10947
  .option('--name <name>', 'human-readable test name (becomes `title` in storage)')
9766
10948
  .option('--description <text>', 'optional human description (≤ 2000 chars)')
9767
- .option('--priority <prio>', 'optional priority — one of: p0, p1, p2, p3')
10949
+ .option('--priority <prio>', 'optional priority: p0/high, p1/medium, p2/low (p3 = low)')
9768
10950
  .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000); applied by the execution engine to every step of this test')
9769
10951
  .option('--code-file <path>', 'file containing the test code (≤ 350 KB)')
9770
10952
  .option('--plan-from <path>', 'JSON file with the full FE test definition — projectId, type, name, planSteps[] all live in the file ' +
@@ -9773,9 +10955,10 @@ export function createTestCommand(deps = {}) {
9773
10955
  'ignores every other flag). Pipe to a file and edit: `--plan-template > plan.json`.', false)
9774
10956
  .option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
9775
10957
  .option('--wait', 'with --run, poll until terminal status', false)
10958
+ .option('--no-wait', 'detach without opening an automatic environment tunnel')
9776
10959
  .option('--timeout <s>', 'with --run --wait, max seconds to wait')
9777
10960
  .option('--target-url <url>', TARGET_URL_HELP)
9778
- .option('--env <name>', 'with --run, run against the named project environment')
10961
+ .option('--env <name>', 'with --run, select the named project environment; loopback URLs open a tunnel automatically')
9779
10962
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
9780
10963
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
9781
10964
  .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering on `test rerun` and `test run --all`.', (val, prev) => [...(prev ?? []), val], [])
@@ -9842,6 +11025,7 @@ export function createTestCommand(deps = {}) {
9842
11025
  planFrom: cmdOpts.planFrom,
9843
11026
  run: cmdOpts.run === true,
9844
11027
  wait: cmdOpts.wait === true,
11028
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
9845
11029
  timeout: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
9846
11030
  // B2(c): capture before parseTimeoutFlag converts undefined → default.
9847
11031
  timeoutIsDefault: cmdOpts.timeout === undefined,
@@ -9859,13 +11043,14 @@ export function createTestCommand(deps = {}) {
9859
11043
  type: parseEnumFlag(cmdOpts.type, 'type', TEST_TYPES),
9860
11044
  name: cmdOpts.name,
9861
11045
  description: cmdOpts.description,
9862
- priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
11046
+ priority: parsePriorityFlag(cmdOpts.priority),
9863
11047
  stepTimeoutMs: parseStepTimeoutFlag(cmdOpts.stepTimeout, 'step-timeout'),
9864
11048
  codeFile: cmdOpts.codeFile,
9865
11049
  idempotencyKey: cmdOpts.idempotencyKey,
9866
11050
  // M3.3 chain flags:
9867
11051
  run: cmdOpts.run === true,
9868
11052
  wait: cmdOpts.wait === true,
11053
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
9869
11054
  timeout: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
9870
11055
  // B2(c): capture before parseTimeoutFlag converts undefined → default.
9871
11056
  timeoutIsDefault: cmdOpts.timeout === undefined,
@@ -9889,9 +11074,10 @@ export function createTestCommand(deps = {}) {
9889
11074
  .option('--max-concurrency <n>', 'with --run, max in-flight triggers at once (1-100, default: 50). The server caps run-triggers at 60/min/key; the CLI throttles to 50/min and auto-retries RATE_LIMITED responses client-side — raising this value does not bypass the server cap. ' +
9890
11075
  `Separately, CLI run triggers are refused once ${SERVER_INFLIGHT_RUN_CAP} of your runs are already in flight (server default; the refusal reports your account's real cap). Runs from every source count toward it, and a large batch can reach it on its own, so anything already running makes later triggers exit 11 with details.reason "inflight_cap" — not auto-retried, runs have to finish first. With --wait a slot is held until each run finishes, so lowering this flag keeps fewer runs in flight; without --wait it only paces dispatch, and a smaller batch is the lever.`)
9891
11076
  .option('--wait', 'with --run, poll each run until terminal status', false)
11077
+ .option('--no-wait', 'detach without opening an automatic environment tunnel')
9892
11078
  .option('--timeout <s>', 'with --run --wait, per-run max seconds to wait (1-3600, default 600)')
9893
11079
  .option('--target-url <url>', TARGET_URL_HELP)
9894
- .option('--env <name>', 'with --run, run each created test against the named project environment')
11080
+ .option('--env <name>', 'with --run, select the named project environment for each test; loopback URLs open a tunnel automatically')
9895
11081
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
9896
11082
  .option('--idempotency-key <token>', 'opaque idempotency token for the batch create (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
9897
11083
  .addHelpText('after', GLOBAL_OPTS_HINT)
@@ -9903,6 +11089,7 @@ export function createTestCommand(deps = {}) {
9903
11089
  run: cmdOpts.run === true,
9904
11090
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency'),
9905
11091
  wait: cmdOpts.wait === true,
11092
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
9906
11093
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
9907
11094
  targetUrl: cmdOpts.targetUrl,
9908
11095
  environment: cmdOpts.env,
@@ -10040,7 +11227,7 @@ export function createTestCommand(deps = {}) {
10040
11227
  .description('Update test metadata — name, description, priority, step timeout')
10041
11228
  .option('--name <name>', 'new human-readable test name')
10042
11229
  .option('--description <text>', 'new human description (≤ 2000 chars)')
10043
- .option('--priority <prio>', 'new priority — one of: p0, p1, p2, p3')
11230
+ .option('--priority <prio>', 'new priority: p0/high, p1/medium, p2/low (p3 = low)')
10044
11231
  .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000); applied by the execution engine to every step of this test')
10045
11232
  .option('--clear-step-timeout', 'clear the per-test step timeout and restore execution engine defaults', false)
10046
11233
  .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering.', (val, prev) => [...(prev ?? []), val], [])
@@ -10057,7 +11244,7 @@ export function createTestCommand(deps = {}) {
10057
11244
  testId,
10058
11245
  name: cmdOpts.name,
10059
11246
  description: cmdOpts.description,
10060
- priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
11247
+ priority: parsePriorityFlag(cmdOpts.priority),
10061
11248
  stepTimeoutMs: parseStepTimeoutFlag(cmdOpts.stepTimeout, 'step-timeout'),
10062
11249
  clearStepTimeout: cmdOpts.clearStepTimeout === true,
10063
11250
  produces: cmdOpts.produces,
@@ -10113,8 +11300,8 @@ export function createTestCommand(deps = {}) {
10113
11300
  // -------------------------------------------------------------------------
10114
11301
  test
10115
11302
  .command('run [test-id...]')
10116
- .description('Trigger one test run, or several local frontend runs through one tunnel. With --wait, polls until terminal status.\n' +
10117
- 'Use --all --project <id> for a wave-ordered batch run, or add --local <port> to run its frontend tests through one tunnel.\n' +
11303
+ .description('Trigger one or several test runs. Saved loopback environments open a tunnel automatically and wait for a verdict.\n' +
11304
+ 'Use --all --project <id> for a wave-ordered batch run. Loopback environments share one tunnel.\n' +
10118
11305
  '\nExit codes:\n' +
10119
11306
  ' 0 passed (or queued without --wait)\n' +
10120
11307
  ' 1 failed / blocked / cancelled\n' +
@@ -10128,38 +11315,40 @@ export function createTestCommand(deps = {}) {
10128
11315
  ' 11 rate limited — honor Retry-After, or the in-flight run cap was hit\n' +
10129
11316
  ' (details.reason "inflight_cap"; see: testsprite test run --help)\n' +
10130
11317
  '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
10131
- '\nCtrl-C during an ordinary --wait detaches; an owned --local tunnel cancels unfinished runs by default.\n' +
10132
- 'Stop a detached run with: testsprite test cancel <run-id>')
11318
+ '\nCtrl-C during an ordinary --wait detaches; an owned tunnel cancels unfinished runs by default.\n' +
11319
+ 'Stop a detached run with: testsprite test cancel <run-id>\n' +
11320
+ 'Local environments: dev servers can take a minute per page through the tunnel.\n' +
11321
+ 'For a heavy dev server, test a built server: npm run build, then your framework preview/start command.')
10133
11322
  .option('--target-url <url>', TARGET_URL_HELP)
10134
11323
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
10135
11324
  .option('--local <port>', 'run against an app on THIS machine, reached through a TestSprite tunnel. The test runner ' +
10136
- 'navigates to http://127.0.0.1:<port> and its traffic is proxied back to you for as long ' +
11325
+ 'navigates to http://localhost:<port> and its traffic is proxied back to you for as long ' +
10137
11326
  'as this command runs. Implies --wait (the tunnel closes when the command exits, so a ' +
10138
11327
  'detached run could not finish). Frontend tests ' +
10139
- 'only; several ids or --all share one tunnel (5 concurrent by default, at most 10). ' +
11328
+ 'only; a matching saved environment keeps its host spelling; several ids or --all share one tunnel (5 concurrent by default, at most 10). ' +
10140
11329
  'Before anything is minted or billed, the port is probed and a dead one is refused.')
10141
- .option('--local-host <host>', `with --local, which loopback address to name in the run's target URL — one of ` +
10142
- `${LOOPBACK_HOSTS.join(', ')} (default ${DEFAULT_LOCAL_HOST}). Use localhost if your app ` +
11330
+ .option('--local-host <host>', `with --local, override which loopback address to name in the run's target URL — one of ` +
11331
+ `${LOOPBACK_HOSTS.join(', ')} (default: saved matching host, else ${DEFAULT_LOCAL_HOST}). Use localhost if your app ` +
10143
11332
  `only answers on that name, or ::1 for an IPv6-only listener.`)
10144
- .option('--tunnel-client <id>', 'with --local, attach to a tunnel already running under `testsprite tunnel start` instead ' +
11333
+ .option('--tunnel-client <id>', 'for a loopback environment or --local, attach to a tunnel already running under `testsprite tunnel start` instead ' +
10145
11334
  'of opening a new one. The id is the non-secret handle that command prints; the tunnel ' +
10146
11335
  'stays owned by that process and is not closed when this run or batch finishes.')
10147
- .option('--no-cancel-on-interrupt', 'with --local, skip automatic cancellation when an owned tunnel is about to close or a ' +
11336
+ .option('--no-cancel-on-interrupt', 'with a tunnel, skip automatic cancellation when an owned tunnel is about to close or a ' +
10148
11337
  "borrowed tunnel's owner disappears. An ordinary interrupt of a borrowed run never " +
10149
11338
  'cancels it because its tunnel remains alive.')
10150
11339
  .option('--env <name>', 'run against the named project environment — its test-account credentials, auto-auth and ' +
10151
- 'OTP settings (names: `testsprite project env list <project-id>`). Combine with --local ' +
10152
- 'to use those credentials against your own machine; without --local, the run opens ' +
11340
+ 'OTP settings (names: `testsprite project env list <project-id>`). A loopback environment opens a tunnel automatically. The run opens ' +
10153
11341
  "that environment's URL. Omit --env to keep using " +
10154
11342
  "the project's default environment. Also applies with --all.")
10155
11343
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
10156
- .option('--timeout <s>', 'with --wait, max seconds per run (1–3600; default 600, or 1200 with --local)')
11344
+ .option('--no-wait', 'detach without opening an automatic environment tunnel')
11345
+ .option('--timeout <s>', 'with --wait, max seconds per run (1–3600; default 600, or 1200 through a tunnel)')
10157
11346
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars); local batches append each test id. Auto-generated keys print to stderr in JSON, verbose or debug mode.')
10158
11347
  .option('--all', 'run all tests in the project (wave-ordered fresh run; uses --project or TESTSPRITE_PROJECT_ID). Mutually exclusive with <test-id>.', false)
10159
11348
  .option('--project <id>', 'project id (with --all, overrides TESTSPRITE_PROJECT_ID; returned by `testsprite project list`)')
10160
11349
  .option('--filter <substr>', 'with --all: only run tests whose name contains this substring (case-insensitive)')
10161
- .option('--max-concurrency <n>', `with --local, max runs in flight through one tunnel (1-10, default 5); with --all --wait without --local, max polls (1-100, default ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
10162
- .option('--report <format>', 'with a --wait batch (--all or several local ids): write a JUnit XML sidecar report after polling (accepted: junit)')
11350
+ .option('--max-concurrency <n>', `with a tunnel, max runs in flight through one tunnel (1-10, default 5); with --all --wait without a tunnel, max polls (1-100, default ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
11351
+ .option('--report <format>', 'with a --wait batch (--all or several ids): write a JUnit XML sidecar report after polling (accepted: junit)')
10163
11352
  .option('--report-file <path>', 'output path for --report (atomic write)')
10164
11353
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
10165
11354
  .option('--gh-output', 'with --wait (single test or batch): emit GitHub-native output (::error:: annotations for failed/timed-out runs, ::warning:: for never-dispatched tests; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
@@ -10204,6 +11393,18 @@ export function createTestCommand(deps = {}) {
10204
11393
  ' has no effect on the cap. A smaller batch does.')
10205
11394
  .addHelpText('after', GLOBAL_OPTS_HINT)
10206
11395
  .action(async (testIdArgs, cmdOpts, command) => {
11396
+ // A literal `testsprite test run list` is someone guessing at a
11397
+ // "list prior runs" subcommand, not naming a test whose id is the
11398
+ // string "list". Left unguarded, this parses as a normal `<test-id>`
11399
+ // and dispatches a run against a test that (almost certainly) does not
11400
+ // exist, wasting a round trip on a typo that a clear message could
11401
+ // have caught locally. Checked first, before any other validation or
11402
+ // network access, so it wins even if other flags (`--all`, etc.) are
11403
+ // also present.
11404
+ if (testIdArgs.length === 1 && testIdArgs[0] === 'list') {
11405
+ throw localValidationError('test-id', 'there is no `test run list` command; to see a test’s prior runs use: ' +
11406
+ 'testsprite test result <test-id> --history');
11407
+ }
10207
11408
  const isAll = cmdOpts.all === true;
10208
11409
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
10209
11410
  // Mutual-exclusion: exactly one of positional <test-id> vs --all must be set.
@@ -10225,9 +11426,23 @@ export function createTestCommand(deps = {}) {
10225
11426
  // tunnel credential.
10226
11427
  const localPort = cmdOpts.local !== undefined ? parseLocalPort(cmdOpts.local) : undefined;
10227
11428
  const usingLocal = localPort !== undefined;
10228
- const effectiveWait = usingLocal || cmdOpts.wait === true;
10229
- if (!usingLocal && testIdArgs.length >= 2) {
10230
- throw localValidationError('test-id', 'several test ids run through one tunnel with --local <port>. For tests the runner can already reach, use `testsprite test run --all --project <id> [--filter <text>]`, or run them one at a time.');
11429
+ const effectiveWait = usingLocal ||
11430
+ (cmdOpts.targetUrl !== undefined &&
11431
+ parseLoopbackTargetUrl(cmdOpts.targetUrl) !== undefined) ||
11432
+ cmdOpts.wait === true;
11433
+ const canAutoWait = !resolveCommonOptions(command, deps.env).dryRun &&
11434
+ !(command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false);
11435
+ const explicitLoopbackTarget = cmdOpts.targetUrl !== undefined && parseLoopbackTargetUrl(cmdOpts.targetUrl) !== undefined;
11436
+ if (!usingLocal &&
11437
+ !explicitLoopbackTarget &&
11438
+ ((command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false) ||
11439
+ cmdOpts.targetUrl !== undefined)) {
11440
+ if (!isAll && testIdArgs.length >= 2)
11441
+ severalIdsWithoutTunnel();
11442
+ assertNoTunnelOptions({
11443
+ tunnelClientId: cmdOpts.tunnelClient,
11444
+ cancelOnInterrupt: cmdOpts.cancelOnInterrupt,
11445
+ });
10231
11446
  }
10232
11447
  const maxConcurrency = cmdOpts.maxConcurrency === undefined
10233
11448
  ? usingLocal
@@ -10252,43 +11467,36 @@ export function createTestCommand(deps = {}) {
10252
11467
  'machine through a tunnel, --target-url runs against an address the test runner can ' +
10253
11468
  'already reach. Pass one');
10254
11469
  }
10255
- // The three flags below are inert without --local. Silently ignoring
11470
+ // A host override is meaningful only for the port shorthand. Silently ignoring
10256
11471
  // them would leave the caller believing something is in effect that is
10257
11472
  // not — the same rule --filter and the JUnit flags already follow.
10258
11473
  if (!usingLocal && cmdOpts.localHost !== undefined) {
10259
11474
  throw localValidationError('local-host', '--local-host only applies with --local (it names the loopback address the tunnel run ' +
10260
11475
  'targets). Add --local <port>, or remove --local-host');
10261
11476
  }
10262
- if (!usingLocal && cmdOpts.tunnelClient !== undefined) {
10263
- throw localValidationError('tunnel-client', '--tunnel-client only applies with --local (it attaches the run to an already-running ' +
10264
- 'tunnel). Add --local <port>, or remove --tunnel-client');
10265
- }
10266
- if (!usingLocal && cmdOpts.cancelOnInterrupt === false) {
10267
- throw localValidationError('cancel-on-interrupt', '--no-cancel-on-interrupt only applies with --local. An ordinary run is never ' +
10268
- 'cancelled when this command stops waiting — Ctrl-C detaches, and `testsprite test ' +
10269
- 'cancel <run-id>` is the way to stop one');
10270
- }
10271
- const localHost = usingLocal ? normalizeLocalHost(cmdOpts.localHost) : undefined;
11477
+ const localHost = usingLocal && cmdOpts.localHost !== undefined
11478
+ ? normalizeLocalHost(cmdOpts.localHost)
11479
+ : undefined;
10272
11480
  const report = parseJUnitReportFormat(cmdOpts.report);
10273
11481
  assertJUnitReportOptions({
10274
11482
  report,
10275
11483
  reportFile: cmdOpts.reportFile,
10276
11484
  reportSuiteName: cmdOpts.reportSuiteName,
10277
- wait: effectiveWait,
10278
- batchPath: isAll || (usingLocal && testIds.length > 1),
11485
+ wait: effectiveWait || canAutoWait,
11486
+ batchPath: isAll || testIds.length > 1,
10279
11487
  });
10280
11488
  // --gh-output / --summary-file reduce a --wait run's terminal result into
10281
11489
  // the CI summary. They require --wait (without it the command returns after
10282
11490
  // enqueueing, before any terminal result exists) but apply to BOTH a single
10283
11491
  // <test-id> run and the --all batch. Without --wait they would silently
10284
11492
  // no-op — reject loudly (same rule as --filter and the JUnit report flags).
10285
- if (cmdOpts.ghOutput === true && !effectiveWait) {
11493
+ if (cmdOpts.ghOutput === true && !effectiveWait && !canAutoWait) {
10286
11494
  throw localValidationError('gh-output', '--gh-output requires --wait (it reduces the terminal run result). Add --wait.');
10287
11495
  }
10288
- if (cmdOpts.summaryFile !== undefined && !effectiveWait) {
11496
+ if (cmdOpts.summaryFile !== undefined && !effectiveWait && !canAutoWait) {
10289
11497
  throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
10290
11498
  }
10291
- if (isAll && !usingLocal) {
11499
+ if (isAll && !usingLocal && cmdOpts.tunnelClient === undefined) {
10292
11500
  // --all path: wave-ordered fresh batch run.
10293
11501
  const projectId = resolveProjectId(cmdOpts.project, deps);
10294
11502
  requireProjectId(projectId, '--all requires a project id - pass --project <id> or set TESTSPRITE_PROJECT_ID');
@@ -10306,6 +11514,10 @@ export function createTestCommand(deps = {}) {
10306
11514
  projectId,
10307
11515
  nameFilter: cmdOpts.filter,
10308
11516
  wait: effectiveWait,
11517
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
11518
+ concurrencyIsDefault: cmdOpts.maxConcurrency === undefined,
11519
+ timeoutIsDefault: cmdOpts.timeout === undefined,
11520
+ cancelOnInterrupt: cmdOpts.cancelOnInterrupt !== false,
10309
11521
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
10310
11522
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
10311
11523
  DEFAULT_BATCH_RUN_CONCURRENCY,
@@ -10350,15 +11562,19 @@ export function createTestCommand(deps = {}) {
10350
11562
  : '[advisory] --local implies --wait: the tunnel closes when this command exits, so ' +
10351
11563
  'the run is followed to a verdict rather than detached.');
10352
11564
  }
10353
- if (usingLocal && (isAll || testIds.length > 1)) {
11565
+ if (isAll || testIds.length > 1) {
10354
11566
  await runTestRunLocalBatch({
10355
11567
  ...commonOpts,
10356
11568
  testIds,
11569
+ wait: effectiveWait,
10357
11570
  all: isAll,
10358
11571
  projectId: cmdOpts.project,
10359
11572
  nameFilter: cmdOpts.filter,
10360
- localPort: localPort,
10361
- localHost: localHost ?? DEFAULT_LOCAL_HOST,
11573
+ localPort,
11574
+ localHost,
11575
+ targetUrl: cmdOpts.targetUrl,
11576
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
11577
+ concurrencyIsDefault: cmdOpts.maxConcurrency === undefined,
10362
11578
  skipPreflight: cmdOpts.skipPreflight === true,
10363
11579
  tunnelClientId: cmdOpts.tunnelClient,
10364
11580
  cancelOnInterrupt: cmdOpts.cancelOnInterrupt !== false,
@@ -10389,6 +11605,7 @@ export function createTestCommand(deps = {}) {
10389
11605
  ...(cmdOpts.tunnelClient !== undefined ? { tunnelClientId: cmdOpts.tunnelClient } : {}),
10390
11606
  cancelOnInterrupt: cmdOpts.cancelOnInterrupt !== false,
10391
11607
  wait: effectiveWait,
11608
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
10392
11609
  timeoutSeconds: usingLocal && cmdOpts.timeout === undefined
10393
11610
  ? DEFAULT_LOCAL_RUN_TIMEOUT_SECONDS
10394
11611
  : parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
@@ -10476,6 +11693,8 @@ export function createTestCommand(deps = {}) {
10476
11693
  .option('--status <list>', `with --all: only dispatch tests whose status matches one of these values (comma-separated; accepted: ${PUBLIC_STATUSES.join('|')})`)
10477
11694
  .option('--filter <substr>', 'with --all: only rerun tests whose name contains this substring (case-insensitive)')
10478
11695
  .option('--wait', 'block until terminal status or --timeout elapses', false)
11696
+ .option('--no-wait', 'detach without opening an automatic environment tunnel')
11697
+ .option('--skip-preflight', 'skip the loopback port probe before opening a tunnel')
10479
11698
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
10480
11699
  .option('--no-auto-heal', 'replay the saved script verbatim instead of letting the agent repair it (default: ' +
10481
11700
  'auto-heal is ON for FE reruns). When heal engages, the agent re-authors the test and ' +
@@ -10484,8 +11703,8 @@ export function createTestCommand(deps = {}) {
10484
11703
  .option('--skip-dependencies', 'BE only: rerun only the named test without expanding the producer/teardown closure', false)
10485
11704
  .option('--env <name>', 'replay against the named project environment — its test-account credentials, auto-auth and ' +
10486
11705
  'OTP settings (names: `testsprite project env list <project-id>`). Omit to keep using the ' +
10487
- "project's default environment. Applies to every test of a batch rerun.")
10488
- .option('--max-concurrency <n>', `with --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
11706
+ "project's default environment. Loopback URLs open a tunnel automatically. Applies to every test of a batch rerun.")
11707
+ .option('--max-concurrency <n>', `with a tunnel, max runs in flight (1-10, default 5); otherwise with --wait, max polls (1-100, default ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
10489
11708
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --verbose if auto-generated.')
10490
11709
  .option('--report <format>', 'with batch --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
10491
11710
  .option('--report-file <path>', 'output path for --report (atomic write)')
@@ -10518,20 +11737,23 @@ export function createTestCommand(deps = {}) {
10518
11737
  const testIds = testIdsArg ?? [];
10519
11738
  const isBatch = cmdOpts.all === true || testIds.length !== 1;
10520
11739
  const report = parseJUnitReportFormat(cmdOpts.report);
11740
+ const canAutoWait = !resolveCommonOptions(command, deps.env).dryRun &&
11741
+ !(command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false);
10521
11742
  assertJUnitReportOptions({
10522
11743
  report,
10523
11744
  reportFile: cmdOpts.reportFile,
10524
11745
  reportSuiteName: cmdOpts.reportSuiteName,
10525
- wait: cmdOpts.wait === true,
11746
+ wait: cmdOpts.wait === true || canAutoWait,
10526
11747
  batchPath: isBatch,
10527
11748
  });
10528
11749
  // --gh-output / --summary-file reduce the batch-rerun --wait envelope, which
10529
11750
  // only exists on the batch (--all or 2+ ids) --wait path. Anywhere else they
10530
11751
  // would silently no-op — reject loudly (same rule as the JUnit report flags).
10531
- if (cmdOpts.ghOutput === true && (!isBatch || cmdOpts.wait !== true)) {
11752
+ if (cmdOpts.ghOutput === true && (!isBatch || (cmdOpts.wait !== true && !canAutoWait))) {
10532
11753
  throw localValidationError('gh-output', '--gh-output requires a batch rerun with --wait (--all or 2+ test ids). Remove --gh-output, or add --all --wait.');
10533
11754
  }
10534
- if (cmdOpts.summaryFile !== undefined && (!isBatch || cmdOpts.wait !== true)) {
11755
+ if (cmdOpts.summaryFile !== undefined &&
11756
+ (!isBatch || (cmdOpts.wait !== true && !canAutoWait))) {
10535
11757
  throw localValidationError('summary-file', '--summary-file requires a batch rerun with --wait (--all or 2+ test ids). Remove --summary-file, or add --all --wait.');
10536
11758
  }
10537
11759
  await runTestRerun({
@@ -10543,6 +11765,9 @@ export function createTestCommand(deps = {}) {
10543
11765
  statusFilter: cmdOpts.status,
10544
11766
  nameFilter: cmdOpts.filter,
10545
11767
  wait: cmdOpts.wait === true,
11768
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
11769
+ skipPreflight: cmdOpts.skipPreflight === true,
11770
+ concurrencyIsDefault: cmdOpts.maxConcurrency === undefined,
10546
11771
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
10547
11772
  autoHeal: cmdOpts.autoHeal !== false,
10548
11773
  autoHealExplicit: false,
@@ -10827,6 +12052,12 @@ function parseEnumFlag(raw, flagName, accepted) {
10827
12052
  }
10828
12053
  return raw;
10829
12054
  }
12055
+ function parsePriorityFlag(raw) {
12056
+ if (raw === undefined)
12057
+ return undefined;
12058
+ assertPriorityInput('priority', raw, 'flag');
12059
+ return raw;
12060
+ }
10830
12061
  function parseNumericFlag(raw, flagName) {
10831
12062
  if (raw === undefined)
10832
12063
  return undefined;
@@ -11228,6 +12459,9 @@ async function readPresignedBody(url, out, deps, shutdownSignal) {
11228
12459
  throw new TransportError(`Failed mid-download of presigned code body: ${message}`);
11229
12460
  }
11230
12461
  }
12462
+ function renderTestTypeCell(test) {
12463
+ return test.isIntegration === true ? `${test.type}/int` : test.type;
12464
+ }
11231
12465
  const TEST_LIST_COLUMNS = [
11232
12466
  {
11233
12467
  header: 'ID',
@@ -11239,16 +12473,36 @@ const TEST_LIST_COLUMNS = [
11239
12473
  width: rows => Math.max(4, ...rows.map(test => test.name.length)),
11240
12474
  render: test => test.name,
11241
12475
  },
11242
- { header: 'TYPE', width: 8, render: test => test.type },
12476
+ {
12477
+ header: 'TYPE',
12478
+ width: rows => Math.max(8, ...rows.map(test => renderTestTypeCell(test).length)),
12479
+ render: renderTestTypeCell,
12480
+ },
11243
12481
  { header: 'FROM', width: 6, render: test => test.createdFrom },
11244
12482
  { header: 'STATUS', width: 9, render: test => test.status },
11245
- { header: 'UPDATED', width: 0, render: test => test.updatedAt },
12483
+ {
12484
+ header: 'UPDATED',
12485
+ width: rows => Math.max(7, ...rows.map(test => test.updatedAt.length)),
12486
+ render: test => test.updatedAt,
12487
+ },
12488
+ {
12489
+ header: 'ENV',
12490
+ width: rows => Math.max(3, ...rows.map(test => (test.headlineEnvironment?.name ?? '-').length)),
12491
+ render: test => test.headlineEnvironment?.name ?? '-',
12492
+ },
11246
12493
  ];
11247
- function renderTestListText(page, options = {}) {
12494
+ export function renderTestListText(page, options = {}) {
12495
+ const note = options.environment === undefined || options.noHeader
12496
+ ? []
12497
+ : [`Frontend test status requested for environment '${options.environment}'.`];
11248
12498
  if (page.items.length === 0) {
11249
- return page.nextToken ? `No tests on this page.\nnextToken: ${page.nextToken}` : 'No tests.';
12499
+ return [
12500
+ ...note,
12501
+ page.nextToken ? `No tests on this page.\nnextToken: ${page.nextToken}` : 'No tests.',
12502
+ ].join('\n');
11250
12503
  }
11251
12504
  const lines = [
12505
+ ...note,
11252
12506
  renderTextTable(page.items, TEST_LIST_COLUMNS, {
11253
12507
  columns: options.columns,
11254
12508
  noHeader: options.noHeader,
@@ -11275,6 +12529,9 @@ function renderTestText(t) {
11275
12529
  `createdFrom: ${t.createdFrom}`,
11276
12530
  `status: ${t.status}`,
11277
12531
  ];
12532
+ if (t.headlineEnvironment?.name != null) {
12533
+ lines.push(`environment: ${t.headlineEnvironment.name}`);
12534
+ }
11278
12535
  // G1a: surface priority when the backend ships it and it is non-null.
11279
12536
  if (t.priority) {
11280
12537
  lines.push(`priority: ${t.priority}`);
@@ -11294,8 +12551,13 @@ function renderTestText(t) {
11294
12551
  const fields = step;
11295
12552
  const type = typeof fields.type === 'string' ? fields.type : 'step';
11296
12553
  const description = typeof fields.description === 'string' ? fields.description : '(no description)';
11297
- lines.push(` ${index + 1}. [${type}] ${description}`);
12554
+ const mark = fields.structured === true ? '*' : ' ';
12555
+ lines.push(`${mark} ${index + 1}. [${type}] ${description}`);
11298
12556
  });
12557
+ const structuredCount = planSteps.filter(step => typeof step === 'object' && step !== null && step.structured === true).length;
12558
+ if (structuredCount > 0) {
12559
+ lines.push(`* ${structuredCount} step(s) carry structured fields; \`plan put\` keeps them only for unchanged steps.`);
12560
+ }
11299
12561
  }
11300
12562
  if (typeof t.stepTimeoutMs === 'number') {
11301
12563
  lines.push(`stepTimeout: ${t.stepTimeoutMs} ms (applies to every step)`);
@@ -11981,20 +13243,208 @@ function renderPlanGenerateFailedText(plans, projectId) {
11981
13243
  lines.push(` completed stages stay done — retry with: testsprite test plan generate --project ${projectId}`);
11982
13244
  return lines.join('\n');
11983
13245
  }
11984
- function makePlanGeneratePartial(projectId, lastSeen) {
13246
+ /** Status → the stage it belongs to (idle/failed map to none). */
13247
+ function planStageOfStatus(status) {
13248
+ switch (status) {
13249
+ case 'exploring':
13250
+ return 'exploration';
13251
+ case 'strategizing':
13252
+ return 'strategy';
13253
+ case 'proposing':
13254
+ return 'proposals';
13255
+ default:
13256
+ return null;
13257
+ }
13258
+ }
13259
+ /**
13260
+ * Follows the ladder from the command layer so the user sees WHERE they are:
13261
+ * one `stage i/N <name> done <elapsed>` line per finished stage, and on an
13262
+ * interruption a "paused during/after stage i/N" line that names what is
13263
+ * left. The ladder itself only starts the next stage while this process is
13264
+ * alive (verified live 2026-08-27), which is exactly why the copy says
13265
+ * "re-run to continue" rather than "work continues".
13266
+ */
13267
+ class PlanStageTracker {
13268
+ emit;
13269
+ /** Every stage this run will perform, in order; known from the first
13270
+ * accepted trigger, unknown (null) when the run only ever attached. */
13271
+ planned = null;
13272
+ /** The stage this run believes is up next or running. */
13273
+ current = null;
13274
+ /** True once a poll has reported `current` as ACTIVE. `idle` is ambiguous
13275
+ * (not started yet vs. finished), so a stage is only ever marked done on
13276
+ * evidence: it was seen running and then stopped, a later stage was seen
13277
+ * running or accepted, or the run settled with proposals staged. */
13278
+ currentActive = false;
13279
+ currentSinceMs = 0;
13280
+ lastElapsedMs = 0;
13281
+ done = [];
13282
+ constructor(emit) {
13283
+ this.emit = emit;
13284
+ }
13285
+ /** An accepted trigger is ground truth: the stage it started is up now,
13286
+ * and every planned stage before it is finished (even if no poll saw it). */
13287
+ onTrigger(response) {
13288
+ if (response.status !== 'accepted' || response.stage === null)
13289
+ return;
13290
+ if (this.planned === null)
13291
+ this.planned = [response.stage, ...response.stagesRemaining];
13292
+ for (const s of this.planned) {
13293
+ if (s === response.stage)
13294
+ break;
13295
+ this.markDone(s);
13296
+ }
13297
+ if (this.current !== response.stage) {
13298
+ this.current = response.stage;
13299
+ this.currentActive = false;
13300
+ this.currentSinceMs = this.lastElapsedMs;
13301
+ }
13302
+ }
13303
+ onTick(plans, elapsedMs) {
13304
+ this.lastElapsedMs = elapsedMs;
13305
+ // A failed read is not a transition: nothing finished.
13306
+ if (plans.generation.status === 'failed')
13307
+ return;
13308
+ const stage = planStageOfStatus(plans.generation.status);
13309
+ if (stage === this.current) {
13310
+ if (stage !== null && !this.currentActive) {
13311
+ this.currentActive = true;
13312
+ this.currentSinceMs = elapsedMs;
13313
+ }
13314
+ return;
13315
+ }
13316
+ if (this.current !== null) {
13317
+ if (stage === null && this.current === 'proposals') {
13318
+ // The last stage has no "next stage" to prove it finished, and the
13319
+ // server can report idle before the staged batch is visible (the
13320
+ // ladder's billing guard #1 keeps polling through that blip). Only
13321
+ // the settled read with proposals staged marks it done — settle().
13322
+ return;
13323
+ }
13324
+ if (this.currentActive) {
13325
+ this.markDone(this.current, elapsedMs);
13326
+ }
13327
+ else if (stage === null) {
13328
+ // idle before the stage was ever seen running: it has not started
13329
+ // (the ladder's own dwell window). Keep waiting on the same stage.
13330
+ return;
13331
+ }
13332
+ else {
13333
+ // A later stage seen running is as strong as an accepted trigger.
13334
+ this.markDone(this.current);
13335
+ }
13336
+ }
13337
+ this.current = stage;
13338
+ this.currentActive = stage !== null;
13339
+ this.currentSinceMs = elapsedMs;
13340
+ }
13341
+ /** The ladder settled with proposals staged: whatever was up is done. */
13342
+ settle(plans) {
13343
+ if (plans.proposals.length === 0)
13344
+ return;
13345
+ if (this.current !== null) {
13346
+ this.markDone(this.current, this.currentActive ? this.lastElapsedMs : undefined);
13347
+ }
13348
+ else if (this.planned !== null) {
13349
+ for (const s of this.planned)
13350
+ this.markDone(s);
13351
+ }
13352
+ this.current = null;
13353
+ this.currentActive = false;
13354
+ }
13355
+ markDone(stage, nowMs) {
13356
+ if (this.done.includes(stage))
13357
+ return;
13358
+ this.done.push(stage);
13359
+ const took = nowMs === undefined || stage !== this.current || !this.currentActive
13360
+ ? ''
13361
+ : ` ${formatPlanElapsed(nowMs - this.currentSinceMs)}`;
13362
+ this.emit(`stage ${this.label(stage)} done${took}`);
13363
+ }
13364
+ /** `i/N name` when the plan is known, else just the name. */
13365
+ label(stage) {
13366
+ if (this.planned === null)
13367
+ return stage;
13368
+ const i = this.planned.indexOf(stage);
13369
+ return i === -1 ? stage : `${i + 1}/${this.planned.length} ${stage}`;
13370
+ }
13371
+ /** Stages this run has not started. An accepted stage counts as started
13372
+ * whether or not a poll has reported it running yet: the server has
13373
+ * committed to it (and, for exploration and proposals, charged for it). */
13374
+ remaining() {
13375
+ if (this.planned === null)
13376
+ return null;
13377
+ return this.planned.filter(s => !this.done.includes(s) && s !== this.current);
13378
+ }
13379
+ /** "during stage 2/3 strategy" / "after stage 1/3 exploration" / "". Whether a
13380
+ * poll has already reported the stage running is not the user's concern:
13381
+ * once accepted it runs to completion either way. */
13382
+ position() {
13383
+ if (this.current !== null)
13384
+ return `during stage ${this.label(this.current)}`;
13385
+ const last = this.done[this.done.length - 1];
13386
+ return last === undefined ? '' : `after stage ${this.label(last)}`;
13387
+ }
13388
+ /** The stuck-fuse line. `tries` is every start request this run sent
13389
+ * (accepted or "already in progress" alike — the split is internal, and
13390
+ * an accepted stage counts as started, so "would not start" would
13391
+ * contradict `position()`/`remaining()`). Deliberately no `Continue:` —
13392
+ * an immediate re-run repeats the same tries. */
13393
+ stalledLine(tries) {
13394
+ const where = this.current === null ? 'Generation' : `Stage ${this.label(this.current)}`;
13395
+ return (`${where} is not making progress after ${tries} ${tries === 1 ? 'try' : 'tries'}. ` +
13396
+ 'Wait a few minutes, then run the same command again; it picks up from here.');
13397
+ }
13398
+ /** "N stages left." / "Nothing left to start." / "" (plan unknown). */
13399
+ leftText() {
13400
+ const rem = this.remaining();
13401
+ if (rem === null)
13402
+ return '';
13403
+ if (rem.length === 0)
13404
+ return ' Nothing left to start.';
13405
+ return ` ${rem.length} stage${rem.length === 1 ? '' : 's'} left.`;
13406
+ }
13407
+ /** One-line stderr summary for every way the wait can stop early. */
13408
+ pausedLine(projectId, lead, verb = 'Paused') {
13409
+ const pos = this.position();
13410
+ return (`${lead} ${verb}${pos === '' ? '' : ` ${pos}`}.${this.leftText()}\n` +
13411
+ ` Continue: testsprite test plan generate --project ${projectId}`);
13412
+ }
13413
+ /** The same story as `pausedLine`, as the single-line JSON `nextAction`. */
13414
+ detachNextAction(projectId) {
13415
+ const pos = this.position();
13416
+ return (`Plan generation paused${pos === '' ? '' : ` ${pos}`}.${this.leftText()} ` +
13417
+ `Continue: testsprite test plan generate --project ${projectId}`);
13418
+ }
13419
+ }
13420
+ function attachPlanInterruptDetach(err, detach) {
13421
+ err.planDetach = detach;
13422
+ }
13423
+ function makePlanGeneratePartial(projectId, lastSeen, stagesRemaining = null) {
11985
13424
  return {
11986
13425
  projectId,
11987
13426
  status: 'running',
11988
13427
  generationStatus: lastSeen?.generation.status ?? null,
11989
13428
  proposalsStaged: lastSeen?.proposals.length ?? 0,
13429
+ stagesRemaining,
11990
13430
  };
11991
13431
  }
11992
- function renderPlanGeneratePartialText(partial, reason) {
11993
- const lines = [`projectId ${partial.projectId}`, `status running (${reason})`];
11994
- if (partial.generationStatus !== null) {
13432
+ function renderPlanGeneratePartialText(partial, reason, position = '', verb = 'paused', withContinue = true) {
13433
+ const lines = [
13434
+ `projectId ${partial.projectId}`,
13435
+ `status ${verb} (${reason})${position === '' ? '' : ` ${position}`}`,
13436
+ ];
13437
+ if (position === '' && partial.generationStatus !== null) {
13438
+ // Interrupted before any trigger answered: the only position we have is
13439
+ // the status of the last read, so keep showing it (JSON has it anyway).
11995
13440
  lines.push(`stage ${partial.generationStatus}`);
11996
13441
  }
11997
- lines.push(`hint Re-attach with: testsprite test plan generate --project ${partial.projectId}`);
13442
+ if (partial.stagesRemaining !== null) {
13443
+ lines.push(`remaining ${partial.stagesRemaining.length === 0 ? 'none' : partial.stagesRemaining.join(', ')}`);
13444
+ }
13445
+ if (withContinue) {
13446
+ lines.push(`continue testsprite test plan generate --project ${partial.projectId}`);
13447
+ }
11998
13448
  return lines.join('\n');
11999
13449
  }
12000
13450
  /**
@@ -12004,8 +13454,9 @@ function renderPlanGeneratePartialText(partial, reason) {
12004
13454
  * proposals) through `runGenerationLadder` and renders the staged
12005
13455
  * proposals. Exit 0 on staged proposals, 1 on a server-side stage failure,
12006
13456
  * 7 on timeout (typed `UNSUPPORTED` envelope — the raw ladder timeout is
12007
- * not a CLI error), 130/143 on Ctrl-C detach (honest: work and charges
12008
- * continue server-side), plus the usual catalog exits for trigger errors
13457
+ * not a CLI error), 130/143 on Ctrl-C (the running stage finishes server-side;
13458
+ * nothing after it starts until a re-run, see PlanStageTracker), plus the
13459
+ * usual catalog exits for trigger errors
12009
13460
  * (412 → 6 with the exact fix command, 402 → 12, 404 → 4, 429 → 11).
12010
13461
  */
12011
13462
  export async function runPlanGenerate(opts, deps = {}) {
@@ -12050,6 +13501,8 @@ export async function runPlanGenerate(opts, deps = {}) {
12050
13501
  // migration bridge). Closing it needs the id on one of those wires.
12051
13502
  let resolvedProjectId = projectId;
12052
13503
  let lastSeen = null;
13504
+ // Stage position for the user (text mode only; JSON gets `stagesRemaining`).
13505
+ const stageTracker = new PlanStageTracker(opts.output === 'json' ? () => undefined : (line) => ticker.note(line));
12053
13506
  try {
12054
13507
  // Pre-trigger baseline snapshot: one plain GET BEFORE any POST, so the
12055
13508
  // settled read's lifetime `credits.charged` block can be diffed into
@@ -12075,23 +13528,25 @@ export async function runPlanGenerate(opts, deps = {}) {
12075
13528
  idempotencyKey,
12076
13529
  sleep: deps.sleep,
12077
13530
  shutdown: shutdownOf(deps),
12078
- onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
13531
+ onTransition: opts.verbose ? (msg) => ticker.note(`[verbose] ${msg}`) : undefined,
12079
13532
  onTick: (plans, elapsedMs) => {
12080
13533
  lastSeen = plans;
13534
+ stageTracker.onTick(plans, elapsedMs);
12081
13535
  ticker.update(planTickerLine(plans, elapsedMs));
12082
13536
  },
12083
13537
  onAttach: () => {
12084
- stderrFn('[advisory] a generation stage is already running for this project (possibly ' +
13538
+ ticker.note('[advisory] a generation stage is already running for this project (possibly ' +
12085
13539
  'started from the Portal) — attaching to it and polling.');
12086
13540
  },
12087
13541
  onTrigger: (response, acceptedPosts) => {
12088
13542
  resolvedProjectId = response.projectId;
13543
+ stageTracker.onTrigger(response);
12089
13544
  if (response.status === 'nothing_to_start') {
12090
13545
  if (acceptedPosts === 0) {
12091
13546
  // The FIRST trigger found the batch already staged: nothing ran,
12092
13547
  // nothing was charged. Regenerating on purpose is a Portal action
12093
13548
  // for now (design §11) — say so instead of silently no-opping.
12094
- stderrFn('[advisory] proposals are already staged for this project — showing the ' +
13549
+ ticker.note('[advisory] proposals are already staged for this project — showing the ' +
12095
13550
  'existing batch (nothing new was started or charged). To regenerate, ' +
12096
13551
  'review and accept or discard the staged batch in the Portal first.');
12097
13552
  }
@@ -12110,12 +13565,10 @@ export async function runPlanGenerate(opts, deps = {}) {
12110
13565
  ...(response.stage !== null ? [response.stage] : []),
12111
13566
  ...response.stagesRemaining,
12112
13567
  ];
12113
- const label = stages.join(' + ');
12114
- stderrFn(stages.includes('exploration')
12115
- ? `[hint] this project hasn't been explored yet — the full pipeline will run ` +
12116
- `(${label}). Ctrl-C detaches safely; work continues server-side.`
12117
- : `[hint] running the missing pipeline stages (${label}). ` +
12118
- `Ctrl-C detaches safely; work continues server-side.`);
13568
+ const plural = stages.length === 1 ? 'stage' : 'stages';
13569
+ ticker.note(`[hint] ${stages.length} ${plural}: ${stages.join(', ')}.` +
13570
+ `${stages.includes('exploration') ? ' Takes minutes.' : ''}` +
13571
+ ' Ctrl-C is safe; re-run to continue.');
12119
13572
  }
12120
13573
  // …and, when browser exploration is about to run, warn about
12121
13574
  // missing test-account sign-in (design §3.1). The wire carries no
@@ -12123,7 +13576,7 @@ export async function runPlanGenerate(opts, deps = {}) {
12123
13576
  // it never blocks and never prompts; the CLI cannot know whether
12124
13577
  // the app actually requires login. Both output modes: stderr only.
12125
13578
  if (response.stage === 'exploration') {
12126
- stderrFn('[warn] exploration signs in only with the test account stored on the ' +
13579
+ ticker.note('[warn] exploration signs in only with the test account stored on the ' +
12127
13580
  "project's default environment. If your app requires login and no test " +
12128
13581
  'account is configured, the agents will explore only the public pages — ' +
12129
13582
  'a shallow result from a stage that still runs and still bills. For ' +
@@ -12134,6 +13587,7 @@ export async function runPlanGenerate(opts, deps = {}) {
12134
13587
  },
12135
13588
  });
12136
13589
  const plans = result.plans;
13590
+ stageTracker.settle(plans);
12137
13591
  if (plans.generation.status === 'failed') {
12138
13592
  ticker.finalize(planTickerLine(plans, 0).replace(/ \(0s\)$/, ''));
12139
13593
  const payload = { projectId: resolvedProjectId, ...plans };
@@ -12175,37 +13629,56 @@ export async function runPlanGenerate(opts, deps = {}) {
12175
13629
  // Typed exit-7 conversion (the design's hard rule): the ladder's raw
12176
13630
  // timeout is NOT a CLI error and would otherwise exit 1. Mirror the
12177
13631
  // wait-site template — partial to stdout, typed envelope thrown.
13632
+ // Every early stop below prints the same partial (stdout, so a redirected
13633
+ // file is never 0-byte) and a stderr line naming the stage position. All
13634
+ // but the stuck fuse add a `Continue:` line — an immediate re-run there
13635
+ // would only repeat the same tries.
13636
+ // The wording is deliberate: only the stage already running finishes on
13637
+ // the server; the next one starts only from a re-run of this command.
13638
+ const remaining = stageTracker.remaining();
13639
+ const position = stageTracker.position();
12178
13640
  if (err instanceof PlanGenerationTimeoutError) {
12179
- ticker.finalize(`timed out after ${opts.timeoutSeconds}s`);
12180
- const partial = makePlanGeneratePartial(resolvedProjectId, err.lastPlans ?? lastSeen);
12181
- out.print(partial, () => renderPlanGeneratePartialText(partial, `timed out after ${opts.timeoutSeconds}s`));
13641
+ const reason = `timed out after ${opts.timeoutSeconds}s`;
13642
+ ticker.finalize(reason);
13643
+ const partial = makePlanGeneratePartial(resolvedProjectId, err.lastPlans ?? lastSeen, remaining);
13644
+ out.print(partial, () => renderPlanGeneratePartialText(partial, reason, position));
12182
13645
  throw ApiError.fromEnvelope({
12183
13646
  error: {
12184
13647
  code: 'UNSUPPORTED', // exit 7 per errors.md
12185
- message: `Timed out after ${opts.timeoutSeconds}s waiting for plan generation on project ${resolvedProjectId}.`,
12186
- nextAction: `Generation continues server-side; re-running the same command re-attaches: ` +
12187
- `testsprite test plan generate --project ${resolvedProjectId} ` +
12188
- `(raise --timeout for exploration-heavy first runs).`,
13648
+ // The prefix is the §13.3 discriminator between "slow" and a real
13649
+ // 501 UNSUPPORTED — keep it literal.
13650
+ message: `Timed out after ${opts.timeoutSeconds}s waiting for plan generation on project ` +
13651
+ `${resolvedProjectId}${position === '' ? '' : ` ${position}`}.${stageTracker.leftText()}`,
13652
+ nextAction: `Continue: testsprite test plan generate --project ${resolvedProjectId} ` +
13653
+ '(or raise --timeout)',
12189
13654
  requestId: 'local',
12190
- details: { projectId: resolvedProjectId, timeoutSeconds: opts.timeoutSeconds },
13655
+ details: {
13656
+ projectId: resolvedProjectId,
13657
+ timeoutSeconds: opts.timeoutSeconds,
13658
+ ...(remaining !== null ? { stagesRemaining: remaining } : {}),
13659
+ },
12191
13660
  },
12192
13661
  });
12193
13662
  }
12194
13663
  if (err instanceof RequestTimeoutError) {
12195
13664
  ticker.finalize('request timed out');
12196
- const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
12197
- out.print(partial, () => renderPlanGeneratePartialText(partial, 'request timed out'));
12198
- stderrFn(`Plan generation is still in progress (request timed out). ` +
12199
- `Re-attach with: testsprite test plan generate --project ${resolvedProjectId}`);
13665
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen, remaining);
13666
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'request timed out', position));
13667
+ stderrFn(stageTracker.pausedLine(resolvedProjectId, 'Request timed out.'));
12200
13668
  throw err;
12201
13669
  }
12202
13670
  if (err instanceof InterruptError) {
12203
13671
  ticker.finalize(`interrupted (${err.signal})`);
12204
- const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
12205
- out.print(partial, () => renderPlanGeneratePartialText(partial, `interrupted (${err.signal})`));
12206
- stderrFn(`Interrupted (${err.signal}). Plan generation keeps running (and billing) on the ` +
12207
- `server until the current stage finishes.\n` +
12208
- ` Re-attach with: testsprite test plan generate --project ${resolvedProjectId}`);
13672
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen, remaining);
13673
+ out.print(partial, () => renderPlanGeneratePartialText(partial, `interrupted (${err.signal})`, position));
13674
+ stderrFn(stageTracker.pausedLine(resolvedProjectId, `Interrupted (${err.signal}).`));
13675
+ // index.ts builds the JSON INTERRUPTED envelope from this, so it tells
13676
+ // the same story as the line above (not the run-detach "test wait" one).
13677
+ attachPlanInterruptDetach(err, {
13678
+ projectId: resolvedProjectId,
13679
+ stagesRemaining: remaining,
13680
+ nextAction: stageTracker.detachNextAction(resolvedProjectId),
13681
+ });
12209
13682
  throw err;
12210
13683
  }
12211
13684
  if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
@@ -12213,10 +13686,9 @@ export async function runPlanGenerate(opts, deps = {}) {
12213
13686
  // a redirected stdout file must never be 0-byte.
12214
13687
  // The original ApiError is rethrown unchanged so exit stays 11.
12215
13688
  ticker.finalize('rate limited by the server');
12216
- const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
12217
- out.print(partial, () => renderPlanGeneratePartialText(partial, 'rate limited'));
12218
- stderrFn(`Rate limited by the server (HTTP 429). Any started generation stage keeps running ` +
12219
- `server-side.\n Re-attach with: testsprite test plan generate --project ${resolvedProjectId}`);
13689
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen, remaining);
13690
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'rate limited', position));
13691
+ stderrFn(stageTracker.pausedLine(resolvedProjectId, 'Rate limited by the server (HTTP 429).'));
12220
13692
  throw err;
12221
13693
  }
12222
13694
  if (err instanceof ApiError &&
@@ -12229,10 +13701,16 @@ export async function runPlanGenerate(opts, deps = {}) {
12229
13701
  // the stage-failed INTERNAL (which already printed its card) never
12230
13702
  // double-prints. Rethrown unchanged.
12231
13703
  ticker.finalize('generation appears stuck');
12232
- const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
12233
- out.print(partial, () => renderPlanGeneratePartialText(partial, 'appears stuck'));
13704
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen, remaining);
13705
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'appears stuck', position, 'stalled', false));
13706
+ const fuse = err.details;
13707
+ stderrFn(stageTracker.stalledLine(fuse.triggerPosts ?? fuse.acceptedPosts));
12234
13708
  throw err;
12235
13709
  }
13710
+ // Any other error (a 402 on a later stage's trigger, a 412 on a re-POST,
13711
+ // an exhausted retry…) is rendered by index.ts as a plain line: end the
13712
+ // live ticker row first so it never lands on the progress line.
13713
+ ticker.finalize();
12236
13714
  throw withPlanFixNextAction(err, resolvedProjectId);
12237
13715
  }
12238
13716
  }
@@ -12352,7 +13830,8 @@ function createTestPlanCommand(deps) {
12352
13830
  .command('put <test-id>')
12353
13831
  .description("Replace an FE test's planSteps[] (BE tests return 400 → use 'test code put')")
12354
13832
  .option('--steps <path>', 'JSON file with { planSteps: [...] } (FE-only, ≤ 200 steps, ≤ 256 KB)')
12355
- .option('--expected-step-count <n>', 'optional defensive concurrency check; server rejects with 412 when the current length differs')
13833
+ .option('--expected-step-count <n>', 'pin the step count the server must still have; 412 when it differs')
13834
+ .option('--force', 'replace even if steps edited in the Portal would lose their structured fields')
12356
13835
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
12357
13836
  .option('--dry-run-simulate-error <code>', 'With --dry-run: synthesise an error envelope to preview the error path. Supported: PRECONDITION_FAILED (412).')
12358
13837
  .addHelpText('after', '\nDry-run note: --dry-run always returns the happy response shape.\n' +
@@ -12369,6 +13848,7 @@ function createTestPlanCommand(deps) {
12369
13848
  testId,
12370
13849
  stepsFile: cmdOpts.steps,
12371
13850
  expectedStepCount: parseNumericFlag(cmdOpts.expectedStepCount, 'expected-step-count'),
13851
+ force: cmdOpts.force === true ? true : undefined,
12372
13852
  idempotencyKey: cmdOpts.idempotencyKey,
12373
13853
  dryRunSimulateError: simulateError === 'PRECONDITION_FAILED' ? 'PRECONDITION_FAILED' : undefined,
12374
13854
  }, deps);
@@ -12382,12 +13862,13 @@ function createTestPlanCommand(deps) {
12382
13862
  'exploration takes minutes on a fresh frontend project)')
12383
13863
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
12384
13864
  .addHelpText('after', '\nBehavior:\n' +
12385
- ' - Only the stages the project is missing actually run; a second call\n' +
12386
- ' resumes rather than starting over.\n' +
12387
- ' - Proposals are STAGED on the server for review; nothing is written to disk.\n' +
12388
- ' - Re-running the command re-attaches to an in-flight stage (409 attaches).\n' +
12389
- ' - Ctrl-C detaches locally; server-side work and charges continue.\n' +
12390
- ' - Exit 7 on --timeout: re-run the same command to re-attach.\n' +
13865
+ ' - Runs the stages the project still needs (exploration for frontend,\n' +
13866
+ ' strategy, proposals) and stops when proposals are staged for review.\n' +
13867
+ ' Nothing is written to disk.\n' +
13868
+ ' - Interrupt (exit 130/143/129) or timeout (exit 7): the stage in\n' +
13869
+ ' progress finishes on its own, the rest wait. Run the same command\n' +
13870
+ ' again to continue; it picks up where it left off. A stage that\n' +
13871
+ ' already completed is never charged again.\n' +
12391
13872
  ' - Workspace credits are spent per stage that runs; the result line reports\n' +
12392
13873
  ' what THIS run charged (omitted when nothing new was charged).\n' +
12393
13874
  ' `testsprite usage` shows your balance.\n' +