@testsprite/testsprite-cli 0.13.0 → 0.14.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 (58) hide show
  1. package/README.md +51 -48
  2. package/dist/commands/doctor.js +12 -11
  3. package/dist/commands/project-env.d.ts +11 -1
  4. package/dist/commands/project-env.js +399 -61
  5. package/dist/commands/project-sign-in.d.ts +60 -0
  6. package/dist/commands/project-sign-in.js +289 -0
  7. package/dist/commands/project.d.ts +9 -0
  8. package/dist/commands/project.js +68 -28
  9. package/dist/commands/schedule.d.ts +12 -0
  10. package/dist/commands/schedule.js +175 -5
  11. package/dist/commands/test.d.ts +53 -20
  12. package/dist/commands/test.js +1356 -342
  13. package/dist/commands/testlist.d.ts +10 -5
  14. package/dist/commands/testlist.js +170 -30
  15. package/dist/commands/tunnel.js +11 -5
  16. package/dist/index.js +12 -37
  17. package/dist/lib/client-factory.d.ts +12 -1
  18. package/dist/lib/client-factory.js +14 -4
  19. package/dist/lib/dry-run/samples.js +53 -0
  20. package/dist/lib/environment-tunnel.d.ts +109 -0
  21. package/dist/lib/environment-tunnel.js +465 -0
  22. package/dist/lib/errors.js +12 -1
  23. package/dist/lib/gh-output.js +3 -0
  24. package/dist/lib/http.d.ts +2 -0
  25. package/dist/lib/junit-report.d.ts +11 -7
  26. package/dist/lib/junit-report.js +13 -7
  27. package/dist/lib/local-target.d.ts +13 -3
  28. package/dist/lib/local-target.js +47 -12
  29. package/dist/lib/output.js +15 -1
  30. package/dist/lib/plan-poll.js +3 -4
  31. package/dist/lib/redact.d.ts +38 -0
  32. package/dist/lib/redact.js +140 -0
  33. package/dist/lib/render-error.d.ts +19 -5
  34. package/dist/lib/render-error.js +31 -0
  35. package/dist/lib/runs.types.d.ts +9 -1
  36. package/dist/lib/target-url.js +5 -5
  37. package/dist/lib/telemetry.d.ts +6 -7
  38. package/dist/lib/telemetry.js +11 -4
  39. package/dist/lib/testlist.types.d.ts +1 -0
  40. package/dist/lib/ticker.d.ts +9 -0
  41. package/dist/lib/ticker.js +18 -0
  42. package/dist/lib/tunnel-session.d.ts +3 -4
  43. package/dist/lib/tunnel-session.js +3 -4
  44. package/dist/lib/v3-advisory.js +0 -1
  45. package/dist/vendor/tunnel-client/client.d.ts +15 -8
  46. package/dist/vendor/tunnel-client/client.js +477 -407
  47. package/dist/vendor/tunnel-client/config.d.ts +5 -5
  48. package/dist/vendor/tunnel-client/config.js +5 -5
  49. package/dist/vendor/tunnel-client/index.d.ts +4 -4
  50. package/dist/vendor/tunnel-client/index.js +4 -4
  51. package/dist/vendor/tunnel-client/types.d.ts +19 -34
  52. package/dist/vendor/tunnel-client/types.js +1 -0
  53. package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
  54. package/dist/vendor/tunnel-client/ws-compat.js +70 -12
  55. package/dist/version.d.ts +1 -1
  56. package/dist/version.js +1 -1
  57. package/package.json +1 -1
  58. 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';
@@ -97,11 +100,22 @@ function stillRunningAndBillingSubject(runIds) {
97
100
  ? `Run ${ids[0]} is still executing on the server and will keep running (and billing) until it finishes.`
98
101
  : `${ids.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
99
102
  }
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.';
103
+ const TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE = 'Passing --no-cancel-on-interrupt keeps the run going in the cloud, and it is still billed. ' +
104
+ 'The tunnel is closed, so steps that still need your machine will fail; the run can still ' +
105
+ 'pass if it no longer needs to load anything from your machine.';
106
+ function tunnelInterruptOptOutConsequence(detach) {
107
+ if (detach.cancel !== 'skipped')
108
+ return TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE;
109
+ return (`${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE} Check the verdict later with ` +
110
+ `testsprite test result ${detach.testId} or testsprite test wait ${detach.runId}.`);
111
+ }
102
112
  function tunnelRerunCommand(detach) {
103
- return (`testsprite test run ${detach.testId} --local ${detach.localPort}` +
104
- (detach.localHost !== DEFAULT_LOCAL_HOST ? ` --local-host ${detach.localHost}` : '') +
113
+ return (`testsprite test run ${detach.testId}` +
114
+ (detach.environment ? ` --env ${quoteEnvironmentName(detach.environment)}` : '') +
115
+ (detach.automatic
116
+ ? ''
117
+ : ` --local ${detach.localPort}` +
118
+ (detach.localHost !== DEFAULT_LOCAL_HOST ? ` --local-host ${detach.localHost}` : '')) +
105
119
  (detach.reason === 'timeout' ? ' --timeout 1800' : ''));
106
120
  }
107
121
  /** Minimum wall-clock gap between adopted-client liveness reads. */
@@ -210,7 +224,7 @@ export function tunnelDetachMessage(detach, interrupt) {
210
224
  `machine through a tunnel that closes with this process, so it was cancelled (exit ` +
211
225
  `${interrupt?.exitCode ?? 130}). The run may already have been billed; a cancelled run's ` +
212
226
  `verdict is discarded. Start a new run with: ${tunnelRerunCommand(detach)}. ` +
213
- TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE);
227
+ tunnelInterruptOptOutConsequence(detach));
214
228
  }
