@testsprite/testsprite-cli 0.5.0 → 0.6.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.
@@ -1,8 +1,9 @@
1
1
  /**
2
- * CI-native output layer for the batch run path (issue #99, reshaped from
3
- * the withdrawn top-level `ci` command per the #264 review).
2
+ * CI-native output layer for the run path (issue #99, reshaped from
3
+ * the withdrawn top-level `ci` command per the #264 review). Covers both a
4
+ * single `test run <test-id> --wait` and the `test run --all --wait` batch.
4
5
  *
5
- * `test run --all --wait` presents its result in the formats CI consumes:
6
+ * A `--wait` run presents its result in the formats CI consumes:
6
7
  * (a) a stable machine summary `{total, passed, failed, timedOut, runs[]}`
7
8
  * written to `--summary-file <path>` when requested,
8
9
  * (b) a Markdown results table appended to `$GITHUB_STEP_SUMMARY` when
@@ -33,8 +34,29 @@ export interface CiSummary {
33
34
  * defensive: it reads the same `accepted[]` rows the automation contract
34
35
  * documents, and anything unparseable (dry-run envelope, partial output
35
36
  * after a timeout) reduces to an empty run list rather than a crash.
37
+ *
38
+ * Non-dispatched work (`deferred` / `conflicts` / `notFound`) is folded in as
39
+ * non-passed rows: those buckets already force a non-zero exit (deferred /
40
+ * timeout → 7, all-conflict → 6) but were previously absent from the summary,
41
+ * so a partial batch like `1 accepted passed + 1 deferred` read as "1/1 passed"
42
+ * with no annotation. (`skippedFrontend` / `skippedIntegration` are NOT folded
43
+ * in — they exit 0 and are the Action layer's allow-partial concern.)
36
44
  */
37
45
  export declare function summarizeAcceptedPayload(capturedJson: string): CiSummary;
46
+ /**
47
+ * Reduce a single `test run <test-id> --wait` result into the same CI summary
48
+ * shape as the batch path, so `--gh-output` / `--summary-file` behave
49
+ * identically for a one-test CI job. Unlike the batch envelope, a single
50
+ * RunResponse carries `error` as a raw string (not `{ message }`) and
51
+ * `dashboardUrl` as `string | null`; both are normalized here.
52
+ */
53
+ export declare function summarizeSingleRun(run: {
54
+ testId?: string;
55
+ runId?: string;
56
+ status?: string;
57
+ dashboardUrl?: string | null;
58
+ error?: string | null;
59
+ }): CiSummary;
38
60
  /** Markdown table for the GitHub job summary. */
39
61
  export declare function renderJobSummaryMarkdown(summary: CiSummary): string;
40
62
  /**
@@ -1,8 +1,9 @@
1
1
  /**
2
- * CI-native output layer for the batch run path (issue #99, reshaped from
3
- * the withdrawn top-level `ci` command per the #264 review).
2
+ * CI-native output layer for the run path (issue #99, reshaped from
3
+ * the withdrawn top-level `ci` command per the #264 review). Covers both a
4
+ * single `test run <test-id> --wait` and the `test run --all --wait` batch.
4
5
  *
5
- * `test run --all --wait` presents its result in the formats CI consumes:
6
+ * A `--wait` run presents its result in the formats CI consumes:
6
7
  * (a) a stable machine summary `{total, passed, failed, timedOut, runs[]}`
7
8
  * written to `--summary-file <path>` when requested,
8
9
  * (b) a Markdown results table appended to `$GITHUB_STEP_SUMMARY` when
@@ -14,11 +15,39 @@
14
15
  * behavior is previewable locally). All writes are best-effort: a broken
15
16
  * summary file must never mask the batch gate's exit code.
16
17
  */
