@testsprite/testsprite-cli 0.17.0 → 0.18.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 (55) hide show
  1. package/README.md +5 -4
  2. package/dist/commands/auth.js +2 -2
  3. package/dist/commands/conversation.js +52 -13
  4. package/dist/commands/project-env.js +48 -8
  5. package/dist/commands/project.d.ts +4 -0
  6. package/dist/commands/project.js +19 -2
  7. package/dist/commands/result.js +2 -1
  8. package/dist/commands/test.d.ts +9 -31
  9. package/dist/commands/test.js +73 -159
  10. package/dist/commands/testlist.d.ts +4 -2
  11. package/dist/commands/testlist.js +32 -4
  12. package/dist/commands/tunnel.d.ts +3 -3
  13. package/dist/commands/tunnel.js +3 -4
  14. package/dist/index.js +9 -6
  15. package/dist/lib/client-factory.d.ts +2 -2
  16. package/dist/lib/client-factory.js +3 -4
  17. package/dist/lib/conversation/api.d.ts +4 -0
  18. package/dist/lib/conversation/api.js +1 -0
  19. package/dist/lib/conversation/context.d.ts +10 -0
  20. package/dist/lib/conversation/context.js +17 -5
  21. package/dist/lib/conversation/environment.d.ts +3 -2
  22. package/dist/lib/conversation/environment.js +5 -17
  23. package/dist/lib/conversation/render.js +3 -0
  24. package/dist/lib/conversation/types.d.ts +2 -0
  25. package/dist/lib/download.d.ts +30 -1
  26. package/dist/lib/download.js +205 -71
  27. package/dist/lib/environment-tunnel.d.ts +3 -3
  28. package/dist/lib/environment-tunnel.js +9 -50
  29. package/dist/lib/first-suite-hint.d.ts +9 -13
  30. package/dist/lib/first-suite-hint.js +29 -35
  31. package/dist/lib/http.d.ts +1 -1
  32. package/dist/lib/http.js +5 -5
  33. package/dist/lib/local-target.d.ts +5 -4
  34. package/dist/lib/local-target.js +11 -10
  35. package/dist/lib/output.d.ts +1 -1
  36. package/dist/lib/output.js +2 -2
  37. package/dist/lib/presigned-url.js +2 -2
  38. package/dist/lib/removed-commands.js +17 -1
  39. package/dist/lib/result/evidence.d.ts +2 -0
  40. package/dist/lib/result/evidence.js +2 -0
  41. package/dist/lib/run-output.d.ts +3 -3
  42. package/dist/lib/target-url.d.ts +7 -7
  43. package/dist/lib/target-url.js +8 -8
  44. package/dist/lib/telemetry.d.ts +4 -4
  45. package/dist/lib/telemetry.js +1 -1
  46. package/dist/lib/transport-failure.js +2 -2
  47. package/dist/lib/tunnel-session.d.ts +1 -1
  48. package/dist/lib/tunnel-session.js +2 -2
  49. package/dist/version.d.ts +1 -1
  50. package/dist/version.js +1 -1
  51. package/package.json +1 -1
  52. package/skills/testsprite-ci.skill.md +4 -5
  53. package/skills/testsprite-onboard.skill.md +14 -12
  54. package/skills/testsprite-verify.codex.md +12 -14
  55. package/skills/testsprite-verify.skill.md +19 -21
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { Command, CommanderError } from 'commander';
2
+ import { Command, CommanderError, Option } from 'commander';
3
3
  import { createAgentCommand } from './commands/agent.js';
4
4
  import { createAuthCommand } from './commands/auth.js';
5
5
  import { createCiCommand } from './commands/ci.js';
@@ -44,7 +44,9 @@ program
44
44
  .version(VERSION)
45
45
  .option('--output <mode>', 'Output format (json|text)', 'text')
46
46
  .option('--profile <name>', 'Configuration profile to use')
47
- .option('--endpoint-url <url>', 'API base URL (a full http(s) URL)')
47
+ // For TestSprite's own use (pointing the CLI at a non-production API): it
48
+ // works, and no help page, completion script or "did you mean" names it.
49
+ .addOption(new Option('--endpoint-url <url>', 'API base URL (a full http(s) URL)').hideHelp())
48
50
  .option('--verbose', 'Log HTTP retry / backoff / polling transitions to stderr (lighter than --debug)')
49
51
  .option('--debug', 'Print HTTP method/path, request id, latency, retry decisions to stderr')
50
52
  .option('--dry-run', 'Skip the network and credentials; emit a canned sample matching the OpenAPI contract. Exception: run launches (`run --project`, `run <test-id...>`, `run --testlist`) with credentials and no explicit target may make read-only GETs to preview an automatic tunnel target; nothing is created or started.')