215
229
  const cause = {
216
230
  interrupt: `Interrupted${interrupt ? ` by ${interrupt.signal}` : ''}`,
@@ -234,7 +248,7 @@ export function tunnelDetachMessage(detach, interrupt) {
234
248
  `${outcome[cancel]}\n` +
235
249
  ` Start a new run with: ${tunnelRerunCommand(detach)}.`;
236
250
  return cancel === 'cancelled' || cancel === 'skipped'
237
- ? `${message}\n ${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE}`
251
+ ? `${message}\n ${tunnelInterruptOptOutConsequence(detach)}`
238
252
  : message;
239
253
  }
240
254
  /**
@@ -273,7 +287,7 @@ export function tunnelInterruptNextAction(detach, err) {
273
287
  return (`Run ${detach.runId} was cancelled after ${err.signal} (exit ${err.exitCode}) and its ` +
274
288
  `tunnel was closed. ` +
275
289
  "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}`);
290
+ `Start a new run with: ${rerun}. ${tunnelInterruptOptOutConsequence(detach)}`);
277
291
  }
278
292
  if (detach.cancel === 'already-terminal') {
279
293
  return (`Run ${detach.runId} had already finished` +
@@ -283,7 +297,7 @@ export function tunnelInterruptNextAction(detach, err) {
283
297
  }
284
298
  if (detach.cancel === 'skipped') {
285
299
  return (`Start a new run with: ${rerun}, after stopping run ${detach.runId} with: testsprite test ` +
286
- `cancel ${detach.runId}. ${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE}`);
300
+ `cancel ${detach.runId}. ${tunnelInterruptOptOutConsequence(detach)}`);
287
301
  }
288
302
  return (`Start a new run with: ${rerun}, after stopping run ${detach.runId} with: testsprite test ` +
289
303
  `cancel ${detach.runId}; automatic cancellation after ${err.signal} failed.`);
@@ -337,9 +351,14 @@ function resolveApiUrl(opts, deps = {}) {
337
351
  return config.apiUrl;
338
352
  }
339
353
  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.
354
+ // The CLI error spec (§2) puts bad input (exit 5) ahead of authentication
355
+ // (exit 3), and the filter validation below keeps that order. `--project` is
356
+ // the one deliberate exception: with no credentials at all, being sent to
357
+ // `testsprite setup` beats being told about a flag you cannot use yet, so the
358
+ // required project is checked only after the client is built. With a key
359
+ // configured, a missing `--project` still exits 5 as before.
342
360
  const projectId = resolveProjectId(opts.projectId, deps);
361
+ const environment = normalizeEnvironmentName(opts.environment);
343
362
  const paginationFlags = validatePaginationFlags({
344
363
  pageSize: opts.pageSize,
345
364
  startingToken: opts.startingToken,
@@ -365,17 +384,66 @@ export async function runList(opts, deps = {}) {
365
384
  type: opts.type,
366
385
  createdFrom: opts.createdFrom,
367
386
  status: opts.status,
387
+ ...(environment !== undefined ? { environment } : {}),
368
388
  };
369
389
  let page;
370
- if (useSinglePage) {
371
- page = await fetchSinglePage(client, '/tests', paginationFlags.pageSize, opts.startingToken, baseQuery);
390
+ try {
391
+ if (useSinglePage) {
392
+ page = await fetchSinglePage(client, '/tests', paginationFlags.pageSize, opts.startingToken, baseQuery);
393
+ }
394
+ else {
395
+ page = await paginate(async ({ pageSize, cursor }) => client.get('/tests', {
396
+ query: { ...baseQuery, pageSize, cursor },
397
+ }), paginationFlags);
398
+ }
372
399
  }
373
- else {
374
- page = await paginate(async ({ pageSize, cursor }) => client.get('/tests', {
375
- query: { ...baseQuery, pageSize, cursor },
376
- }), paginationFlags);
400
+ catch (err) {
401
+ if (err instanceof InterruptError)
402
+ throw err;
403
+ if (err instanceof ApiError &&
404
+ err.code === 'VALIDATION_ERROR' &&
405
+ err.getDetail('field') === 'environment' &&
406
+ Array.isArray(err.getDetail('available')) &&
407
+ environment !== undefined) {
408
+ const available = err.getDetail('available').filter((name) => typeof name === 'string');
409
+ if (available.length > 0 && !err.nextAction.includes(available.join(', '))) {
410
+ const hint = `Flag \`--env\` is invalid: unknown environment '${environment}'; use one of: ${available.join(', ')}.`;
411
+ throw new ApiError({
412
+ code: err.code,
413
+ message: err.message,
414
+ nextAction: err.nextAction ? `${hint} ${err.nextAction}` : hint,
415
+ requestId: err.requestId,
416
+ details: err.details,
417
+ }, err.httpStatus, err.retryAfterMs);
418
+ }
419
+ }
420
+ throw err;
377
421
  }
378
- out.print(page, data => renderTestListText(data, { columns: opts.columns, noHeader: opts.noHeader }));
422
+ if (environment !== undefined) {
423
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
424
+ if (opts.output === 'text' && opts.noHeader) {
425
+ stderr(`Frontend test status requested for environment '${environment}'.`);
426
+ }
427
+ if (page.items.length > 0 &&
428
+ !page.items.some(test => test.headlineEnvironment !== undefined || test.statusByEnvironment !== undefined)) {
429
+ // An older server ignores `environment` and returns unfiltered
430
+ // statuses; printing them would look like a filtered answer.
431
+ throw ApiError.fromEnvelope({
432
+ error: {
433
+ code: 'UNSUPPORTED',
434
+ message: 'This server does not support `test list --env` yet.',
435
+ nextAction: 'Run the command without --env, or retry after the server is upgraded.',
436
+ requestId: 'local',
437
+ details: {},
438
+ },
439
+ });
440
+ }
441
+ }
442
+ out.print(page, data => renderTestListText(data, {
443
+ columns: opts.columns,
444
+ noHeader: opts.noHeader,
445
+ environment,
446
+ }));
379
447
  return page;
380
448
  }
381
449
  export const CLI_CREATE_PRIORITIES = ['p0', 'p1', 'p2', 'p3'];
@@ -460,6 +528,59 @@ async function emitDupNameAdvisoryIfNeeded(client, projectId, name, stderrFn) {
460
528
  clearTimeout(timer);
461
529
  }
462
530
  }
531
+ async function resolveCreationTargets(opts, deps, tests) {
532
+ const targets = new Map();
533
+ if (opts.dryRun || deps.environmentTunnel)
534
+ return targets;
535
+ const client = makeClient(opts, deps);
536
+ const cache = deps.environmentCache ?? new Map();
537
+ for (const test of new Map(tests.filter(test => test.type !== 'backend').map(test => [test.projectId, test])).values()) {
538
+ const target = await resolveEnvironmentRunTarget({
539
+ client,
540
+ knownTest: test,
541
+ environment: normalizeEnvironmentName(opts.environment),
542
+ targetUrl: opts.targetUrl,
543
+ noWait: opts.noWait,
544
+ cache,
545
+ stderr: deps.stderr ?? (line => process.stderr.write(`${line}\n`)),
546
+ });
547
+ if (target)
548
+ targets.set(test.projectId, target);
549
+ }
550
+ return targets;
551
+ }
552
+ /** A late failure must retain created IDs in the command's normal result envelope. */
553
+ async function withCreatedReceipt(opts, deps, receipt, operation) {
554
+ let printed = false;
555
+ try {
556
+ return await operation({
557
+ ...deps,
558
+ stdout: line => {
559
+ printed = true;
560
+ (deps.stdout ?? (text => process.stdout.write(`${text}\n`)))(line);
561
+ },
562
+ });
563
+ }
564
+ catch (err) {
565
+ if (!printed) {
566
+ const error = err instanceof ApiError
567
+ ? { code: err.code, message: err.message, exitCode: err.exitCode, details: err.details }
568
+ : {
569
+ code: 'UNSUPPORTED',
570
+ message: err instanceof Error ? err.message : String(err),
571
+ exitCode: err instanceof CLIError ? err.exitCode : 1,
572
+ };
573
+ const data = receipt;
574
+ const payload = data.results
575
+ ? {
576
+ results: data.results.map(row => row.status === 'created' ? { ...row, status: 'error', error } : row),
577
+ }
578
+ : { ...data, run: { testId: data.testId, status: 'error', error } };
579
+ makeOutput(opts.output, deps).print(payload, () => JSON.stringify(payload));
580
+ }
581
+ throw err;
582
+ }
583
+ }
463
584
  /**
464
585
  * `test create --code-file <path>` — M3.2 piece-2 first mutation.
465
586
  *
@@ -592,7 +713,7 @@ export async function runCreate(opts, deps = {}) {
592
713
  if (opts.category !== undefined) {
593
714
  body.category = opts.category;
594
715
  }
595
- if (opts.targetUrl !== undefined) {
716
+ if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
596
717
  assertNotLocal(opts.targetUrl, {
597
718
  field: 'target-url',
598
719
  helpCommand: 'testsprite test create',
@@ -621,6 +742,7 @@ export async function runCreate(opts, deps = {}) {
621
742
  // so this exact URL is never probed twice.
622
743
  if (opts.type !== 'backend' &&
623
744
  opts.targetUrl !== undefined &&
745
+ !parseLoopbackTargetUrl(opts.targetUrl) &&
624
746
  opts.run === true &&
625
747
  !opts.dryRun) {
626
748
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
@@ -631,6 +753,13 @@ export async function runCreate(opts, deps = {}) {
631
753
  shutdown: shutdownOf(deps),
632
754
  }, stderrFn);
633
755
  }
756
+ deps = { ...deps, environmentCache: deps.environmentCache ?? new Map() };
757
+ if (opts.run && !opts.dryRun && !deps.environmentTunnel) {
758
+ const targets = await resolveCreationTargets(opts, deps, [{ type: opts.type, projectId }]);
759
+ if (targets.size) {
760
+ 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 }));
761
+ }
762
+ }
634
763
  const client = makeClient(opts, deps);
635
764
  const out = makeOutput(opts.output, deps);
636
765
  // B3: best-effort duplicate-name advisory. Skip under --dry-run.
@@ -685,7 +814,7 @@ export async function runCreate(opts, deps = {}) {
685
814
  // `undefined` when unmapped) via `createContextWithUrl` above.
686
815
  runDashboardStderrFn(`Dashboard: ${createContextWithUrl.dashboardUrl}`);
687
816
  }
688
- await runTestRun({
817
+ await withCreatedReceipt(opts, deps, createContextWithUrl, runDeps => runTestRun({
689
818
  ...opts,
690
819
  testId: response.testId,
691
820
  idempotencyKey: runIdempotencyKey,
@@ -699,11 +828,13 @@ export async function runCreate(opts, deps = {}) {
699
828
  // Thread the known type so fast BE runs (terminal on first poll, where
700
829
  // beFallbackUsed would be false) still render `steps: n/a (backend)`.
701
830
  type: opts.type,
831
+ knownTest: { type: opts.type, projectId },
702
832
  // The preflight above (or its explicit --skip-preflight opt-out)
703
833
  // already ran against this exact URL before the create POST — never
704
834
  // probe it a second time here.
705
- skipPreflight: true,
706
- }, deps);
835
+ skipPreflight: opts.skipPreflight === true ||
836
+ (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)),
837
+ }, runDeps));
707
838
  return response;
708
839
  }
709
840
  // Emit dashboard deep-link when projectId + testId are known client-side
@@ -1957,7 +2088,7 @@ export async function runCreateFromPlan(opts, deps = {}) {
1957
2088
  // of orphaning a created test with no run.
1958
2089
  assertChainedRunKeyFits(opts.run, opts.idempotencyKey);
1959
2090
  requireNonEmpty('plan-from', opts.planFrom);
1960
- if (opts.targetUrl !== undefined) {
2091
+ if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
1961
2092
  assertNotLocal(opts.targetUrl, {
1962
2093
  field: 'target-url',
1963
2094
  helpCommand: 'testsprite test create',
@@ -2012,7 +2143,10 @@ export async function runCreateFromPlan(opts, deps = {}) {
2012
2143
  // plans already threw above), so no type gate is needed. The delegated
2013
2144
  // `runTestRun` call in the --run chain below sets `skipPreflight: true`
2014
2145
  // so this exact URL is never probed twice.
2015
- if (opts.targetUrl !== undefined && opts.run === true && !opts.dryRun) {
2146
+ if (opts.targetUrl !== undefined &&
2147
+ !parseLoopbackTargetUrl(opts.targetUrl) &&
2148
+ opts.run === true &&
2149
+ !opts.dryRun) {
2016
2150
  await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, {
2017
2151
  fetchImpl: deps.fetchImpl,
2018
2152
  proxyActive: isProxyAgentActive(),
@@ -2020,6 +2154,15 @@ export async function runCreateFromPlan(opts, deps = {}) {
2020
2154
  shutdown: shutdownOf(deps),
2021
2155
  }, stderrFn);
2022
2156
  }
2157
+ deps = { ...deps, environmentCache: deps.environmentCache ?? new Map() };
2158
+ if (opts.run && !opts.dryRun && !deps.environmentTunnel) {
2159
+ const targets = await resolveCreationTargets(opts, deps, [
2160
+ { type: plan.type, projectId: plan.projectId },
2161
+ ]);
2162
+ if (targets.size) {
2163
+ 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 }));
2164
+ }
2165
+ }
2023
2166
  const client = makeClient(opts, deps);
2024
2167
  const out = makeOutput(opts.output, deps);
2025
2168
  // Fix 4: best-effort duplicate-name advisory — same semantics as runCreate.
@@ -2053,9 +2196,11 @@ export async function runCreateFromPlan(opts, deps = {}) {
2053
2196
  if (planDashboardSuppressed) {
2054
2197
  emitDashboardLinkSuppressedAdvisory(response.testId, stderrFn);
2055
2198
  }
2056
- return runTestRun({
2199
+ return withCreatedReceipt(opts, deps, responseWithDashboardUrl, runDeps => runTestRun({
2057
2200
  ...opts,
2058
2201
  testId: response.testId,
2202
+ type: plan.type,
2203
+ knownTest: { type: plan.type, projectId: plan.projectId },
2059
2204
  idempotencyKey: runIdempotencyKey,
2060
2205
  timeoutSeconds: opts.timeout ?? DEFAULT_RUN_TIMEOUT_SECONDS,
2061
2206
  // B2(c): thread through whether --timeout was explicitly set so the
@@ -2065,8 +2210,9 @@ export async function runCreateFromPlan(opts, deps = {}) {
2065
2210
  createContext: responseWithDashboardUrl,
2066
2211
  // Already preflighted above (or explicitly skipped) — don't probe
2067
2212
  // the same URL twice.
2068
- skipPreflight: true,
2069
- }, deps).then(() => response);
2213
+ skipPreflight: opts.skipPreflight === true ||
2214
+ (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)),
2215
+ }, runDeps)).then(() => response);
2070
2216
  }
2071
2217
  if (opts.output === 'json') {
2072
2218
  out.print(responseWithDashboardUrl, data => renderCreateText(data));
@@ -2339,7 +2485,7 @@ export async function runCreateBatch(opts, deps = {}) {
2339
2485
  (opts.maxConcurrency < 1 || opts.maxConcurrency > MAX_BATCH_CONCURRENCY)) {
2340
2486
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
2341
2487
  }
2342
- if (opts.targetUrl !== undefined) {
2488
+ if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
2343
2489
  assertNotLocal(opts.targetUrl, {
2344
2490
  field: 'target-url',
2345
2491
  helpCommand: 'testsprite test create-batch',
@@ -2389,6 +2535,25 @@ export async function runCreateBatch(opts, deps = {}) {
2389
2535
  },
2390
2536
  });
2391
2537
  }
2538
+ deps = { ...deps, environmentCache: deps.environmentCache ?? new Map() };
2539
+ if (opts.run && !opts.dryRun && !deps.environmentTunnel) {
2540
+ const targets = await resolveCreationTargets(opts, deps, specs.map(spec => ({ type: spec.type, projectId: spec.projectId })));
2541
+ if (targets.size) {
2542
+ if ((opts.maxConcurrency ?? 5) > 10)
2543
+ throw localValidationError('max-concurrency', 'tunnel runs support at most 10 concurrent runs (default 5)');
2544
+ return withEnvironmentTunnel({
2545
+ ...opts,
2546
+ maxConcurrency: opts.maxConcurrency ?? 5,
2547
+ timeoutSeconds: opts.timeoutSeconds ?? DEFAULT_RUN_TIMEOUT_SECONDS,
2548
+ }, deps, [...targets.values()], 'test create-batch --run', context => runCreateBatch({
2549
+ ...opts,
2550
+ idempotencyKey,
2551
+ wait: true,
2552
+ maxConcurrency: opts.maxConcurrency ?? 5,
2553
+ skipPreflight: true,
2554
+ }, { ...deps, environmentTunnel: context, creationTargets: targets }));
2555
+ }
2556
+ }
2392
2557
  const client = makeClient(opts, deps);
2393
2558
  const out = makeOutput(opts.output, deps);
2394
2559
  const response = await client.post('/tests/batch', {
@@ -2510,9 +2675,18 @@ export async function runCreateBatch(opts, deps = {}) {
2510
2675
  else if (opts.output !== 'json') {
2511
2676
  out.print(enrichedResponse, data => renderBatchText(data));
2512
2677
  }
2678
+ deps = {
2679
+ ...deps,
2680
+ createdTests: new Map(response.results.flatMap(row => {
2681
+ const spec = specs[row.specIndex];
2682
+ return row.testId && spec
2683
+ ? [[row.testId, { type: spec.type, projectId: spec.projectId }]]
2684
+ : [];
2685
+ })),
2686
+ };
2513
2687
  // --run: fan out a trigger for each created test, then emit results.
2514
2688
  if (opts.run === true) {
2515
- await runBatchRun(opts, response, client, out, deps, opts.dryRun ? undefined : testIdToDashboardState);
2689
+ await withCreatedReceipt(opts, deps, response, runDeps => runBatchRun(opts, response, runDeps.environmentTunnel?.client ?? client, makeOutput(opts.output, runDeps), runDeps, opts.dryRun ? undefined : testIdToDashboardState));
2516
2690
  // runBatchRun handles its own exit-code logic via CLIError.
2517
2691
  // Return the create response to satisfy the return type; callers that
2518
2692
  // inspect the return value only do so when not using --run.
@@ -2585,6 +2759,44 @@ testIdToDashboardState) {
2585
2759
  out.print(envelope);
2586
2760
  return;
2587
2761
  }
2762
+ if (deps.environmentTunnel && deps.creationTargets) {
2763
+ deps.environmentTunnel.targets = new Map(testIds.flatMap(id => {
2764
+ const known = deps.createdTests?.get(id);
2765
+ const target = known ? deps.creationTargets.get(known.projectId) : undefined;
2766
+ return target ? [[id, target]] : [];
2767
+ }));
2768
+ }
2769
+ if (!deps.environmentTunnel) {
2770
+ const targets = new Map();
2771
+ const cache = deps.environmentCache ?? new Map();
2772
+ for (const testId of testIds) {
2773
+ const target = await resolveEnvironmentRunTarget({
2774
+ client,
2775
+ testId,
2776
+ knownTest: deps.createdTests?.get(testId),
2777
+ environment: normalizeEnvironmentName(opts.environment),
2778
+ targetUrl: opts.targetUrl,
2779
+ noWait: opts.noWait,
2780
+ verbose: opts.verbose || opts.debug,
2781
+ stderr: stderrFn,
2782
+ cache,
2783
+ });
2784
+ if (target)
2785
+ targets.set(testId, target);
2786
+ }
2787
+ if (targets.size) {
2788
+ const maxConcurrency = opts.maxConcurrency ?? 5;
2789
+ if (maxConcurrency > 10)
2790
+ throw localValidationError('max-concurrency', 'tunnel runs support at most 10 concurrent runs (default 5)');
2791
+ return withEnvironmentTunnel({
2792
+ ...opts,
2793
+ requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true, timeoutSeconds }),
2794
+ }, deps, [...targets.values()], 'test create-batch --run', context => {
2795
+ context.targets = targets;
2796
+ return runBatchRun({ ...opts, wait: true, maxConcurrency }, createResponse, context.client, out, { ...deps, environmentTunnel: context }, testIdToDashboardState);
2797
+ });
2798
+ }
2799
+ }
2588
2800
  // Pre-charge reachability preflight, ONCE for the whole batch
2589
2801
  // before the fan-out — not once per item (mirrors the "fire once per
2590
2802
  // invocation" contract Finding 2 already established for the target-url
@@ -2593,7 +2805,7 @@ testIdToDashboardState) {
2593
2805
  // `type: "backend"` spec always fails create-time server validation, so
2594
2806
  // it never reaches this fan-out at all — see the `beIndexes` warning in
2595
2807
  // `runCreateBatch`).
2596
- if (opts.targetUrl !== undefined) {
2808
+ if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
2597
2809
  await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, {
2598
2810
  fetchImpl: deps.fetchImpl,
2599
2811
  proxyActive: isProxyAgentActive(),
@@ -2611,6 +2823,7 @@ testIdToDashboardState) {
2611
2823
  // matching comment in `runTestRun` for why this replaced the old
2612
2824
  // `v3Enabled`-assumption probe.
2613
2825
  let targetUrlAdvisoryPrinted = false;
2826
+ let fanOutStopped = false;
2614
2827
  /**
2615
2828
  * Client-side sliding-window throttle: caps outgoing triggers at
2616
2829
  * BATCH_RUN_RATE_LIMIT (50) per BATCH_RUN_RATE_WINDOW_MS (60 s), sitting
@@ -2638,6 +2851,7 @@ testIdToDashboardState) {
2638
2851
  // partial reads it because a member's runId is local to triggerOne until
2639
2852
  // the poll settles.
2640
2853
  const dispatchedRunIds = new Map();
2854
+ const pendingTriggers = new Set();
2641
2855
  async function triggerOne(testId) {
2642
2856
  // Mint a fresh idempotency key per run — MUST NOT reuse the create key.
2643
2857
  const runIdempotencyKey = `cli-batch-run-${randomUUID()}`;
@@ -2707,18 +2921,41 @@ testIdToDashboardState) {
2707
2921
  }
2708
2922
  await sleepUntilOrInterrupt(clampedWait, shutdown.signal, sleepFn);
2709
2923
  }
2924
+ if (fanOutStopped && deps.environmentTunnel) {
2925
+ return { testId, runId: '', status: 'not_dispatched', codeVersion: '' };
2926
+ }
2710
2927
  try {
2711
- const result = await client.triggerRunWithMeta(testId, {
2928
+ const dispatch = client
2929
+ .triggerRunWithMeta(testId, {
2712
2930
  source: 'cli',
2713
2931
  ...(opts.targetUrl ? { targetUrl: opts.targetUrl } : {}),
2932
+ ...(deps.environmentTunnel?.targets?.has(testId)
2933
+ ? {
2934
+ targetUrl: deps.environmentTunnel.targets.get(testId).targetUrl,
2935
+ tunnelClientId: deps.environmentTunnel.clientId,
2936
+ }
2937
+ : {}),
2714
2938
  ...(opts.environment !== undefined ? { environment: opts.environment.trim() } : {}),
2715
2939
  },
2716
2940
  // retryOnRateLimit: false — the outer retry loop is the SOLE owner of
2717
2941
  // rate-limit handling for the batch path. Allowing the HTTP layer to add
2718
2942
  // up to 3 internal retries per outer attempt would multiply trigger
2719
2943
  // 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;
2944
+ { idempotencyKey: runIdempotencyKey, retryOnRateLimit: false })
2945
+ .then(async (result) => {
2946
+ if (result.body.runId)
2947
+ dispatchedRunIds.set(testId, result.body.runId);
2948
+ if (deps.environmentTunnel?.targets?.has(testId))
2949
+ await deps.environmentTunnel.confirm(result.body, [result.body.runId], false);
2950
+ return result;
2951
+ });
2952
+ pendingTriggers.add(dispatch);
2953
+ try {
2954
+ triggerResponse = (await dispatch).body;
2955
+ }
2956
+ finally {
2957
+ pendingTriggers.delete(dispatch);
2958
+ }
2722
2959
  // Fire the response-driven mismatch advisory at most once for the
2723
2960
  // whole batch. Synchronous check-and-set (no `await` between the
2724
2961
  // two) so two members whose triggers resolve in the same tick
@@ -2761,7 +2998,12 @@ testIdToDashboardState) {
2761
2998
  runId: '',
2762
2999
  status: 'error',
2763
3000
  codeVersion: '',
2764
- error: { code: err.code, message: err.message, exitCode: err.exitCode },
3001
+ error: {
3002
+ code: err.code,
3003
+ message: err.message,
3004
+ exitCode: err.exitCode,
3005
+ details: err.details,
3006
+ },
2765
3007
  };
2766
3008
  }
2767
3009
  if (outerRateLimitAttempt < BATCH_RUN_RATE_MAX_OUTER_RETRIES) {
@@ -2798,11 +3040,19 @@ testIdToDashboardState) {
2798
3040
  runId: '',
2799
3041
  status: 'error',
2800
3042
  codeVersion: '',
2801
- error: { code: err.code, message: err.message, exitCode: err.exitCode },
3043
+ error: {
3044
+ code: err.code,
3045
+ message: err.message,
3046
+ exitCode: err.exitCode,
3047
+ details: err.details,
3048
+ },
2802
3049
  };
2803
3050
  }
2804
3051
  // Reuse the same CONFLICT + --wait auto-resume logic as single-test run.
2805
- if (opts.wait && err instanceof ApiError && err.code === 'CONFLICT') {
3052
+ if (opts.wait &&
3053
+ !deps.environmentTunnel?.targets?.has(testId) &&
3054
+ err instanceof ApiError &&
3055
+ err.code === 'CONFLICT') {
2806
3056
  const conflictReason = err.getDetail('reason', (v) => typeof v === 'string' && v.length > 0);
2807
3057
  const currentRunId = err.getDetail('currentRunId', (v) => typeof v === 'string' && v.length > 0);
2808
3058
  if (conflictReason === 'run_in_flight' && currentRunId !== undefined) {
@@ -2853,6 +3103,7 @@ testIdToDashboardState) {
2853
3103
  code: apiErr?.code ?? 'INTERNAL',
2854
3104
  message: err instanceof Error ? err.message : String(err),
2855
3105
  exitCode: apiErr?.exitCode ?? 1,
3106
+ ...(apiErr ? { details: apiErr.details } : {}),
2856
3107
  },
2857
3108
  };
2858
3109
  }
@@ -2863,8 +3114,8 @@ testIdToDashboardState) {
2863
3114
  // a member's runId is otherwise local until its poll settles.
2864
3115
  if (triggerResponse.runId)
2865
3116
  dispatchedRunIds.set(testId, triggerResponse.runId);
2866
- if (!opts.wait) {
2867
- // No-wait path: return the trigger response as-is.
3117
+ if (!opts.wait || (fanOutStopped && deps.environmentTunnel)) {
3118
+ // Retain late trigger receipts without starting another poll during cleanup.
2868
3119
  if (opts.output !== 'json') {
2869
3120
  stderrFn(`[batch-run] ${testId} — triggered (runId: ${triggerResponse.runId}, status: ${triggerResponse.status})`);
2870
3121
  }
@@ -2881,6 +3132,16 @@ testIdToDashboardState) {
2881
3132
  // polling. Math.max(1, ...) would otherwise convert 0 ms → 1 s poll.
2882
3133
  const rem = remainingMs();
2883
3134
  if (opts.wait && rem <= 0) {
3135
+ if (deps.environmentTunnel?.targets?.has(testId)) {
3136
+ fanOutStopped = true;
3137
+ throw new ApiError({
3138
+ code: 'UNSUPPORTED',
3139
+ message: `Timed out after ${timeoutSeconds}s before polling run ${triggerResponse.runId}.`,
3140
+ nextAction: `Inspect cancellation with testsprite test cancel ${triggerResponse.runId}.`,
3141
+ requestId: 'local',
3142
+ details: { runId: triggerResponse.runId },
3143
+ });
3144
+ }
2884
3145
  return {
2885
3146
  testId,
2886
3147
  runId: triggerResponse.runId,
@@ -2901,6 +3162,7 @@ testIdToDashboardState) {
2901
3162
  finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
2902
3163
  timeoutSeconds: remainingSeconds,
2903
3164
  sleep: deps.sleep,
3165
+ onTick: run => deps.environmentTunnel?.onPoll(run),
2904
3166
  shutdown: shutdownOf(deps),
2905
3167
  onTransition: opts.verbose
2906
3168
  ? (msg) => stderrFn(`[batch-run][verbose] ${testId}: ${msg}`)
@@ -2908,6 +3170,21 @@ testIdToDashboardState) {
2908
3170
  });
2909
3171
  }
2910
3172
  catch (err) {
3173
+ // An unobserved tunnel run still occupies a slot until cleanup settles.
3174
+ if (deps.environmentTunnel?.targets?.has(testId)) {
3175
+ fanOutStopped = true;
3176
+ if (err instanceof TimeoutError) {
3177
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
3178
+ throw new ApiError({
3179
+ code: 'UNSUPPORTED',
3180
+ message: err.message,
3181
+ nextAction: `Inspect cancellation with testsprite test cancel ${triggerResponse.runId}.`,
3182
+ requestId: 'local',
3183
+ details: { runId: triggerResponse.runId },
3184
+ });
3185
+ }
3186
+ throw err;
3187
+ }
2911
3188
  // Interrupt rejects the fan-out — see the trigger-stage catch above.
2912
3189
  if (err instanceof InterruptError)
2913
3190
  throw err;
@@ -2951,6 +3228,7 @@ testIdToDashboardState) {
2951
3228
  code: apiErr?.code ?? 'INTERNAL',
2952
3229
  message: err instanceof Error ? err.message : String(err),
2953
3230
  exitCode: apiErr?.exitCode ?? 1,
3231
+ ...(apiErr ? { details: apiErr.details } : {}),
2954
3232
  },
2955
3233
  };
2956
3234
  }
@@ -2976,7 +3254,7 @@ testIdToDashboardState) {
2976
3254
  try {
2977
3255
  await new Promise((resolve, reject) => {
2978
3256
  function startNext() {
2979
- while (inFlight < concurrencyLimit && nextIdx < testIds.length) {
3257
+ while (!fanOutStopped && inFlight < concurrencyLimit && nextIdx < testIds.length) {
2980
3258
  const testId = testIds[nextIdx++];
2981
3259
  inFlight++;
2982
3260
  triggerOne(testId)
@@ -2987,7 +3265,10 @@ testIdToDashboardState) {
2987
3265
  if (inFlight === 0 && nextIdx >= testIds.length)
2988
3266
  resolve();
2989
3267
  })
2990
- .catch(reject);
3268
+ .catch(err => {
3269
+ fanOutStopped = true;
3270
+ reject(err);
3271
+ });
2991
3272
  }
2992
3273
  }
2993
3274
  startNext();
@@ -2996,10 +3277,12 @@ testIdToDashboardState) {
2996
3277
  });
2997
3278
  }
2998
3279
  catch (fanOutErr) {
3280
+ if (deps.environmentTunnel)
3281
+ await Promise.allSettled([...pendingTriggers]);
2999
3282
  // Graceful detach: leave stdout parseable — settled members keep
3000
3283
  // their real status, unfinished ones are marked running — then rethrow so
3001
3284
  // index.ts exits 128+signum.
3002
- if (fanOutErr instanceof InterruptError) {
3285
+ if (fanOutErr instanceof InterruptError || deps.environmentTunnel) {
3003
3286
  const settled = new Map(batchRunResults.map(r => [r.testId, r]));
3004
3287
  // Members mid-poll have no settled result yet — their runId comes from
3005
3288
  // the dispatchedRunIds map recorded at trigger time.
@@ -3013,12 +3296,14 @@ testIdToDashboardState) {
3013
3296
  const unfinished = partialResults
3014
3297
  .filter(r => r.status === 'running' && r.runId)
3015
3298
  .map(r => r.runId);
3016
- if (unfinished.length > 0) {
3299
+ if (unfinished.length > 0 && fanOutErr instanceof InterruptError) {
3017
3300
  fanOutErr.runWaitContext = true;
3018
- stderrFn(interruptDetachMessage(fanOutErr, unfinished));
3301
+ stderrFn(deps.environmentTunnel
3302
+ ? `Interrupted (${fanOutErr.signal}). The owned tunnel is closing; cancellation will be requested for unfinished tunnel runs.`
3303
+ : interruptDetachMessage(fanOutErr, unfinished));
3019
3304
  }
3020
- else {
3021
- stderrFn(`Interrupted (${fanOutErr.signal}). Already-triggered runs keep executing (and billing) server-side; ` +
3305
+ else if (fanOutErr instanceof InterruptError) {
3306
+ 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
3307
  `check them with: testsprite test list`);
3023
3308
  }
3024
3309
  }
@@ -4209,7 +4494,40 @@ export async function runResult(opts, deps = {}) {
4209
4494
  const printData = opts.output === 'json' && result.analysis !== undefined
4210
4495
  ? { ...result, analysis: annotateAnalysisTruncation(result.analysis) }
4211
4496
  : result;
4497
+ // Print the latest result first: the optional default-environment line below
4498
+ // costs up to two reads, and a slow read or Ctrl-C must not withhold it.
4212
4499
  out.print(printData, data => renderResultText(data));
4500
+ if (opts.output !== 'json' && result.environment) {
4501
+ try {
4502
+ const readOptions = {
4503
+ retry: false,
4504
+ signal: AbortSignal.timeout(ENVIRONMENT_PREFLIGHT_TIMEOUT_MS),
4505
+ };
4506
+ const test = await client.get(`/tests/${encodeURIComponent(opts.testId)}`, readOptions);
4507
+ if (test.projectId &&
4508
+ test.headlineEnvironment?.id !== result.environment.id &&
4509
+ test.statusByEnvironment?.some(status => status.environmentId !== result.environment?.id)) {
4510
+ // A missing default result lets the headline fall back to another environment.
4511
+ const listing = await client.get(`/projects/${encodeURIComponent(test.projectId)}/env`, readOptions);
4512
+ const defaultEnvironment = listing.environments?.find(environment => environment.isDefault);
4513
+ const defaultStatus = defaultEnvironment?.id
4514
+ ? test.statusByEnvironment.find(status => status.environmentId === defaultEnvironment.id)
4515
+ : undefined;
4516
+ if (defaultEnvironment?.name &&
4517
+ defaultStatus &&
4518
+ defaultStatus.environmentId !== result.environment.id) {
4519
+ const line = `Default environment ${defaultEnvironment.name}: ${defaultStatus.status} ` +
4520
+ `(testsprite test result ${opts.testId} --history --env ${quoteEnvironmentName(defaultEnvironment.name)})`;
4521
+ out.print(line, text => String(text));
4522
+ }
4523
+ }
4524
+ }
4525
+ catch (err) {
4526
+ if (err instanceof InterruptError)
4527
+ throw err;
4528
+ // Optional context must never prevent displaying the latest result.
4529
+ }
4530
+ }
4213
4531
  return result;
4214
4532
  }
4215
4533
  // ---------------------------------------------------------------------------
@@ -4985,77 +5303,6 @@ function normalizeEnvironmentName(raw) {
4985
5303
  }
4986
5304
  return name;
4987
5305
  }
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
5306
  /**
5060
5307
  * Validate the `--timeout` flag value. Returns a clamped integer in
5061
5308
  * range [1, 3600], or the default when absent.
@@ -5132,6 +5379,21 @@ reported) {
5132
5379
  }
5133
5380
  stderrFn(`[advisory] --no-auto-heal was not applied by the server — ${label} may re-author drifted code.`);
5134
5381
  }
5382
+ function assertFreshRunWaitOptions(opts, batchPath) {
5383
+ assertJUnitReportOptions({ ...opts, wait: opts.wait === true, batchPath });
5384
+ if (opts.ghOutput === true && !opts.wait)
5385
+ throw localValidationError('gh-output', '--gh-output requires --wait (it reduces the terminal run result). Add --wait.');
5386
+ if (opts.summaryFile !== undefined && !opts.wait)
5387
+ throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
5388
+ }
5389
+ function isSameLoopbackPort(url, port) {
5390
+ try {
5391
+ return parseLoopbackTargetUrl(url)?.port === port;
5392
+ }
5393
+ catch {
5394
+ return false;
5395
+ }
5396
+ }
5135
5397
  export async function runTestRun(opts, deps = {}) {
5136
5398
  assertIdempotencyKey(opts.idempotencyKey);
5137
5399
  const environment = normalizeEnvironmentName(opts.environment);
@@ -5139,29 +5401,56 @@ export async function runTestRun(opts, deps = {}) {
5139
5401
  // must happen before a client is even constructed, because the guarantee
5140
5402
  // this feature sells is that a doomed `--local` run never gets a run row,
5141
5403
  // a credit spend, or a tunnel credential.
5142
- const isTunnelRun = opts.localPort !== undefined;
5143
- if (isTunnelRun && opts.targetUrl !== undefined) {
5404
+ let isTunnelRun = opts.localPort !== undefined ||
5405
+ (opts.targetUrl !== undefined && parseLoopbackTargetUrl(opts.targetUrl) !== undefined);
5406
+ if (opts.localPort !== undefined && opts.targetUrl !== undefined) {
5144
5407
  throw localValidationError('local', '--local and --target-url are mutually exclusive: --local runs against your own machine ' +
5145
5408
  'through a tunnel, --target-url runs against an address the test runner can already ' +
5146
5409
  'reach. Pass one');
5147
5410
  }
5148
- if (isTunnelRun && !opts.wait) {
5411
+ if (opts.localPort !== undefined && !opts.wait) {
5149
5412
  // The tunnel's lifetime IS this process's lifetime, so a no-wait tunnel
5150
5413
  // run dooms itself the instant the command returns. The command wiring
5151
5414
  // forces --wait; this covers a programmatic caller that did not.
5152
5415
  throw localValidationError('local', '--local runs cannot detach: the tunnel closes when this command exits, so the run would ' +
5153
5416
  'fail. Remove --local, or let the command wait');
5154
5417
  }
5155
- if (opts.targetUrl !== undefined) {
5418
+ if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
5156
5419
  assertNotLocal(opts.targetUrl, {
5157
5420
  field: 'target-url',
5158
5421
  helpCommand: 'testsprite test run',
5159
5422
  hintContext: 'runtime',
5160
5423
  });
5161
5424
  }
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;
5425
+ if (!isTunnelRun && (opts.noWait || opts.type === 'backend' || opts.targetUrl !== undefined))
5426
+ assertNoTunnelOptions(opts);
5427
+ let localHost = opts.localHost ?? DEFAULT_LOCAL_HOST;
5428
+ let localTargetUrl = opts.localPort !== undefined ? buildLocalTargetUrl(localHost, opts.localPort) : undefined;
5429
+ let effectiveTargetUrl = localTargetUrl ?? opts.targetUrl;
5430
+ if (opts.dryRun && !isTunnelRun && !opts.noWait && opts.targetUrl === undefined) {
5431
+ try {
5432
+ const target = await resolveEnvironmentRunTarget({
5433
+ client: makeClient({ ...opts, dryRun: false }, deps),
5434
+ testId: opts.testId,
5435
+ knownTest: opts.knownTest,
5436
+ environment,
5437
+ dryRun: true,
5438
+ stderr: deps.stderr ?? (line => process.stderr.write(`${line}\n`)),
5439
+ });
5440
+ if (target) {
5441
+ isTunnelRun = true;
5442
+ localHost = target.host;
5443
+ effectiveTargetUrl = target.targetUrl;
5444
+ opts = { ...opts, wait: true };
5445
+ }
5446
+ }
5447
+ catch (err) {
5448
+ if (err instanceof InterruptError)
5449
+ throw err;
5450
+ }
5451
+ }
5452
+ if (opts.dryRun && !isTunnelRun)
5453
+ assertNoTunnelOptions(opts);
5165
5454
  if (opts.dryRun) {
5166
5455
  const client = makeClient(opts, deps);
5167
5456
  const out = makeOutput(opts.output, deps);
@@ -5216,18 +5505,49 @@ export async function runTestRun(opts, deps = {}) {
5216
5505
  // D4: under --wait, raise the per-request timeout to cover --timeout so a
5217
5506
  // slow trigger/long-poll under load isn't falsely cut at the 120s default.
5218
5507
  const requestTimeoutMs = resolveWaitRequestTimeoutMs(opts);
5219
- const clientOpts = { ...opts, requestTimeoutMs };
5220
- const client = makeClient(clientOpts, deps);
5221
- if (isTunnelRun) {
5222
- await preflightLocalRunTest({
5508
+ let clientOpts = { ...opts, requestTimeoutMs };
5509
+ let client;
5510
+ try {
5511
+ client = makeClient(clientOpts, deps);
5512
+ }
5513
+ catch (err) {
5514
+ assertFreshRunWaitOptions(opts, false);
5515
+ throw err;
5516
+ }
5517
+ const resolvedTarget = deps.environmentTunnel?.targets?.get(opts.testId) ??
5518
+ (opts.knownTest ? deps.creationTargets?.get(opts.knownTest.projectId) : undefined) ??
5519
+ (await resolveEnvironmentRunTarget({
5223
5520
  client,
5224
5521
  testId: opts.testId,
5522
+ knownTest: opts.knownTest,
5225
5523
  environment,
5226
5524
  localPort: opts.localPort,
5227
- opts,
5228
- deps,
5229
- });
5525
+ localHost: opts.localHost,
5526
+ targetUrl: opts.targetUrl,
5527
+ tunnelClientId: opts.tunnelClientId,
5528
+ noWait: opts.noWait,
5529
+ verbose: opts.verbose || opts.debug,
5530
+ stderr: deps.stderr ?? (line => process.stderr.write(`${line}\n`)),
5531
+ cache: deps.environmentCache,
5532
+ }));
5533
+ isTunnelRun = resolvedTarget !== undefined;
5534
+ if (!isTunnelRun)
5535
+ assertNoTunnelOptions(opts);
5536
+ if (resolvedTarget) {
5537
+ localHost = resolvedTarget.host;
5538
+ localTargetUrl = resolvedTarget.targetUrl;
5539
+ effectiveTargetUrl = resolvedTarget.targetUrl;
5540
+ opts = {
5541
+ ...opts,
5542
+ wait: true,
5543
+ timeoutSeconds: opts.timeoutIsDefault
5544
+ ? DEFAULT_LOCAL_RUN_TIMEOUT_SECONDS
5545
+ : opts.timeoutSeconds,
5546
+ };
5547
+ clientOpts = { ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) };
5548
+ client = makeClient(clientOpts, deps);
5230
5549
  }
5550
+ assertFreshRunWaitOptions(opts, false);
5231
5551
  const tunnelRequestTimeoutMs = isTunnelRun
5232
5552
  ? resolveRequestTimeoutMs(clientOpts, deps.env ?? process.env)
5233
5553
  : undefined;
@@ -5249,14 +5569,17 @@ export async function runTestRun(opts, deps = {}) {
5249
5569
  // this one is conclusive — the dial it performs is the same raw loopback
5250
5570
  // connect the tunnel client will make from this same process — so it
5251
5571
  // refuses rather than advises.
5252
- await assertLocalPortListening(localHost, opts.localPort, { skipPreflight: opts.skipPreflight }, stderrFn);
5572
+ await assertLocalPortListening(localHost, resolvedTarget.port, {
5573
+ skipPreflight: opts.skipPreflight,
5574
+ ...(resolvedTarget.automatic ? { environmentName: resolvedTarget.environmentName } : {}),
5575
+ }, stderrFn);
5253
5576
  if (isProxyAgentActive()) {
5254
5577
  stderrFn('[advisory] An HTTP proxy is configured for this process. The tunnel control channel ' +
5255
5578
  `honours it, but ${TUNNEL_DATA_PLANE_PROXY_BYPASS_DESCRIPTION} — if the ` +
5256
5579
  'run cannot reach your machine, an egress proxy is the first thing to rule out.');
5257
5580
  }
5258
5581
  }
5259
- else if (opts.targetUrl !== undefined) {
5582
+ else if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
5260
5583
  await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, {
5261
5584
  fetchImpl: deps.fetchImpl,
5262
5585
  proxyActive: isProxyAgentActive(),
@@ -5275,22 +5598,24 @@ export async function runTestRun(opts, deps = {}) {
5275
5598
  try {
5276
5599
  if (isTunnelRun) {
5277
5600
  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
- });
5601
+ tunnelSession =
5602
+ deps.environmentTunnel?.session ??
5603
+ (await openTunnelSession({
5604
+ log: stderrFn,
5605
+ logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error',
5606
+ onMinted: minted => stderrFn(`[tunnel] Minted tunnel client ${minted.clientId}; connecting…`),
5607
+ onFatal: () => {
5608
+ // Surfaced to the poll loop through `onTick` below; a remint cannot
5609
+ // rescue this run (see `lib/tunnel-session.ts`).
5610
+ },
5611
+ ...(opts.tunnelClientId !== undefined
5612
+ ? { adopt: { clientId: opts.tunnelClientId, expiresAt: '' } }
5613
+ : {}),
5614
+ }, {
5615
+ mint: async (ttlSeconds) => withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, mintClient => mintClient.mintTunnel({ ...(ttlSeconds ? { ttlSeconds } : {}) })),
5616
+ destroy: async (clientId) => deleteTunnelForCleanup(opts, deps, clientId),
5617
+ createClient: shutdownAwareTunnelClientFactory(deps.createTunnelClient ?? (options => new TunnelClient(options)), shutdown.signal),
5618
+ }));
5294
5619
  }
5295
5620
  catch (err) {
5296
5621
  // `openTunnelSession` converts a client-start rejection to UNAVAILABLE
@@ -5298,8 +5623,9 @@ export async function runTestRun(opts, deps = {}) {
5298
5623
  // initiating signal so the documented interrupt exit code is retained.
5299
5624
  if (shutdown.signal.aborted)
5300
5625
  throw shutdown.signal.reason;
5301
- throw err;
5626
+ throw tunnelScopeError(err);
5302
5627
  }
5628
+ recordTelemetryTunnelOpened(!tunnelSession.adopted);
5303
5629
  if (!tunnelSession.adopted) {
5304
5630
  stderrFn(`[tunnel] Reaching ${localTargetUrl} through TestSprite (client ${tunnelSession.clientId}).`);
5305
5631
  }
@@ -5422,19 +5748,6 @@ export async function runTestRun(opts, deps = {}) {
5422
5748
  throw incompatibleRun('its environment does not match the requested environment');
5423
5749
  }
5424
5750
  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
5751
  }
5439
5752
  // If the caller supplied --target-url, verify the in-flight run targets
5440
5753
  // the same URL. A mismatch means we would be reporting a different
@@ -5486,7 +5799,7 @@ export async function runTestRun(opts, deps = {}) {
5486
5799
  `). Auto-resuming wait on in-flight run. ` +
5487
5800
  `To run it again, cancel it with ` +
5488
5801
  `testsprite test cancel ${currentRunId}, or wait for it to finish; ` +
5489
- `then re-trigger${retryFlags ? ` with ${retryFlags}` : ''}.`);
5802
+ `then re-trigger${retryFlags ? ` with testsprite test run ${opts.testId} ${retryFlags}` : ''}.`);
5490
5803
  triggerResponse = {
5491
5804
  runId: currentRunId,
5492
5805
  status: 'queued',
@@ -5527,7 +5840,13 @@ export async function runTestRun(opts, deps = {}) {
5527
5840
  // for backend tests") already covers this case at create time.
5528
5841
  if (effectiveTargetUrl !== undefined &&
5529
5842
  opts.type !== 'backend' &&
5530
- triggerResponse.targetUrl !== effectiveTargetUrl) {
5843
+ triggerResponse.targetUrl !== effectiveTargetUrl &&
5844
+ !(
5845
+ // `--local <port>` never named a URL: the shorthand's host is the CLI's
5846
+ // own default, so an echo that differs only in loopback spelling
5847
+ // (localhost vs 127.0.0.1) is not an unapplied `--target-url`.
5848
+ opts.localPort !== undefined &&
5849
+ isSameLoopbackPort(triggerResponse.targetUrl, resolvedTarget?.port ?? opts.localPort))) {
5531
5850
  emitTargetUrlMismatchAdvisory(stderrFn, effectiveTargetUrl, triggerResponse.targetUrl);
5532
5851
  }
5533
5852
  if (!opts.wait) {
@@ -5628,8 +5947,10 @@ export async function runTestRun(opts, deps = {}) {
5628
5947
  return {
5629
5948
  runId: triggerResponse.runId,
5630
5949
  testId: opts.testId,
5631
- localPort: opts.localPort,
5950
+ localPort: resolvedTarget.port,
5632
5951
  localHost,
5952
+ automatic: resolvedTarget.automatic,
5953
+ environment,
5633
5954
  reason,
5634
5955
  ...(borrowedOwnerGone ? { ownerGone: true } : {}),
5635
5956
  cancel: cancel.outcome,
@@ -5900,7 +6221,8 @@ export async function runTestRun(opts, deps = {}) {
5900
6221
  // client whose ref'd heartbeat timer keeps the process alive after the
5901
6222
  // command has printed its last line.
5902
6223
  try {
5903
- await tunnelSession?.close();
6224
+ if (!deps.environmentTunnel)
6225
+ await tunnelSession?.close();
5904
6226
  }
5905
6227
  finally {
5906
6228
  disarmTunnelLifecycle?.();
@@ -6557,7 +6879,7 @@ export async function writeBatchJUnitReportIfRequested(opts, results, nameByTest
6557
6879
  const enriched = results.map(r => ({
6558
6880
  ...r,
6559
6881
  name: nameByTestId?.get(r.testId) ?? (r.testTitle?.trim() ? r.testTitle : undefined) ?? r.name,
6560
- durationSeconds: r.durationSeconds ?? durationSecondsBetween(r.startedAt, r.finishedAt),
6882
+ durationSeconds: r.durationSeconds ?? durationSecondsBetween(r.startedAt, r.finishedAt, r.createdAt),
6561
6883
  }));
6562
6884
  const xml = buildJUnitReport({
6563
6885
  suiteName,
@@ -6681,13 +7003,43 @@ export async function runTestRunAll(opts, deps = {}) {
6681
7003
  report: opts.report,
6682
7004
  reportFile: opts.reportFile,
6683
7005
  reportSuiteName: opts.reportSuiteName,
6684
- wait: opts.wait,
7006
+ wait: opts.wait || (!opts.dryRun && !opts.noWait),
6685
7007
  batchPath: true,
6686
7008
  });
6687
7009
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
6688
7010
  const out = makeOutput(opts.output, deps);
7011
+ if (opts.dryRun && opts.targetUrl === undefined && !opts.noWait) {
7012
+ let target;
7013
+ try {
7014
+ target = await resolveEnvironmentRunTarget({
7015
+ client: makeClient({ ...opts, dryRun: false }, deps),
7016
+ projectId,
7017
+ environment,
7018
+ dryRun: true,
7019
+ stderr: stderrFn,
7020
+ });
7021
+ }
7022
+ catch (err) {
7023
+ if (err instanceof InterruptError)
7024
+ throw err;
7025
+ }
7026
+ if (target) {
7027
+ await runTestRunLocalBatch({
7028
+ ...opts,
7029
+ all: true,
7030
+ testIds: [],
7031
+ projectId,
7032
+ resolvedTarget: target,
7033
+ skipPreflight: true,
7034
+ cancelOnInterrupt: true,
7035
+ allowEmpty: opts.allowEmpty === true,
7036
+ }, deps);
7037
+ return undefined;
7038
+ }
7039
+ }
6689
7040
  // --- Dry-run path ---
6690
7041
  if (opts.dryRun) {
7042
+ assertNoTunnelOptions(opts);
6691
7043
  // This path returns before makeClient() fires the banner, so emit it
6692
7044
  // here — otherwise the canned sample can be mistaken for a live response.
6693
7045
  emitDryRunBanner(stderrFn);
@@ -6716,13 +7068,46 @@ export async function runTestRunAll(opts, deps = {}) {
6716
7068
  }
6717
7069
  // Probe once before dispatch. A preview still warming up can use
6718
7070
  // --skip-preflight; ambiguous probe results warn without blocking.
6719
- if (opts.targetUrl !== undefined) {
7071
+ if (opts.targetUrl !== undefined && !parseLoopbackTargetUrl(opts.targetUrl)) {
6720
7072
  await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
6721
7073
  }
6722
7074
  // D4: under --wait, raise per-request timeout to cover --timeout.
6723
7075
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
6724
7076
  // `--env` gate — see `runTestRun`. Before the test-set enumeration so a
6725
7077
  // gated batch makes no billable call at all.
7078
+ const environmentCache = deps.environmentCache ?? new Map();
7079
+ const automaticTarget = opts.environmentResolutionComplete
7080
+ ? undefined
7081
+ : await resolveEnvironmentRunTarget({
7082
+ client,
7083
+ cache: environmentCache,
7084
+ projectId,
7085
+ environment,
7086
+ targetUrl: opts.targetUrl,
7087
+ noWait: opts.noWait,
7088
+ stderr: stderrFn,
7089
+ });
7090
+ if (automaticTarget) {
7091
+ await runTestRunLocalBatch({
7092
+ ...opts,
7093
+ testIds: [],
7094
+ all: true,
7095
+ projectId,
7096
+ localPort: automaticTarget.port,
7097
+ localHost: automaticTarget.host,
7098
+ resolvedTarget: automaticTarget,
7099
+ timeoutSeconds: opts.timeoutIsDefault
7100
+ ? DEFAULT_LOCAL_RUN_TIMEOUT_SECONDS
7101
+ : opts.timeoutSeconds,
7102
+ skipPreflight: opts.skipPreflight === true,
7103
+ cancelOnInterrupt: opts.cancelOnInterrupt !== false,
7104
+ allowEmpty: opts.allowEmpty === true,
7105
+ maxConcurrency: opts.concurrencyIsDefault ? 5 : opts.maxConcurrency,
7106
+ }, { ...deps, environmentCache });
7107
+ return undefined;
7108
+ }
7109
+ assertNoTunnelOptions(opts);
7110
+ assertFreshRunWaitOptions(opts, true);
6726
7111
  // Portal deep links for batch output: every test in the batch belongs to
6727
7112
  // opts.projectId, so per-item dashboardUrl needs no extra wire data. The
6728
7113
  // project-level URL closes out text-mode output ("watch the wave here").
@@ -7007,7 +7392,7 @@ export async function runTestRunAll(opts, deps = {}) {
7007
7392
  // deadline check below is the real stop), scaled to the timeout so it never
7008
7393
  // caps a legitimate long wait.
7009
7394
  const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
7010
- const batchDeadlineMs = Date.now() + opts.timeoutSeconds * 1000;
7395
+ const batchDeadlineMs = deps.environmentTunnel?.deadlineMs ?? Date.now() + opts.timeoutSeconds * 1000;
7011
7396
  // finding 1: reserve a poll window so the deferred-retry loop can't consume the
7012
7397
  // ENTIRE --timeout and leave the fan-out poll with nothing — which would report
7013
7398
  // already-finished runs as timeouts (exit 7) instead of their real verdicts
@@ -7225,6 +7610,7 @@ export async function runTestRunAll(opts, deps = {}) {
7225
7610
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
7226
7611
  const concurrencyLimit = opts.maxConcurrency;
7227
7612
  const freshRunResults = [];
7613
+ const reportTiming = new Map();
7228
7614
  // Single deadline shared across the whole fan-out (codex): each queued poll
7229
7615
  // gets the time REMAINING against this batch deadline, not a fresh full
7230
7616
  // `timeoutSeconds`. Without this, runs that wait behind `--max-concurrency`
@@ -7256,6 +7642,11 @@ export async function runTestRunAll(opts, deps = {}) {
7256
7642
  shutdown: shutdownOf(deps),
7257
7643
  resolveAlternate: lastResortAlternate,
7258
7644
  });
7645
+ reportTiming.set(runId, {
7646
+ createdAt: finalRun.createdAt,
7647
+ startedAt: finalRun.startedAt,
7648
+ finishedAt: finalRun.finishedAt,
7649
+ });
7259
7650
  return {
7260
7651
  testId: entry.testId,
7261
7652
  testTitle: finalRun.testTitle ?? null,
@@ -7304,6 +7695,11 @@ export async function runTestRunAll(opts, deps = {}) {
7304
7695
  onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`)),
7305
7696
  resolveAlternate,
7306
7697
  });
7698
+ reportTiming.set(runId, {
7699
+ createdAt: finalRun.createdAt,
7700
+ startedAt: finalRun.startedAt,
7701
+ finishedAt: finalRun.finishedAt,
7702
+ });
7307
7703
  return {
7308
7704
  testId: entry.testId,
7309
7705
  testTitle: finalRun.testTitle ?? null,
@@ -7438,7 +7834,13 @@ export async function runTestRunAll(opts, deps = {}) {
7438
7834
  ? await buildTestNameMap(client, opts.projectId)
7439
7835
  : undefined;
7440
7836
  const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
7441
- await writeBatchJUnitReportIfRequested(opts, [...freshRunResults, ...skippedJUnitResultsFromSummary(ciSummary)], freshNameMap);
7837
+ await writeBatchJUnitReportIfRequested(opts, [
7838
+ ...freshRunResults.map(r => ({
7839
+ ...r,
7840
+ ...(r.runId ? reportTiming.get(r.runId) : {}),
7841
+ })),
7842
+ ...skippedJUnitResultsFromSummary(ciSummary, freshRunResults),
7843
+ ], freshNameMap);
7442
7844
  out.print(jsonPayload);
7443
7845
  recordBatchOutcome({
7444
7846
  accepted: accepted.length,
@@ -7522,15 +7924,79 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7522
7924
  const environment = normalizeEnvironmentName(opts.environment);
7523
7925
  if (!Number.isInteger(opts.maxConcurrency) ||
7524
7926
  opts.maxConcurrency < 1 ||
7525
- opts.maxConcurrency > 10) {
7927
+ (opts.maxConcurrency > 10 &&
7928
+ !opts.concurrencyIsDefault &&
7929
+ (opts.localPort !== undefined ||
7930
+ opts.resolvedTarget !== undefined ||
7931
+ (opts.targetUrl !== undefined && parseLoopbackTargetUrl(opts.targetUrl) !== undefined)))) {
7526
7932
  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
7933
  }
7528
7934
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
7529
7935
  const out = makeOutput(opts.output, deps);
7530
- const targetUrl = buildLocalTargetUrl(opts.localHost, opts.localPort);
7936
+ let targetUrl = opts.resolvedTarget?.targetUrl ??
7937
+ opts.targetUrl ??
7938
+ (opts.localPort !== undefined
7939
+ ? buildLocalTargetUrl(opts.localHost ?? DEFAULT_LOCAL_HOST, opts.localPort)
7940
+ : undefined);
7531
7941
  const projectId = opts.all ? resolveProjectId(opts.projectId, deps) : opts.projectId;
7532
7942
  if (opts.all)
7533
7943
  requireProjectId(projectId);
7944
+ if (opts.localPort === undefined &&
7945
+ targetUrl !== undefined &&
7946
+ !parseLoopbackTargetUrl(targetUrl)) {
7947
+ if (!opts.all)
7948
+ severalIdsWithoutTunnel();
7949
+ assertNoTunnelOptions(opts);
7950
+ }
7951
+ const dryRunTargets = new Map();
7952
+ const automaticDryRun = opts.dryRun && targetUrl === undefined;
7953
+ if (automaticDryRun) {
7954
+ const targets = [];
7955
+ try {
7956
+ const client = makeClient({ ...opts, dryRun: false }, deps);
7957
+ const cache = deps.environmentCache ?? new Map();
7958
+ if (opts.all) {
7959
+ const target = await resolveEnvironmentRunTarget({
7960
+ client,
7961
+ projectId,
7962
+ environment,
7963
+ noWait: opts.noWait,
7964
+ tunnelClientId: opts.tunnelClientId,
7965
+ dryRun: true,
7966
+ cache,
7967
+ stderr: stderrFn,
7968
+ });
7969
+ if (target)
7970
+ targets.push(target);
7971
+ }
7972
+ for (const testId of opts.testIds) {
7973
+ const target = await resolveEnvironmentRunTarget({
7974
+ client,
7975
+ testId,
7976
+ projectId,
7977
+ environment,
7978
+ noWait: opts.noWait,
7979
+ tunnelClientId: opts.tunnelClientId,
7980
+ dryRun: true,
7981
+ cache,
7982
+ stderr: stderrFn,
7983
+ });
7984
+ if (target) {
7985
+ targets.push(target);
7986
+ dryRunTargets.set(testId, target);
7987
+ }
7988
+ }
7989
+ }
7990
+ catch (err) {
7991
+ if (err instanceof InterruptError)
7992
+ throw err;
7993
+ }
7994
+ if (!targets.length) {
7995
+ assertNoTunnelOptions(opts);
7996
+ severalIdsWithoutTunnel();
7997
+ }
7998
+ targetUrl = targets[0].targetUrl;
7999
+ }
7534
8000
  if (opts.dryRun) {
7535
8001
  emitDryRunBanner(stderrFn);
7536
8002
  const runs = (opts.all ? ['<each frontend test in the project>'] : opts.testIds).map(testId => ({
@@ -7538,8 +8004,12 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7538
8004
  path: `/api/cli/v1/tests/${testId}/runs`,
7539
8005
  body: {
7540
8006
  source: 'cli',
7541
- targetUrl,
7542
- tunnelClientId: opts.tunnelClientId ?? '<minted at run time>',
8007
+ ...(automaticDryRun && !opts.all && !dryRunTargets.has(testId)
8008
+ ? {}
8009
+ : {
8010
+ targetUrl: dryRunTargets.get(testId)?.targetUrl ?? targetUrl,
8011
+ tunnelClientId: opts.tunnelClientId ?? '<minted at run time>',
8012
+ }),
7543
8013
  ...(opts.autoHeal === false ? { autoHeal: false } : {}),
7544
8014
  ...(environment !== undefined ? { environment } : {}),
7545
8015
  },
@@ -7561,21 +8031,6 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7561
8031
  };
7562
8032
  const client = makeClient(clientOpts, deps);
7563
8033
  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
8034
  const skipped = [];
7580
8035
  let tests = opts.testIds.map(id => ({ id }));
7581
8036
  const knownTests = new Map();
@@ -7590,18 +8045,77 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7590
8045
  const omitted = page.items.length - filtered.length;
7591
8046
  if (omitted > 0)
7592
8047
  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 => {
8048
+ tests = filtered.map(t => {
7601
8049
  knownTests.set(t.id, { type: t.type, projectId: t.projectId ?? projectId });
7602
8050
  return { id: t.id, name: t.name };
7603
8051
  });
7604
8052
  }
8053
+ const targets = new Map();
8054
+ const cache = new Map();
8055
+ for (const test of tests) {
8056
+ let known = knownTests.get(test.id);
8057
+ if (!known) {
8058
+ try {
8059
+ known = await readEnvironmentPreflight(client, `/tests/${encodeURIComponent(test.id)}`);
8060
+ }
8061
+ catch (err) {
8062
+ if (err instanceof InterruptError)
8063
+ throw err;
8064
+ if (opts.localPort !== undefined)
8065
+ throw err;
8066
+ }
8067
+ }
8068
+ const target = (known?.projectId === projectId && known?.type !== 'backend'
8069
+ ? opts.resolvedTarget
8070
+ : undefined) ??
8071
+ (await resolveEnvironmentRunTarget({
8072
+ client,
8073
+ testId: test.id,
8074
+ knownTest: known,
8075
+ skipTestLookup: true,
8076
+ includeBackend: opts.all || (opts.localPort === undefined && opts.targetUrl === undefined),
8077
+ environment,
8078
+ localPort: opts.localPort,
8079
+ localHost: opts.localHost,
8080
+ targetUrl: opts.targetUrl,
8081
+ noWait: opts.noWait,
8082
+ tunnelClientId: opts.tunnelClientId,
8083
+ verbose: opts.verbose || opts.debug,
8084
+ stderr: stderrFn,
8085
+ cache,
8086
+ }));
8087
+ if (target && known?.type === 'backend') {
8088
+ skipped.push({ testId: test.id, reason: 'backend-test' });
8089
+ }
8090
+ else if (target)
8091
+ targets.set(test.id, target);
8092
+ }
8093
+ const firstTarget = targets.values().next().value;
8094
+ if (!firstTarget && !(opts.all && tests.length === 0) && skipped.length === 0) {
8095
+ assertNoTunnelOptions(opts);
8096
+ if (!opts.all)
8097
+ severalIdsWithoutTunnel();
8098
+ return void (await runTestRunAll({
8099
+ ...opts,
8100
+ projectId: projectId,
8101
+ wait: opts.wait === true,
8102
+ environmentResolutionComplete: true,
8103
+ }, deps));
8104
+ }
8105
+ if (skipped.length)
8106
+ stderrFn(`[advisory] ${skipped.length} backend test(s) skipped — tunnel runs frontend tests only.`);
8107
+ assertFreshRunWaitOptions({ ...opts, wait: true }, true);
8108
+ tests = tests.filter(test => !skipped.some(row => row.testId === test.id));
8109
+ targetUrl = firstTarget?.targetUrl;
8110
+ opts = { ...opts, maxConcurrency: opts.concurrencyIsDefault ? 5 : opts.maxConcurrency };
8111
+ if (opts.maxConcurrency > 10)
8112
+ throw localValidationError('max-concurrency', 'tunnel runs support at most 10 concurrent runs (default 5)');
8113
+ for (const target of new Map([...targets.values()].map(target => [target.targetUrl, target])).values()) {
8114
+ await assertLocalPortListening(target.host, target.port, {
8115
+ skipPreflight: opts.skipPreflight,
8116
+ ...(target.automatic ? { environmentName: target.environmentName } : {}),
8117
+ }, stderrFn);
8118
+ }
7605
8119
  const results = tests.map(t => ({
7606
8120
  testId: t.id,
7607
8121
  ...(t.name !== undefined ? { testTitle: t.name } : {}),
@@ -7612,6 +8126,7 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7612
8126
  // start/finish timestamps; it stays out of the JSON, which only reports what
7613
8127
  // the server said.
7614
8128
  const clientSeconds = new WeakMap();
8129
+ const reportCreatedAt = new WeakMap();
7615
8130
  const batchSummary = () => {
7616
8131
  const passed = results.filter(r => r.status === 'passed').length;
7617
8132
  const timedOut = results.filter(r => r.status === 'timeout').length;
@@ -7652,7 +8167,11 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7652
8167
  stderr: stderrFn,
7653
8168
  }, 'run');
7654
8169
  await writeBatchJUnitReportIfRequested(opts, [
7655
- ...results.map(r => ({ ...r, status: r.runId === undefined ? 'skipped' : r.status })),
8170
+ ...results.map(r => ({
8171
+ ...r,
8172
+ createdAt: reportCreatedAt.get(r),
8173
+ status: r.runId === undefined ? 'skipped' : r.status,
8174
+ })),
7656
8175
  ...skipped.map(s => ({ testId: s.testId, status: 'skipped' })),
7657
8176
  ]);
7658
8177
  };
@@ -7711,19 +8230,6 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7711
8230
  });
7712
8231
  return;
7713
8232
  }
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
8233
  const shutdown = shutdownOf(deps);
7728
8234
  const disarm = shutdown.arm();
7729
8235
  const poolAbort = new AbortController();
@@ -7777,10 +8283,11 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7777
8283
  // partial result (every test `not-run`); the session helper has already
7778
8284
  // deleted a minted binding.
7779
8285
  if (!shutdown.signal.aborted)
7780
- throw err;
8286
+ throw tunnelScopeError(err);
7781
8287
  setAbort(shutdown.signal.reason);
7782
8288
  }
7783
8289
  if (session !== undefined) {
8290
+ recordTelemetryTunnelOpened(!session.adopted);
7784
8291
  stderrFn(`[tunnel] Reaching ${targetUrl} through TestSprite (client ${session.clientId}).`);
7785
8292
  stderrFn(`Running ${results.length} tests through one tunnel, up to ${opts.maxConcurrency} at a time.`);
7786
8293
  const liveSession = session;
@@ -7808,15 +8315,19 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7808
8315
  if (abortReason !== undefined)
7809
8316
  return;
7810
8317
  const fatalBeforeTrigger = liveSession.fatalReason();
7811
- if (fatalBeforeTrigger) {
8318
+ if (fatalBeforeTrigger && targets.has(row.testId)) {
7812
8319
  setAbort(new TunnelLostError(fatalBeforeTrigger, '', liveSession.fatalMessage()), fatalBeforeTrigger);
7813
8320
  return;
7814
8321
  }
7815
8322
  triggerStartedAtMs = Date.now();
7816
8323
  const triggering = withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, triggerClient => triggerClient.triggerRunWithMeta(row.testId, {
7817
8324
  source: 'cli',
7818
- targetUrl,
7819
- tunnelClientId: liveSession.clientId,
8325
+ ...(targets.has(row.testId)
8326
+ ? {
8327
+ targetUrl: targets.get(row.testId).targetUrl,
8328
+ tunnelClientId: liveSession.clientId,
8329
+ }
8330
+ : {}),
7820
8331
  ...(opts.autoHeal === false ? { autoHeal: false } : {}),
7821
8332
  ...(environment !== undefined ? { environment } : {}),
7822
8333
  }, { idempotencyKey: key }));
@@ -7830,7 +8341,8 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7830
8341
  row.runId = response.runId;
7831
8342
  row.status = 'running';
7832
8343
  activeRows.add(index);
7833
- unsettled.add(row);
8344
+ if (targets.has(row.testId))
8345
+ unsettled.add(row);
7834
8346
  activeRuns++;
7835
8347
  peakInFlight = Math.max(peakInFlight, activeRuns);
7836
8348
  stderrFn(`[${index + 1}/${results.length}] ${row.testId} → run ${row.runId}`);
@@ -7874,7 +8386,9 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7874
8386
  try {
7875
8387
  if (abortReason !== undefined)
7876
8388
  return;
7877
- if (liveSession.adopted && checkBorrowedLiveness === undefined) {
8389
+ if (targets.has(row.testId) &&
8390
+ liveSession.adopted &&
8391
+ checkBorrowedLiveness === undefined) {
7878
8392
  checkBorrowedLiveness = makeBorrowedTunnelLivenessCheck({
7879
8393
  client: livenessClient,
7880
8394
  clientId: liveSession.clientId,
@@ -7893,14 +8407,14 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7893
8407
  onTick: (run, elapsedMs) => {
7894
8408
  if (abortReason !== undefined)
7895
8409
  throw abortReason;
7896
- if (!isTerminalStatus(run.status)) {
8410
+ if (targets.has(row.testId) && !isTerminalStatus(run.status)) {
7897
8411
  const fatal = liveSession.fatalReason();
7898
8412
  if (fatal)
7899
8413
  throw new TunnelLostError(fatal, row.runId, liveSession.fatalMessage());
7900
8414
  }
7901
8415
  ticker.update(formatRunProgressLine(run, elapsedMs, `(${row.testId})`));
7902
8416
  },
7903
- ...(checkBorrowedLiveness
8417
+ ...(targets.has(row.testId) && checkBorrowedLiveness
7904
8418
  ? {
7905
8419
  resolveAlternate: async (_run, _elapsed, signal) => {
7906
8420
  await checkBorrowedLiveness(signal);
@@ -7913,6 +8427,7 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7913
8427
  unsettled.delete(row);
7914
8428
  row.testTitle = finalRun.testTitle ?? row.testTitle;
7915
8429
  row.projectId = finalRun.projectId;
8430
+ reportCreatedAt.set(row, finalRun.createdAt);
7916
8431
  row.startedAt = finalRun.startedAt;
7917
8432
  row.finishedAt = finalRun.finishedAt;
7918
8433
  if (typeof finalRun.dashboardUrl === 'string')
@@ -7958,7 +8473,7 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
7958
8473
  // An owned run cannot finish once this process closes its tunnel, so a
7959
8474
  // run the batch stops waiting for is cancelled — unless the caller
7960
8475
  // opted out, exactly as the single-run path honours it.
7961
- if (!liveSession.adopted) {
8476
+ if (!liveSession.adopted && targets.has(row.testId)) {
7962
8477
  const cancel = await cancelDoomedTunnelRun({
7963
8478
  runId: row.runId,
7964
8479
  enabled: opts.cancelOnInterrupt,
@@ -8088,6 +8603,16 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8088
8603
  const waits = results.filter(r => r.runId && r.status === 'running').map(r => r.runId);
8089
8604
  if (waits.length)
8090
8605
  stderrFn(`Runs may still finish: testsprite test wait ${waits.join(' ')}`);
8606
+ if (abortReason instanceof InterruptError &&
8607
+ opts.cancelOnInterrupt === false &&
8608
+ session?.adopted === false &&
8609
+ waits.length) {
8610
+ stderrFn(tunnelInterruptOptOutConsequence({
8611
+ cancel: 'skipped',
8612
+ testId: results.find(r => r.runId === waits[0]).testId,
8613
+ runId: waits.join(' '),
8614
+ }));
8615
+ }
8091
8616
  if (session !== undefined)
8092
8617
  stderrFn(`Tunnel ${session.clientId}: ${unfinished.filter(r => r.cancel === 'cancelled').length} run(s) cancelled, ${waits.length} still running.`);
8093
8618
  if (lostReason !== undefined)
@@ -8138,11 +8663,7 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8138
8663
  * Batch / `--all`: `POST /tests/batch/rerun` → per-test runIds. With
8139
8664
  * `--wait`, fan-out poll under `--max-concurrency`. `deferred[]` → exit 7.
8140
8665
  */
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);
8666
+ function validateRerunOptions(opts) {
8146
8667
  // -------------------------------------------------------------------------
8147
8668
  // Input validation
8148
8669
  // -------------------------------------------------------------------------
@@ -8194,7 +8715,7 @@ export async function runTestRerun(opts, deps = {}) {
8194
8715
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
8195
8716
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
8196
8717
  }
8197
- const isSingle = !opts.all && opts.testIds.length === 1;
8718
+ const isSingle = !opts.all && !opts.batchResolved && opts.testIds.length === 1;
8198
8719
  assertJUnitReportOptions({
8199
8720
  report: opts.report,
8200
8721
  reportFile: opts.reportFile,
@@ -8202,6 +8723,85 @@ export async function runTestRerun(opts, deps = {}) {
8202
8723
  wait: opts.wait,
8203
8724
  batchPath: !isSingle,
8204
8725
  });
8726
+ if (opts.ghOutput === true && (isSingle || !opts.wait))
8727
+ throw localValidationError('gh-output', '--gh-output requires a batch rerun with --wait (--all or 2+ test ids). Remove --gh-output, or add --all --wait.');
8728
+ if (opts.summaryFile !== undefined && (isSingle || !opts.wait))
8729
+ throw localValidationError('summary-file', '--summary-file requires a batch rerun with --wait (--all or 2+ test ids). Remove --summary-file, or add --all --wait.');
8730
+ return isSingle;
8731
+ }
8732
+ export async function runTestRerun(opts, deps = {}) {
8733
+ assertIdempotencyKey(opts.idempotencyKey);
8734
+ validateRerunOptions({ ...opts, wait: opts.wait || (!opts.dryRun && !opts.noWait) });
8735
+ if (opts.dryRun || deps.environmentTunnel || opts.testIds.length === 0 || opts.all)
8736
+ return runTestRerunCore(opts, deps);
8737
+ let client;
8738
+ try {
8739
+ client = makeClient(opts, deps);
8740
+ }
8741
+ catch (err) {
8742
+ validateRerunOptions(opts);
8743
+ throw err;
8744
+ }
8745
+ const stderr = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
8746
+ const targets = new Map();
8747
+ const backend = [];
8748
+ const cache = new Map();
8749
+ for (const testId of opts.testIds) {
8750
+ let knownTest = opts.knownTests?.get(testId);
8751
+ try {
8752
+ if (!knownTest)
8753
+ knownTest = await readEnvironmentPreflight(client, `/tests/${encodeURIComponent(testId)}`);
8754
+ }
8755
+ catch (err) {
8756
+ if (err instanceof InterruptError)
8757
+ throw err;
8758
+ }
8759
+ const target = await resolveEnvironmentRunTarget({
8760
+ client,
8761
+ testId,
8762
+ knownTest,
8763
+ skipTestLookup: true,
8764
+ includeBackend: opts.testIds.length > 1 || opts.batchResolved,
8765
+ environment: normalizeEnvironmentName(opts.environment),
8766
+ noWait: opts.noWait,
8767
+ verbose: opts.verbose || opts.debug,
8768
+ stderr,
8769
+ cache,
8770
+ });
8771
+ if (target && knownTest?.type === 'backend')
8772
+ backend.push(testId);
8773
+ else if (target)
8774
+ targets.set(testId, target);
8775
+ }
8776
+ if (!targets.size)
8777
+ return runTestRerunCore(opts, deps);
8778
+ const maxConcurrency = opts.concurrencyIsDefault ? 5 : opts.maxConcurrency;
8779
+ if (maxConcurrency > 10)
8780
+ throw localValidationError('max-concurrency', 'tunnel runs support at most 10 concurrent runs (default 5)');
8781
+ return withEnvironmentTunnel({
8782
+ ...opts,
8783
+ maxConcurrency,
8784
+ requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }),
8785
+ }, deps, [...targets.values()], 'test rerun', context => {
8786
+ context.targets = targets;
8787
+ context.skipped = backend.map(testId => ({ testId, reason: 'backend-test' }));
8788
+ if (backend.length)
8789
+ stderr(`[advisory] ${backend.length} backend test(s) skipped — tunnel runs frontend tests only.`);
8790
+ return runTestRerunCore({
8791
+ ...opts,
8792
+ testIds: opts.testIds.filter(id => !backend.includes(id)),
8793
+ batchResolved: opts.batchResolved || opts.testIds.length > 1,
8794
+ wait: true,
8795
+ maxConcurrency,
8796
+ }, { ...deps, environmentTunnel: context });
8797
+ });
8798
+ }
8799
+ async function runTestRerunCore(opts, deps = {}) {
8800
+ assertIdempotencyKey(opts.idempotencyKey);
8801
+ const environment = normalizeEnvironmentName(opts.environment);
8802
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
8803
+ const out = makeOutput(opts.output, deps);
8804
+ const isSingle = validateRerunOptions(opts.all && !opts.dryRun && !opts.noWait ? { ...opts, wait: true } : opts);
8205
8805
  // -------------------------------------------------------------------------
8206
8806
  // Pre-flight: auto-heal + Free-tier hint (best-effort, non-blocking)
8207
8807
  // -------------------------------------------------------------------------
@@ -8253,7 +8853,8 @@ export async function runTestRerun(opts, deps = {}) {
8253
8853
  }
8254
8854
  // D4: under --wait, raise the per-request timeout to cover --timeout so a
8255
8855
  // slow rerun trigger / long-poll under load isn't cut at the 120s default.
8256
- const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
8856
+ const client = deps.environmentTunnel?.client ??
8857
+ makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
8257
8858
  // `--env` gate — see `runTestRun`. Before the type probe and every dispatch.
8258
8859
  const idempotencyKey = opts.idempotencyKey ?? `cli-rerun-${randomUUID()}`;
8259
8860
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
@@ -8292,6 +8893,12 @@ export async function runTestRerun(opts, deps = {}) {
8292
8893
  try {
8293
8894
  rerunResp = await client.triggerRerun(testId, {
8294
8895
  source: 'cli',
8896
+ ...(deps.environmentTunnel?.targets?.has(testId)
8897
+ ? {
8898
+ tunnelClientId: deps.environmentTunnel.clientId,
8899
+ targetUrl: deps.environmentTunnel.targets.get(testId).targetUrl,
8900
+ }
8901
+ : {}),
8295
8902
  // Always send the effective boolean, including an explicit `false`
8296
8903
  // opt-out — the server defaults an ABSENT field to heal-on, so
8297
8904
  // omitting the key on opt-out silently discarded --no-auto-heal.
@@ -8299,6 +8906,7 @@ export async function runTestRerun(opts, deps = {}) {
8299
8906
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
8300
8907
  ...(environment !== undefined ? { environment } : {}),
8301
8908
  }, { idempotencyKey });
8909
+ await deps.environmentTunnel?.confirm(rerunResp, [rerunResp.runId]);
8302
8910
  }
8303
8911
  catch (err) {
8304
8912
  if (err instanceof ApiError && err.code === 'CONFLICT') {
@@ -8443,7 +9051,10 @@ export async function runTestRerun(opts, deps = {}) {
8443
9051
  sleep: deps.sleep,
8444
9052
  shutdown: shutdownOf(deps),
8445
9053
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
8446
- onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `[${member.role}]`)),
9054
+ onTick: (run, elapsedMs) => {
9055
+ deps.environmentTunnel?.onPoll(run);
9056
+ ticker.update(formatRunProgressLine(run, elapsedMs, `[${member.role}]`));
9057
+ },
8447
9058
  resolveAlternate,
8448
9059
  });
8449
9060
  return { kind: 'terminal', run: finalRun };
@@ -8719,7 +9330,10 @@ export async function runTestRerun(opts, deps = {}) {
8719
9330
  sleep: deps.sleep,
8720
9331
  shutdown: shutdownOf(deps),
8721
9332
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
8722
- onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, '(replay)')),
9333
+ onTick: (run, elapsedMs) => {
9334
+ deps.environmentTunnel?.onPoll(run);
9335
+ ticker.update(formatRunProgressLine(run, elapsedMs, '(replay)'));
9336
+ },
8723
9337
  resolveAlternate,
8724
9338
  });
