@testsprite/testsprite-cli 0.16.0 → 0.17.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 (206) hide show
  1. package/README.md +51 -147
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +48 -63
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +38 -54
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +293 -487
  8. package/dist/commands/conversation.d.ts +27 -0
  9. package/dist/commands/conversation.js +702 -0
  10. package/dist/commands/doctor.d.ts +5 -1
  11. package/dist/commands/doctor.js +129 -34
  12. package/dist/commands/init.d.ts +4 -45
  13. package/dist/commands/init.js +108 -66
  14. package/dist/commands/project-env.d.ts +62 -2
  15. package/dist/commands/project-env.js +388 -37
  16. package/dist/commands/project-sign-in.d.ts +0 -48
  17. package/dist/commands/project-sign-in.js +1 -229
  18. package/dist/commands/project.d.ts +15 -186
  19. package/dist/commands/project.js +89 -924
  20. package/dist/commands/result.d.ts +10 -0
  21. package/dist/commands/result.js +215 -0
  22. package/dist/commands/schedule.d.ts +0 -29
  23. package/dist/commands/schedule.js +28 -87
  24. package/dist/commands/test.d.ts +301 -1816
  25. package/dist/commands/test.js +1951 -13902
  26. package/dist/commands/testlist.d.ts +128 -5
  27. package/dist/commands/testlist.js +269 -339
  28. package/dist/commands/tunnel.d.ts +2 -2
  29. package/dist/commands/tunnel.js +23 -19
  30. package/dist/commands/usage.d.ts +12 -45
  31. package/dist/commands/usage.js +50 -131
  32. package/dist/index.js +182 -104
  33. package/dist/lib/agent-detect.js +9 -5
  34. package/dist/lib/agent-targets.d.ts +21 -2
  35. package/dist/lib/agent-targets.js +88 -11
  36. package/dist/lib/args.d.ts +13 -0
  37. package/dist/lib/args.js +49 -0
  38. package/dist/lib/basic-auth.d.ts +3 -0
  39. package/dist/lib/basic-auth.js +15 -0
  40. package/dist/lib/billing-refusal.js +4 -3
  41. package/dist/lib/ci-linkage.d.ts +4 -82
  42. package/dist/lib/ci-linkage.js +4 -157
  43. package/dist/lib/ci-run.js +1 -1
  44. package/dist/lib/client-factory.d.ts +10 -2
  45. package/dist/lib/client-factory.js +38 -26
  46. package/dist/lib/commit-signal.d.ts +65 -0
  47. package/dist/lib/commit-signal.js +305 -0
  48. package/dist/lib/concurrency-limiter.d.ts +6 -0
  49. package/dist/lib/concurrency-limiter.js +29 -0
  50. package/dist/lib/config.js +10 -5
  51. package/dist/lib/conflict-reason.d.ts +9 -3
  52. package/dist/lib/conflict-reason.js +6 -3
  53. package/dist/lib/conversation/answers.d.ts +9 -0
  54. package/dist/lib/conversation/answers.js +49 -0
  55. package/dist/lib/conversation/api.d.ts +71 -0
  56. package/dist/lib/conversation/api.js +150 -0
  57. package/dist/lib/conversation/change.d.ts +31 -0
  58. package/dist/lib/conversation/change.js +124 -0
  59. package/dist/lib/conversation/context.d.ts +19 -0
  60. package/dist/lib/conversation/context.js +70 -0
  61. package/dist/lib/conversation/environment.d.ts +15 -0
  62. package/dist/lib/conversation/environment.js +33 -0
  63. package/dist/lib/conversation/follow.d.ts +24 -0
  64. package/dist/lib/conversation/follow.js +42 -0
  65. package/dist/lib/conversation/render.d.ts +33 -0
  66. package/dist/lib/conversation/render.js +315 -0
  67. package/dist/lib/conversation/title.d.ts +2 -0
  68. package/dist/lib/conversation/title.js +18 -0
  69. package/dist/lib/conversation/types.d.ts +156 -0
  70. package/dist/lib/conversation/types.js +6 -0
  71. package/dist/lib/credentials.js +67 -11
  72. package/dist/lib/cron.d.ts +1 -1
  73. package/dist/lib/cron.js +2 -2
  74. package/dist/lib/dispatch-stop.d.ts +20 -0
  75. package/dist/lib/dispatch-stop.js +30 -0
  76. package/dist/lib/download.d.ts +71 -0
  77. package/dist/lib/download.js +274 -0
  78. package/dist/lib/dry-run/fetch.d.ts +10 -0
  79. package/dist/lib/dry-run/fetch.js +20 -0
  80. package/dist/lib/dry-run/samples.d.ts +6 -34
  81. package/dist/lib/dry-run/samples.js +375 -747
  82. package/dist/lib/environment-tunnel.d.ts +16 -27
  83. package/dist/lib/environment-tunnel.js +161 -154
  84. package/dist/lib/errors.d.ts +20 -4
  85. package/dist/lib/errors.js +36 -16
  86. package/dist/lib/facade.d.ts +7 -29
  87. package/dist/lib/facade.js +7 -36
  88. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  89. package/dist/lib/failing-fe-resolver.js +47 -132
  90. package/dist/lib/first-suite-hint.d.ts +16 -22
  91. package/dist/lib/first-suite-hint.js +38 -47
  92. package/dist/lib/gh-output.d.ts +76 -21
  93. package/dist/lib/gh-output.js +171 -90
  94. package/dist/lib/git-utils.d.ts +56 -0
  95. package/dist/lib/git-utils.js +212 -0
  96. package/dist/lib/github-context.d.ts +2 -0
  97. package/dist/lib/github-context.js +40 -8
  98. package/dist/lib/history-retention.d.ts +6 -2
  99. package/dist/lib/history-retention.js +10 -7
  100. package/dist/lib/http.d.ts +58 -134
  101. package/dist/lib/http.js +352 -289
  102. package/dist/lib/interrupt.d.ts +14 -8
  103. package/dist/lib/interrupt.js +28 -10
  104. package/dist/lib/junit-report.d.ts +57 -4
  105. package/dist/lib/junit-report.js +202 -32
  106. package/dist/lib/local-target.d.ts +3 -3
  107. package/dist/lib/local-target.js +3 -3
  108. package/dist/lib/output.d.ts +1 -40
  109. package/dist/lib/output.js +11 -49
  110. package/dist/lib/pagination.d.ts +2 -5
  111. package/dist/lib/pagination.js +2 -5
  112. package/dist/lib/presigned-url.d.ts +22 -0
  113. package/dist/lib/presigned-url.js +90 -0
  114. package/dist/lib/prompt.js +36 -2
  115. package/dist/lib/proxy.js +2 -1
  116. package/dist/lib/redact.d.ts +2 -2
  117. package/dist/lib/redact.js +3 -4
  118. package/dist/lib/removed-commands.d.ts +18 -0
  119. package/dist/lib/removed-commands.js +154 -0
  120. package/dist/lib/render-error.d.ts +31 -6
  121. package/dist/lib/render-error.js +88 -25
  122. package/dist/lib/response-schemas.d.ts +38 -30
  123. package/dist/lib/response-schemas.js +207 -207
  124. package/dist/lib/result/api.d.ts +24 -0
  125. package/dist/lib/result/api.js +28 -0
  126. package/dist/lib/result/evidence.d.ts +71 -0
  127. package/dist/lib/result/evidence.js +420 -0
  128. package/dist/lib/result/render.d.ts +20 -0
  129. package/dist/lib/result/render.js +194 -0
  130. package/dist/lib/result/types.d.ts +122 -0
  131. package/dist/lib/result/types.js +19 -0
  132. package/dist/lib/run-output.d.ts +275 -0
  133. package/dist/lib/run-output.js +227 -0
  134. package/dist/lib/run-render.d.ts +101 -0
  135. package/dist/lib/run-render.js +183 -0
  136. package/dist/lib/run-wait.d.ts +192 -0
  137. package/dist/lib/run-wait.js +452 -0
  138. package/dist/lib/runs.types.d.ts +118 -367
  139. package/dist/lib/runs.types.js +0 -14
  140. package/dist/lib/secret-file.d.ts +1 -1
  141. package/dist/lib/secret-file.js +11 -2
  142. package/dist/lib/skill-nudge.d.ts +7 -27
  143. package/dist/lib/skill-nudge.js +9 -37
  144. package/dist/lib/target-path.d.ts +15 -0
  145. package/dist/lib/target-path.js +35 -0
  146. package/dist/lib/target-url-advisory.d.ts +19 -0
  147. package/dist/lib/target-url-advisory.js +31 -0
  148. package/dist/lib/target-url-preflight.d.ts +9 -0
  149. package/dist/lib/target-url-preflight.js +214 -106
  150. package/dist/lib/target-url.d.ts +1 -1
  151. package/dist/lib/target-url.js +6 -16
  152. package/dist/lib/telemetry.d.ts +31 -11
  153. package/dist/lib/telemetry.js +37 -8
  154. package/dist/lib/terminal-text.d.ts +41 -0
  155. package/dist/lib/terminal-text.js +127 -0
  156. package/dist/lib/testlist.types.d.ts +16 -8
  157. package/dist/lib/testlist.types.js +1 -1
  158. package/dist/lib/text-equality.d.ts +2 -0
  159. package/dist/lib/text-equality.js +5 -0
  160. package/dist/lib/text-file.d.ts +16 -0
  161. package/dist/lib/text-file.js +41 -0
  162. package/dist/lib/text-table.d.ts +46 -0
  163. package/dist/lib/text-table.js +72 -4
  164. package/dist/lib/ticker.d.ts +9 -2
  165. package/dist/lib/ticker.js +16 -3
  166. package/dist/lib/transport-failure.d.ts +22 -0
  167. package/dist/lib/transport-failure.js +126 -0
  168. package/dist/lib/tunnel-session.d.ts +7 -1
  169. package/dist/lib/tunnel-session.js +22 -9
  170. package/dist/lib/update-check.js +3 -2
  171. package/dist/lib/url-template.d.ts +43 -0
  172. package/dist/lib/url-template.js +151 -0
  173. package/dist/lib/validate.d.ts +0 -64
  174. package/dist/lib/validate.js +2 -131
  175. package/dist/lib/version-notice.js +4 -3
  176. package/dist/lib/wait-exit.d.ts +37 -2
  177. package/dist/lib/wait-exit.js +88 -30
  178. package/dist/lib/workspace-status.js +10 -2
  179. package/dist/version.d.ts +1 -1
  180. package/dist/version.js +1 -1
  181. package/package.json +2 -3
  182. package/skills/testsprite-ci.skill.md +48 -18
  183. package/skills/testsprite-onboard.skill.md +66 -151
  184. package/skills/testsprite-verify.codex.md +50 -52
  185. package/skills/testsprite-verify.skill.md +184 -351
  186. package/dist/lib/browser.d.ts +0 -6
  187. package/dist/lib/browser.js +0 -54
  188. package/dist/lib/bundle.d.ts +0 -234
  189. package/dist/lib/bundle.js +0 -781
  190. package/dist/lib/deprecate.d.ts +0 -32
  191. package/dist/lib/deprecate.js +0 -39
  192. package/dist/lib/flaky.d.ts +0 -91
  193. package/dist/lib/flaky.js +0 -71
  194. package/dist/lib/plan-poll.d.ts +0 -171
  195. package/dist/lib/plan-poll.js +0 -441
  196. package/dist/lib/plans.types.d.ts +0 -130
  197. package/dist/lib/plans.types.js +0 -31
  198. package/dist/lib/poll.d.ts +0 -100
  199. package/dist/lib/poll.js +0 -290
  200. package/dist/lib/rate-throttle.d.ts +0 -49
  201. package/dist/lib/rate-throttle.js +0 -75
  202. package/dist/lib/run-progress.d.ts +0 -41
  203. package/dist/lib/run-progress.js +0 -56
  204. package/dist/lib/v3-advisory.d.ts +0 -55
  205. package/dist/lib/v3-advisory.js +0 -74
  206. package/schemas/plan.schema.json +0 -61
