diff --git a/src/commands/artifacts.ts b/src/commands/artifacts.ts index fa33f3f..1732a55 100644 --- a/src/commands/artifacts.ts +++ b/src/commands/artifacts.ts @@ -42,7 +42,7 @@ export const artifactsCommand = defineCommand({ 'artifacts-path': { type: 'string', description: - 'Custom file path for downloaded artifacts (default: ./artifacts.zip). Requires --download-artifacts.', + 'File path for downloaded artifacts, or a folder to save artifacts.zip in (default: ./artifacts.zip). Requires --download-artifacts.', }, 'result-id': { type: 'string', diff --git a/src/config/flags/output.flags.ts b/src/config/flags/output.flags.ts index eeeac3c..b8817a8 100644 --- a/src/config/flags/output.flags.ts +++ b/src/config/flags/output.flags.ts @@ -16,7 +16,7 @@ export const outputFlags = { 'artifacts-path': { type: 'string', description: - 'Custom file path for downloaded artifacts (default: ./artifacts.zip). Requires --download-artifacts.', + 'File path for downloaded artifacts, or a folder to save artifacts.zip in (default: ./artifacts.zip). Requires --download-artifacts.', }, 'junit-path': { type: 'string', diff --git a/src/gateways/api-gateway.ts b/src/gateways/api-gateway.ts index ef65682..e4eeb8b 100644 --- a/src/gateways/api-gateway.ts +++ b/src/gateways/api-gateway.ts @@ -1,6 +1,5 @@ import { createWriteStream, mkdirSync } from 'node:fs'; import { rm } from 'node:fs/promises'; -import { homedir } from 'node:os'; import * as path from 'node:path'; import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; @@ -20,13 +19,9 @@ import type { } from '../types/domain/live.types.js'; import type { TeamSettings } from '../types/domain/team-settings.types.js'; import { components, paths } from '../types/generated/schema.types.js'; +import { expandHome } from '../utils/paths.js'; import { assertCompleteZip, IncompleteZipError } from '../utils/zip-integrity.js'; -/** Expand a leading `~` to the home directory, as the download paths allow. */ -function expandHome(p: string): string { - return p.replace(/^~(?=$|\/|\\)/, homedir()); -} - /** Extra checks a bundle download makes before it trusts the manifest. */ interface BundleDownloadOptions { /** @@ -59,6 +54,16 @@ function errorDetail(error: unknown): Pick< }; } +/** + * A Node file-system error (EACCES, ENOSPC, EISDIR…) on the local side of a + * download. These name a `syscall` and a `path`; network errors from fetch + * carry neither. + */ +function isLocalFileError(error: unknown): boolean { + const e = error as { path?: unknown; syscall?: unknown } | null; + return typeof e?.syscall === 'string' && typeof e?.path === 'string'; +} + function failure( reason: BundleFallbackReason, extra: Omit = {}, @@ -422,6 +427,10 @@ export const ApiGateway = { operation, ); } catch (error) { + // The destination can't be written (a permission, a full disk): the + // inline path would hit the same wall, after making the API build the + // whole ZIP. Report it as it is instead of falling back. + if (isLocalFileError(error)) throw error; return failure('bundle_stream_failed', { ...errorDetail(error), bytes_received: bytesReceived, diff --git a/src/mcp/tools/download-artifacts.ts b/src/mcp/tools/download-artifacts.ts index fde0eaa..f5761ed 100644 --- a/src/mcp/tools/download-artifacts.ts +++ b/src/mcp/tools/download-artifacts.ts @@ -6,6 +6,7 @@ import { z } from 'zod'; import { ReportDownloadService } from '../../services/report-download.service.js'; import { getContext, logStderr } from '../context.js'; import { jsonResult, runTool } from '../helpers.js'; +import { resolveArtifactsPath } from '../../utils/paths.js'; import { localOutput, markWritten } from '../local-files.js'; /** @@ -38,7 +39,9 @@ export function registerDownloadArtifacts(server: McpServer): void { artifactsPath: z .string() .optional() - .describe('Where to write the artifacts zip, inside the working directory (default ./artifacts.zip)'), + .describe( + 'Where to write the artifacts zip, inside the working directory: a file path, or a folder to put artifacts.zip in (default ./artifacts.zip)', + ), resultId: z .number() .int() @@ -85,7 +88,9 @@ export function registerDownloadArtifacts(server: McpServer): void { }; // Both checked before anything is downloaded. - const artifactsPath = localOutput(args.artifactsPath ?? './artifacts.zip'); + // A folder becomes artifacts.zip inside it before the checks, so they + // run on the file that gets written. + const artifactsPath = localOutput(resolveArtifactsPath(args.artifactsPath ?? './artifacts.zip')); const defaultReportPath = args.report ? { allure: 'report.html', html: 'report.zip', junit: 'report.xml' }[args.report] : undefined; diff --git a/src/services/report-download.service.ts b/src/services/report-download.service.ts index 68ce24d..dbf7690 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 { resolveArtifactsPath } from '../utils/paths.js'; import { deviceFromResultRow } from './results-polling.service.js'; export interface DownloadOptions { @@ -137,12 +138,13 @@ export class ReportDownloadService { auth, uploadId, downloadType, - artifactsPath = './artifacts.zip', debug = false, flow, logger, warnLogger, } = options; + // A folder gets artifacts.zip inside it; the message and result name the file. + const artifactsPath = resolveArtifactsPath(options.artifactsPath ?? './artifacts.zip'); try { if (debug && logger) { diff --git a/src/services/telemetry.service.ts b/src/services/telemetry.service.ts index b19b894..d330413 100644 --- a/src/services/telemetry.service.ts +++ b/src/services/telemetry.service.ts @@ -99,11 +99,16 @@ class Telemetry { * be sent. Commands that never reach `resolveAuth` (`--help`, `--version`, * `dcd login` before sign-in completes) will skip telemetry entirely — by * design, since those flows have no identity to attach. + * + * Events go where the command's requests go: the `--api-url` flag first, + * then `opts.apiUrl` (a login's stored API). Taking the login's API first + * sent events from a command aimed at another API (a local one, or dev) to + * that login's API instead. */ configure(opts: { auth: AuthContext; apiUrl?: string }) { if (this.disabled) return; this.config = { - apiUrl: opts.apiUrl ?? inferApiUrlFromArgv(), + apiUrl: argvApiUrl() ?? opts.apiUrl ?? DEFAULT_API_URL, auth: opts.auth, command: this.command, }; @@ -448,11 +453,12 @@ function inferCommandFromArgv(): string { const API_URL_FLAGS = ['--api-url', '--apiURL', '--apiUrl']; -function inferApiUrlFromArgv(): string { +/** The `--api-url` this command was given, if it is one the command would use. */ +function argvApiUrl(): string | undefined { const args = process.argv.slice(2); // Only a URL the command itself would send credentials to: these events // carry them too, and may be sent before the command checks its flag. - const usable = (url: string) => (checkApiUrl(url.trim()).ok ? url.trim() : DEFAULT_API_URL); + const usable = (url: string) => (checkApiUrl(url.trim()).ok ? url.trim() : undefined); for (let i = 0; i < args.length; i++) { const arg = args[i]; for (const flag of API_URL_FLAGS) { @@ -460,7 +466,7 @@ function inferApiUrlFromArgv(): string { if (arg.startsWith(`${flag}=`)) return usable(arg.slice(flag.length + 1)); } } - return DEFAULT_API_URL; + return undefined; } export const telemetry = new Telemetry(); diff --git a/src/utils/paths.ts b/src/utils/paths.ts index 713af1f..d5c6b35 100644 --- a/src/utils/paths.ts +++ b/src/utils/paths.ts @@ -1,5 +1,39 @@ +import { statSync } from 'node:fs'; +import { homedir } from 'node:os'; import * as path from 'node:path'; +/** Expand a leading `~` to the home directory, as the download paths allow. */ +export function expandHome(p: string): string { + return p.replace(/^~(?=$|\/|\\)/, homedir()); +} + +/** The file name an artifacts download gets when it is given a folder. */ +export const DEFAULT_ARTIFACTS_FILENAME = 'artifacts.zip'; + +/** + * Where an artifacts download goes. A folder, meaning one that exists or a + * path ending in a separator, gets `artifacts.zip` inside it. Anything else is + * a file path and is returned unchanged, so calling this twice is harmless. + * Writing to a folder path used to fail with EISDIR, after the download had + * started. + */ +export function resolveArtifactsPath(p: string): string { + const endsWithSeparator = /[/\\]$/.test(p); + if (endsWithSeparator || isDirectory(expandHome(p))) { + return path.join(p, DEFAULT_ARTIFACTS_FILENAME); + } + + return p; +} + +function isDirectory(p: string): boolean { + try { + return statSync(p).isDirectory(); + } catch { + return false; + } +} + /** * Convert an absolute path into the portable './'-prefixed, forward-slash * relative form used as flow keys across submission, metadata maps, and diff --git a/test/unit/artifacts-path.test.ts b/test/unit/artifacts-path.test.ts new file mode 100644 index 0000000..e4ae63b --- /dev/null +++ b/test/unit/artifacts-path.test.ts @@ -0,0 +1,55 @@ +import { expect } from 'chai'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +import { localOutput } from '../../src/mcp/local-files.js'; +import { resolveArtifactsPath } from '../../src/utils/paths.js'; + +describe('resolveArtifactsPath', () => { + let tempDir: string; + + before(() => { + tempDir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-artifacts-path-'))); + }); + + after(() => { + fs.rmSync(tempDir, { force: true, recursive: true }); + }); + + it('puts artifacts.zip inside an existing folder', () => { + expect(resolveArtifactsPath(tempDir)).to.equal(path.join(tempDir, 'artifacts.zip')); + }); + + it('treats a trailing separator as a folder, even one that does not exist yet', () => { + const dir = path.join(tempDir, 'later') + '/'; + expect(resolveArtifactsPath(dir)).to.equal(path.join(tempDir, 'later', 'artifacts.zip')); + }); + + it('leaves a file path alone, existing or not', () => { + const file = path.join(tempDir, 'mine.zip'); + expect(resolveArtifactsPath(file)).to.equal(file); + fs.writeFileSync(file, 'x'); + expect(resolveArtifactsPath(file)).to.equal(file); + }); + + it('is harmless to apply twice', () => { + const once = resolveArtifactsPath(tempDir); + expect(resolveArtifactsPath(once)).to.equal(once); + }); + + it('checks a ~ path against the home folder and keeps the ~', () => { + expect(resolveArtifactsPath('~')).to.equal(path.join('~', 'artifacts.zip')); + }); + + // The MCP tool resolves the folder first, so its write check runs on the + // file. A folder given as is would be refused as "already exists". + it('lets the MCP write check pass for a folder inside the working directory', () => { + const dir = path.join(tempDir, 'out'); + fs.mkdirSync(dir); + expect(localOutput(resolveArtifactsPath(dir), tempDir)).to.equal( + path.join(dir, 'artifacts.zip'), + ); + expect(() => localOutput(dir, tempDir)).to.throw(/already exists/); + }); +}); diff --git a/test/unit/report-download.service.test.ts b/test/unit/report-download.service.test.ts index e1be83d..2e7951e 100644 --- a/test/unit/report-download.service.test.ts +++ b/test/unit/report-download.service.test.ts @@ -617,6 +617,59 @@ describe('ReportDownloadService', () => { expect(fs.readFileSync(outPath).equals(INLINE_ZIP)).to.be.true; }); + // A folder as the artifacts path failed with EISDIR, which the + // CLI took for a broken stream, so it fell back to the inline download + // (the API building the whole ZIP) and then failed the same way. + describe('folder and local file paths', () => { + it('saves artifacts.zip inside an existing folder', async () => { + mockBundleFetch(); + const dir = fs.mkdtempSync(path.join(tempDir, 'shard-')); + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: dir, + downloadType: 'ALL', + }); + + const file = path.join(dir, 'artifacts.zip'); + expect(result).to.include({ ok: true, path: file }); + expect(fs.readFileSync(file).equals(BUNDLE_ZIP)).to.be.true; + expect(fallbacks).to.deep.equal([]); + }); + + it('creates a folder given with a trailing separator', async () => { + mockBundleFetch(); + const dir = path.join(tempDir, 'not-yet', 'here') + path.sep; + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: dir, + downloadType: 'ALL', + }); + + const file = path.join(dir, 'artifacts.zip'); + expect(result).to.include({ ok: true, path: file }); + expect(fs.readFileSync(file).equals(BUNDLE_ZIP)).to.be.true; + }); + + it('reports a destination it cannot write, without falling back', async () => { + mockBundleFetch(); + // A file where a parent folder should be: mkdir fails (ENOTDIR/EEXIST). + const blocker = path.join(tempDir, 'blocker.txt'); + fs.writeFileSync(blocker, 'x'); + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: path.join(blocker, 'artifacts.zip'), + downloadType: 'ALL', + }); + + expect(result.ok).to.be.false; + expect(fallbacks).to.deep.equal([]); + expect(calls.some((c) => c.url.endsWith('/download'))).to.be.false; + }); + }); + describe('records why it fell back', () => { const download = (name: string) => service.downloadArtifacts({ diff --git a/test/unit/telemetry-api-url.test.ts b/test/unit/telemetry-api-url.test.ts new file mode 100644 index 0000000..d4707dd --- /dev/null +++ b/test/unit/telemetry-api-url.test.ts @@ -0,0 +1,76 @@ +import { expect } from 'chai'; + +import { telemetry } from '../../src/services/telemetry.service.js'; + +/** + * Events go to the API the command itself talks to. A login's stored API used + * to win over `--api-url`, so a logged-in run aimed at a local or dev API sent + * its events to the login's API (prod) instead. + */ +describe('telemetry API URL', () => { + const realFetch = globalThis.fetch; + const realArgv = process.argv; + let urls: string[]; + + beforeEach(function () { + // The singleton reads this once, at import. + if (process.env.DCD_TELEMETRY_DISABLED) this.skip(); + + urls = []; + globalThis.fetch = (async (input: unknown) => { + urls.push(String(input)); + return new Response('{}', { status: 202 }); + }) as typeof fetch; + }); + + afterEach(() => { + globalThis.fetch = realFetch; + process.argv = realArgv; + }); + + async function sendWith(argv: string[], storedApiUrl?: string): Promise { + process.argv = ['node', 'dcd', ...argv]; + telemetry.configure({ + apiUrl: storedApiUrl, + auth: { headers: { authorization: 'Bearer t' }, mode: 'bearer' } as never, + }); + telemetry.recordSubmitAttempts(1); + telemetry.recordCommandSuccess(); + await telemetry.flush(); + return urls.pop()!; + } + + it('follows --api-url over the login’s stored API', async () => { + const url = await sendWith( + ['artifacts', '--api-url', 'http://localhost:4321'], + 'https://api.devicecloud.dev', + ); + expect(url).to.equal('http://localhost:4321/cli/logs'); + }); + + it('accepts the --api-url= form', async () => { + const url = await sendWith( + ['artifacts', '--api-url=https://dev-api.devicecloud.dev'], + 'https://api.devicecloud.dev', + ); + expect(url).to.equal('https://dev-api.devicecloud.dev/cli/logs'); + }); + + it('uses the stored API when there is no flag', async () => { + const url = await sendWith(['artifacts'], 'https://dev-api.devicecloud.dev'); + expect(url).to.equal('https://dev-api.devicecloud.dev/cli/logs'); + }); + + it('ignores a flag URL the command would refuse', async () => { + const url = await sendWith( + ['artifacts', '--api-url', 'http://not-local.example'], + 'https://dev-api.devicecloud.dev', + ); + expect(url).to.equal('https://dev-api.devicecloud.dev/cli/logs'); + }); + + it('falls back to the default API with neither', async () => { + const url = await sendWith(['artifacts']); + expect(url).to.equal('https://api.devicecloud.dev/cli/logs'); + }); +});