@@ -118,6 +120,7 @@ function buildCompletionSpec() {
118
120
  subcommands[command.name()] = subs;
119
121
  }
120
122
  const flags = program.options
123
+ .filter(option => !option.hidden)
121
124
  .map(option => option.long)
122
125
  .filter((long) => typeof long === 'string');
123
126
  if (!flags.includes('--help'))
@@ -146,7 +149,7 @@ let telemetryEmit = false;
146
149
  // `auth remove` (which deletes the profile) is still reported on the key it used.
147
150
  let telemetryAuth;
148
151
  // Local project admission failures must exit without any TestSprite HTTP,
149
- // including telemetry. Track companion flags even when --local is missing.
152
+ // including telemetry.
150
153
  let telemetryLocalProject = false;
151
154
  // Propagate exitOverride AND the buffered outputError config to every
152
155
  // subcommand in the tree. Commander's addCommand() does NOT inherit either
@@ -232,8 +235,8 @@ function commandNamedBy(args) {
232
235
  }
233
236
  program.addHelpText('after', '\nEnvironment:\n' +
234
237
  ' TESTSPRITE_API_KEY (overrides stored credentials), TESTSPRITE_NO_UPDATE_NOTIFIER (disables\n' +
235
- ' the version check); TESTSPRITE_API_URL, TESTSPRITE_PROFILE and TESTSPRITE_REQUEST_TIMEOUT_MS\n' +
236
- ' (milliseconds) mirror --endpoint-url, --profile and --request-timeout.');
238
+ ' the version check); TESTSPRITE_PROFILE and TESTSPRITE_REQUEST_TIMEOUT_MS (milliseconds)\n' +
239
+ ' mirror --profile and --request-timeout.');
237
240
  program.addHelpText('beforeAll', () => {
238
241
  const unknownCommand = unknownCommandIn(program.args)?.name;
239
242
  if (unknownCommand) {
@@ -271,7 +274,7 @@ program.hook('preAction', (_thisCommand, actionCommand) => {
271
274
  // Record which leaf command ran, for the telemetry emit around parseAsync.
272
275
  ranCommandPath = commandPath;
273
276
  const globals = actionCommand.optsWithGlobals();
274
- // Preserve explicit --local attempts, including refusals and borrowed tunnels;
277
+ // Preserve explicit --local attempts (project env create), including refusals;
275
278
  // only flag presence is recorded. Automatic tunnel paths record the same fact.
276
279
  if (globals.local !== undefined)
277
280
  recordTelemetryExtras({ local: true });
@@ -130,8 +130,8 @@ export declare function resolveRequestTimeoutMs(opts: Pick<CommonOptions, 'reque
130
130
  * retry-and-backoff cycle.
131
131
  *
132
132
  * The value can originate from `--endpoint-url`, `TESTSPRITE_API_URL`, or the
133
- * credentials file `api_url`, so the message names all three rather than
134
- * assuming the flag.
133
+ * credentials file `api_url`. The message names none of them: they are for
134
+ * TestSprite's own use and no user-facing text mentions them.
135
135
  */
136
136
  export declare function assertValidEndpointUrl(rawUrl: string): void;
137
137
  /**
@@ -97,8 +97,8 @@ function clampRequestTimeout(ms) {
97
97
  * retry-and-backoff cycle.
98
98
  *
99
99
  * The value can originate from `--endpoint-url`, `TESTSPRITE_API_URL`, or the
100
- * credentials file `api_url`, so the message names all three rather than
101
- * assuming the flag.
100
+ * credentials file `api_url`. The message names none of them: they are for
101
+ * TestSprite's own use and no user-facing text mentions them.
102
102
  */
103
103
  export function assertValidEndpointUrl(rawUrl) {
104
104
  let parsed;
@@ -106,8 +106,7 @@ export function assertValidEndpointUrl(rawUrl) {
106
106
  parsed = new URL(rawUrl);
107
107
  }
108
108
  catch {
109
- throw localValidationError('endpoint-url', `"${rawUrl}" is not a valid URL — provide an http(s) URL (e.g. https://api.testsprite.com) ` +
110
- `via --endpoint-url, TESTSPRITE_API_URL, or the credentials file`, undefined, 'field');
109
+ throw localValidationError('endpoint-url', `"${rawUrl}" is not a valid URL — provide an http(s) URL (e.g. https://api.testsprite.com)`, undefined, 'field');
111
110
  }
112
111
  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
113
112
  throw localValidationError('endpoint-url', `scheme "${parsed.protocol.replace(/:$/, '')}" is not supported — use http or https ` +
@@ -5,6 +5,10 @@ import type { PlanEnvironment } from './environment.js';
5
5
  /** The longest a follow request may be held by the server, in seconds. */
6
6
  export declare const MAX_WAIT_SECONDS = 25;
7
7
  export interface ConversationApi {
8
+ /** The project's name, for saying which project a command took from the folder. */
9
+ project(projectId: string): Promise<{
10
+ name: string;
11
+ }>;
8
12
  environments(projectId: string): Promise<PlanEnvironment[]>;
9
13
  start(projectId: string, options: {
10
14
  model?: string;
@@ -9,6 +9,7 @@ const one = (projectId, id) => `${base(projectId)}/${encodeURIComponent(id)}`;
9
9
  const idempotent = () => ({ 'idempotency-key': randomUUID() });
10
10
  export function conversationApi(client, fetchImpl, storage) {
11
11
  return {
12
+ project: projectId => client.get(`/projects/${encodeURIComponent(projectId)}`),
12
13
  environments: async (projectId) => (await client.get(`/projects/${encodeURIComponent(projectId)}/env`)).environments,
13
14
  start: (projectId, { model, title }) => client.post(base(projectId), {
14
15
  body: {
@@ -3,8 +3,18 @@ export interface ContextDeps {
3
3
  /** The folder the state lives in: the repository root, else the working directory. */
4
4
  root: string;
5
5
  }
6
+ /** The project a command works on, and whether it came from this folder's state rather than the caller. */
7
+ export interface ResolvedProject {
8
+ projectId: string;
9
+ /** Neither `--project` nor `TESTSPRITE_PROJECT_ID` named it: it is the one last worked on here. */
10
+ remembered: boolean;
11
+ }
12
+ /** `--project`, else `TESTSPRITE_PROJECT_ID`, else the project last worked on in this folder. */
13
+ export declare function resolveProject(flag: string | undefined, deps: ContextDeps): ResolvedProject;
6
14
  /** `--project`, else `TESTSPRITE_PROJECT_ID`, else the project last worked on in this folder. */
7
15
  export declare function resolveProjectId(flag: string | undefined, deps: ContextDeps): string;
16
+ /** Make a project the one this folder works on, as `project create` does for the project it makes. */
17
+ export declare function rememberProject(root: string, projectId: string): void;
8
18
  /** Remember the project and its conversation for the next command run in this folder. */
9
19
  export declare function rememberConversation(root: string, projectId: string, conversationId: string): void;
10
20
  /**
@@ -23,15 +23,27 @@ function writeState(root, state) {
23
23
  writeFileSync(join(dir, STATE_FILE), `${JSON.stringify(state, null, 2)}\n`);
24
24
  }
25
25
  /** `--project`, else `TESTSPRITE_PROJECT_ID`, else the project last worked on in this folder. */
26
- export function resolveProjectId(flag, deps) {
27
- const projectId = flag?.trim() ||
28
- (deps.env ?? process.env).TESTSPRITE_PROJECT_ID?.trim() ||
29
- readState(deps.root).projectId;
26
+ export function resolveProject(flag, deps) {
27
+ const given = flag?.trim() || (deps.env ?? process.env).TESTSPRITE_PROJECT_ID?.trim();
28
+ if (given)
29
+ return { projectId: given, remembered: false };
30
+ const projectId = readState(deps.root).projectId;
30
31
  if (!projectId) {
31
32
  throw new CLIError('No project. Pass --project <id> (see `testsprite project list`) or set TESTSPRITE_PROJECT_ID; ' +
32
33
  'this folder remembers it after that.', 5, 'VALIDATION_ERROR');
33
34
  }
34
- return projectId;
35
+ return { projectId, remembered: true };
36
+ }
37
+ /** `--project`, else `TESTSPRITE_PROJECT_ID`, else the project last worked on in this folder. */
38
+ export function resolveProjectId(flag, deps) {
39
+ return resolveProject(flag, deps).projectId;
40
+ }
41
+ /** Make a project the one this folder works on, as `project create` does for the project it makes. */
42
+ export function rememberProject(root, projectId) {
43
+ const state = readState(root);
44
+ if (state.projectId === projectId)
45
+ return;
46
+ writeState(root, { ...state, projectId });
35
47
  }
36
48
  /** Remember the project and its conversation for the next command run in this folder. */
37
49
  export function rememberConversation(root, projectId, conversationId) {
@@ -9,7 +9,8 @@ export interface PlanEnvironment {
9
9
  }
10
10
  /**
11
11
  * What the caller should know before the agent starts on this environment:
12
- * what its browser can't reach and what only a person can do there. Said up
13
- * front so nobody learns it from a run that went half way.
12
+ * what only a person can do there. Said up front so nobody learns it from a
13
+ * run that went half way. An environment on this machine needs no note: the
14
+ * agent asks for the tunnel itself when it finds none.
14
15
  */
15
16
  export declare function environmentNotes(environment: PlanEnvironment): string[];
@@ -1,27 +1,15 @@
1
- import { loopbackHost } from '../local-target.js';
2
1
  import { terminalSafeLine } from '../terminal-text.js';
3
2
  /**
4
3
  * What the caller should know before the agent starts on this environment:
5
- * what its browser can't reach and what only a person can do there. Said up
6
- * front so nobody learns it from a run that went half way.
4
+ * what only a person can do there. Said up front so nobody learns it from a
5
+ * run that went half way. An environment on this machine needs no note: the
6
+ * agent asks for the tunnel itself when it finds none.
7
7
  */
8
8
  export function environmentNotes(environment) {
9
- // Each note is one line naming the server's name and URL: each stays on it,
10
- // so neither can start a line or take the words between them.
9
+ // Each note is one line naming the server's name: it stays on the line, so
10
+ // it can neither start one nor take the words after it.
11
11
  const name = terminalSafeLine(environment.name);
12
12
  const notes = [];
13
- let local = null;
14
- try {
15
- const url = new URL(environment.url);
16
- if (loopbackHost(url.hostname) !== undefined)
17
- local = { port: url.port };
18
- }
19
- catch {
20
- local = null;
21
- }
22
- if (local) {
23
- notes.push(`The "${name}" environment is on this machine (${terminalSafeLine(environment.url)}), which the agent's browser can't open: it works from your change and the project's files. Run what it saves here with \`testsprite run <test-id...> --local ${local.port || '<port>'}\`.`);
24
- }
25
13
  if (environment.authMode === 'manual') {
26
14
  notes.push(`The "${name}" environment signs in by hand (single sign-on). The agent can't reuse that sign-in yet: it covers what it reaches without signing in, and a person can sign in once in the conversation's live browser.`);
27
15
  }
@@ -179,6 +179,9 @@ export function renderProposal(proposal, showSteps) {
179
179
  if (!showSteps && [...plan.added, ...plan.changed].some(t => t.steps?.length)) {
180
180
  lines.push('', ' Add --steps to see each test step by step.');
181
181
  }
182
+ if (plan.environment) {
183
+ lines.push('', ` Explored on the ${terminalSafeLine(plan.environment.name)} environment${plan.environment.isDefault ? " (the project's default)" : ''}.`);
184
+ }
182
185
  }
183
186
  for (const change of proposal.changes ?? []) {
184
187
  lines.push(` ${terminalSafeLine(change.op).padEnd(7)} ${terminalSafeLine(change.name)}${change.detail ? ` ${terminalSafeLine(change.detail)}` : ''}`);
@@ -61,6 +61,8 @@ export interface Proposal {
61
61
  removed: Array<{
62
62
  ref: string;
63
63
  }>;
64
+ /** The environment the agent explored these tests on, when it named one: where to run them. */
65
+ environment?: RunEnvironment;
64
66
  };
65
67
  changes?: Array<{
66
68
  op: string;
@@ -3,7 +3,8 @@
3
3
  * the guards on where files land (the `--out` directory the user chose, and
4
4
  * every name composed under it).
5
5
  */
6
- import type { FetchImpl } from './http.js';
6
+ import { Writable } from 'node:stream';
7
+ import { type FetchImpl } from './http.js';
7
8
  import { type ShutdownHandle } from './interrupt.js';
8
9
  /** Max fetch attempts for each presigned URL (initial + retries). */
9
10
  export declare const STREAM_URL_MAX_RETRIES = 3;
@@ -63,9 +64,37 @@ export declare function assertNoEscape(baseDir: string, segment: string): string
63
64
  * retried up to STREAM_URL_MAX_RETRIES times with a fixed delay, well
64
65
  * inside a signed link's lifetime. A file whose last attempt broke off
65
66
  * mid-stream is left as far as it got: the caller removes it.
67
+ *
68
+ * Only an `https` link to a host that is not a literal local or private
69
+ * address is fetched; any other link is refused before a request is made.
70
+ *
71
+ * `stallTimeoutMs` bounds each wait for data: for the response to start, and
72
+ * between two chunks of its body. It does not bound the whole download, so a
73
+ * large file that keeps arriving is never cut off. A stalled download is not
74
+ * retried.
66
75
  */
67
76
  export declare function streamUrlToFile(url: string, filePath: string, fetchImpl: FetchImpl, deps?: {
68
77
  sleep?: (ms: number) => Promise<void>;
69
78
  shutdownSignal?: AbortSignal;
70
79
  shutdown?: Pick<ShutdownHandle, 'runCriticalOperation'>;
80
+ stallTimeoutMs?: number;
71
81
  }): Promise<void>;
82
+ /**
83
+ * Why a link is not downloaded, or `undefined` when it may be. The host is
84
+ * judged as written: a name is not resolved, so a proxy or a private storage
85
+ * endpoint reached by name keeps working.
86
+ */
87
+ export declare function refusedDownloadUrl(url: string): string | undefined;
88
+ /** One attempt's stall clock: `signal` aborts when `arm` is not called again in time. */
89
+ export declare function stallClock(stallTimeoutMs: number): {
90
+ signal: AbortSignal;
91
+ arm: () => void;
92
+ stop: () => void;
93
+ };
94
+ /**
95
+ * A sink that writes each chunk to `file` with the stall clock stopped, and
96
+ * starts it again once the write is done: the clock runs only while the next
97
+ * chunk is awaited, so time the disk takes is not time the link was silent.
98
+ * A failed write is the stream's error, and no further write is started.
99
+ */
100
+ export declare function stallTimedSink(file: Writable, clock: ReturnType<typeof stallClock>): Writable;
@@ -5,11 +5,14 @@
5
5
  */
6
6
  import { createWriteStream } from 'node:fs';
7
7
  import { mkdir, rm, stat, writeFile } from 'node:fs/promises';
8
+ import { Readable, Writable } from 'node:stream';
8
9
  import { pipeline } from 'node:stream/promises';
9
10
  import { dirname, isAbsolute, relative, resolve } from 'node:path';
10
11
  import { ApiError, InterruptError, TransportError, localValidationError } from './errors.js';
12
+ import { REQUEST_TIMEOUT_DEFAULT_MS } from './http.js';
11
13
  import { globalShutdown } from './interrupt.js';
12
14
  import { defaultSleep, sleepUnlessInterrupted } from './poll-support.js';
15
+ import { disallowedIpReason } from './target-url.js';
13
16
  /** Max fetch attempts for each presigned URL (initial + retries). */
14
17
  export const STREAM_URL_MAX_RETRIES = 3;
15
18
  /** Delay between retries for transient transport failures (ms). */
@@ -159,93 +162,186 @@ export function assertNoEscape(baseDir, segment) {
159
162
  * retried up to STREAM_URL_MAX_RETRIES times with a fixed delay, well
160
163
  * inside a signed link's lifetime. A file whose last attempt broke off
161
164
  * mid-stream is left as far as it got: the caller removes it.
165
+ *
166
+ * Only an `https` link to a host that is not a literal local or private
167
+ * address is fetched; any other link is refused before a request is made.
168
+ *
169
+ * `stallTimeoutMs` bounds each wait for data: for the response to start, and
170
+ * between two chunks of its body. It does not bound the whole download, so a
171
+ * large file that keeps arriving is never cut off. A stalled download is not
172
+ * retried.
162
173
  */
163
174
  export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
175
+ const refusal = refusedDownloadUrl(url);
176
+ if (refusal !== undefined) {
177
+ throw ApiError.fromEnvelope({
178
+ error: {
179
+ code: 'UNAVAILABLE',
180
+ message: `Refused to download ${redactArtifactUrlForDetails(url)}: ${refusal}.`,
181
+ nextAction: 'Evidence is downloaded only from https storage links. If this result came from the TestSprite API, report it.',
182
+ requestId: 'local',
183
+ details: { artifactUrl: redactArtifactUrlForDetails(url) },
184
+ },
185
+ });
186
+ }
164
187
  const shutdownSignal = deps?.shutdownSignal ?? globalShutdown.signal;
165
188
  const shutdown = deps?.shutdown ?? globalShutdown;
166
- return shutdown.runCriticalOperation(() => streamUrlToFileTracked(url, filePath, fetchImpl, deps?.sleep ?? defaultSleep, shutdownSignal));
189
+ return shutdown.runCriticalOperation(() => streamUrlToFileTracked(url, filePath, fetchImpl, deps?.sleep ?? defaultSleep, shutdownSignal, deps?.stallTimeoutMs ?? REQUEST_TIMEOUT_DEFAULT_MS));
190
+ }
191
+ /**
192
+ * Why a link is not downloaded, or `undefined` when it may be. The host is
193
+ * judged as written: a name is not resolved, so a proxy or a private storage
194
+ * endpoint reached by name keeps working.
195
+ */
196
+ export function refusedDownloadUrl(url) {
197
+ let parsed;
198
+ try {
199
+ parsed = new URL(url);
200
+ }
201
+ catch {
202
+ return 'it is not a URL';
203
+ }
204
+ if (parsed.protocol !== 'https:')
205
+ return 'only https links are downloaded';
206
+ const host = parsed.hostname.toLowerCase().replace(/\.$/, '');
207
+ const local = host === 'localhost' || host.endsWith('.localhost') || disallowedIpReason(host) !== undefined;
208
+ return local ? 'it points at a local or private address' : undefined;
167
209
  }
168
- async function streamUrlToFileTracked(url, filePath, fetchImpl, sleepFn, shutdownSignal) {
210
+ /** A download that stopped receiving data. Never retried. */
211
+ class DownloadStalledError extends TransportError {
212
+ constructor(artifactUrl, stallTimeoutMs) {
213
+ super(`Download of ${artifactUrl} stalled: no data for ${Math.round(stallTimeoutMs / 1000)}s.`, 'local', {
214
+ nextAction: 'Re-run the command. Use --request-timeout <seconds> or TESTSPRITE_REQUEST_TIMEOUT_MS to wait longer for a slow link.',
215
+ });
216
+ }
217
+ }
218
+ /** One attempt's stall clock: `signal` aborts when `arm` is not called again in time. */
219
+ export function stallClock(stallTimeoutMs) {
220
+ const stalled = new AbortController();
221
+ let timer;
222
+ const stop = () => clearTimeout(timer);
223
+ const arm = () => {
224
+ stop();
225
+ timer = setTimeout(() => stalled.abort(), stallTimeoutMs);
226
+ };
227
+ return { signal: stalled.signal, arm, stop };
228
+ }
229
+ async function streamUrlToFileTracked(url, filePath, fetchImpl, sleepFn, shutdownSignal, stallTimeoutMs) {
169
230
  const artifactUrl = redactArtifactUrlForDetails(url);
170
231
  for (let attempt = 1; attempt <= STREAM_URL_MAX_RETRIES; attempt++) {
171
232
  if (shutdownSignal.aborted)
172
233
  throw shutdownSignal.reason;
173
- let response;
234
+ const clock = stallClock(stallTimeoutMs);
174
235
  try {
175
- response = await fetchImpl(url, { redirect: 'error', signal: shutdownSignal });
236
+ const done = await streamAttempt(url, filePath, fetchImpl, sleepFn, shutdownSignal, clock, artifactUrl, attempt);
237
+ if (done)
238
+ return;
176
239
  }
177
240
  catch (err) {
178
- if (err instanceof InterruptError || shutdownSignal.aborted)
179
- throw shutdownSignal.reason ?? err;
180
- const message = err instanceof Error ? err.message : String(err);
181
- if (attempt < STREAM_URL_MAX_RETRIES) {
182
- await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
183
- continue;
241
+ if (clock.signal.aborted && !shutdownSignal.aborted) {
242
+ throw new DownloadStalledError(artifactUrl, stallTimeoutMs);
184
243
  }
185
- throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
244
+ throw err;
186
245
  }
187
- if (shutdownSignal.aborted)
188
- throw shutdownSignal.reason;
189
- if (!response.ok) {
190
- // Non-2xx: the URL itself is bad (expired, unauthorized, not found).
191
- // Retrying the same URL won't help — surface immediately.
192
- throw ApiError.fromEnvelope({
193
- error: {
194
- code: 'UNAVAILABLE',
195
- message: `Failed to download presigned URL (HTTP ${response.status}).`,
196
- nextAction: 'Signed links expire. Re-run `testsprite result get <result-id> --out <dir>`: each read signs new ones.',
197
- requestId: 'local',
198
- details: { status: response.status, artifactUrl },
199
- },
200
- });
246
+ finally {
247
+ clock.stop();
201
248
  }
202
- if (!response.body) {
203
- // Some test runtimes / fetch polyfills don't expose `body` as a
204
- // ReadableStream. Fall back to a buffered write — same correctness,
205
- // just no streaming benefit. Even a multi-MB video buffers fully in
206
- // a tolerable amount of memory.
207
- try {
208
- const buffer = Buffer.from(await response.arrayBuffer());
209
- // eslint-disable-next-line security/detect-non-literal-fs-filename -- a path its caller composed under the --out directory.
210
- await writeFile(filePath, buffer);
211
- if (shutdownSignal.aborted) {
212
- // eslint-disable-next-line security/detect-non-literal-fs-filename -- the partial file this download just wrote.
213
- await rm(filePath, { force: true }).catch(() => undefined);
214
- throw shutdownSignal.reason;
215
- }
216
- return;
217
- }
218
- catch (err) {
219
- if (err instanceof InterruptError || shutdownSignal.aborted) {
220
- // eslint-disable-next-line security/detect-non-literal-fs-filename -- the partial file this download just wrote.
221
- await rm(filePath, { force: true }).catch(() => undefined);
222
- throw shutdownSignal.reason ?? err;
223
- }
224
- const message = err instanceof Error ? err.message : String(err);
225
- if (attempt < STREAM_URL_MAX_RETRIES) {
226
- await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
227
- continue;
228
- }
229
- throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
230
- }
249
+ }
250
+ }
251
+ /**
252
+ * A sink that writes each chunk to `file` with the stall clock stopped, and
253
+ * starts it again once the write is done: the clock runs only while the next
254
+ * chunk is awaited, so time the disk takes is not time the link was silent.
255
+ * A failed write is the stream's error, and no further write is started.
256
+ */
257
+ export function stallTimedSink(file, clock) {
258
+ const sink = new Writable({
259
+ write(chunk, _encoding, callback) {
260
+ clock.stop();
261
+ file.write(chunk, err => {
262
+ if (!err)
263
+ clock.arm();
264
+ callback(err);
265
+ });
266
+ },
267
+ final(callback) {
268
+ clock.stop();
269
+ file.end(callback);
270
+ },
271
+ destroy(err, callback) {
272
+ clock.stop();
273
+ file.destroy();
274
+ callback(err);
275
+ },
276
+ });
277
+ // A failure outside a write (the file could not be opened) ends the download too.
278
+ file.on('error', err => sink.destroy(err));
279
+ return sink;
280
+ }
281
+ /** `work`, unless `stalled` aborts first. */
282
+ function orStalled(work, stalled) {
283
+ return new Promise((resolve, reject) => {
284
+ const onStall = () => reject(new Error('stalled'));
285
+ stalled.addEventListener('abort', onStall, { once: true });
286
+ work.then(resolve, reject).finally(() => stalled.removeEventListener('abort', onStall));
287
+ });
288
+ }
289
+ /** One attempt: true when the file is written, false when the next attempt is due. */
290
+ async function streamAttempt(url, filePath, fetchImpl, sleepFn, shutdownSignal, clock, artifactUrl, attempt) {
291
+ let response;
292
+ clock.arm();
293
+ try {
294
+ response = await fetchImpl(url, {
295
+ redirect: 'error',
296
+ signal: AbortSignal.any([shutdownSignal, clock.signal]),
297
+ });
298
+ }
299
+ catch (err) {
300
+ if (err instanceof InterruptError || shutdownSignal.aborted)
301
+ throw shutdownSignal.reason ?? err;
302
+ if (clock.signal.aborted)
303
+ throw err;
304
+ const message = err instanceof Error ? err.message : String(err);
305
+ if (attempt < STREAM_URL_MAX_RETRIES) {
306
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
307
+ return false;
231
308
  }
232
- // eslint-disable-next-line security/detect-non-literal-fs-filename -- the directory of a file under the --out directory the user chose.
233
- await mkdir(dirname(filePath), { recursive: true });
234
- // `response.body` is a Web ReadableStream. Node's `pipeline` accepts
235
- // it via `Readable.fromWeb` (Node >= 18). Wrap in a try so any error
236
- // from the stream propagates as a TransportError, preserving the
237
- // exit-code contract. `pipeline` destroys both streams on error, so
238
- // a new WriteStream on retry starts clean.
239
- // eslint-disable-next-line security/detect-non-literal-fs-filename -- a path its caller composed under the --out directory.
240
- const fileSink = createWriteStream(filePath);
309
+ throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
310
+ }
311
+ // The response has started: that wait is over, and the body's waits are its own.
312
+ clock.stop();
313
+ if (shutdownSignal.aborted)
314
+ throw shutdownSignal.reason;
315
+ if (!response.ok) {
316
+ // Non-2xx: the URL itself is bad (expired, unauthorized, not found).
317
+ // Retrying the same URL won't help — surface immediately.
318
+ throw ApiError.fromEnvelope({
319
+ error: {
320
+ code: 'UNAVAILABLE',
321
+ message: `Failed to download presigned URL (HTTP ${response.status}).`,
322
+ nextAction: 'Signed links expire. Re-run `testsprite result get <result-id> --out <dir>`: each read signs new ones.',
323
+ requestId: 'local',
324
+ details: { status: response.status, artifactUrl },
325
+ },
326
+ });
327
+ }
328
+ if (!response.body) {
329
+ // Some test runtimes / fetch polyfills don't expose `body` as a
330
+ // ReadableStream. Fall back to a buffered write — same correctness,
331
+ // just no streaming benefit. Even a multi-MB video buffers fully in
332
+ // a tolerable amount of memory.
241
333
  try {
242
- const webBody = response.body;
243
- const { Readable } = await import('node:stream');
244
- const nodeStream = Readable.fromWeb(webBody);
245
- await pipeline(nodeStream, fileSink);
246
- if (shutdownSignal.aborted)
334
+ clock.arm();
335
+ const buffer = Buffer.from(await orStalled(response.arrayBuffer(), clock.signal));
336
+ clock.stop();
337
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- a path its caller composed under the --out directory.
338
+ await writeFile(filePath, buffer);
339
+ if (shutdownSignal.aborted) {
340
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the partial file this download just wrote.
341
+ await rm(filePath, { force: true }).catch(() => undefined);
247
342
  throw shutdownSignal.reason;
248
- return;
343
+ }
344
+ return true;
249
345
  }
250
346
  catch (err) {
251
347
  if (err instanceof InterruptError || shutdownSignal.aborted) {
@@ -253,18 +349,56 @@ async function streamUrlToFileTracked(url, filePath, fetchImpl, sleepFn, shutdow
253
349
  await rm(filePath, { force: true }).catch(() => undefined);
254
350
  throw shutdownSignal.reason ?? err;
255
351
  }
352
+ if (clock.signal.aborted)
353
+ throw err;
256
354
  const message = err instanceof Error ? err.message : String(err);
257
355
  if (attempt < STREAM_URL_MAX_RETRIES) {
258
356
  await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
259
- continue;
357
+ return false;
260
358
  }
261
- throw new TransportError(`Failed mid-download of ${artifactUrl}: ${message}`);
359
+ throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
262
360
  }
263
361
  }
362
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the directory of a file under the --out directory the user chose.
363
+ await mkdir(dirname(filePath), { recursive: true });
364
+ // `response.body` is a Web ReadableStream. Node's `pipeline` accepts
365
+ // it via `Readable.fromWeb` (Node >= 18). Wrap in a try so any error
366
+ // from the stream propagates as a TransportError, preserving the
367
+ // exit-code contract. `pipeline` destroys both streams on error, so
368
+ // a new WriteStream on retry starts clean.
369
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- a path its caller composed under the --out directory.
370
+ const fileSink = createWriteStream(filePath);
371
+ try {
372
+ const webBody = response.body;
373
+ clock.arm();
374
+ await pipeline(Readable.fromWeb(webBody), stallTimedSink(fileSink, clock));
375
+ if (shutdownSignal.aborted)
376
+ throw shutdownSignal.reason;
377
+ return true;
378
+ }
379
+ catch (err) {
380
+ if (err instanceof InterruptError || shutdownSignal.aborted) {
381
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the partial file this download just wrote.
382
+ await rm(filePath, { force: true }).catch(() => undefined);
383
+ throw shutdownSignal.reason ?? err;
384
+ }
385
+ if (clock.signal.aborted)
386
+ throw err;
387
+ const message = err instanceof Error ? err.message : String(err);
388
+ if (attempt < STREAM_URL_MAX_RETRIES) {
389
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
390
+ return false;
391
+ }
392
+ throw new TransportError(`Failed mid-download of ${artifactUrl}: ${message}`);
393
+ }
264
394
  }
265
395
  function redactArtifactUrlForDetails(url) {
266
396
  try {
267
397
  const parsed = new URL(url);
398
+ // A `data:` link is its own content, and a `file:` one a local path.
399
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
400
+ return `<${parsed.protocol.slice(0, -1)} link>`;
401
+ }
268
402
  return `${parsed.origin}${parsed.pathname}`;
269
403
  }
270
404
  catch {
@@ -6,7 +6,7 @@ import type { HttpClient } from './http.js';
6
6
  import type { RunWaitSnapshot } from './run-wait.js';
7
7
  import type { CliTestListRunResponse } from './testlist.types.js';
8
8
  import { ApiError } from './errors.js';
9
- import { type LoopbackHost, type StoredLocalTarget } from './local-target.js';
9
+ import { type StoredLocalTarget } from './local-target.js';
10
10
  export interface RunTargetTest {
11
11
  type: 'frontend' | 'backend';
12
12
  projectId: string;
@@ -21,6 +21,8 @@ export interface ResolvedRunTarget extends StoredLocalTarget {
21
21
  targetUrl: string;
22
22
  automatic: boolean;
23
23
  environmentName?: string;
24
+ /** Whether that environment is the project's default, when the server says. */
25
+ environmentIsDefault?: boolean;
24
26
  }
25
27
  export declare const ENVIRONMENT_PREFLIGHT_TIMEOUT_MS = 5000;
26
28
  /** Advisory-only reads must not inherit the run's long wait or retry budget. */
@@ -39,8 +41,6 @@ export declare function resolveEnvironmentRunTarget(args: {
39
41
  dryRun?: boolean;
40
42
  projectId?: string;
41
43
  environment?: string;
42
- localPort?: number;
43
- localHost?: LoopbackHost;
44
44
  targetUrl?: string;
45
45
  tunnelClientId?: string;
46
46
  noWait?: boolean;