@testsprite/testsprite-cli 0.15.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 (207) hide show
  1. package/README.md +53 -141
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +55 -65
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +44 -56
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +297 -489
  8. package/dist/commands/completion.js +2 -1
  9. package/dist/commands/conversation.d.ts +27 -0
  10. package/dist/commands/conversation.js +702 -0
  11. package/dist/commands/doctor.d.ts +5 -1
  12. package/dist/commands/doctor.js +130 -34
  13. package/dist/commands/init.d.ts +4 -45
  14. package/dist/commands/init.js +116 -68
  15. package/dist/commands/project-env.d.ts +62 -2
  16. package/dist/commands/project-env.js +426 -53
  17. package/dist/commands/project-sign-in.d.ts +0 -48
  18. package/dist/commands/project-sign-in.js +1 -224
  19. package/dist/commands/project.d.ts +15 -186
  20. package/dist/commands/project.js +93 -921
  21. package/dist/commands/result.d.ts +10 -0
  22. package/dist/commands/result.js +215 -0
  23. package/dist/commands/schedule.d.ts +0 -29
  24. package/dist/commands/schedule.js +47 -97
  25. package/dist/commands/test.d.ts +315 -1824
  26. package/dist/commands/test.js +1962 -13733
  27. package/dist/commands/testlist.d.ts +128 -5
  28. package/dist/commands/testlist.js +269 -329
  29. package/dist/commands/tunnel.d.ts +2 -2
  30. package/dist/commands/tunnel.js +43 -41
  31. package/dist/commands/usage.d.ts +12 -45
  32. package/dist/commands/usage.js +51 -131
  33. package/dist/index.js +189 -108
  34. package/dist/lib/agent-detect.js +9 -5
  35. package/dist/lib/agent-targets.d.ts +21 -2
  36. package/dist/lib/agent-targets.js +88 -11
  37. package/dist/lib/args.d.ts +13 -0
  38. package/dist/lib/args.js +49 -0
  39. package/dist/lib/basic-auth.d.ts +3 -0
  40. package/dist/lib/basic-auth.js +15 -0
  41. package/dist/lib/billing-refusal.js +4 -3
  42. package/dist/lib/ci-linkage.d.ts +4 -82
  43. package/dist/lib/ci-linkage.js +4 -157
  44. package/dist/lib/ci-run.js +1 -1
  45. package/dist/lib/client-factory.d.ts +10 -2
  46. package/dist/lib/client-factory.js +38 -26
  47. package/dist/lib/commit-signal.d.ts +65 -0
  48. package/dist/lib/commit-signal.js +305 -0
  49. package/dist/lib/concurrency-limiter.d.ts +6 -0
  50. package/dist/lib/concurrency-limiter.js +29 -0
  51. package/dist/lib/config.js +10 -5
  52. package/dist/lib/conflict-reason.d.ts +31 -4
  53. package/dist/lib/conflict-reason.js +38 -4
  54. package/dist/lib/conversation/answers.d.ts +9 -0
  55. package/dist/lib/conversation/answers.js +49 -0
  56. package/dist/lib/conversation/api.d.ts +71 -0
  57. package/dist/lib/conversation/api.js +150 -0
  58. package/dist/lib/conversation/change.d.ts +31 -0
  59. package/dist/lib/conversation/change.js +124 -0
  60. package/dist/lib/conversation/context.d.ts +19 -0
  61. package/dist/lib/conversation/context.js +70 -0
  62. package/dist/lib/conversation/environment.d.ts +15 -0
  63. package/dist/lib/conversation/environment.js +33 -0
  64. package/dist/lib/conversation/follow.d.ts +24 -0
  65. package/dist/lib/conversation/follow.js +42 -0
  66. package/dist/lib/conversation/render.d.ts +33 -0
  67. package/dist/lib/conversation/render.js +315 -0
  68. package/dist/lib/conversation/title.d.ts +2 -0
  69. package/dist/lib/conversation/title.js +18 -0
  70. package/dist/lib/conversation/types.d.ts +156 -0
  71. package/dist/lib/conversation/types.js +6 -0
  72. package/dist/lib/credentials.js +67 -11
  73. package/dist/lib/cron.d.ts +1 -1
  74. package/dist/lib/cron.js +2 -2
  75. package/dist/lib/dispatch-stop.d.ts +20 -0
  76. package/dist/lib/dispatch-stop.js +30 -0
  77. package/dist/lib/download.d.ts +71 -0
  78. package/dist/lib/download.js +274 -0
  79. package/dist/lib/dry-run/fetch.d.ts +10 -0
  80. package/dist/lib/dry-run/fetch.js +20 -0
  81. package/dist/lib/dry-run/samples.d.ts +6 -34
  82. package/dist/lib/dry-run/samples.js +389 -751
  83. package/dist/lib/environment-tunnel.d.ts +16 -26
  84. package/dist/lib/environment-tunnel.js +161 -157
  85. package/dist/lib/errors.d.ts +20 -4
  86. package/dist/lib/errors.js +36 -16
  87. package/dist/lib/facade.d.ts +7 -29
  88. package/dist/lib/facade.js +7 -36
  89. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  90. package/dist/lib/failing-fe-resolver.js +47 -132
  91. package/dist/lib/first-suite-hint.d.ts +16 -22
  92. package/dist/lib/first-suite-hint.js +38 -47
  93. package/dist/lib/gh-output.d.ts +76 -21
  94. package/dist/lib/gh-output.js +171 -90
  95. package/dist/lib/git-utils.d.ts +56 -0
  96. package/dist/lib/git-utils.js +212 -0
  97. package/dist/lib/github-context.d.ts +2 -0
  98. package/dist/lib/github-context.js +40 -8
  99. package/dist/lib/history-retention.d.ts +6 -2
  100. package/dist/lib/history-retention.js +10 -7
  101. package/dist/lib/http.d.ts +58 -134
  102. package/dist/lib/http.js +352 -271
  103. package/dist/lib/interrupt.d.ts +14 -8
  104. package/dist/lib/interrupt.js +28 -10
  105. package/dist/lib/junit-report.d.ts +60 -4
  106. package/dist/lib/junit-report.js +209 -32
  107. package/dist/lib/local-target.d.ts +3 -3
  108. package/dist/lib/local-target.js +3 -3
  109. package/dist/lib/output.d.ts +0 -29
  110. package/dist/lib/output.js +10 -33
  111. package/dist/lib/pagination.d.ts +2 -5
  112. package/dist/lib/pagination.js +2 -5
  113. package/dist/lib/presigned-url.d.ts +22 -0
  114. package/dist/lib/presigned-url.js +90 -0
  115. package/dist/lib/prompt.js +36 -2
  116. package/dist/lib/proxy.js +2 -1
  117. package/dist/lib/redact.d.ts +2 -2
  118. package/dist/lib/redact.js +3 -4
  119. package/dist/lib/removed-commands.d.ts +18 -0
  120. package/dist/lib/removed-commands.js +154 -0
  121. package/dist/lib/render-error.d.ts +31 -6
  122. package/dist/lib/render-error.js +88 -25
  123. package/dist/lib/response-schemas.d.ts +38 -30
  124. package/dist/lib/response-schemas.js +210 -207
  125. package/dist/lib/result/api.d.ts +24 -0
  126. package/dist/lib/result/api.js +28 -0
  127. package/dist/lib/result/evidence.d.ts +71 -0
  128. package/dist/lib/result/evidence.js +420 -0
  129. package/dist/lib/result/render.d.ts +20 -0
  130. package/dist/lib/result/render.js +194 -0
  131. package/dist/lib/result/types.d.ts +122 -0
  132. package/dist/lib/result/types.js +19 -0
  133. package/dist/lib/run-output.d.ts +275 -0
  134. package/dist/lib/run-output.js +227 -0
  135. package/dist/lib/run-render.d.ts +101 -0
  136. package/dist/lib/run-render.js +183 -0
  137. package/dist/lib/run-wait.d.ts +192 -0
  138. package/dist/lib/run-wait.js +452 -0
  139. package/dist/lib/runs.types.d.ts +134 -367
  140. package/dist/lib/runs.types.js +0 -14
  141. package/dist/lib/secret-file.d.ts +1 -1
  142. package/dist/lib/secret-file.js +11 -2
  143. package/dist/lib/skill-nudge.d.ts +7 -27
  144. package/dist/lib/skill-nudge.js +9 -37
  145. package/dist/lib/target-path.d.ts +15 -0
  146. package/dist/lib/target-path.js +35 -0
  147. package/dist/lib/target-url-advisory.d.ts +19 -0
  148. package/dist/lib/target-url-advisory.js +31 -0
  149. package/dist/lib/target-url-preflight.d.ts +9 -0
  150. package/dist/lib/target-url-preflight.js +214 -106
  151. package/dist/lib/target-url.d.ts +1 -1
  152. package/dist/lib/target-url.js +6 -16
  153. package/dist/lib/telemetry.d.ts +32 -12
  154. package/dist/lib/telemetry.js +39 -8
  155. package/dist/lib/terminal-text.d.ts +41 -0
  156. package/dist/lib/terminal-text.js +127 -0
  157. package/dist/lib/testlist.types.d.ts +16 -8
  158. package/dist/lib/testlist.types.js +1 -1
  159. package/dist/lib/text-equality.d.ts +2 -0
  160. package/dist/lib/text-equality.js +5 -0
  161. package/dist/lib/text-file.d.ts +16 -0
  162. package/dist/lib/text-file.js +41 -0
  163. package/dist/lib/text-table.d.ts +46 -0
  164. package/dist/lib/text-table.js +72 -4
  165. package/dist/lib/ticker.d.ts +9 -2
  166. package/dist/lib/ticker.js +16 -3
  167. package/dist/lib/transport-failure.d.ts +22 -0
  168. package/dist/lib/transport-failure.js +126 -0
  169. package/dist/lib/tunnel-session.d.ts +7 -1
  170. package/dist/lib/tunnel-session.js +22 -9
  171. package/dist/lib/update-check.js +3 -2
  172. package/dist/lib/url-template.d.ts +43 -0
  173. package/dist/lib/url-template.js +151 -0
  174. package/dist/lib/validate.d.ts +0 -64
  175. package/dist/lib/validate.js +2 -131
  176. package/dist/lib/version-notice.js +4 -3
  177. package/dist/lib/wait-exit.d.ts +37 -2
  178. package/dist/lib/wait-exit.js +88 -30
  179. package/dist/lib/workspace-status.js +10 -2
  180. package/dist/version.d.ts +1 -1
  181. package/dist/version.js +1 -1
  182. package/package.json +3 -4
  183. package/skills/testsprite-ci.skill.md +48 -18
  184. package/skills/testsprite-onboard.skill.md +66 -151
  185. package/skills/testsprite-verify.codex.md +54 -56
  186. package/skills/testsprite-verify.skill.md +194 -358
  187. package/dist/lib/browser.d.ts +0 -6
  188. package/dist/lib/browser.js +0 -54
  189. package/dist/lib/bundle.d.ts +0 -234
  190. package/dist/lib/bundle.js +0 -781
  191. package/dist/lib/deprecate.d.ts +0 -10
  192. package/dist/lib/deprecate.js +0 -13
  193. package/dist/lib/flaky.d.ts +0 -91
  194. package/dist/lib/flaky.js +0 -71
  195. package/dist/lib/plan-poll.d.ts +0 -171
  196. package/dist/lib/plan-poll.js +0 -441
  197. package/dist/lib/plans.types.d.ts +0 -130
  198. package/dist/lib/plans.types.js +0 -31
  199. package/dist/lib/poll.d.ts +0 -100
  200. package/dist/lib/poll.js +0 -290
  201. package/dist/lib/rate-throttle.d.ts +0 -49
  202. package/dist/lib/rate-throttle.js +0 -75
  203. package/dist/lib/run-progress.d.ts +0 -41
  204. package/dist/lib/run-progress.js +0 -56
  205. package/dist/lib/v3-advisory.d.ts +0 -55
  206. package/dist/lib/v3-advisory.js +0 -74
  207. package/schemas/plan.schema.json +0 -61
