@testsprite/testsprite-cli 0.11.0 → 0.13.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 (99) hide show
  1. package/README.md +52 -44
  2. package/dist/commands/agent.js +16 -13
  3. package/dist/commands/auth.d.ts +19 -0
  4. package/dist/commands/auth.js +60 -24
  5. package/dist/commands/ci.d.ts +86 -1
  6. package/dist/commands/ci.js +470 -9
  7. package/dist/commands/doctor.d.ts +2 -0
  8. package/dist/commands/doctor.js +22 -9
  9. package/dist/commands/init.js +14 -11
  10. package/dist/commands/project-env.d.ts +90 -0
  11. package/dist/commands/project-env.js +486 -0
  12. package/dist/commands/project.d.ts +15 -5
  13. package/dist/commands/project.js +88 -92
  14. package/dist/commands/schedule.d.ts +2 -0
  15. package/dist/commands/schedule.js +18 -10
  16. package/dist/commands/test.d.ts +102 -30
  17. package/dist/commands/test.js +1949 -419
  18. package/dist/commands/testlist.js +77 -21
  19. package/dist/commands/tunnel.d.ts +26 -3
  20. package/dist/commands/tunnel.js +211 -14
  21. package/dist/commands/usage.d.ts +3 -0
  22. package/dist/commands/usage.js +12 -5
  23. package/dist/index.js +47 -23
  24. package/dist/lib/agent-targets.d.ts +3 -3
  25. package/dist/lib/agent-targets.js +2 -2
  26. package/dist/lib/billing-refusal.d.ts +43 -0
  27. package/dist/lib/billing-refusal.js +171 -0
  28. package/dist/lib/bundle.d.ts +5 -0
  29. package/dist/lib/bundle.js +43 -13
  30. package/dist/lib/ci-linkage.d.ts +90 -0
  31. package/dist/lib/ci-linkage.js +181 -0
  32. package/dist/lib/client-factory.d.ts +4 -1
  33. package/dist/lib/client-factory.js +25 -2
  34. package/dist/lib/client-tag.d.ts +13 -0
  35. package/dist/lib/client-tag.js +44 -0
  36. package/dist/lib/config.d.ts +17 -0
  37. package/dist/lib/config.js +20 -1
  38. package/dist/lib/conflict-reason.d.ts +67 -2
  39. package/dist/lib/conflict-reason.js +148 -13
  40. package/dist/lib/credentials.js +56 -14
  41. package/dist/lib/cron.js +8 -1
  42. package/dist/lib/dry-run/samples.d.ts +13 -1
  43. package/dist/lib/dry-run/samples.js +51 -7
  44. package/dist/lib/errors.d.ts +62 -12
  45. package/dist/lib/errors.js +180 -25
  46. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  47. package/dist/lib/failing-fe-resolver.js +3 -3
  48. package/dist/lib/gh-output.d.ts +26 -11
  49. package/dist/lib/gh-output.js +47 -15
  50. package/dist/lib/history-retention.d.ts +8 -0
  51. package/dist/lib/history-retention.js +24 -0
  52. package/dist/lib/http.d.ts +44 -19
  53. package/dist/lib/http.js +53 -26
  54. package/dist/lib/interrupt.d.ts +21 -13
  55. package/dist/lib/interrupt.js +32 -21
  56. package/dist/lib/junit-report.d.ts +11 -1
  57. package/dist/lib/junit-report.js +15 -3
  58. package/dist/lib/local-target.d.ts +33 -1
  59. package/dist/lib/local-target.js +78 -1
  60. package/dist/lib/output.d.ts +27 -1
  61. package/dist/lib/output.js +22 -3
  62. package/dist/lib/plan-poll.d.ts +11 -11
  63. package/dist/lib/plan-poll.js +12 -12
  64. package/dist/lib/plans.types.d.ts +9 -9
  65. package/dist/lib/plans.types.js +3 -3
  66. package/dist/lib/poll.d.ts +2 -2
  67. package/dist/lib/poll.js +9 -3
  68. package/dist/lib/render-error.d.ts +2 -0
  69. package/dist/lib/render-error.js +13 -0
  70. package/dist/lib/response-schemas.d.ts +54 -12
  71. package/dist/lib/response-schemas.js +106 -7
  72. package/dist/lib/runs.types.d.ts +92 -6
  73. package/dist/lib/secret-file.js +72 -14
  74. package/dist/lib/skill-nudge.d.ts +6 -1
  75. package/dist/lib/skill-nudge.js +32 -5
  76. package/dist/lib/target-url-preflight.d.ts +6 -4
  77. package/dist/lib/target-url-preflight.js +64 -51
  78. package/dist/lib/target-url.js +31 -12
  79. package/dist/lib/telemetry.d.ts +172 -3
  80. package/dist/lib/telemetry.js +276 -15
  81. package/dist/lib/ticker.js +93 -4
  82. package/dist/lib/tunnel-session.d.ts +13 -0
  83. package/dist/lib/tunnel-session.js +4 -1
  84. package/dist/lib/tunnel.types.d.ts +12 -2
  85. package/dist/lib/tunnel.types.js +2 -2
  86. package/dist/lib/version-notice.d.ts +20 -1
  87. package/dist/lib/version-notice.js +59 -12
  88. package/dist/lib/wait-exit.d.ts +8 -0
  89. package/dist/lib/wait-exit.js +76 -4
  90. package/dist/lib/workspace-status.d.ts +23 -0
  91. package/dist/lib/workspace-status.js +15 -0
  92. package/dist/version-guard.d.ts +7 -1
  93. package/dist/version-guard.js +19 -1
  94. package/dist/version.d.ts +1 -1
  95. package/dist/version.js +1 -1
  96. package/package.json +4 -4
  97. package/skills/testsprite-onboard.skill.md +4 -4
  98. package/skills/testsprite-verify.codex.md +59 -57
  99. package/skills/testsprite-verify.skill.md +53 -36