8725
9339
  }
@@ -8736,15 +9350,21 @@ export async function runTestRerun(opts, deps = {}) {
8736
9350
  return [
8737
9351
  `runId ${p.runId}`,
8738
9352
  `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
8739
- `hint Re-attach with: testsprite test wait ${p.runId}`,
9353
+ deps.environmentTunnel
9354
+ ? `hint The owned tunnel is closing; inspect cancellation with testsprite test cancel ${p.runId}`
9355
+ : `hint Re-attach with: testsprite test wait ${p.runId}`,
8740
9356
  ].join('\n');
8741
9357
  });
8742
9358
  throw ApiError.fromEnvelope({
8743
9359
  error: {
8744
9360
  code: 'UNSUPPORTED',
8745
9361
  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}`,
9362
+ (deps.environmentTunnel
9363
+ ? 'The owned tunnel is closing; cancellation will be requested.'
9364
+ : stillRunningAndBillingSubject(rerunResp.runId)),
9365
+ nextAction: deps.environmentTunnel
9366
+ ? `Inspect cancellation: testsprite test cancel ${rerunResp.runId}. Start a new run: testsprite test run ${testId}${environment ? ` --env ${quoteEnvironmentName(environment)}` : ''}.`
9367
+ : `Resume polling: testsprite test wait ${rerunResp.runId}, or cancel it: testsprite test cancel ${rerunResp.runId}`,
8748
9368
  requestId: 'local',
8749
9369
  details: { runId: rerunResp.runId, timeoutSeconds: opts.timeoutSeconds },
8750
9370
  },
@@ -8760,12 +9380,16 @@ export async function runTestRerun(opts, deps = {}) {
8760
9380
  return [
8761
9381
  `runId ${p.runId}`,
8762
9382
  `status ${p.status} (request timed out)`,
8763
- `hint Re-attach with: testsprite test wait ${p.runId}`,
9383
+ deps.environmentTunnel
9384
+ ? `hint The owned tunnel is closing; inspect cancellation with testsprite test cancel ${p.runId}`
9385
+ : `hint Re-attach with: testsprite test wait ${p.runId}`,
8764
9386
  `hint Cancel with: testsprite test cancel ${p.runId}`,
8765
9387
  ].join('\n');
8766
9388
  });
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}`);
9389
+ stderrFn(`Request timed out. ${deps.environmentTunnel ? 'The owned tunnel is closing; cancellation will be requested.' : stillRunningAndBillingSubject(rerunResp.runId)} ` +
9390
+ (deps.environmentTunnel
9391
+ ? `Inspect cancellation with testsprite test cancel ${rerunResp.runId}.`
9392
+ : `Re-attach with: testsprite test wait ${rerunResp.runId}, or cancel with: testsprite test cancel ${rerunResp.runId}`));
8769
9393
  throw err;
8770
9394
  }
8771
9395
  // RATE_LIMITED during polling — see the matching comment in runTestRun.
@@ -8779,11 +9403,15 @@ export async function runTestRerun(opts, deps = {}) {
8779
9403
  return [
8780
9404
  `runId ${p.runId}`,
8781
9405
  `status ${p.status} (rate limited by the server)`,
8782
- `hint Re-attach with: testsprite test wait ${p.runId}`,
9406
+ deps.environmentTunnel
9407
+ ? `hint The owned tunnel is closing; inspect cancellation with testsprite test cancel ${p.runId}`
9408
+ : `hint Re-attach with: testsprite test wait ${p.runId}`,
8783
9409
  `hint Cancel with: testsprite test cancel ${p.runId}`,
8784
9410
  ].join('\n');
8785
9411
  });
8786
- stderrFn(rateLimitedDetachMessage(err, [rerunResp.runId]));
9412
+ stderrFn(deps.environmentTunnel
9413
+ ? `The owned tunnel is closing; cancellation will be requested. Inspect with testsprite test cancel ${rerunResp.runId}.`
9414
+ : rateLimitedDetachMessage(err, [rerunResp.runId]));
8787
9415
  throw err;
8788
9416
  }
8789
9417
  // Graceful detach on SIGINT/SIGTERM — see runTestRun.
@@ -8795,11 +9423,15 @@ export async function runTestRerun(opts, deps = {}) {
8795
9423
  return [
8796
9424
  `runId ${p.runId}`,
8797
9425
  `status ${p.status} (interrupted)`,
8798
- `hint Re-attach with: testsprite test wait ${p.runId}`,
9426
+ deps.environmentTunnel
9427
+ ? `hint The owned tunnel is closing; inspect cancellation with testsprite test cancel ${p.runId}`
9428
+ : `hint Re-attach with: testsprite test wait ${p.runId}`,
8799
9429
  `hint Cancel with: testsprite test cancel ${p.runId}`,
8800
9430
  ].join('\n');
8801
9431
  });
8802
- stderrFn(interruptDetachMessage(err, [rerunResp.runId]));
9432
+ stderrFn(deps.environmentTunnel
9433
+ ? `Interrupted (${err.signal}). Cancellation will be requested for ${rerunResp.runId} before the owned tunnel closes.`
9434
+ : interruptDetachMessage(err, [rerunResp.runId]));
8803
9435
  err.runWaitContext = true;
8804
9436
  throw err;
8805
9437
  }
@@ -8828,6 +9460,7 @@ export async function runTestRerun(opts, deps = {}) {
8828
9460
  // Batch / --all rerun path
8829
9461
  // -------------------------------------------------------------------------
8830
9462
  let testIds = opts.testIds;
9463
+ let knownTests = opts.knownTests;
8831
9464
  if (opts.all) {
8832
9465
  // Validate --status filter before any network call.
8833
9466
  if (opts.statusFilter !== undefined) {
@@ -8875,7 +9508,9 @@ export async function runTestRerun(opts, deps = {}) {
8875
9508
  }
8876
9509
  }
8877
9510
  testIds = allTests.map(t => t.id);
9511
+ knownTests = new Map(allTests.map(t => [t.id, { type: t.type, projectId: t.projectId ?? opts.projectId }]));
8878
9512
  if (testIds.length === 0) {
9513
+ validateRerunOptions(opts);
8879
9514
  stderrFn(`No tests found in project ${opts.projectId} matching filters — nothing to rerun.`);
8880
9515
  out.print({ accepted: [], deferred: [], conflicts: [], closure: { byProject: [] } });
8881
9516
  // Zero-dispatch: emit the CI artifacts and fail with exit 5 unless
@@ -8902,13 +9537,32 @@ export async function runTestRerun(opts, deps = {}) {
8902
9537
  // safe) and aggregate accepted/deferred/conflicts/closure into a single
8903
9538
  // synthetic BatchRerunResponse that downstream --wait / exit-code logic
8904
9539
  // can treat as one result.
9540
+ if (opts.all && !deps.environmentTunnel) {
9541
+ return runTestRerun({
9542
+ ...opts,
9543
+ testIds,
9544
+ idempotencyKey,
9545
+ all: false,
9546
+ batchResolved: true,
9547
+ knownTests,
9548
+ nameFilter: undefined,
9549
+ statusFilter: undefined,
9550
+ skipTerminal: undefined,
9551
+ allowEmpty: undefined,
9552
+ }, deps);
9553
+ }
8905
9554
  const chunks = [];
8906
9555
  for (let i = 0; i < testIds.length; i += MAX_BATCH_RERUN_IDS) {
8907
9556
  chunks.push(testIds.slice(i, i + MAX_BATCH_RERUN_IDS));
8908
9557
  }
8909
9558
  if (chunks.length === 0)
8910
9559
  chunks.push([]); // defensive: empty list handled above
8911
- let chunkResponses;
9560
+ if (deps.environmentTunnel?.targets) {
9561
+ const grouped = chunks.flatMap(chunk => groupEnvironmentTargets(chunk, deps.environmentTunnel.targets, deps.environmentTunnel.maxConcurrency));
9562
+ chunks.splice(0, chunks.length, ...grouped);
9563
+ }
9564
+ let chunkResponses = [];
9565
+ let waitingForCapacity = false;
8912
9566
  try {
8913
9567
  // Dispatch chunks one at a time, NOT via Promise.all. BE producer/
8914
9568
  // teardown closure dedup happens per-request, server-side. Two chunks
@@ -8928,9 +9582,20 @@ export async function runTestRerun(opts, deps = {}) {
8928
9582
  ? idempotencyKey.slice(0, 256 - chunkSuffix.length)
8929
9583
  : idempotencyKey;
8930
9584
  const chunkKey = `${chunkBase}${chunkSuffix}`;
9585
+ if (deps.environmentTunnel?.targets?.has(chunk[0])) {
9586
+ waitingForCapacity = true;
9587
+ await deps.environmentTunnel.waitForCapacity(chunk.length);
9588
+ waitingForCapacity = false;
9589
+ }
8931
9590
  const chunkResp = await client.triggerBatchRerun({
8932
9591
  source: 'cli',
8933
9592
  testIds: chunk,
9593
+ ...(deps.environmentTunnel?.targets?.has(chunk[0])
9594
+ ? {
9595
+ tunnelClientId: deps.environmentTunnel.clientId,
9596
+ targetUrl: deps.environmentTunnel.targets.get(chunk[0]).targetUrl,
9597
+ }
9598
+ : {}),
8934
9599
  // Always send the effective boolean, including an explicit `false`
8935
9600
  // opt-out — see the matching comment on the single-rerun call site.
8936
9601
  autoHeal: effectiveAutoHeal,
@@ -8938,16 +9603,20 @@ export async function runTestRerun(opts, deps = {}) {
8938
9603
  ...(environment !== undefined ? { environment } : {}),
8939
9604
  }, { idempotencyKey: chunkKey });
8940
9605
  chunkResponses.push(chunkResp);
9606
+ if (deps.environmentTunnel?.targets?.has(chunk[0]))
9607
+ await deps.environmentTunnel.confirm(chunkResp, chunkResp.accepted.map(row => row.runId));
8941
9608
  }
8942
9609
  }
8943
9610
  catch (err) {
9611
+ if (deps.environmentTunnel && chunkResponses.length)
9612
+ await emitEnvironmentDispatchPartial(chunkResponses, testIds, opts, deps, 'rerun', err, deps.environmentTunnel);
8944
9613
  // D2 (dogfood): the batch endpoint rejects the WHOLE request when any id is
8945
9614
  // unresolvable (unknown, cross-tenant, or never ran cleanly), so one bad id
8946
9615
  // aborts the batch with NOT_FOUND. Replace the bare exit-4 with an
8947
9616
  // actionable hint. (Server-side partial-accept of unknown ids — a
8948
9617
  // `notFound[]` in the batch response so good ids still run — is a tracked
8949
9618
  // backend follow-up.)
8950
- if (err instanceof ApiError && err.code === 'NOT_FOUND') {
9619
+ if (!waitingForCapacity && err instanceof ApiError && err.code === 'NOT_FOUND') {
8951
9620
  throw ApiError.fromEnvelope({
8952
9621
  error: {
8953
9622
  code: 'NOT_FOUND',
@@ -8969,6 +9638,7 @@ export async function runTestRerun(opts, deps = {}) {
8969
9638
  const { deduped: dedupedAccepted, dropped: duplicateAccepted } = dedupeBatchRerunAccepted(chunkResponses.flatMap(r => r.accepted));
8970
9639
  warnDroppedDuplicateRuns(dedupedAccepted, duplicateAccepted, stderrFn);
8971
9640
  const batchResp = {
9641
+ ...(deps.environmentTunnel?.skipped?.length ? { skipped: deps.environmentTunnel.skipped } : {}),
8972
9642
  accepted: dedupedAccepted,
8973
9643
  deferred: chunkResponses.flatMap(r => r.deferred),
8974
9644
  conflicts: chunkResponses.flatMap(r => r.conflicts),
@@ -9031,6 +9701,22 @@ export async function runTestRerun(opts, deps = {}) {
9031
9701
  const deferredIds = deferred.map(d => d.testId).join(' ');
9032
9702
  stderrFn(`nextAction: testsprite test rerun ${deferredIds}`);
9033
9703
  }
9704
+ const emitRetryPartial = async (error, responses = []) => {
9705
+ if (!deps.environmentTunnel)
9706
+ return;
9707
+ const retried = new Set(responses
9708
+ .flatMap(response => [...response.accepted, ...response.conflicts, ...response.deferred])
9709
+ .map(row => row.testId));
9710
+ await emitEnvironmentDispatchPartial([
9711
+ {
9712
+ accepted,
9713
+ conflicts,
9714
+ deferred: deferred.filter(row => !retried.has(row.testId)),
9715
+ notFound,
9716
+ },
9717
+ ...responses,
9718
+ ], testIds, opts, deps, 'rerun', error, deps.environmentTunnel);
9719
+ };
9034
9720
  // D3: budget-driven deferred-retry loop for rerun --all (only under --wait).
9035
9721
  // Re-dispatches still-deferred tests until they all clear OR the --timeout
9036
9722
  // budget is exhausted — a busy pool drains within the user's own timeout
@@ -9040,7 +9726,7 @@ export async function runTestRerun(opts, deps = {}) {
9040
9726
  // through to the existing exit-7 path. `maxDeferredAttempts` is a pure runaway
9041
9727
  // backstop (the deadline check below is the real stop), scaled to the timeout.
9042
9728
  const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
9043
- const batchDeadlineMs = Date.now() + opts.timeoutSeconds * 1000;
9729
+ const batchDeadlineMs = deps.environmentTunnel?.deadlineMs ?? Date.now() + opts.timeoutSeconds * 1000;
9044
9730
  // finding 1: reserve a poll window so the deferred-retry loop can't consume the
9045
9731
  // ENTIRE --timeout and leave the fan-out poll with nothing — which would report
9046
9732
  // already-finished runs as timeouts (exit 7) instead of their real verdicts
@@ -9059,7 +9745,16 @@ export async function runTestRerun(opts, deps = {}) {
9059
9745
  // POLL_RESERVE_MS, so the difference is always positive).
9060
9746
  const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs - POLL_RESERVE_MS);
9061
9747
  stderrFn(`[deferred-retry] attempt ${attempt} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