@@ -1,6 +1,7 @@
1
- import { TunnelLostError } from '../lib/tunnel-session.js';
1
+ import { waitForRun, resolveRunWaitFailure } from '../lib/run-wait.js';
2
2
  import { resolveEnvironmentRunTarget, readEnvironmentPreflight, groupEnvironmentTargets, emitEnvironmentDispatchPartial, withEnvironmentTunnel, } from '../lib/environment-tunnel.js';
3
3
  import { globalShutdown } from '../lib/interrupt.js';
4
+ import { TunnelLostError } from '../lib/tunnel-session.js';
4
5
  import { randomUUID } from 'node:crypto';
5
6
  import { Command } from 'commander';
6
7
  import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
@@ -8,16 +9,18 @@ import { ApiError, CLIError, InterruptError, RequestTimeoutError, localValidatio
8
9
  import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, } from '../lib/http.js';
9
10
  import { resolveProfileName } from '../lib/config.js';
10
11
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
11
- import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
12
- import { emitCiArtifacts, summarizeAcceptedPayload } from '../lib/gh-output.js';
12
+ import { emitCiArtifacts } from '../lib/gh-output.js';
13
+ import { buildRunOutput, listResultReceipt, previewRun, renderRunResults, } from '../lib/run-output.js';
13
14
  import { billingConflictLink, describeConflict, insufficientCreditsConflictError, isAllCreditsRefusal, isPausedRefusal, pausedConflictError, summarizeConflicts, } from '../lib/conflict-reason.js';
14
15
  import { recordBatchOutcome } from '../lib/telemetry.js';
15
- import { formatRunProgressLine } from '../lib/run-progress.js';
16
- import { createTicker } from '../lib/ticker.js';
17
- import { buildJUnitReport, durationSecondsBetween, parseJUnitReportFormat, skippedJUnitResultsFromSummary, writeJUnitReportFile, } from '../lib/junit-report.js';
16
+ import { markRunWaitInterrupt } from '../lib/render-error.js';
17
+ import { interruptDetachMessage, launchIds, waitCommand } from '../lib/run-render.js';
18
+ import { assertJUnitReportOptions, buildJUnitReport, parseJUnitReportFormat, skippedJUnitResultsFromSummary, writeJUnitReportFile, writeReportOwing, assertArtifactPath, } from '../lib/junit-report.js';
18
19
  import { renderTextTable, resolveTextColumns } from '../lib/text-table.js';
19
20
  import { assertIdempotencyKey } from '../lib/validate.js';
20
- import { resolveWaitFailure, waitMemberError } from '../lib/wait-exit.js';
21
+ import { terminalSafeLine, terminalSafeWriter } from '../lib/terminal-text.js';
22
+ /** Why a `--case` id the server reports as not found was not dispatched. */
23
+ const NOT_A_MEMBER_NOTE = 'not a member of this list (not dispatched)';
21
24
  // ── helpers ──────────────────────────────────────────────────────────────────