@@ -3,21 +3,23 @@ import { Command } from 'commander';
3
3
  import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
4
4
  import { ApiError, CLIError, InterruptError, RequestTimeoutError, localValidationError, } from '../lib/errors.js';
5
5
  import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, } from '../lib/http.js';
6
+ import { resolveProfileName } from '../lib/config.js';
6
7
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
7
8
  import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
8
9
  import { emitCiArtifacts, summarizeAcceptedPayload } from '../lib/gh-output.js';
9
- import { describeConflict, summarizeConflicts } from '../lib/conflict-reason.js';
10
+ import { billingConflictLink, describeConflict, insufficientCreditsConflictError, isAllCreditsRefusal, isPausedRefusal, pausedConflictError, summarizeConflicts, } from '../lib/conflict-reason.js';
11
+ import { recordBatchOutcome } from '../lib/telemetry.js';
10
12
  import { formatRunProgressLine } from '../lib/run-progress.js';
11
13
  import { createTicker } from '../lib/ticker.js';
12
- import { buildJUnitReport, parseJUnitReportFormat, writeJUnitReportFile, } from '../lib/junit-report.js';
14
+ import { buildJUnitReport, parseJUnitReportFormat, skippedJUnitResultsFromSummary, writeJUnitReportFile, } from '../lib/junit-report.js';
13
15
  import { renderTextTable, resolveTextColumns } from '../lib/text-table.js';
14
16
  import { assertIdempotencyKey } from '../lib/validate.js';
15
- import { resolveWaitFailure } from '../lib/wait-exit.js';
17
+ import { resolveWaitFailure, waitMemberError } from '../lib/wait-exit.js';
16
18
  // ── helpers ──────────────────────────────────────────────────────────────────