@@ -3,7 +3,8 @@ import { type ShutdownHandle } from './interrupt.js';
3
3
  import { openTunnelSession, type TunnelClientHandle } from './tunnel-session.js';
4
4
  import { type TunnelClientOptions } from '../vendor/tunnel-client/index.js';
5
5
  import type { HttpClient } from './http.js';
6
- import type { RunResponse } from './runs.types.js';
6
+ import type { RunWaitSnapshot } from './run-wait.js';
7
+ import type { CliTestListRunResponse } from './testlist.types.js';
7
8
  import { ApiError } from './errors.js';
8
9
  import { type LoopbackHost, type StoredLocalTarget } from './local-target.js';
9
10
  export interface RunTargetTest {
@@ -28,7 +29,6 @@ export declare function assertNoTunnelOptions(args: {
28
29
  tunnelClientId?: string;
29
30
  cancelOnInterrupt?: boolean;
30
31
  }): void;
31
- export declare function severalIdsWithoutTunnel(): never;
32
32
  /** One resolver for fresh runs, replay, chained creation and test-list runs. */
33
33
  export declare function resolveEnvironmentRunTarget(args: {
34
34
  client: Pick<HttpClient, 'get'>;
@@ -48,7 +48,6 @@ export declare function resolveEnvironmentRunTarget(args: {
48
48
  stderr: (line: string) => void;
49
49
  cache?: Map<string, Environment[] | undefined>;
50
50
  }): Promise<ResolvedRunTarget | undefined>;
51
- export declare function tunnelScopeError(err: unknown): unknown;
52
51
  export declare function unsupportedTunnelError(command: string): ApiError;
53
52
  export interface EnvironmentTunnelContext {
54
53
  client: HttpClient;
@@ -57,47 +56,36 @@ export interface EnvironmentTunnelContext {
57
56
  maxConcurrency: number;
58
57
  deadlineMs: number;
59
58
  session: Awaited<ReturnType<typeof openTunnelSession>>;
60
- cancellation: (runId: string) => 'cancelled' | 'cancel-failed' | undefined;
59
+ cancellation: (runId: string) => 'cancelled' | 'cancel-failed' | 'already-terminal' | undefined;
60
+ cancelActive: () => Promise<void>;
61
61
  skipped?: Array<{
62
62
  testId: string;
63
63
  reason: 'backend-test';
64
64
  }>;
65
- terminalRun: (runId: string) => RunResponse | undefined;
66
- waitForCapacity: (incoming: number) => Promise<void>;
65
+ resultStatus: (resultId: string) => string | undefined;
67
66
  confirm: (response: {
68
67
  tunnelClientId?: string;
69
68
  }, runIds: string[], requireEcho?: boolean) => Promise<void>;
70
- onPoll: (run: {
71
- runId: string;
72
- status: string;
73
- }) => void;
69
+ onRead: (snapshot: RunWaitSnapshot, signal: AbortSignal) => Promise<void>;
74
70
  }
75
- /** Replay and list dispatch keep their existing envelopes under one owned tunnel. */
71
+ /** Own tunnel lifecycle and executions, without a client-side dispatch capacity loop. */
76
72
  export declare function withEnvironmentTunnel<T>(opts: CommonOptions & {
77
73
  skipPreflight?: boolean;
78
74
  maxConcurrency?: number;
79
75
  timeoutSeconds?: number;
76
+ tunnelClientId?: string;
77
+ cancelOnInterrupt?: boolean;
80
78
  }, deps: ClientFactoryDeps & {
81
79
  shutdown?: ShutdownHandle;
82
80
  createTunnelClient?: (options: TunnelClientOptions) => TunnelClientHandle;
83
81
  sleep?: (ms: number) => Promise<void>;
84
82
  }, targets: ResolvedRunTarget[], command: string, operation: (context: EnvironmentTunnelContext) => Promise<T>): Promise<T>;
85
83
  /** Keep each dispatch on one verbatim loopback URL; public runs omit tunnel fields. */
86
- export declare function groupEnvironmentTargets(ids: string[], targets: ReadonlyMap<string, ResolvedRunTarget>, maxLocalGroupSize?: number): string[][];
84
+ export declare function groupEnvironmentTargets(ids: string[], targets: ReadonlyMap<string, {
85
+ targetUrl: string;
86
+ }>): string[][];
87
87
  export declare function quoteEnvironmentName(name: string): string;
88
- export declare function emitEnvironmentDispatchPartial(responses: Array<{
89
- accepted: Array<{
90
- testId: string;
91
- runId: string;
92
- }>;
93
- conflicts: Array<{
94
- testId: string;
95
- }>;
96
- deferred: Array<{
97
- testId: string;
98
- }>;
99
- notFound?: string[];
100
- }>, testIds: string[], opts: CommonOptions & {
88
+ export declare function emitEnvironmentDispatchPartial(responses: readonly CliTestListRunResponse[], testIds: string[], opts: CommonOptions & {
101
89
  report?: 'junit';
102
90
  reportFile?: string;
103
91
  reportSuiteName?: string;
@@ -105,5 +93,7 @@ export declare function emitEnvironmentDispatchPartial(responses: Array<{
105
93
  summaryFile?: string;
106
94
  }, deps: ClientFactoryDeps & {
107
95
  stdout?: (line: string) => void;
108
- }, label: string, error: unknown, context: EnvironmentTunnelContext): Promise<void>;
96
+ }, label: string, error: unknown, context: EnvironmentTunnelContext,
97
+ /** The reason a `notFound` id was not dispatched (`run --testlist`: not a member of the list). */
98
+ notFoundNote?: string): Promise<void>;
109
99
  export {};
@@ -1,22 +1,41 @@
1
+ import { isProxyAgentActive } from './proxy.js';
1
2
  import { makeHttpClient, resolveRequestTimeoutMs, } from './client-factory.js';
2
3
  import { globalShutdown } from './interrupt.js';
3
- import { openTunnelSession, TunnelLostError } from './tunnel-session.js';
4
+ import { TUNNEL_DATA_PLANE_PROXY_BYPASS_DESCRIPTION, openTunnelSession, TunnelLostError, } from './tunnel-session.js';
4
5
  import { TunnelClient } from '../vendor/tunnel-client/index.js';
5
6
  import { assertLocalPortListening } from './local-target.js';
6
- import { recordTelemetryTunnelOpened } from './telemetry.js';
7
+ import { recordTelemetryExtras, recordTelemetryTunnelOpened } from './telemetry.js';
7
8
  import { Output } from './output.js';
8
- import { emitCiArtifacts, summarizeAcceptedPayload } from './gh-output.js';
9
- import { buildJUnitReport, writeJUnitReportFile } from './junit-report.js';
10
- import { pollRunUntilTerminal, TimeoutError, isTerminalStatus } from './poll.js';
9
+ import { emitCiArtifacts, isNonDispatchedStatus } from './gh-output.js';
10
+ import { buildJUnitReport, skippedRowFromSummary, writeJUnitReportFile } from './junit-report.js';
11
+ import { launchIds } from './run-render.js';
12
+ import { buildRunOutput, listResultReceipt, renderRunResults } from './run-output.js';
11
13
  import { ApiError, InterruptError, RequestTimeoutError, localValidationError } from './errors.js';
12
14
  import { buildLocalTargetUrl, DEFAULT_LOCAL_HOST, parseLoopbackTargetUrl, } from './local-target.js';
15
+ import { terminalSafeLine, terminalSafeWriter } from './terminal-text.js';
13
16
  export const ENVIRONMENT_PREFLIGHT_TIMEOUT_MS = 5_000;
14
17
  /** Advisory-only reads must not inherit the run's long wait or retry budget. */
15
18
  export function readEnvironmentPreflight(client, path) {
16
- return client.get(path, {
17
- retry: false,
18
- signal: AbortSignal.timeout(ENVIRONMENT_PREFLIGHT_TIMEOUT_MS),
19
- });
19
+ // Abort with a RequestTimeoutError as the reason, not AbortSignal.timeout's
20
+ // raw DOMException: HttpClient passes a RequestTimeoutError through
21
+ // untouched, so a stalled preflight read surfaces as REQUEST_TIMEOUT
22
+ // (exit 7) instead of reaching the top-level catch as an uncaught
23
+ // exception. The 5s deadline here is fixed — --request-timeout does not
24
+ // govern it — so the message and nextAction name the preflight read
25
+ // rather than pointing at the flag.
26
+ const controller = new AbortController();
27
+ const timer = setTimeout(() => {
28
+ controller.abort(new RequestTimeoutError(ENVIRONMENT_PREFLIGHT_TIMEOUT_MS, 'local', {
29
+ message: `Environment preflight read timed out after ` +
30
+ `${ENVIRONMENT_PREFLIGHT_TIMEOUT_MS / 1000}s (client-side).`,
31
+ nextAction: 'The environment preflight read timed out. ' +
32
+ 'Check that the backend is reachable and not overloaded, then retry.',
33
+ }));
34
+ }, ENVIRONMENT_PREFLIGHT_TIMEOUT_MS);
35
+ timer.unref?.();
36
+ return client
37
+ .get(path, { retry: false, signal: controller.signal })
38
+ .finally(() => clearTimeout(timer));
20
39
  }
21
40
  export function assertNoTunnelOptions(args) {
22
41
  if (args.tunnelClientId !== undefined)
@@ -27,9 +46,6 @@ export function assertNoTunnelOptions(args) {
27
46
  'cancelled when this command stops waiting — Ctrl-C detaches, and `testsprite test ' +
28
47
  'cancel <run-id>` is the way to stop one');
29
48
  }
30
- export function severalIdsWithoutTunnel() {
31
- throw localValidationError('test-id', 'several test ids run through one tunnel with --local <port>. For tests the runner can already reach, use `testsprite test run --all --project <id> [--filter <text>]`, or run them one at a time.');
32
- }
33
49
  const announcedEnvironments = new WeakMap();
34
50
  /** One resolver for fresh runs, replay, chained creation and test-list runs. */
35
51
  export async function resolveEnvironmentRunTarget(args) {
@@ -63,7 +79,7 @@ export async function resolveEnvironmentRunTarget(args) {
63
79
  }
64
80
  if (test?.type === 'backend' && !args.includeBackend) {
65
81
  if (explicit)
66
- throw localValidationError('local', `backend tests don't open a browser; the tunnel is not used. Run: testsprite test run ${args.testId}`);
82
+ throw localValidationError('local', `backend tests don't open a browser; the tunnel is not used. Run: testsprite run ${args.testId}`);
67
83
  return undefined;
68
84
  }
69
85
  const projectId = test?.projectId ?? args.projectId;
@@ -116,7 +132,7 @@ export async function resolveEnvironmentRunTarget(args) {
116
132
  };
117
133
  const explicitTarget = (target) => {
118
134
  if (args.environment !== undefined && selected && !localOf(selected))
119
- announce(`sign-in:${projectId}:${selected.name}:${target.targetUrl}`, `Using environment "${selected.name}" sign-in against ${target.targetUrl} through a tunnel.`);
135
+ announce(`sign-in:${projectId}:${selected.name}:${target.targetUrl}`, `Using environment "${terminalSafeLine(selected.name)}" sign-in against ${terminalSafeLine(target.targetUrl)} through a tunnel.`);
120
136
  return target;
121
137
  };
122
138
  if (explicitUrl)
@@ -146,8 +162,8 @@ export async function resolveEnvironmentRunTarget(args) {
146
162
  if (!args.tunnelClientId && test?.type !== 'backend') {
147
163
  const key = `${projectId}:${selected.name}:${selected.url}`;
148
164
  announce(key, args.dryRun
149
- ? `Would open a tunnel to ${selected.url} (environment "${selected.name}").`
150
- : `Environment "${selected.name}" is on this machine (${selected.url}) — opening a tunnel.`);
165
+ ? `Would open a tunnel to ${terminalSafeLine(selected.url)} (environment "${terminalSafeLine(selected.name)}").`
166
+ : `Environment "${terminalSafeLine(selected.name)}" is on this machine (${terminalSafeLine(selected.url)}) — opening a tunnel.`);
151
167
  }
152
168
  return {
153
169
  ...local,
@@ -156,30 +172,22 @@ export async function resolveEnvironmentRunTarget(args) {
156
172
  environmentName: selected.name,
157
173
  };
158
174
  }
159
- export function tunnelScopeError(err) {
160
- if (!(err instanceof ApiError) || err.httpStatus !== 403)
161
- return err;
162
- return new ApiError({
163
- code: err.code,
164
- message: err.message,
165
- requestId: err.requestId,
166
- details: err.details,
167
- nextAction: `${err.nextAction ?? ''} A tunnel is required for this environment; use an API key with run:tunnel permission.`,
168
- }, err.httpStatus);
169
- }
170
175
  export function unsupportedTunnelError(command) {
171
176
  return new ApiError({
172
177
  code: 'UNSUPPORTED',
173
178
  message: `This server did not confirm tunnel use for ${command}. Cancellation was attempted for the started runs; no tunnel-free result can be trusted.`,
174
- nextAction: 'Update the server, or use testsprite test run <id> with the saved environment.',
179
+ nextAction: 'Update the server, or use testsprite run <id> with the saved environment.',
175
180
  requestId: 'local',
176
181
  details: {},
177
182
  });
178
183
  }
179
- /** Replay and list dispatch keep their existing envelopes under one owned tunnel. */
184
+ /** Own tunnel lifecycle and executions, without a client-side dispatch capacity loop. */
180
185
  export async function withEnvironmentTunnel(opts, deps, targets, command, operation) {
181
- const stderr = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
186
+ const stderr = terminalSafeWriter(deps.stderr);
182
187
  const shutdown = deps.shutdown ?? globalShutdown;
188
+ if (isProxyAgentActive())
189
+ stderr(`[advisory] An HTTP proxy is configured for this process. The tunnel control channel honours it, but ${TUNNEL_DATA_PLANE_PROXY_BYPASS_DESCRIPTION} — if the run cannot reach your machine, an egress proxy is the first thing to rule out.`);
190
+ recordTelemetryExtras({ localConcurrencyLimit: opts.maxConcurrency ?? 5 });
183
191
  const seen = new Set();
184
192
  for (const target of targets) {
185
193
  if (seen.has(target.targetUrl))
@@ -201,130 +209,113 @@ export async function withEnvironmentTunnel(opts, deps, targets, command, operat
201
209
  };
202
210
  const cleanup = (operation) => request(10_000, operation);
203
211
  const client = makeHttpClient(opts, { ...deps, shutdownSignal: shutdown.signal, shutdown });
212
+ const livenessClient = makeHttpClient({ ...opts, debug: false, verbose: false }, { ...deps, shutdownSignal: shutdown.signal, shutdown });
204
213
  const active = new Set();
205
- const terminalRuns = new Map();
206
- const getRun = client.getRun.bind(client);
207
- client.getRun = async (runId, options) => {
208
- const cached = terminalRuns.get(runId);
209
- if (cached)
210
- return cached;
211
- const run = await getRun(runId, options);
212
- if (isTerminalStatus(run.status))
213
- terminalRuns.set(runId, run);
214
- return run;
215
- };
214
+ const statuses = new Map();
216
215
  const cancellations = new Map();
217
216
  let failure;
218
- let context;
219
- const cancel = async () => {
217
+ let session;
218
+ let ownerGone = false;
219
+ let lastLivenessRead = -Infinity;
220
+ const cancel = async (force = false) => {
221
+ if (!force && (opts.cancelOnInterrupt === false || (session?.adopted && !ownerGone)))
222
+ return;
220
223
  for (const runId of active) {
221
224
  try {
222
- await cleanup(transport => transport.cancelRun(runId));
223
- cancellations.set(runId, 'cancelled');
224
- stderr(`[tunnel] Cancellation requested for ${runId}; the owned tunnel is closing.`);
225
+ const cancelled = await cleanup(transport => transport.cancelRun(runId));
226
+ cancellations.set(runId, cancelled.alreadyFinished ? 'already-terminal' : 'cancelled');
227
+ stderr(cancelled.alreadyFinished
228
+ ? `[tunnel] Run ${terminalSafeLine(runId)} had already finished; no cancellation was needed.`
229
+ : `[tunnel] Cancellation requested for run ${terminalSafeLine(runId)}; its tunnel is closing.`);
230
+ for (const result of cancelled.results)
231
+ if (result.refund?.status === 'failed')
232
+ stderr(`[tunnel] Refund failed for result ${terminalSafeLine(result.resultId)}: inspect the cancellation response or contact support.`);
225
233
  }
226
234
  catch (err) {
227
- cancellations.set(runId, 'failed');
228
- stderr(`[tunnel] Could not cancel ${runId}: ${err instanceof Error ? err.message : String(err)}. Use testsprite test cancel ${runId}.`);
235
+ cancellations.set(runId, 'cancel-failed');
236
+ stderr(`[tunnel] Could not cancel run ${terminalSafeLine(runId)}: ${terminalSafeLine(err instanceof Error ? err.message : String(err))}. Use testsprite run cancel ${terminalSafeLine(runId)}.`);
229
237
  }
230
238
  active.delete(runId);
231
239
  }
232
240
  };
233
241
  const disarm = shutdown.arm();
234
- let session;
235
242
  try {
236
243
  try {
237
- session = await openTunnelSession({ log: stderr, logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error' }, {
244
+ session = await openTunnelSession({
245
+ log: stderr,
246
+ onMinted: ({ clientId }) => stderr(`[tunnel] Minted tunnel client ${terminalSafeLine(clientId)}`),
247
+ logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error',
248
+ ...(opts.tunnelClientId
249
+ ? { adopt: { clientId: opts.tunnelClientId, expiresAt: '' } }
250
+ : {}),
251
+ }, {
238
252
  mint: ttlSeconds => request(requestTimeoutMs, transport => transport.mintTunnel({ ...(ttlSeconds ? { ttlSeconds } : {}) })),
239
253
  destroy: clientId => cleanup(transport => transport.deleteTunnel(clientId)),
240
254
  createClient: shutdownAwareTunnelClient(deps.createTunnelClient ?? (options => new TunnelClient(options)), shutdown.signal),
241
255
  });
242
256
  }
243
257
  catch (err) {
244
- throw tunnelScopeError(err);
258
+ if (shutdown.signal.aborted)
259
+ throw shutdown.signal.reason;
260
+ throw err;
245
261
  }
246
- recordTelemetryTunnelOpened(true);
247
- if (shutdown.signal.aborted)
248
- throw shutdown.signal.reason;
249
- const checkDispatch = () => {
262
+ recordTelemetryTunnelOpened(!session.adopted);
263
+ const dispatch = (operation) => {
250
264
  if (shutdown.signal.aborted)
251
265
  throw shutdown.signal.reason;
252
266
  if (session.fatalReason())
253
- throw new TunnelLostError(session.fatalReason(), '', session.fatalMessage());
254
- };
255
- // Retain a charged response across the first interrupt, with a total retry deadline.
256
- const dispatch = (operation) => {
257
- checkDispatch();
267
+ throw new TunnelLostError(session.fatalReason(), {}, session.fatalMessage());
268
+ // Keep the response across the first interrupt so its owned run can be cancelled.
258
269
  return request(requestTimeoutMs, operation);
259
270
  };
260
- client.triggerRerun = (...args) => dispatch(transport => transport.triggerRerun(...args));
261
- client.triggerBatchRerun = (...args) => dispatch(transport => transport.triggerBatchRerun(...args));
271
+ client.triggerProjectRun = (...args) => dispatch(transport => transport.triggerProjectRun(...args));
262
272
  client.triggerTestListRun = (...args) => dispatch(transport => transport.triggerTestListRun(...args));
263
- client.triggerRunWithMeta = (...args) => dispatch(transport => transport.triggerRunWithMeta(...args));
264
- const deadlineMs = Date.now() + (opts.timeoutSeconds ?? 600) * 1000;
265
- const assertCapacityDeadline = () => {
266
- if (Date.now() >= deadlineMs)
267
- throw new ApiError({
268
- code: 'UNSUPPORTED',
269
- message: `Timed out after ${opts.timeoutSeconds ?? 600}s waiting for tunnel batch capacity.`,
270
- nextAction: 'The owned tunnel is closing; inspect cancellation with testsprite test cancel <run-id>.',
271
- requestId: 'local',
272
- details: {},
273
- });
274
- };
275
- context = {
273
+ return await operation({
276
274
  client,
277
275
  session,
278
- deadlineMs,
279
- cancellation: id => {
280
- const outcome = cancellations.get(id);
281
- return outcome === 'failed' ? 'cancel-failed' : outcome;
282
- },
283
276
  clientId: session.clientId,
284
277
  maxConcurrency: opts.maxConcurrency ?? 5,
285
- terminalRun: runId => terminalRuns.get(runId),
286
- waitForCapacity: async (incoming) => {
287
- assertCapacityDeadline();
288
- while (active.size + incoming > (opts.maxConcurrency ?? 5)) {
289
- const runId = active.values().next().value;
278
+ deadlineMs: Date.now() + (opts.timeoutSeconds ?? 600) * 1000,
279
+ cancellation: runId => cancellations.get(runId),
280
+ cancelActive: () => cancel(),
281
+ resultStatus: resultId => statuses.get(resultId),
282
+ confirm: async (response, runIds, requireEcho = true) => {
283
+ for (const runId of runIds)
284
+ active.add(runId);
285
+ if (requireEcho && runIds.length > 0 && response.tunnelClientId !== session.clientId) {
286
+ await cancel(true);
287
+ throw unsupportedTunnelError(command);
288
+ }
289
+ },
290
+ onRead: async ({ run, results }, signal) => {
291
+ for (const result of results)
292
+ statuses.set(result.resultId, result.testStatus.toLowerCase());
293
+ if (run.status === 'finished') {
294
+ active.delete(run.runId);
295
+ return;
296
+ }
297
+ if (!active.has(run.runId))
298
+ return;
299
+ const fatal = session.fatalReason();
300
+ if (fatal)
301
+ throw new TunnelLostError(fatal, { runId: run.runId }, session.fatalMessage());
302
+ if (session.adopted && Date.now() - lastLivenessRead >= 15_000) {
303
+ lastLivenessRead = Date.now();
290
304
  try {
291
- await pollRunUntilTerminal(client, runId, {
292
- timeoutSeconds: Math.max(0, (deadlineMs - Date.now()) / 1000),
293
- shutdown,
294
- sleep: deps.sleep,
295
- onTick: run => context.onPoll(run),
305
+ const observed = await livenessClient.getTunnelStatus(session.clientId, {
306
+ signal,
307
+ retry: false,
296
308
  });
309
+ ownerGone = observed.status.toLowerCase() === 'offline';
297
310
  }
298
311
  catch (err) {
299
- if (!(err instanceof TimeoutError))
300
- throw err;
301
- throw new ApiError({
302
- code: 'UNSUPPORTED',
303
- message: err.message,
304
- nextAction: `The owned tunnel is closing; inspect cancellation with testsprite test cancel ${runId}.`,
305
- requestId: 'local',
306
- details: { runId },
307
- });
312
+ ownerGone = err instanceof ApiError && err.httpStatus === 404;
308
313
  }
309
- }
310
- assertCapacityDeadline();
311
- },
312
- confirm: async (response, runIds, requireEcho = true) => {
313
- for (const id of runIds)
314
- active.add(id);
315
- if (requireEcho && runIds.length && response.tunnelClientId !== session.clientId) {
316
- await cancel();
317
- throw unsupportedTunnelError(command);
314
+ if (ownerGone)
315
+ throw new TunnelLostError('owner-gone', { runId: run.runId });
318
316
  }
319
317
  },
320
- onPoll: run => {
321
- if (['passed', 'failed', 'blocked', 'cancelled'].includes(run.status))
322
- active.delete(run.runId);
323
- else if (active.has(run.runId) && session.fatalReason())
324
- throw new TunnelLostError(session.fatalReason(), run.runId, session.fatalMessage());
325
- },
326
- };
327
- return await operation(context);
318
+ });
328
319
  }
329
320
  catch (err) {
330
321
  failure = err;
@@ -333,18 +324,18 @@ export async function withEnvironmentTunnel(opts, deps, targets, command, operat
333
324
  finally {
334
325
  const closing = [...active];
335
326
  await cancel();
336
- if (failure instanceof InterruptError && closing.length) {
337
- const runId = closing[0];
338
- const cancelOutcome = closing.every(id => cancellations.get(id) === 'cancelled')
339
- ? 'cancelled'
340
- : 'failed';
341
- const retry = [...(context?.targets ?? [])]
342
- .map(([id, target]) => `testsprite test run ${id}${target.environmentName ? ` --env ${quoteEnvironmentName(target.environmentName)}` : ''}`)
343
- .join('; ') || 'testsprite test run <id>';
344
- const nextAction = `The owned tunnel is closing; cancellation was ${cancelOutcome === 'cancelled' ? 'requested' : 'attempted'} for ${closing.join(' ')}. Inspect with testsprite test cancel ${closing.join(' ')}. Start a new run with ${retry}.`;
327
+ if (failure instanceof InterruptError && closing.length && (!session?.adopted || ownerGone)) {
328
+ const cancelled = closing.every(id => cancellations.get(id) === 'cancelled');
329
+ const nextAction = cancelled
330
+ ? `The owned tunnel closed; cancellation was requested for runs ${closing.join(' ')}. Start a new run to test the local target again.`
331
+ : `The owned tunnel closed; cancellation was not confirmed. Stop the runs with testsprite run cancel ${closing.join(' ')}.`;
345
332
  Object.assign(failure, {
346
333
  runWaitContext: true,
347
- tunnelDetach: { runId, cancel: cancelOutcome, nextAction },
334
+ tunnelDetach: {
335
+ runId: closing[0],
336
+ cancel: cancelled ? 'cancelled' : opts.cancelOnInterrupt === false ? 'skipped' : 'failed',
337
+ nextAction,
338
+ },
348
339
  });
349
340
  }
350
341
  try {
@@ -382,7 +373,7 @@ function shutdownAwareTunnelClient(create, signal) {
382
373
  };
383
374
  }
384
375
  /** Keep each dispatch on one verbatim loopback URL; public runs omit tunnel fields. */
385
- export function groupEnvironmentTargets(ids, targets, maxLocalGroupSize = Infinity) {
376
+ export function groupEnvironmentTargets(ids, targets) {
386
377
  const groups = new Map();
387
378
  for (const id of ids) {
388
379
  const key = targets.get(id)?.targetUrl;
@@ -390,28 +381,24 @@ export function groupEnvironmentTargets(ids, targets, maxLocalGroupSize = Infini
390
381
  group.push(id);
391
382
  groups.set(key, group);
392
383
  }
393
- return [...groups.values()].flatMap(group => {
394
- if (!targets.has(group[0]) || !Number.isFinite(maxLocalGroupSize))
395
- return [group];
396
- const chunks = [];
397
- for (let index = 0; index < group.length; index += maxLocalGroupSize)
398
- chunks.push(group.slice(index, index + maxLocalGroupSize));
399
- return chunks;
400
- });
384
+ return [...groups.values()];
401
385
  }
402
386
  export function quoteEnvironmentName(name) {
403
387
  return "'" + name.replaceAll("'", "'\\''") + "'";
404
388
  }
405
- export async function emitEnvironmentDispatchPartial(responses, testIds, opts, deps, label, error, context) {
389
+ export async function emitEnvironmentDispatchPartial(responses, testIds, opts, deps, label, error, context,
390
+ /** The reason a `notFound` id was not dispatched (`run --testlist`: not a member of the list). */
391
+ notFoundNote) {
406
392
  const message = error instanceof Error ? error.message : String(error);
407
393
  const timedOut = error instanceof RequestTimeoutError ||
408
394
  (error instanceof ApiError && error.code === 'UNSUPPORTED' && message.startsWith('Timed out'));
409
395
  const accepted = responses
410
396
  .flatMap(response => response.accepted)
397
+ .map(listResultReceipt)
411
398
  .map(row => ({
412
399
  ...row,
413
- status: context.cancellation(row.runId) ??
414
- context.terminalRun(row.runId)?.status ??
400
+ status: (row.runId ? context.cancellation(row.runId) : undefined) ??
401
+ context.resultStatus(row.resultId) ??
415
402
  (timedOut ? 'timeout' : 'running'),
416
403
  }));
417
404
  const conflicts = responses.flatMap(response => response.conflicts);
@@ -421,24 +408,34 @@ export async function emitEnvironmentDispatchPartial(responses, testIds, opts, d
421
408
  for (const id of notFound)
422
409
  seen.add(id);
423
410
  const notRunTestIds = testIds.filter(id => !seen.has(id));
424
- const partial = {
425
- accepted,
411
+ const buckets = {
426
412
  conflicts,
427
413
  deferred,
428
414
  ...(context.skipped?.length ? { skipped: context.skipped } : {}),
429
- notRunTestIds,
430
415
  ...(responses.some(response => response.notFound) ? { notFound } : {}),
431
416
  };
432
- const stderr = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
433
- new Output(opts.output, { stdout: deps.stdout, stderr: deps.stderr }).print(partial, () => accepted.map(row => `${row.runId} ${row.status}`).join('\n'));
434
- const summary = summarizeAcceptedPayload(JSON.stringify(partial));
435
- summary.runs.push(...notRunTestIds.map(testId => ({
436
- testId,
437
- status: 'skipped',
438
- error: 'not dispatched before the owned tunnel closed',
439
- })));
440
- summary.total += notRunTestIds.length;
441
- summary.skipped += notRunTestIds.length;
417
+ const { output, summary } = buildRunOutput({
418
+ receipts: launchIds(accepted).map(runId => ({ runId })),
419
+ dispatched: accepted,
420
+ wait: true,
421
+ failure: error,
422
+ requestTimedOut: timedOut,
423
+ incompleteDispatch: true,
424
+ cancellation: context.cancellation,
425
+ buckets: {
426
+ ...buckets,
427
+ skipped: [
428
+ ...(context.skipped ?? []),
429
+ ...notRunTestIds.map(testId => ({
430
+ testId,
431
+ reason: 'not dispatched before the owned tunnel closed',
432
+ })),
433
+ ],
434
+ },
435
+ notFoundNote,
436
+ });
437
+ const stderr = terminalSafeWriter(deps.stderr);
438
+ new Output(opts.output, { stdout: deps.stdout, stderr: deps.stderr }).print({ ...output, ...buckets, notRunTestIds }, () => renderRunResults(output.runs, output.results, summary));
442
439
  emitCiArtifacts(summary, opts, {
443
440
  env: deps.env ?? process.env,
444
441
  stdout: deps.stdout ?? (line => process.stdout.write(`${line}\n`)),
@@ -449,12 +446,19 @@ export async function emitEnvironmentDispatchPartial(responses, testIds, opts, d
449
446
  await writeJUnitReportFile(opts.reportFile, buildJUnitReport({
450
447
  suiteName: opts.reportSuiteName ?? `testsprite:${label}`,
451
448
  classname: label,
452
- results: summary.runs.map(row => ({
453
- testId: row.testId,
454
- runId: row.runId,
455
- status: row.status,
456
- error: { code: error instanceof ApiError ? error.code : 'UNSUPPORTED', message },
457
- })),
449
+ // A test that never dispatched is skipped with its own reason. A
450
+ // dispatched one keeps the status it reached (running, timeout, a
451
+ // verdict) and names the error that closed the tunnel, which is why
452
+ // this is not `junitRowsFromSummary`.
453
+ results: summary.results.map(row => isNonDispatchedStatus(row.status)
454
+ ? skippedRowFromSummary(row)
455
+ : {
456
+ testId: row.testId ?? row.resultId ?? '(unknown)',
457
+ resultId: row.resultId,
458
+ runId: row.runId,
459
+ status: row.status,
460
+ error: { code: error instanceof ApiError ? error.code : 'UNSUPPORTED', message },
461
+ }),
458
462
  }));
459
463
  }
460
464
  catch (err) {
@@ -168,13 +168,19 @@ export declare class ApiError extends CLIError {
168
168
  * (e.g. `'... Remove --target-url.'`), and unconditionally appending a
169
169
  * second period produced a doubled `..` at the end of the rendered message.
170
170
  */
171
- export declare function localValidationError(field: string, reason: string, accepted?: unknown, kind?: 'flag' | 'field'): ApiError;
171
+ export declare function localValidationError(field: string, reason: string, accepted?: unknown, kind?: 'flag' | 'field' | 'argument'): ApiError;
172
+ export interface TransportErrorOptions {
173
+ /** Cause-specific remediation; defaults to the generic availability text. */
174
+ nextAction?: string;
175
+ /** Machine-readable cause, e.g. `{ cause: 'SELF_SIGNED_CERT_IN_CHAIN' }`. */
176
+ details?: Record<string, unknown>;
177
+ }
172
178
  /**
173
179
  * Network/transport failure not associated with a server envelope. Treated
174
180
  * as `UNAVAILABLE` for exit-code purposes per design §8.2.
175
181
  */
176
182
  export declare class TransportError extends ApiError {
177
- constructor(message: string, requestId?: string);
183
+ constructor(message: string, requestId?: string, options?: TransportErrorOptions);
178
184
  }
179
185
  /**
180
186
  * Client-side per-request timeout. The fetch was aborted because the
@@ -184,11 +190,21 @@ export declare class TransportError extends ApiError {
184
190
  * as `TimeoutError` from the polling path. Use `--request-timeout <s>` or
185
191
  * `TESTSPRITE_REQUEST_TIMEOUT_MS` to extend the deadline when targeting a
186
192
  * slow backend.
193
+ *
194
+ * A caller working against a fixed internal deadline the `--request-timeout`
195
+ * flag does not govern (e.g. the environment preflight read) passes
196
+ * `message` / `nextAction` overrides so the rendered guidance names that
197
+ * deadline instead of pointing at the flag.
187
198
  */
188
199
  export declare class RequestTimeoutError extends CLIError {
189
200
  readonly requestId: string;
190
201
  readonly timeoutMs: number;
191
- constructor(timeoutMs: number, requestId?: string);
202
+ /** Caller-specific envelope guidance; unset keeps the generic advice. */
203
+ readonly nextAction?: string;
204
+ constructor(timeoutMs: number, requestId?: string, options?: {
205
+ message?: string;
206
+ nextAction?: string;
207
+ });
192
208
  }
193
209
  /**
194
210
  * The synthesized `nextAction` for an INSUFFICIENT_CREDITS refusal when the
@@ -197,7 +213,7 @@ export declare class RequestTimeoutError extends CLIError {
197
213
  * prod portals live on different domains); an unknown host gets the route only —
198
214
  * a hardcoded domain would point at the wrong environment.
199
215
  *
200
- * V3 API keys are membership-bound: a key minted for a team org spends THAT
216
+ * API keys are membership-bound: a key minted for a team org spends THAT
201
217
  * org's wallet, not the holder's personal one, and there is no request-scoped
202
218
  * signal at this layer to tell which kind of key just failed. So the hint
203
219
  * deliberately does NOT assert "top up your (personal) credits" as the only