@testsprite/testsprite-cli 0.7.0 → 0.8.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 (68) hide show
  1. package/README.md +51 -38
  2. package/dist/commands/agent.js +47 -3
  3. package/dist/commands/ci.d.ts +88 -0
  4. package/dist/commands/ci.js +429 -0
  5. package/dist/commands/doctor.js +100 -1
  6. package/dist/commands/init.js +8 -0
  7. package/dist/commands/project.d.ts +78 -0
  8. package/dist/commands/project.js +426 -3
  9. package/dist/commands/test.d.ts +162 -2
  10. package/dist/commands/test.js +1814 -392
  11. package/dist/commands/testlist.js +15 -9
  12. package/dist/commands/tunnel.d.ts +72 -0
  13. package/dist/commands/tunnel.js +367 -0
  14. package/dist/index.js +107 -38
  15. package/dist/lib/dry-run/samples.d.ts +9 -0
  16. package/dist/lib/dry-run/samples.js +116 -0
  17. package/dist/lib/gh-output.d.ts +7 -0
  18. package/dist/lib/gh-output.js +50 -7
  19. package/dist/lib/http.d.ts +94 -0
  20. package/dist/lib/http.js +120 -5
  21. package/dist/lib/interrupt.d.ts +38 -13
  22. package/dist/lib/interrupt.js +130 -15
  23. package/dist/lib/local-target.d.ts +95 -0
  24. package/dist/lib/local-target.js +184 -0
  25. package/dist/lib/plan-poll.d.ts +171 -0
  26. package/dist/lib/plan-poll.js +442 -0
  27. package/dist/lib/plans.types.d.ts +130 -0
  28. package/dist/lib/plans.types.js +31 -0
  29. package/dist/lib/poll-support.d.ts +26 -0
  30. package/dist/lib/poll-support.js +65 -0
  31. package/dist/lib/poll.d.ts +1 -0
  32. package/dist/lib/poll.js +2 -40
  33. package/dist/lib/response-schemas.d.ts +13 -0
  34. package/dist/lib/response-schemas.js +32 -0
  35. package/dist/lib/run-progress.d.ts +41 -0
  36. package/dist/lib/run-progress.js +56 -0
  37. package/dist/lib/runs.types.d.ts +24 -0
  38. package/dist/lib/target-url-preflight.js +3 -3
  39. package/dist/lib/target-url.d.ts +44 -7
  40. package/dist/lib/target-url.js +250 -61
  41. package/dist/lib/telemetry.d.ts +11 -0
  42. package/dist/lib/telemetry.js +1 -0
  43. package/dist/lib/ticker.d.ts +8 -0
  44. package/dist/lib/ticker.js +3 -0
  45. package/dist/lib/tunnel-session.d.ts +129 -0
  46. package/dist/lib/tunnel-session.js +232 -0
  47. package/dist/lib/tunnel.types.d.ts +54 -0
  48. package/dist/lib/tunnel.types.js +8 -0
  49. package/dist/vendor/tunnel-client/client.d.ts +83 -0
  50. package/dist/vendor/tunnel-client/client.js +871 -0
  51. package/dist/vendor/tunnel-client/config.d.ts +41 -0
  52. package/dist/vendor/tunnel-client/config.js +42 -0
  53. package/dist/vendor/tunnel-client/index.d.ts +9 -0
  54. package/dist/vendor/tunnel-client/index.js +9 -0
  55. package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
  56. package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
  57. package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
  58. package/dist/vendor/tunnel-client/protocol.js +143 -0
  59. package/dist/vendor/tunnel-client/types.d.ts +96 -0
  60. package/dist/vendor/tunnel-client/types.js +10 -0
  61. package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
  62. package/dist/vendor/tunnel-client/ws-compat.js +316 -0
  63. package/dist/version.d.ts +1 -1
  64. package/dist/version.js +1 -1
  65. package/package.json +2 -1
  66. package/skills/testsprite-onboard.skill.md +60 -4
  67. package/skills/testsprite-verify.codex.md +22 -16
  68. package/skills/testsprite-verify.skill.md +27 -18
@@ -4,9 +4,9 @@ import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { Command } from 'commander';
6
6
  import { openInBrowser } from '../lib/browser.js';
7
- import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
7
+ import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
8
8
  import { assertContextIntegrity, buildMeta, pickCodeExtension, pickVideoExtension, resolveBundleDir, stepFilenamePrefix, writeBundle, } from '../lib/bundle.js';