17
- function resolveCommonOptions(command) {
19
+ function resolveCommonOptions(command, env) {
18
20
  const g = command.optsWithGlobals();
19
21
  return {
20
- profile: g.profile ?? 'default',
22
+ profile: resolveProfileName(g.profile, env),
21
23
  output: resolveOutputMode(g.output),
22
24
  endpointUrl: g.endpointUrl,
23
25
  debug: g.debug ?? false,
@@ -332,6 +334,11 @@ export async function runTestlistRun(opts, deps = {}) {
332
334
  if (resp.notFound && resp.notFound.length > 0) {
333
335
  stderrFn(`warning: ${resp.notFound.length} --case id(s) not in this list, skipped: ${resp.notFound.join(' ')}`);
334
336
  }
337
+ if (resp.accepted.length > 0) {
338
+ const link = billingConflictLink(resp.conflicts, client.resolvedBaseUrl);
339
+ if (link)
340
+ stderrFn(`[advisory] Billing refusal for some tests.${link}`);
341
+ }
335
342
  // All-conflict: nothing new dispatched because every targeted case is already
336
343
  // in flight → exit 6, for BOTH --wait and non-wait (a --wait over zero accepted
337
344
  // would otherwise no-op straight to exit 0). Distinct from the empty/no-match
@@ -339,13 +346,19 @@ export async function runTestlistRun(opts, deps = {}) {
339
346
  // flows through the tail below so its CI artifacts are still emitted.
340
347
  if (resp.accepted.length === 0 && resp.conflicts.length > 0) {
341
348
  out.print(resp, () => renderRunAcceptedText(resp));
349
+ recordBatchOutcome({
350
+ accepted: 0,
351
+ conflicts: resp.conflicts,
352
+ deferred: resp.deferred.length,
353
+ skipped: 0,
354
+ });
342
355
  // Surface the exit-6 in CI too (only under --wait, the CI-artifact contract):
343
356
  // an all-conflict re-run — every targeted case already in flight — otherwise
344
357
  // exits 6 with no ::error:: annotation and no summary file. The conflicts fold
345
358
  // into the summary as non-passed rows. The non-wait path never emits CI
346
359
  // artifacts, matching the main tail below.
347
360
  if (opts.wait) {
348
- emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify({
361
+ const summary = summarizeAcceptedPayload(JSON.stringify({
349
362
  accepted: [],
350
363
  conflicts: resp.conflicts,
351
364
  deferred: resp.deferred,
@@ -354,28 +367,57 @@ export async function runTestlistRun(opts, deps = {}) {
354
367
  // CI summary must report the whole requested set (same reason the
355
368
  // main --wait envelope threads it). Undefined ⇒ JSON.stringify drops it.
356
369
  notFound: resp.notFound,
357
- }), { notFoundNote: 'not a member of this list (not dispatched)' }), opts, {
370
+ }), { notFoundNote: 'not a member of this list (not dispatched)' });
371
+ if (opts.report === 'junit' && opts.reportFile !== undefined) {
372
+ const suiteName = opts.reportSuiteName ?? `testsprite:testlist:${opts.listId}`;
373
+ await writeJUnitReportFile(opts.reportFile, buildJUnitReport({
374
+ suiteName,
375
+ classname: `testlist:${opts.listId}`,
376
+ results: skippedJUnitResultsFromSummary(summary),
377
+ }));
378
+ }
379
+ emitCiArtifacts(summary, opts, {
358
380
  env: deps.env ?? process.env,
359
381
  stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
360
382
  stderr: stderrFn,
361
383
  }, 'testlist run');
362
384
  }
385
+ // Every case refused for credits → exit 12, the same INSUFFICIENT_CREDITS
386
+ // envelope the single-run route answers (a rate-deferred remainder is exit 7
387
+ // below; `isAllCreditsRefusal` requires an empty deferred set).
388
+ if (isAllCreditsRefusal(resp)) {
389
+ throw insufficientCreditsConflictError(resp.conflicts, client.resolvedBaseUrl);
390
+ }
391
+ if (isPausedRefusal(resp)) {
392
+ throw pausedConflictError(resp.conflicts, client.resolvedBaseUrl);
393
+ }
363
394
  const pollIds = resp.conflicts
364
395
  .map(c => c.currentRunId)
365
396
  .filter((id) => Boolean(id));
366
397
  // Name the causes instead of blanket "already in flight" — a list pinned to
367
398
  // a local env or a view-only project is not something to poll. The poll hint
368
- // is emitted only for the cases that actually have an in-flight run.
399
+ // is emitted only for the cases that actually have an in-flight run. A
400
+ // paused (`billing_hold`) / insufficient_credits conflict riding along a NON-uniform
401
+ // mix (the uniform cases already threw above) still needs its upgrade
402
+ // link — `accepted.length` is 0 in this whole branch, so the advisory
403
+ // printed earlier (guarded on `accepted.length > 0`) never showed it.
369
404
  throw new CLIError(`Nothing dispatched — ${resp.conflicts.length} conflict(s): ${summarizeConflicts(resp.conflicts)}` +
370
405
  (pollIds.length > 0
371
406
  ? `. Poll in-flight runs: testsprite test wait ${pollIds.join(' ')}`
372
- : ''), 6);
407
+ : '') +
408
+ billingConflictLink(resp.conflicts, client.resolvedBaseUrl), 6);
373
409
  }
374
410
  if (!opts.wait) {
375
411
  // Print what dispatched, or the empty/no-match reason. Exit 0.
376
412
  out.print(resp, () => resp.accepted.length > 0
377
413
  ? renderRunAcceptedText(resp)
378
414
  : `No runs dispatched${resp.reason ? ` (${resp.reason})` : ''}.`);
415
+ recordBatchOutcome({
416
+ accepted: resp.accepted.length,
417
+ conflicts: resp.conflicts,
418
+ deferred: resp.deferred.length,
419
+ skipped: 0,
420
+ });
379
421
  assertNoDeferred(resp);
380
422
  assertNoNotFound(resp);
381
423
  return resp;
@@ -467,7 +509,7 @@ export async function runTestlistRun(opts, deps = {}) {
467
509
  testId: entry.testId,
468
510
  runId: entry.runId,
469
511
  status: 'error',
470
- error: { code: err.code, message: err.message, exitCode: err.exitCode },
512
+ error: waitMemberError(err),
471
513
  };
472
514
  }
473
515
  throw err;
@@ -527,10 +569,24 @@ export async function runTestlistRun(opts, deps = {}) {
527
569
  // Multi-project list: name the suite/classname by the LIST, not one project
528
570
  // (`resolveBatchReportProjectId`'s single-project assumption doesn't hold).
529
571
  const suiteName = opts.reportSuiteName ?? `testsprite:testlist:${opts.listId}`;
530
- const xml = buildJUnitReport({ suiteName, classname: `testlist:${opts.listId}`, results });
572
+ const summary = summarizeAcceptedPayload(JSON.stringify(jsonPayload), {
573
+ notFoundNote: 'not a member of this list (not dispatched)',
574
+ });
575
+ const xml = buildJUnitReport({
576
+ suiteName,
577
+ classname: `testlist:${opts.listId}`,
578
+ results: [...results, ...skippedJUnitResultsFromSummary(summary)],
579
+ });
531
580
  await writeJUnitReportFile(opts.reportFile, xml);
532
581
  }
533
582
  out.print(jsonPayload, () => results.map(r => `${r.runId} ${r.status}`).join('\n'));
583
+ recordBatchOutcome({
584
+ accepted: resp.accepted.length,
585
+ conflicts: resp.conflicts,
586
+ deferred: resp.deferred.length,
587
+ skipped: 0,
588
+ results,
589
+ });
534
590
  // CI-native output parity with `test run` (--gh-output / --summary-file):
535
591
  // auto-enable under GITHUB_ACTIONS. Emit BEFORE the exit-code gates below so a
536
592
  // failing/timed-out/deferred run still gets its ::error:: annotations + the
@@ -632,7 +688,7 @@ export function createTestListCommand(deps = {}) {
632
688
  .addHelpText('after', GLOBAL_OPTS_HINT)
633
689
  .action(async (cmdOpts, command) => {
634
690
  await runTestlistList({
635
- ...resolveCommonOptions(command),
691
+ ...resolveCommonOptions(command, deps.env),
636
692
  columns: cmdOpts.columns,
637
693
  noHeader: cmdOpts.header === false,
638
694
  }, deps);
@@ -642,7 +698,7 @@ export function createTestListCommand(deps = {}) {
642
698
  .description('Get a test list with its cases')
643
699
  .addHelpText('after', GLOBAL_OPTS_HINT)
644
700
  .action(async (listId, _cmdOpts, command) => {
645
- await runTestlistGet({ ...resolveCommonOptions(command), listId }, deps);
701
+ await runTestlistGet({ ...resolveCommonOptions(command, deps.env), listId }, deps);
646
702
  });
647
703
  testlist
648
704
  .command('create')
@@ -653,7 +709,7 @@ export function createTestListCommand(deps = {}) {
653
709
  .addHelpText('after', GLOBAL_OPTS_HINT)
654
710
  .action(async (cmdOpts, command) => {
655
711
  await runTestlistCreate({
656
- ...resolveCommonOptions(command),
712
+ ...resolveCommonOptions(command, deps.env),
657
713
  name: cmdOpts.name,
658
714
  projectEnv: cmdOpts.projectEnv,
659
715
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -669,7 +725,7 @@ export function createTestListCommand(deps = {}) {
669
725
  .addHelpText('after', GLOBAL_OPTS_HINT)
670
726
  .action(async (listId, cmdOpts, command) => {
671
727
  await runTestlistUpdate({
672
- ...resolveCommonOptions(command),
728
+ ...resolveCommonOptions(command, deps.env),
673
729
  listId,
674
730
  name: cmdOpts.name,
675
731
  projectEnv: cmdOpts.projectEnv,
@@ -685,7 +741,7 @@ export function createTestListCommand(deps = {}) {
685
741
  .addHelpText('after', GLOBAL_OPTS_HINT)
686
742
  .action(async (listId, cmdOpts, command) => {
687
743
  await runTestlistDelete({
688
- ...resolveCommonOptions(command),
744
+ ...resolveCommonOptions(command, deps.env),
689
745
  listId,
690
746
  confirm: cmdOpts.confirm,
691
747
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -698,7 +754,7 @@ export function createTestListCommand(deps = {}) {
698
754
  .addHelpText('after', GLOBAL_OPTS_HINT)
699
755
  .action(async (listId, testIds, cmdOpts, command) => {
700
756
  await runTestlistAdd({
701
- ...resolveCommonOptions(command),
757
+ ...resolveCommonOptions(command, deps.env),
702
758
  listId,
703
759
  testIds,
704
760
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -711,7 +767,7 @@ export function createTestListCommand(deps = {}) {
711
767
  .addHelpText('after', GLOBAL_OPTS_HINT)
712
768
  .action(async (listId, testIds, cmdOpts, command) => {
713
769
  await runTestlistRemove({
714
- ...resolveCommonOptions(command),
770
+ ...resolveCommonOptions(command, deps.env),
715
771
  listId,
716
772
  testIds,
717
773
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -728,13 +784,13 @@ export function createTestListCommand(deps = {}) {
728
784
  .option('--report <format>', 'with --wait: write a JUnit XML sidecar after polling (accepted: junit)')
729
785
  .option('--report-file <path>', 'output path for --report (atomic write)')
730
786
  .option('--report-suite-name <name>', 'JUnit <testsuite name=...> override (default: testsprite:testlist:<listId>)')
731
- .option('--gh-output', 'with --wait: emit GitHub-native output (::error:: annotations per non-passed member; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
732
- .option('--summary-file <path>', 'with --wait: also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
787
+ .option('--gh-output', 'with --wait: emit GitHub-native output (::error:: annotations for failed/timed-out members, ::warning:: for never-dispatched ones; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
788
+ .option('--summary-file <path>', 'with --wait: also write the reduced machine summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
733
789
  .addHelpText('after', GLOBAL_OPTS_HINT)
734
790
  .action(async (listId, cmdOpts, command) => {
735
791
  const wait = cmdOpts.wait === true;
736
792
  await runTestlistRun({
737
- ...resolveCommonOptions(command),
793
+ ...resolveCommonOptions(command, deps.env),
738
794
  listId,
739
795
  cases: cmdOpts.case,
740
796
  wait,
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `testsprite tunnel start | status | stop` — DEV-747 piece 3.
2
+ * `testsprite tunnel start | list | status | stop`.
3
3
  *
4
4
  * The out-of-band primitive under `test run --local`, which is sugar over it.
5
5
  * Two things it buys that the sugar cannot:
@@ -22,7 +22,7 @@ import { Command } from 'commander';
22
22
  import type { CommonOptions } from '../lib/client-factory.js';
23
23
  import { type ShutdownHandle } from '../lib/interrupt.js';
24
24
  import { type TunnelClientHandle } from '../lib/tunnel-session.js';
25
- import type { TunnelStatusResponse } from '../lib/tunnel.types.js';
25
+ import type { TunnelListResponse, TunnelStatusResponse } from '../lib/tunnel.types.js';
26
26
  import { type TunnelClientOptions } from '../vendor/tunnel-client/index.js';
27
27
  export interface TunnelDeps {
28
28
  env?: NodeJS.ProcessEnv;
@@ -41,6 +41,28 @@ export interface TunnelStartOptions extends CommonOptions {
41
41
  export interface TunnelClientIdOptions extends CommonOptions {
42
42
  clientId: string;
43
43
  }
44
+ export interface TunnelStopOptions extends CommonOptions {
45
+ clientId?: string;
46
+ all?: boolean;
47
+ confirm?: boolean;
48
+ }
49
+ export interface TunnelStopResult {
50
+ clientId: string;
51
+ stopped: boolean;
52
+ error?: {
53
+ code: string;
54
+ message: string;
55
+ exitCode: number;
56
+ };
57
+ }
58
+ export interface TunnelStopSummary {
59
+ results: TunnelStopResult[];
60
+ summary: {
61
+ total: number;
62
+ stopped: number;
63
+ failed: number;
64
+ };
65
+ }
44
66
  /**
45
67
  * Open a tunnel and hold it until the command is stopped.
46
68
  *
@@ -60,6 +82,7 @@ export declare function runTunnelStart(opts: TunnelStartOptions, deps?: TunnelDe
60
82
  * defect backend-v2.0 #1068 fixed on the server side of this same question.
61
83
  */
62
84
  export declare function runTunnelStatus(opts: TunnelClientIdOptions, deps?: TunnelDeps): Promise<TunnelStatusResponse>;
85
+ export declare function runTunnelList(opts: CommonOptions, deps?: TunnelDeps): Promise<TunnelListResponse>;
63
86
  /**
64
87
  * Destroy a binding. Idempotent by contract — deleting an unknown or
65
88
  * already-deleted binding is a success, because the requested end state holds.
@@ -68,5 +91,5 @@ export declare function runTunnelStatus(opts: TunnelClientIdOptions, deps?: Tunn
68
91
  * removes the client from the tunnel server. A running `tunnel start`
69
92
  * observes the revocation on its next status check and exits.
70
93
  */
71
- export declare function runTunnelStop(opts: TunnelClientIdOptions, deps?: TunnelDeps): Promise<void>;
94
+ export declare function runTunnelStop(opts: TunnelStopOptions, deps?: TunnelDeps): Promise<void>;
72
95
  export declare function createTunnelCommand(deps?: TunnelDeps): Command;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `testsprite tunnel start | status | stop` — DEV-747 piece 3.
2
+ * `testsprite tunnel start | list | status | stop`.
3
3
  *
4
4
  * The out-of-band primitive under `test run --local`, which is sugar over it.
5
5
  * Two things it buys that the sugar cannot:
@@ -20,10 +20,12 @@
20
20
  */
21
21
  import { Command } from 'commander';
22
22
  import * as v from 'valibot';
23
+ import { resolveProfileName } from '../lib/config.js';
23
24
  import { createHttpClientFactory, emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
24
- import { ApiError, RequestTimeoutError } from '../lib/errors.js';
25
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError } from '../lib/errors.js';
25
26
  import { globalShutdown } from '../lib/interrupt.js';
26
27
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
28
+ import { renderTextTable } from '../lib/text-table.js';
27
29
  import { formatDataPlaneUnreachableMessage, formatDataPlaneUnreachableNextAction, openTunnelSession, } from '../lib/tunnel-session.js';
28
30
  import { TunnelClient } from '../vendor/tunnel-client/index.js';
29
31
  const TUNNEL_CLIENT_ID_SCHEMA = v.pipe(v.string(), v.uuid());
@@ -50,7 +52,7 @@ function makeClient(opts, deps, shutdownSignal = (deps.shutdown ?? globalShutdow
50
52
  return makeHttpClient(opts, {
51
53
  env: deps.env,
52
54
  credentialsPath: deps.credentialsPath,
53
- fetchImpl: deps.fetchImpl,
55
+ fetchImpl: opts.dryRun ? undefined : deps.fetchImpl,
54
56
  stderr: deps.stderr,
55
57
  shutdownSignal,
56
58
  });
@@ -228,6 +230,7 @@ export async function runTunnelStart(opts, deps = {}) {
228
230
  log: stderr,
229
231
  logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error',
230
232
  ...(opts.ttlSeconds !== undefined ? { ttlSeconds: opts.ttlSeconds } : {}),
233
+ onMinted: minted => stderr(`Minted tunnel client ${minted.clientId} (expires ${minted.expiresAt}); connecting…`),
231
234
  onFatal: (reason, message) => {
232
235
  fatal = true;
233
236
  fatalReason = reason;
@@ -363,6 +366,66 @@ function renderStatus(status) {
363
366
  }
364
367
  return lines.join('\n');
365
368
  }
369
+ async function listTunnelsForAccount(opts, deps) {
370
+ try {
371
+ return await makeClient(opts, deps).listTunnels();
372
+ }
373
+ catch (err) {
374
+ if (err instanceof ApiError && err.httpStatus === 404) {
375
+ throw ApiError.fromEnvelope({
376
+ error: {
377
+ code: 'NOT_FOUND',
378
+ message: 'This TestSprite server cannot list tunnels yet.',
379
+ nextAction: 'Stop a tunnel you know the id of with `testsprite tunnel stop <client-id>`, or wait for it to expire.',
380
+ requestId: err.requestId,
381
+ details: err.details,
382
+ },
383
+ }, 404);
384
+ }
385
+ throw err;
386
+ }
387
+ }
388
+ export async function runTunnelList(opts, deps = {}) {
389
+ const response = await listTunnelsForAccount(opts, deps);
390
+ makeOutput(opts.output, deps).print(response, data => renderTunnelList(data));
391
+ return response;
392
+ }
393
+ function renderTunnelList(response) {
394
+ if (response.tunnels.length === 0)
395
+ return 'No live tunnels.';
396
+ const columns = [
397
+ {
398
+ header: 'CLIENT ID',
399
+ width: (rows) => Math.max(9, ...rows.map(item => item.clientId.length)),
400
+ render: (item) => item.clientId,
401
+ },
402
+ {
403
+ header: 'STATUS',
404
+ width: (rows) => Math.max(6, ...rows.map(item => item.status.length)),
405
+ render: (item) => item.status,
406
+ },
407
+ {
408
+ header: 'CREATED',
409
+ width: (rows) => Math.max(7, ...rows.map(item => (item.createdAt ?? '-').length)),
410
+ render: (item) => item.createdAt ?? '-',
411
+ },
412
+ {
413
+ header: 'EXPIRES',
414
+ width: (rows) => Math.max(7, ...rows.map(item => item.expiresAt.length)),
415
+ render: (item) => item.expiresAt,
416
+ },
417
+ ];
418
+ return [
419
+ renderTextTable(response.tunnels, columns),
420
+ 'hint Stop one: testsprite tunnel stop <client-id>',
421
+ 'hint Stop all of them: testsprite tunnel stop --all --confirm',
422
+ ...(response.tunnels.some(item => item.status === 'unknown')
423
+ ? [
424
+ 'note "unknown" means TestSprite could not check that connection just now; the tunnel may still be up.',
425
+ ]
426
+ : []),
427
+ ].join('\n');
428
+ }
366
429
  /**
367
430
  * Destroy a binding. Idempotent by contract — deleting an unknown or
368
431
  * already-deleted binding is a success, because the requested end state holds.
@@ -372,6 +435,109 @@ function renderStatus(status) {
372
435
  * observes the revocation on its next status check and exits.
373
436
  */
374
437
  export async function runTunnelStop(opts, deps = {}) {
438
+ if (opts.clientId !== undefined && opts.all) {
439
+ throw ApiError.fromEnvelope({
440
+ error: {
441
+ code: 'VALIDATION_ERROR',
442
+ message: 'Pass either a <client-id> or --all, not both.',
443
+ nextAction: 'Choose one tunnel to stop, or use --all --confirm.',
444
+ requestId: 'local',
445
+ details: { field: 'all', reason: 'mutually exclusive with clientId' },
446
+ },
447
+ });
448
+ }
449
+ if (opts.confirm && !opts.all) {
450
+ throw ApiError.fromEnvelope({
451
+ error: {
452
+ code: 'VALIDATION_ERROR',
453
+ message: '--confirm only applies with --all.',
454
+ nextAction: 'Remove --confirm, or use --all --confirm.',
455
+ requestId: 'local',
456
+ details: { field: 'confirm', reason: 'requires --all' },
457
+ },
458
+ });
459
+ }
460
+ if (opts.clientId === undefined && !opts.all) {
461
+ throw ApiError.fromEnvelope({
462
+ error: {
463
+ code: 'VALIDATION_ERROR',
464
+ message: 'provide a <client-id>, or use --all --confirm to stop every tunnel on this account',
465
+ nextAction: 'Run testsprite tunnel list to see your tunnel client ids.',
466
+ requestId: 'local',
467
+ details: { field: 'clientId', reason: 'required unless --all is set' },
468
+ },
469
+ });
470
+ }
471
+ if (opts.all) {
472
+ if (!opts.confirm && !opts.dryRun) {
473
+ throw ApiError.fromEnvelope({
474
+ error: {
475
+ code: 'VALIDATION_ERROR',
476
+ message: 'Refusing to stop every tunnel without --confirm.',
477
+ nextAction: 'This revokes every live tunnel on this account, including ones another terminal or a CI job is using — their runs lose their route to your machine. Re-run with --confirm. To see what would be stopped: testsprite tunnel list.',
478
+ requestId: 'local',
479
+ details: { field: 'confirm', reason: 'required for destructive operation' },
480
+ },
481
+ });
482
+ }
483
+ if (opts.dryRun) {
484
+ stderrOf(deps)("[dry-run] WARNING: the preview below uses sample data and does NOT reflect the real tunnels on this account. Run 'testsprite tunnel list' to see them.");
485
+ }
486
+ const response = await listTunnelsForAccount(opts, deps);
487
+ const out = makeOutput(opts.output, deps);
488
+ if (opts.dryRun) {
489
+ const requests = response.tunnels.map(item => ({
490
+ method: 'DELETE',
491
+ path: `/api/cli/v1/tunnel/${item.clientId}`,
492
+ }));
493
+ out.print({ requests }, () => requests.map(item => `${item.method} ${item.path}`).join('\n'));
494
+ return;
495
+ }
496
+ if (response.tunnels.length === 0) {
497
+ out.print({ results: [], summary: { total: 0, stopped: 0, failed: 0 } }, () => 'No live tunnels — nothing to stop.');
498
+ return;
499
+ }
500
+ const client = makeClient(opts, deps);
501
+ const results = [];
502
+ for (const item of response.tunnels) {
503
+ try {
504
+ // Sequential and one id at a time, with the HTTP layer's normal retries:
505
+ // the delete is idempotent, so a transient failure is worth retrying.
506
+ await client.deleteTunnel(item.clientId);
507
+ results.push({ clientId: item.clientId, stopped: true });
508
+ }
509
+ catch (err) {
510
+ if (err instanceof InterruptError)
511
+ throw err;
512
+ const failure = err instanceof CLIError ? err : new CLIError(String(err), 1);
513
+ results.push({
514
+ clientId: item.clientId,
515
+ stopped: false,
516
+ error: {
517
+ code: failure.code,
518
+ message: failure.message,
519
+ exitCode: failure.exitCode,
520
+ },
521
+ });
522
+ }
523
+ }
524
+ const stopped = results.filter(result => result.stopped).length;
525
+ const bulk = {
526
+ results,
527
+ summary: { total: results.length, stopped, failed: results.length - stopped },
528
+ };
529
+ out.print(bulk, () => [
530
+ ...results.map(result => result.stopped
531
+ ? `stopped ${result.clientId}`
532
+ : `failed ${result.clientId} ${result.error?.message}`),
533
+ `Stopped ${stopped} of ${results.length} tunnels.`,
534
+ 'hint A running `tunnel start` notices a revoked credential within ~15 s and exits.',
535
+ ].join('\n'));
536
+ if (bulk.summary.failed > 0) {
537
+ throw new CLIError(`${bulk.summary.failed} tunnel stop${bulk.summary.failed === 1 ? '' : 's'} failed. See results for details.`, 1);
538
+ }
539
+ return;
540
+ }
375
541
  assertTunnelClientId(opts.clientId);
376
542
  const out = makeOutput(opts.output, deps);
377
543
  if (opts.dryRun) {
@@ -394,8 +560,10 @@ export function createTunnelCommand(deps = {}) {
394
560
  '\nExamples:\n' +
395
561
  ' testsprite tunnel start # hold a tunnel open (Ctrl-C to stop)\n' +
396
562
  ' testsprite test run <id> --local 5173 --tunnel-client <id>\n' +
563
+ ' testsprite tunnel list\n' +
397
564
  ' testsprite tunnel status <id>\n' +
398
- ' testsprite tunnel stop <id>\n');
565
+ ' testsprite tunnel stop <id>\n' +
566
+ ' testsprite tunnel stop --all --confirm\n');
399
567
  tunnel
400
568
  .command('start')
401
569
  // One-line description: Commander prints it in the parent's command list,
@@ -405,7 +573,8 @@ export function createTunnelCommand(deps = {}) {
405
573
  .option('--ttl <seconds>', 'requested lifetime of the tunnel credential (60–28800). The server clamps this, and the ' +
406
574
  'credential is deleted when the command exits regardless — the lifetime only matters if ' +
407
575
  'this process is killed without cleaning up.')
408
- .addHelpText('after', '\nPrints the client id to pass to `test run --local <port> --tunnel-client <id>`.\n' +
576
+ .addHelpText('after', '\nPrints the client id to stderr as soon as it is minted, before connecting; pass it\n' +
577
+ 'to `test run --local <port> --tunnel-client <id>`.\n' +
409
578
  '\nExit codes:\n' +
410
579
  ' 0 you stopped it (Ctrl-C is the normal way to end this command)\n' +
411
580
  ' 3 auth error — the key needs the `run:tunnel` scope; mint a new key\n' +
@@ -415,10 +584,23 @@ export function createTunnelCommand(deps = {}) {
415
584
  .action(async (cmdOpts, command) => {
416
585
  const ttlSeconds = parseTtl(cmdOpts.ttl);
417
586
  await runTunnelStart({
418
- ...resolveCommonOptions(command),
587
+ ...resolveCommonOptions(command, deps.env),
419
588
  ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),
420
589
  }, deps);
421
590
  });
591
+ tunnel
592
+ .command('list')
593
+ .description('List live tunnel bindings for this account')
594
+ .addHelpText('after', '\nShows each tunnel client id, connection status, creation time and expiry.\n' +
595
+ '\nExit codes:\n' +
596
+ ' 0 listed (possibly empty)\n' +
597
+ ' 3 auth error — the key needs the `run:tunnel` scope\n' +
598
+ ' 4 server too old to list tunnels\n' +
599
+ ' 10 could not reach TestSprite\n')
600
+ .addHelpText('after', GLOBAL_OPTS_HINT)
601
+ .action(async (_cmdOpts, command) => {
602
+ await runTunnelList(resolveCommonOptions(command, deps.env), deps);
603
+ });
422
604
  tunnel
423
605
  .command('status <client-id>')
424
606
  .description('Report whether a tunnel client of yours is connected')
@@ -430,23 +612,38 @@ export function createTunnelCommand(deps = {}) {
430
612
  ' 10 could not reach TestSprite to ask\n')
431
613
  .addHelpText('after', GLOBAL_OPTS_HINT)
432
614
  .action(async (clientId, _cmdOpts, command) => {
433
- await runTunnelStatus({ ...resolveCommonOptions(command), clientId }, deps);
615
+ await runTunnelStatus({ ...resolveCommonOptions(command, deps.env), clientId }, deps);
434
616
  });
435
617
  tunnel
436
- .command('stop <client-id>')
437
- .description('Destroy a tunnel credential (idempotent)')
618
+ .command('stop [client-id]')
619
+ .description('Destroy one tunnel credential or stop every live tunnel')
620
+ .option('--all', 'stop every live tunnel on this account', false)
621
+ .option('--confirm', 'required with --all for this destructive operation', false)
438
622
  .addHelpText('after', '\nStopping one that is already gone succeeds. Revoking the credential\n' +
439
- 'also makes a running `tunnel start` exit within ~15 s.\n')
623
+ 'also makes a running `tunnel start` exit within ~15 s.\n' +
624
+ 'Stopping all requires --confirm; --dry-run previews sample ids without it.\n' +
625
+ '\nExit codes:\n' +
626
+ ' 0 stopped (or already absent), including an empty --all result\n' +
627
+ ' 1 at least one tunnel could not be stopped\n' +
628
+ ' 3 auth error — the key needs the `run:tunnel` scope\n' +
629
+ ' 4 server too old to list tunnels (with --all)\n' +
630
+ ' 5 invalid arguments or --all without --confirm\n' +
631
+ ' 10 could not reach TestSprite\n')
440
632
  .addHelpText('after', GLOBAL_OPTS_HINT)
441
- .action(async (clientId, _cmdOpts, command) => {
442
- await runTunnelStop({ ...resolveCommonOptions(command), clientId }, deps);
633
+ .action(async (clientId, cmdOpts, command) => {
634
+ await runTunnelStop({
635
+ ...resolveCommonOptions(command, deps.env),
636
+ clientId,
637
+ all: cmdOpts.all,
638
+ confirm: cmdOpts.confirm,
639
+ }, deps);
443
640
  });
444
641
  return tunnel;
445
642
  }
446
- function resolveCommonOptions(command) {
643
+ function resolveCommonOptions(command, env) {
447
644
  const globals = command.optsWithGlobals();
448
645
  return {
449
- profile: globals.profile ?? 'default',
646
+ profile: resolveProfileName(globals.profile, env),
450
647
  output: resolveOutputMode(globals.output),
451
648
  endpointUrl: globals.endpointUrl,
452
649
  debug: globals.debug ?? false,
@@ -11,6 +11,7 @@
11
11
  * has no server-side source at all today).
12
12
  */
13
13
  import { Command } from 'commander';
14
+ import { type WorkspaceStatus } from '../lib/workspace-status.js';
14
15
  import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
15
16
  import type { FetchImpl } from '../lib/http.js';
16
17
  import type { CliOrgBinding, CliOrgSummary } from '../lib/org-render.js';
@@ -80,6 +81,8 @@ export interface ActiveOrg {
80
81
  /** Monthly per-seat credit allowance for the org's plan. */
81
82
  includedCredits: number;
82
83
  seats: number;
84
+ /** Billing standing (paused / pending / ok). Absent on an older backend. */
85
+ workspace?: WorkspaceStatus;
83
86
  }
84
87
  export interface UsageDeps {
85
88
  env?: NodeJS.ProcessEnv;