18
+ /**
19
+ * Reduce a non-dispatched bucket (`deferred` / `conflicts` / `notFound`) into
20
+ * CI rows. Items are either bare testId strings (`notFound`) or
21
+ * `{ testId, currentRunId? }` objects; both shapes are handled. `note` becomes
22
+ * the row's error text so the annotation explains why the item did not run.
23
+ */
24
+ function bucketRows(bucket, status, note) {
25
+ if (!Array.isArray(bucket))
26
+ return [];
27
+ return bucket.map(item => {
28
+ const rec = item !== null && typeof item === 'object' ? item : undefined;
29
+ const testId = typeof item === 'string' ? item : typeof rec?.testId === 'string' ? rec.testId : '';
30
+ const currentRunId = typeof rec?.currentRunId === 'string' ? rec.currentRunId : undefined;
31
+ return {
32
+ testId,
33
+ status,
34
+ ...(currentRunId ? { runId: currentRunId } : {}),
35
+ error: note,
36
+ };
37
+ });
38
+ }
17
39
  /**
18
40
  * Reduce the batch command's JSON payload into the CI summary. The parse is
19
41
  * defensive: it reads the same `accepted[]` rows the automation contract
20
42
  * documents, and anything unparseable (dry-run envelope, partial output
21
43
  * after a timeout) reduces to an empty run list rather than a crash.
44
+ *
45
+ * Non-dispatched work (`deferred` / `conflicts` / `notFound`) is folded in as
46
+ * non-passed rows: those buckets already force a non-zero exit (deferred /
47
+ * timeout → 7, all-conflict → 6) but were previously absent from the summary,
48
+ * so a partial batch like `1 accepted passed + 1 deferred` read as "1/1 passed"
49
+ * with no annotation. (`skippedFrontend` / `skippedIntegration` are NOT folded
50
+ * in — they exit 0 and are the Action layer's allow-partial concern.)
22
51
  */
