@testsprite/testsprite-cli 0.10.0 → 0.11.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 (42) hide show
  1. package/README.md +25 -2
  2. package/dist/commands/auth.d.ts +5 -1
  3. package/dist/commands/auth.js +17 -5
  4. package/dist/commands/init.d.ts +6 -1
  5. package/dist/commands/init.js +13 -5
  6. package/dist/commands/project.d.ts +9 -0
  7. package/dist/commands/project.js +89 -18
  8. package/dist/commands/test.d.ts +14 -2
  9. package/dist/commands/test.js +141 -33
  10. package/dist/commands/tunnel.d.ts +2 -2
  11. package/dist/commands/tunnel.js +139 -31
  12. package/dist/index.js +29 -11
  13. package/dist/lib/client-factory.d.ts +4 -1
  14. package/dist/lib/client-factory.js +12 -4
  15. package/dist/lib/credentials.d.ts +4 -0
  16. package/dist/lib/credentials.js +43 -4
  17. package/dist/lib/http.d.ts +14 -2
  18. package/dist/lib/http.js +38 -6
  19. package/dist/lib/response-schemas.d.ts +5 -2
  20. package/dist/lib/response-schemas.js +21 -1
  21. package/dist/lib/runs.types.d.ts +11 -0
  22. package/dist/lib/target-url.d.ts +1 -1
  23. package/dist/lib/target-url.js +4 -0
  24. package/dist/lib/telemetry.d.ts +6 -2
  25. package/dist/lib/telemetry.js +12 -0
  26. package/dist/lib/tunnel-session.d.ts +13 -2
  27. package/dist/lib/tunnel-session.js +92 -23
  28. package/dist/lib/tunnel.types.d.ts +3 -1
  29. package/dist/vendor/tunnel-client/client.d.ts +11 -0
  30. package/dist/vendor/tunnel-client/client.js +383 -56
  31. package/dist/vendor/tunnel-client/config.d.ts +11 -3
  32. package/dist/vendor/tunnel-client/config.js +11 -3
  33. package/dist/vendor/tunnel-client/types.d.ts +26 -1
  34. package/dist/vendor/tunnel-client/types.js +1 -0
  35. package/dist/vendor/tunnel-client/ws-compat.d.ts +3 -2
  36. package/dist/vendor/tunnel-client/ws-compat.js +3 -2
  37. package/dist/version.d.ts +1 -1
  38. package/dist/version.js +1 -1
  39. package/package.json +2 -1
  40. package/skills/testsprite-onboard.skill.md +74 -59
  41. package/skills/testsprite-verify.codex.md +82 -97
  42. package/skills/testsprite-verify.skill.md +62 -15