9062
- await sleepFn(sleepMs);
9748
+ try {
9749
+ if (deps.environmentTunnel)
9750
+ await sleepUntilOrInterrupt(sleepMs, shutdownOf(deps).signal, sleepFn);
9751
+ else
9752
+ await sleepFn(sleepMs);
9753
+ }
9754
+ catch (err) {
9755
+ await emitRetryPartial(err);
9756
+ throw err;
9757
+ }
9063
9758
  const remainingAfterSleep = batchDeadlineMs - Date.now();
9064
9759
  if (remainingAfterSleep <= POLL_RESERVE_MS) {
9065
9760
  stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
@@ -9071,12 +9766,15 @@ export async function runTestRerun(opts, deps = {}) {
9071
9766
  for (let i = 0; i < retryIds.length; i += MAX_BATCH_RERUN_IDS) {
9072
9767
  retryChunks.push(retryIds.slice(i, i + MAX_BATCH_RERUN_IDS));
9073
9768
  }
9074
- let retryChunkResponses;
9769
+ if (deps.environmentTunnel?.targets) {
9770
+ const grouped = retryChunks.flatMap(chunk => groupEnvironmentTargets(chunk, deps.environmentTunnel.targets, deps.environmentTunnel.maxConcurrency));
9771
+ retryChunks.splice(0, retryChunks.length, ...grouped);
9772
+ }
9773
+ const retryChunkResponses = [];
9075
9774
  try {
9076
9775
  // Sequential, same reason as the initial dispatch above: concurrent
9077
9776
  // chunks racing on per-request server-side closure dedup can
9078
9777
  // double-trigger a shared BE producer/teardown.
9079
- retryChunkResponses = [];
9080
9778
  for (let idx = 0; idx < retryChunks.length; idx++) {
9081
9779
  const chunk = retryChunks[idx];
9082
9780
  // [P2] Bound the derived key to ≤256 chars. Caller-supplied keys may
@@ -9097,9 +9795,18 @@ export async function runTestRerun(opts, deps = {}) {
9097
9795
  // still-deferred, inviting a duplicate rerun on the user's next
9098
9796
  // invocation. The per-request timeout still bounds it; the sleeps +
9099
9797
  // poll stay deadline-aware.
9798
+ if (deps.environmentTunnel?.targets?.has(chunk[0]))
9799
+ await deps.environmentTunnel.waitForCapacity(chunk.length);
9100
9800
  const retryChunkResp = await client.triggerBatchRerun({
9101
9801
  source: 'cli',
9102
9802
  testIds: chunk,
9803
+ ...(environment !== undefined ? { environment } : {}),
9804
+ ...(deps.environmentTunnel?.targets?.has(chunk[0])
9805
+ ? {
9806
+ tunnelClientId: deps.environmentTunnel.clientId,
9807
+ targetUrl: deps.environmentTunnel.targets.get(chunk[0]).targetUrl,
9808
+ }
9809
+ : {}),
9103
9810
  // Always send the effective boolean, including an explicit
9104
9811
  // `false` opt-out — see the matching comment on the initial
9105
9812
  // dispatch call site above.
@@ -9107,9 +9814,15 @@ export async function runTestRerun(opts, deps = {}) {
9107
9814
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
9108
9815
  }, { idempotencyKey: retryKey });
9109
9816
  retryChunkResponses.push(retryChunkResp);
9817
+ if (deps.environmentTunnel?.targets?.has(chunk[0]))
9818
+ await deps.environmentTunnel.confirm(retryChunkResp, retryChunkResp.accepted.map(row => row.runId));
9110
9819
  }
9111
9820
  }
9112
9821
  catch (err) {
9822
+ if (deps.environmentTunnel) {
9823
+ await emitRetryPartial(err, retryChunkResponses);
9824
+ throw err;
9825
+ }
9113
9826
  if (err instanceof InterruptError)
9114
9827
  throw err;
9115
9828
  stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
@@ -9285,6 +9998,7 @@ export async function runTestRerun(opts, deps = {}) {
9285
9998
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
9286
9999
  const concurrencyLimit = opts.maxConcurrency;
9287
10000
  const rerunResults = [];
10001
+ const reportTiming = new Map();
9288
10002
  // sleepFn is declared above in the D3 deferred-retry section (shared by fan-out).
9289
10003
  async function pollAccepted(entry) {
9290
10004
  const resolveAlternate = makeBackendWaitFallback({
@@ -9305,9 +10019,17 @@ export async function runTestRerun(opts, deps = {}) {
9305
10019
  sleep: deps.sleep,
9306
10020
  shutdown: shutdownOf(deps),
9307
10021
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
9308
- onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`)),
10022
+ onTick: (run, elapsedMs) => {
10023
+ deps.environmentTunnel?.onPoll(run);
10024
+ ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`));
10025
+ },
9309
10026
  resolveAlternate,
9310
10027
  });
10028
+ reportTiming.set(entry.runId, {
10029
+ createdAt: finalRun.createdAt,
10030
+ startedAt: finalRun.startedAt,
10031
+ finishedAt: finalRun.finishedAt,
10032
+ });
9311
10033
  return {
9312
10034
  testId: entry.testId,
9313
10035
  testTitle: finalRun.testTitle ?? null,
@@ -9323,6 +10045,8 @@ export async function runTestRerun(opts, deps = {}) {
9323
10045
  };
9324
10046
  }
9325
10047
  catch (err) {
10048
+ if (deps.environmentTunnel && err instanceof TunnelLostError)
10049
+ throw err;
9326
10050
  if (err instanceof TimeoutError) {
9327
10051
  deps.onWaitTimeout?.({ reason: 'wait_timeout' });
9328
10052
  return {
@@ -9400,7 +10124,13 @@ export async function runTestRerun(opts, deps = {}) {
9400
10124
  // Graceful detach: stdout stays parseable — settled members
9401
10125
  // keep their real status, unfinished ones are marked running — and the
9402
10126
  // honest stderr line names every runId still executing (and billing).
9403
- if (fanOutErr instanceof InterruptError) {
10127
+ if (deps.environmentTunnel) {
10128
+ ticker.finalize();
10129
+ await emitEnvironmentDispatchPartial([{ accepted, deferred, conflicts, notFound }], testIds, opts, deps, 'rerun', fanOutErr, deps.environmentTunnel);
10130
+ if (fanOutErr instanceof InterruptError)
10131
+ fanOutErr.runWaitContext = true;
10132
+ }
10133
+ else if (fanOutErr instanceof InterruptError) {
9404
10134
  ticker.finalize(`Batch rerun — interrupted (${fanOutErr.signal})`);
9405
10135
  const settled = new Map(rerunResults.map(r => [r.runId, r]));
9406
10136
  const partialResults = accepted.map((e) => settled.get(e.runId) ?? { testId: e.testId, runId: e.runId, status: 'running' });
@@ -9408,7 +10138,9 @@ export async function runTestRerun(opts, deps = {}) {
9408
10138
  const unfinished = accepted.filter(e => !settled.has(e.runId)).map(e => e.runId);
9409
10139
  if (unfinished.length > 0) {
9410
10140
  fanOutErr.runWaitContext = true;
9411
- stderrFn(interruptDetachMessage(fanOutErr, unfinished));
10141
+ stderrFn(deps.environmentTunnel
10142
+ ? `Interrupted (${fanOutErr.signal}). Cancellation will be requested for unfinished tunnel runs before the owned tunnel closes.`
10143
+ : interruptDetachMessage(fanOutErr, unfinished));
9412
10144
  }
9413
10145
  }
9414
10146
  throw fanOutErr;
@@ -9419,6 +10151,7 @@ export async function runTestRerun(opts, deps = {}) {
9419
10151
  const timedOut = rerunResults.filter(r => r.status === 'timeout').length;
9420
10152
  stderrFn(`Batch rerun complete: ${passed}/${accepted.length} passed, ${failed} failed/blocked, ${timedOut} timed out`);
9421
10153
  const jsonPayload = {
10154
+ ...(deps.environmentTunnel?.skipped?.length ? { skipped: deps.environmentTunnel.skipped } : {}),
9422
10155
  accepted: rerunResults,
9423
10156
  // [P2] Use post-retry mutable vars, not the stale initial batchResp fields.
9424
10157
  // batchResp.deferred/conflicts reflect only the INITIAL response; after D3
@@ -9453,7 +10186,7 @@ export async function runTestRerun(opts, deps = {}) {
9453
10186
  const rerunNameMap = opts.report === 'junit' && opts.reportFile !== undefined
9454
10187
  ? await buildTestNameMap(client, opts.projectId)
9455
10188
  : undefined;
9456
- await writeBatchJUnitReportIfRequested(opts, rerunResults, rerunNameMap);
10189
+ await writeBatchJUnitReportIfRequested(opts, rerunResults.map(r => ({ ...r, ...(r.runId ? reportTiming.get(r.runId) : {}) })), rerunNameMap);
9457
10190
  out.print(jsonPayload);
9458
10191
  // CI-native output layer (issue #99): batch-rerun parity with `run --all`.
9459
10192
  // Emitted before the exit-code gates below so the summary file / annotations
@@ -9705,7 +10438,7 @@ const SKIP_PREFLIGHT_HELP = 'skip the pre-charge reachability probe for a target
9705
10438
  'from the Lambda that executes the test, so it can occasionally be wrong (e.g. an IP allowlist ' +
9706
10439
  'that permits the Lambda but not this machine); use this flag when you know better. Zero network ' +
9707
10440
  '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";
10441
+ 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
10442
  export function createTestCommand(deps = {}) {
9710
10443
  const test = new Command('test').description('Inspect TestSprite tests');
9711
10444
  test
@@ -9718,6 +10451,7 @@ export function createTestCommand(deps = {}) {
9718
10451
  // below raises `ApiError(VALIDATION_ERROR)` so JSON consumers can read
9719
10452
  // `error.code` and the exit code matches the catalog.
9720
10453
  .option('--project <id>', 'project id (returned by `testsprite project list`)')
10454
+ .option('--env <name>', 'show frontend test statuses for the named project environment')
9721
10455
  .option('--type <type>', 'filter by test type (frontend|backend)')
9722
10456
  .option('--created-from <source>', 'filter by where the test was authored (portal|mcp|cli)')
9723
10457
  .option('--status <list>', 'filter by normalized status (comma-separated). One of: draft, ready, queued, running, passed, failed, blocked, cancelled, unknown')
@@ -9740,6 +10474,7 @@ export function createTestCommand(deps = {}) {
9740
10474
  await runList({
9741
10475
  ...resolveCommonOptions(command, deps.env),
9742
10476
  projectId: cmdOpts.project,
10477
+ environment: cmdOpts.env,
9743
10478
  type: parseEnumFlag(cmdOpts.type, 'type', TEST_TYPES),
9744
10479
  createdFrom: parseEnumFlag(cmdOpts.createdFrom, 'created-from', CREATED_FROMS),
9745
10480
  status: cmdOpts.status,
@@ -9773,9 +10508,10 @@ export function createTestCommand(deps = {}) {
9773
10508
  'ignores every other flag). Pipe to a file and edit: `--plan-template > plan.json`.', false)
9774
10509
  .option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
9775
10510
  .option('--wait', 'with --run, poll until terminal status', false)
10511
+ .option('--no-wait', 'detach without opening an automatic environment tunnel')
9776
10512
  .option('--timeout <s>', 'with --run --wait, max seconds to wait')
9777
10513
  .option('--target-url <url>', TARGET_URL_HELP)
9778
- .option('--env <name>', 'with --run, run against the named project environment')
10514
+ .option('--env <name>', 'with --run, select the named project environment; loopback URLs open a tunnel automatically')
9779
10515
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
9780
10516
  .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
10517
  .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 +10578,7 @@ export function createTestCommand(deps = {}) {
9842
10578
  planFrom: cmdOpts.planFrom,
9843
10579
  run: cmdOpts.run === true,
9844
10580
  wait: cmdOpts.wait === true,
10581
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
9845
10582
  timeout: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
9846
10583
  // B2(c): capture before parseTimeoutFlag converts undefined → default.
9847
10584
  timeoutIsDefault: cmdOpts.timeout === undefined,
@@ -9866,6 +10603,7 @@ export function createTestCommand(deps = {}) {
9866
10603
  // M3.3 chain flags:
9867
10604
  run: cmdOpts.run === true,
9868
10605
  wait: cmdOpts.wait === true,
10606
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
9869
10607
  timeout: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
9870
10608
  // B2(c): capture before parseTimeoutFlag converts undefined → default.
9871
10609
  timeoutIsDefault: cmdOpts.timeout === undefined,
@@ -9889,9 +10627,10 @@ export function createTestCommand(deps = {}) {
9889
10627
  .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
10628
  `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
10629
  .option('--wait', 'with --run, poll each run until terminal status', false)
10630
+ .option('--no-wait', 'detach without opening an automatic environment tunnel')
9892
10631
  .option('--timeout <s>', 'with --run --wait, per-run max seconds to wait (1-3600, default 600)')
9893
10632
  .option('--target-url <url>', TARGET_URL_HELP)
9894
- .option('--env <name>', 'with --run, run each created test against the named project environment')
10633
+ .option('--env <name>', 'with --run, select the named project environment for each test; loopback URLs open a tunnel automatically')
9895
10634
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
9896
10635
  .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
10636
  .addHelpText('after', GLOBAL_OPTS_HINT)
@@ -9903,6 +10642,7 @@ export function createTestCommand(deps = {}) {
9903
10642
  run: cmdOpts.run === true,
9904
10643
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency'),
9905
10644
  wait: cmdOpts.wait === true,
10645
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
9906
10646
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
9907
10647
  targetUrl: cmdOpts.targetUrl,
9908
10648
  environment: cmdOpts.env,
@@ -10113,8 +10853,8 @@ export function createTestCommand(deps = {}) {
10113
10853
  // -------------------------------------------------------------------------
10114
10854
  test
10115
10855
  .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' +
10856
+ .description('Trigger one or several test runs. Saved loopback environments open a tunnel automatically and wait for a verdict.\n' +
10857
+ 'Use --all --project <id> for a wave-ordered batch run. Loopback environments share one tunnel.\n' +
10118
10858
  '\nExit codes:\n' +
10119
10859
  ' 0 passed (or queued without --wait)\n' +
10120
10860
  ' 1 failed / blocked / cancelled\n' +
@@ -10128,38 +10868,40 @@ export function createTestCommand(deps = {}) {
10128
10868
  ' 11 rate limited — honor Retry-After, or the in-flight run cap was hit\n' +
10129
10869
  ' (details.reason "inflight_cap"; see: testsprite test run --help)\n' +
10130
10870
  '\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>')
10871
+ '\nCtrl-C during an ordinary --wait detaches; an owned tunnel cancels unfinished runs by default.\n' +
10872
+ 'Stop a detached run with: testsprite test cancel <run-id>\n' +
10873
+ 'Local environments: dev servers can take a minute per page through the tunnel.\n' +
10874
+ 'For a heavy dev server, test a built server: npm run build, then your framework preview/start command.')
10133
10875
  .option('--target-url <url>', TARGET_URL_HELP)
10134
10876
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
10135
10877
  .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 ' +
10878
+ 'navigates to http://localhost:<port> and its traffic is proxied back to you for as long ' +
10137
10879
  'as this command runs. Implies --wait (the tunnel closes when the command exits, so a ' +
10138
10880
  'detached run could not finish). Frontend tests ' +
10139
- 'only; several ids or --all share one tunnel (5 concurrent by default, at most 10). ' +
10881
+ 'only; a matching saved environment keeps its host spelling; several ids or --all share one tunnel (5 concurrent by default, at most 10). ' +
10140
10882
  '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 ` +
10883
+ .option('--local-host <host>', `with --local, override which loopback address to name in the run's target URL — one of ` +
10884
+ `${LOOPBACK_HOSTS.join(', ')} (default: saved matching host, else ${DEFAULT_LOCAL_HOST}). Use localhost if your app ` +
10143
10885
  `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 ' +
10886
+ .option('--tunnel-client <id>', 'for a loopback environment or --local, attach to a tunnel already running under `testsprite tunnel start` instead ' +
10145
10887
  'of opening a new one. The id is the non-secret handle that command prints; the tunnel ' +
10146
10888
  '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 ' +
10889
+ .option('--no-cancel-on-interrupt', 'with a tunnel, skip automatic cancellation when an owned tunnel is about to close or a ' +
10148
10890
  "borrowed tunnel's owner disappears. An ordinary interrupt of a borrowed run never " +
10149
10891
  'cancels it because its tunnel remains alive.')
10150
10892
  .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 ' +
10893
+ 'OTP settings (names: `testsprite project env list <project-id>`). A loopback environment opens a tunnel automatically. The run opens ' +
10153
10894
  "that environment's URL. Omit --env to keep using " +
10154
10895
  "the project's default environment. Also applies with --all.")
10155
10896
  .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)')
10897
+ .option('--no-wait', 'detach without opening an automatic environment tunnel')
10898
+ .option('--timeout <s>', 'with --wait, max seconds per run (1–3600; default 600, or 1200 through a tunnel)')
10157
10899
  .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
10900
  .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
10901
  .option('--project <id>', 'project id (with --all, overrides TESTSPRITE_PROJECT_ID; returned by `testsprite project list`)')
10160
10902
  .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)')
10903
+ .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})`)
10904
+ .option('--report <format>', 'with a --wait batch (--all or several ids): write a JUnit XML sidecar report after polling (accepted: junit)')
10163
10905
  .option('--report-file <path>', 'output path for --report (atomic write)')
10164
10906
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
10165
10907
  .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 +10946,18 @@ export function createTestCommand(deps = {}) {
10204
10946
  ' has no effect on the cap. A smaller batch does.')
10205
10947
  .addHelpText('after', GLOBAL_OPTS_HINT)
10206
10948
  .action(async (testIdArgs, cmdOpts, command) => {
10949
+ // A literal `testsprite test run list` is someone guessing at a
10950
+ // "list prior runs" subcommand, not naming a test whose id is the
10951
+ // string "list". Left unguarded, this parses as a normal `<test-id>`
10952
+ // and dispatches a run against a test that (almost certainly) does not
10953
+ // exist, wasting a round trip on a typo that a clear message could
10954
+ // have caught locally. Checked first, before any other validation or
10955
+ // network access, so it wins even if other flags (`--all`, etc.) are
10956
+ // also present.
10957
+ if (testIdArgs.length === 1 && testIdArgs[0] === 'list') {
10958
+ throw localValidationError('test-id', 'there is no `test run list` command; to see a test’s prior runs use: ' +
10959
+ 'testsprite test result <test-id> --history');
10960
+ }
10207
10961
  const isAll = cmdOpts.all === true;
10208
10962
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
10209
10963
  // Mutual-exclusion: exactly one of positional <test-id> vs --all must be set.
@@ -10225,9 +10979,23 @@ export function createTestCommand(deps = {}) {
10225
10979
  // tunnel credential.
10226
10980
  const localPort = cmdOpts.local !== undefined ? parseLocalPort(cmdOpts.local) : undefined;
10227
10981
  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.');
10982
+ const effectiveWait = usingLocal ||
10983
+ (cmdOpts.targetUrl !== undefined &&
10984
+ parseLoopbackTargetUrl(cmdOpts.targetUrl) !== undefined) ||
10985
+ cmdOpts.wait === true;
10986
+ const canAutoWait = !resolveCommonOptions(command, deps.env).dryRun &&
10987
+ !(command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false);
10988
+ const explicitLoopbackTarget = cmdOpts.targetUrl !== undefined && parseLoopbackTargetUrl(cmdOpts.targetUrl) !== undefined;
10989
+ if (!usingLocal &&
10990
+ !explicitLoopbackTarget &&
10991
+ ((command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false) ||
10992
+ cmdOpts.targetUrl !== undefined)) {
10993
+ if (!isAll && testIdArgs.length >= 2)
10994
+ severalIdsWithoutTunnel();
10995
+ assertNoTunnelOptions({
10996
+ tunnelClientId: cmdOpts.tunnelClient,
10997
+ cancelOnInterrupt: cmdOpts.cancelOnInterrupt,
10998
+ });
10231
10999
  }
10232
11000
  const maxConcurrency = cmdOpts.maxConcurrency === undefined
10233
11001
  ? usingLocal
@@ -10252,43 +11020,36 @@ export function createTestCommand(deps = {}) {
10252
11020
  'machine through a tunnel, --target-url runs against an address the test runner can ' +
10253
11021
  'already reach. Pass one');
10254
11022
  }
10255
- // The three flags below are inert without --local. Silently ignoring
11023
+ // A host override is meaningful only for the port shorthand. Silently ignoring
10256
11024
  // them would leave the caller believing something is in effect that is
10257
11025
  // not — the same rule --filter and the JUnit flags already follow.
10258
11026
  if (!usingLocal && cmdOpts.localHost !== undefined) {
10259
11027
  throw localValidationError('local-host', '--local-host only applies with --local (it names the loopback address the tunnel run ' +
10260
11028
  'targets). Add --local <port>, or remove --local-host');
10261
11029
  }
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;
11030
+ const localHost = usingLocal && cmdOpts.localHost !== undefined
11031
+ ? normalizeLocalHost(cmdOpts.localHost)
11032
+ : undefined;
10272
11033
  const report = parseJUnitReportFormat(cmdOpts.report);
10273
11034
  assertJUnitReportOptions({
10274
11035
  report,
10275
11036
  reportFile: cmdOpts.reportFile,
10276
11037
  reportSuiteName: cmdOpts.reportSuiteName,
10277
- wait: effectiveWait,
10278
- batchPath: isAll || (usingLocal && testIds.length > 1),
11038
+ wait: effectiveWait || canAutoWait,
11039
+ batchPath: isAll || testIds.length > 1,
10279
11040
  });
10280
11041
  // --gh-output / --summary-file reduce a --wait run's terminal result into
10281
11042
  // the CI summary. They require --wait (without it the command returns after
10282
11043
  // enqueueing, before any terminal result exists) but apply to BOTH a single
10283
11044
  // <test-id> run and the --all batch. Without --wait they would silently
10284
11045
  // no-op — reject loudly (same rule as --filter and the JUnit report flags).
10285
- if (cmdOpts.ghOutput === true && !effectiveWait) {
11046
+ if (cmdOpts.ghOutput === true && !effectiveWait && !canAutoWait) {
10286
11047
  throw localValidationError('gh-output', '--gh-output requires --wait (it reduces the terminal run result). Add --wait.');
10287
11048
  }
10288
- if (cmdOpts.summaryFile !== undefined && !effectiveWait) {
11049
+ if (cmdOpts.summaryFile !== undefined && !effectiveWait && !canAutoWait) {
10289
11050
  throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
10290
11051
  }
10291
- if (isAll && !usingLocal) {
11052
+ if (isAll && !usingLocal && cmdOpts.tunnelClient === undefined) {
10292
11053
  // --all path: wave-ordered fresh batch run.
10293
11054
  const projectId = resolveProjectId(cmdOpts.project, deps);
10294
11055
  requireProjectId(projectId, '--all requires a project id - pass --project <id> or set TESTSPRITE_PROJECT_ID');
@@ -10306,6 +11067,10 @@ export function createTestCommand(deps = {}) {
10306
11067
  projectId,
10307
11068
  nameFilter: cmdOpts.filter,
10308
11069
  wait: effectiveWait,
11070
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
11071
+ concurrencyIsDefault: cmdOpts.maxConcurrency === undefined,
11072
+ timeoutIsDefault: cmdOpts.timeout === undefined,
11073
+ cancelOnInterrupt: cmdOpts.cancelOnInterrupt !== false,
10309
11074
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
10310
11075
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
10311
11076
  DEFAULT_BATCH_RUN_CONCURRENCY,
@@ -10350,15 +11115,19 @@ export function createTestCommand(deps = {}) {
10350
11115
  : '[advisory] --local implies --wait: the tunnel closes when this command exits, so ' +
10351
11116
  'the run is followed to a verdict rather than detached.');
10352
11117
  }
10353
- if (usingLocal && (isAll || testIds.length > 1)) {
11118
+ if (isAll || testIds.length > 1) {
10354
11119
  await runTestRunLocalBatch({
10355
11120
  ...commonOpts,
10356
11121
  testIds,
11122
+ wait: effectiveWait,
10357
11123
  all: isAll,
10358
11124
  projectId: cmdOpts.project,
10359
11125
  nameFilter: cmdOpts.filter,
10360
- localPort: localPort,
10361
- localHost: localHost ?? DEFAULT_LOCAL_HOST,
11126
+ localPort,
11127
+ localHost,
11128
+ targetUrl: cmdOpts.targetUrl,
11129
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
11130
+ concurrencyIsDefault: cmdOpts.maxConcurrency === undefined,
10362
11131
  skipPreflight: cmdOpts.skipPreflight === true,
10363
11132
  tunnelClientId: cmdOpts.tunnelClient,
10364
11133
  cancelOnInterrupt: cmdOpts.cancelOnInterrupt !== false,
@@ -10389,6 +11158,7 @@ export function createTestCommand(deps = {}) {
10389
11158
  ...(cmdOpts.tunnelClient !== undefined ? { tunnelClientId: cmdOpts.tunnelClient } : {}),
10390
11159
  cancelOnInterrupt: cmdOpts.cancelOnInterrupt !== false,
10391
11160
  wait: effectiveWait,
11161
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
10392
11162
  timeoutSeconds: usingLocal && cmdOpts.timeout === undefined
10393
11163
  ? DEFAULT_LOCAL_RUN_TIMEOUT_SECONDS
10394
11164
  : parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
@@ -10476,6 +11246,8 @@ export function createTestCommand(deps = {}) {
10476
11246
  .option('--status <list>', `with --all: only dispatch tests whose status matches one of these values (comma-separated; accepted: ${PUBLIC_STATUSES.join('|')})`)
10477
11247
  .option('--filter <substr>', 'with --all: only rerun tests whose name contains this substring (case-insensitive)')
10478
11248
  .option('--wait', 'block until terminal status or --timeout elapses', false)
11249
+ .option('--no-wait', 'detach without opening an automatic environment tunnel')
11250
+ .option('--skip-preflight', 'skip the loopback port probe before opening a tunnel')
10479
11251
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
10480
11252
  .option('--no-auto-heal', 'replay the saved script verbatim instead of letting the agent repair it (default: ' +
10481
11253
  'auto-heal is ON for FE reruns). When heal engages, the agent re-authors the test and ' +
@@ -10484,8 +11256,8 @@ export function createTestCommand(deps = {}) {
10484
11256
  .option('--skip-dependencies', 'BE only: rerun only the named test without expanding the producer/teardown closure', false)
10485
11257
  .option('--env <name>', 'replay against the named project environment — its test-account credentials, auto-auth and ' +
10486
11258
  '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})`)
11259
+ "project's default environment. Loopback URLs open a tunnel automatically. Applies to every test of a batch rerun.")
11260
+ .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
11261
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --verbose if auto-generated.')
10490
11262
  .option('--report <format>', 'with batch --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
10491
11263
  .option('--report-file <path>', 'output path for --report (atomic write)')
@@ -10518,20 +11290,23 @@ export function createTestCommand(deps = {}) {
10518
11290
  const testIds = testIdsArg ?? [];
10519
11291
  const isBatch = cmdOpts.all === true || testIds.length !== 1;
10520
11292
  const report = parseJUnitReportFormat(cmdOpts.report);
11293
+ const canAutoWait = !resolveCommonOptions(command, deps.env).dryRun &&
11294
+ !(command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false);
10521
11295
  assertJUnitReportOptions({
10522
11296
  report,
10523
11297
  reportFile: cmdOpts.reportFile,
10524
11298
  reportSuiteName: cmdOpts.reportSuiteName,
10525
- wait: cmdOpts.wait === true,
11299
+ wait: cmdOpts.wait === true || canAutoWait,
10526
11300
  batchPath: isBatch,
10527
11301
  });
10528
11302
  // --gh-output / --summary-file reduce the batch-rerun --wait envelope, which
10529
11303
  // only exists on the batch (--all or 2+ ids) --wait path. Anywhere else they
10530
11304
  // would silently no-op — reject loudly (same rule as the JUnit report flags).
10531
- if (cmdOpts.ghOutput === true && (!isBatch || cmdOpts.wait !== true)) {
11305
+ if (cmdOpts.ghOutput === true && (!isBatch || (cmdOpts.wait !== true && !canAutoWait))) {
10532
11306
  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
11307
  }
10534
- if (cmdOpts.summaryFile !== undefined && (!isBatch || cmdOpts.wait !== true)) {
11308
+ if (cmdOpts.summaryFile !== undefined &&
11309
+ (!isBatch || (cmdOpts.wait !== true && !canAutoWait))) {
10535
11310
  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
11311
  }
10537
11312
  await runTestRerun({
@@ -10543,6 +11318,9 @@ export function createTestCommand(deps = {}) {
10543
11318
  statusFilter: cmdOpts.status,
10544
11319
  nameFilter: cmdOpts.filter,
10545
11320
  wait: cmdOpts.wait === true,
11321
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
11322
+ skipPreflight: cmdOpts.skipPreflight === true,
11323
+ concurrencyIsDefault: cmdOpts.maxConcurrency === undefined,
10546
11324
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
10547
11325
  autoHeal: cmdOpts.autoHeal !== false,
10548
11326
  autoHealExplicit: false,
@@ -11242,13 +12020,29 @@ const TEST_LIST_COLUMNS = [
11242
12020
  { header: 'TYPE', width: 8, render: test => test.type },
11243
12021
  { header: 'FROM', width: 6, render: test => test.createdFrom },
11244
12022
  { header: 'STATUS', width: 9, render: test => test.status },
11245
- { header: 'UPDATED', width: 0, render: test => test.updatedAt },
12023
+ {
12024
+ header: 'UPDATED',
12025
+ width: rows => Math.max(7, ...rows.map(test => test.updatedAt.length)),
12026
+ render: test => test.updatedAt,
12027
+ },
12028
+ {
12029
+ header: 'ENV',
12030
+ width: rows => Math.max(3, ...rows.map(test => (test.headlineEnvironment?.name ?? '-').length)),
12031
+ render: test => test.headlineEnvironment?.name ?? '-',
12032
+ },
11246
12033
  ];
11247
12034
  function renderTestListText(page, options = {}) {
12035
+ const note = options.environment === undefined || options.noHeader
12036
+ ? []
12037
+ : [`Frontend test status requested for environment '${options.environment}'.`];
11248
12038
  if (page.items.length === 0) {
11249
- return page.nextToken ? `No tests on this page.\nnextToken: ${page.nextToken}` : 'No tests.';
12039
+ return [
12040
+ ...note,
12041
+ page.nextToken ? `No tests on this page.\nnextToken: ${page.nextToken}` : 'No tests.',
12042
+ ].join('\n');
11250
12043
  }
11251
12044
  const lines = [
12045
+ ...note,
11252
12046
  renderTextTable(page.items, TEST_LIST_COLUMNS, {
11253
12047
  columns: options.columns,
11254
12048
  noHeader: options.noHeader,
@@ -11275,6 +12069,9 @@ function renderTestText(t) {
11275
12069
  `createdFrom: ${t.createdFrom}`,
11276
12070
  `status: ${t.status}`,
11277
12071
  ];
12072
+ if (t.headlineEnvironment?.name != null) {
12073
+ lines.push(`environment: ${t.headlineEnvironment.name}`);
12074
+ }
11278
12075
  // G1a: surface priority when the backend ships it and it is non-null.
11279
12076
  if (t.priority) {
11280
12077
  lines.push(`priority: ${t.priority}`);
@@ -11981,20 +12778,208 @@ function renderPlanGenerateFailedText(plans, projectId) {
11981
12778
  lines.push(` completed stages stay done — retry with: testsprite test plan generate --project ${projectId}`);
11982
12779
  return lines.join('\n');
11983
12780
  }
11984
- function makePlanGeneratePartial(projectId, lastSeen) {
12781
+ /** Status → the stage it belongs to (idle/failed map to none). */
12782
+ function planStageOfStatus(status) {
12783
+ switch (status) {
12784
+ case 'exploring':
12785
+ return 'exploration';
12786
+ case 'strategizing':
12787
+ return 'strategy';
12788
+ case 'proposing':
12789
+ return 'proposals';
12790
+ default:
12791
+ return null;
12792
+ }
12793
+ }
12794
+ /**
12795
+ * Follows the ladder from the command layer so the user sees WHERE they are:
12796
+ * one `stage i/N <name> done <elapsed>` line per finished stage, and on an
12797
+ * interruption a "paused during/after stage i/N" line that names what is
12798
+ * left. The ladder itself only starts the next stage while this process is
12799
+ * alive (verified live 2026-08-27), which is exactly why the copy says
12800
+ * "re-run to continue" rather than "work continues".
12801
+ */
12802
+ class PlanStageTracker {
12803
+ emit;
12804
+ /** Every stage this run will perform, in order; known from the first
12805
+ * accepted trigger, unknown (null) when the run only ever attached. */
12806
+ planned = null;
12807
+ /** The stage this run believes is up next or running. */
12808
+ current = null;
12809
+ /** True once a poll has reported `current` as ACTIVE. `idle` is ambiguous
12810
+ * (not started yet vs. finished), so a stage is only ever marked done on
12811
+ * evidence: it was seen running and then stopped, a later stage was seen
12812
+ * running or accepted, or the run settled with proposals staged. */
12813
+ currentActive = false;
12814
+ currentSinceMs = 0;
12815
+ lastElapsedMs = 0;
12816
+ done = [];
12817
+ constructor(emit) {
12818
+ this.emit = emit;
12819
+ }
12820
+ /** An accepted trigger is ground truth: the stage it started is up now,
12821
+ * and every planned stage before it is finished (even if no poll saw it). */
12822
+ onTrigger(response) {
12823
+ if (response.status !== 'accepted' || response.stage === null)
12824
+ return;
12825
+ if (this.planned === null)
12826
+ this.planned = [response.stage, ...response.stagesRemaining];
12827
+ for (const s of this.planned) {
12828
+ if (s === response.stage)
12829
+ break;
12830
+ this.markDone(s);
12831
+ }
12832
+ if (this.current !== response.stage) {
12833
+ this.current = response.stage;
12834
+ this.currentActive = false;
12835
+ this.currentSinceMs = this.lastElapsedMs;
12836
+ }
12837
+ }
12838
+ onTick(plans, elapsedMs) {
12839
+ this.lastElapsedMs = elapsedMs;
12840
+ // A failed read is not a transition: nothing finished.
12841
+ if (plans.generation.status === 'failed')
12842
+ return;
12843
+ const stage = planStageOfStatus(plans.generation.status);
12844
+ if (stage === this.current) {
12845
+ if (stage !== null && !this.currentActive) {
12846
+ this.currentActive = true;
12847
+ this.currentSinceMs = elapsedMs;
12848
+ }
12849
+ return;
12850
+ }
12851
+ if (this.current !== null) {
12852
+ if (stage === null && this.current === 'proposals') {
12853
+ // The last stage has no "next stage" to prove it finished, and the
12854
+ // server can report idle before the staged batch is visible (the
12855
+ // ladder's billing guard #1 keeps polling through that blip). Only
12856
+ // the settled read with proposals staged marks it done — settle().
12857
+ return;
12858
+ }
12859
+ if (this.currentActive) {
12860
+ this.markDone(this.current, elapsedMs);
12861
+ }
12862
+ else if (stage === null) {
12863
+ // idle before the stage was ever seen running: it has not started
12864
+ // (the ladder's own dwell window). Keep waiting on the same stage.
12865
+ return;
12866
+ }
12867
+ else {
12868
+ // A later stage seen running is as strong as an accepted trigger.
12869
+ this.markDone(this.current);
12870
+ }
12871
+ }
12872
+ this.current = stage;
12873
+ this.currentActive = stage !== null;
12874
+ this.currentSinceMs = elapsedMs;
12875
+ }
12876
+ /** The ladder settled with proposals staged: whatever was up is done. */
12877
+ settle(plans) {
12878
+ if (plans.proposals.length === 0)
12879
+ return;
12880
+ if (this.current !== null) {
12881
+ this.markDone(this.current, this.currentActive ? this.lastElapsedMs : undefined);
12882
+ }
12883
+ else if (this.planned !== null) {
12884
+ for (const s of this.planned)
12885
+ this.markDone(s);
12886
+ }
12887
+ this.current = null;
12888
+ this.currentActive = false;
12889
+ }
12890
+ markDone(stage, nowMs) {
12891
+ if (this.done.includes(stage))
12892
+ return;
12893
+ this.done.push(stage);
12894
+ const took = nowMs === undefined || stage !== this.current || !this.currentActive
12895
+ ? ''
12896
+ : ` ${formatPlanElapsed(nowMs - this.currentSinceMs)}`;
12897
+ this.emit(`stage ${this.label(stage)} done${took}`);
12898
+ }
12899
+ /** `i/N name` when the plan is known, else just the name. */
12900
+ label(stage) {
12901
+ if (this.planned === null)
12902
+ return stage;
12903
+ const i = this.planned.indexOf(stage);
12904
+ return i === -1 ? stage : `${i + 1}/${this.planned.length} ${stage}`;
12905
+ }
12906
+ /** Stages this run has not started. An accepted stage counts as started
12907
+ * whether or not a poll has reported it running yet: the server has
12908
+ * committed to it (and, for exploration and proposals, charged for it). */
12909
+ remaining() {
12910
+ if (this.planned === null)
12911
+ return null;
12912
+ return this.planned.filter(s => !this.done.includes(s) && s !== this.current);
12913
+ }
12914
+ /** "during stage 2/3 strategy" / "after stage 1/3 exploration" / "". Whether a
12915
+ * poll has already reported the stage running is not the user's concern:
12916
+ * once accepted it runs to completion either way. */
12917
+ position() {
12918
+ if (this.current !== null)
12919
+ return `during stage ${this.label(this.current)}`;
12920
+ const last = this.done[this.done.length - 1];
12921
+ return last === undefined ? '' : `after stage ${this.label(last)}`;
12922
+ }
12923
+ /** The stuck-fuse line. `tries` is every start request this run sent
12924
+ * (accepted or "already in progress" alike — the split is internal, and
12925
+ * an accepted stage counts as started, so "would not start" would
12926
+ * contradict `position()`/`remaining()`). Deliberately no `Continue:` —
12927
+ * an immediate re-run repeats the same tries. */
12928
+ stalledLine(tries) {
12929
+ const where = this.current === null ? 'Generation' : `Stage ${this.label(this.current)}`;
12930
+ return (`${where} is not making progress after ${tries} ${tries === 1 ? 'try' : 'tries'}. ` +
12931
+ 'Wait a few minutes, then run the same command again; it picks up from here.');
12932
+ }
12933
+ /** "N stages left." / "Nothing left to start." / "" (plan unknown). */
12934
+ leftText() {
12935
+ const rem = this.remaining();
12936
+ if (rem === null)
12937
+ return '';
12938
+ if (rem.length === 0)
12939
+ return ' Nothing left to start.';
12940
+ return ` ${rem.length} stage${rem.length === 1 ? '' : 's'} left.`;
12941
+ }
12942
+ /** One-line stderr summary for every way the wait can stop early. */
12943
+ pausedLine(projectId, lead, verb = 'Paused') {
12944
+ const pos = this.position();
12945
+ return (`${lead} ${verb}${pos === '' ? '' : ` ${pos}`}.${this.leftText()}\n` +
12946
+ ` Continue: testsprite test plan generate --project ${projectId}`);
12947
+ }
12948
+ /** The same story as `pausedLine`, as the single-line JSON `nextAction`. */
12949
+ detachNextAction(projectId) {
12950
+ const pos = this.position();
12951
+ return (`Plan generation paused${pos === '' ? '' : ` ${pos}`}.${this.leftText()} ` +
12952
+ `Continue: testsprite test plan generate --project ${projectId}`);
12953
+ }
12954
+ }
12955
+ function attachPlanInterruptDetach(err, detach) {
12956
+ err.planDetach = detach;
12957
+ }
12958
+ function makePlanGeneratePartial(projectId, lastSeen, stagesRemaining = null) {
11985
12959
  return {
11986
12960
  projectId,
11987
12961
  status: 'running',
11988
12962
  generationStatus: lastSeen?.generation.status ?? null,
11989
12963
  proposalsStaged: lastSeen?.proposals.length ?? 0,
12964
+ stagesRemaining,
11990
12965
  };
11991
12966
  }
11992
- function renderPlanGeneratePartialText(partial, reason) {
11993
- const lines = [`projectId ${partial.projectId}`, `status running (${reason})`];
11994
- if (partial.generationStatus !== null) {
12967
+ function renderPlanGeneratePartialText(partial, reason, position = '', verb = 'paused', withContinue = true) {
12968
+ const lines = [
12969
+ `projectId ${partial.projectId}`,
12970
+ `status ${verb} (${reason})${position === '' ? '' : ` ${position}`}`,
12971
+ ];
12972
+ if (position === '' && partial.generationStatus !== null) {
12973
+ // Interrupted before any trigger answered: the only position we have is
12974
+ // the status of the last read, so keep showing it (JSON has it anyway).
11995
12975
  lines.push(`stage ${partial.generationStatus}`);
11996
12976
  }
11997
- lines.push(`hint Re-attach with: testsprite test plan generate --project ${partial.projectId}`);
12977
+ if (partial.stagesRemaining !== null) {
12978
+ lines.push(`remaining ${partial.stagesRemaining.length === 0 ? 'none' : partial.stagesRemaining.join(', ')}`);
12979
+ }
12980
+ if (withContinue) {
12981
+ lines.push(`continue testsprite test plan generate --project ${partial.projectId}`);
12982
+ }
11998
12983
  return lines.join('\n');
11999
12984
  }
12000
12985
  /**
@@ -12004,8 +12989,9 @@ function renderPlanGeneratePartialText(partial, reason) {
12004
12989
  * proposals) through `runGenerationLadder` and renders the staged
12005
12990
  * proposals. Exit 0 on staged proposals, 1 on a server-side stage failure,
12006
12991
  * 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
12992
+ * not a CLI error), 130/143 on Ctrl-C (the running stage finishes server-side;
12993
+ * nothing after it starts until a re-run, see PlanStageTracker), plus the
12994
+ * usual catalog exits for trigger errors
12009
12995
  * (412 → 6 with the exact fix command, 402 → 12, 404 → 4, 429 → 11).
12010
12996
  */
12011
12997
  export async function runPlanGenerate(opts, deps = {}) {
@@ -12050,6 +13036,8 @@ export async function runPlanGenerate(opts, deps = {}) {
12050
13036
  // migration bridge). Closing it needs the id on one of those wires.
12051
13037
  let resolvedProjectId = projectId;
12052
13038
  let lastSeen = null;
13039
+ // Stage position for the user (text mode only; JSON gets `stagesRemaining`).
13040
+ const stageTracker = new PlanStageTracker(opts.output === 'json' ? () => undefined : (line) => ticker.note(line));
12053
13041
  try {
12054
13042
  // Pre-trigger baseline snapshot: one plain GET BEFORE any POST, so the
12055
13043
  // settled read's lifetime `credits.charged` block can be diffed into
@@ -12075,23 +13063,25 @@ export async function runPlanGenerate(opts, deps = {}) {
12075
13063
  idempotencyKey,
12076
13064
  sleep: deps.sleep,
12077
13065
  shutdown: shutdownOf(deps),
12078
- onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
13066
+ onTransition: opts.verbose ? (msg) => ticker.note(`[verbose] ${msg}`) : undefined,
12079
13067
  onTick: (plans, elapsedMs) => {
12080
13068
  lastSeen = plans;
13069
+ stageTracker.onTick(plans, elapsedMs);
12081
13070
  ticker.update(planTickerLine(plans, elapsedMs));
12082
13071
  },
12083
13072
  onAttach: () => {
12084
- stderrFn('[advisory] a generation stage is already running for this project (possibly ' +
13073
+ ticker.note('[advisory] a generation stage is already running for this project (possibly ' +
12085
13074
  'started from the Portal) — attaching to it and polling.');
12086
13075
  },
12087
13076
  onTrigger: (response, acceptedPosts) => {
12088
13077
  resolvedProjectId = response.projectId;
13078
+ stageTracker.onTrigger(response);
12089
13079
  if (response.status === 'nothing_to_start') {
12090
13080
  if (acceptedPosts === 0) {
12091
13081
  // The FIRST trigger found the batch already staged: nothing ran,
12092
13082
  // nothing was charged. Regenerating on purpose is a Portal action
12093
13083
  // for now (design §11) — say so instead of silently no-opping.
12094
- stderrFn('[advisory] proposals are already staged for this project — showing the ' +
13084
+ ticker.note('[advisory] proposals are already staged for this project — showing the ' +
12095
13085
  'existing batch (nothing new was started or charged). To regenerate, ' +
12096
13086
  'review and accept or discard the staged batch in the Portal first.');
12097
13087
  }
@@ -12110,12 +13100,10 @@ export async function runPlanGenerate(opts, deps = {}) {
12110
13100
  ...(response.stage !== null ? [response.stage] : []),
12111
13101
  ...response.stagesRemaining,
12112
13102
  ];
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.`);
13103
+ const plural = stages.length === 1 ? 'stage' : 'stages';
13104
+ ticker.note(`[hint] ${stages.length} ${plural}: ${stages.join(', ')}.` +
13105
+ `${stages.includes('exploration') ? ' Takes minutes.' : ''}` +
13106
+ ' Ctrl-C is safe; re-run to continue.');
12119
13107
  }
12120
13108
  // …and, when browser exploration is about to run, warn about
12121
13109
  // missing test-account sign-in (design §3.1). The wire carries no
@@ -12123,7 +13111,7 @@ export async function runPlanGenerate(opts, deps = {}) {
12123
13111
  // it never blocks and never prompts; the CLI cannot know whether
12124
13112
  // the app actually requires login. Both output modes: stderr only.
12125
13113
  if (response.stage === 'exploration') {
12126
- stderrFn('[warn] exploration signs in only with the test account stored on the ' +
13114
+ ticker.note('[warn] exploration signs in only with the test account stored on the ' +
12127
13115
  "project's default environment. If your app requires login and no test " +
12128
13116
  'account is configured, the agents will explore only the public pages — ' +
12129
13117
  'a shallow result from a stage that still runs and still bills. For ' +
@@ -12134,6 +13122,7 @@ export async function runPlanGenerate(opts, deps = {}) {
12134
13122
  },
12135
13123
  });
12136
13124
  const plans = result.plans;
13125
+ stageTracker.settle(plans);
12137
13126
  if (plans.generation.status === 'failed') {
12138
13127
  ticker.finalize(planTickerLine(plans, 0).replace(/ \(0s\)$/, ''));
12139
13128
  const payload = { projectId: resolvedProjectId, ...plans };
@@ -12175,37 +13164,56 @@ export async function runPlanGenerate(opts, deps = {}) {
12175
13164
  // Typed exit-7 conversion (the design's hard rule): the ladder's raw
12176
13165
  // timeout is NOT a CLI error and would otherwise exit 1. Mirror the
12177
13166
  // wait-site template — partial to stdout, typed envelope thrown.
13167
+ // Every early stop below prints the same partial (stdout, so a redirected
13168
+ // file is never 0-byte) and a stderr line naming the stage position. All
13169
+ // but the stuck fuse add a `Continue:` line — an immediate re-run there
13170
+ // would only repeat the same tries.
13171
+ // The wording is deliberate: only the stage already running finishes on
13172
+ // the server; the next one starts only from a re-run of this command.
13173
+ const remaining = stageTracker.remaining();
13174
+ const position = stageTracker.position();
12178
13175
  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`));
13176
+ const reason = `timed out after ${opts.timeoutSeconds}s`;
13177
+ ticker.finalize(reason);
13178
+ const partial = makePlanGeneratePartial(resolvedProjectId, err.lastPlans ?? lastSeen, remaining);
13179
+ out.print(partial, () => renderPlanGeneratePartialText(partial, reason, position));
12182
13180
  throw ApiError.fromEnvelope({
12183
13181
  error: {
12184
13182
  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).`,
13183
+ // The prefix is the §13.3 discriminator between "slow" and a real
13184
+ // 501 UNSUPPORTED — keep it literal.
13185
+ message: `Timed out after ${opts.timeoutSeconds}s waiting for plan generation on project ` +
13186
+ `${resolvedProjectId}${position === '' ? '' : ` ${position}`}.${stageTracker.leftText()}`,
13187
+ nextAction: `Continue: testsprite test plan generate --project ${resolvedProjectId} ` +
13188
+ '(or raise --timeout)',
12189
13189
  requestId: 'local',
12190
- details: { projectId: resolvedProjectId, timeoutSeconds: opts.timeoutSeconds },
13190
+ details: {
13191
+ projectId: resolvedProjectId,
13192
+ timeoutSeconds: opts.timeoutSeconds,
13193
+ ...(remaining !== null ? { stagesRemaining: remaining } : {}),
13194
+ },
12191
13195
  },
12192
13196
  });
12193
13197
  }
12194
13198
  if (err instanceof RequestTimeoutError) {
12195
13199
  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}`);
13200
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen, remaining);
13201
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'request timed out', position));
13202
+ stderrFn(stageTracker.pausedLine(resolvedProjectId, 'Request timed out.'));
12200
13203
  throw err;
12201
13204
  }
12202
13205
  if (err instanceof InterruptError) {
12203
13206
  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}`);
13207
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen, remaining);
13208
+ out.print(partial, () => renderPlanGeneratePartialText(partial, `interrupted (${err.signal})`, position));
13209
+ stderrFn(stageTracker.pausedLine(resolvedProjectId, `Interrupted (${err.signal}).`));
13210
+ // index.ts builds the JSON INTERRUPTED envelope from this, so it tells
13211
+ // the same story as the line above (not the run-detach "test wait" one).
13212
+ attachPlanInterruptDetach(err, {
13213
+ projectId: resolvedProjectId,
13214
+ stagesRemaining: remaining,
13215
+ nextAction: stageTracker.detachNextAction(resolvedProjectId),
13216
+ });
12209
13217
  throw err;
12210
13218
  }
12211
13219
  if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
@@ -12213,10 +13221,9 @@ export async function runPlanGenerate(opts, deps = {}) {
12213
13221
  // a redirected stdout file must never be 0-byte.
12214
13222
  // The original ApiError is rethrown unchanged so exit stays 11.
12215
13223
  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}`);
13224
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen, remaining);
13225
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'rate limited', position));
13226
+ stderrFn(stageTracker.pausedLine(resolvedProjectId, 'Rate limited by the server (HTTP 429).'));
12220
13227
  throw err;
12221
13228
  }
12222
13229
  if (err instanceof ApiError &&
@@ -12229,10 +13236,16 @@ export async function runPlanGenerate(opts, deps = {}) {
12229
13236
  // the stage-failed INTERNAL (which already printed its card) never
12230
13237
  // double-prints. Rethrown unchanged.
12231
13238
  ticker.finalize('generation appears stuck');
12232
- const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
12233
- out.print(partial, () => renderPlanGeneratePartialText(partial, 'appears stuck'));
13239
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen, remaining);
13240
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'appears stuck', position, 'stalled', false));
13241
+ const fuse = err.details;
13242
+ stderrFn(stageTracker.stalledLine(fuse.triggerPosts ?? fuse.acceptedPosts));
12234
13243
  throw err;
12235
13244
  }
13245
+ // Any other error (a 402 on a later stage's trigger, a 412 on a re-POST,
13246
+ // an exhausted retry…) is rendered by index.ts as a plain line: end the
13247
+ // live ticker row first so it never lands on the progress line.
13248
+ ticker.finalize();
12236
13249
  throw withPlanFixNextAction(err, resolvedProjectId);
12237
13250
  }
12238
13251
  }
@@ -12382,12 +13395,13 @@ function createTestPlanCommand(deps) {
12382
13395
  'exploration takes minutes on a fresh frontend project)')
12383
13396
  .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
13397
  .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' +
13398
+ ' - Runs the stages the project still needs (exploration for frontend,\n' +
13399
+ ' strategy, proposals) and stops when proposals are staged for review.\n' +
13400
+ ' Nothing is written to disk.\n' +
13401
+ ' - Interrupt (exit 130/143/129) or timeout (exit 7): the stage in\n' +
13402
+ ' progress finishes on its own, the rest wait. Run the same command\n' +
13403
+ ' again to continue; it picks up where it left off. A stage that\n' +
13404
+ ' already completed is never charged again.\n' +
12391
13405
  ' - Workspace credits are spent per stage that runs; the result line reports\n' +
12392
13406
  ' what THIS run charged (omitted when nothing new was charged).\n' +
12393
13407
  ' `testsprite usage` shows your balance.\n' +