23
52
  export function summarizeAcceptedPayload(capturedJson) {
24
53
  let parsed;
@@ -32,7 +61,7 @@ export function summarizeAcceptedPayload(capturedJson) {
32
61
  // `JSON.parse('null')` and non-object payloads are valid JSON but carry no
33
62
  // batch envelope — treat them like unparseable input instead of crashing.
34
63
  const payload = parsed !== null && typeof parsed === 'object' ? parsed : {};
35
- const rows = Array.isArray(payload.accepted)
64
+ const acceptedRows = Array.isArray(payload.accepted)
36
65
  ? payload.accepted
37
66
  .filter((entry) => entry !== null && typeof entry === 'object')
38
67
  .map(row => {
@@ -48,11 +77,58 @@ export function summarizeAcceptedPayload(capturedJson) {
48
77
  };
49
78
  })
50
79
  : [];
80
+ const rows = [
81
+ ...acceptedRows,
82
+ ...bucketRows(payload.deferred, 'deferred', 'rate-deferred (not dispatched)'),
83
+ ...bucketRows(payload.conflicts, 'conflict', 'already in flight (not dispatched)'),
84
+ ...bucketRows(payload.notFound, 'not_found', 'no replayable run (not dispatched)'),
85
+ ];
51
86
  const passed = rows.filter(row => row.status === 'passed').length;
52
87
  const timedOut = rows.filter(row => row.status === 'timeout').length;
53
88
  const failed = rows.length - passed - timedOut;
54
89
  return { total: rows.length, passed, failed, timedOut, runs: rows };
55
90
  }
91
+ /**
92
+ * Reduce a single `test run <test-id> --wait` result into the same CI summary
93
+ * shape as the batch path, so `--gh-output` / `--summary-file` behave
94
+ * identically for a one-test CI job. Unlike the batch envelope, a single
95
+ * RunResponse carries `error` as a raw string (not `{ message }`) and
96
+ * `dashboardUrl` as `string | null`; both are normalized here.
97
+ */
98
+ export function summarizeSingleRun(run) {
99
+ const row = {
100
+ testId: String(run.testId ?? ''),
101
+ ...(typeof run.runId === 'string' ? { runId: run.runId } : {}),
102
+ status: String(run.status ?? 'unknown'),
103
+ ...(typeof run.dashboardUrl === 'string' ? { dashboardUrl: run.dashboardUrl } : {}),
104
+ ...(typeof run.error === 'string' && run.error.length > 0 ? { error: run.error } : {}),
105
+ };
106
+ const passed = row.status === 'passed' ? 1 : 0;
107
+ const timedOut = row.status === 'timeout' ? 1 : 0;
108
+ const failed = 1 - passed - timedOut;
109
+ return { total: 1, passed, failed, timedOut, runs: [row] };
110
+ }
111
+ /**
112
+ * Escape a value for a Markdown table cell. A raw `|` would break the column
113
+ * layout and a CR/LF would inject extra Markdown lines (rows are newline-joined)
114
+ * — the same injection class the annotation escaping guards against, on the
115
+ * step-summary surface.
116
+ */
117
+ function escapeTableCell(value) {
118
+ return value.replace(/\|/g, '\\|').replace(/[\r\n]+/g, ' ');
119
+ }
120
+ /**
121
+ * Escape a URL for a Markdown `[text](url)` link: a literal `)` closes the link
122
+ * early and whitespace / `|` / CR-LF break the link or the surrounding cell.
123
+ */
124
+ function escapeMarkdownUrl(url) {
125
+ return url
126
+ .replace(/[\r\n]+/g, '')
127
+ .replace(/ /g, '%20')
128
+ .replace(/\(/g, '%28')
129
+ .replace(/\)/g, '%29')
130
+ .replace(/\|/g, '%7C');
131
+ }
56
132
  /** Markdown table for the GitHub job summary. */
57
133
  export function renderJobSummaryMarkdown(summary) {
58
134
  return [
@@ -62,10 +138,33 @@ export function renderJobSummaryMarkdown(summary) {
62
138
  '',
63
139
  '| Test | Status | Run |',
64
140
  '| --- | --- | --- |',
65
- ...summary.runs.map(row => `| ${row.testId} | ${row.status} | ${row.dashboardUrl ? `[dashboard](${row.dashboardUrl})` : (row.runId ?? '')} |`),
141
+ ...summary.runs.map(row => {
142
+ const run = row.dashboardUrl
143
+ ? `[dashboard](${escapeMarkdownUrl(row.dashboardUrl)})`
144
+ : escapeTableCell(row.runId ?? '');
145
+ return `| ${escapeTableCell(row.testId)} | ${escapeTableCell(row.status)} | ${run} |`;
146
+ }),
66
147
  '',
67
148
  ].join('\n');
68
149
  }
150
+ /**
151
+ * Escape a value destined for the DATA half of a workflow command (the text
152
+ * after `::`). Per GitHub's rules, `%`, CR and LF are percent-encoded so a raw
153
+ * multiline run error can never introduce a newline that starts a second
154
+ * `::command::` line in the Actions output stream (`%` first, so the encodings
155
+ * we add are not themselves re-encoded).
156
+ */
157
+ function escapeCommandData(value) {
158
+ return value.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
159
+ }
160
+ /**
161
+ * Escape a value destined for a command PROPERTY (e.g. `title=...`). Beyond the
162
+ * data rules, `:` and `,` are encoded so the value cannot terminate the
163
+ * property list or the command header.
164
+ */
165
+ function escapeCommandProperty(value) {
166
+ return escapeCommandData(value).replace(/:/g, '%3A').replace(/,/g, '%2C');
167
+ }
69
168
  /**
70
169
  * Emit the GitHub-native surfaces. Self-gating on the standard env vars:
71
170
  * `$GITHUB_STEP_SUMMARY` (a file path Actions provides) receives the Markdown
@@ -92,7 +191,11 @@ export function emitGithubOutputs(summary, env, sinks, opts = {}) {
92
191
  continue;
93
192
  const detail = row.error !== undefined ? ` ${row.error}` : '';
94
193
  const link = row.dashboardUrl !== undefined ? ` ${row.dashboardUrl}` : '';
95
- annotate(`::error title=TestSprite ${row.testId}::status=${row.status}${detail}${link}`);
194
+ // Escape both halves: a raw multiline run error (or a testId) must not be
195
+ // able to smuggle a second workflow command into the Actions stream.
196
+ const title = `TestSprite ${escapeCommandProperty(row.testId)}`;
197
+ const message = escapeCommandData(`status=${row.status}${detail}${link}`);
198
+ annotate(`::error title=${title}::${message}`);
96
199
  }
97
200
  }
98
201
  }
package/dist/lib/http.js CHANGED
@@ -345,7 +345,17 @@ export class HttpClient {
345
345
  // letting a long-poll drain its window before the interrupt surfaces.
346
346
  if (this.shutdownSignal != null)
347
347
  composedSignals.push(this.shutdownSignal);
348
- const effectiveSignal = composedSignals.length > 1 ? AbortSignal.any(composedSignals) : timeoutSignal;
348
+ // Composed via `composeAbortSignals` (manual listeners), NOT the native
349
+ // `AbortSignal.any` — see that function's doc comment. `this.shutdownSignal`
350
+ // is process-lifetime (`globalShutdown.signal`, `client-factory.ts`) and is
351
+ // pushed into `composedSignals` on essentially every request, so
352
+ // `AbortSignal.any` here was measured to register ~330K dependent-signal
353
+ // trackings against that one long-lived signal over a single request-heavy
354
+ // test file — the same `FinalizationRegistry` backlog mechanism already
355
+ // fixed once in `poll.ts`, just recreated per-request instead of
356
+ // per-poll-iteration. `cleanupAbortComposition` MUST be called once the
357
+ // request settles (below, alongside `requestTimeout.clear()`).
358
+ const { signal: effectiveSignal, cleanup: cleanupAbortComposition } = composeAbortSignals(composedSignals);
349
359
  try {
350
360
  try {
351
361
  response = await this.fetchImpl(url, {
@@ -564,6 +574,11 @@ export class HttpClient {
564
574
  }
565
575
  finally {
566
576
  requestTimeout.clear();
577
+ // Remove the manually-added abort listeners now, synchronously —
578
+ // see `composeAbortSignals`. Runs on every path out of the try
579
+ // (return, throw, or `continue` into the next attempt), so nothing
580
+ // outlives the request it was created for.
581
+ cleanupAbortComposition();
567
582
  }
568
583
  }
569
584
  }
@@ -658,6 +673,63 @@ export function buildUrl(baseUrl, path, query) {
658
673
  function newRequestId() {
659
674
  return `cli_${randomUUID()}`;
660
675
  }
676
+ /**
677
+ * Compose multiple `AbortSignal`s into one — abort on whichever fires first —
678
+ * WITHOUT using the native `AbortSignal.any`.
679
+ *
680
+ * `AbortSignal.any` builds a persistent "dependent signal" relationship: the
681
+ * signal it returns is tracked (via a `WeakRef` + `FinalizationRegistry`)
682
+ * against EVERY source signal passed in, including any long-lived one. Every
683
+ * outgoing request here composes `this.shutdownSignal` — process-lifetime
684
+ * (`globalShutdown.signal`, wired by `client-factory.ts` on essentially every
685
+ * command invocation) — into `composedSignals`, so each request added one
686
+ * more tracked dependent against that single long-lived signal, reclaimed
687
+ * only whenever V8 next got around to running ITS `FinalizationRegistry`
688
+ * cleanup pass. Under a request-heavy path (retries, a wide closure/batch
689
+ * fan-out, RATE_LIMITED backoff) this reproduces — per HTTP request instead
690
+ * of per poll-iteration — the exact backlog mechanism already fixed once in
691
+ * `poll.ts` (`JSFinalizationRegistry::Cleanup` → `KeepDuringJob` →
692
+ * `OrderedHashSet::Add` pegging the CPU once the deferred backlog is finally
693
+ * walked). Measured directly: the RATE_LIMITED closure-fanout scenario in
694
+ * `test.rerun.spec.ts` alone drives ~330K `AbortSignal.any` calls against the
695
+ * one process-lifetime `globalShutdown.signal` over the life of that single
696
+ * test file.
697
+ *
698
+ * This performs the identical "first one wins, propagate its `.reason`"
699
+ * composition with a plain `AbortController` and ordinary
700
+ * `addEventListener`/`removeEventListener` — no dependent-signal tracking, no
701
+ * `WeakRef`, no GC-deferred cleanup. The caller MUST invoke the returned
702
+ * `cleanup()` once the request settles (success, error, or retry) so the
703
+ * listeners are removed immediately rather than left for a cleanup pass that,
704
+ * for this composition, no longer exists.
705
+ */
706
+ function composeAbortSignals(signals) {
707
+ if (signals.length <= 1) {
708
+ return { signal: signals[0], cleanup: () => { } };
709
+ }
710
+ // Mirror AbortSignal.any's already-aborted short-circuit: if a source is
711
+ // already aborted at composition time, propagate its reason immediately —
712
+ // no listeners are ever added, so cleanup is a no-op.
713
+ const alreadyAborted = signals.find(s => s.aborted);
714
+ const controller = new AbortController();
715
+ if (alreadyAborted) {
716
+ controller.abort(alreadyAborted.reason);
717
+ return { signal: controller.signal, cleanup: () => { } };
718
+ }
719
+ const removers = [];
720
+ for (const source of signals) {
721
+ const onAbort = () => controller.abort(source.reason);
722
+ source.addEventListener('abort', onAbort, { once: true });
723
+ removers.push(() => source.removeEventListener('abort', onAbort));
724
+ }
725
+ return {
726
+ signal: controller.signal,
727
+ cleanup: () => {
728
+ for (const remove of removers)
729
+ remove();
730
+ },
731
+ };
732
+ }
661
733
  function createRequestTimeout(timeoutMs) {
662
734
  const controller = new AbortController();
663
735
  const timer = setTimeout(() => {
package/dist/lib/poll.js CHANGED
@@ -56,7 +56,7 @@ export async function pollRunUntilTerminal(client, runId, options) {
56
56
  }
57
57
  }
58
58
  async function pollLoop(client, runId, options) {
59
- const { timeoutSeconds, onTick, onTransition, resolveAlternate } = options;
59
+ const { timeoutSeconds, resolveAlternate } = options;
60
60
  const shutdownSignal = options.shutdown?.signal;
61
61
  const rawSleep = options.sleep ?? defaultSleep;
62
62
  // Every sleep site (retryAfterSeconds, backoff schedule, not_yet_visible,
@@ -65,6 +65,68 @@ async function pollLoop(client, runId, options) {
65
65
  const sleep = (ms) => sleepUnlessInterrupted(rawSleep, ms, shutdownSignal);
66
66
  const startMs = Date.now();
67
67
  const deadlineMs = startMs + timeoutSeconds * 1000;
68
+ // Hoisted ONCE per poll *session* rather than re-minted every iteration.
69
+ // The abort target here — deadlineMs + a transport cushion — is a fixed
70
+ // absolute instant that does not change from one iteration to the next
71
+ // (remainingMs shrinks, but remainingMs + TRANSPORT_CUSHION_MS measured
72
+ // from "now" always lands on the same deadlineMs + cushion point). Minting
73
+ // a fresh AbortController + setTimeout + `AbortSignal.any` composite every
74
+ // iteration was therefore pure churn with no behavioral purpose: on a
75
+ // `--wait` fan-out over many concurrent runIds, each polling for many
76
+ // iterations, this created thousands of composite signals per invocation.
77
+ // Every `AbortSignal.any` call registers an internal dependency listener
78
+ // on the long-lived `shutdownSignal`, tracked via a WeakRef +
79
+ // FinalizationRegistry so the listener can be reclaimed once the derived
80
+ // signal is garbage-collected without leaking on the long-lived source —
81
+ // but under a high allocation rate with no macrotask yield between
82
+ // iterations (`TestDeps.sleep` in tests resolves via a bare microtask),
83
+ // V8 can fall behind on running that reclamation incrementally, and the
84
+ // eventual cleanup pass then has to walk a large backlog in one go
85
+ // (`JSFinalizationRegistry::Cleanup` → `KeepDuringJob` →
86
+ // `OrderedHashSet::Add`), pegging the CPU for minutes. One controller,
87
+ // one timer, and one composed signal — created once, reused for every
88
+ // iteration and every retry, cleared once when the session ends —
89
+ // removes that per-iteration scaling factor entirely; the deadline
90
+ // semantics are unchanged, since the abort target was already the same
91
+ // absolute instant on every iteration.
92
+ const TRANSPORT_CUSHION_MS = 2000;
93
+ const deadlineController = new AbortController();
94
+ const deadlineTimer = setTimeout(() => deadlineController.abort(), deadlineMs - startMs + TRANSPORT_CUSHION_MS);
95
+ const sessionSignal = shutdownSignal != null
96
+ ? AbortSignal.any([deadlineController.signal, shutdownSignal])
97
+ : deadlineController.signal;
98
+ // Same hoisting rationale for the `resolveAlternate` abort target
99
+ // (deadlineMs, no cushion — also a fixed absolute instant). Allocated
100
+ // lazily so callers that never pass `resolveAlternate` pay nothing for it.
101
+ let altAbort;
102
+ let altTimer;
103
+ let altSignal;
104
+ if (resolveAlternate) {
105
+ altAbort = new AbortController();
106
+ const controller = altAbort;
107
+ altTimer = setTimeout(() => controller.abort(), deadlineMs - startMs);
108
+ altSignal =
109
+ shutdownSignal != null ? AbortSignal.any([altAbort.signal, shutdownSignal]) : altAbort.signal;
110
+ }
111
+ try {
112
+ return await pollIterations(client, runId, options, {
113
+ startMs,
114
+ deadlineMs,
115
+ sessionSignal,
116
+ altSignal,
117
+ sleep,
118
+ });
119
+ }
120
+ finally {
121
+ clearTimeout(deadlineTimer);
122
+ if (altTimer !== undefined)
123
+ clearTimeout(altTimer);
124
+ }
125
+ }
126
+ async function pollIterations(client, runId, options, ctx) {
127
+ const { timeoutSeconds, onTick, onTransition, resolveAlternate } = options;
128
+ const shutdownSignal = options.shutdown?.signal;
129
+ const { startMs, deadlineMs, sessionSignal, altSignal, sleep } = ctx;
68
130
  // Track whether the server supports ?waitSeconds. Start optimistic.
69
131
  let useBackoff = false;
70
132
  let backoffIndex = 0;
@@ -82,36 +144,20 @@ async function pollLoop(client, runId, options) {
82
144
  }
83
145
  const remainingMs = deadlineMs - now;
84
146
  const remainingSeconds = Math.ceil(remainingMs / 1000);
85
- // Mint a per-iteration AbortController. The signal fires at the remaining
86
- // deadline plus a small transport cushion (2 s) so a hung fetch does not
87
- // block the CLI past --timeout.
88
- const TRANSPORT_CUSHION_MS = 2000;
89
- const abortController = new AbortController();
90
- const abortTimer = setTimeout(() => {
91
- abortController.abort();
92
- }, remainingMs + TRANSPORT_CUSHION_MS);
93
- // Compose the interrupt into the per-iteration signal: a `--wait` can sit
94
- // inside one <=25s long-poll fetch (and the auto-raised per-request
95
- // timeout means even longer for slow backends) — checking the flag
96
- // between iterations is not enough, the in-flight fetch must abort.
97
- const iterationSignal = shutdownSignal != null
98
- ? AbortSignal.any([abortController.signal, shutdownSignal])
99
- : abortController.signal;
100
147
  let run;
101
148
  try {
102
149
  if (useBackoff) {
103
- run = await client.getRun(runId, { signal: iterationSignal });
150
+ run = await client.getRun(runId, { signal: sessionSignal });
104
151
  }
105
152
  else {
106
153
  const waitSeconds = Math.min(remainingSeconds, LONG_POLL_WAIT_SECONDS);
107
- run = await client.getRun(runId, { waitSeconds, signal: iterationSignal });
154
+ run = await client.getRun(runId, { waitSeconds, signal: sessionSignal });
108
155
  }
109
156
  // Successful GET resets the consecutive-error counter.
110
157
  consecutiveErrors = 0;
111
158
  notYetVisibleRetries = 0;
112
159
  }
113
160
  catch (err) {
114
- clearTimeout(abortTimer);
115
161
  // Interrupt classification precedes the timeout mapping: the composed
116
162
  // signal makes the fetch reject on Ctrl-C, and that abort must surface
117
163
  // as the InterruptError — not as a spurious TimeoutError.
@@ -119,8 +165,8 @@ async function pollLoop(client, runId, options) {
119
165
  throw err;
120
166
  if (shutdownSignal?.aborted)
121
167
  throw shutdownSignal.reason;
122
- // An AbortError from our per-iteration controller means the deadline
123
- // passed while the fetch was in flight — surface as TimeoutError.
168
+ // An AbortError from the session controller means the deadline passed
169
+ // while the fetch was in flight — surface as TimeoutError.
124
170
  if (isAbortError(err)) {
125
171
  throw new TimeoutError(runId, timeoutSeconds);
126
172
  }
@@ -170,8 +216,6 @@ async function pollLoop(client, runId, options) {
170
216
  // Everything else propagates.
171
217
  throw err;
172
218
  }
173
- // fetch completed — cancel the per-iteration abort timer.
174
- clearTimeout(abortTimer);
175
219
  const elapsedMs = Date.now() - startMs;
176
220
  onTick?.(run, elapsedMs);
177
221
  if (isTerminalStatus(run.status)) {
@@ -188,21 +232,13 @@ async function pollLoop(client, runId, options) {
188
232
  if (altRemainingMs <= 0) {
189
233
  throw new TimeoutError(runId, timeoutSeconds);
190
234
  }
191
- const altAbort = new AbortController();
192
- const altTimer = setTimeout(() => altAbort.abort(), altRemainingMs);
193
235
  // The alternate lookup aborts on interrupt too; its errors are swallowed
194
236
  // by the fallback (best-effort), so the loop-top interrupt check above
195
- // surfaces the InterruptError on the next iteration.
196
- const altSignal = shutdownSignal != null
197
- ? AbortSignal.any([altAbort.signal, shutdownSignal])
198
- : altAbort.signal;
199
- let alternate;
200
- try {
201
- alternate = await resolveAlternate(run, elapsedMs, altSignal);
202
- }
203
- finally {
204
- clearTimeout(altTimer);
205
- }
237
+ // surfaces the InterruptError on the next iteration. `altSignal` is the
238
+ // hoisted per-session signal (allocated once, above, whenever
239
+ // `resolveAlternate` is present) — reused across every non-terminal
240
+ // tick rather than re-composed each time.
241
+ const alternate = await resolveAlternate(run, elapsedMs, altSignal);
206
242
  // Enforce the hard cap: reject a terminal alternate that only arrived
207
243
  // at/after the deadline, same as the run-row long-poll path below.
208
244
  if (Date.now() >= deadlineMs) {
@@ -92,24 +92,34 @@ export const RUN_RESPONSE_SCHEMA = v.looseObject({
92
92
  videoUrl: v.nullish(v.string(), null),
93
93
  stepSummary: RUN_STEP_SUMMARY_SCHEMA,
94
94
  retryAfterSeconds: v.optional(v.number()),
95
- // Portal link. Newer backends DO send this (they alone know which store
96
- // answered the read and can resolve a non-prod portal origin); older ones
97
- // omit it and the CLI computes its own. `nullish` rather than `optional`
98
- // deliberately: the backend omits the field when no correct link exists, but
99
- // a `null` from any other producer must not fail validation and take down
100
- // `test wait` — the same trap that had to be un-sprung for a null
101
- // `targetUrl`/`codeVersion`.
95
+ // Portal link. Three-state wire contract (pinned): **absent** — an older
96
+ // backend that predates this field, and cannot have produced a V3-native/
97
+ // unmirrored entity either (that capability and this field ship together)
98
+ // — the CLI computes its own legacy V2-shaped link. **Present + string** —
99
+ // the backend built a correct link (it alone knows which store answered
100
+ // and this environment's portal origin) — use it verbatim. **Present +
101
+ // `null`** — the backend deliberately has no correct link to offer (e.g. a
102
+ // V3-native entity with no DynamoDB mirror row for the client's V2-shaped
103
+ // guess to land on) — suppress the link entirely; a client-side guess here
104
+ // would be exactly the dead link the server declined to emit. The backend
105
+ // always includes the key going forward (typed `string | null`, never
106
+ // omitted when it has an opinion) — an earlier revision of this comment
107
+ // described the backend as omitting the key on "no correct link", which
108
+ // was the actual production defect this contract closes: the client's
109
+ // absent-branch fallback was firing on real V3-native no-link responses
110
+ // and printing the dead legacy URL this whole feature exists to remove.
102
111
  //
103
112
  // The `undefined` default (NOT `null`, unlike every field above) is load-bearing
104
113
  // and measured: valibot applies a default only when the key is absent, and
105
114
  // skips the assignment entirely when that default is `undefined` — so an
106
115
  // omitted field stays an ABSENT key, which is exactly what
107
- // `withRunDashboardUrl`'s `'dashboardUrl' in run` test reads to decide
108
- // "old backend, compute the link myself". Aligning this with the
109
- // `nullish(..., null)` fields above would materialize the key on every
110
- // response and silently kill that fallback. A wire `null` is preserved as
111
- // null here (nullable passes it through untouched) and normalized at the
112
- // consumer, not in the schema. Locked by tests in response-schemas.test.ts.
116
+ // `withRunDashboardUrl`'s `'dashboardUrl' in run` test (via the shared
117
+ // `resolveDashboardUrl` helper) reads to decide "old backend, compute the
118
+ // link myself". Aligning this with the `nullish(..., null)` fields above
119
+ // would materialize the key on every response and silently kill that
120
+ // fallback. A wire `null` is preserved as null here (nullable passes it
121
+ // through untouched) and normalized at the consumer, not in the schema.
122
+ // Locked by tests in response-schemas.test.ts.
113
123
  dashboardUrl: v.nullish(v.string(), undefined),
114
124
  // Absence means "steps not requested" and drives command branching, so no
115
125
  // default is applied (rule 3, optional branch).
@@ -20,3 +20,23 @@ export declare function routingLabel(v3Enabled: boolean): 'v3' | 'v2';
20
20
  export declare const V3_ROUTING_ADVISORY: string[];
21
21
  /** Write the advisory to a stderr sink, one line per call. */
22
22
  export declare function emitV3RoutingAdvisory(stderr: (line: string) => void): void;
23
+ /**
24
+ * Point-of-use advisory for `test run --target-url` on a V3-routed caller
25
+ * (DEV-749). `V3_ROUTING_ADVISORY` above already names this gap once, in
26
+ * the account-level summary `auth status`/`doctor` print — this is the
27
+ * SAME gap surfaced at the moment the caller actually hits it, matching
28
+ * the existing backend-test `--target-url` advisory in `runCreate`
29
+ * (`commands/test.ts`): unconditional across every `--output` mode. That
30
+ * advisory's family is "a flag the caller just passed has a structural
31
+ * consequence" — `--output json` is precisely the unattended/CI case that
32
+ * needs the warning most, not the case to withhold it from (unlike the
33
+ * routing-advisory family above, which a JSON caller can skip by reading
34
+ * `v3Enabled` directly off that command's own structured output — `test
35
+ * run`'s JSON output carries no such field). Deliberately type-agnostic
36
+ * (no "on frontend runs" claim): the CLI cannot learn a test's type at
37
+ * `test run <existing-test-id>` time without an extra round trip, and the
38
+ * override is equally inert on the V3 backend-run path.
39
+ */
40
+ export declare const TARGET_URL_V3_ADVISORY: string;
41
+ /** Write the target-url advisory to a stderr sink. */
42
+ export declare function emitTargetUrlV3Advisory(stderr: (line: string) => void): void;
@@ -29,4 +29,27 @@ export function emitV3RoutingAdvisory(stderr) {
29
29
  for (const line of V3_ROUTING_ADVISORY)
30
30
  stderr(line);
31
31
  }
32
+ /**
33
+ * Point-of-use advisory for `test run --target-url` on a V3-routed caller
34
+ * (DEV-749). `V3_ROUTING_ADVISORY` above already names this gap once, in
35
+ * the account-level summary `auth status`/`doctor` print — this is the
36
+ * SAME gap surfaced at the moment the caller actually hits it, matching
37
+ * the existing backend-test `--target-url` advisory in `runCreate`
38
+ * (`commands/test.ts`): unconditional across every `--output` mode. That
39
+ * advisory's family is "a flag the caller just passed has a structural
40
+ * consequence" — `--output json` is precisely the unattended/CI case that
41
+ * needs the warning most, not the case to withhold it from (unlike the
42
+ * routing-advisory family above, which a JSON caller can skip by reading
43
+ * `v3Enabled` directly off that command's own structured output — `test
44
+ * run`'s JSON output carries no such field). Deliberately type-agnostic
45
+ * (no "on frontend runs" claim): the CLI cannot learn a test's type at
46
+ * `test run <existing-test-id>` time without an extra round trip, and the
47
+ * override is equally inert on the V3 backend-run path.
48
+ */
49
+ export const TARGET_URL_V3_ADVISORY = "[advisory] --target-url is not applied on the V3 execution path; the run uses the test's " +
50
+ 'configured environment instead.';
51
+ /** Write the target-url advisory to a stderr sink. */
52
+ export function emitTargetUrlV3Advisory(stderr) {
53
+ stderr(TARGET_URL_V3_ADVISORY);
54
+ }
32
55
  //# sourceMappingURL=v3-advisory.js.map
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.5.0";
1
+ export declare const VERSION = "0.6.0";
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // AUTO-GENERATED by scripts/generate-version.mjs — do not edit by hand.
2
2
  // Run `npm run build` (or `npm run generate:version`) to regenerate.
3
- export const VERSION = '0.5.0';
3
+ export const VERSION = '0.6.0';
4
4
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@testsprite/testsprite-cli",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Official TestSprite command-line interface",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -70,6 +70,7 @@
70
70
  "ajv": "^8.20.0",
71
71
  "eslint": "^10.7.0",
72
72
  "eslint-config-prettier": "^9.1.0",
73
+ "eslint-plugin-security": "4.0.1",
73
74
  "globals": "^17.7.0",
74
75
  "msw": "^2.14.3",
75
76
  "prettier": "^3.3.3",