9
- import { findSample, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
9
+ import { findSample, findSampleOrThrow, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
10
10
  import { assertJUnitReportOptions, buildJUnitReport, durationSecondsBetween, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
11
11
  import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, isAuthCode, localValidationError, } from '../lib/errors.js';
12
12
  import { globalShutdown } from '../lib/interrupt.js';
@@ -15,19 +15,24 @@ import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS } from '../lib/http.
15
15
  import { VERSION } from '../version.js';
16
16
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
17
17
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
18
- import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
18
+ import { isTerminalStatus, pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
19
+ import { PlanGenerationTimeoutError, runGenerationLadder } from '../lib/plan-poll.js';
19
20
  import { resolveWaitFailure } from '../lib/wait-exit.js';
20
21
  import { RUN_SOURCES } from '../lib/runs.types.js';
21
22
  import { summarizeConflicts } from '../lib/conflict-reason.js';
22
23
  import { isProxyAgentActive } from '../lib/proxy.js';
23
24
  import { assertNotLocal } from '../lib/target-url.js';
24
25
  import { assertTargetUrlReachable } from '../lib/target-url-preflight.js';
26
+ import { assertLocalPortListening, buildLocalTargetUrl, DEFAULT_LOCAL_HOST, LOOPBACK_HOSTS, normalizeLocalHost, parseLocalPort, } from '../lib/local-target.js';
27
+ import { openTunnelSession, TunnelLostError, } from '../lib/tunnel-session.js';
28
+ import { TunnelClient } from '../vendor/tunnel-client/index.js';
25
29
  import { formatTextTableRow, measureTextColumns, renderTextTable, resolveTextColumns, } from '../lib/text-table.js';
30
+ import { createLiveRunProgress, formatRunProgressLine } from '../lib/run-progress.js';
26
31
  import { createTicker } from '../lib/ticker.js';
27
32
  import { RateThrottle } from '../lib/rate-throttle.js';
28
33
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
29
34
  import { emitTargetUrlMismatchAdvisory } from '../lib/v3-advisory.js';
30
- import { emitCiArtifacts, summarizeAcceptedPayload, summarizeSingleRun } from '../lib/gh-output.js';
35
+ import { emitCiArtifacts, summarizeAcceptedPayload, summarizeSingleRun, } from '../lib/gh-output.js';
31
36
  import { loadConfig } from '../lib/config.js';
32
37
  import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
33
38
  /** The effective shutdown handle for a command invocation (DEV-331). */
@@ -88,6 +93,124 @@ function stillRunningAndBillingSubject(runIds) {
88
93
  ? `Run ${ids[0]} is still executing on the server and will keep running (and billing) until it finishes.`
89
94
  : `${ids.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
90
95
  }
96
+ /**
97
+ * Stop a tunnel run that can no longer succeed.
98
+ *
99
+ * Called on every path where this process stops waiting while the run is
100
+ * non-terminal. Unlike an ordinary run — where DEV-331 deliberately decided a
101
+ * Ctrl-C detaches and leaves the run to finish — a tunnel run's target lives
102
+ * behind a tunnel this process is holding open, so the moment we exit the
103
+ * Lambda's browser starts getting connection failures. Leaving it running
104
+ * bills the user for a guaranteed failure, which is exactly the case
105
+ * `--cancel-on-interrupt` was scoped for.
106
+ *
107
+ * The cancel is issued through a DETACHED client: the normal one composes the
108
+ * process shutdown signal into every fetch, and on the interrupt path that
109
+ * signal has already fired, so the request would abort before leaving the
110
+ * machine.
111
+ */
112
+ async function cancelDoomedTunnelRun(args) {
113
+ if (!args.enabled)
114
+ return { outcome: 'skipped' };
115
+ try {
116
+ await withTeardownDeadline(args.opts, args.deps, client => client.post(`/runs/${encodeURIComponent(args.runId)}/cancel`));
117
+ return { outcome: 'cancelled' };
118
+ }
119
+ catch (err) {
120
+ // 409 = already terminal. Not a failure: the requested end state holds.
121
+ if (err instanceof ApiError && err.code === 'CONFLICT') {
122
+ const terminalStatus = err.getDetail('status', (value) => typeof value === 'string' && isTerminalStatus(value));
123
+ return {
124
+ outcome: 'already-terminal',
125
+ ...(terminalStatus !== undefined ? { terminalStatus } : {}),
126
+ };
127
+ }
128
+ return { outcome: 'failed' };
129
+ }
130
+ }
131
+ /**
132
+ * The stderr line for a tunnel run whose wait is ending.
133
+ *
134
+ * Deliberately NOT built from `stillRunningAndBillingSubject`: that sentence
135
+ * is true for an ordinary run and false here, and the whole point of D1 (a)
136
+ * is that the four detach paths stop telling a tunnel user something untrue.
137
+ */
138
+ function tunnelDetachMessage(detach) {
139
+ const { runId, reason, cancel } = detach;
140
+ const cause = {
141
+ interrupt: 'Interrupted',
142
+ timeout: `Timed out waiting for run ${runId}`,
143
+ 'request-timeout': 'Request timed out',
144
+ 'rate-limited': 'Rate limited by the server (HTTP 429)',
145
+ 'tunnel-lost': 'The tunnel was disconnected by the tunnel service',
146
+ 'poll-error': 'Polling stopped because the run status could not be read',
147
+ };
148
+ const doom = reason === 'tunnel-lost'
149
+ ? `Run ${runId} was reaching your machine through that tunnel, and the run's proxy credential ` +
150
+ `names the client that just went away, so it cannot be restored for this run.`
151
+ : `Run ${runId} was reaching your machine through a tunnel that closes with this process, so ` +
152
+ `it cannot finish.`;
153
+ const outcome = {
154
+ cancelled: ' Cancelled it, so no further credits are spent on a guaranteed failure.',
155
+ 'already-terminal': ' It had already finished server-side; there was nothing to cancel.',
156
+ failed: ` Could NOT cancel it from here — stop it with: testsprite test cancel ${runId}`,
157
+ skipped: ` Left it running (--no-cancel-on-interrupt); stop it with: testsprite test cancel ${runId}`,
158
+ };
159
+ return (`${cause[reason]}. ${doom}\n` +
160
+ `${outcome[cancel]}\n` +
161
+ ` Start it again with --local when you're ready; a retry mints a fresh tunnel.`);
162
+ }
163
+ /**
164
+ * The `hint` lines under a partial run envelope.
165
+ *
166
+ * For an ordinary run these point at `test wait` / `test cancel`, which is
167
+ * right: the run is still going. For a tunnel run `test wait` is actively
168
+ * misleading — re-attaching cannot revive a tunnel that closed with the
169
+ * process that owned it — so it is never offered.
170
+ */
171
+ function detachHintLines(runId, detach) {
172
+ if (detach === undefined) {
173
+ return [
174
+ `hint Re-attach with: testsprite test wait ${runId}`,
175
+ `hint Cancel with: testsprite test cancel ${runId}`,
176
+ ];
177
+ }
178
+ return detach.cancel === 'cancelled' || detach.cancel === 'already-terminal'
179
+ ? ['hint The tunnel closed with this process, so the run was stopped.']
180
+ : [`hint Stop the run with: testsprite test cancel ${runId}`];
181
+ }
182
+ /** Status to report in a partial envelope once a doomed tunnel run was stopped. */
183
+ function detachPartialStatus(detach) {
184
+ if (detach === undefined)
185
+ return 'running';
186
+ if (detach.cancel === 'cancelled')
187
+ return 'cancelled';
188
+ return detach.terminalStatus ?? 'running';
189
+ }
190
+ function tunnelInterruptNextAction(detach) {
191
+ if (detach.cancel === 'cancelled') {
192
+ return (`Run ${detach.runId} was cancelled and its tunnel was closed. ` +
193
+ 'Start it again with --local when you are ready.');
194
+ }
195
+ if (detach.cancel === 'already-terminal') {
196
+ return (`Run ${detach.runId} had already finished` +
197
+ (detach.terminalStatus ? ` with status ${detach.terminalStatus}` : '') +
198
+ '; its tunnel was closed. Start a new --local run if you need to test again.');
199
+ }
200
+ if (detach.cancel === 'skipped') {
201
+ return (`The tunnel for run ${detach.runId} was closed, but cancellation was disabled. ` +
202
+ `Stop the run with: testsprite test cancel ${detach.runId}; then start it again with --local.`);
203
+ }
204
+ return (`The tunnel for run ${detach.runId} was closed and automatic cancellation failed. ` +
205
+ `Stop the run with: testsprite test cancel ${detach.runId}; then start it again with --local.`);
206
+ }
207
+ function attachTunnelInterruptDetach(err, detach) {
208
+ err.tunnelDetach = {
209
+ runId: detach.runId,
210
+ cancel: detach.cancel,
211
+ nextAction: tunnelInterruptNextAction(detach),
212
+ };
213
+ }
91
214
  const TEST_TYPES = ['frontend', 'backend'];
92
215
  // 'cli' added 2026-06-04 (dogfood): backend now stamps createFrom='cli' on
93
216
  // tests created via `testsprite test create`, so the `--created-from cli`
@@ -367,6 +490,9 @@ export async function runCreate(opts, deps = {}) {
367
490
  priority: opts.priority,
368
491
  code,
369
492
  };
493
+ if (opts.stepTimeoutMs !== undefined) {
494
+ body.stepTimeoutMs = opts.stepTimeoutMs;
495
+ }
370
496
  // M4 piece-2: thread BE dependency fields into the POST body.
371
497
  // Only include when non-empty so the wire stays clean for tests that
372
498
  // don't declare any dependencies (undefined is omitted by JSON.stringify).
@@ -424,6 +550,9 @@ export async function runCreate(opts, deps = {}) {
424
550
  // tests) on stderr so they reach the agent without polluting stdout JSON.
425
551
  // Emitted before the --run early return so they always show.
426
552
  emitResponseWarnings(response.warnings, deps);
553
+ if (!opts.dryRun) {
554
+ emitStepTimeoutRunWarning(opts.stepTimeoutMs, deps);
555
+ }
427
556
  // --run chain (M3.3 piece-3). Per codex round-1 P1: suppress the
428
557
  // create's own print when chaining; `runTestRun` emits a single
429
558
  // merged envelope `{ ...createResponse, run: <trigger|final> }` so
@@ -615,6 +744,19 @@ function emitResponseWarnings(warnings, deps) {
615
744
  for (const w of warnings)
616
745
  stderrFn(`[warn] ${w}`);
617
746
  }
747
+ /**
748
+ * A per-step timeout can make the overall run exceed the CLI's independent
749
+ * client-side poll deadline. Keep the two timeout concepts explicit and make
750
+ * clear that detaching the client never cancels server-side execution.
751
+ */
752
+ function emitStepTimeoutRunWarning(stepTimeoutMs, deps) {
753
+ if (stepTimeoutMs === undefined)
754
+ return;
755
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
756
+ stderrFn(`[warn] Runs of this test may take longer with a ${stepTimeoutMs} ms per-step timeout. ` +
757
+ `\`test run --wait\` polls for up to ${DEFAULT_RUN_TIMEOUT_SECONDS}s by default; ` +
758
+ 'raise it with `--timeout <s>` if needed. A client-side timeout never stops the server-side run.');
759
+ }
618
760
  /**
619
761
  * piece-6 cap for the `PUT /tests/{id}/plan-steps` body. Distinct from
620
762
  * piece-5's `MAX_PLAN_BODY_BYTES` because the wire shape differs
@@ -887,8 +1029,11 @@ export async function runUpdate(opts, deps = {}) {
887
1029
  ...CLI_CREATE_PRIORITIES,
888
1030
  ]);
889
1031
  }
890
- // No-op rejection: requires at least one of the three patchable
891
- // fields. Caught before fetching credentials or building the
1032
+ if (opts.stepTimeoutMs !== undefined && opts.clearStepTimeout === true) {
1033
+ throw localValidationError('step-timeout', '--step-timeout and --clear-step-timeout are mutually exclusive');
1034
+ }
1035
+ // No-op rejection: requires at least one patchable field. Caught before
1036
+ // fetching credentials or building the
892
1037
  // request so the user gets the cheapest possible error.
893
1038
  const hasName = opts.name !== undefined;
894
1039
  const hasDescription = opts.description !== undefined;
@@ -896,8 +1041,26 @@ export async function runUpdate(opts, deps = {}) {
896
1041
  const hasProduces = opts.produces !== undefined && opts.produces.length > 0;
897
1042
  const hasNeeds = opts.needs !== undefined && opts.needs.length > 0;
898
1043
  const hasCategory = opts.category !== undefined;
899
- if (!hasName && !hasDescription && !hasPriority && !hasProduces && !hasNeeds && !hasCategory) {
900
- throw localValidationError('fields', 'at least one of --name / --description / --priority / --produces / --needs / --category must be set', ['name', 'description', 'priority', 'produces', 'needs', 'category']);
1044
+ const hasStepTimeout = opts.stepTimeoutMs !== undefined;
1045
+ const hasClearStepTimeout = opts.clearStepTimeout === true;
1046
+ if (!hasName &&
1047
+ !hasDescription &&
1048
+ !hasPriority &&
1049
+ !hasProduces &&
1050
+ !hasNeeds &&
1051
+ !hasCategory &&
1052
+ !hasStepTimeout &&
1053
+ !hasClearStepTimeout) {
1054
+ throw localValidationError('fields', 'at least one of --name / --description / --priority / --produces / --needs / --category / --step-timeout / --clear-step-timeout must be set', [
1055
+ 'name',
1056
+ 'description',
1057
+ 'priority',
1058
+ 'produces',
1059
+ 'needs',
1060
+ 'category',
1061
+ 'step-timeout',
1062
+ 'clear-step-timeout',
1063
+ ]);
901
1064
  }
902
1065
  const idempotencyKey = opts.idempotencyKey ?? `cli-update-${randomUUID()}`;
903
1066
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
@@ -922,12 +1085,19 @@ export async function runUpdate(opts, deps = {}) {
922
1085
  body.consumes = opts.needs;
923
1086
  if (hasCategory)
924
1087
  body.category = opts.category;
1088
+ if (hasStepTimeout)
1089
+ body.stepTimeoutMs = opts.stepTimeoutMs;
1090
+ if (hasClearStepTimeout)
1091
+ body.stepTimeoutMs = null;
925
1092
  const client = makeClient(opts, deps);
926
1093
  const out = makeOutput(opts.output, deps);
927
1094
  const response = await client.put(`/tests/${encodeURIComponent(opts.testId)}`, {
928
1095
  body,
929
1096
  headers: { 'idempotency-key': idempotencyKey },
930
1097
  });
1098
+ if (!opts.dryRun && hasStepTimeout) {
1099
+ emitStepTimeoutRunWarning(opts.stepTimeoutMs, deps);
1100
+ }
931
1101
  out.print(response, data => renderUpdateText(data));
932
1102
  return response;
933
1103
  }
@@ -4106,7 +4276,7 @@ function isTerminalPublicStatus(status) {
4106
4276
  * only the verdict/result fields are taken from the test record (codex
4107
4277
  * round-2: don't fabricate blank correlation fields).
4108
4278
  */
4109
- function backendResultToRunResponse(result, run) {
4279
+ export function backendResultToRunResponse(result, run, testTitle) {
4110
4280
  // `result.summary` is now a semantic string, not a count object.
4111
4281
  // Reconstruct the synthetic 1-test stepSummary from the verdict (byte-identical
4112
4282
  // to the prior status-derived counts: passed→1/0, failed→0/1, else→0/0).
@@ -4116,6 +4286,12 @@ function backendResultToRunResponse(result, run) {
4116
4286
  return {
4117
4287
  ...run,
4118
4288
  status: result.status,
4289
+ // The backend only resolves `testTitle` on a TERMINAL run read; this fallback
4290
+ // synthesizes a terminal response from a NON-terminal poll (`run.testTitle` is
4291
+ // null there by contract), so overlay the name the type-probe already fetched
4292
+ // — zero extra request. `.trim() ||` matches the empty-title→id fallback the
4293
+ // summary/JUnit renderers use, so a blank name never renders an empty cell.
4294
+ testTitle: testTitle?.trim() ? testTitle : (run.testTitle ?? null),
4119
4295
  // Drop the polling hint — it's meaningless on a terminal response
4120
4296
  // (JSON.stringify omits undefined keys).
4121
4297
  retryAfterSeconds: undefined,
@@ -4178,8 +4354,13 @@ export function backendResultIsForThisRun(result, runId, notBefore) {
4178
4354
  * - Every lookup is best-effort: any error → "keep polling the run row", so
4179
4355
  * the fallback can never make either path worse than the prior timeout.
4180
4356
  */
4181
- function makeBackendWaitFallback(args) {
4357
+ export function makeBackendWaitFallback(args) {
4182
4358
  let detection = 'pending';
4359
+ // Cached alongside `detection` from the same one-time type-probe: the human
4360
+ // name, used to overlay `testTitle` onto the synthesized terminal response
4361
+ // (the backend never sends a title on the non-terminal poll this fallback
4362
+ // reads). Null until the probe succeeds, or if the test has no/blank name.
4363
+ let testName = null;
4183
4364
  return async (run, _elapsedMs, signal) => {
4184
4365
  const testId = args.resolveTestId(run);
4185
4366
  if (!testId)
@@ -4196,6 +4377,7 @@ function makeBackendWaitFallback(args) {
4196
4377
  // non-terminal tick retries; the FE path is unaffected because its run
4197
4378
  // row finalizes and `resolveAlternate` stops being called.
4198
4379
  detection = test.type === 'backend' ? 'backend' : 'frontend';
4380
+ testName = test.name?.trim() ? test.name : null;
4199
4381
  }
4200
4382
  catch {
4201
4383
  return null; // transient — keep polling the run row, retry the probe next tick.
@@ -4215,8 +4397,9 @@ function makeBackendWaitFallback(args) {
4215
4397
  }
4216
4398
  args.onResolved?.(testId, result.status);
4217
4399
  // Overlay the verdict onto the polled run row (preserves real correlation
4218
- // metadata; codex round-2).
4219
- return backendResultToRunResponse(result, run);
4400
+ // metadata; codex round-2) plus the probe-cached name so the CI title is
4401
+ // populated even on a run row that never finalizes on its own.
4402
+ return backendResultToRunResponse(result, run, testName);
4220
4403
  };
4221
4404
  }
4222
4405
  /**
@@ -4447,6 +4630,16 @@ function parseTimeoutFlag(raw, flagName) {
4447
4630
  }
4448
4631
  return n;
4449
4632
  }
4633
+ /** Validate the per-test timeout that the execution engine applies to every step. */
4634
+ function parseStepTimeoutFlag(raw, flagName) {
4635
+ if (raw === undefined)
4636
+ return undefined;
4637
+ const n = Number(raw);
4638
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 60_000) {
4639
+ throw localValidationError(flagName, 'must be an integer between 1 and 60000 milliseconds');
4640
+ }
4641
+ return n;
4642
+ }
4450
4643
  /**
4451
4644
  * `test run <test-id>` — M3.3 piece-3.
4452
4645
  *
@@ -4457,9 +4650,29 @@ function parseTimeoutFlag(raw, flagName) {
4457
4650
  */
4458
4651
  export async function runTestRun(opts, deps = {}) {
4459
4652
  assertIdempotencyKey(opts.idempotencyKey);
4653
+ // --local resolution runs FIRST and touches nothing: every refusal below
4654
+ // must happen before a client is even constructed, because the guarantee
4655
+ // this feature sells is that a doomed `--local` run never gets a run row,
4656
+ // a credit spend, or a tunnel credential.
4657
+ const isTunnelRun = opts.localPort !== undefined;
4658
+ if (isTunnelRun && opts.targetUrl !== undefined) {
4659
+ throw localValidationError('local', '--local and --target-url are mutually exclusive: --local runs against your own machine ' +
4660
+ 'through a tunnel, --target-url runs against an address the test runner can already ' +
4661
+ 'reach. Pass one');
4662
+ }
4663
+ if (isTunnelRun && !opts.wait) {
4664
+ // The tunnel's lifetime IS this process's lifetime, so a no-wait tunnel
4665
+ // run dooms itself the instant the command returns. The command wiring
4666
+ // forces --wait; this covers a programmatic caller that did not.
4667
+ throw localValidationError('local', '--local runs cannot detach: the tunnel closes when this command exits, so the run would ' +
4668
+ 'fail. Remove --local, or let the command wait');
4669
+ }
4460
4670
  if (opts.targetUrl !== undefined) {
4461
4671
  assertNotLocal(opts.targetUrl);
4462
4672
  }
4673
+ const localHost = opts.localHost ?? DEFAULT_LOCAL_HOST;
4674
+ const localTargetUrl = opts.localPort !== undefined ? buildLocalTargetUrl(localHost, opts.localPort) : undefined;
4675
+ const effectiveTargetUrl = localTargetUrl ?? opts.targetUrl;
4463
4676
  if (opts.dryRun) {
4464
4677
  const client = makeClient(opts, deps);
4465
4678
  const out = makeOutput(opts.output, deps);
@@ -4482,8 +4695,22 @@ export async function runTestRun(opts, deps = {}) {
4482
4695
  const envelope = {
4483
4696
  method: 'POST',
4484
4697
  path: `/api/cli/v1/tests/${opts.testId}/runs`,
4485
- body: { source: 'cli', ...(opts.targetUrl ? { targetUrl: opts.targetUrl } : {}) },
4698
+ body: {
4699
+ source: 'cli',
4700
+ ...(effectiveTargetUrl ? { targetUrl: effectiveTargetUrl } : {}),
4701
+ // A dry run mints nothing, so there is no real client id to show —
4702
+ // and inventing a UUID-shaped one would read as a live credential
4703
+ // handle, the same reason `dashboardUrl` is suppressed under
4704
+ // --dry-run rather than pointing at the canned sample id.
4705
+ ...(isTunnelRun ? { tunnelClientId: '<minted at run time>' } : {}),
4706
+ },
4486
4707
  idempotencyKey,
4708
+ ...(isTunnelRun
4709
+ ? {
4710
+ precededBy: 'POST /api/cli/v1/tunnel',
4711
+ followedBy: 'DELETE /api/cli/v1/tunnel/<client-id>',
4712
+ }
4713
+ : {}),
4487
4714
  ...(opts.wait ? { thenPoll: `/api/cli/v1/runs/<run-id>?waitSeconds=25` } : {}),
4488
4715
  };
4489
4716
  printRunOrChain(out, envelope, opts.createContext);
@@ -4498,9 +4725,15 @@ export async function runTestRun(opts, deps = {}) {
4498
4725
  }
4499
4726
  // D4: under --wait, raise the per-request timeout to cover --timeout so a
4500
4727
  // slow trigger/long-poll under load isn't falsely cut at the 120s default.
4501
- const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
4728
+ const requestTimeoutMs = resolveWaitRequestTimeoutMs(opts);
4729
+ const clientOpts = { ...opts, requestTimeoutMs };
4730
+ const client = makeClient(clientOpts, deps);
4731
+ const tunnelRequestTimeoutMs = isTunnelRun
4732
+ ? resolveRequestTimeoutMs(clientOpts, deps.env ?? process.env)
4733
+ : undefined;
4502
4734
  const out = makeOutput(opts.output, deps);
4503
4735
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4736
+ const shutdown = shutdownOf(deps);
4504
4737
  // Pre-charge reachability preflight — real path only (dry-run
4505
4738
  // makes zero network calls by convention), after `assertNotLocal` and
4506
4739
  // before the trigger POST so a doomed run never gets a run row or charge.
@@ -4508,350 +4741,544 @@ export async function runTestRun(opts, deps = {}) {
4508
4741
  // delegating caller (`runCreate`/`runCreateFromPlan` chaining `--run`)
4509
4742
  // already ran this exact check against the same URL before its own
4510
4743
  // create POST and sets `skipPreflight: true` here to avoid probing twice.
4511
- if (opts.targetUrl !== undefined) {
4744
+ if (isTunnelRun) {
4745
+ // The tunnel-run equivalent of the --target-url probe, and the reason
4746
+ // DEV-868 exists: a dev server that is not running is the single most
4747
+ // likely `--local` mistake, and this is the last moment it costs nothing.
4748
+ // Unlike the --target-url probe this one is conclusive — the dial it
4749
+ // performs is the same raw loopback connect the tunnel client will make
4750
+ // from this same process — so it refuses rather than advises.
4751
+ await assertLocalPortListening(localHost, opts.localPort, { skipPreflight: opts.skipPreflight }, stderrFn);
4752
+ if (isProxyAgentActive()) {
4753
+ stderrFn('[advisory] An HTTP proxy is configured for this process. The tunnel control channel ' +
4754
+ 'honours it, but the tunnel data plane is a raw TCP connection that does not — if the ' +
4755
+ 'run cannot reach your machine, an egress proxy is the first thing to rule out.');
4756
+ }
4757
+ }
4758
+ else if (opts.targetUrl !== undefined) {
4512
4759
  await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
4513
4760
  }
4514
- let triggerResponse;
4515
- let triggerRequestId;
4516
- let resumedFromConflict = false;
4761
+ // Nothing above this line has spent money or minted a credential. Everything
4762
+ // below it must be unwound on every exit path, which is what the `finally`
4763
+ // at the end of this function is for.
4764
+ let tunnelSession;
4765
+ // Arm before minting and keep the scope armed until close/delete finishes.
4766
+ // The nested poll arm is intentionally re-entrant; when it disarms, this
4767
+ // outer lifecycle scope still protects cancellation and binding teardown.
4768
+ const disarmTunnelLifecycle = isTunnelRun ? shutdown.arm() : undefined;
4517
4769
  try {
4518
- const result = await client.triggerRunWithMeta(opts.testId, { source: 'cli', ...(opts.targetUrl ? { targetUrl: opts.targetUrl } : {}) }, { idempotencyKey });
4519
- triggerResponse = result.body;
4520
- triggerRequestId = result.requestId;
4521
- }
4522
- catch (err) {
4523
- // CONFLICT (409) can arise from two different causes:
4524
- // 1. reason === 'run_in_flight' — another run is currently executing for
4525
- // this test. Auto-resume polling is valid ONLY for this reason and ONLY
4526
- // when --wait is set. Any other reason (snapshot_in_flight, etc.) or
4527
- // IDEMPOTENCY_BODY_MISMATCH must propagate to exit 6 so callers can
4528
- // decide what to do.
4529
- // 2. reason !== 'run_in_flight' — snapshot mid-mutation or body-hash
4530
- // mismatch. Always propagate.
4531
- if (opts.wait && err instanceof ApiError && err.code === 'CONFLICT') {
4532
- const conflictReason = err.getDetail('reason', (v) => typeof v === 'string' && v.length > 0);
4533
- const currentRunId = err.getDetail('currentRunId', (v) => typeof v === 'string' && v.length > 0);
4534
- // Only the genuine "another run currently executing" race qualifies for
4535
- // auto-resume. Other CONFLICT reasons (snapshot_in_flight, etc.) exit 6.
4536
- if (conflictReason === 'run_in_flight' && currentRunId !== undefined) {
4537
- const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4538
- // If the caller supplied --target-url, verify the in-flight run targets
4539
- // the same URL. A mismatch means we would be reporting a different
4540
- // environment's results as if our requested environment was tested.
4541
- if (opts.targetUrl !== undefined) {
4542
- const inFlightRun = await client.getRun(currentRunId);
4543
- if (inFlightRun.targetUrl !== opts.targetUrl) {
4544
- throw new ApiError({
4545
- code: 'CONFLICT',
4546
- message: `Conflict: another run for this test is in flight against a different ` +
4547
- `target URL (${inFlightRun.targetUrl ?? 'not reported'}). Your --target-url ${opts.targetUrl} ` +
4548
- `cannot attach to that run. Wait for it to finish ` +
4549
- `(\`testsprite test wait ${currentRunId}\`) or retry your trigger when ` +
4550
- `the test is free.`,
4551
- nextAction: `testsprite test wait ${currentRunId}`,
4552
- requestId: err.requestId,
4553
- details: {
4554
- reason: 'run_in_flight',
4555
- currentRunId,
4556
- inFlightTargetUrl: inFlightRun.targetUrl,
4557
- requestedTargetUrl: opts.targetUrl,
4558
- },
4559
- });
4560
- }
4561
- stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}, ` +
4562
- `target: ${inFlightRun.targetUrl}). ` +
4563
- `Attaching to that run's --wait poll instead of creating a new one. ` +
4564
- `To stop it instead: testsprite test cancel ${currentRunId}`);
4565
- triggerResponse = {
4566
- runId: currentRunId,
4567
- status: 'queued',
4568
- enqueuedAt: new Date().toISOString(),
4569
- codeVersion: inFlightRun.codeVersion ?? '',
4570
- // The check above proved the in-flight run targets exactly this URL.
4571
- targetUrl: opts.targetUrl,
4572
- };
4770
+ if (isTunnelRun) {
4771
+ try {
4772
+ tunnelSession = await openTunnelSession({
4773
+ log: stderrFn,
4774
+ logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error',
4775
+ onFatal: () => {
4776
+ // Surfaced to the poll loop through `onTick` below; a remint cannot
4777
+ // rescue this run (see `lib/tunnel-session.ts`).
4778
+ },
4779
+ ...(opts.tunnelClientId !== undefined
4780
+ ? { adopt: { clientId: opts.tunnelClientId, expiresAt: '' } }
4781
+ : {}),
4782
+ }, {
4783
+ mint: async (ttlSeconds) => withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, mintClient => mintClient.mintTunnel({ ...(ttlSeconds ? { ttlSeconds } : {}) })),
4784
+ destroy: async (clientId) => deleteTunnelForCleanup(opts, deps, clientId),
4785
+ createClient: shutdownAwareTunnelClientFactory(deps.createTunnelClient ?? (options => new TunnelClient(options)), shutdown.signal),
4786
+ });
4787
+ }
4788
+ catch (err) {
4789
+ // `openTunnelSession` converts a client-start rejection to UNAVAILABLE
4790
+ // after it has stopped the client and deleted the binding. Restore the
4791
+ // initiating signal so the documented interrupt exit code is retained.
4792
+ if (shutdown.signal.aborted)
4793
+ throw shutdown.signal.reason;
4794
+ throw err;
4795
+ }
4796
+ if (!tunnelSession.adopted) {
4797
+ stderrFn(`[tunnel] Reaching ${localTargetUrl} through TestSprite (client ${tunnelSession.clientId}).`);
4798
+ }
4799
+ }
4800
+ let triggerResponse;
4801
+ let triggerRequestId;
4802
+ let resumedFromConflict = false;
4803
+ try {
4804
+ // A signal received before the POST begins is still free to stop here.
4805
+ // Once the request has begun, however, it must finish under its own
4806
+ // bounded deadline so we can learn the runId if the server charged it.
4807
+ if (isTunnelRun && shutdown.signal.aborted)
4808
+ throw shutdown.signal.reason;
4809
+ const triggerBody = {
4810
+ source: 'cli',
4811
+ ...(effectiveTargetUrl ? { targetUrl: effectiveTargetUrl } : {}),
4812
+ // The client ID only. The secret stays in this process and never
4813
+ // reaches a request body, an idempotency row, or an audit line.
4814
+ ...(tunnelSession ? { tunnelClientId: tunnelSession.clientId } : {}),
4815
+ };
4816
+ const result = isTunnelRun
4817
+ ? await withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, triggerClient => triggerClient.triggerRunWithMeta(opts.testId, triggerBody, { idempotencyKey }))
4818
+ : await client.triggerRunWithMeta(opts.testId, triggerBody, { idempotencyKey });
4819
+ triggerResponse = result.body;
4820
+ triggerRequestId = result.requestId;
4821
+ }
4822
+ catch (err) {
4823
+ // CONFLICT (409) can arise from two different causes:
4824
+ // 1. reason === 'run_in_flight' — another run is currently executing for
4825
+ // this test. Auto-resume polling is valid ONLY for this reason and ONLY
4826
+ // when --wait is set. Any other reason (snapshot_in_flight, etc.) or
4827
+ // IDEMPOTENCY_BODY_MISMATCH must propagate to exit 6 so callers can
4828
+ // decide what to do.
4829
+ // 2. reason !== 'run_in_flight' — snapshot mid-mutation or body-hash
4830
+ // mismatch. Always propagate.
4831
+ if (opts.wait && err instanceof ApiError && err.code === 'CONFLICT') {
4832
+ const conflictReason = err.getDetail('reason', (v) => typeof v === 'string' && v.length > 0);
4833
+ const currentRunId = err.getDetail('currentRunId', (v) => typeof v === 'string' && v.length > 0);
4834
+ // Auto-resume is wrong for a tunnel run: the in-flight run was
4835
+ // triggered without OUR client id, so it is not routed through this
4836
+ // tunnel and is testing something else entirely. Attaching to its poll
4837
+ // would report a different environment's verdict as if it were the
4838
+ // local one — the exact substitution `--local` exists to prevent.
4839
+ if (isTunnelRun) {
4840
+ throw err;
4573
4841
  }
4574
- else {
4575
- // D: No --target-url supplied — fetch the in-flight run so the
4576
- // synthesised triggerResponse.targetUrl is the REAL environment being
4577
- // tested, not an empty string that would propagate into the timeout
4578
- // partial (Finding D). Fall back to null (not '') if the lookup fails.
4579
- let inFlightTargetUrl = null;
4580
- let inFlightCodeVersion = '';
4581
- try {
4842
+ // Only the genuine "another run currently executing" race qualifies for
4843
+ // auto-resume. Other CONFLICT reasons (snapshot_in_flight, etc.) exit 6.
4844
+ if (conflictReason === 'run_in_flight' && currentRunId !== undefined) {
4845
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4846
+ // If the caller supplied --target-url, verify the in-flight run targets
4847
+ // the same URL. A mismatch means we would be reporting a different
4848
+ // environment's results as if our requested environment was tested.
4849
+ if (opts.targetUrl !== undefined) {
4582
4850
  const inFlightRun = await client.getRun(currentRunId);
4583
- inFlightTargetUrl = inFlightRun.targetUrl ?? null;
4584
- inFlightCodeVersion = inFlightRun.codeVersion ?? '';
4851
+ if (inFlightRun.targetUrl !== opts.targetUrl) {
4852
+ throw new ApiError({
4853
+ code: 'CONFLICT',
4854
+ message: `Conflict: another run for this test is in flight against a different ` +
4855
+ `target URL (${inFlightRun.targetUrl ?? 'not reported'}). Your --target-url ${opts.targetUrl} ` +
4856
+ `cannot attach to that run. Wait for it to finish ` +
4857
+ `(\`testsprite test wait ${currentRunId}\`) or retry your trigger when ` +
4858
+ `the test is free.`,
4859
+ nextAction: `testsprite test wait ${currentRunId}`,
4860
+ requestId: err.requestId,
4861
+ details: {
4862
+ reason: 'run_in_flight',
4863
+ currentRunId,
4864
+ inFlightTargetUrl: inFlightRun.targetUrl,
4865
+ requestedTargetUrl: opts.targetUrl,
4866
+ },
4867
+ });
4868
+ }
4869
+ stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}, ` +
4870
+ `target: ${inFlightRun.targetUrl}). ` +
4871
+ `Attaching to that run's --wait poll instead of creating a new one. ` +
4872
+ `To stop it instead: testsprite test cancel ${currentRunId}`);
4873
+ triggerResponse = {
4874
+ runId: currentRunId,
4875
+ status: 'queued',
4876
+ enqueuedAt: new Date().toISOString(),
4877
+ codeVersion: inFlightRun.codeVersion ?? '',
4878
+ // The check above proved the in-flight run targets exactly this URL.
4879
+ targetUrl: opts.targetUrl,
4880
+ };
4585
4881
  }
4586
- catch {
4587
- // Best-effort — if the lookup fails, proceed with null targetUrl.
4882
+ else {
4883
+ // D: No --target-url supplied — fetch the in-flight run so the
4884
+ // synthesised triggerResponse.targetUrl is the REAL environment being
4885
+ // tested, not an empty string that would propagate into the timeout
4886
+ // partial (Finding D). Fall back to null (not '') if the lookup fails.
4887
+ let inFlightTargetUrl = null;
4888
+ let inFlightCodeVersion = '';
4889
+ try {
4890
+ const inFlightRun = await client.getRun(currentRunId);
4891
+ inFlightTargetUrl = inFlightRun.targetUrl ?? null;
4892
+ inFlightCodeVersion = inFlightRun.codeVersion ?? '';
4893
+ }
4894
+ catch {
4895
+ // Best-effort — if the lookup fails, proceed with null targetUrl.
4896
+ }
4897
+ // Auto-resume but emit a stronger advisory so the caller is aware
4898
+ // they are attaching to the project default.
4899
+ // SIG-9 (DEV-331 final): the in-flight run is NOT auto-cancelled —
4900
+ // name the real `test cancel` command instead of the old (false)
4901
+ // "cancel with Ctrl-C" claim.
4902
+ stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}` +
4903
+ (inFlightTargetUrl ? `, target: ${inFlightTargetUrl}` : '') +
4904
+ `). Auto-resuming wait on in-flight run. ` +
4905
+ `If you needed a specific target URL, cancel it with ` +
4906
+ `testsprite test cancel ${currentRunId}, or re-trigger with ` +
4907
+ `--target-url after it finishes.`);
4908
+ triggerResponse = {
4909
+ runId: currentRunId,
4910
+ status: 'queued',
4911
+ enqueuedAt: new Date().toISOString(),
4912
+ codeVersion: inFlightCodeVersion,
4913
+ // Use the real targetUrl from the in-flight run (or null if unknown),
4914
+ // never '' — the timeout partial inherits this value.
4915
+ targetUrl: inFlightTargetUrl ?? '',
4916
+ };
4588
4917
  }
4589
- // Auto-resume but emit a stronger advisory so the caller is aware
4590
- // they are attaching to the project default.
4591
- // SIG-9 (DEV-331 final): the in-flight run is NOT auto-cancelled —
4592
- // name the real `test cancel` command instead of the old (false)
4593
- // "cancel with Ctrl-C" claim.
4594
- stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}` +
4595
- (inFlightTargetUrl ? `, target: ${inFlightTargetUrl}` : '') +
4596
- `). Auto-resuming wait on in-flight run. ` +
4597
- `If you needed a specific target URL, cancel it with ` +
4598
- `testsprite test cancel ${currentRunId}, or re-trigger with ` +
4599
- `--target-url after it finishes.`);
4600
- triggerResponse = {
4601
- runId: currentRunId,
4602
- status: 'queued',
4603
- enqueuedAt: new Date().toISOString(),
4604
- codeVersion: inFlightCodeVersion,
4605
- // Use the real targetUrl from the in-flight run (or null if unknown),
4606
- // never '' — the timeout partial inherits this value.
4607
- targetUrl: inFlightTargetUrl ?? '',
4608
- };
4918
+ resumedFromConflict = true;
4919
+ }
4920
+ else {
4921
+ throw err;
4609
4922
  }
4610
- resumedFromConflict = true;
4611
4923
  }
4612
4924
  else {
4613
4925
  throw err;
4614
4926
  }
4615
4927
  }
4616
- else {
4617
- throw err;
4928
+ // Response-driven, not assumption-driven: the backend is the ground
4929
+ // truth for whether --target-url was actually applied — V3
4930
+ // deliberately returns `targetUrl: ''` rather than echoing an override it
4931
+ // did not apply ("so the response doesn't claim a target we didn't use"),
4932
+ // while V2 echoes the real applied value. Comparing what we asked for
4933
+ // against what the trigger response reports self-corrects the day the
4934
+ // backend applies the override, with no `v3Enabled` assumption at all.
4935
+ // Skipped for a known-backend caller (`opts.type` threaded from the
4936
+ // `test create --run` chain): a backend trigger response's `targetUrl`
4937
+ // is an unconditional echo of the request body (verified against
4938
+ // backend-v2.0's `CliTestsController.createRun` — `targetUrl: body.targetUrl
4939
+ // ?? ''` on both the V2 and V3 backend branches), so it can never mismatch
4940
+ // and the existing, more specific C1 advisory ("--target-url has no effect
4941
+ // for backend tests") already covers this case at create time.
4942
+ if (effectiveTargetUrl !== undefined &&
4943
+ opts.type !== 'backend' &&
4944
+ triggerResponse.targetUrl !== effectiveTargetUrl) {
4945
+ emitTargetUrlMismatchAdvisory(stderrFn, effectiveTargetUrl, triggerResponse.targetUrl);
4618
4946
  }
4619
- }
4620
- // Response-driven, not assumption-driven: the backend is the ground
4621
- // truth for whether --target-url was actually applied — V3
4622
- // deliberately returns `targetUrl: ''` rather than echoing an override it
4623
- // did not apply ("so the response doesn't claim a target we didn't use"),
4624
- // while V2 echoes the real applied value. Comparing what we asked for
4625
- // against what the trigger response reports self-corrects the day the
4626
- // backend applies the override, with no `v3Enabled` assumption at all.
4627
- // Skipped for a known-backend caller (`opts.type` threaded from the
4628
- // `test create --run` chain): a backend trigger response's `targetUrl`
4629
- // is an unconditional echo of the request body (verified against
4630
- // backend-v2.0's `CliTestsController.createRun` — `targetUrl: body.targetUrl
4631
- // ?? ''` on both the V2 and V3 backend branches), so it can never mismatch
4632
- // and the existing, more specific C1 advisory ("--target-url has no effect
4633
- // for backend tests") already covers this case at create time.
4634
- if (opts.targetUrl !== undefined &&
4635
- opts.type !== 'backend' &&
4636
- triggerResponse.targetUrl !== opts.targetUrl) {
4637
- emitTargetUrlMismatchAdvisory(stderrFn, opts.targetUrl, triggerResponse.targetUrl);
4638
- }
4639
- if (!opts.wait) {
4640
- printRunOrChain(out, triggerResponse, opts.createContext, data => renderTriggerRunText(data));
4641
- if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
4642
- stderrFn(`requestId: ${triggerRequestId}`);
4643
- return triggerResponse;
4644
- }
4645
- // --wait path: poll until terminal.
4646
- const startMs = Date.now();
4647
- void resumedFromConflict; // used above; suppress unused-variable lint
4648
- const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
4649
- // B2(c): emit a one-time hint when the user did not explicitly set --timeout
4650
- // (i.e. the default is in effect). First runs can take several minutes;
4651
- // skipped when --output json (non-interactive consumers don't need the hint).
4652
- if (opts.timeoutIsDefault === true && opts.output !== 'json') {
4653
- stderrFn(`[hint] First runs can take several minutes; raise --timeout if this run is cut short.`);
4654
- }
4655
- // Backend-test fallback (dogfood L1888): BE run rows never finalize, so
4656
- // resolve the verdict from the testId record once it's terminal.
4657
- let beFallbackUsed = false;
4658
- const resolveAlternate = makeBackendWaitFallback({
4659
- client,
4660
- resolveTestId: () => opts.testId,
4661
- resolveNotBefore: () => triggerResponse.enqueuedAt,
4662
- onResolved: testId => {
4663
- beFallbackUsed = true;
4664
- stderrFn(`[advisory] Backend run-surface row is not finalized server-side (dogfood L1888); ` +
4665
- `resolved the verdict from the test record (testId=${testId}). ` +
4666
- `Read full detail with: testsprite test result ${testId}`);
4667
- },
4668
- });
4669
- let finalRun;
4670
- try {
4671
- finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
4672
- timeoutSeconds: opts.timeoutSeconds,
4673
- sleep: deps.sleep,
4674
- shutdown: shutdownOf(deps),
4675
- onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4676
- onTick: (run, elapsedMs) => {
4677
- const elapsed = Math.round(elapsedMs / 1000);
4678
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
4679
- ticker.update(`Run ${run.runId} — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
4947
+ if (!opts.wait) {
4948
+ printRunOrChain(out, triggerResponse, opts.createContext, data => renderTriggerRunText(data));
4949
+ if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
4950
+ stderrFn(`requestId: ${triggerRequestId}`);
4951
+ return triggerResponse;
4952
+ }
4953
+ // --wait path: poll until terminal.
4954
+ const startMs = Date.now();
4955
+ void resumedFromConflict; // used above; suppress unused-variable lint
4956
+ const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
4957
+ // B2(c): emit a one-time hint when the user did not explicitly set --timeout
4958
+ // (i.e. the default is in effect). First runs can take several minutes;
4959
+ // skipped when --output json (non-interactive consumers don't need the hint).
4960
+ if (opts.timeoutIsDefault === true && opts.output !== 'json') {
4961
+ stderrFn(`[hint] First runs can take several minutes; raise --timeout if this run is cut short.`);
4962
+ }
4963
+ // Backend-test fallback (dogfood L1888): BE run rows never finalize, so
4964
+ // resolve the verdict from the testId record once it's terminal.
4965
+ let beFallbackUsed = false;
4966
+ const resolveAlternate = makeBackendWaitFallback({
4967
+ client,
4968
+ resolveTestId: () => opts.testId,
4969
+ resolveNotBefore: () => triggerResponse.enqueuedAt,
4970
+ onResolved: testId => {
4971
+ beFallbackUsed = true;
4972
+ stderrFn(`[advisory] Backend run-surface row is not finalized server-side (dogfood L1888); ` +
4973
+ `resolved the verdict from the test record (testId=${testId}). ` +
4974
+ `Read full detail with: testsprite test result ${testId}`);
4680
4975
  },
4681
- resolveAlternate,
4682
4976
  });
4683
- }
4684
- catch (err) {
4685
- if (err instanceof TimeoutError) {
4686
- ticker.finalize(`Run ${triggerResponse.runId} — timed out after ${opts.timeoutSeconds}s`);
4687
- // Mirror the RequestTimeoutError path: emit a partial run to stdout so
4688
- // JSON consumers and AI agents can grab the runId and chain into
4689
- // `testsprite test wait <runId>` without parsing the stderr error envelope.
4690
- const timeoutPartial = {
4691
- runId: triggerResponse.runId,
4692
- status: 'running',
4693
- enqueuedAt: triggerResponse.enqueuedAt,
4694
- codeVersion: triggerResponse.codeVersion,
4695
- targetUrl: triggerResponse.targetUrl || null,
4696
- };
4697
- printRunOrChain(out, timeoutPartial, opts.createContext, data => {
4698
- const p = data;
4699
- const lines = [
4700
- `runId ${p.runId}`,
4701
- `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
4702
- ];
4703
- if (p.targetUrl)
4704
- lines.push(`targetUrl ${p.targetUrl}`);
4705
- lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4706
- lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4707
- return lines.join('\n');
4708
- });
4709
- throw ApiError.fromEnvelope({
4710
- error: {
4711
- code: 'UNSUPPORTED', // exit 7 per errors.md
4712
- message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}. ` +
4713
- stillRunningAndBillingSubject(triggerResponse.runId),
4714
- nextAction: `Resume polling: testsprite test wait ${triggerResponse.runId}, or cancel it: testsprite test cancel ${triggerResponse.runId}`,
4715
- requestId: 'local',
4716
- details: { runId: triggerResponse.runId, timeoutSeconds: opts.timeoutSeconds },
4977
+ // Keeps the elapsed counter moving between long-poll returns (~25s apart).
4978
+ // Armed only when the ticker redraws in place (its own TTY / NO_COLOR call).
4979
+ const live = createLiveRunProgress(ticker);
4980
+ let finalRun;
4981
+ try {
4982
+ finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
4983
+ timeoutSeconds: opts.timeoutSeconds,
4984
+ sleep: deps.sleep,
4985
+ shutdown,
4986
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4987
+ onTick: (run, elapsedMs) => {
4988
+ // The tunnel is checked on every tick rather than through an abort
4989
+ // signal because there is nothing to race: once the control channel
4990
+ // is terminally closed the run is already doomed, and one long-poll
4991
+ // cycle of latency costs far less than plumbing a second abort
4992
+ // source through the shared poll loop for every ordinary run.
4993
+ if (!isTerminalStatus(run.status)) {
4994
+ const fatal = tunnelSession?.fatalReason();
4995
+ if (fatal !== undefined)
4996
+ throw new TunnelLostError(fatal, triggerResponse.runId);
4997
+ }
4998
+ live.onTick(run, elapsedMs);
4717
4999
  },
5000
+ resolveAlternate,
4718
5001
  });
4719
5002
  }
4720
- // C+D: RequestTimeoutError during polling — emit a partial object to stdout
4721
- // routed through printRunOrChain so:
4722
- // TEXT mode: renders human-readable (not raw JSON)
4723
- // JSON mode: preserves the merged create-chain envelope
4724
- // { ...createContext, run: { runId, status, targetUrl } }
4725
- // targetUrl is taken from triggerResponse, which is already bound to
4726
- // the real in-flight URL (see Finding D fix in the 409 resume path).
4727
- if (err instanceof RequestTimeoutError) {
4728
- ticker.finalize(`Run ${triggerResponse.runId} — request timed out`);
4729
- const partial = {
4730
- runId: triggerResponse.runId,
4731
- status: 'running',
4732
- enqueuedAt: triggerResponse.enqueuedAt,
4733
- codeVersion: triggerResponse.codeVersion,
4734
- targetUrl: triggerResponse.targetUrl || null,
5003
+ catch (err) {
5004
+ // Stop redrawing BEFORE any final line below is written, so a stale
5005
+ // "running · Ns" can never land after "timed out" / "interrupted".
5006
+ live.stop();
5007
+ // A tunnel run that stops being waited on is a tunnel run that is about
5008
+ // to lose its tunnel, on ALL of these paths. `cancelOnInterrupt` defaults
5009
+ // ON here and only here — for an ordinary run, detaching leaves something
5010
+ // that can still pass, which is why DEV-331 deliberately did not cancel.
5011
+ const settleTunnelDetach = async (reason) => {
5012
+ if (tunnelSession === undefined || tunnelSession.adopted)
5013
+ return undefined;
5014
+ const cancel = await cancelDoomedTunnelRun({
5015
+ runId: triggerResponse.runId,
5016
+ enabled: opts.cancelOnInterrupt !== false,
5017
+ opts,
5018
+ deps,
5019
+ });
5020
+ return {
5021
+ runId: triggerResponse.runId,
5022
+ reason,
5023
+ cancel: cancel.outcome,
5024
+ ...(cancel.terminalStatus !== undefined ? { terminalStatus: cancel.terminalStatus } : {}),
5025
+ };
4735
5026
  };
4736
- printRunOrChain(out, partial, opts.createContext, data => {
4737
- const p = data;
4738
- const lines = [`runId ${p.runId}`, `status ${p.status} (request timed out)`];
4739
- if (p.targetUrl)
4740
- lines.push(`targetUrl ${p.targetUrl}`);
4741
- lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4742
- lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4743
- return lines.join('\n');
4744
- });
4745
- stderrFn(`Request timed out. ${stillRunningAndBillingSubject(triggerResponse.runId)} ` +
4746
- `Re-attach with: testsprite test wait ${triggerResponse.runId}, or cancel with: testsprite test cancel ${triggerResponse.runId}`);
5027
+ if (err instanceof TunnelLostError) {
5028
+ ticker.finalize(`Run ${triggerResponse.runId} — tunnel disconnected`);
5029
+ const detach = await settleTunnelDetach('tunnel-lost');
5030
+ const partial = {
5031
+ runId: triggerResponse.runId,
5032
+ status: detachPartialStatus(detach),
5033
+ enqueuedAt: triggerResponse.enqueuedAt,
5034
+ codeVersion: triggerResponse.codeVersion,
5035
+ targetUrl: triggerResponse.targetUrl || null,
5036
+ };
5037
+ printRunOrChain(out, partial, opts.createContext, data => {
5038
+ const pr = data;
5039
+ const lines = [
5040
+ `runId ${pr.runId}`,
5041
+ `status ${pr.status} (tunnel disconnected)`,
5042
+ ];
5043
+ if (pr.targetUrl)
5044
+ lines.push(`targetUrl ${pr.targetUrl}`);
5045
+ lines.push(...detachHintLines(pr.runId, detach));
5046
+ return lines.join('\n');
5047
+ });
5048
+ if (detach)
5049
+ stderrFn(tunnelDetachMessage(detach));
5050
+ throw err;
5051
+ }
5052
+ if (err instanceof TimeoutError) {
5053
+ ticker.finalize(`Run ${triggerResponse.runId} — timed out after ${opts.timeoutSeconds}s`);
5054
+ // Mirror the RequestTimeoutError path: emit a partial run to stdout so
5055
+ // JSON consumers and AI agents can grab the runId and chain into
5056
+ // `testsprite test wait <runId>` without parsing the stderr error envelope.
5057
+ const detach = await settleTunnelDetach('timeout');
5058
+ const timeoutPartial = {
5059
+ runId: triggerResponse.runId,
5060
+ status: detachPartialStatus(detach),
5061
+ enqueuedAt: triggerResponse.enqueuedAt,
5062
+ codeVersion: triggerResponse.codeVersion,
5063
+ targetUrl: triggerResponse.targetUrl || null,
5064
+ };
5065
+ printRunOrChain(out, timeoutPartial, opts.createContext, data => {
5066
+ const p = data;
5067
+ const lines = [
5068
+ `runId ${p.runId}`,
5069
+ `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
5070
+ ];
5071
+ if (p.targetUrl)
5072
+ lines.push(`targetUrl ${p.targetUrl}`);
5073
+ lines.push(...detachHintLines(p.runId, detach));
5074
+ return lines.join('\n');
5075
+ });
5076
+ if (detach)
5077
+ stderrFn(tunnelDetachMessage(detach));
5078
+ throw ApiError.fromEnvelope({
5079
+ error: {
5080
+ code: 'UNSUPPORTED', // exit 7 per errors.md
5081
+ message: detach
5082
+ ? `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}, ` +
5083
+ `which could not have finished without this process holding its tunnel open.`
5084
+ : `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}. ` +
5085
+ stillRunningAndBillingSubject(triggerResponse.runId),
5086
+ nextAction: detach
5087
+ ? `Start it again with --local and a longer --timeout; a retry mints a fresh tunnel.`
5088
+ : `Resume polling: testsprite test wait ${triggerResponse.runId}, or cancel it: testsprite test cancel ${triggerResponse.runId}`,
5089
+ requestId: 'local',
5090
+ details: { runId: triggerResponse.runId, timeoutSeconds: opts.timeoutSeconds },
5091
+ },
5092
+ });
5093
+ }
5094
+ // C+D: RequestTimeoutError during polling — emit a partial object to stdout
5095
+ // routed through printRunOrChain so:
5096
+ // TEXT mode: renders human-readable (not raw JSON)
5097
+ // JSON mode: preserves the merged create-chain envelope
5098
+ // { ...createContext, run: { runId, status, targetUrl } }
5099
+ // targetUrl is taken from triggerResponse, which is already bound to
5100
+ // the real in-flight URL (see Finding D fix in the 409 resume path).
5101
+ if (err instanceof RequestTimeoutError) {
5102
+ ticker.finalize(`Run ${triggerResponse.runId} — request timed out`);
5103
+ const detach = await settleTunnelDetach('request-timeout');
5104
+ const partial = {
5105
+ runId: triggerResponse.runId,
5106
+ status: detachPartialStatus(detach),
5107
+ enqueuedAt: triggerResponse.enqueuedAt,
5108
+ codeVersion: triggerResponse.codeVersion,
5109
+ targetUrl: triggerResponse.targetUrl || null,
5110
+ };
5111
+ printRunOrChain(out, partial, opts.createContext, data => {
5112
+ const p = data;
5113
+ const lines = [`runId ${p.runId}`, `status ${p.status} (request timed out)`];
5114
+ if (p.targetUrl)
5115
+ lines.push(`targetUrl ${p.targetUrl}`);
5116
+ lines.push(...detachHintLines(p.runId, detach));
5117
+ return lines.join('\n');
5118
+ });
5119
+ stderrFn(detach
5120
+ ? tunnelDetachMessage(detach)
5121
+ : `Request timed out. ${stillRunningAndBillingSubject(triggerResponse.runId)} ` +
5122
+ `Re-attach with: testsprite test wait ${triggerResponse.runId}, or cancel with: testsprite test cancel ${triggerResponse.runId}`);
5123
+ throw err;
5124
+ }
5125
+ // RATE_LIMITED during polling — the backend's pre-auth rate limiter can
5126
+ // trip on a shared egress IP (CI runner, NAT) and 429 an otherwise-valid
5127
+ // key for its window; the HTTP layer already retried internally and gave
5128
+ // up. The run was already triggered (and billed) and keeps executing
5129
+ // server-side, so this must not be a silent, runId-less death: same
5130
+ // partial-envelope contract as the RequestTimeoutError branch above, and
5131
+ // the SAME thrown ApiError is rethrown unchanged so its native exit code
5132
+ // (11) is preserved — never reclassified to 7.
5133
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
5134
+ ticker.finalize(`Run ${triggerResponse.runId} — rate limited by the server`);
5135
+ // The cancel this issues is itself a request to the same rate-limited
5136
+ // API, so it may well be refused. `cancelDoomedTunnelRun` reports that
5137
+ // honestly and the message names `test cancel` rather than claiming a
5138
+ // cancel that did not happen.
5139
+ const detach = await settleTunnelDetach('rate-limited');
5140
+ const partial = {
5141
+ runId: triggerResponse.runId,
5142
+ status: detachPartialStatus(detach),
5143
+ enqueuedAt: triggerResponse.enqueuedAt,
5144
+ codeVersion: triggerResponse.codeVersion,
5145
+ targetUrl: triggerResponse.targetUrl || null,
5146
+ };
5147
+ printRunOrChain(out, partial, opts.createContext, data => {
5148
+ const p = data;
5149
+ const lines = [
5150
+ `runId ${p.runId}`,
5151
+ `status ${p.status} (rate limited by the server)`,
5152
+ ];
5153
+ if (p.targetUrl)
5154
+ lines.push(`targetUrl ${p.targetUrl}`);
5155
+ lines.push(...detachHintLines(p.runId, detach));
5156
+ return lines.join('\n');
5157
+ });
5158
+ stderrFn(detach
5159
+ ? tunnelDetachMessage(detach)
5160
+ : rateLimitedDetachMessage(err, [triggerResponse.runId]));
5161
+ throw err;
5162
+ }
5163
+ // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1): same partial-
5164
+ // envelope shape as the timeout paths so stdout stays parseable, plus the
5165
+ // honest "keeps running and billing" stderr line. Rethrow → index.ts
5166
+ // renders the INTERRUPTED envelope and exits 128+signum.
5167
+ if (err instanceof InterruptError) {
5168
+ ticker.finalize(`Run ${triggerResponse.runId} — interrupted (${err.signal})`);
5169
+ const detach = await settleTunnelDetach('interrupt');
5170
+ const partial = {
5171
+ runId: triggerResponse.runId,
5172
+ status: detachPartialStatus(detach),
5173
+ enqueuedAt: triggerResponse.enqueuedAt,
5174
+ codeVersion: triggerResponse.codeVersion,
5175
+ targetUrl: triggerResponse.targetUrl || null,
5176
+ };
5177
+ printRunOrChain(out, partial, opts.createContext, data => {
5178
+ const p = data;
5179
+ const lines = [`runId ${p.runId}`, `status ${p.status} (interrupted)`];
5180
+ if (p.targetUrl)
5181
+ lines.push(`targetUrl ${p.targetUrl}`);
5182
+ lines.push(...detachHintLines(p.runId, detach));
5183
+ return lines.join('\n');
5184
+ });
5185
+ stderrFn(detach
5186
+ ? tunnelDetachMessage(detach)
5187
+ : interruptDetachMessage(err, [triggerResponse.runId]));
5188
+ if (detach !== undefined)
5189
+ attachTunnelInterruptDetach(err, detach);
5190
+ throw err;
5191
+ }
5192
+ // Any other poll failure still leaves us holding a known, charged runId.
5193
+ // An owned tunnel is about to close in the outer finally, so settle the
5194
+ // run exactly like the classified detach paths before preserving the
5195
+ // original error object/type/code/message for the caller.
5196
+ const detach = await settleTunnelDetach('poll-error');
5197
+ if (detach !== undefined) {
5198
+ ticker.finalize(`Run ${triggerResponse.runId} — polling stopped`);
5199
+ const partial = {
5200
+ runId: triggerResponse.runId,
5201
+ status: detachPartialStatus(detach),
5202
+ enqueuedAt: triggerResponse.enqueuedAt,
5203
+ codeVersion: triggerResponse.codeVersion,
5204
+ targetUrl: triggerResponse.targetUrl || null,
5205
+ };
5206
+ printRunOrChain(out, partial, opts.createContext, data => {
5207
+ const p = data;
5208
+ const lines = [`runId ${p.runId}`, `status ${p.status} (polling stopped)`];
5209
+ if (p.targetUrl)
5210
+ lines.push(`targetUrl ${p.targetUrl}`);
5211
+ lines.push(...detachHintLines(p.runId, detach));
5212
+ return lines.join('\n');
5213
+ });
5214
+ stderrFn(tunnelDetachMessage(detach));
5215
+ }
5216
+ else {
5217
+ ticker.finalize();
5218
+ }
4747
5219
  throw err;
4748
5220
  }
4749
- // RATE_LIMITED during polling — the backend's pre-auth rate limiter can
4750
- // trip on a shared egress IP (CI runner, NAT) and 429 an otherwise-valid
4751
- // key for its window; the HTTP layer already retried internally and gave
4752
- // up. The run was already triggered (and billed) and keeps executing
4753
- // server-side, so this must not be a silent, runId-less death: same
4754
- // partial-envelope contract as the RequestTimeoutError branch above, and
4755
- // the SAME thrown ApiError is rethrown unchanged so its native exit code
4756
- // (11) is preserved — never reclassified to 7.
4757
- if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
4758
- ticker.finalize(`Run ${triggerResponse.runId} — rate limited by the server`);
4759
- const partial = {
4760
- runId: triggerResponse.runId,
4761
- status: 'running',
4762
- enqueuedAt: triggerResponse.enqueuedAt,
4763
- codeVersion: triggerResponse.codeVersion,
4764
- targetUrl: triggerResponse.targetUrl || null,
4765
- };
4766
- printRunOrChain(out, partial, opts.createContext, data => {
4767
- const p = data;
4768
- const lines = [
4769
- `runId ${p.runId}`,
4770
- `status ${p.status} (rate limited by the server)`,
4771
- ];
4772
- if (p.targetUrl)
4773
- lines.push(`targetUrl ${p.targetUrl}`);
4774
- lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4775
- lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4776
- return lines.join('\n');
4777
- });
4778
- stderrFn(rateLimitedDetachMessage(err, [triggerResponse.runId]));
4779
- throw err;
5221
+ finally {
5222
+ live.stop();
5223
+ }
5224
+ ticker.finalize(formatRunProgressLine(finalRun, Date.now() - startMs));
5225
+ // BE detection: type hint (create-chain) OR beFallbackUsed (slow runs); on
5226
+ // the standalone `test run <id>` path neither is set, so probe the test type
5227
+ // once (text mode only, best-effort) — DEV-282.
5228
+ const isBackend = await resolveRunCardIsBackend(client, opts.testId, opts.output, beFallbackUsed || opts.type === 'backend');
5229
+ const finalRunWithUrl = withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps));
5230
+ printRunOrChain(out, finalRunWithUrl, opts.createContext, data => renderRunResponseText(data, { isBackend }));
5231
+ // Surface the trigger requestId under --verbose/--debug or JSON mode so
5232
+ // operators can trace the full lifecycle (gated since 2026-06-04 dogfood;
5233
+ // JSON mode always emits to stderr — it never pollutes stdout).
5234
+ if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
5235
+ stderrFn(`requestId: ${triggerRequestId}`);
5236
+ if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
5237
+ // BE runs have no run-scoped artifact bundle — their failure bundle is
5238
+ // addressed by testId, not runId.
5239
+ stderrFn(isBackend
5240
+ ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${finalRun.testId}' to download the bundle.`
5241
+ : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
4780
5242
  }
4781
- // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1): same partial-
4782
- // envelope shape as the timeout paths so stdout stays parseable, plus the
4783
- // honest "keeps running and billing" stderr line. Rethrow → index.ts
4784
- // renders the INTERRUPTED envelope and exits 128+signum.
4785
- if (err instanceof InterruptError) {
4786
- ticker.finalize(`Run ${triggerResponse.runId} — interrupted (${err.signal})`);
4787
- const partial = {
4788
- runId: triggerResponse.runId,
4789
- status: 'running',
4790
- enqueuedAt: triggerResponse.enqueuedAt,
4791
- codeVersion: triggerResponse.codeVersion,
4792
- targetUrl: triggerResponse.targetUrl || null,
4793
- };
4794
- printRunOrChain(out, partial, opts.createContext, data => {
4795
- const p = data;
4796
- const lines = [`runId ${p.runId}`, `status ${p.status} (interrupted)`];
4797
- if (p.targetUrl)
4798
- lines.push(`targetUrl ${p.targetUrl}`);
4799
- lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4800
- lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4801
- return lines.join('\n');
4802
- });
4803
- stderrFn(interruptDetachMessage(err, [triggerResponse.runId]));
4804
- throw err;
5243
+ // CI-native output layer (issue #99): single-test parity with the --all batch.
5244
+ // Emitted before the exit-code gate throws below so the summary file and
5245
+ // annotations land even when the run exits non-zero (mirrors the batch path).
5246
+ // The summary file is a machine artifact written regardless of --output mode;
5247
+ // under --output json the run envelope above owns stdout, so ::error::
5248
+ // workflow commands are routed to stderr (the Actions runner parses both).
5249
+ // Best-effort: a sink write throwing (e.g. EPIPE) must never skip the
5250
+ // exit-code gate below or change the command's exit status.
5251
+ try {
5252
+ emitCiArtifacts(summarizeSingleRun(finalRunWithUrl), opts, {
5253
+ env: deps.env ?? process.env,
5254
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
5255
+ stderr: stderrFn,
5256
+ }, 'run');
4805
5257
  }
4806
- ticker.finalize();
4807
- throw err;
4808
- }
4809
- const elapsed = Math.round((Date.now() - startMs) / 1000);
4810
- const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
4811
- ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
4812
- // BE detection: type hint (create-chain) OR beFallbackUsed (slow runs); on
4813
- // the standalone `test run <id>` path neither is set, so probe the test type
4814
- // once (text mode only, best-effort) — DEV-282.
4815
- const isBackend = await resolveRunCardIsBackend(client, opts.testId, opts.output, beFallbackUsed || opts.type === 'backend');
4816
- const finalRunWithUrl = withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps));
4817
- printRunOrChain(out, finalRunWithUrl, opts.createContext, data => renderRunResponseText(data, { isBackend }));
4818
- // Surface the trigger requestId under --verbose/--debug or JSON mode so
4819
- // operators can trace the full lifecycle (gated since 2026-06-04 dogfood;
4820
- // JSON mode always emits to stderr — it never pollutes stdout).
4821
- if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
4822
- stderrFn(`requestId: ${triggerRequestId}`);
4823
- if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
4824
- // BE runs have no run-scoped artifact bundle — their failure bundle is
4825
- // addressed by testId, not runId.
4826
- stderrFn(isBackend
4827
- ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${finalRun.testId}' to download the bundle.`
4828
- : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
4829
- }
4830
- // CI-native output layer (issue #99): single-test parity with the --all batch.
4831
- // Emitted before the exit-code gate throws below so the summary file and
4832
- // annotations land even when the run exits non-zero (mirrors the batch path).
4833
- // The summary file is a machine artifact written regardless of --output mode;
4834
- // under --output json the run envelope above owns stdout, so ::error::
4835
- // workflow commands are routed to stderr (the Actions runner parses both).
4836
- // Best-effort: a sink write throwing (e.g. EPIPE) must never skip the
4837
- // exit-code gate below or change the command's exit status.
4838
- try {
4839
- emitCiArtifacts(summarizeSingleRun(finalRunWithUrl), opts, {
4840
- env: deps.env ?? process.env,
4841
- stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
4842
- stderr: stderrFn,
4843
- }, 'run');
4844
- }
4845
- catch (ciErr) {
4846
- stderrFn(`[run] CI output emission failed; continuing: ${ciErr.message}`);
5258
+ catch (ciErr) {
5259
+ stderrFn(`[run] CI output emission failed; continuing: ${ciErr.message}`);
5260
+ }
5261
+ const exitCode = exitCodeForRunStatus(finalRun.status);
5262
+ if (exitCode !== 0) {
5263
+ // Throw a CLIError so index.ts exits with the right code without
5264
+ // printing an error envelope — the result was already printed above.
5265
+ throw new CLIError(`Run ${finalRun.runId} finished with status: ${finalRun.status}`, exitCode);
5266
+ }
5267
+ return finalRun;
4847
5268
  }
4848
- const exitCode = exitCodeForRunStatus(finalRun.status);
4849
- if (exitCode !== 0) {
4850
- // Throw a CLIError so index.ts exits with the right code without
4851
- // printing an error envelope — the result was already printed above.
4852
- throw new CLIError(`Run ${finalRun.runId} finished with status: ${finalRun.status}`, exitCode);
5269
+ finally {
5270
+ // Every exit path — success, run failure, timeout, signal, a throw from
5271
+ // the trigger itself — releases the tunnel and deletes the binding.
5272
+ // Skipping this on any one of them leaves a live inbound credential and a
5273
+ // client whose ref'd heartbeat timer keeps the process alive after the
5274
+ // command has printed its last line.
5275
+ try {
5276
+ await tunnelSession?.close();
5277
+ }
5278
+ finally {
5279
+ disarmTunnelLifecycle?.();
5280
+ }
4853
5281
  }
4854
- return finalRun;
4855
5282
  }
4856
5283
  /**
4857
5284
  * `test wait <run-id...>` with two or more ids: attach to N already-dispatched
@@ -5292,6 +5719,9 @@ export async function runTestWait(opts, deps = {}) {
5292
5719
  `Read full detail with: testsprite test result ${testId}`);
5293
5720
  },
5294
5721
  });
5722
+ // Keeps the elapsed counter moving between long-poll returns (~25s apart).
5723
+ // Armed only when the ticker redraws in place (its own TTY / NO_COLOR call).
5724
+ const live = createLiveRunProgress(ticker);
5295
5725
  let finalRun;
5296
5726
  try {
5297
5727
  finalRun = await pollRunUntilTerminal(client, opts.runId, {
@@ -5299,15 +5729,14 @@ export async function runTestWait(opts, deps = {}) {
5299
5729
  sleep: deps.sleep,
5300
5730
  shutdown: shutdownOf(deps),
5301
5731
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
5302
- onTick: (run, elapsedMs) => {
5303
- const elapsed = Math.round(elapsedMs / 1000);
5304
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
5305
- ticker.update(`Run ${run.runId} — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
5306
- },
5732
+ onTick: live.onTick,
5307
5733
  resolveAlternate,
5308
5734
  });
5309
5735
  }
5310
5736
  catch (err) {
5737
+ // Stop redrawing BEFORE any final line below is written, so a stale
5738
+ // "running · Ns" can never land after "timed out" / "interrupted".
5739
+ live.stop();
5311
5740
  if (err instanceof TimeoutError) {
5312
5741
  ticker.finalize(`Run ${opts.runId} — timed out after ${opts.timeoutSeconds}s`);
5313
5742
  // Mirror the RequestTimeoutError path: emit a partial run to stdout so
@@ -5392,9 +5821,10 @@ export async function runTestWait(opts, deps = {}) {
5392
5821
  ticker.finalize();
5393
5822
  throw err;
5394
5823
  }
5395
- const elapsed = Math.round((Date.now() - startMs) / 1000);
5396
- const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
5397
- ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
5824
+ finally {
5825
+ live.stop();
5826
+ }
5827
+ ticker.finalize(formatRunProgressLine(finalRun, Date.now() - startMs));
5398
5828
  // `test wait` has no type hint; probe the test type once (text mode only,
5399
5829
  // best-effort) so a backend run's card reads `n/a (backend)` — DEV-282.
5400
5830
  const isBackend = await resolveRunCardIsBackend(client, finalRun.testId, opts.output, beFallbackUsed);
@@ -5447,16 +5877,20 @@ async function buildTestNameMap(client, projectId) {
5447
5877
  }
5448
5878
  return map;
5449
5879
  }
5450
- async function writeBatchJUnitReportIfRequested(opts, results, nameByTestId) {
5880
+ export async function writeBatchJUnitReportIfRequested(opts, results, nameByTestId) {
5451
5881
  if (opts.report !== 'junit' || opts.reportFile === undefined)
5452
5882
  return;
5453
5883
  const projectId = resolveBatchReportProjectId(opts, results);
5454
5884
  const suiteName = opts.reportSuiteName ?? `testsprite:${projectId}`;
5455
5885
  // Enrich each row with the human name (from the map) and the run duration
5456
5886
  // (from poll timing) — the two fields whose absence made the report unreadable.
5887
+ // Name precedence: the sweep map wins (it's a full page scan), then the poll
5888
+ // response's own `testTitle` (same source the summary table uses — this keeps
5889
+ // the two surfaces on the same name when the sweep over-pages / times out),
5890
+ // then the row's fallback name. `.trim() ||` so a blank title never shadows it.
5457
5891
  const enriched = results.map(r => ({
5458
5892
  ...r,
5459
- name: nameByTestId?.get(r.testId) ?? r.name,
5893
+ name: nameByTestId?.get(r.testId) ?? (r.testTitle?.trim() ? r.testTitle : undefined) ?? r.name,
5460
5894
  durationSeconds: r.durationSeconds ?? durationSecondsBetween(r.startedAt, r.finishedAt),
5461
5895
  }));
5462
5896
  const xml = buildJUnitReport({
@@ -5466,6 +5900,70 @@ async function writeBatchJUnitReportIfRequested(opts, results, nameByTestId) {
5466
5900
  });
5467
5901
  await writeJUnitReportFile(opts.reportFile, xml);
5468
5902
  }
5903
+ /** Human explanation for a zero-dispatch batch, from what the engine skipped. */
5904
+ function zeroDispatchReason(skippedFrontend, skippedIntegration) {
5905
+ const parts = [];
5906
+ if (skippedFrontend.length > 0) {
5907
+ parts.push(`${skippedFrontend.length} frontend test${skippedFrontend.length !== 1 ? 's' : ''} skipped (the batch engine is BE-only for FE tests — run them with 'test run <id>')`);
5908
+ }
5909
+ if (skippedIntegration.length > 0) {
5910
+ parts.push(`${skippedIntegration.length} assembled integration test${skippedIntegration.length !== 1 ? 's' : ''} skipped (run via the portal)`);
5911
+ }
5912
+ return parts.length > 0
5913
+ ? `all resolved tests were skipped: ${parts.join('; ')}`
5914
+ : 'no runnable tests in the project';
5915
+ }
5916
+ /**
5917
+ * Handle a batch invocation that dispatched ZERO tests — all skipped, an empty
5918
+ * project, or a `--filter` that matched nothing. Left alone this exits 0 with no
5919
+ * artifact, a CI false-green: a gate that greens on zero tests is worse than no
5920
+ * gate (DEV-1046). So it emits the CI artifacts (summary + `::error::` annotation
5921
+ * + JUnit report) so the gate shows WHY, then fails with **exit 5** unless the
5922
+ * caller passed `--allow-empty` (in which case it returns and the caller exits 0).
5923
+ *
5924
+ * `skipped` is the union of skipped FE + integration tests (rendered as
5925
+ * `<skipped/>` JUnit cases and non-passed summary rows so they're visible);
5926
+ * `reason` is the human explanation shown in the annotation and the throw.
5927
+ */
5928
+ async function finishZeroDispatchBatch(params) {
5929
+ const { reason, skipped, allowEmpty, opts, deps, stderrFn, label = 'run' } = params;
5930
+ const runs = skipped.length > 0
5931
+ ? skipped.map(testId => ({ testId, status: 'skipped', error: reason }))
5932
+ : [{ testId: '(no tests)', status: 'no_tests', error: reason }];
5933
+ const summary = {
5934
+ total: runs.length,
5935
+ passed: 0,
5936
+ failed: runs.length,
5937
+ timedOut: 0,
5938
+ runs,
5939
+ };
5940
+ // Emit the in-memory artifacts (summary + `::error::` annotation) FIRST: they
5941
+ // can't fail on I/O, so the "show WHY it's red" diagnostics always land — even
5942
+ // if the JUnit path below is misconfigured. Ordering these after the file write
5943
+ // would let an unwritable --report-file throw (exit 10) preempt both the
5944
+ // diagnostics AND the exit-5 gate, masking the zero-dispatch cause.
5945
+ emitCiArtifacts(summary, opts, {
5946
+ env: deps.env ?? process.env,
5947
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
5948
+ stderr: stderrFn,
5949
+ }, label);
5950
+ // Then the JUnit sidecar (the other half of "no artifact was produced before").
5951
+ // `writeBatchJUnitReportIfRequested` no-ops unless --report junit. Degrade a
5952
+ // write failure to a warning so an unwritable path can't mask the exit-5 intent
5953
+ // with an I/O exit code.
5954
+ try {
5955
+ await writeBatchJUnitReportIfRequested(opts, runs.map(r => ({ testId: r.testId, status: 'skipped' })));
5956
+ }
5957
+ catch (err) {
5958
+ stderrFn(`[${label}] could not write the JUnit report on a zero-dispatch run: ${err instanceof Error ? err.message : String(err)}; continuing`);
5959
+ }
5960
+ if (allowEmpty) {
5961
+ stderrFn(`[${label}] 0 tests dispatched (${reason}); --allow-empty set — exiting 0.`);
5962
+ return;
5963
+ }
5964
+ throw new CLIError(`No tests were dispatched — ${reason}. A CI gate that passes on zero tests is unsafe; ` +
5965
+ `pass --allow-empty to exit 0 intentionally.`, 5);
5966
+ }
5469
5967
  /**
5470
5968
  * `test run --all --project <id>` — M4 piece-2.
5471
5969
  *
@@ -5528,6 +6026,16 @@ export async function runTestRunAll(opts, deps = {}) {
5528
6026
  ? undefined
5529
6027
  : `${batchPortalBase}/dashboard/tests/${encodeURIComponent(projectId)}`;
5530
6028
  const withBatchDashboardUrl = (item) => {
6029
+ // Prefer the SERVER-built link the poll already captured onto the row — only
6030
+ // the server knows which store answered and can resolve a non-prod origin, and
6031
+ // for a V3-native project the client's V2-shaped guess is structurally dead
6032
+ // (the same footgun that 404'd MCP report links for months). Fall back to the
6033
+ // client guess only when the server sent none (older backend). `executionUrl`,
6034
+ // when present, rides through untouched — it is never client-built.
6035
+ // TODO: drop the resolvePortalUrl fallback once the server dashboardUrl has
6036
+ // shipped in every environment — it only serves runs from an older backend.
6037
+ if (typeof item.dashboardUrl === 'string')
6038
+ return item;
5531
6039
  const dashboardUrl = resolvePortalUrl(batchApiUrl, projectId, item.testId);
5532
6040
  return dashboardUrl !== undefined ? { ...item, dashboardUrl } : item;
5533
6041
  };
@@ -5559,6 +6067,17 @@ export async function runTestRunAll(opts, deps = {}) {
5559
6067
  skippedFrontend: [],
5560
6068
  skippedIntegration: [],
5561
6069
  });
6070
+ // Zero-dispatch (a --filter that matched nothing): emit the CI artifacts
6071
+ // and fail unless --allow-empty, so a renamed test can't turn a filtered
6072
+ // gate permanently green (DEV-1046). Returns here only under --allow-empty.
6073
+ await finishZeroDispatchBatch({
6074
+ reason: `--filter "${opts.nameFilter}" matched no tests in project ${projectId}`,
6075
+ skipped: [],
6076
+ allowEmpty: opts.allowEmpty === true,
6077
+ opts,
6078
+ deps,
6079
+ stderrFn,
6080
+ });
5562
6081
  return undefined;
5563
6082
  }
5564
6083
  stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${projectId} for batch run.`);
@@ -5642,6 +6161,18 @@ export async function runTestRunAll(opts, deps = {}) {
5642
6161
  },
5643
6162
  });
5644
6163
  }
6164
+ // Zero dispatched, nothing pending (deferred / conflict already threw above):
6165
+ // all tests were skipped, or the project has none. Don't exit 0 (DEV-1046).
6166
+ if (accepted.length === 0) {
6167
+ await finishZeroDispatchBatch({
6168
+ reason: zeroDispatchReason(skippedFrontend, skippedIntegration),
6169
+ skipped: [...skippedFrontend, ...skippedIntegration.map(s => s.testId)],
6170
+ allowEmpty: opts.allowEmpty === true,
6171
+ opts,
6172
+ deps,
6173
+ stderrFn,
6174
+ });
6175
+ }
5645
6176
  // [P2] Return post-retry state so programmatic callers and the create-chain
5646
6177
  // JSON merge reflect what was actually dispatched, not the stale initial resp.
5647
6178
  return { ...batchResp, accepted, deferred, conflicts };
@@ -5791,17 +6322,17 @@ export async function runTestRunAll(opts, deps = {}) {
5791
6322
  skippedIntegration,
5792
6323
  };
5793
6324
  out.print(finalResp);
5794
- // Nothing was dispatched, but a --wait CI run still needs the exit-6/7 to be
5795
- // visible: emit annotations + summary before the throw below (conflicts /
5796
- // deferred fold into the summary as non-passed rows; skipped* are not folded).
5797
- // Without this an all-in-flight or all-deferred batch fails CI silently.
5798
- emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(finalResp)), opts, {
5799
- env: deps.env ?? process.env,
5800
- stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
5801
- stderr: stderrFn,
5802
- }, 'run');
5803
6325
  // Nothing to poll: surface deferred (rate-limit → exit 7) or all-conflict (exit 6),
5804
6326
  // mirroring the non-wait path so `--wait` never silently exits 0 on a no-op batch.
6327
+ // Emit the deferred/conflict summary + annotations first so CI shows them (the
6328
+ // pure zero-dispatch fall-through emits its OWN skipped-rows summary below).
6329
+ if (deferred.length > 0 || conflicts.length > 0) {
6330
+ emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(finalResp)), opts, {
6331
+ env: deps.env ?? process.env,
6332
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
6333
+ stderr: stderrFn,
6334
+ }, 'run');
6335
+ }
5805
6336
  if (deferred.length > 0) {
5806
6337
  throw new CLIError(`Batch run incomplete: ${deferred.length} test${deferred.length !== 1 ? 's' : ''} rate-deferred (per-key run budget) — retry these individually after ~60s: ${deferred.map(d => d.testId).join(' ')}`, 7);
5807
6338
  }
@@ -5816,7 +6347,18 @@ export async function runTestRunAll(opts, deps = {}) {
5816
6347
  },
5817
6348
  });
5818
6349
  }
5819
- // [P2] Return post-retry state.
6350
+ // Reached only when nothing was queued and nothing is pending: all tests were
6351
+ // skipped, or the project has none. Emit a skipped-rows summary + JUnit and
6352
+ // fail unless --allow-empty — never a silent exit 0 (DEV-1046).
6353
+ await finishZeroDispatchBatch({
6354
+ reason: zeroDispatchReason(skippedFrontend, skippedIntegration),
6355
+ skipped: [...skippedFrontend, ...skippedIntegration.map(s => s.testId)],
6356
+ allowEmpty: opts.allowEmpty === true,
6357
+ opts,
6358
+ deps,
6359
+ stderrFn,
6360
+ });
6361
+ // [P2] Return post-retry state (reached only under --allow-empty).
5820
6362
  return { ...batchResp, accepted, deferred, conflicts };
5821
6363
  }
5822
6364
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
@@ -5855,9 +6397,16 @@ export async function runTestRunAll(opts, deps = {}) {
5855
6397
  });
5856
6398
  return {
5857
6399
  testId: entry.testId,
6400
+ testTitle: finalRun.testTitle ?? null,
5858
6401
  runId,
5859
6402
  projectId: finalRun.projectId,
5860
6403
  status: finalRun.status,
6404
+ ...(typeof finalRun.dashboardUrl === 'string'
6405
+ ? { dashboardUrl: finalRun.dashboardUrl }
6406
+ : {}),
6407
+ ...(typeof finalRun.executionUrl === 'string'
6408
+ ? { executionUrl: finalRun.executionUrl }
6409
+ : {}),
5861
6410
  };
5862
6411
  }
5863
6412
  catch {
@@ -5887,18 +6436,21 @@ export async function runTestRunAll(opts, deps = {}) {
5887
6436
  sleep: deps.sleep,
5888
6437
  shutdown: shutdownOf(deps),
5889
6438
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
5890
- onTick: (run, elapsedMs) => {
5891
- const elapsed = Math.round(elapsedMs / 1000);
5892
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
5893
- ticker.update(`Run ${run.runId} (${entry.testId}) — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
5894
- },
6439
+ onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`)),
5895
6440
  resolveAlternate,
5896
6441
  });
5897
6442
  return {
5898
6443
  testId: entry.testId,
6444
+ testTitle: finalRun.testTitle ?? null,
5899
6445
  runId,
5900
6446
  projectId: finalRun.projectId,
5901
6447
  status: finalRun.status,
6448
+ ...(typeof finalRun.dashboardUrl === 'string'
6449
+ ? { dashboardUrl: finalRun.dashboardUrl }
6450
+ : {}),
6451
+ ...(typeof finalRun.executionUrl === 'string'
6452
+ ? { executionUrl: finalRun.executionUrl }
6453
+ : {}),
5902
6454
  startedAt: finalRun.startedAt,
5903
6455
  finishedAt: finalRun.finishedAt,
5904
6456
  };
@@ -6362,16 +6914,7 @@ export async function runTestRerun(opts, deps = {}) {
6362
6914
  sleep: deps.sleep,
6363
6915
  shutdown: shutdownOf(deps),
6364
6916
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
6365
- onTick: (run, elapsedMs) => {
6366
- const elapsed = Math.round(elapsedMs / 1000);
6367
- const s = run.stepSummary ?? {
6368
- total: 0,
6369
- completed: 0,
6370
- passedCount: 0,
6371
- failedCount: 0,
6372
- };
6373
- ticker.update(`Run ${run.runId} [${member.role}] — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
6374
- },
6917
+ onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `[${member.role}]`)),
6375
6918
  resolveAlternate,
6376
6919
  });
6377
6920
  return { kind: 'terminal', run: finalRun };
@@ -6636,6 +7179,7 @@ export async function runTestRerun(opts, deps = {}) {
6636
7179
  `resolved the verdict from the test record (testId=${tid}).`);
6637
7180
  },
6638
7181
  });
7182
+ const replayStartMs = Date.now();
6639
7183
  let finalRun;
6640
7184
  try {
6641
7185
  finalRun = await pollRunUntilTerminal(client, rerunResp.runId, {
@@ -6643,11 +7187,7 @@ export async function runTestRerun(opts, deps = {}) {
6643
7187
  sleep: deps.sleep,
6644
7188
  shutdown: shutdownOf(deps),
6645
7189
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
6646
- onTick: (run, elapsedMs) => {
6647
- const elapsed = Math.round(elapsedMs / 1000);
6648
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
6649
- ticker.update(`Run ${run.runId} — ${run.status} (${s.completed}/${s.total} steps replay elapsed=${elapsed}s)`);
6650
- },
7190
+ onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, '(replay)')),
6651
7191
  resolveAlternate,
6652
7192
  });
6653
7193
  }
@@ -6732,10 +7272,7 @@ export async function runTestRerun(opts, deps = {}) {
6732
7272
  ticker.finalize();
6733
7273
  throw err;
6734
7274
  }
6735
- const elapsed = Math.round(Date.now() / 1000);
6736
- void elapsed;
6737
- const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
6738
- ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps replay)`);
7275
+ ticker.finalize(formatRunProgressLine(finalRun, Date.now() - replayStartMs, '(replay)'));
6739
7276
  // Probe the test type once (text mode only, best-effort) so a backend
6740
7277
  // rerun's card reads `n/a (backend)` even when the fallback never fired
6741
7278
  // (BE run rows finalize server-side now) — DEV-282.
@@ -7166,18 +7703,21 @@ export async function runTestRerun(opts, deps = {}) {
7166
7703
  sleep: deps.sleep,
7167
7704
  shutdown: shutdownOf(deps),
7168
7705
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
7169
- onTick: (run, elapsedMs) => {
7170
- const elapsed = Math.round(elapsedMs / 1000);
7171
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
7172
- ticker.update(`Run ${run.runId} (${entry.testId}) — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
7173
- },
7706
+ onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`)),
7174
7707
  resolveAlternate,
7175
7708
  });
7176
7709
  return {
7177
7710
  testId: entry.testId,
7711
+ testTitle: finalRun.testTitle ?? null,
7178
7712
  runId: entry.runId,
7179
7713
  projectId: finalRun.projectId,
7180
7714
  status: finalRun.status,
7715
+ ...(typeof finalRun.dashboardUrl === 'string'
7716
+ ? { dashboardUrl: finalRun.dashboardUrl }
7717
+ : {}),
7718
+ ...(typeof finalRun.executionUrl === 'string'
7719
+ ? { executionUrl: finalRun.executionUrl }
7720
+ : {}),
7181
7721
  };
7182
7722
  }
7183
7723
  catch (err) {
@@ -7617,9 +8157,10 @@ export function createTestCommand(deps = {}) {
7617
8157
  .option('--name <name>', 'human-readable test name (becomes `title` in storage)')
7618
8158
  .option('--description <text>', 'optional human description (≤ 2000 chars)')
7619
8159
  .option('--priority <prio>', 'optional priority — one of: p0, p1, p2, p3')
8160
+ .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000); applied by the execution engine to every step of this test')
7620
8161
  .option('--code-file <path>', 'file containing the test code (≤ 350 KB)')
7621
8162
  .option('--plan-from <path>', 'JSON file with the full FE test definition — projectId, type, name, planSteps[] all live in the file ' +
7622
- '(≤ 256 KB; mutually exclusive with --code-file). In this mode --project/--type/--name/--description/--priority are ignored.')
8163
+ '(≤ 256 KB; mutually exclusive with --code-file). In this mode --project/--type/--name/--description/--priority/--step-timeout are ignored.')
7623
8164
  .option('--plan-template', 'print a minimal valid plan-file skeleton to stdout and exit (pure-local: no network, no credentials, ' +
7624
8165
  'ignores every other flag). Pipe to a file and edit: `--plan-template > plan.json`.', false)
7625
8166
  .option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
@@ -7684,6 +8225,8 @@ export function createTestCommand(deps = {}) {
7684
8225
  ignored.push('--description');
7685
8226
  if (cmdOpts.priority !== undefined)
7686
8227
  ignored.push('--priority');
8228
+ if (cmdOpts.stepTimeout !== undefined)
8229
+ ignored.push('--step-timeout');
7687
8230
  await runCreateFromPlan({
7688
8231
  ...resolveCommonOptions(command),
7689
8232
  planFrom: cmdOpts.planFrom,
@@ -7706,6 +8249,7 @@ export function createTestCommand(deps = {}) {
7706
8249
  name: cmdOpts.name,
7707
8250
  description: cmdOpts.description,
7708
8251
  priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
8252
+ stepTimeoutMs: parseStepTimeoutFlag(cmdOpts.stepTimeout, 'step-timeout'),
7709
8253
  codeFile: cmdOpts.codeFile,
7710
8254
  idempotencyKey: cmdOpts.idempotencyKey,
7711
8255
  // M3.3 chain flags:
@@ -7873,22 +8417,29 @@ export function createTestCommand(deps = {}) {
7873
8417
  });
7874
8418
  test
7875
8419
  .command('update <test-id>')
7876
- .description('Update test metadata — name, description, priority')
8420
+ .description('Update test metadata — name, description, priority, step timeout')
7877
8421
  .option('--name <name>', 'new human-readable test name')
7878
8422
  .option('--description <text>', 'new human description (≤ 2000 chars)')
7879
8423
  .option('--priority <prio>', 'new priority — one of: p0, p1, p2, p3')
8424
+ .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000); applied by the execution engine to every step of this test')
8425
+ .option('--clear-step-timeout', 'clear the per-test step timeout and restore execution engine defaults', false)
7880
8426
  .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering.', (val, prev) => [...(prev ?? []), val], [])
7881
8427
  .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Declares an upstream producer dependency.', (val, prev) => [...(prev ?? []), val], [])
7882
8428
  .option('--category <str>', "BE only: test category. Use 'teardown' or 'cleanup' to mark a final-wave cleanup test.")
7883
8429
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
7884
8430
  .addHelpText('after', GLOBAL_OPTS_HINT)
7885
8431
  .action(async (testId, cmdOpts, command) => {
8432
+ if (cmdOpts.stepTimeout !== undefined && cmdOpts.clearStepTimeout === true) {
8433
+ throw localValidationError('step-timeout', '--step-timeout and --clear-step-timeout are mutually exclusive');
8434
+ }
7886
8435
  await runUpdate({
7887
8436
  ...resolveCommonOptions(command),
7888
8437
  testId,
7889
8438
  name: cmdOpts.name,
7890
8439
  description: cmdOpts.description,
7891
8440
  priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
8441
+ stepTimeoutMs: parseStepTimeoutFlag(cmdOpts.stepTimeout, 'step-timeout'),
8442
+ clearStepTimeout: cmdOpts.clearStepTimeout === true,
7892
8443
  produces: cmdOpts.produces,
7893
8444
  needs: cmdOpts.needs,
7894
8445
  category: cmdOpts.category,
@@ -7967,6 +8518,20 @@ export function createTestCommand(deps = {}) {
7967
8518
  "`run` command has no way to know a test's type before triggering it, so the preflight " +
7968
8519
  'still runs and can still refuse; use --skip-preflight if that surprises you.')
7969
8520
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
8521
+ .option('--local <port>', 'run against an app on THIS machine, reached through a TestSprite tunnel. The test runner ' +
8522
+ 'navigates to http://127.0.0.1:<port> and its traffic is proxied back to you for as long ' +
8523
+ 'as this command runs. Implies --wait (the tunnel closes when the command exits, so a ' +
8524
+ 'detached run could not finish) and cannot be combined with --target-url. Frontend tests ' +
8525
+ 'only. Before anything is minted or billed, the port is probed and a dead one is refused.')
8526
+ .option('--local-host <host>', `with --local, which loopback address to name in the run's target URL — one of ` +
8527
+ `${LOOPBACK_HOSTS.join(', ')} (default ${DEFAULT_LOCAL_HOST}). Use localhost if your app ` +
8528
+ `only answers on that name, or ::1 for an IPv6-only listener.`)
8529
+ .option('--tunnel-client <id>', 'with --local, attach to a tunnel already running under `testsprite tunnel start` instead ' +
8530
+ 'of opening a new one. The id is the non-secret handle that command prints; the tunnel ' +
8531
+ 'stays owned by that process and is not closed when this run finishes.')
8532
+ .option('--no-cancel-on-interrupt', 'with --local, leave the run executing (and billing) when this command stops waiting. By ' +
8533
+ 'default a --local run is cancelled at that point, because its tunnel closes with this ' +
8534
+ 'process and the run could then only fail.')
7970
8535
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
7971
8536
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
7972
8537
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
@@ -7979,6 +8544,7 @@ export function createTestCommand(deps = {}) {
7979
8544
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
7980
8545
  .option('--gh-output', 'with --wait (single test or --all): emit GitHub-native output (::error:: annotations per non-passed run; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
7981
8546
  .option('--summary-file <path>', 'with --wait (single test or --all): also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
8547
+ .option('--allow-empty', 'with --all: exit 0 when the run dispatches ZERO tests (all skipped / empty project / --filter matched nothing). Default: fail with exit 5 — a zero-dispatch run is a CI false-green')
7982
8548
  .addHelpText('after', '\nDependency-aware fresh run (M4):\n' +
7983
8549
  ' testsprite test run --all --project <id> run all project tests in wave order\n' +
7984
8550
  ' TESTSPRITE_PROJECT_ID=<id> testsprite test run --all use env default project\n' +
@@ -8006,12 +8572,45 @@ export function createTestCommand(deps = {}) {
8006
8572
  if (cmdOpts.filter !== undefined && cmdOpts.filter !== '' && !isAll) {
8007
8573
  throw localValidationError('filter', '--filter only applies with --all (it narrows which project tests run). Remove --filter, or add --all with --project <id> or TESTSPRITE_PROJECT_ID.');
8008
8574
  }
8575
+ // --local resolution. Every one of these refuses BEFORE any network
8576
+ // call, which is the contract `--local` is sold on: a mistake in the
8577
+ // invocation must never reach a run row, a credit spend, or a minted
8578
+ // tunnel credential.
8579
+ const localPort = cmdOpts.local !== undefined ? parseLocalPort(cmdOpts.local) : undefined;
8580
+ const usingLocal = localPort !== undefined;
8581
+ const effectiveWait = usingLocal || cmdOpts.wait === true;
8582
+ if (usingLocal && isAll) {
8583
+ throw localValidationError('local', '--local runs one test through one tunnel; --all fans out across a project. Run the ' +
8584
+ 'tests you want against your machine one at a time, or drop --local');
8585
+ }
8586
+ if (usingLocal && cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
8587
+ throw localValidationError('local', '--local and --target-url are mutually exclusive: --local runs against your own ' +
8588
+ 'machine through a tunnel, --target-url runs against an address the test runner can ' +
8589
+ 'already reach. Pass one');
8590
+ }
8591
+ // The three flags below are inert without --local. Silently ignoring
8592
+ // them would leave the caller believing something is in effect that is
8593
+ // not — the same rule --filter and the JUnit flags already follow.
8594
+ if (!usingLocal && cmdOpts.localHost !== undefined) {
8595
+ throw localValidationError('local-host', '--local-host only applies with --local (it names the loopback address the tunnel run ' +
8596
+ 'targets). Add --local <port>, or remove --local-host');
8597
+ }
8598
+ if (!usingLocal && cmdOpts.tunnelClient !== undefined) {
8599
+ throw localValidationError('tunnel-client', '--tunnel-client only applies with --local (it attaches the run to an already-running ' +
8600
+ 'tunnel). Add --local <port>, or remove --tunnel-client');
8601
+ }
8602
+ if (!usingLocal && cmdOpts.cancelOnInterrupt === false) {
8603
+ throw localValidationError('cancel-on-interrupt', '--no-cancel-on-interrupt only applies with --local. An ordinary run is never ' +
8604
+ 'cancelled when this command stops waiting — Ctrl-C detaches, and `testsprite test ' +
8605
+ 'cancel <run-id>` is the way to stop one');
8606
+ }
8607
+ const localHost = usingLocal ? normalizeLocalHost(cmdOpts.localHost) : undefined;
8009
8608
  const report = parseJUnitReportFormat(cmdOpts.report);
8010
8609
  assertJUnitReportOptions({
8011
8610
  report,
8012
8611
  reportFile: cmdOpts.reportFile,
8013
8612
  reportSuiteName: cmdOpts.reportSuiteName,
8014
- wait: cmdOpts.wait === true,
8613
+ wait: effectiveWait,
8015
8614
  batchPath: isAll,
8016
8615
  });
8017
8616
  // --gh-output / --summary-file reduce a --wait run's terminal result into
@@ -8019,10 +8618,10 @@ export function createTestCommand(deps = {}) {
8019
8618
  // enqueueing, before any terminal result exists) but apply to BOTH a single
8020
8619
  // <test-id> run and the --all batch. Without --wait they would silently
8021
8620
  // no-op — reject loudly (same rule as --filter and the JUnit report flags).
8022
- if (cmdOpts.ghOutput === true && cmdOpts.wait !== true) {
8621
+ if (cmdOpts.ghOutput === true && !effectiveWait) {
8023
8622
  throw localValidationError('gh-output', '--gh-output requires --wait (it reduces the terminal run result). Add --wait.');
8024
8623
  }
8025
- if (cmdOpts.summaryFile !== undefined && cmdOpts.wait !== true) {
8624
+ if (cmdOpts.summaryFile !== undefined && !effectiveWait) {
8026
8625
  throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
8027
8626
  }
8028
8627
  if (isAll) {
@@ -8042,7 +8641,7 @@ export function createTestCommand(deps = {}) {
8042
8641
  ...resolveCommonOptions(command),
8043
8642
  projectId,
8044
8643
  nameFilter: cmdOpts.filter,
8045
- wait: cmdOpts.wait === true,
8644
+ wait: effectiveWait,
8046
8645
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
8047
8646
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
8048
8647
  DEFAULT_BATCH_RUN_CONCURRENCY,
@@ -8052,16 +8651,40 @@ export function createTestCommand(deps = {}) {
8052
8651
  reportSuiteName: cmdOpts.reportSuiteName,
8053
8652
  ghOutput: cmdOpts.ghOutput === true,
8054
8653
  summaryFile: cmdOpts.summaryFile,
8654
+ allowEmpty: cmdOpts.allowEmpty === true,
8055
8655
  }, deps);
8056
8656
  return;
8057
8657
  }
8658
+ // `--local` implies `--wait`: for a self-minted tunnel the tunnel's
8659
+ // lifetime is this process's lifetime, so returning early would doom the
8660
+ // run it just started. Announced rather than assumed — a caller who did
8661
+ // not type --wait should learn why the command is now blocking.
8662
+ //
8663
+ // The reason splits on how the tunnel was obtained. An adopted one
8664
+ // (--tunnel-client) outlives this process, so "the tunnel closes when
8665
+ // this command exits" is simply false there, and it is the sentence a
8666
+ // reader would act on: told that, someone deciding whether to background
8667
+ // this command concludes the wrong thing about their own tunnel.
8668
+ const commonOpts = resolveCommonOptions(command);
8669
+ if (usingLocal && cmdOpts.wait !== true && commonOpts.output !== 'json') {
8670
+ const adopted = cmdOpts.tunnelClient !== undefined;
8671
+ (deps.stderr ?? ((line) => process.stderr.write(`${line}\n`)))(adopted
8672
+ ? '[advisory] --local implies --wait: the run is followed to a verdict rather than ' +
8673
+ 'detached. The tunnel you attached to stays open — this command does not close it.'
8674
+ : '[advisory] --local implies --wait: the tunnel closes when this command exits, so ' +
8675
+ 'the run is followed to a verdict rather than detached.');
8676
+ }
8058
8677
  // Single test-id path (unchanged M3.3 behavior).
8059
8678
  await runTestRun({
8060
- ...resolveCommonOptions(command),
8679
+ ...commonOpts,
8061
8680
  testId: testIdArg,
8062
8681
  targetUrl: cmdOpts.targetUrl,
8063
8682
  skipPreflight: cmdOpts.skipPreflight === true,
8064
- wait: cmdOpts.wait === true,
8683
+ ...(localPort !== undefined ? { localPort } : {}),
8684
+ ...(localHost !== undefined ? { localHost } : {}),
8685
+ ...(cmdOpts.tunnelClient !== undefined ? { tunnelClientId: cmdOpts.tunnelClient } : {}),
8686
+ cancelOnInterrupt: cmdOpts.cancelOnInterrupt !== false,
8687
+ wait: effectiveWait,
8065
8688
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
8066
8689
  // B2(c): tell runTestRun whether --timeout was explicitly provided.
8067
8690
  timeoutIsDefault: cmdOpts.timeout === undefined,
@@ -8524,15 +9147,118 @@ export function resolveWaitRequestTimeoutMs(opts) {
8524
9147
  const cover = Math.min(opts.timeoutSeconds * 1000 + WAIT_REQUEST_TIMEOUT_CUSHION_MS, REQUEST_TIMEOUT_MAX_MS);
8525
9148
  return Math.max(base, cover);
8526
9149
  }
8527
- function makeClient(opts, deps) {
9150
+ function makeClient(opts, deps, shutdownSignal = shutdownOf(deps).signal) {
8528
9151
  return makeHttpClient(opts, {
8529
9152
  env: deps.env,
8530
9153
  credentialsPath: deps.credentialsPath,
8531
9154
  fetchImpl: deps.fetchImpl,
8532
9155
  stderr: deps.stderr,
8533
- shutdownSignal: shutdownOf(deps).signal,
9156
+ shutdownSignal,
8534
9157
  });
8535
9158
  }
9159
+ /**
9160
+ * Run one request under a total deadline that is independent of Ctrl-C.
9161
+ *
9162
+ * Mint and trigger responses carry the only handles that let us undo the
9163
+ * server-side effects they may already have committed. A first signal is
9164
+ * therefore allowed to request shutdown, but cannot tear either response down
9165
+ * before we learn the clientId/runId needed for cleanup. The total deadline
9166
+ * still bounds all HTTP retries and their sleeps end to end.
9167
+ */
9168
+ async function withUninterruptibleRequest(opts, deps, timeoutMs, operation) {
9169
+ const deadline = new AbortController();
9170
+ const timer = setTimeout(() => {
9171
+ deadline.abort(new RequestTimeoutError(timeoutMs));
9172
+ }, timeoutMs);
9173
+ timer.unref?.();
9174
+ try {
9175
+ return await operation(makeClient({ ...opts, requestTimeoutMs: timeoutMs }, deps, deadline.signal));
9176
+ }
9177
+ finally {
9178
+ clearTimeout(timer);
9179
+ }
9180
+ }
9181
+ /** Make `start()` reject promptly when the armed lifecycle receives a signal. */
9182
+ function shutdownAwareTunnelClientFactory(createClient, signal) {
9183
+ return options => {
9184
+ const client = createClient(options);
9185
+ return {
9186
+ start: async () => {
9187
+ if (signal.aborted)
9188
+ throw signal.reason;
9189
+ await new Promise((resolve, reject) => {
9190
+ const onAbort = () => reject(signal.reason);
9191
+ signal.addEventListener('abort', onAbort, { once: true });
9192
+ client.start().then(() => {
9193
+ signal.removeEventListener('abort', onAbort);
9194
+ resolve();
9195
+ }, err => {
9196
+ signal.removeEventListener('abort', onAbort);
9197
+ reject(err);
9198
+ });
9199
+ });
9200
+ },
9201
+ stop: () => {
9202
+ const stopping = client.stop();
9203
+ if (!signal.aborted)
9204
+ return stopping;
9205
+ // `TunnelClient.stop()` synchronously flips its running flag before
9206
+ // its first await. Do not let a still-CONNECTING WebSocket delay the
9207
+ // binding DELETE after Ctrl-C; observe the eventual rejection only to
9208
+ // avoid an unhandled promise.
9209
+ void stopping.catch(() => { });
9210
+ return Promise.resolve();
9211
+ },
9212
+ };
9213
+ };
9214
+ }
9215
+ /**
9216
+ * A client for teardown work that must survive an interrupt.
9217
+ *
9218
+ * `makeClient` composes the process shutdown signal into every request, which
9219
+ * is right for the work a Ctrl-C is meant to abandon — and wrong for the two
9220
+ * calls that only exist BECAUSE of the Ctrl-C: deleting the tunnel binding and
9221
+ * cancelling the doomed run. Composed with an already-aborted signal, those
9222
+ * requests never leave the machine, and the user is left holding a live
9223
+ * credential and a burning run.
9224
+ *
9225
+ * The timeout is deliberately short and fixed rather than inherited: teardown
9226
+ * happens while the user is waiting for their prompt back, and a stalled
9227
+ * cleanup call must not out-live their patience.
9228
+ */
9229
+ function makeDetachedClient(opts, deps, operationSignal) {
9230
+ return makeHttpClient({ ...opts, requestTimeoutMs: TEARDOWN_OPERATION_TIMEOUT_MS }, {
9231
+ env: deps.env,
9232
+ credentialsPath: deps.credentialsPath,
9233
+ fetchImpl: deps.fetchImpl,
9234
+ stderr: deps.stderr,
9235
+ // Detached from the process signal, but still bounded end to end. The
9236
+ // HTTP retry sleeper listens to shutdownSignal, so this operation signal
9237
+ // cuts both in-flight attempts and the backoff between them.
9238
+ shutdownSignal: operationSignal,
9239
+ });
9240
+ }
9241
+ async function withTeardownDeadline(opts, deps, operation) {
9242
+ const deadline = new AbortController();
9243
+ const timer = setTimeout(() => {
9244
+ deadline.abort(new RequestTimeoutError(TEARDOWN_OPERATION_TIMEOUT_MS));
9245
+ }, TEARDOWN_OPERATION_TIMEOUT_MS);
9246
+ timer.unref?.();
9247
+ const shutdown = deps.shutdown ?? globalShutdown;
9248
+ try {
9249
+ return await shutdown.runCriticalOperation(() => operation(makeDetachedClient(opts, deps, deadline.signal)));
9250
+ }
9251
+ finally {
9252
+ clearTimeout(timer);
9253
+ }
9254
+ }
9255
+ async function deleteTunnelForCleanup(opts, deps, clientId) {
9256
+ await withTeardownDeadline(opts, deps, client => client.delete(`/tunnel/${encodeURIComponent(clientId)}`, {
9257
+ allowNoContent: true,
9258
+ }));
9259
+ }
9260
+ /** See {@link makeDetachedClient}. */
9261
+ const TEARDOWN_OPERATION_TIMEOUT_MS = 10_000;
8536
9262
  function makeOutput(mode, deps) {
8537
9263
  return new Output(mode, {
8538
9264
  stdout: deps.stdout,
@@ -8807,6 +9533,9 @@ function renderTestText(t) {
8807
9533
  if (typeof t.planStepCount === 'number') {
8808
9534
  lines.push(`planSteps: ${t.planStepCount}`);
8809
9535
  }
9536
+ if (typeof t.stepTimeoutMs === 'number') {
9537
+ lines.push(`stepTimeout: ${t.stepTimeoutMs} ms (applies to every step)`);
9538
+ }
8810
9539
  // Surface backend dependency declarations when present.
8811
9540
  if (Array.isArray(t.produces) && t.produces.length > 0) {
8812
9541
  lines.push(`produces: ${t.produces.join(', ')}`);
@@ -9214,8 +9943,645 @@ function createTestCodeCommand(deps) {
9214
9943
  });
9215
9944
  return code;
9216
9945
  }
9946
+ // ---------------------------------------------------------------------------
9947
+ // `test plan generate` / `test plan accept` — DEV-384 V3-B
9948
+ // ---------------------------------------------------------------------------
9949
+ /** Default `--timeout` for `test plan generate` (design-doc §3.1): a fresh
9950
+ * frontend project runs browser exploration, which takes minutes — the runs
9951
+ * default (600s) would routinely cut it short. */
9952
+ const PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS = 1800;
9953
+ /** Cap on the F1 pre-trigger baseline read — best-effort display data must
9954
+ * never hold up the real work (review follow-up). */
9955
+ const PLAN_BASELINE_READ_TIMEOUT_MS = 10_000;
9956
+ /** `--project` is a flag (not a positional) on both plan-generation leaves —
9957
+ * route through the house helpers so `TESTSPRITE_PROJECT_ID` works here the
9958
+ * same as on every other command (DEV-384 review F5). */
9959
+ function requirePlanProjectId(projectId, deps) {
9960
+ const resolved = resolveProjectId(projectId, deps);
9961
+ requireProjectId(resolved);
9962
+ return resolved;
9963
+ }
9964
+ /**
9965
+ * Normalize `--only` tokens: split comma-separated entries, trim, drop
9966
+ * empties, dedupe (order-preserving). Returns `undefined` when the flag was
9967
+ * absent; throws when the flag was supplied but named no usable id.
9968
+ */
9969
+ function normalizePlanOnlyIds(raw) {
9970
+ if (raw === undefined)
9971
+ return undefined;
9972
+ const ids = [];
9973
+ const seen = new Set();
9974
+ for (const token of raw) {
9975
+ for (const piece of token.split(',')) {
9976
+ const id = piece.trim();
9977
+ if (id.length === 0 || seen.has(id))
9978
+ continue;
9979
+ seen.add(id);
9980
+ ids.push(id);
9981
+ }
9982
+ }
9983
+ if (ids.length === 0) {
9984
+ throw localValidationError('only', 'requires at least one proposal id');
9985
+ }
9986
+ return ids;
9987
+ }
9988
+ /**
9989
+ * Fallback `nextAction` texts for the plan-generation error reasons
9990
+ * (design-doc §7/§8: every precondition failure names its exact fix). The
9991
+ * backend facade already ships these texts; this map is the CLI-side
9992
+ * FALLBACK applied only when the envelope's `nextAction` is empty (same
9993
+ * convention as the FEATURE_GATED `/pricing` fallback) — backend-supplied
9994
+ * text always passes through unchanged.
9995
+ */
9996
+ function planFixNextAction(reason, projectId, categoryCount) {
9997
+ switch (reason) {
9998
+ case 'v3_required':
9999
+ return ('Plan generation runs on the V3 platform and your account has not been migrated yet ' +
10000
+ '(it will be soon). Until then, generate test plans in the Portal.');
10001
+ case 'environment_url_missing':
10002
+ return `Set the app URL first: testsprite project update ${projectId} --url https://staging.your-app.com`;
10003
+ case 'no_processed_inputs':
10004
+ return (`Upload your API documentation: testsprite project docs upload <file> --project ${projectId} --role api-doc ` +
10005
+ '(or add sources in the Portal — upload a document, give the assistant a link, or paste it). ' +
10006
+ 'If you just added a source, it may still be processing — retry shortly.');
10007
+ case 'no_plannable_categories':
10008
+ // Mirrors the server's own 0 / 1 / n split: zero categories is
10009
+ // reachable on a frontend project too, where "upload a fuller API
10010
+ // document" cannot apply.
10011
+ if (categoryCount === 0) {
10012
+ return ('The strategy is ready but has no categories, so there is nothing to plan test cases ' +
10013
+ 'against. Retrying will not change this. Regenerate the strategy in the Portal, then run ' +
10014
+ 'this again.');
10015
+ }
10016
+ return ((categoryCount === 1
10017
+ ? 'The strategy is ready, but its only category has no endpoint to attach a test to, so '
10018
+ : 'The strategy is ready, but none of its categories has an endpoint to attach a test to, so ') +
10019
+ 'there is nothing to plan against. Retrying will not change this. Review the strategy in the ' +
10020
+ 'Portal; if your API documentation does not describe the endpoints, upload a fuller document ' +
10021
+ `(testsprite project docs upload <file> --project ${projectId} --role api-doc) and regenerate ` +
10022
+ 'the strategy there, then run this again.');
10023
+ case 'nothing_staged':
10024
+ return `Generate proposals first: testsprite test plan generate --project ${projectId}`;
10025
+ default:
10026
+ return undefined;
10027
+ }
10028
+ }
10029
+ /** Apply {@link planFixNextAction} to an ApiError whose envelope lacks a
10030
+ * `nextAction`; every other error passes through untouched. */
10031
+ function withPlanFixNextAction(err, projectId) {
10032
+ if (!(err instanceof ApiError))
10033
+ return err;
10034
+ if (err.nextAction !== '')
10035
+ return err;
10036
+ const reason = err.getDetail('reason', (v) => typeof v === 'string');
10037
+ if (reason === undefined)
10038
+ return err;
10039
+ const categoryCount = err.getDetail('categoryCount', (v) => typeof v === 'number');
10040
+ const nextAction = planFixNextAction(reason, projectId, categoryCount);
10041
+ if (nextAction === undefined)
10042
+ return err;
10043
+ return new ApiError({
10044
+ code: err.code,
10045
+ message: err.message,
10046
+ nextAction,
10047
+ requestId: err.requestId,
10048
+ details: err.details,
10049
+ }, err.httpStatus, err.retryAfterMs);
10050
+ }
10051
+ /** Local envelope for "accept with nothing staged" — same shape/reason the
10052
+ * server emits (412 `nothing_staged`, exit 6) so scripts can't tell whether
10053
+ * the CLI or the facade caught it first. */
10054
+ function planNothingStagedError(projectId) {
10055
+ return ApiError.fromEnvelope({
10056
+ error: {
10057
+ code: 'PRECONDITION_FAILED',
10058
+ message: 'No proposals are staged for this project — there is nothing to accept.',
10059
+ nextAction: planFixNextAction('nothing_staged', projectId),
10060
+ requestId: 'local',
10061
+ details: { projectId, reason: 'nothing_staged' },
10062
+ },
10063
+ });
10064
+ }
10065
+ /** `52s` under a minute, `4m10s` above (design §3.1 ticker examples). */
10066
+ function formatPlanElapsed(elapsedMs) {
10067
+ const totalSeconds = Math.max(0, Math.round(elapsedMs / 1000));
10068
+ if (totalSeconds < 60)
10069
+ return `${totalSeconds}s`;
10070
+ const minutes = Math.floor(totalSeconds / 60);
10071
+ const seconds = totalSeconds % 60;
10072
+ return `${minutes}m${String(seconds).padStart(2, '0')}s`;
10073
+ }
10074
+ /** One in-place ticker line per generation status (design §3.2). */
10075
+ function planTickerLine(plans, elapsedMs) {
10076
+ const elapsed = formatPlanElapsed(elapsedMs);
10077
+ const generation = plans.generation;
10078
+ switch (generation.status) {
10079
+ case 'exploring': {
10080
+ const progress = generation.progress;
10081
+ return progress !== undefined
10082
+ ? `exploring app… (resources ${progress.resourcesReady}/${progress.resourcesTotal}, ${elapsed})`
10083
+ : `exploring app… (${elapsed})`;
10084
+ }
10085
+ case 'strategizing':
10086
+ return `generating strategy… (${elapsed})`;
10087
+ case 'proposing':
10088
+ return `proposing tests… (${elapsed})`;
10089
+ case 'failed':
10090
+ return `generation failed (${elapsed})`;
10091
+ case 'idle':
10092
+ return plans.proposals.length > 0
10093
+ ? `proposals staged (${elapsed})`
10094
+ : `starting next stage… (${elapsed})`;
10095
+ }
10096
+ }
10097
+ /** Sum of the best-effort `credits.charged` amounts (0 when absent). */
10098
+ function planCreditsUsed(plans) {
10099
+ return (plans.credits?.charged ?? []).reduce((sum, c) => sum + c.amount, 0);
10100
+ }
10101
+ /**
10102
+ * THIS invocation's spend: the settled read's per-action charged totals minus
10103
+ * the pre-trigger baseline's (DEV-935 / review F1 — the wire block is a
10104
+ * LIFETIME project total, so printing its sum as "credits used" reported
10105
+ * all-time spend on re-runs that charged nothing). `null` = unknown (no
10106
+ * baseline snapshot, or either read lacks the best-effort block) — the
10107
+ * caller omits the figure rather than printing a lifetime number.
10108
+ */
10109
+ function planCreditsDelta(baseline, settled) {
10110
+ if (baseline?.credits?.charged === undefined || settled.credits?.charged === undefined) {
10111
+ return null;
10112
+ }
10113
+ // DEV-935: a facade-side billing failure degrades the block to
10114
+ // `{charged: [], balance: null}` — `charged` is DEFINED there, so without
10115
+ // this guard a degraded read makes the other read's lifetime totals print
10116
+ // as this run's spend (the F1 misreport, back through the degrade window).
10117
+ // A healthy block always carries a numeric balance.
10118
+ if (baseline.credits.balance === null || settled.credits.balance === null) {
10119
+ return null;
10120
+ }
10121
+ const before = new Map(baseline.credits.charged.map(c => [c.action, c.amount]));
10122
+ let delta = 0;
10123
+ for (const c of settled.credits.charged) {
10124
+ delta += Math.max(0, c.amount - (before.get(c.action) ?? 0));
10125
+ }
10126
+ return delta;
10127
+ }
10128
+ /** ` (credits used: N, balance: M)` — `creditsUsed` is this invocation's
10129
+ * delta (omitted when 0 or unknown); balance is the settled read's current
10130
+ * figure. Empty string when the facade couldn't fill either. */
10131
+ function planCreditsSuffix(plans, creditsUsed) {
10132
+ const parts = [];
10133
+ if (creditsUsed !== null && creditsUsed > 0)
10134
+ parts.push(`credits used: ${creditsUsed}`);
10135
+ const balance = plans.credits?.balance;
10136
+ if (balance !== undefined && balance !== null)
10137
+ parts.push(`balance: ${balance}`);
10138
+ return parts.length > 0 ? ` (${parts.join(', ')})` : '';
10139
+ }
10140
+ /** Auto-width column helper for the proposals table. */
10141
+ function planTableColumn(header, render) {
10142
+ return {
10143
+ header,
10144
+ width: rows => Math.max(header.length, ...rows.map(r => render(r.proposal, r.index).length), 1),
10145
+ render: r => render(r.proposal, r.index),
10146
+ };
10147
+ }
10148
+ /** The staged-proposals table. Every row prints its stable `proposalId` —
10149
+ * that id is what `accept --only` consumes (design §3.3). */
10150
+ function renderPlanProposalsTable(proposals) {
10151
+ const rows = proposals.map((proposal, index) => ({ proposal, index }));
10152
+ const columns = [
10153
+ planTableColumn('#', (_p, i) => String(i + 1)),
10154
+ planTableColumn('ID', p => p.proposalId),
10155
+ planTableColumn('TITLE', p => (p.title.length > 48 ? `${p.title.slice(0, 47)}…` : p.title)),
10156
+ planTableColumn('FEATURE', p => `${p.category}/${p.feature}`),
10157
+ planTableColumn('PRIORITY', p => p.priority),
10158
+ planTableColumn('TYPE', p => p.type),
10159
+ ];
10160
+ return renderTextTable(rows, columns);
10161
+ }
10162
+ /** Text card for a settled successful generate (or `--dry-run`). */
10163
+ /** Exported for the renderer-level spec: the zero-proposals branch is not
10164
+ * reachable through `runGenerationLadder` today (after the proposals rung it
10165
+ * polls until staged/failed/timeout), so it is pinned directly. */
10166
+ export function renderPlanGenerateResultText(plans, projectId, creditsUsed, skippedCategories = null) {
10167
+ const count = plans.proposals.length;
10168
+ if (count === 0) {
10169
+ return [
10170
+ `0 test-case proposals staged${planCreditsSuffix(plans, creditsUsed)}`,
10171
+ // The skip count matters MOST here: a batch already narrowed to the
10172
+ // plannable categories that still settled at zero points at the
10173
+ // strategy, not at a re-run (which would bill again for the same result).
10174
+ ...renderSkippedCategoriesLine(skippedCategories, { staged: false }),
10175
+ `hint: nothing is staged for review — run: testsprite test plan generate --project ${projectId}`,
10176
+ ].join('\n');
10177
+ }
10178
+ const noun = count === 1 ? 'proposal' : 'proposals';
10179
+ return [
10180
+ `${count} test-case ${noun} staged for review${planCreditsSuffix(plans, creditsUsed)}`,
10181
+ ...renderSkippedCategoriesLine(skippedCategories, { staged: true }),
10182
+ '',
10183
+ renderPlanProposalsTable(plans.proposals),
10184
+ '',
10185
+ 'next',
10186
+ ` review the list above, then: testsprite test plan accept --project ${projectId}`,
10187
+ ` accept a subset with: testsprite test plan accept --project ${projectId} --only <id ...>`,
10188
+ ' (or review visually in the Portal before accepting)',
10189
+ ].join('\n');
10190
+ }
10191
+ /** DEV-1008 — one line when the proposals stage left strategy categories out
10192
+ * because they have no endpoint to attach a test to. The stage is charged
10193
+ * flat, so without this the caller cannot tell a partial plan from a full
10194
+ * one. Empty when nothing was skipped (the common case). */
10195
+ function renderSkippedCategoriesLine(skippedCategories, opts) {
10196
+ if (skippedCategories === null || skippedCategories <= 0)
10197
+ return [];
10198
+ const noun = skippedCategories === 1 ? 'category' : 'categories';
10199
+ const head = `note: ${skippedCategories} strategy ${noun} skipped — no endpoint to attach a test to ` +
10200
+ '(cross-cutting themes such as authorization or pagination)';
10201
+ return [
10202
+ opts.staged
10203
+ ? `${head}; the proposals above cover the rest.`
10204
+ : `${head}; the remaining categories produced nothing. Review the strategy in the Portal ` +
10205
+ 'before re-running — a re-run is charged again and will give the same result.',
10206
+ ];
10207
+ }
10208
+ /** Text card for a server-side stage failure (exit 1 follows via the thrown
10209
+ * INTERNAL envelope; earlier completed stages stay done — a re-run resumes). */
10210
+ function renderPlanGenerateFailedText(plans, projectId) {
10211
+ const generation = plans.generation;
10212
+ const lines = [`generation failed${generation.errorCode ? ` (${generation.errorCode})` : ''}`];
10213
+ if (generation.errorMessage)
10214
+ lines.push(` ${generation.errorMessage}`);
10215
+ lines.push(` completed stages stay done — retry with: testsprite test plan generate --project ${projectId}`);
10216
+ return lines.join('\n');
10217
+ }
10218
+ function makePlanGeneratePartial(projectId, lastSeen) {
10219
+ return {
10220
+ projectId,
10221
+ status: 'running',
10222
+ generationStatus: lastSeen?.generation.status ?? null,
10223
+ proposalsStaged: lastSeen?.proposals.length ?? 0,
10224
+ };
10225
+ }
10226
+ function renderPlanGeneratePartialText(partial, reason) {
10227
+ const lines = [`projectId ${partial.projectId}`, `status running (${reason})`];
10228
+ if (partial.generationStatus !== null) {
10229
+ lines.push(`stage ${partial.generationStatus}`);
10230
+ }
10231
+ lines.push(`hint Re-attach with: testsprite test plan generate --project ${partial.projectId}`);
10232
+ return lines.join('\n');
10233
+ }
10234
+ /**
10235
+ * `test plan generate --project <id>` — DEV-384 V3-B.
10236
+ *
10237
+ * Drives the server's generation ladder (exploration → strategy →
10238
+ * proposals) through `runGenerationLadder` and renders the staged
10239
+ * proposals. Exit 0 on staged proposals, 1 on a server-side stage failure,
10240
+ * 7 on timeout (typed `UNSUPPORTED` envelope — the raw ladder timeout is
10241
+ * not a CLI error), 130/143 on Ctrl-C detach (honest: work and charges
10242
+ * continue server-side), plus the usual catalog exits for trigger errors
10243
+ * (412 → 6 with the exact fix command, 402 → 12, 404 → 4, 429 → 11).
10244
+ */
10245
+ export async function runPlanGenerate(opts, deps = {}) {
10246
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
10247
+ const out = makeOutput(opts.output, deps);
10248
+ const projectId = requirePlanProjectId(opts.projectId, deps);
10249
+ assertIdempotencyKey(opts.idempotencyKey);
10250
+ if (opts.dryRun) {
10251
+ // Zero network, zero charges: resolve both canned samples directly
10252
+ // (no fetch — even the canned dry-run fetch is bypassed, matching the
10253
+ // `test run --dry-run` convention) and render the settled success shape.
10254
+ const client = makeClient(opts, deps);
10255
+ const plans = findSampleOrThrow('GET', `/api/cli/v1/projects/${encodeURIComponent(projectId)}/plans`).body();
10256
+ // Dry-run has no baseline to diff; teach the credits line from the
10257
+ // canned block's sum (everything here is canned anyway).
10258
+ const canned = planCreditsUsed(plans);
10259
+ const payload = { projectId, creditsUsedThisInvocation: canned, ...plans };
10260
+ out.print(payload, () => renderPlanGenerateResultText(plans, projectId, canned));
10261
+ void client; // constructed so dry-run still validates --endpoint-url etc.
10262
+ return payload;
10263
+ }
10264
+ const idempotencyKey = opts.idempotencyKey ?? `cli-plan-gen-${randomUUID()}`;
10265
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
10266
+ stderrFn(`idempotency-key: ${idempotencyKey}`);
10267
+ }
10268
+ // D4: the ladder is a long wait bounded by --timeout — raise the
10269
+ // per-request window to cover it (same as every `--wait` path).
10270
+ const client = makeClient({
10271
+ ...opts,
10272
+ requestTimeoutMs: resolveWaitRequestTimeoutMs({
10273
+ wait: true,
10274
+ timeoutSeconds: opts.timeoutSeconds,
10275
+ requestTimeoutMs: opts.requestTimeoutMs,
10276
+ }),
10277
+ }, deps);
10278
+ const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
10279
+ // Upgraded to the server-resolved V3 id by the first ACCEPTED trigger
10280
+ // response. KNOWN LIMITATION (DEV-384 review F8): when the very first
10281
+ // trigger 409-attaches, no trigger response ever arrives and neither the
10282
+ // 409 envelope nor the `GET /plans` read carries the resolved id, so the
10283
+ // output keeps the caller's input id (a V2 id still polls fine through the
10284
+ // migration bridge). Closing it needs the id on one of those wires.
10285
+ let resolvedProjectId = projectId;
10286
+ let lastSeen = null;
10287
+ try {
10288
+ // Pre-trigger baseline snapshot (review F1 / DEV-935): one plain GET
10289
+ // BEFORE any POST, so the settled read's lifetime `credits.charged`
10290
+ // block can be diffed into "what THIS invocation spent" (the first
10291
+ // stage's charge lands before the ladder's own first read, so first
10292
+ // in-ladder read vs last would undercount). Best-effort: a failure only
10293
+ // costs the credits line, never the command. Bounded by its own short
10294
+ // signal — without it the read inherits the D4-raised per-request window
10295
+ // (up to 600s under --wait semantics), all outside the --timeout budget.
10296
+ let baselinePlans = null;
10297
+ try {
10298
+ baselinePlans = await client.getPlans(projectId, {
10299
+ signal: AbortSignal.timeout(PLAN_BASELINE_READ_TIMEOUT_MS),
10300
+ });
10301
+ }
10302
+ catch (err) {
10303
+ if (err instanceof InterruptError)
10304
+ throw err;
10305
+ baselinePlans = null;
10306
+ }
10307
+ const result = await runGenerationLadder(client, projectId, {
10308
+ timeoutSeconds: opts.timeoutSeconds,
10309
+ idempotencyKey,
10310
+ sleep: deps.sleep,
10311
+ shutdown: shutdownOf(deps),
10312
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
10313
+ onTick: (plans, elapsedMs) => {
10314
+ lastSeen = plans;
10315
+ ticker.update(planTickerLine(plans, elapsedMs));
10316
+ },
10317
+ onAttach: () => {
10318
+ stderrFn('[advisory] a generation stage is already running for this project (possibly ' +
10319
+ 'started from the Portal) — attaching to it and polling.');
10320
+ },
10321
+ onTrigger: (response, acceptedPosts) => {
10322
+ resolvedProjectId = response.projectId;
10323
+ if (response.status === 'nothing_to_start') {
10324
+ if (acceptedPosts === 0) {
10325
+ // The FIRST trigger found the batch already staged: nothing ran,
10326
+ // nothing was charged. Regenerating on purpose is a Portal action
10327
+ // for now (design §11) — say so instead of silently no-opping.
10328
+ stderrFn('[advisory] proposals are already staged for this project — showing the ' +
10329
+ 'existing batch (nothing new was started or charged). To regenerate, ' +
10330
+ 'review and accept or discard the staged batch in the Portal first.');
10331
+ }
10332
+ return;
10333
+ }
10334
+ if (acceptedPosts === 1) {
10335
+ // First accepted trigger: state which stages will run (text mode
10336
+ // only — JSON pipelines get just the result object). Deliberately
10337
+ // does NOT quote a price up front: the surface matches `test run`,
10338
+ // which announces no cost either. Actual spend IS reported after
10339
+ // the fact, on the result line (`credits used: N, balance: M`) —
10340
+ // N is THIS invocation's settled−baseline delta (review F1), not
10341
+ // the wire block's lifetime total, and never a local price table.
10342
+ if (opts.output !== 'json') {
10343
+ const stages = [
10344
+ ...(response.stage !== null ? [response.stage] : []),
10345
+ ...response.stagesRemaining,
10346
+ ];
10347
+ const label = stages.join(' + ');
10348
+ stderrFn(stages.includes('exploration')
10349
+ ? `[hint] this project hasn't been explored yet — the full pipeline will run ` +
10350
+ `(${label}). Ctrl-C detaches safely; work continues server-side.`
10351
+ : `[hint] running the missing pipeline stages (${label}). ` +
10352
+ `Ctrl-C detaches safely; work continues server-side.`);
10353
+ }
10354
+ // …and, when browser exploration is about to run, warn about
10355
+ // missing test-account sign-in (design §3.1). The wire carries no
10356
+ // credential-presence signal, so the warning is hedged ("if …") —
10357
+ // it never blocks and never prompts; the CLI cannot know whether
10358
+ // the app actually requires login. Both output modes: stderr only.
10359
+ if (response.stage === 'exploration') {
10360
+ stderrFn('[warn] exploration signs in only with the test account stored on the ' +
10361
+ "project's default environment. If your app requires login and no test " +
10362
+ 'account is configured, the agents will explore only the public pages — ' +
10363
+ 'a shallow result from a stage that still runs and still bills. For ' +
10364
+ 'signed-in coverage, store a test account first: ' +
10365
+ `testsprite project update ${projectId} --username <user> --password-file <path>`);
10366
+ }
10367
+ }
10368
+ },
10369
+ });
10370
+ const plans = result.plans;
10371
+ if (plans.generation.status === 'failed') {
10372
+ ticker.finalize(planTickerLine(plans, 0).replace(/ \(0s\)$/, ''));
10373
+ const payload = { projectId: resolvedProjectId, ...plans };
10374
+ out.print(payload, () => renderPlanGenerateFailedText(plans, resolvedProjectId));
10375
+ throw ApiError.fromEnvelope({
10376
+ error: {
10377
+ code: 'INTERNAL', // exit 1 — "a pipeline stage failed server-side" (§8)
10378
+ message: `Plan generation failed: ${plans.generation.errorMessage ??
10379
+ plans.generation.errorCode ??
10380
+ 'a pipeline stage failed server-side'}`,
10381
+ nextAction: `Completed stages stay done — re-run \`testsprite test plan generate --project ${resolvedProjectId}\` ` +
10382
+ 'to retry the failed stage, or check the project in the Portal.',
10383
+ requestId: 'local',
10384
+ details: {
10385
+ projectId: resolvedProjectId,
10386
+ errorCode: plans.generation.errorCode,
10387
+ },
10388
+ },
10389
+ });
10390
+ }
10391
+ const count = plans.proposals.length;
10392
+ ticker.finalize(`${count} ${count === 1 ? 'proposal' : 'proposals'} staged`);
10393
+ // This invocation's spend (settled − baseline; null = unknown) — the
10394
+ // wire block alone is a lifetime total (DEV-935 / review F1).
10395
+ const creditsUsed = planCreditsDelta(baselinePlans, plans);
10396
+ const skippedCategories = result.skippedCategories;
10397
+ const payload = {
10398
+ projectId: resolvedProjectId,
10399
+ creditsUsedThisInvocation: creditsUsed,
10400
+ // DEV-1008: present only when the proposals stage skipped endpoint-less
10401
+ // categories, so every other JSON payload is byte-identical.
10402
+ ...(skippedCategories !== null ? { skippedCategories } : {}),
10403
+ ...plans,
10404
+ };
10405
+ out.print(payload, () => renderPlanGenerateResultText(plans, resolvedProjectId, creditsUsed, skippedCategories));
10406
+ return payload;
10407
+ }
10408
+ catch (err) {
10409
+ // Typed exit-7 conversion (the design's hard rule): the ladder's raw
10410
+ // timeout is NOT a CLI error and would otherwise exit 1. Mirror the
10411
+ // wait-site template — partial to stdout, typed envelope thrown.
10412
+ if (err instanceof PlanGenerationTimeoutError) {
10413
+ ticker.finalize(`timed out after ${opts.timeoutSeconds}s`);
10414
+ const partial = makePlanGeneratePartial(resolvedProjectId, err.lastPlans ?? lastSeen);
10415
+ out.print(partial, () => renderPlanGeneratePartialText(partial, `timed out after ${opts.timeoutSeconds}s`));
10416
+ throw ApiError.fromEnvelope({
10417
+ error: {
10418
+ code: 'UNSUPPORTED', // exit 7 per errors.md
10419
+ message: `Timed out after ${opts.timeoutSeconds}s waiting for plan generation on project ${resolvedProjectId}.`,
10420
+ nextAction: `Generation continues server-side; re-running the same command re-attaches: ` +
10421
+ `testsprite test plan generate --project ${resolvedProjectId} ` +
10422
+ `(raise --timeout for exploration-heavy first runs).`,
10423
+ requestId: 'local',
10424
+ details: { projectId: resolvedProjectId, timeoutSeconds: opts.timeoutSeconds },
10425
+ },
10426
+ });
10427
+ }
10428
+ if (err instanceof RequestTimeoutError) {
10429
+ ticker.finalize('request timed out');
10430
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
10431
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'request timed out'));
10432
+ stderrFn(`Plan generation is still in progress (request timed out). ` +
10433
+ `Re-attach with: testsprite test plan generate --project ${resolvedProjectId}`);
10434
+ throw err;
10435
+ }
10436
+ if (err instanceof InterruptError) {
10437
+ ticker.finalize(`interrupted (${err.signal})`);
10438
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
10439
+ out.print(partial, () => renderPlanGeneratePartialText(partial, `interrupted (${err.signal})`));
10440
+ stderrFn(`Interrupted (${err.signal}). Plan generation keeps running (and billing) on the ` +
10441
+ `server until the current stage finishes.\n` +
10442
+ ` Re-attach with: testsprite test plan generate --project ${resolvedProjectId}`);
10443
+ throw err;
10444
+ }
10445
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
10446
+ // Same partial-envelope family as the timeout/interrupt branches
10447
+ // (DEV-384 review): a redirected stdout file must never be 0-byte.
10448
+ // The original ApiError is rethrown unchanged so exit stays 11.
10449
+ ticker.finalize('rate limited by the server');
10450
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
10451
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'rate limited'));
10452
+ stderrFn(`Rate limited by the server (HTTP 429). Any started generation stage keeps running ` +
10453
+ `server-side.\n Re-attach with: testsprite test plan generate --project ${resolvedProjectId}`);
10454
+ throw err;
10455
+ }
10456
+ if (err instanceof ApiError &&
10457
+ err.code === 'INTERNAL' &&
10458
+ typeof err.details?.acceptedPosts === 'number') {
10459
+ // The ladder's cap-exhaustion "appears stuck" fuse (DEV-384 review F7)
10460
+ // joins the partial-envelope family too — it is a terminal outcome of a
10461
+ // long wait, exactly like the branches above, so redirected stdout must
10462
+ // carry the partial. Keyed on the fuse's own `acceptedPosts` detail so
10463
+ // the stage-failed INTERNAL (which already printed its card) never
10464
+ // double-prints. Rethrown unchanged.
10465
+ ticker.finalize('generation appears stuck');
10466
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
10467
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'appears stuck'));
10468
+ throw err;
10469
+ }
10470
+ throw withPlanFixNextAction(err, resolvedProjectId);
10471
+ }
10472
+ }
10473
+ function renderPlanAcceptText(result, includesBackend) {
10474
+ const proposalNoun = result.acceptedCount === 1 ? 'proposal' : 'proposals';
10475
+ const caseNoun = result.acceptedCount === 1 ? 'test case' : 'test cases';
10476
+ const discarded = result.discardedCount > 0
10477
+ ? ` (${result.discardedCount} remaining ${result.discardedCount === 1 ? 'proposal' : 'proposals'} discarded)`
10478
+ : '';
10479
+ const lines = [
10480
+ `${result.acceptedCount} ${proposalNoun} accepted — ${result.acceptedCount} ${caseNoun} created${discarded}`,
10481
+ ];
10482
+ if (includesBackend) {
10483
+ // Only when API cases were among the accepted set (design §3.3) — keyed
10484
+ // on the project/proposal type, which IS reliable at that granularity.
10485
+ lines.push('note: API test code is generated when the tests first run');
10486
+ }
10487
+ lines.push('', 'next', ` testsprite test list --project ${result.projectId}`, ` testsprite test run --all --project ${result.projectId} --wait`);
10488
+ return lines.join('\n');
10489
+ }
10490
+ /**
10491
+ * Select the proposals to accept. Enforces the §3.3 safety rules:
10492
+ * the returned list is EXPLICIT and NEVER EMPTY — `--only` matching zero
10493
+ * staged ids (or naming unknown ids) is a local validation error and the
10494
+ * request is never sent, because an empty `only` list is server-destructive
10495
+ * (it means "reject everything" and clears the staged batch).
10496
+ */
10497
+ function selectPlanProposals(staged, onlyIds) {
10498
+ if (onlyIds === undefined)
10499
+ return staged;
10500
+ const byId = new Map(staged.map(p => [p.proposalId, p]));
10501
+ const unknown = onlyIds.filter(id => !byId.has(id));
10502
+ if (unknown.length > 0) {
10503
+ throw localValidationError('only', `no staged proposal matches id(s): ${unknown.join(', ')}. ` +
10504
+ `Staged proposal ids: ${staged.map(p => p.proposalId).join(', ')}. ` +
10505
+ `The accept request was not sent`);
10506
+ }
10507
+ return onlyIds.map(id => byId.get(id));
10508
+ }
10509
+ /**
10510
+ * `test plan accept --project <id> [--only <ids...>]` — DEV-384 V3-B.
10511
+ *
10512
+ * Reads the staged batch, selects all of it (or the `--only` subset),
10513
+ * and POSTs an EXPLICIT id list. Free — the generation charge already
10514
+ * covered it. Exit 0 on success, 5 on a bad `--only` selection (request
10515
+ * never sent), 6 when nothing is staged (pointer at `test plan generate`).
10516
+ */
10517
+ export async function runPlanAccept(opts, deps = {}) {
10518
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
10519
+ const out = makeOutput(opts.output, deps);
10520
+ const projectId = requirePlanProjectId(opts.projectId, deps);
10521
+ assertIdempotencyKey(opts.idempotencyKey);
10522
+ const onlyIds = normalizePlanOnlyIds(opts.only);
10523
+ if (opts.dryRun) {
10524
+ // Zero network, zero charges: run the real selection logic against the
10525
+ // canned staged batch so `--only` behavior (subset counts, unknown-id
10526
+ // validation) is learnable offline, then echo the input-derived sample.
10527
+ const client = makeClient(opts, deps);
10528
+ const plans = findSampleOrThrow('GET', `/api/cli/v1/projects/${encodeURIComponent(projectId)}/plans`).body();
10529
+ const staged = plans.proposals;
10530
+ const selected = selectPlanProposals(staged, onlyIds);
10531
+ const ids = selected.map(p => p.proposalId);
10532
+ const response = findSampleOrThrow('POST', `/api/cli/v1/projects/${encodeURIComponent(projectId)}/plans/accept`, { only: ids }).body();
10533
+ const result = {
10534
+ projectId,
10535
+ acceptedCount: response.acceptedCount,
10536
+ caseKeys: response.caseKeys,
10537
+ discardedCount: staged.length - selected.length,
10538
+ };
10539
+ out.print(result, () => renderPlanAcceptText(result, selected.some(p => p.type === 'backend')));
10540
+ void client;
10541
+ return result;
10542
+ }
10543
+ const idempotencyKey = opts.idempotencyKey ?? `cli-plan-accept-${randomUUID()}`;
10544
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
10545
+ stderrFn(`idempotency-key: ${idempotencyKey}`);
10546
+ }
10547
+ const client = makeClient(opts, deps);
10548
+ // The staged batch is read first because the CLI ALWAYS sends an explicit
10549
+ // id list (full list when --only is absent) — never the omitted form and
10550
+ // never an empty one (§3.3). Nothing staged → the same 412 nothing_staged
10551
+ // answer the server would give, without a request.
10552
+ let plans;
10553
+ try {
10554
+ plans = await client.getPlans(projectId);
10555
+ }
10556
+ catch (err) {
10557
+ throw withPlanFixNextAction(err, projectId);
10558
+ }
10559
+ const staged = plans.proposals;
10560
+ if (staged.length === 0) {
10561
+ throw planNothingStagedError(projectId);
10562
+ }
10563
+ const selected = selectPlanProposals(staged, onlyIds);
10564
+ const ids = selected.map(p => p.proposalId);
10565
+ let response;
10566
+ try {
10567
+ response = await client.acceptPlans(projectId, ids, { idempotencyKey });
10568
+ }
10569
+ catch (err) {
10570
+ // Covers the read-then-accept race too (another client accepted or
10571
+ // discarded the batch in between → server 412 nothing_staged).
10572
+ throw withPlanFixNextAction(err, projectId);
10573
+ }
10574
+ const result = {
10575
+ projectId,
10576
+ acceptedCount: response.acceptedCount,
10577
+ caseKeys: response.caseKeys,
10578
+ discardedCount: staged.length - selected.length,
10579
+ };
10580
+ out.print(result, () => renderPlanAcceptText(result, selected.some(p => p.type === 'backend')));
10581
+ return result;
10582
+ }
9217
10583
  function createTestPlanCommand(deps) {
9218
- const plan = new Command('plan').description('Manage FE test plan-steps (FE-only)');
10584
+ const plan = new Command('plan').description('Generate + accept AI test plans (V3), and manage FE plan-steps');
9219
10585
  plan
9220
10586
  .command('put <test-id>')
9221
10587
  .description("Replace an FE test's planSteps[] (BE tests return 400 → use 'test code put')")
@@ -9241,6 +10607,62 @@ function createTestPlanCommand(deps) {
9241
10607
  dryRunSimulateError: simulateError === 'PRECONDITION_FAILED' ? 'PRECONDITION_FAILED' : undefined,
9242
10608
  }, deps);
