Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/commands/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
2 changes: 1 addition & 1 deletion src/config/flags/output.flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
21 changes: 15 additions & 6 deletions src/gateways/api-gateway.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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 {
/**
Expand Down Expand Up @@ -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<BundleFailure, 'reason'> = {},
Expand Down Expand Up @@ -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,
Expand Down
9 changes: 7 additions & 2 deletions src/mcp/tools/download-artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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;
Expand Down
4 changes: 3 additions & 1 deletion src/services/report-download.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down
14 changes: 10 additions & 4 deletions src/services/telemetry.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down Expand Up @@ -448,19 +453,20 @@ 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) {
if (arg === flag && args[i + 1]) return usable(args[i + 1]);
if (arg.startsWith(`${flag}=`)) return usable(arg.slice(flag.length + 1));
}
}
return DEFAULT_API_URL;
return undefined;
}

export const telemetry = new Telemetry();
34 changes: 34 additions & 0 deletions src/utils/paths.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
55 changes: 55 additions & 0 deletions test/unit/artifacts-path.test.ts
Original file line number Diff line number Diff line change
@@ -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/);
});
});
53 changes: 53 additions & 0 deletions test/unit/report-download.service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
76 changes: 76 additions & 0 deletions test/unit/telemetry-api-url.test.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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=<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');
});
});
Loading