22
25
  function resolveCommonOptions(command, env) {
23
26
  const g = command.optsWithGlobals();
@@ -44,7 +47,7 @@ function makeOutput(mode, deps) {
44
47
  }
45
48
  function emitIdempotencyKey(opts, deps, key, supplied) {
46
49
  if (supplied === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
47
- const stderr = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
50
+ const stderr = terminalSafeWriter(deps.stderr);
48
51
  stderr(`idempotency-key: ${key}`);
49
52
  }
50
53
  }
@@ -67,17 +70,18 @@ function parseProjectEnvs(pairs) {
67
70
  }
68
71
  const collectRepeatable = (value, acc) => [...acc, value];
69
72
  function dryRunStderr(deps) {
70
- return deps.stderr ?? (line => process.stderr.write(`${line}\n`));
73
+ return terminalSafeWriter(deps.stderr);
71
74
  }
72
75
  // Canned `--dry-run` samples (offline, no network) — the global `--dry-run`
73
- // contract promises a shape-accurate sample for every command.
76
+ // contract promises a shape-accurate sample for every command. They are wire
77
+ // shapes, printed under the output names like a real response.
74
78
  const DRY_RUN_LIST = {
75
79
  id: 'tl_dryrun',
76
80
  name: 'dry-run test list',
77
81
  orgId: 'org_dryrun',
78
82
  caseCount: 0,
79
83
  projectEnvironments: [],
80
- lastExecutionId: null,
84
+ lastRunId: null,
81
85
  createdAt: '2026-05-16T00:00:00.000Z',
82
86
  updatedAt: '2026-05-16T00:00:00.000Z',
83
87
  };
@@ -85,7 +89,7 @@ const DRY_RUN_DETAIL = {
85
89
  ...DRY_RUN_LIST,
86
90
  cases: [],
87
91
  stats: { total: 0, passed: 0, failed: 0, blocked: 0, running: 0 },
88
- lastExecutionCreated: null,
92
+ lastRunCreated: null,
89
93
  };
90
94
  // ── run functions (called directly by tests) ─────────────────────────────────
91
95
  export async function runTestlistList(opts, deps = {}) {
@@ -95,24 +99,24 @@ export async function runTestlistList(opts, deps = {}) {
95
99
  }
96
100
  if (opts.dryRun) {
97
101
  emitDryRunBanner(dryRunStderr(deps));
98
- out.print([DRY_RUN_LIST], data => renderTestListListText(data, opts));
102
+ printTestLists(out, [DRY_RUN_LIST], opts);
99
103
  return [DRY_RUN_LIST];
100
104
  }
101
105
  const client = makeClient(opts, deps);
102
106
  const resp = await client.get('/testlist');
103
- out.print(resp.items, data => renderTestListListText(data, opts));
107
+ printTestLists(out, resp.items, opts);
104
108
  return resp.items;
105
109
  }
106
110
  export async function runTestlistGet(opts, deps = {}) {
107
111
  const out = makeOutput(opts.output, deps);
108
112
  if (opts.dryRun) {
109
113
  emitDryRunBanner(dryRunStderr(deps));
110
- out.print(DRY_RUN_DETAIL, data => renderTestListDetailText(data));
114
+ printTestListDetail(out, DRY_RUN_DETAIL);
111
115
  return DRY_RUN_DETAIL;
112
116
  }
113
117
  const client = makeClient(opts, deps);
114
118
  const detail = await client.get(`/testlist/${encodeURIComponent(opts.listId)}`);
115
- out.print(detail, data => renderTestListDetailText(data));
119
+ printTestListDetail(out, detail);
116
120
  return detail;
117
121
  }
118
122
  export async function runTestlistCreate(opts, deps = {}) {
@@ -128,7 +132,7 @@ export async function runTestlistCreate(opts, deps = {}) {
128
132
  if (opts.dryRun) {
129
133
  emitDryRunBanner(dryRunStderr(deps));
130
134
  const sample = { ...DRY_RUN_DETAIL, name: opts.name };
131
- out.print(sample, data => renderTestListDetailText(data));
135
+ printTestListDetail(out, sample);
132
136
  return sample;
133
137
  }
134
138
  const client = makeClient(opts, deps);
@@ -136,7 +140,7 @@ export async function runTestlistCreate(opts, deps = {}) {
136
140
  body: { name: opts.name, ...(projectEnvironments ? { projectEnvironments } : {}) },
137
141
  headers: { 'idempotency-key': idempotencyKey },
138
142
  });
139
- out.print(detail, data => renderTestListDetailText(data));
143
+ printTestListDetail(out, detail);
140
144
  return detail;
141
145
  }
142
146
  export async function runTestlistUpdate(opts, deps = {}) {
@@ -151,14 +155,14 @@ export async function runTestlistUpdate(opts, deps = {}) {
151
155
  if (opts.idempotencyKey !== undefined)
152
156
  assertIdempotencyKey(opts.idempotencyKey);
153
157
  // `[]` (clear) vs the parsed array vs `undefined` (leave untouched) — the
154
- // three cases the V3 update contract distinguishes.
158
+ // three cases the update contract distinguishes.
155
159
  const projectEnvironments = opts.clearProjectEnv ? [] : parseProjectEnvs(opts.projectEnv);
156
160
  const idempotencyKey = opts.idempotencyKey ?? `cli-testlist-update-${randomUUID()}`;
157
161
  emitIdempotencyKey(opts, deps, idempotencyKey, opts.idempotencyKey);
158
162
  if (opts.dryRun) {
159
163
  emitDryRunBanner(dryRunStderr(deps));
160
164
  const sample = { ...DRY_RUN_DETAIL, ...(opts.name !== undefined ? { name: opts.name } : {}) };
161
- out.print(sample, data => renderTestListDetailText(data));
165
+ printTestListDetail(out, sample);
162
166
  return sample;
163
167
  }
164
168
  const client = makeClient(opts, deps);
@@ -169,7 +173,7 @@ export async function runTestlistUpdate(opts, deps = {}) {
169
173
  },
170
174
  headers: { 'idempotency-key': idempotencyKey },
171
175
  });
172
- out.print(detail, data => renderTestListDetailText(data));
176
+ printTestListDetail(out, detail);
173
177
  return detail;
174
178
  }
175
179
  export async function runTestlistDelete(opts, deps = {}) {
@@ -188,12 +192,12 @@ export async function runTestlistDelete(opts, deps = {}) {
188
192
  if (opts.dryRun) {
189
193
  emitDryRunBanner(dryRunStderr(deps));
190
194
  const sample = { listId: opts.listId };
191
- out.print(sample, data => `Deleted test list ${data.listId}`);
195
+ out.print(sample, data => `Deleted test list ${terminalSafeLine(data.listId)}`);
192
196
  return sample;
193
197
  }
194
198
  const client = makeClient(opts, deps);
195
199
  const resp = await client.delete(`/testlist/${encodeURIComponent(opts.listId)}`, { headers: { 'idempotency-key': idempotencyKey } });
196
- out.print(resp, data => `Deleted test list ${data.listId}`);
200
+ out.print(resp, data => `Deleted test list ${terminalSafeLine(data.listId)}`);
197
201
  return resp;
198
202
  }
199
203
  async function mutateCases(verb, opts, deps) {
@@ -207,7 +211,7 @@ async function mutateCases(verb, opts, deps) {
207
211
  emitIdempotencyKey(opts, deps, idempotencyKey, opts.idempotencyKey);
208
212
  if (opts.dryRun) {
209
213
  emitDryRunBanner(dryRunStderr(deps));
210
- out.print(DRY_RUN_DETAIL, data => renderTestListDetailText(data));
214
+ printTestListDetail(out, DRY_RUN_DETAIL);
211
215
  return DRY_RUN_DETAIL;
212
216
  }
213
217
  const path = verb === 'add'
@@ -218,7 +222,7 @@ async function mutateCases(verb, opts, deps) {
218
222
  body: { testIds: opts.testIds },
219
223
  headers: { 'idempotency-key': idempotencyKey },
220
224
  });
221
- out.print(detail, data => renderTestListDetailText(data));
225
+ printTestListDetail(out, detail);
222
226
  return detail;
223
227
  }
224
228
  export const runTestlistAdd = (opts, deps = {}) => mutateCases('add', opts, deps);
@@ -232,7 +236,7 @@ const WAIT_REQUEST_TIMEOUT_CUSHION_MS = 5_000;
232
236
  * Under `--wait`, raise the per-request HTTP timeout to cover `--timeout` so a
233
237
  * slow trigger / long-poll on a large list isn't cut short by the default 120s
234
238
  * request deadline and mis-reported as a member timeout. Mirrors
235
- * `test run`'s `resolveWaitRequestTimeoutMs` (reimplemented locally to keep this
239
+ * `run`'s `resolveWaitRequestTimeoutMs` (reimplemented locally to keep this
236
240
  * file off the `test.ts` module — see the security-lint note on `run`).
237
241
  */