package/README.md CHANGED
@@ -116,7 +116,7 @@ Get this exact skeleton without hand-copying it (and without the risk of it drif
116
116
 
117
117
  > The `$schema` URL above is pinned to the CLI version that generated this doc (`v0.4.0`) — `--plan-template`'s live output always pins to **your installed version** instead, which is what actually resolves. If you're reading this on a later release, run the command yourself rather than trusting this snippet verbatim.
118
118
 
119
- **Don't want to write the first tests yourself?** Ask TestSprite to propose them. `testsprite test plan generate --project <id>` explores your app (or reads the API spec you uploaded with `project docs upload`), drafts test cases, and stages them for review — nothing is written to your disk. You read the printed table and keep what you want:
119
+ **Don't want to write the first tests yourself?** For a deployed target, ask TestSprite to propose them. Local projects use the authored-plan flow below. `testsprite test plan generate --project <id>` explores your app (or reads the API spec you uploaded with `project docs upload`), drafts test cases, and stages them for review — nothing is written to your disk. You read the printed table and keep what you want:
120
120
 
121
121
  ```bash
122
122
  testsprite test plan generate --project proj_8f0f6 # stages proposals for review
@@ -128,6 +128,29 @@ It only runs what the project is still missing, so a second call picks up where
128
128
 
129
129
  Prefer to configure each step by hand (or learn the surface offline with `--dry-run` first)? See [Manual setup](./DOCUMENTATION.md#manual-setup) and [Install & verify](./DOCUMENTATION.md#install--verify).
130
130
 
131
+ ## Testing an app on your machine (--local)
132
+
133
+ Frontend tests can reach your running app through a TestSprite tunnel, including on the Free plan (ordinary run credits apply).
134
+ Use an API key with `run:tunnel`: keys minted before that scope existed need to be replaced; the CLI names the missing scope.
135
+
136
+ ```bash
137
+ testsprite project create --type frontend --name "My local app" --local 3000
138
+ testsprite test create --plan-from ./checkout.plan.json --project <project-id>
139
+ testsprite test run <test-id> --local 3000 # per-run tunnel; waits up to 1200 seconds
140
+ # Or keep one tunnel open in terminal A (no port argument)
141
+ testsprite tunnel start --ttl 3600
142
+ # Terminal B: borrow the clientId printed above; keep terminal A running
143
+ testsprite test run <test-id> --local 3000 --tunnel-client <client-uuid>
144
+ ```
145
+
146
+ Run one test per invocation; parallel invocations are fine (5 live tunnel bindings per user); `--all --local` is refused.
147
+ A second `tunnel start` or process using the same credential takes over, and the first exits **10**.
148
+ The examples use `127.0.0.1`. For another loopback listener, pass the same `--local-host localhost` or `--local-host ::1` to project creation and every follow-up run. The selected host is stored in the project URL (`::1` becomes `http://[::1]:<port>`); `project get/list` exposes `originMode: 'local'` in JSON and shows `(Local)` in text output.
149
+ The control plane is WebSocket over TLS (`wss://control.tun.testsprite.com/ws`). The data plane, which carries the tunnel secret and proxied traffic, uses TLS at `data.tun.testsprite.com:443` and verifies the certificate with Node's default trust store: its bundled Mozilla roots, plus certificates supplied through `NODE_EXTRA_CA_CERTS` and the system CAs when Node is started with `--use-system-ca`. Node 20 is supported without losing `NODE_EXTRA_CA_CERTS`. Verification cannot be disabled, and the CLI never falls back from TLS to plaintext. On a network that re-signs TLS, export your organisation's root CA to a PEM file and set `NODE_EXTRA_CA_CERTS=/path/to/ca.pem` before running `testsprite`. Plaintext connects and TLS handshakes each time out after 10 seconds. The first failed attempt starts a **60-second** retry episode; writing `TunnelHello` is not enough to reset it. The episode ends only after the first inbound tunnel stream or after the socket remains open for 5 seconds following the hello. A real deadline timer stays armed across retries and destroys an in-flight socket when it expires. After that, an owned `test run --local` run is cancelled and refunded and the command exits **10**; `tunnel start` exits **10**. If a self-hosted or older TestSprite server does not advertise a TLS endpoint, the CLI prints a one-time warning and uses legacy plaintext port **7400** under the same timeout and retry rules. `tunnel start` prints `transport: tls` or `transport: plaintext`.
150
+ An owned tunnel's timeout or Ctrl-C cancels the run by default. A borrowed run still detaches without cancellation on Ctrl-C/SIGTERM because its owner keeps the tunnel alive; if that owner disappears while the run is active, the borrower cancels its own run and reports `cancelled`, `already finished`, or `skipped`. A run cancelled before it finishes is refunded. `--no-cancel-on-interrupt` also skips this owner-gone cancellation. Keep the early `Run <runId>` receipt on stderr and read the reported run before re-running.
151
+ Local projects skip exploration/plan generation; author plans with `test create --plan-from`. Portal runs are blocked for free until you set a public project URL.
152
+ See [the full local-testing reference](./DOCUMENTATION.md#local-frontend-testing-and-tunnels) for flags, login, billing/refunds, timeouts, and retargeting.
153
+
131
154
  ## Commands
132
155
 
133
156
  | Group | Command | What it does |
@@ -159,7 +182,7 @@ Prefer to configure each step by hand (or learn the surface offline with `--dry-
159
182
  | | `test rerun` | Replay one/many tests (FE verbatim; BE with deps); billed as a run (0.5 credits FE / 0.2 BE); `--all --project <id>` reruns all tests |
160
183
  | | `test flaky` | Replay a test several times (auto-heal off) and report a stability score |
161
184
  | | `test wait` | Block on one or more `runId`s until terminal |
162
- | | `test cancel` | Cancel one or more in-flight runs (Ctrl-C during `--wait` only detaches, `cancel` is the real stop — except a `--local` run, which Ctrl-C cancels by default) |
185
+ | | `test cancel` | Cancel one or more in-flight runs (Ctrl-C during `--wait` only detaches, `cancel` is the real stop — except an owned `--local` run, which Ctrl-C cancels by default) |
163
186
  | | `test artifact get` | Download the failure bundle for a specific `runId` |
164
187
  | **Test lists** | `testlist list` / `testlist get` | Inspect saved test lists — named, cross-project collections with per-project environment pins (V3-only) |
165
188
  | | `testlist create` / `update` / `add` / `remove` / `delete` | Manage a list and its cases; `--project-env <id>:<env>` pins environments; `delete` requires `--confirm` |
@@ -92,7 +92,11 @@ interface ConfigureOptions extends CommonOptions {
92
92
  */
93
93
  skipIfConfigured?: boolean;
94
94
  }
95
- export declare function runConfigure(opts: ConfigureOptions, deps?: AuthDeps): Promise<void>;
95
+ export interface ConfigureResult {
96
+ persisted: boolean;
97
+ source: 'env' | 'prompt' | 'profile' | 'dry-run';
98
+ }
99
+ export declare function runConfigure(opts: ConfigureOptions, deps?: AuthDeps): Promise<ConfigureResult>;
96
100
  export declare function runWhoami(opts: CommonOptions, deps?: AuthDeps): Promise<MeResponse>;
97
101
  export declare function runLogout(opts: CommonOptions, deps?: AuthDeps): Promise<void>;
98
102
  export declare function createAuthCommand(deps?: AuthDeps): Command;
@@ -3,7 +3,7 @@ import { assertValidApiKey, assertValidEndpointUrl, emitDryRunBanner, makeHttpCl
3
3
  import { ApiError, CLIError } from '../lib/errors.js';
4
4
  import { facadeBaseUrl } from '../lib/facade.js';
5
5
  import { HttpClient } from '../lib/http.js';
6
- import { defaultCredentialsPath, deleteProfile, readProfile, writeProfile, } from '../lib/credentials.js';
6
+ import { defaultCredentialsPath, deleteProfile, isCredentialsWritePermissionError, readProfile, writeProfile, } from '../lib/credentials.js';
7
7
  import { loadConfig, normalizeEnvVar } from '../lib/config.js';
8
8
  import { emitDeprecationNotice } from '../lib/deprecate.js';
9
9
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
@@ -38,7 +38,7 @@ export async function runConfigure(opts, deps = {}) {
38
38
  const d = data;
39
39
  return `Profile "${d.profile}" configured (dry-run). Endpoint: ${d.apiUrl}`;
40
40
  });
41
- return;
41
+ return { persisted: false, source: 'dry-run' };
42
42
  }
43
43
  let apiKey;
44
44
  // Read the existing profile once — used for apiUrl inheritance in both
@@ -73,7 +73,7 @@ export async function runConfigure(opts, deps = {}) {
73
73
  const d = data;
74
74
  return `Profile "${d.profile}" already configured. Endpoint: ${d.apiUrl}`;
75
75
  });
76
- return;
76
+ return { persisted: true, source: 'profile' };
77
77
  }
78
78
  const promptApi = deps.prompt ?? { secret: (q) => promptSecret(q) };
79
79
  prelude(`Configuring profile "${opts.profile}".\n`);
@@ -129,15 +129,27 @@ export async function runConfigure(opts, deps = {}) {
129
129
  // misconfigured fetchImpl). Exit 3 (auth family).
130
130
  throw new CLIError(`API key rejected by ${apiUrl}: ${message} — did you mean to set TESTSPRITE_API_URL?`, 3);
131
131
  }
132
- writeProfile(opts.profile, { apiKey, apiUrl }, { path: credentialsPath });
132
+ let persisted = true;
133
+ try {
134
+ writeProfile(opts.profile, { apiKey, apiUrl }, { path: credentialsPath });
135
+ }
136
+ catch (error) {
137
+ if (!opts.fromEnv || !isCredentialsWritePermissionError(error))
138
+ throw error;
139
+ persisted = false;
140
+ stderr(`Using TESTSPRITE_API_KEY for this session; credentials could not be saved to ${credentialsPath} (${error.code}). Set TESTSPRITE_API_KEY in every shell that runs testsprite.`);
141
+ }
133
142
  out.print({ profile: opts.profile, apiUrl, status: 'configured' }, data => {
134
143
  const d = data;
135
- return `Profile "${d.profile}" configured. Endpoint: ${d.apiUrl}`;
144
+ return persisted
145
+ ? `Profile "${d.profile}" configured. Endpoint: ${d.apiUrl}`
146
+ : `Profile "${d.profile}" configured for this session only (credentials not saved). Endpoint: ${d.apiUrl}`;
136
147
  });
137
148
  // Note: the old "run `testsprite agent install`" self-bootstrap tip was
138
149
  // removed with the setup consolidation. `runConfigure` now only runs as part
139
150
  // of `setup` (the sole credential-writing path), which installs the skill
140
151
  // itself (unless --no-agent) — so the tip would be redundant or misleading.
152
+ return { persisted, source: opts.fromEnv ? 'env' : 'prompt' };
141
153
  }
142
154
  export async function runWhoami(opts, deps = {}) {
143
155
  const out = makeOutput(opts.output, deps);
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import { Command } from 'commander';
15
15
  import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
16
- import type { AuthDeps } from './auth.js';
16
+ import type { AuthDeps, ConfigureResult } from './auth.js';
17
17
  import type { AgentFs } from './agent.js';
18
18
  import { type AgentTarget } from '../lib/agent-targets.js';
19
19
  import { type AgentDetection, type DetectAgentDeps } from '../lib/agent-detect.js';
@@ -69,6 +69,11 @@ export interface InitSummary {
69
69
  env: string;
70
70
  email?: string;
71
71
  scopes: string[];
72
+ /** Credential persistence outcome; omitted for a dry-run preview. */
73
+ credentials?: {
74
+ persisted: boolean;
75
+ source: ConfigureResult['source'] | 'flag';
76
+ };
72
77
  /**
73
78
  * Agent skill install outcome. `action` is an AGGREGATE across the installed
74
79
  * skills (setup installs {@link DEFAULT_SKILLS}); `skills` lists which skills
@@ -332,7 +332,7 @@ export async function runInit(opts, deps = {}) {
332
332
  // --api-key takes precedence over --from-env: when an explicit key is supplied,
333
333
  // force fromEnv=false so runConfigure uses the injected key (toAuthDeps wires it
334
334
  // as the prompt) instead of reading TESTSPRITE_API_KEY from the environment (codex).
335
- await runConfigure({
335
+ const configured = await runConfigure({
336
336
  ...opts,
337
337
  fromEnv: opts.apiKey ? false : opts.fromEnv,
338
338
  // --api-key always overwrites; skip only applies when no explicit key source was given.
@@ -413,10 +413,11 @@ export async function runInit(opts, deps = {}) {
413
413
  installedSkills = [...new Set(capturedInstallResults.flatMap(r => r.skills ?? []))];
414
414
  }
415
415
  catch (installErr) {
416
- // Fix 6: credentials were already saved (Step 1+2 above succeeded).
417
- // Emit a clear summary line BEFORE re-throwing so the user knows their
418
- // API key was persisted — only the agent skill step failed (Fix 6).
419
- stderrFn(`[info] credentials saved for profile "${opts.profile}"; only the agent skill install failed — ` +
416
+ // Explain the credential outcome before re-throwing the install failure.
417
+ const credentialStatus = configured.persisted
418
+ ? `credentials saved for profile "${opts.profile}"`
419
+ : 'credentials are session-only (TESTSPRITE_API_KEY; not saved)';
420
+ stderrFn(`[info] ${credentialStatus}; only the agent skill install failed — ` +
420
421
  `re-run 'testsprite agent install --target ${resolution.targets.join(',')}' after fixing the path`);
421
422
  throw installErr;
422
423
  }
@@ -441,6 +442,10 @@ export async function runInit(opts, deps = {}) {
441
442
  env: me.env,
442
443
  email: me.email,
443
444
  scopes: me.scopes,
445
+ credentials: {
446
+ persisted: configured.persisted,
447
+ source: opts.apiKey ? 'flag' : configured.source,
448
+ },
444
449
  agent: agentSummary,
445
450
  ...(agentSummary === null && agentSkippedBy ? { agentSkippedBy } : {}),
446
451
  status: 'initialized',
@@ -462,6 +467,9 @@ function renderInitText(data) {
462
467
  lines.push(` email: ${s.email}`);
463
468
  if (s.scopes.length > 0)
464
469
  lines.push(` scopes: ${s.scopes.join(', ')}`);
470
+ if (s.credentials?.persisted === false) {
471
+ lines.push(' credentials: session-only (TESTSPRITE_API_KEY; not saved)');
472
+ }
465
473
  lines.push('');
466
474
  if (s.agent) {
467
475
  const targets = s.agent.targets.length > 0 ? s.agent.targets : [s.agent.target];
@@ -2,6 +2,7 @@ import { Command } from 'commander';
2
2
  import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
3
3
  import type { FetchImpl } from '../lib/http.js';
4
4
  import { type ShutdownHandle } from '../lib/interrupt.js';
5
+ import { type LocalPortProbeDeps } from '../lib/local-target.js';
5
6
  import { type Page } from '../lib/pagination.js';
6
7
  export interface CliProject {
7
8
  id: string;
@@ -42,6 +43,8 @@ export interface CliProject {
42
43
  * (see the `project create --type backend` note in CLAUDE.md).
43
44
  */
44
45
  targetUrl?: string | null;
46
+ /** Present only when the stored project target is local to the developer machine. */
47
+ originMode?: 'local';
45
48
  /**
46
49
  * Project-level test-id attribute priority list (e.g. `['data-element',
47
50
  * 'data-testid']`). The execution engine tries these DOM attributes, in
@@ -64,6 +67,7 @@ export interface ProjectDeps {
64
67
  fetchImpl?: FetchImpl;
65
68
  stdout?: (line: string) => void;
66
69
  stderr?: (line: string) => void;
70
+ localPortProbeDeps?: LocalPortProbeDeps;
67
71
  /** Graceful-detach coordinator (DEV-331); tests inject their own. */
68
72
  shutdown?: ShutdownHandle;
69
73
  }
@@ -84,6 +88,7 @@ export interface CliCreateProjectRequest {
84
88
  type: 'frontend' | 'backend';
85
89
  name: string;
86
90
  targetUrl?: string;
91
+ originMode?: 'local';
87
92
  username?: string;
88
93
  password?: string;
89
94
  instruction?: string;
@@ -115,6 +120,7 @@ export interface CliCreateProjectResponse {
115
120
  /** Absent-safe: not guaranteed on every backend response. */
116
121
  updatedAt?: string;
117
122
  targetUrl?: string;
123
+ originMode?: 'local';
118
124
  }
119
125
  /** Resolve the created project's id regardless of which field name the backend used. */
120
126
  export declare function resolveCreatedProjectId(r: CliCreateProjectResponse): string | undefined;
@@ -122,6 +128,9 @@ interface CreateOptions extends CommonOptions {
122
128
  type: 'frontend' | 'backend';
123
129
  name: string;
124
130
  targetUrl?: string;
131
+ local?: string;
132
+ localHost?: string;
133
+ skipPreflight?: boolean;
125
134
  description?: string;
126
135
  testIdAttributes?: string[];
127
136
  username?: string;
@@ -4,8 +4,9 @@ import { basename, extname } from 'node:path';
4
4
  import { Readable } from 'node:stream';
5
5
  import { Command } from 'commander';
6
6
  import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
7
- import { ApiError, InterruptError, RequestTimeoutError } from '../lib/errors.js';
7
+ import { ApiError, InterruptError, RequestTimeoutError, localValidationError as flagValidationError, } from '../lib/errors.js';
8
8
  import { globalShutdown } from '../lib/interrupt.js';
9
+ import { buildLocalTargetUrl, DEFAULT_LOCAL_HOST, normalizeLocalHost, parseLocalPort, probeLocalPort, } from '../lib/local-target.js';
9
10
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
10
11
  import { readSecretFileGuarded } from '../lib/secret-file.js';
11
12
  import { assertNotLocal } from '../lib/target-url.js';
@@ -84,6 +85,17 @@ export async function runGet(opts, deps = {}) {
84
85
  export function resolveCreatedProjectId(r) {
85
86
  return r.projectId ?? r.id;
86
87
  }
88
+ function normalizeProjectLocalHost(raw) {
89
+ try {
90
+ return normalizeLocalHost(raw);
91
+ }
92
+ catch (err) {
93
+ if (err instanceof ApiError && typeof err.details?.reason === 'string') {
94
+ throw flagValidationError('local-host', err.details.reason.replace('--target-url', '--url'), err.details.accepted);
95
+ }
96
+ throw err;
97
+ }
98
+ }
87
99
  export async function runCreate(opts, deps = {}) {
88
100
  const out = makeOutput(opts.output, deps);
89
101
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
@@ -109,16 +121,34 @@ export async function runCreate(opts, deps = {}) {
109
121
  if (opts.description !== undefined) {
110
122
  throw localValidationError('--description is not supported for projects; omit it (test-level descriptions are set on `test create`)');
111
123
  }
124
+ if (opts.local !== undefined && opts.targetUrl !== undefined) {
125
+ throw localValidationError('--local and --url are mutually exclusive');
126
+ }
127
+ if (opts.local !== undefined && opts.type !== 'frontend') {
128
+ throw localValidationError('--local projects are frontend-only');
129
+ }
130
+ if (opts.localHost !== undefined && opts.local === undefined) {
131
+ throw localValidationError('--local-host requires --local');
132
+ }
133
+ if (opts.local !== undefined && !/^\d+$/.test(opts.local)) {
134
+ throw localValidationError('--local must be a port number between 1 and 65535');
135
+ }
136
+ const localTarget = opts.local !== undefined
137
+ ? { host: normalizeProjectLocalHost(opts.localHost), port: parseLocalPort(opts.local) }
138
+ : undefined;
139
+ const targetUrl = localTarget
140
+ ? buildLocalTargetUrl(localTarget.host, localTarget.port)
141
+ : opts.targetUrl;
112
142
  // P2-7: guard --url against localhost/RFC1918/non-http(s) (same rules as
113
143
  // `test create --target-url`). Applies to both FE (required) and BE (optional).
114
144
  if (opts.targetUrl !== undefined) {
115
145
  assertNotLocal(opts.targetUrl, {
116
146
  field: 'url',
117
147
  helpCommand: 'testsprite project create',
118
- hintContext: 'bootstrap',
148
+ hintContext: 'local-project-create',
119
149
  });
120
150
  }
121
- if (opts.type === 'frontend' && !opts.targetUrl) {
151
+ if (opts.type === 'frontend' && !targetUrl) {
122
152
  throw localValidationError('--url is required for --type frontend');
123
153
  }
124
154
  if (opts.dryRun) {
@@ -141,7 +171,8 @@ export async function runCreate(opts, deps = {}) {
141
171
  id: 'p_dryrun_2026',
142
172
  type: opts.type,
143
173
  name: opts.name,
144
- targetUrl: opts.targetUrl ?? '',
174
+ targetUrl: targetUrl ?? '',
175
+ ...(localTarget ? { originMode: 'local' } : {}),
145
176
  createdFrom: 'cli',
146
177
  createdAt: '2026-05-16T00:00:00.000Z',
147
178
  updatedAt: '2026-05-16T00:00:00.000Z',
@@ -149,6 +180,26 @@ export async function runCreate(opts, deps = {}) {
149
180
  out.print(sample, data => renderCreateProjectText(data));
150
181
  return sample;
151
182
  }
183
+ if (localTarget && !opts.skipPreflight) {
184
+ const outcome = await probeLocalPort(localTarget.host, localTarget.port, deps.localPortProbeDeps);
185
+ if (outcome.verdict === 'refuse') {
186
+ throw ApiError.fromEnvelope({
187
+ error: {
188
+ code: 'VALIDATION_ERROR',
189
+ message: `Nothing is listening on ${targetUrl}. Start your app first, or pass --skip-preflight.`,
190
+ nextAction: 'Verify --local and --local-host match the app you want to test.',
191
+ requestId: 'local',
192
+ details: {
193
+ field: 'local',
194
+ reason: 'local-port-not-listening',
195
+ host: localTarget.host,
196
+ port: localTarget.port,
197
+ probeReason: outcome.reason,
198
+ },
199
+ },
200
+ });
201
+ }
202
+ }
152
203
  // Resolve password: flag > file > none
153
204
  let password = opts.password;
154
205
  if (password === undefined && opts.passwordFile !== undefined) {
@@ -161,7 +212,8 @@ export async function runCreate(opts, deps = {}) {
161
212
  const body = {
162
213
  type: opts.type,
163
214
  name: opts.name,
164
- ...(opts.targetUrl !== undefined ? { targetUrl: opts.targetUrl } : {}),
215
+ ...(targetUrl !== undefined ? { targetUrl } : {}),
216
+ ...(localTarget ? { originMode: 'local' } : {}),
165
217
  ...(opts.username !== undefined ? { username: opts.username } : {}),
166
218
  ...(password !== undefined ? { password } : {}),
167
219
  ...(opts.instruction !== undefined ? { instruction: opts.instruction } : {}),
@@ -186,7 +238,7 @@ export async function runCreate(opts, deps = {}) {
186
238
  ...rawCreated,
187
239
  ...(resolvedId !== undefined ? { projectId: resolvedId, id: resolvedId } : {}),
188
240
  };
189
- out.print(created, data => renderCreateProjectText(data));
241
+ out.print(created, data => renderCreateProjectText(data, localTarget));
190
242
  // A backend project created without --url has no default environment URL.
191
243
  // On the V3 execution path, the shared admission guard (`runProjectGuarded`
192
244
  // -> `assertProjectEnvNotLocal`, called by every V3 run/rerun/batch entry
@@ -937,8 +989,11 @@ export function createProjectCommand(deps = {}) {
937
989
  .description('Create a new project')
938
990
  .option('--type <frontend|backend>', 'project type (required)')
939
991
  .option('--name <name>', 'project name (required)')
940
- .option('--url <url>', 'target URL (required for frontend; also required for backend on the V3 execution ' +
992
+ .option('--url <url>', 'target URL (required for frontend unless --local is used; also required for backend on the V3 execution ' +
941
993
  'path — see `auth status` for your routing)')
994
+ .option('--local <port>', 'create a frontend project for an app on this machine (1-65535; excludes --url)')
995
+ .option('--local-host <host>', 'loopback host: localhost, 127.0.0.1 (default), or ::1; requires --local')
996
+ .option('--skip-preflight', 'skip the local TCP listener check before project creation')
942
997
  .option('--description <text>', 'not supported — projects have no description (test-level descriptions are set on `test create`)')
943
998
  .option('--username <user>', 'optional auth username')
944
999
  .option('--password <pw>', 'optional auth password (use --password-file for non-interactive)')
@@ -957,14 +1012,14 @@ export function createProjectCommand(deps = {}) {
957
1012
  if (type !== 'frontend' && type !== 'backend') {
958
1013
  throw localValidationError('--type must be frontend or backend');
959
1014
  }
960
- if (type === 'frontend' && !cmdOpts.url) {
961
- throw localValidationError('--url is required for --type frontend');
962
- }
963
1015
  await runCreate({
964
1016
  ...resolveCommonOptions(command),
965
1017
  type,
966
1018
  name: cmdOpts.name,
967
1019
  targetUrl: cmdOpts.url,
1020
+ local: cmdOpts.local,
1021
+ localHost: cmdOpts.localHost,
1022
+ skipPreflight: cmdOpts.skipPreflight,
968
1023
  description: cmdOpts.description,
969
1024
  username: cmdOpts.username,
970
1025
  password: cmdOpts.password,
@@ -1201,19 +1256,26 @@ const PROJECT_LIST_COLUMNS = [
1201
1256
  width: rows => Math.max(3, ...rows.map(project => (project.orgName ?? project.orgId ?? '').length)),
1202
1257
  render: project => project.orgName ?? project.orgId ?? '',
1203
1258
  },
1259
+ {
1260
+ header: 'URL',
1261
+ width: rows => Math.max(3, ...rows.map(project => renderProjectUrl(project).length)),
1262
+ render: renderProjectUrl,
1263
+ },
1204
1264
  { header: 'CREATED', width: 0, render: project => project.createdAt },
1205
1265
  ];
1206
- const PROJECT_LIST_ORG_COLUMN = PROJECT_LIST_COLUMNS.find(c => c.header === 'ORG');
1266
+ function renderProjectUrl(project) {
1267
+ const url = project.targetUrl ?? '';
1268
+ return project.originMode === 'local' ? `${url ? `${url} ` : ''}(Local)` : url;
1269
+ }
1207
1270
  /**
1208
1271
  * Default (no explicit `--columns`) column set. ORG is included only when
1209
- * at least one row in this page carries `orgId` — avoids widening the table
1210
- * for callers whose projects have no org attribution at all.
1272
+ * at least one row carries `orgId`; URL is included when a row is local.
1273
+ * Older responses retain the existing default table columns.
1211
1274
  */
1212
1275
  function defaultProjectListColumns(rows) {
1213
1276
  const hasOrgInfo = rows.some(project => project.orgId !== undefined);
1214
- return hasOrgInfo
1215
- ? PROJECT_LIST_COLUMNS
1216
- : PROJECT_LIST_COLUMNS.filter(c => c !== PROJECT_LIST_ORG_COLUMN);
1277
+ const hasLocalProject = rows.some(project => project.originMode === 'local');
1278
+ return PROJECT_LIST_COLUMNS.filter(column => (column.header !== 'ORG' || hasOrgInfo) && (column.header !== 'URL' || hasLocalProject));
1217
1279
  }
1218
1280
  function renderProjectListText(page, options = {}) {
1219
1281
  if (page.items.length === 0) {
@@ -1252,9 +1314,12 @@ function renderProjectText(p) {
1252
1314
  // hint) from "this endpoint doesn't report it" (say nothing).
1253
1315
  if ('targetUrl' in p) {
1254
1316
  lines.push(p.targetUrl
1255
- ? `targetUrl: ${p.targetUrl}`
1317
+ ? `targetUrl: ${renderProjectUrl(p)}`
1256
1318
  : `targetUrl: (not set — set one with: testsprite project update ${p.id} --url <url>)`);
1257
1319
  }
1320
+ if (p.originMode === 'local' && !p.targetUrl) {
1321
+ lines.push('originMode: local (Local)');
1322
+ }
1258
1323
  // Presence-keyed like targetUrl: older backends don't report the field at all.
1259
1324
  if ('testIdAttributes' in p) {
1260
1325
  lines.push(p.testIdAttributes && p.testIdAttributes.length > 0
@@ -1269,7 +1334,7 @@ function renderProjectText(p) {
1269
1334
  * field is proven reliable) because the create response's id field name and
1270
1335
  * `updatedAt` presence are not guaranteed — see `CliCreateProjectResponse`.
1271
1336
  */
1272
- function renderCreateProjectText(p) {
1337
+ function renderCreateProjectText(p, localTarget) {
1273
1338
  const lines = [
1274
1339
  `id: ${resolveCreatedProjectId(p) ?? '(unknown)'}`,
1275
1340
  `name: ${p.name}`,
@@ -1279,6 +1344,12 @@ function renderCreateProjectText(p) {
1279
1344
  ];
1280
1345
  if (p.updatedAt !== undefined)
1281
1346
  lines.push(`updatedAt: ${p.updatedAt}`);
1347
+ if (localTarget) {
1348
+ const projectId = resolveCreatedProjectId(p) ?? '<project-id>';
1349
+ const url = buildLocalTargetUrl(localTarget.host, localTarget.port);
1350
+ const hostFlag = localTarget.host === DEFAULT_LOCAL_HOST ? '' : ` --local-host ${localTarget.host}`;
1351
+ lines.push(`Local project: TestSprite will reach ${url} only through a tunnel from this machine.`, 'Next: write a plan and run it locally:', ` In plan.json, set projectId to ${projectId}.`, ` testsprite test create --project ${projectId} --plan-from plan.json`, ` testsprite test run <test-id> --local ${localTarget.port}${hostFlag}`, `Portal runs of this project stay blocked (free) until you set a public URL with: testsprite project update ${projectId} --url https://...`);
1352
+ }
1282
1353
  return lines.join('\n');
1283
1354
  }
1284
1355
  function renderUpdateText(r) {
@@ -6,6 +6,7 @@ import { ApiError, InterruptError } from '../lib/errors.js';
6
6
  import { type ShutdownHandle } from '../lib/interrupt.js';
7
7
  import type { FetchImpl } from '../lib/http.js';
8
8
  import { type Page } from '../lib/pagination.js';
9
+ import type { WaitTimeoutTelemetry } from '../lib/telemetry.js';
9
10
  import type { CliGetPlansResponse } from '../lib/plans.types.js';
10
11
  import type { RunResponse, RunStatus, TriggerRunResponse, RerunResponse, BatchRerunResponse, ListRunsResponse, RunSource, BatchRunFreshResponse, CancelRunResponse } from '../lib/runs.types.js';
11
12
  import { type LoopbackHost } from '../lib/local-target.js';
@@ -315,6 +316,8 @@ export interface CliFailureContext {
315
316
  failure: CliFailureBlock;
316
317
  }
317
318
  export interface TestDeps {
319
+ /** Report an exhausted poll deadline without changing the public output/error shape. */
320
+ onWaitTimeout?: (context: WaitTimeoutTelemetry) => void;
318
321
  env?: NodeJS.ProcessEnv;
319
322
  credentialsPath?: string;
320
323
  fetchImpl?: FetchImpl;
@@ -359,7 +362,10 @@ export interface TunnelDetach {
359
362
  runId: string;
360
363
  testId: string;
361
364
  localPort: number;
365
+ localHost: LoopbackHost;
362
366
  reason: TunnelDetachReason;
367
+ /** The borrowed tunnel owner disappeared while this run was non-terminal. */
368
+ ownerGone?: boolean;
363
369
  cancel: TunnelCancelOutcome;
364
370
  terminalStatus?: RunStatus;
365
371
  }
@@ -745,7 +751,7 @@ export interface CliCreateFromPlanResponse extends CliCreateTestResponse {
745
751
  * Caveat: the pinned tag only resolves once that version is actually
746
752
  * released — a locally-built/pre-release checkout may see a 404 until then.
747
753
  */
748
- export declare const PLAN_SCHEMA_URL = "https://raw.githubusercontent.com/TestSprite/testsprite-cli/v0.10.0/schemas/plan.schema.json";
754
+ export declare const PLAN_SCHEMA_URL = "https://raw.githubusercontent.com/TestSprite/testsprite-cli/v0.11.0/schemas/plan.schema.json";
749
755
  /**
750
756
  * The SINGLE canonical example plan. This
751
757
  * exact value (via `PLAN_TEMPLATE_TEXT` below) is:
@@ -934,8 +940,14 @@ export declare const DEFERRED_RETRY_DEFAULT_SLEEP_MS = 61000;
934
940
  * a secondary guard. If both fields are absent we treat the error as permanent
935
941
  * to avoid silently burning the entire retry budget on a non-recoverable state.
936
942
  *
943
+ * A 429 whose `details.reason` names a standing condition (see
944
+ * `STANDING_RATE_LIMIT_REASONS` in `lib/http.ts` — e.g. the live
945
+ * tunnel-binding cap) is also permanent, even though it now carries a real
946
+ * `Retry-After`: that header says when a retry COULD first succeed if the
947
+ * caller frees the resource, not that the condition clears on its own.
948
+ *
937
949
  * Limitation: a hypothetical future backend that emits `RATE_LIMITED` for a
938
- * third reason without a `Retry-After` header AND without the per-minute
950
+ * new reason without a `Retry-After` header AND without the per-minute
939
951
  * wording would be classified as permanent here. Document this if it occurs.
940
952
  */
941
953
  export declare function isTransientRateLimit(err: ApiError): boolean;