9243
10609
  });
10610
+ plan
10611
+ .command('generate')
10612
+ .description('Generate AI test-case proposals for a project — runs only the missing pipeline ' +
10613
+ 'stages and stages the results server-side for review (nothing is written locally)')
10614
+ .option('--project <id>', 'project id (V3-native; V2 ids resolve through the migration bridge)')
10615
+ .option('--timeout <seconds>', `total wait budget in seconds (1-3600, default ${PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS}; ` +
10616
+ 'exploration takes minutes on a fresh frontend project)')
10617
+ .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
10618
+ .addHelpText('after', '\nBehavior:\n' +
10619
+ ' - Only the stages the project is missing actually run; a second call\n' +
10620
+ ' resumes rather than starting over.\n' +
10621
+ ' - Proposals are STAGED on the server for review; nothing is written to disk.\n' +
10622
+ ' - Re-running the command re-attaches to an in-flight stage (409 attaches).\n' +
10623
+ ' - Ctrl-C detaches locally; server-side work and charges continue.\n' +
10624
+ ' - Exit 7 on --timeout: re-run the same command to re-attach.\n' +
10625
+ ' - Workspace credits are spent per stage that runs; the result line reports\n' +
10626
+ ' what THIS run charged (omitted when nothing new was charged).\n' +
10627
+ ' `testsprite usage` shows your balance.\n' +
10628
+ '\n' +
10629
+ 'Next step: review the printed table, then `testsprite test plan accept`.\n' +
10630
+ '\n' +
10631
+ GLOBAL_OPTS_HINT)
10632
+ .action(async (cmdOpts, command) => {
10633
+ await runPlanGenerate({
10634
+ ...resolveCommonOptions(command),
10635
+ projectId: cmdOpts.project,
10636
+ timeoutSeconds: cmdOpts.timeout === undefined
10637
+ ? PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS
10638
+ : parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
10639
+ idempotencyKey: cmdOpts.idempotencyKey,
10640
+ }, deps);
10641
+ });
10642
+ plan
10643
+ .command('accept')
10644
+ .description('Convert staged proposals into real test cases (free) — all of them, or a subset with --only')
10645
+ .option('--project <id>', 'project id (V3-native; V2 ids resolve through the migration bridge)')
10646
+ .option('--only <ids...>', 'accept only these proposal ids (space- or comma-separated; the ids come from the ' +
10647
+ '`test plan generate` table). Accepting a subset discards the rest. ANY id that ' +
10648
+ 'matches no staged proposal is a validation error — the request is never sent.')
10649
+ .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
10650
+ .addHelpText('after', '\nNotes:\n' +
10651
+ ' - Accepting adds no charge of its own; generation already did the work.\n' +
10652
+ ' - API test code is generated when the tests first run, not at accept.\n' +
10653
+ ' - Accepting a subset discards the remaining staged proposals (the staging\n' +
10654
+ ' area is cleared either way) — the output says how many were discarded.\n' +
10655
+ ' - Nothing staged → exit 6 with a pointer at `test plan generate`.\n' +
10656
+ '\n' +
10657
+ GLOBAL_OPTS_HINT)
10658
+ .action(async (cmdOpts, command) => {
10659
+ await runPlanAccept({
10660
+ ...resolveCommonOptions(command),
10661
+ projectId: cmdOpts.project,
10662
+ only: cmdOpts.only,
10663
+ idempotencyKey: cmdOpts.idempotencyKey,
10664
+ }, deps);
10665
+ });
9244
10666
  return plan;
9245
10667
  }
9246
10668
  export function createTestArtifactCommand(deps) {