238
242
  export function waitRequestTimeoutMs(opts) {
@@ -242,7 +246,7 @@ export function waitRequestTimeoutMs(opts) {
242
246
  const cover = Math.min(opts.timeoutSeconds * 1000 + WAIT_REQUEST_TIMEOUT_CUSHION_MS, REQUEST_TIMEOUT_MAX_MS);
243
247
  return Math.max(base, cover);
244
248
  }
245
- /** Parse `--timeout <s>` (1–3600, default 600). Mirrors `test run`'s bounds. */
249
+ /** Parse `--timeout <s>` (1–3600, default 600). Mirrors `run`'s bounds. */
246
250
  function parseTestlistTimeoutFlag(raw) {
247
251
  if (raw === undefined)
248
252
  return DEFAULT_TESTLIST_RUN_TIMEOUT_SECONDS;
@@ -264,7 +268,7 @@ function parseTestlistConcurrencyFlag(raw) {
264
268
  }
265
269
  /**
266
270
  * Rate-deferred members were never dispatched → the batch is incomplete (exit 7),
267
- * mirroring `test run --all`. The backend applies the same per-key run-rate
271
+ * mirroring `run --project`. The backend applies the same per-key run-rate
268
272
  * soft-fold as `POST /tests/batch/run` and returns the overflow here, so a
269
273
  * partial dispatch surfaces as a non-zero exit instead of silently passing CI.
270
274
  */
@@ -285,12 +289,12 @@ function assertNoDeferred(resp) {
285
289
  function assertNoNotFound(resp) {
286
290
  if (!resp.notFound || resp.notFound.length === 0)
287
291
  return;
288
- throw new CLIError(`${resp.notFound.length} --case id(s) not in this list: ${resp.notFound.join(' ')}`, 4);
292
+ throw new CLIError(`${resp.notFound.length} test ID(s) not in this list: ${resp.notFound.join(' ')}`, 4);
289
293
  }
290
294
  /**
291
- * `testlist run` — dispatch the list's cases (optionally a `--case` subset) and,
292
- * with `--wait`, poll every returned runId to a verdict, optionally writing a
293
- * JUnit XML report (`--report junit`). testlist run is V3-only.
295
+ * `run --testlist` — dispatch the list's cases (optionally a `--case` subset) and,
296
+ * with `--wait`, poll every returned resultId to a verdict, optionally writing a
297
+ * JUnit XML report (`--report junit`).
294
298
  */
295
299
  function validateTestlistRunOptions(opts) {
296
300
  if (opts.idempotencyKey !== undefined)
@@ -300,23 +304,26 @@ function validateTestlistRunOptions(opts) {
300
304
  opts.maxConcurrency > MAX_TESTLIST_RUN_CONCURRENCY) {
301
305
  throw localValidationError('max-concurrency', `must be an integer between 1 and ${MAX_TESTLIST_RUN_CONCURRENCY}`);
302
306
  }
303
- if (opts.report === 'junit' && opts.reportFile === undefined) {
304
- throw localValidationError('report-file', 'required when --report junit is set');
305
- }
306
- if (opts.report === 'junit' && !opts.wait) {
307
- throw localValidationError('report', '--report junit requires --wait (verdicts come from the poll)');
308
- }
307
+ // Same report-flag rules as `run` via the shared
308
+ // validator: orphan --report-file / --report-suite-name and --report junit
309
+ // without --wait are refused before anything is dispatched (#569).
310
+ assertJUnitReportOptions({ ...opts, wait: opts.wait === true, batchPath: true });
309
311
  // --gh-output / --summary-file reduce a --wait run's per-member results into the
310
312
  // CI summary. They require --wait (without it the command returns after dispatch,
311
313
  // before any terminal result exists) — reject loudly, same rule as --report junit
312
- // above and the sibling `test run` flags. Gate only the EXPLICIT flags; the
313
- // GITHUB_ACTIONS auto-enable must stay silent without --wait, same as `test run`.
314
+ // above and the sibling `run` flags. Gate only the EXPLICIT flags; the
315
+ // GITHUB_ACTIONS auto-enable must stay silent without --wait, same as `run`.
314
316
  if (opts.ghOutput === true && !opts.wait) {
315
317
  throw localValidationError('gh-output', '--gh-output requires --wait (it reduces the terminal run result). Add --wait.');
316
318
  }
317
319
  if (opts.summaryFile !== undefined && !opts.wait) {
318
320
  throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
319
321
  }
322
+ if (opts.report === 'junit' && opts.reportFile !== undefined) {
323
+ assertArtifactPath('report-file', opts.reportFile);
324
+ }
325
+ if (opts.summaryFile !== undefined)
326
+ assertArtifactPath('summary-file', opts.summaryFile);
320
327
  }
321
328
  export async function runTestlistRun(opts, deps = {}) {
322
329
  validateTestlistRunOptions({ ...opts, wait: opts.wait || (!opts.dryRun && !opts.noWait) });
@@ -330,7 +337,7 @@ export async function runTestlistRun(opts, deps = {}) {
330
337
  validateTestlistRunOptions(opts);
331
338
  throw err;
332
339
  }
333
- const stderr = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
340
+ const stderr = terminalSafeWriter(deps.stderr);
334
341
  let list;
335
342
  try {
336
343
  list = await readEnvironmentPreflight(client, `/testlist/${encodeURIComponent(opts.listId)}`);
@@ -375,23 +382,39 @@ export async function runTestlistRun(opts, deps = {}) {
375
382
  (!opts.cases?.length || opts.cases.includes(test.testId)))
376
383
  .map(test => test.testId);
377
384
  cases.push(...(opts.cases ?? []).filter(id => !list.cases?.some(test => test.testId === id)));
378
- return withEnvironmentTunnel({ ...opts, maxConcurrency, requestTimeoutMs: waitRequestTimeoutMs({ ...opts, wait: true }) }, deps, [...targets.values()], 'testlist run', context => {
385
+ return withEnvironmentTunnel({ ...opts, maxConcurrency, requestTimeoutMs: waitRequestTimeoutMs({ ...opts, wait: true }) }, deps, [...targets.values()], 'run', context => {
379
386
  context.targets = targets;
380
387
  context.skipped = backend;
381
388
  return runTestlistRunCore({ ...opts, cases, wait: true, maxConcurrency }, { ...deps, environmentTunnel: context });
382
389
  });
383
390
  }
391
+ /**
392
+ * Dispatch selected list members and optionally collect their terminal results.
393
+ * On interruption, emit acknowledged runs and settled outcomes before rethrowing;
394
+ * tunnel execution retains its separate cancellation and partial-output handling.
395
+ */
384
396
  async function runTestlistRunCore(opts, deps = {}) {
385
397
  validateTestlistRunOptions(opts);
386
398
  const out = makeOutput(opts.output, deps);
387
- const stderrFn = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
399
+ const stderrFn = terminalSafeWriter(deps.stderr);
388
400
  const idempotencyKey = opts.idempotencyKey ?? `cli-testlist-run-${randomUUID()}`;
389
401
  emitIdempotencyKey(opts, deps, idempotencyKey, opts.idempotencyKey);
390
402
  if (opts.dryRun) {
391
403
  emitDryRunBanner(dryRunStderr(deps));
392
- const sample = { accepted: [], conflicts: [], deferred: [] };
393
- out.print(sample, () => 'dry-run: no runs dispatched');
394
- return sample;
404
+ const path = `/api/cli/v1/testlist/${encodeURIComponent(opts.listId)}/run`;
405
+ const preview = previewRun([
406
+ {
407
+ method: 'POST',
408
+ path,
409
+ body: {
410
+ ...(opts.cases?.length ? { testIds: opts.cases } : {}),
411
+ maxConcurrency: opts.maxConcurrency,
412
+ },
413
+ idempotencyKey,
414
+ },
415
+ ], opts.wait, opts.wait);
416
+ out.print(preview, () => `dry-run: POST ${path}`);
417
+ return preview;
395
418
  }
396
419
  // Under --wait, raise the per-request timeout to cover --timeout (see helper).
397
420
  const client = deps.environmentTunnel?.client ??
@@ -399,28 +422,42 @@ async function runTestlistRunCore(opts, deps = {}) {
399
422
  let resp;
400
423
  if (deps.environmentTunnel) {
401
424
  const targets = deps.environmentTunnel.targets;
402
- const groups = groupEnvironmentTargets(opts.cases ?? [...targets.keys()], targets, deps.environmentTunnel.maxConcurrency);
425
+ const groups = groupEnvironmentTargets(opts.cases ?? [...targets.keys()], targets);
403
426
  const responses = [];
404
427
  try {
405
428
  for (const [index, testIds] of groups.entries()) {
406
429
  const target = targets.get(testIds[0]);
407
430
  const suffix = groups.length > 1 ? `:group${index}` : '';
408
- if (target)
409
- await deps.environmentTunnel.waitForCapacity(testIds.length);
410
431
  const response = await client.triggerTestListRun(opts.listId, {
411
432
  testIds,
433
+ maxConcurrency: target ? deps.environmentTunnel.maxConcurrency : opts.maxConcurrency,
412
434
  ...(target
413
435
  ? { targetUrl: target.targetUrl, tunnelClientId: deps.environmentTunnel.clientId }
414
436
  : {}),
415
437
  }, { idempotencyKey: `${idempotencyKey.slice(0, 256 - suffix.length)}${suffix}` });
416
438
  responses.push(response);
417
- if (target)
418
- await deps.environmentTunnel.confirm(response, response.accepted.map(row => row.runId));
439
+ if (target) {
440
+ // The response also tells the tunnel which launch each result is in.
441
+ await deps.environmentTunnel.confirm(response, response.accepted.flatMap(row => (row.runId ? [row.runId] : [])));
442
+ if (response.accepted.some(row => row.runId) &&
443
+ (!Number.isInteger(response.maxConcurrency) ||
444
+ response.maxConcurrency < 1 ||
445
+ response.maxConcurrency > deps.environmentTunnel.maxConcurrency)) {
446
+ await deps.environmentTunnel.cancelActive();
447
+ throw new ApiError({
448
+ code: 'UNSUPPORTED',
449
+ message: 'The server did not confirm the requested local concurrency limit.',
450
+ nextAction: 'Upgrade the backend before retrying this local test-list run.',
451
+ requestId: 'local',
452
+ details: { field: 'maxConcurrency' },
453
+ });
454
+ }
455
+ }
419
456
  }
420
457
  }
421
458
  catch (err) {
422
459
  if (responses.length)
423
- await emitEnvironmentDispatchPartial(responses, groups.flat(), opts, deps, 'testlist', err, deps.environmentTunnel);
460
+ await emitEnvironmentDispatchPartial(responses, groups.flat(), opts, deps, 'testlist', err, deps.environmentTunnel, NOT_A_MEMBER_NOTE);
424
461
  throw err;
425
462
  }
426
463
  resp = {
@@ -437,27 +474,43 @@ async function runTestlistRunCore(opts, deps = {}) {
437
474
  };
438
475
  }
439
476
  else {
440
- resp = await client.triggerTestListRun(opts.listId, opts.cases && opts.cases.length > 0 ? { testIds: opts.cases } : {}, { idempotencyKey });
477
+ resp = await client.triggerTestListRun(opts.listId, {
478
+ ...(opts.cases?.length ? { testIds: opts.cases } : {}),
479
+ maxConcurrency: opts.maxConcurrency,
480
+ }, { idempotencyKey });
441
481
  }
442
482
  // Partial `--case` miss: some ids were not members of this list. The matched
443
483
  // subset still dispatched; a FULL miss is a 404 upstream and never reaches
444
484
  // here. Warn on stderr so JSON stdout stays the machine payload (the ids are
445
485
  // also carried on `resp.notFound`).
446
486
  if (resp.notFound && resp.notFound.length > 0) {
447
- stderrFn(`warning: ${resp.notFound.length} --case id(s) not in this list, skipped: ${resp.notFound.join(' ')}`);
487
+ stderrFn(`warning: ${resp.notFound.length} test ID(s) not in this list, skipped: ${terminalSafeLine(resp.notFound.join(' '))}`);
448
488
  }
449
489
  if (resp.accepted.length > 0) {
450
490
  const link = billingConflictLink(resp.conflicts, client.resolvedBaseUrl);
451
491
  if (link)
452
492
  stderrFn(`[advisory] Billing refusal for some tests.${link}`);
453
493
  }
494
+ const { accepted, ...dispatchMetadata } = resp;
495
+ const runIds = launchIds(accepted);
496
+ const receipts = runIds.map(runId => ({ runId }));
497
+ const dispatched = accepted.map(listResultReceipt);
498
+ const outputOptions = {
499
+ receipts,
500
+ dispatched,
501
+ wait: opts.wait,
502
+ buckets: dispatchMetadata,
503
+ notFoundNote: NOT_A_MEMBER_NOTE,
504
+ cancellation: deps.environmentTunnel?.cancellation,
505
+ };
454
506
  // All-conflict: nothing new dispatched because every targeted case is already
455
507
  // in flight → exit 6, for BOTH --wait and non-wait (a --wait over zero accepted
456
508
  // would otherwise no-op straight to exit 0). Distinct from the empty/no-match
457
509
  // case (accepted AND conflicts both empty), which is a legitimate success and
458
510
  // flows through the tail below so its CI artifacts are still emitted.
459
511
  if (resp.accepted.length === 0 && resp.conflicts.length > 0) {
460
- out.print(resp, () => renderRunAcceptedText(resp));
512
+ const { output, summary } = buildRunOutput(outputOptions);
513
+ out.print({ ...output, ...dispatchMetadata }, () => renderRunResults(output.runs, output.results, opts.wait ? summary : undefined, conflictRows(resp.conflicts)));
461
514
  recordBatchOutcome({
462
515
  accepted: 0,
463
516
  conflicts: resp.conflicts,
@@ -470,29 +523,20 @@ async function runTestlistRunCore(opts, deps = {}) {
470
523
  // into the summary as non-passed rows. The non-wait path never emits CI
471
524
  // artifacts, matching the main tail below.
472
525
  if (opts.wait) {
473
- const summary = summarizeAcceptedPayload(JSON.stringify({
474
- accepted: [],
475
- conflicts: resp.conflicts,
476
- deferred: resp.deferred,
477
- // Include notFound too: a mixed `--case` selection can be
478
- // all-conflict on its matched ids AND carry not-in-list ids, and the
479
- // CI summary must report the whole requested set (same reason the
480
- // main --wait envelope threads it). Undefined ⇒ JSON.stringify drops it.
481
- notFound: resp.notFound,
482
- }), { notFoundNote: 'not a member of this list (not dispatched)' });
483
526
  if (opts.report === 'junit' && opts.reportFile !== undefined) {
527
+ const file = opts.reportFile;
484
528
  const suiteName = opts.reportSuiteName ?? `testsprite:testlist:${opts.listId}`;
485
- await writeJUnitReportFile(opts.reportFile, buildJUnitReport({
529
+ await writeReportOwing(true, () => writeJUnitReportFile(file, buildJUnitReport({
486
530
  suiteName,
487
531
  classname: `testlist:${opts.listId}`,
488
532
  results: skippedJUnitResultsFromSummary(summary),
489
- }));
533
+ })), stderrFn, { label: 'run' });
490
534
  }
491
535
  emitCiArtifacts(summary, opts, {
492
536
  env: deps.env ?? process.env,
493
537
  stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
494
538
  stderr: stderrFn,
495
- }, 'testlist run');
539
+ }, 'run');
496
540
  }
497
541
  // Every case refused for credits → exit 12, the same INSUFFICIENT_CREDITS
498
542
  // envelope the single-run route answers (a rate-deferred remainder is exit 7
@@ -503,9 +547,9 @@ async function runTestlistRunCore(opts, deps = {}) {
503
547
  if (isPausedRefusal(resp)) {
504
548
  throw pausedConflictError(resp.conflicts, client.resolvedBaseUrl);
505
549
  }
506
- const pollIds = resp.conflicts
507
- .map(c => c.currentRunId)
508
- .filter((id) => Boolean(id));
550
+ // `run wait` takes the launch holding each in-flight case; a conflict the
551
+ // backend named no launch for has no command to offer.
552
+ const poll = waitCommand(resp.conflicts.map(c => ({ resultId: c.currentResultId, runId: c.currentRunId })));
509
553
  // Name the causes instead of blanket "already in flight" — a list pinned to
510
554
  // a local env or a view-only project is not something to poll. The poll hint
511
555
  // is emitted only for the cases that actually have an in-flight run. A
@@ -514,16 +558,16 @@ async function runTestlistRunCore(opts, deps = {}) {
514
558
  // link — `accepted.length` is 0 in this whole branch, so the advisory
515
559
  // printed earlier (guarded on `accepted.length > 0`) never showed it.
516
560
  throw new CLIError(`Nothing dispatched — ${resp.conflicts.length} conflict(s): ${summarizeConflicts(resp.conflicts)}` +
517
- (pollIds.length > 0
518
- ? `. Poll in-flight runs: testsprite test wait ${pollIds.join(' ')}`
519
- : '') +
561
+ (poll ? `. Poll in-flight runs: ${poll}` : '') +
520
562
  billingConflictLink(resp.conflicts, client.resolvedBaseUrl), 6);
521
563
  }
522
564
  if (!opts.wait) {
523
565
  // Print what dispatched, or the empty/no-match reason. Exit 0.
524
- out.print(resp, () => resp.accepted.length > 0
525
- ? renderRunAcceptedText(resp)
526
- : `No runs dispatched${resp.reason ? ` (${resp.reason})` : ''}.`);
566
+ const { output } = buildRunOutput(outputOptions);
567
+ const launch = { ...output, ...dispatchMetadata };
568
+ out.print(launch, () => resp.accepted.length > 0
569
+ ? renderRunResults(output.runs, output.results, undefined, conflictRows(resp.conflicts))
570
+ : `No runs dispatched${resp.reason ? ` (${terminalSafeLine(resp.reason)})` : ''}.`);
527
571
  recordBatchOutcome({
528
572
  accepted: resp.accepted.length,
529
573
  conflicts: resp.conflicts,
@@ -532,233 +576,142 @@ async function runTestlistRunCore(opts, deps = {}) {
532
576
  });
533
577
  assertNoDeferred(resp);
534
578
  assertNoNotFound(resp);
535
- return resp;
536
- }
537
- // --wait beyond this point. An empty/no-match run (zero accepted, zero
538
- // conflicts) is NOT short-circuited: it flows through the fan-out (a no-op) and
539
- // the report tail so an explicitly-requested --report junit still emits an
540
- // empty-suite report rather than nothing.
541
- // --- --wait fan-out ---
542
- const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
543
- const batchDeadlineMs = deps.environmentTunnel?.deadlineMs ?? Date.now() + opts.timeoutSeconds * 1000;
544
- const results = [];
545
- const reportDurations = new Map();
546
- async function pollOne(entry) {
547
- const remainingMs = batchDeadlineMs - Date.now();
548
- if (remainingMs <= 0) {
549
- return {
550
- testId: entry.testId,
551
- runId: entry.runId,
552
- status: 'timeout',
553
- error: {
554
- code: 'UNSUPPORTED',
555
- message: `Timed out after ${opts.timeoutSeconds}s`,
556
- exitCode: 7,
557
- },
558
- };
559
- }
560
- try {
561
- // testlist run is V3-only; V3 run rows (FE and BE) finalize via the
562
- // execution completion path, so the run-surface poll resolves without the
563
- // V2 BE-orphan-row fallback that `test run` needs.
564
- const finalRun = await pollRunUntilTerminal(client, entry.runId, {
565
- timeoutSeconds: Math.ceil(remainingMs / 1000),
566
- sleep: deps.sleep,
567
- onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
568
- shutdown: deps.shutdown ?? globalShutdown,
569
- onTick: (run, elapsedMs) => {
570
- deps.environmentTunnel?.onPoll(run);
571
- ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`));
572
- },
573
- });
574
- reportDurations.set(entry.runId, durationSecondsBetween(finalRun.startedAt, finalRun.finishedAt, finalRun.createdAt));
575
- return {
576
- testId: entry.testId,
577
- testTitle: finalRun.testTitle ?? null,
578
- // Give the JUnit `<testcase name>` the human title too (testlist has no
579
- // separate name sweep like `test run --all`, so this is its only source;
580
- // renderTestcase falls back to the id when name is absent).
581
- ...(finalRun.testTitle ? { name: finalRun.testTitle } : {}),
582
- runId: entry.runId,
583
- projectId: finalRun.projectId,
584
- status: finalRun.status,
585
- // Carry both SERVER-built links so the ::error:: annotations and the
586
- // job-summary are clickable (parity with `test run --all`): the test-case
587
- // page anchors the Test column title, the execution-result page anchors
588
- // the Run column. Never a client-built resolvePortalUrl — testlist run is
589
- // V3-only and the client helper emits the V2 route shape which 404s.
590
- ...(typeof finalRun.dashboardUrl === 'string'
591
- ? { dashboardUrl: finalRun.dashboardUrl }
592
- : {}),
593
- ...(typeof finalRun.executionUrl === 'string'
594
- ? { executionUrl: finalRun.executionUrl }
595
- : {}),
596
- };
597
- }
598
- catch (err) {
599
- if (deps.environmentTunnel && err instanceof TunnelLostError)
600
- throw err;
601
- if (err instanceof TimeoutError) {
602
- return {
603
- testId: entry.testId,
604
- runId: entry.runId,
605
- status: 'timeout',
606
- error: {
607
- code: 'UNSUPPORTED',
608
- message: `Timed out after ${opts.timeoutSeconds}s`,
609
- exitCode: 7,
579
+ return launch;
580
+ }
581
+ for (const runId of runIds)
582
+ stderrFn(`Run ${terminalSafeLine(runId)}`);
583
+ const deadline = deps.environmentTunnel?.deadlineMs ?? Date.now() + opts.timeoutSeconds * 1000;
584
+ const outcomes = new Map();
585
+ let failure;
586
+ let requestTimedOut = false;
587
+ if (resp.accepted.some(row => !row.runId))
588
+ failure = new ApiError({
589
+ code: 'UNSUPPORTED',
590
+ message: 'The test-list response did not identify every execution.',
591
+ nextAction: 'Update the server before waiting on this test list.',
592
+ requestId: 'local',
593
+ details: {},
594
+ });
595
+ if (!failure) {
596
+ const stopped = new AbortController();
597
+ await Promise.all(runIds.map(async (runId) => {
598
+ if (stopped.signal.aborted)
599
+ return;
600
+ try {
601
+ const outcome = await waitForRun(client, runId, {
602
+ deadline,
603
+ signal: stopped.signal,
604
+ shutdown: deps.shutdown ?? globalShutdown,
605
+ sleep: deps.sleep,
606
+ onRead: async (snapshot, signal) => {
607
+ outcomes.set(runId, { ...snapshot, runId, timedOut: false, missingResultIds: [] });
608
+ await deps.environmentTunnel?.onRead(snapshot, signal);
610
609
  },
611
- };
612
- }
613
- // Interrupt must reject the whole fan-out (never flatten to a per-member
614
- // outcome that would swallow the 128+signum exit).
615
- if (err instanceof InterruptError)
616
- throw err;
617
- if (err instanceof RequestTimeoutError) {
618
- return {
619
- testId: entry.testId,
620
- runId: entry.runId,
621
- status: 'timeout',
622
- error: { code: 'UNSUPPORTED', message: err.message, exitCode: err.exitCode },
623
- };
610
+ });
611
+ outcomes.set(runId, outcome);
624
612
  }
625
- if (err instanceof ApiError) {
626
- // Preserve the real code/exit (AUTH_INVALID=3, NOT_FOUND=4, …) rather
627
- // than flattening every member failure to a generic 1.
628
- return {
629
- testId: entry.testId,
630
- runId: entry.runId,
631
- status: 'error',
632
- error: waitMemberError(err),
633
- };
634
- }
635
- throw err;
636
- }
637
- }
638
- // Bounded-concurrency fan-out (self-contained; deliberately kept separate from
639
- // `runTestRunAll`'s inline driver rather than extracting a shared helper).
640
- let pollIdx = 0;
641
- let inFlight = 0;
642
- try {
643
- await new Promise((resolve, reject) => {
644
- function startNext() {
645
- while (inFlight < opts.maxConcurrency && pollIdx < resp.accepted.length) {
646
- const entry = resp.accepted[pollIdx++];
647
- inFlight++;
648
- pollOne(entry)
649
- .then(r => {
650
- results.push(r);
651
- inFlight--;
652
- startNext();
653
- if (inFlight === 0 && pollIdx >= resp.accepted.length)
654
- resolve();
655
- })
656
- .catch(reject);
613
+ catch (err) {
614
+ if (err instanceof ApiError)
615
+ outcomes.set(runId, {
616
+ ...(outcomes.get(runId) ?? {
617
+ runId,
618
+ run: null,
619
+ results: [],
620
+ timedOut: false,
621
+ missingResultIds: [],
622
+ }),
623
+ error: err,
624
+ });
625
+ else {
626
+ if (failure === undefined || err instanceof InterruptError)
627
+ failure = err;
628
+ if (err instanceof RequestTimeoutError)
629
+ requestTimedOut = true;
630
+ else
631
+ stopped.abort(err);
657
632
  }
633
+ if (err instanceof TunnelLostError)
634
+ stopped.abort(err);
658
635
  }
659
- startNext();
660
- if (resp.accepted.length === 0)
661
- resolve();
662
- });
663
- }
664
- catch (err) {
665
- ticker.finalize();
666
- if (deps.environmentTunnel)
667
- await emitEnvironmentDispatchPartial([resp], resp.accepted.map(row => row.testId), opts, deps, 'testlist', err, deps.environmentTunnel);
668
- throw err;
669
- }
670
- ticker.finalize();
671
- const passed = results.filter(r => r.status === 'passed').length;
672
- const failed = results.filter(r => r.status !== 'passed' && r.status !== 'timeout').length;
673
- const timedOut = results.filter(r => r.status === 'timeout').length;
674
- stderrFn(`Test-list run complete: ${passed}/${resp.accepted.length} passed, ${failed} failed/blocked, ${timedOut} timed out`);
675
- const jsonPayload = {
676
- ...(deps.environmentTunnel?.skipped?.length ? { skipped: deps.environmentTunnel.skipped } : {}),
677
- accepted: results,
678
- conflicts: resp.conflicts,
679
- deferred: resp.deferred,
680
- // Not members of this list (partial `--case` miss). Threaded into the
681
- // envelope so `summarizeAcceptedPayload` folds them as non-passed rows
682
- // (gh-output.ts) — without this a `1 accepted passed + 1 not-found` run
683
- // read as "1/1 passed" in the CI summary while the command exits 4.
684
- ...(resp.notFound && resp.notFound.length > 0 ? { notFound: resp.notFound } : {}),
685
- // Present only on a nothing-dispatched run (empty list / no-match --case);
686
- // surfaced here so the --wait envelope explains a zero-run report.
687
- ...(resp.reason ? { reason: resp.reason } : {}),
688
- summary: {
689
- passed,
690
- failed,
691
- timedOut,
692
- deferred: resp.deferred.length,
693
- conflicts: resp.conflicts.length,
694
- total: resp.accepted.length,
695
- },
696
- };
697
- if (opts.report === 'junit' && opts.reportFile !== undefined) {
698
- // Multi-project list: name the suite/classname by the LIST, not one project
699
- // (`resolveBatchReportProjectId`'s single-project assumption doesn't hold).
700
- const suiteName = opts.reportSuiteName ?? `testsprite:testlist:${opts.listId}`;
701
- const summary = summarizeAcceptedPayload(JSON.stringify(jsonPayload), {
702
- notFoundNote: 'not a member of this list (not dispatched)',
703
- });
704
- const xml = buildJUnitReport({
705
- suiteName,
706
- classname: `testlist:${opts.listId}`,
707
- results: [
708
- ...results.map(r => ({
709
- ...r,
710
- durationSeconds: r.runId ? reportDurations.get(r.runId) : undefined,
711
- })),
712
- ...skippedJUnitResultsFromSummary(summary, results),
713
- ],
714
- });
715
- await writeJUnitReportFile(opts.reportFile, xml);
716
- }
717
- out.print(jsonPayload, () => results.map(r => `${r.runId} ${r.status}`).join('\n'));
636
+ }));
637
+ }
638
+ // Keep launch order even when independent reads finish in a different order.
639
+ const observed = new Map(outcomes);
640
+ outcomes.clear();
641
+ for (const runId of runIds) {
642
+ const outcome = observed.get(runId);
643
+ if (outcome)
644
+ outcomes.set(runId, outcome);
645
+ }
646
+ if (failure === undefined || failure instanceof RequestTimeoutError) {
647
+ failure =
648
+ resolveRunWaitFailure([...outcomes.values()], { timeoutSeconds: opts.timeoutSeconds }, failure) ?? undefined;
649
+ }
650
+ const tunnel = deps.environmentTunnel;
651
+ if (failure && tunnel)
652
+ await tunnel.cancelActive();
653
+ const { output, members: results, summary, diagnosticRows, unfinishedRuns, } = buildRunOutput({
654
+ ...outputOptions,
655
+ outcomes,
656
+ failure,
657
+ requestTimedOut,
658
+ });
659
+ const launch = { ...output, ...dispatchMetadata };
660
+ out.print(launch, () => renderRunResults(output.runs, output.results, summary, conflictRows(resp.conflicts)));
718
661
  recordBatchOutcome({
719
662
  accepted: resp.accepted.length,
720
663
  conflicts: resp.conflicts,
721
664
  deferred: resp.deferred.length,
722
- skipped: 0,
665
+ skipped: tunnel?.skipped?.length ?? 0,
723
666
  results,
724
667
  });
725
- // CI-native output parity with `test run` (--gh-output / --summary-file):
726
- // auto-enable under GITHUB_ACTIONS. Emit BEFORE the exit-code gates below so a
727
- // failing/timed-out/deferred run still gets its ::error:: annotations + the
728
- // job-summary table. `emitCiArtifacts` is the shared helper the sibling run
729
- // paths use, keyed off the identical reduced envelope.
730
- emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(jsonPayload), {
731
- notFoundNote: 'not a member of this list (not dispatched)',
732
- }), opts, {
668
+ emitCiArtifacts(summary, opts, {
733
669
  env: deps.env ?? process.env,
734
- stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
670
+ stdout: deps.stdout ?? (line => process.stdout.write(`${line}\n`)),
735
671
  stderr: stderrFn,
736
- }, 'testlist run');
737
- // Rate-deferred → incomplete batch (exit 7), checked before the timeout/failed
738
- // gates so the operator learns to retry the deferred set (mirrors test run --all).
739
- assertNoDeferred(resp);
740
- // Shared exit-code precedence (auth 3 → typed operational ApiError → timeout 7
741
- // → generic fail 1) so `testlist run` and `test run` can't drift.
742
- const failure = resolveWaitFailure(results, { timeoutSeconds: opts.timeoutSeconds });
672
+ }, 'run');
673
+ const owesExit = failure !== undefined || resp.deferred.length > 0 || (resp.notFound?.length ?? 0) > 0;
674
+ if (opts.report === 'junit' && opts.reportFile) {
675
+ const file = opts.reportFile;
676
+ await writeReportOwing(owesExit, () => writeJUnitReportFile(file, buildJUnitReport({
677
+ suiteName: opts.reportSuiteName ?? `testsprite:testlist:${opts.listId}`,
678
+ classname: `testlist:${opts.listId}`,
679
+ results: [
680
+ ...results,
681
+ ...diagnosticRows,
682
+ ...skippedJUnitResultsFromSummary(summary, results),
683
+ ],
684
+ })), stderrFn, { label: 'run' });
685
+ }
686
+ if (failure instanceof InterruptError && unfinishedRuns.length) {
687
+ markRunWaitInterrupt(failure, unfinishedRuns);
688
+ if (!tunnel || tunnel.session.adopted)
689
+ stderrFn(interruptDetachMessage(failure, unfinishedRuns));
690
+ }
743
691
  if (failure)
744
692
  throw failure;
693
+ assertNoDeferred(resp);
745
694
  assertNoNotFound(resp);
746
- return resp;
695
+ return launch;
747
696
  }
748
- function renderRunAcceptedText(resp) {
749
- const lines = [];
750
- for (const a of resp.accepted)
751
- lines.push(`${a.runId} ${a.testId} dispatched`);
752
- for (const c of resp.conflicts) {
753
- // Reason-aware: a view-only / un-runnable / not-found case is no longer
754
- // mislabelled "already-in-flight" (see describeConflict).
755
- lines.push(`${c.currentRunId ?? '(none)'} ${c.testId} ${describeConflict(c)}`);
756
- }
757
- if (lines.length === 0)
758
- return 'No runs dispatched.';
759
- return lines.join('\n');
697
+ /** One line per refused member: `<in-flight result or (none)> <testId> <reason>`. */
698
+ function conflictRows(conflicts) {
699
+ // Reason-aware: a view-only / un-runnable / not-found case is no longer
700
+ // mislabelled "already-in-flight" (see describeConflict).
701
+ return conflicts.map(c => `${terminalSafeLine(c.currentResultId ?? '(none)')} ${terminalSafeLine(c.testId)} ${terminalSafeLine(describeConflict(c))}`);
760
702
  }
761
703
  // ── text renderers ───────────────────────────────────────────────────────────
704
+ /**
705
+ * Print test lists under the output names (`lastRunId`). The caller keeps the
706
+ * lists as the backend sent them.
707
+ */
708
+ function printTestLists(out, lists, options) {
709
+ out.print(lists, data => renderTestListListText(data, options));
710
+ }
711
+ /** Print one list's detail under the output names; see {@link printTestLists}. */
712
+ function printTestListDetail(out, detail) {
713
+ out.print(detail, data => renderTestListDetailText(data));
714
+ }
762
715
  const TESTLIST_COLUMNS = [
763
716
  { header: 'ID', width: rows => Math.max(2, ...rows.map(r => r.id.length)), render: r => r.id },
764
717
  {
@@ -768,9 +721,9 @@ const TESTLIST_COLUMNS = [
768
721
  },
769
722
  { header: 'CASES', width: 5, render: r => String(r.caseCount) },
770
723
  // Fixed 36 (a UUID); `width: 0` (skip-padding) is only valid on the LAST
771
- // column, and UPDATED is last — a `width: 0` here would leave LAST_EXEC
724
+ // column, and UPDATED is last — a `width: 0` here would leave LAST RUN
772
725
  // unpadded and drift UPDATED per row (UUID 36 chars vs "(none)" 6 chars).
773
- { header: 'LAST_EXEC', width: 36, render: r => r.lastExecutionId ?? '(none)' },
726
+ { header: 'LAST RUN', width: 36, render: r => r.lastRunId ?? '(none)' },
774
727
  { header: 'UPDATED', width: 0, render: r => r.updatedAt },
775
728
  ];
776
729
  function renderTestListListText(items, options = {}) {
@@ -783,15 +736,17 @@ function renderTestListListText(items, options = {}) {
783
736
  }
784
737
  function renderTestListDetailText(d) {
785
738
  const lines = [
786
- `ID: ${d.id}`,
787
- `Name: ${d.name}`,
739
+ `ID: ${terminalSafeLine(d.id)}`,
740
+ `Name: ${terminalSafeLine(d.name)}`,
788
741
  `Cases: ${d.stats.total} (passed ${d.stats.passed}, failed ${d.stats.failed}, blocked ${d.stats.blocked}, running ${d.stats.running})`,
789
742
  ];
790
743
  if (d.projectEnvironments.length > 0) {
791
- lines.push(`Envs: ${d.projectEnvironments.map(e => `${e.projectId}:${e.environmentName}`).join(', ')}`);
744
+ lines.push(`Envs: ${d.projectEnvironments
745
+ .map(e => `${terminalSafeLine(e.projectId)}:${terminalSafeLine(e.environmentName)}`)
746
+ .join(', ')}`);
792
747
  }
793
- lines.push(`Last exec: ${d.lastExecutionId ?? '(none)'}`);
794
- lines.push(`Updated: ${d.updatedAt}`);
748
+ lines.push(`Last run: ${terminalSafeLine(d.lastRunId ?? '(none)')}`);
749
+ lines.push(`Updated: ${terminalSafeLine(d.updatedAt)}`);
795
750
  if (d.cases.length > 0) {
796
751
  lines.push('');
797
752
  const caseTable = renderTextTable(d.cases, [
@@ -908,52 +863,27 @@ export function createTestListCommand(deps = {}) {
908
863
  idempotencyKey: cmdOpts.idempotencyKey,
909
864
  }, deps);
910
865
  });
911
- testlist
912
- .command('run <list-id>')
913
- .summary('Run a test list')
914
- .description("Run a test list (dispatch its cases and return pollable run ids). Environments come from the list's --project-env mapping; loopback ones open one tunnel and wait (backend cases are skipped).\n" +
915
- '\nExit codes:\n' +
916
- ' 0 dispatched (or all passed with --wait)\n' +
917
- ' 1 a run failed / blocked / cancelled\n' +
918
- ' 3 auth error\n' +
919
- ' 4 a --case id is not in the list\n' +
920
- ' 6 nothing dispatched: every case conflicted (already running, or cannot run here)\n' +
921
- ' 7 timeout, or some cases were rate-deferred (retry the printed ids)\n' +
922
- ' 12 insufficient credits (non-retriable; top up)\n' +
923
- ' 13 feature gated / workspace paused')
924
- .option('--case <test-id>', 'run only this case (repeatable; default: every case in the list)', collectRepeatable, [])
925
- .option('--wait', 'poll every dispatched run until terminal or --timeout', false)
926
- .option('--no-wait', 'detach without opening an automatic environment tunnel')
927
- .option('--skip-preflight', 'skip the loopback port probe before opening a tunnel')
928
- .option('--timeout <s>', 'with --wait, max seconds to wait (1–3600, default 600)')
929
- .option('--max-concurrency <n>', `with a tunnel, max runs in flight (1-10, default 5); otherwise with --wait, max polls (1-${MAX_TESTLIST_RUN_CONCURRENCY}, default ${DEFAULT_TESTLIST_RUN_CONCURRENCY})`)
930
- .option('--idempotency-key <key>', 'caller-supplied idempotency key (1-256 chars)')
931
- .option('--report <format>', 'with --wait: write a JUnit XML sidecar after polling (accepted: junit)')
932
- .option('--report-file <path>', 'output path for --report (atomic write)')
933
- .option('--report-suite-name <name>', 'JUnit <testsuite name=...> override (default: testsprite:testlist:<listId>)')
934
- .option('--gh-output', 'with --wait: emit GitHub annotations (::error:: failed/timed-out, ::warning:: never dispatched) and a job-summary table when $GITHUB_STEP_SUMMARY is set; auto-enabled when GITHUB_ACTIONS=true')
935
- .option('--summary-file <path>', 'with --wait: also write summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
936
- .addHelpText('after', GLOBAL_OPTS_HINT)
937
- .action(async (listId, cmdOpts, command) => {
938
- const wait = cmdOpts.wait === true;
939
- await runTestlistRun({
940
- ...resolveCommonOptions(command, deps.env),
941
- listId,
942
- cases: cmdOpts.case,
943
- wait,
944
- noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
945
- skipPreflight: cmdOpts.skipPreflight === true,
946
- concurrencyIsDefault: cmdOpts.maxConcurrency === undefined,
947
- timeoutSeconds: parseTestlistTimeoutFlag(cmdOpts.timeout),
948
- maxConcurrency: parseTestlistConcurrencyFlag(cmdOpts.maxConcurrency),
949
- idempotencyKey: cmdOpts.idempotencyKey,
950
- report: parseJUnitReportFormat(cmdOpts.report),
951
- reportFile: cmdOpts.reportFile,
952
- reportSuiteName: cmdOpts.reportSuiteName,
953
- ghOutput: cmdOpts.ghOutput,
954
- summaryFile: cmdOpts.summaryFile,
955
- }, deps);
956
- });
957
866
  return testlist;
958
867
  }
868
+ /** Root run's list mode keeps this module's parsers and native list receipt. */
869
+ export async function runTestlistRunFromCommand(command, listId, testIds, deps = {}) {
870
+ const opts = command.opts();
871
+ await runTestlistRun({
872
+ ...resolveCommonOptions(command, deps.env),
873
+ listId,
874
+ cases: testIds.length ? testIds : undefined,
875
+ wait: opts.wait === true,
876
+ noWait: command.getOptionValueSource('wait') === 'cli' && opts.wait === false,
877
+ skipPreflight: opts.skipPreflight === true,
878
+ concurrencyIsDefault: opts.maxConcurrency === undefined,
879
+ timeoutSeconds: parseTestlistTimeoutFlag(opts.timeout),
880
+ maxConcurrency: parseTestlistConcurrencyFlag(opts.maxConcurrency),
881
+ idempotencyKey: opts.idempotencyKey,
882
+ report: parseJUnitReportFormat(opts.report),
883
+ reportFile: opts.reportFile,
884
+ reportSuiteName: opts.reportSuiteName,
885
+ ghOutput: opts.ghOutput,
886
+ summaryFile: opts.summaryFile,
887
+ }, deps);
888
+ }
959
889
  //# sourceMappingURL=testlist.js.map