diff --git a/src/commands/artifacts.ts b/src/commands/artifacts.ts index b521c96..c0a5c2c 100644 --- a/src/commands/artifacts.ts +++ b/src/commands/artifacts.ts @@ -43,6 +43,16 @@ export const artifactsCommand = defineCommand({ description: 'Custom file path for downloaded artifacts (default: ./artifacts.zip). Requires --download-artifacts.', }, + 'result-id': { + type: 'string', + description: + "Download only this result's artifacts: its flow's attempts on that one device. Requires --download-artifacts.", + }, + flow: { + type: 'string', + description: + 'Download only the artifacts of the flow with this file path or name (e.g. flows/login.yaml or login). Fails, listing the result ids, when it matches more than one result, e.g. one per device. Requires --download-artifacts.', + }, report: { type: 'string', description: @@ -76,6 +86,8 @@ export const artifactsCommand = defineCommand({ 'download-artifacts', ); const artifactsPath = args['artifacts-path'] as string | undefined; + const resultIdArg = args['result-id'] as string | undefined; + const flow = args.flow as string | undefined; const report = validateEnum( args.report as string | undefined, REPORT_OPTIONS, @@ -109,6 +121,8 @@ export const artifactsCommand = defineCommand({ ); } + const resultId = parseResultFilter(resultIdArg, flow, Boolean(downloadArtifacts)); + const service = new ReportDownloadService(); const downloads: DownloadResult[] = []; @@ -119,7 +133,9 @@ export const artifactsCommand = defineCommand({ artifactsPath: artifactsPath ?? './artifacts.zip', debug, downloadType: downloadArtifacts, + flow, logger: log, + resultId, uploadId, warnLogger: (m: string) => logger.warn(m), })); @@ -153,4 +169,37 @@ export const artifactsCommand = defineCommand({ }, }); +/** + * Check --result-id and --flow: at most one, only with --download-artifacts, + * and a result id that is a positive whole number. Returns the parsed id. + */ +export function parseResultFilter( + resultIdArg: string | undefined, + flow: string | undefined, + downloadingArtifacts: boolean, +): number | undefined { + if (resultIdArg !== undefined && flow !== undefined) { + throw new CliError( + '--result-id cannot also be provided when using --flow (flags are mutually exclusive).', + ); + } + + const flag = resultIdArg === undefined ? (flow === undefined ? undefined : '--flow') : '--result-id'; + if (flag && !downloadingArtifacts) { + throw new CliError(`${flag} requires --download-artifacts.`); + } + + if (flow !== undefined && flow.trim() === '') { + throw new CliError('--flow needs a flow file path or name.'); + } + + if (resultIdArg === undefined) return undefined; + const resultId = Number(resultIdArg); + if (!/^\d+$/.test(resultIdArg.trim()) || !Number.isSafeInteger(resultId) || resultId <= 0) { + throw new CliError(`--result-id must be a positive whole number, got '${resultIdArg}'.`); + } + + return resultId; +} + export default artifactsCommand; diff --git a/src/gateways/api-gateway.ts b/src/gateways/api-gateway.ts index 7d3dc31..ef65682 100644 --- a/src/gateways/api-gateway.ts +++ b/src/gateways/api-gateway.ts @@ -27,6 +27,17 @@ function expandHome(p: string): string { return p.replace(/^~(?=$|\/|\\)/, homedir()); } +/** Extra checks a bundle download makes before it trusts the manifest. */ +interface BundleDownloadOptions { + /** + * The manifest's `filename` must start with this, or the download throws + * `unsupportedMessage` instead of falling back: how a filtered request + * tells an API that applied the filter from an older one that ignored it. + */ + requiredFilenamePrefix?: string; + unsupportedMessage?: string; +} + /** What went wrong in a bundle attempt, minus the route/timing added later. */ type BundleFailure = Omit< BundleFallbackTelemetry, @@ -293,6 +304,7 @@ export const ApiGateway = { manifestEndpoint: string, destinationPath: string, operation: string, + options: BundleDownloadOptions = {}, ): Promise { const startedAt = Date.now(); const outcome = await this.attemptBundleDownload( @@ -301,6 +313,7 @@ export const ApiGateway = { manifestEndpoint, destinationPath, operation, + options, ); if (outcome === true) return true; @@ -327,6 +340,7 @@ export const ApiGateway = { manifestEndpoint: string, destinationPath: string, operation: string, + options: BundleDownloadOptions = {}, ): Promise { let manifestRes: Response; try { @@ -349,6 +363,7 @@ export const ApiGateway = { let bundle: { bundleUrl?: string; + filename?: string; manifest?: string; sig?: string; }; @@ -361,6 +376,14 @@ export const ApiGateway = { return failure('manifest_incomplete'); } + // An API that predates a filter ignores it and bundles the whole upload, + // named as such. Thrown, not a fallback: the inline route would ignore the + // filter just the same and save the wrong ZIP. + const prefix = options.requiredFilenamePrefix; + if (prefix !== undefined && !bundle.filename?.startsWith(prefix)) { + throw new Error(options.unsupportedMessage ?? `${operation}: the API ignored the request filter`); + } + let zipRes: Response; try { zipRes = await fetch(bundle.bundleUrl, { @@ -503,21 +526,37 @@ export const ApiGateway = { }, + /** + * Download an upload's artifacts ZIP. With `resultId`, only the attempts of + * the flow run that result belongs to; the parameter is sent only when set, + * so an unfiltered request is exactly what it always was. + */ async downloadArtifactsZip( baseUrl: string, auth: AuthContext, uploadId: string, results: 'ALL' | 'FAILED', artifactsPath: string = './artifacts.zip', + resultId?: number, ) { + const filtered = resultId !== undefined; // Prefer bundle delivery; fall back to the inline download below. if ( await this.tryBundleDownload( baseUrl, auth, - `/results/${uploadId}/artifacts-bundle?results=${results}`, + `/results/${uploadId}/artifacts-bundle?results=${results}` + + (filtered ? `&resultId=${resultId}` : ''), artifactsPath, 'Failed to download artifacts', + filtered + ? { + // What the API names a bundle it narrowed to one result. + requiredFilenamePrefix: 'artifacts-result-', + unsupportedMessage: + 'Failed to download artifacts: this API does not support downloading one result yet. Download without --result-id or --flow.', + } + : {}, ) ) { return; @@ -525,7 +564,7 @@ export const ApiGateway = { try { const res = await fetch(`${baseUrl}/results/${uploadId}/download`, { - body: JSON.stringify({ results }), + body: JSON.stringify(filtered ? { results, resultId } : { results }), headers: { 'content-type': 'application/json', ...auth.headers, diff --git a/src/mcp/tools/download-artifacts.ts b/src/mcp/tools/download-artifacts.ts index c5705d0..1a41988 100644 --- a/src/mcp/tools/download-artifacts.ts +++ b/src/mcp/tools/download-artifacts.ts @@ -34,6 +34,21 @@ export function registerDownloadArtifacts(server: McpServer): void { .string() .optional() .describe('Local path to write the artifacts zip (default ./artifacts.zip)'), + resultId: z + .number() + .int() + .positive() + .optional() + .describe( + "Only this result's artifacts: its flow's attempts on that one device. Leave unset with flow.", + ), + flow: z + .string() + .min(1) + .optional() + .describe( + 'Only the artifacts of the flow with this file path or name (e.g. flows/login.yaml or login). A name matching several results (one per device) gives a warning listing their ids; pass one as resultId.', + ), report: z .enum(['junit', 'allure', 'html']) .optional() @@ -51,6 +66,10 @@ export function registerDownloadArtifacts(server: McpServer): void { }, async (args) => runTool('dcd_download_artifacts', async () => { + if (args.resultId !== undefined && args.flow !== undefined) { + throw new Error('Pass resultId or flow, not both'); + } + const { apiUrl, auth } = await getContext(); const service = new ReportDownloadService(); const warnings: string[] = []; @@ -66,6 +85,8 @@ export function registerDownloadArtifacts(server: McpServer): void { uploadId: args.uploadId, downloadType: args.type ?? 'ALL', artifactsPath, + flow: args.flow, + resultId: args.resultId, logger: logStderr, warnLogger, }); diff --git a/src/services/report-download.service.ts b/src/services/report-download.service.ts index 1011e0a..68ce24d 100644 --- a/src/services/report-download.service.ts +++ b/src/services/report-download.service.ts @@ -3,6 +3,7 @@ import * as path from 'node:path'; import { ApiGateway } from '../gateways/api-gateway.js'; import type { AuthContext } from '../types/domain/auth.types.js'; import { refreshAuth } from '../utils/auth.js'; +import { deviceFromResultRow } from './results-polling.service.js'; export interface DownloadOptions { auth: AuthContext; @@ -16,6 +17,60 @@ export interface DownloadOptions { export interface ArtifactsDownloadOptions extends DownloadOptions { artifactsPath?: string; downloadType: 'ALL' | 'FAILED'; + /** + * Only this flow's artifacts, by its file path or name: resolved to one + * result with {@link matchFlowResult}. Leave unset with `resultId`. + */ + flow?: string; + /** + * Only the artifacts of the flow run this result belongs to: its first + * attempt and every retry, on that one device. + */ + resultId?: number; +} + +/** A result row as the flow lookup needs it. */ +export interface FlowResultRow { + config?: unknown; + id: number; + retry_of?: null | number; + simulator_name?: null | string; + test_file_name: string; +} + +/** `./flows/login.yaml` -> `flows/login.yaml`, so the forms compare equal. */ +const normaliseFlowPath = (p: string) => p.trim().replace(/^(\.\/)+/, ''); + +/** + * The one run in an upload whose flow file matches `flow`: its full path as + * submitted (`flows/login.yaml`, with or without `./`), its file name + * (`login.yaml`) or its name without the extension (`login`). Only first + * attempts are candidates; the API adds the retries. Throws when nothing + * matches, or when several runs do (a device matrix runs one flow per + * device), listing the result ids to pick from with --result-id. + */ +export function matchFlowResult(rows: FlowResultRow[], flow: string): number { + const wanted = normaliseFlowPath(flow); + const roots = rows.filter((r) => r.retry_of === null || r.retry_of === undefined); + const matches = roots.filter((r) => { + const file = normaliseFlowPath(r.test_file_name); + const base = file.split('/').pop() ?? file; + return file === wanted || base === wanted || base.replace(/\.ya?ml$/i, '') === wanted; + }); + + if (matches.length === 1) return matches[0].id; + if (matches.length === 0) { + throw new Error(`No flow matching '${flow}' in this upload`); + } + + const candidates = matches.map((r) => { + const device = deviceFromResultRow(r); + const label = [device?.name, device?.osVersion].filter(Boolean).join(' '); + return `${r.id} (${r.test_file_name}${label ? `, ${label}` : ''})`; + }); + throw new Error( + `'${flow}' matches ${matches.length} results in this upload; pick one with --result-id: ${candidates.join(', ')}`, + ); } export interface ReportDownloadOptions extends DownloadOptions { @@ -84,6 +139,7 @@ export class ReportDownloadService { downloadType, artifactsPath = './artifacts.zip', debug = false, + flow, logger, warnLogger, } = options; @@ -95,12 +151,30 @@ export class ReportDownloadService { // `dcd cloud` downloads after polling, which can outlast a `dcd login` // token; a failed refresh lands in the warning below like any failure. + const freshAuth = await refreshAuth(auth); + + // A flow name becomes the result id the API filters on. A name that + // matches nothing, or several runs, lands in the warning below. + let { resultId } = options; + if (flow !== undefined) { + const { results } = (await ApiGateway.getResultsForUpload( + apiUrl, + freshAuth, + uploadId, + )) as { results?: FlowResultRow[] }; + resultId = matchFlowResult(results ?? [], flow); + if (debug && logger) { + logger(`[DEBUG] Flow '${flow}' is result ${resultId}`); + } + } + await ApiGateway.downloadArtifactsZip( apiUrl, - await refreshAuth(auth), + freshAuth, uploadId, downloadType, artifactsPath, + resultId, ); if (logger) { diff --git a/test/unit/artifacts-result-filter.test.ts b/test/unit/artifacts-result-filter.test.ts new file mode 100644 index 0000000..2ca9a6e --- /dev/null +++ b/test/unit/artifacts-result-filter.test.ts @@ -0,0 +1,43 @@ +import { expect } from 'chai'; + +import { parseResultFilter } from '../../src/commands/artifacts.js'; + +describe('dcd artifacts --result-id / --flow', () => { + it('passes nothing through when neither is given', () => { + expect(parseResultFilter(undefined, undefined, true)).to.equal(undefined); + expect(parseResultFilter(undefined, undefined, false)).to.equal(undefined); + }); + + it('parses a result id', () => { + expect(parseResultFilter('4446290', undefined, true)).to.equal(4446290); + }); + + it('leaves a flow for the service to resolve', () => { + expect(parseResultFilter(undefined, 'login', true)).to.equal(undefined); + }); + + for (const bad of ['0', '-3', '1.5', 'abc', '12abc', '', '9007199254740993']) { + it(`rejects --result-id '${bad}'`, () => { + expect(() => parseResultFilter(bad, undefined, true)).to.throw( + /--result-id must be a positive whole number/, + ); + }); + } + + it('rejects both at once', () => { + expect(() => parseResultFilter('1', 'login', true)).to.throw(/mutually exclusive/); + }); + + it('needs --download-artifacts', () => { + expect(() => parseResultFilter('1', undefined, false)).to.throw( + '--result-id requires --download-artifacts.', + ); + expect(() => parseResultFilter(undefined, 'login', false)).to.throw( + '--flow requires --download-artifacts.', + ); + }); + + it('rejects an empty --flow', () => { + expect(() => parseResultFilter(undefined, ' ', true)).to.throw(/--flow needs/); + }); +}); diff --git a/test/unit/report-download.service.test.ts b/test/unit/report-download.service.test.ts index 99f4747..06ae46c 100644 --- a/test/unit/report-download.service.test.ts +++ b/test/unit/report-download.service.test.ts @@ -6,6 +6,7 @@ import * as path from 'node:path'; import { ApiGateway } from '../../src/gateways/api-gateway.js'; import { downloadsSucceeded, + matchFlowResult, ReportDownloadService, reportFormatDeprecation, } from '../../src/services/report-download.service.js'; @@ -463,6 +464,8 @@ describe('ReportDownloadService', () => { opts: { manifestBody?: Record; manifestStatus?: number; + /** Rows for `GET /results/{id}?view=summary`, the --flow lookup. */ + results?: Array>; zipBody?: Buffer | string; zipBreaksAfter?: string; zipStatus?: number; @@ -477,6 +480,7 @@ describe('ReportDownloadService', () => { sig: 'SIG', }, manifestStatus = 200, + results = [], zipBody = BUNDLE_ZIP, zipBreaksAfter, zipStatus = 200, @@ -505,6 +509,12 @@ describe('ReportDownloadService', () => { url, }); + if (url.includes('?view=summary')) { + return new Response( + stream(JSON.stringify({ results, statusCode: 200 })), + { headers: { 'content-type': 'application/json' }, status: 200 }, + ); + } if (url.includes('artifacts-bundle') || url.includes('report-bundle')) { return new Response( stream(JSON.stringify(manifestBody)), @@ -725,6 +735,157 @@ describe('ReportDownloadService', () => { url: 'https://cdn.example.com/bundle', }); }); + + describe('one result (--result-id / --flow)', () => { + const filteredManifest = { + bundleUrl: 'https://cdn.example.com/bundle', + entryCount: 3, + filename: 'artifacts-result-41-all.zip', + manifest: '{"version":1}', + sig: 'SIG', + }; + + it('asks the bundle route for the result, and takes the narrowed bundle', async () => { + mockBundleFetch({ manifestBody: filteredManifest }); + const outPath = path.join(tempDir, 'one-result.zip'); + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: outPath, + downloadType: 'ALL', + resultId: 42, + }); + + expect(result.ok).to.equal(true); + expect(calls[0].url).to.equal( + 'https://api.example.com/results/run-42/artifacts-bundle?results=ALL&resultId=42', + ); + expect(fs.readFileSync(outPath).equals(BUNDLE_ZIP)).to.be.true; + }); + + it('sends resultId in the inline body only when set', async () => { + mockBundleFetch({ manifestBody: filteredManifest, manifestStatus: 501 }); + let inlineBody: string | undefined; + const routed = globalThis.fetch; + globalThis.fetch = (async (input: URL | string, init?: RequestInit) => { + if (input.toString().endsWith('/download')) inlineBody = String(init?.body); + return routed(input, init); + }) as typeof fetch; + + await service.downloadArtifacts({ + ...BASE, + artifactsPath: path.join(tempDir, 'one-result-inline.zip'), + downloadType: 'FAILED', + resultId: 42, + }); + + expect(JSON.parse(inlineBody!)).to.deep.equal({ results: 'FAILED', resultId: 42 }); + }); + + it('refuses a whole-upload bundle from an API that ignored the filter', async () => { + // An older API: no resultId support, so the usual bundle name. + mockBundleFetch(); + const outPath = path.join(tempDir, 'old-api.zip'); + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: outPath, + downloadType: 'ALL', + resultId: 42, + }); + + expect(result.ok).to.equal(false); + expect(result.error).to.include('does not support downloading one result'); + // Neither the bundle nor the inline route was downloaded. + expect(calls.map((c) => c.url)).to.deep.equal([ + 'https://api.example.com/results/run-42/artifacts-bundle?results=ALL&resultId=42', + ]); + expect(fs.existsSync(outPath)).to.be.false; + }); + + it('resolves --flow to its result id', async () => { + mockBundleFetch({ + manifestBody: filteredManifest, + results: [ + { id: 41, retry_of: null, test_file_name: './flows/login.yaml' }, + { id: 43, retry_of: 41, test_file_name: './flows/login.yaml' }, + { id: 44, retry_of: null, test_file_name: './flows/checkout.yaml' }, + ], + }); + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: path.join(tempDir, 'one-flow.zip'), + downloadType: 'ALL', + flow: 'login', + }); + + expect(result.ok).to.equal(true); + expect(calls[0].url).to.equal( + 'https://api.example.com/results/run-42?view=summary', + ); + expect(calls[1].url).to.equal( + 'https://api.example.com/results/run-42/artifacts-bundle?results=ALL&resultId=41', + ); + }); + + it('warns, listing the ids, when --flow matches several results', async () => { + mockBundleFetch({ + results: [ + { config: { deviceName: 'Pixel 8', osVersion: '15' }, id: 41, retry_of: null, test_file_name: 'login.yaml' }, + { config: { deviceName: 'iPhone 16', osVersion: '18' }, id: 42, retry_of: null, test_file_name: 'login.yaml' }, + ], + }); + const warnings: string[] = []; + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: path.join(tempDir, 'ambiguous.zip'), + downloadType: 'ALL', + flow: 'login', + warnLogger: (m) => warnings.push(m), + }); + + expect(result.ok).to.equal(false); + expect(warnings[0]).to.include('matches 2 results'); + expect(warnings[0]).to.include('41 (login.yaml, Pixel 8 15)'); + expect(warnings[0]).to.include('42 (login.yaml, iPhone 16 18)'); + expect(calls.some((c) => c.url.includes('artifacts-bundle'))).to.be.false; + }); + }); + }); +}); + +describe('matchFlowResult', () => { + const rows = [ + { id: 1, retry_of: null, test_file_name: './flows/auth/login.yaml' }, + { id: 2, retry_of: 1, test_file_name: './flows/auth/login.yaml' }, + { id: 3, retry_of: null, test_file_name: './flows/checkout.yml' }, + ]; + + for (const flow of [ + './flows/auth/login.yaml', + 'flows/auth/login.yaml', + 'login.yaml', + 'login', + ]) { + it(`matches '${flow}' to the first attempt`, () => { + expect(matchFlowResult(rows, flow)).to.equal(1); + }); + } + + it('matches a .yml flow by its name', () => { + expect(matchFlowResult(rows, 'checkout')).to.equal(3); + }); + + it('fails when nothing matches', () => { + expect(() => matchFlowResult(rows, 'signup')).to.throw( + "No flow matching 'signup' in this upload", + ); + }); + + it('never matches a part of a name', () => { + expect(() => matchFlowResult(rows, 'log')).to.throw(/No flow matching/); }); });