From a03d4da3c5ea13916dfbfdec1d6a7e8a1b52231c Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Wed, 18 Nov 2026 19:13:11 +0000 Subject: [PATCH 1/7] feat(device): keep agents to their own device sessions When several agents in one organization each drive a device session, one could not tell its session from another's: a call without a session id took the org's only open session, and `dcd device stop --all` stopped every one. - A command that names no session takes yours (the API's `started_by.you`), never someone else's; with none of yours it lists who started each. An API that does not say whose a session is is read as before. - `--force` on the commands that change a session (stop, install, launch, run, tap, type, swipe, press-key, open-link, set-location, request-human): the API refuses an agent changing a session someone else started (LIVE_NOT_YOURS, exit 2) unless it is given. - `stop --all` stops your sessions and leaves the others, naming them; with `--force`, everyone's. - `dcd mcp` names its process on its connection to the hosted tools (x-dcd-client-instance), so the sessions it starts read as its own and a call without a session id takes one of them. - The session fields show who started it. --- src/commands/device.ts | 78 +++++++++++++++++++----- src/gateways/device-gateway.ts | 27 +++++--- src/mcp/bridge.ts | 15 +++++ src/types/domain/device-session.types.ts | 17 ++++++ src/utils/device-output.ts | 44 ++++++++++--- test/unit/device-command.test.ts | 58 ++++++++++++++++++ test/unit/mcp-bridge.test.ts | 15 +++++ 7 files changed, 222 insertions(+), 32 deletions(-) diff --git a/src/commands/device.ts b/src/commands/device.ts index eb7c2c4..046d309 100644 --- a/src/commands/device.ts +++ b/src/commands/device.ts @@ -69,7 +69,18 @@ const commonArgs = { ...apiFlags, json: jsonFlag } as const; const idArg = { type: 'positional', required: false, - description: 'Session id, e.g. brave-teal-otter. Optional when exactly one session is open.', + description: 'Session id, e.g. brave-teal-otter. Optional when you have exactly one open session.', +} as const; + +/** + * For the commands that change a session: one someone else started (another + * person or another API key) is refused with LIVE_NOT_YOURS unless this is + * given. A teammate's agent may be using it. + */ +const forceArg = { + type: 'boolean', + default: false, + description: 'Change a session someone else started (another person or API key)', } as const; interface Ctx { @@ -538,11 +549,12 @@ const statusSub = defineCommand({ }); const stopSub = defineCommand({ - meta: { name: 'stop', description: 'Stop a session, or every open one with --all' }, + meta: { name: 'stop', description: 'Stop a session, or every open one of yours with --all' }, args: { ...commonArgs, id: idArg, - all: { type: 'boolean', default: false, description: "Stop every open session in your org" }, + all: { type: 'boolean', default: false, description: 'Stop every open session of yours (with --force, everyone\'s)' }, + force: forceArg, }, async run({ args }) { const json = Boolean(args.json); @@ -551,26 +563,38 @@ const stopSub = defineCommand({ if (args.all) { if (args.id) throw new CliError('Pass a session id or --all, not both.'); const { sessions } = await DeviceGateway.list(ctx.apiUrl, ctx.auth); + // Yours, or every one with --force: another's may be a teammate's + // agent at work. An API that does not say whose is read as before. + const force = Boolean(args.force); + const mine = sessions.filter((s) => force || !s.started_by || s.started_by.you); + const others = sessions.filter((s) => !mine.includes(s)); const stopped: DeviceSession[] = []; - for (const s of sessions) { - stopped.push((await DeviceGateway.stop(ctx.apiUrl, ctx.auth, s.id)).session); + for (const s of mine) { + stopped.push((await DeviceGateway.stop(ctx.apiUrl, ctx.auth, s.id, force)).session); } return { session: undefined, - data: { stopped }, + data: { left: others.map((s) => s.id), stopped }, print() { logger.log( stopped.length === 0 - ? ui.info('No open device sessions to stop.') + ? ui.info('No open device sessions of yours to stop.') : ui.success(`Stopped ${stopped.map((s) => s.id).join(', ')}`), ); + if (others.length > 0) { + logger.log( + ui.info( + `Left ${others.map((s) => s.id).join(', ')}, started by someone else. Add --force to stop those too.`, + ), + ); + } }, }; } const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id as string | undefined); - const { session } = await DeviceGateway.stop(ctx.apiUrl, ctx.auth, id); + const { session } = await DeviceGateway.stop(ctx.apiUrl, ctx.auth, id, Boolean(args.force)); return { session, data: null, @@ -595,6 +619,7 @@ const installSub = defineCommand({ meta: { name: 'install', description: 'Install a build: a local file (uploaded first) or an https URL' }, args: { ...commonArgs, + force: forceArg, id: idArg, app: { type: 'positional', @@ -623,7 +648,7 @@ const installSub = defineCommand({ id = await resolveSessionId(ctx.apiUrl, ctx.auth, id); const body = binaryId ? { binaryUploadId: binaryId } : await resolveApp(ctx, app!); ctx.progress(ui.running(`Installing on ${colors.highlight(id)}…`)); - const installed = await DeviceGateway.install(ctx.apiUrl, ctx.auth, id, body); + const installed = await DeviceGateway.install(ctx.apiUrl, ctx.auth, id, body, Boolean(args.force)); let { session } = installed; if (args.wait) { ctx.progress(ui.running('Waiting for the device…')); @@ -674,6 +699,7 @@ const launchSub = defineCommand({ meta: { name: 'launch', description: 'Launch an app: the installed one, or a bundle id / package name' }, args: { ...commonArgs, + force: forceArg, id: idArg, appId: { type: 'positional', @@ -695,10 +721,16 @@ const launchSub = defineCommand({ const ctx = await context(args); id = await resolveSessionId(ctx.apiUrl, ctx.auth, id); - const { result, session } = await DeviceGateway.launch(ctx.apiUrl, ctx.auth, id, { - ...(appId && { appId }), - ...(args['clear-state'] ? { clearState: true } : {}), - }); + const { result, session } = await DeviceGateway.launch( + ctx.apiUrl, + ctx.auth, + id, + { + ...(appId && { appId }), + ...(args['clear-state'] ? { clearState: true } : {}), + }, + Boolean(args.force), + ); return { session, data: { result } as { result: DeviceCommandResult }, @@ -791,7 +823,13 @@ async function performAction( ) { const ctx = await context(args); const sessionId = await resolveSessionId(ctx.apiUrl, ctx.auth, id); - const { result, session } = await DeviceGateway.action(ctx.apiUrl, ctx.auth, sessionId, body); + const { result, session } = await DeviceGateway.action( + ctx.apiUrl, + ctx.auth, + sessionId, + body, + Boolean(args.force), + ); return { session, data: { result } as { result: DeviceCommandResult }, @@ -809,6 +847,7 @@ const tapSub = defineCommand({ meta: { name: 'tap', description: 'Tap an element by text or id, or a point on the screen' }, args: { ...commonArgs, + force: forceArg, id: idArg, text: { type: 'string', description: 'The element\'s text, label or hint, matched whole, ignoring case' }, rid: { type: 'string', description: 'The element\'s resource id (rid in `dcd device inspect`)' }, @@ -860,6 +899,7 @@ const typeSub = defineCommand({ meta: { name: 'type', description: 'Type text into the focused field' }, args: { ...commonArgs, + force: forceArg, id: idArg, // Not `required`: citty would reject a missing value before runDeviceCommand, // and --json would then print the top-level error instead of the envelope. @@ -894,6 +934,7 @@ const swipeSub = defineCommand({ meta: { name: 'swipe', description: 'Swipe up, down, left or right, or from one point to another' }, args: { ...commonArgs, + force: forceArg, id: idArg, direction: { type: 'positional', @@ -936,6 +977,7 @@ const pressKeySub = defineCommand({ meta: { name: 'press-key', description: `Press a key: ${DEVICE_KEYS.join(', ')}` }, args: { ...commonArgs, + force: forceArg, id: idArg, key: { type: 'positional', required: false, description: `One of ${DEVICE_KEYS.join(', ')}` }, maestro: maestroArg, @@ -959,6 +1001,7 @@ const openLinkSub = defineCommand({ meta: { name: 'open-link', description: 'Open a link on the device: a deep link into an app, or a web link' }, args: { ...commonArgs, + force: forceArg, id: idArg, // Not `required`, as with `type --text`: a missing link fails inside the envelope. url: { @@ -1000,6 +1043,7 @@ const setLocationSub = defineCommand({ meta: { name: 'set-location', description: "Set the device's GPS position, in decimal degrees" }, args: { ...commonArgs, + force: forceArg, id: idArg, latitude: { type: 'string', description: 'Decimal degrees, north positive (-90 to 90)' }, longitude: { type: 'string', description: 'Decimal degrees, east positive (-180 to 180)' }, @@ -1202,6 +1246,7 @@ const runSub = defineCommand({ }, args: { ...commonArgs, + force: forceArg, id: idArg, flow: { type: 'positional', @@ -1274,7 +1319,7 @@ const runSub = defineCommand({ } ctx.progress(ui.running(`Running ${entry ?? flow ?? 'the flow'} on ${colors.highlight(id)}…`)); - let response = await DeviceGateway.run(ctx.apiUrl, ctx.auth, id, body); + let response = await DeviceGateway.run(ctx.apiUrl, ctx.auth, id, body, Boolean(args.force)); if (response.status === 'running') response = await waitForCommand(ctx, id, response.command_id); const result = response.result ?? { success: false }; @@ -1496,6 +1541,7 @@ const requestHumanSub = defineCommand({ }, args: { ...commonArgs, + force: forceArg, reason: { type: 'positional', // Checked in run, so a missing reason still fails with the --json envelope. @@ -1513,7 +1559,7 @@ const requestHumanSub = defineCommand({ if (reason.length > 500) throw new CliError('The reason is too long: keep it to 500 characters.'); const ctx = await context(args); const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id as string | undefined); - let response = await DeviceGateway.requestHuman(ctx.apiUrl, ctx.auth, id, reason); + let response = await DeviceGateway.requestHuman(ctx.apiUrl, ctx.auth, id, reason, Boolean(args.force)); ctx.progress(ui.success(`Asked for a person on ${id}`)); if (args.wait) response = await waitForHandBack(ctx, id, response); const { human, session } = response; diff --git a/src/gateways/device-gateway.ts b/src/gateways/device-gateway.ts index 4c044c2..a804a19 100644 --- a/src/gateways/device-gateway.ts +++ b/src/gateways/device-gateway.ts @@ -146,6 +146,14 @@ async function request( const sessionPath = (id: string) => `/device/sessions/${encodeURIComponent(id)}`; /** The Agent Devices session API (dcd docs/device-v1-plan.md, section 4.1). */ +/** + * A changing request's body, with `force` when asked: the API refuses an + * agent changing a session someone else started (LIVE_NOT_YOURS) unless it + * says so. Left out otherwise, so an older API sees the body it always did. + */ +const withForce = (body: T, force: boolean): T | (T & { force: true }) => + force ? { ...body, force: true } : body; + export const DeviceGateway = { artifacts( baseUrl: string, @@ -202,8 +210,9 @@ export const DeviceGateway = { auth: AuthContext, id: string, app: { binaryUploadId: string } | { url: string }, + force = false, ): Promise<{ app: DeviceInstalledApp; session: DeviceSession }> { - return request(baseUrl, auth, 'POST', `${sessionPath(id)}/install`, app); + return request(baseUrl, auth, 'POST', `${sessionPath(id)}/install`, withForce(app, force)); }, launch( @@ -211,8 +220,9 @@ export const DeviceGateway = { auth: AuthContext, id: string, body: { appId?: string; clearState?: boolean }, + force = false, ): Promise<{ result: DeviceCommandResult; session: DeviceSession }> { - return request(baseUrl, auth, 'POST', `${sessionPath(id)}/launch`, body); + return request(baseUrl, auth, 'POST', `${sessionPath(id)}/launch`, withForce(body, force)); }, list( @@ -274,8 +284,9 @@ export const DeviceGateway = { auth: AuthContext, id: string, reason: string, + force = false, ): Promise<{ human: DeviceHumanStatus; session: DeviceSession }> { - return request(baseUrl, auth, 'POST', `${sessionPath(id)}/request-human`, { reason }); + return request(baseUrl, auth, 'POST', `${sessionPath(id)}/request-human`, withForce({ reason }, force)); }, /** One typed action: tap, type, swipe, press_key, open_link or set_location. Synchronous: answers with the outcome. */ @@ -284,8 +295,9 @@ export const DeviceGateway = { auth: AuthContext, id: string, body: DeviceActionRequest, + force = false, ): Promise<{ result: DeviceCommandResult; session: DeviceSession }> { - return request(baseUrl, auth, 'POST', `${sessionPath(id)}/actions`, body); + return request(baseUrl, auth, 'POST', `${sessionPath(id)}/actions`, withForce(body, force)); }, run( @@ -295,8 +307,9 @@ export const DeviceGateway = { body: | { env?: Record; flow?: string; flowUploadId: string } | { env?: Record; yaml: string }, + force = false, ): Promise { - return request(baseUrl, auth, 'POST', `${sessionPath(id)}/run`, body); + return request(baseUrl, auth, 'POST', `${sessionPath(id)}/run`, withForce(body, force)); }, screenshot( @@ -319,7 +332,7 @@ export const DeviceGateway = { return request(baseUrl, auth, 'GET', sessionPath(id)); }, - stop(baseUrl: string, auth: AuthContext, id: string): Promise<{ session: DeviceSession }> { - return request(baseUrl, auth, 'DELETE', sessionPath(id)); + stop(baseUrl: string, auth: AuthContext, id: string, force = false): Promise<{ session: DeviceSession }> { + return request(baseUrl, auth, 'DELETE', `${sessionPath(id)}${force ? '?force=true' : ''}`); }, }; diff --git a/src/mcp/bridge.ts b/src/mcp/bridge.ts index 421f388..ffc8480 100644 --- a/src/mcp/bridge.ts +++ b/src/mcp/bridge.ts @@ -15,6 +15,7 @@ * * stdout is the JSON-RPC channel: everything else goes to stderr. */ +import { randomBytes } from 'node:crypto'; import { readFile, stat } from 'node:fs/promises'; import * as path from 'node:path'; @@ -49,6 +50,16 @@ import { createServer } from './server.js'; const INSTRUCTIONS = 'DeviceCloud tools. dcd_* tools run Maestro test suites in the cloud: dcd_list_devices shows what you can test on, dcd_run_cloud_test submits flows (billable), and dcd_get_status follows a run. dcd_get_team_settings reads the team settings and limits. Any other tools describe their own use. Where a tool takes a path to a local file (an app build, a flow file or a directory), this server uploads it for you.'; +/** The header the API reads a connection's name from. */ +export const CLIENT_INSTANCE_HEADER = 'x-dcd-client-instance'; + +/** + * This process's name for its connection to the hosted tools, the same for + * as long as it runs: one `dcd mcp` is one agent's connection, and a + * reconnect must not make its sessions someone else's. + */ +export const BRIDGE_INSTANCE = `dcd-mcp-${randomBytes(8).toString('hex')}`; + /** * How long one forwarded call may take. Longer than dcd_run_cloud_test's * longest wait (3600s) plus an upload. The MCP client calling this server @@ -237,6 +248,10 @@ class RemoteDevices { const { auth } = await getContext(); const headers = new Headers(init?.headers); for (const [key, value] of Object.entries(auth.headers)) headers.set(key, value); + // This process, by name: the sessions it starts are its own + // (started_by.this_client), and a call that names no session takes + // one of them, never a session another process started. + headers.set(CLIENT_INSTANCE_HEADER, BRIDGE_INSTANCE); return fetch(url, { ...init, headers }); }, }), diff --git a/src/types/domain/device-session.types.ts b/src/types/domain/device-session.types.ts index 8f65875..f448279 100644 --- a/src/types/domain/device-session.types.ts +++ b/src/types/domain/device-session.types.ts @@ -49,6 +49,23 @@ export interface DeviceSession { } | null; warnings: string[]; monitor_url: string; + /** + * Who started the session, and how that stands to you. Absent from an API + * that predates it. + */ + started_by?: DeviceSessionStarter; +} + +/** Who started a session. */ +export interface DeviceSessionStarter { + /** The person who started it, when a person did. */ + api_key_name: null | string; + client_label: null | string; + email: null | string; + /** Started from this connection (the same `dcd mcp` process). */ + this_client: boolean; + /** Started by you: this person, or this API key. */ + you: boolean; } /** diff --git a/src/utils/device-output.ts b/src/utils/device-output.ts index 25e545b..9f86a6c 100644 --- a/src/utils/device-output.ts +++ b/src/utils/device-output.ts @@ -1,6 +1,6 @@ import { DeviceApiError, DeviceGateway } from '../gateways/device-gateway.js'; import type { AuthContext } from '../types/domain/auth.types.js'; -import type { DeviceHumanStatus, DeviceSession } from '../types/domain/device-session.types.js'; +import type { DeviceHumanStatus, DeviceSession, DeviceSessionStarter } from '../types/domain/device-session.types.js'; import { CliError, logger } from './cli.js'; import { colors, formatUrl } from './styling.js'; import { type Field, ui } from './ui.js'; @@ -123,9 +123,13 @@ export function deviceProgress(json: boolean): (message: string) => void { } /** - * The default-session rule: `` may be left out when the org has exactly - * one open session. With none, or several, the command is a usage error and - * lists what there is to choose from. + * The default-session rule: `` may be left out when you have exactly one + * open session. Other people's sessions are never the default: a teammate's + * agent may be using one. With none of yours, or several, the command is a + * usage error that lists what there is to choose from. + * + * An API that does not say who started each session (no `started_by`) is + * read the old way: the org's only open session. */ export async function resolveSessionId( apiUrl: string, @@ -136,7 +140,9 @@ export async function resolveSessionId( if (id) return id; const { sessions } = await DeviceGateway.list(apiUrl, auth); - if (sessions.length === 1) return sessions[0].id; + const knowsOwners = sessions.some((s) => s.started_by !== undefined); + const yours = knowsOwners ? sessions.filter((s) => s.started_by?.you) : sessions; + if (yours.length === 1) return yours[0].id; if (sessions.length === 0) { throw new CliError( 'No open device session. Start one with `dcd device start --platform ios|android`.', @@ -144,15 +150,34 @@ export async function resolveSessionId( ); } - const candidates = sessions - .map((s) => ` ${s.id} ${s.platform} ${s.state}${s.client_label ? ` ${s.client_label}` : ''}`) - .join('\n'); + const candidates = (list: DeviceSession[]) => + list + .map((s) => { + const who = s.started_by ? startedByLabel(s.started_by) : ''; + return ` ${s.id} ${s.platform} ${s.state}${s.client_label ? ` ${s.client_label}` : ''}${who ? ` (${who})` : ''}`; + }) + .join('\n'); + if (yours.length === 0) { + throw new CliError( + `None of the open device sessions is yours. Start your own, or name one of these (changing it needs --force):\n${candidates(sessions)}`, + DEVICE_EXIT.usage, + ); + } + throw new CliError( - `${sessions.length} device sessions are open. Name one:\n${candidates}`, + `${yours.length} of your device sessions are open. Name one:\n${candidates(yours)}`, DEVICE_EXIT.usage, ); } +/** Who started a session, in a few words: "you", an email, or an API key's name. */ +export function startedByLabel(starter: DeviceSessionStarter): string { + if (starter.you) return starter.this_client ? 'you, this connection' : 'you'; + if (starter.email) return `started by ${starter.email}`; + if (starter.api_key_name) return `started with API key "${starter.api_key_name}"`; + return 'started by someone else'; +} + export function formatSeconds(seconds: number): string { if (seconds < 60) return `${seconds}s`; const minutes = Math.floor(seconds / 60); @@ -169,6 +194,7 @@ export function sessionFields(session: DeviceSession): Field[] { ]; if (session.model) fields.push(['model', session.model]); if (session.client_label) fields.push(['client', session.client_label]); + if (session.started_by) fields.push(['started', startedByLabel(session.started_by)]); if (session.queue) { const position = session.queue.position === null ? '' : `#${session.queue.position}`; const eta = session.queue.eta_s === null ? '' : `, about ${formatSeconds(session.queue.eta_s)}`; diff --git a/test/unit/device-command.test.ts b/test/unit/device-command.test.ts index 6287add..cdae27e 100644 --- a/test/unit/device-command.test.ts +++ b/test/unit/device-command.test.ts @@ -215,6 +215,8 @@ describe('dcd device', () => { expect(deviceExitCode(apiError(401, null))).to.equal(DEVICE_EXIT.usage); expect(deviceExitCode(new CliError('bad flag'))).to.equal(DEVICE_EXIT.usage); expect(deviceExitCode(apiError(409, 'LIVE_HUMAN_IN_CONTROL'))).to.equal(DEVICE_EXIT.failed); + // Another's session: as a person in control, it could not be done. + expect(deviceExitCode(apiError(409, 'LIVE_NOT_YOURS'))).to.equal(DEVICE_EXIT.failed); expect(deviceExitCode(apiError(503, null))).to.equal(DEVICE_EXIT.failed); expect(deviceExitCode(new Error('network'))).to.equal(DEVICE_EXIT.failed); }); @@ -244,6 +246,27 @@ describe('dcd device', () => { } }); + it("takes your only session, never someone else's", async () => { + stubFetch(() => ({ + body: { sessions: [session('theirs', { started_by: { api_key_name: null, client_label: 'claude-code', email: 'ann@example.com', this_client: false, you: false } }), session('yours', { started_by: { api_key_name: null, client_label: null, email: null, this_client: false, you: true } })] }, + })); + expect(await resolveSessionId(API, auth, undefined)).to.equal('yours'); + }); + + it('is a usage error, naming who started each, when none of the open sessions is yours', async () => { + stubFetch(() => ({ body: { sessions: [session('theirs', { started_by: { api_key_name: null, client_label: 'claude-code', email: 'ann@example.com', this_client: false, you: false } })] } })); + try { + await resolveSessionId(API, auth, undefined); + expect.fail('should have thrown'); + } catch (error) { + expect((error as CliError).exitCode).to.equal(DEVICE_EXIT.usage); + expect((error as Error).message) + .to.include('None of the open device sessions is yours') + .and.include('started by ann@example.com') + .and.include('--force'); + } + }); + it('is a usage error when none is open', async () => { stubFetch(() => ({ body: { sessions: [] } })); try { @@ -755,6 +778,41 @@ describe('dcd device', () => { expect(calls[1].body).to.deep.equal({ appId: 'com.example.app', clearState: true }); }); + it("stop --all stops your sessions and leaves others' unless --force", async () => { + const calls = stubFetch((call) => + call.method === 'GET' + ? { body: { sessions: [session('mine-1', { started_by: { api_key_name: null, client_label: null, email: null, this_client: false, you: true } }), session('theirs', { started_by: { api_key_name: null, client_label: 'claude-code', email: 'ann@example.com', this_client: false, you: false } })] } } + : { body: { session: session(call.url.split('/').pop()!.split('?')[0], { state: 'released' }) } }, + ); + const { out } = await runJson('stop', { all: true }); + expect(calls.filter((c) => c.method === 'DELETE').map((c) => c.url)).to.deep.equal([ + `${API}/device/sessions/mine-1`, + ]); + expect((out.data as { left: string[] }).left).to.deep.equal(['theirs']); + + calls.length = 0; + await runJson('stop', { all: true, force: true }); + expect(calls.filter((c) => c.method === 'DELETE').map((c) => c.url)).to.deep.equal([ + `${API}/device/sessions/mine-1?force=true`, + `${API}/device/sessions/theirs?force=true`, + ]); + }); + + it('--force asks the API to change a session someone else started', async () => { + const calls = stubFetch((call) => + call.method === 'DELETE' + ? { body: { session: session('theirs', { state: 'released' }) } } + : { body: { result: { success: true }, session: session('theirs') } }, + ); + await runJson('stop', { id: 'theirs', force: true }); + expect(calls[0].url).to.equal(`${API}/device/sessions/theirs?force=true`); + await runJson('press-key', { id: 'theirs', key: 'back', force: true }); + expect(calls[1].body).to.deep.equal({ force: true, key: 'back', type: 'press_key' }); + // Without it, nothing extra is sent: an older API sees what it always did. + await runJson('press-key', { id: 'theirs', key: 'back' }); + expect(calls[2].body).to.deep.equal({ key: 'back', type: 'press_key' }); + }); + it('stop --all stops every open session', async () => { const calls = stubFetch((call) => call.method === 'GET' diff --git a/test/unit/mcp-bridge.test.ts b/test/unit/mcp-bridge.test.ts index e946c73..937d1d5 100644 --- a/test/unit/mcp-bridge.test.ts +++ b/test/unit/mcp-bridge.test.ts @@ -12,6 +12,7 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/ import { z } from 'zod'; import { + BRIDGE_INSTANCE, createBridgeServer, explainFailedStart, flowFileBundle, @@ -30,6 +31,8 @@ function startHosted(): Promise<{ http: HttpServer; ignoreReadOnly: boolean; inits: number; + /** The connection name each request carried. */ + instances: (string | undefined)[]; paths: string[]; sessions: Record[]; url: string; @@ -40,6 +43,7 @@ function startHosted(): Promise<{ failStart: false, ignoreReadOnly: false, inits: 0, + instances: [] as (string | undefined)[], paths: [] as string[], sessions: [] as Record[], }; @@ -57,6 +61,7 @@ function startHosted(): Promise<{ } hosted.paths.push(req.url ?? ''); + hosted.instances.push(req.headers['x-dcd-client-instance'] as string | undefined); const chunks: Buffer[] = []; for await (const c of req) chunks.push(c as Buffer); const body = JSON.parse(Buffer.concat(chunks).toString() || '{}'); @@ -178,6 +183,16 @@ describe('dcd mcp bridge', () => { await client.close(); }); + it('names this process on every request, so the sessions it starts are its own', async () => { + const client = await connect(); + await client.listTools(); + await client.callTool({ name: 'inspect_screen', arguments: {} }); + expect(hosted.instances.length).to.be.greaterThan(1); + expect(new Set(hosted.instances)).to.deep.equal(new Set([BRIDGE_INSTANCE])); + expect(BRIDGE_INSTANCE).to.match(/^dcd-mcp-[0-9a-f]{16}$/); + await client.close(); + }); + it('keeps a running call when the session is renewed, and sends the new auth', async () => { const client = await connect(); await client.listTools(); From c817efb27763c860cdc09481859a7d5e68aa2f72 Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Wed, 18 Nov 2026 19:56:35 +0000 Subject: [PATCH 2/7] fix(device): make dcd device safer to script and to drive from an agent Flags and ids - Every subcommand refuses a flag it does not define and names the one meant: `type --text ... --sensetive` typed the text in the clear and exited 0, and `--wiat` started a session without waiting. - An id that can't be a session (`undefined`, `null`, a single word) is a usage error, never sent: a script's unset variable reached the API. - An unknown subcommand under --json prints the device envelope, with the command meant (`press_key` is `press-key`). - request-human takes --reason, so the session id may come first; a lone argument that is an open session's id is refused instead of being sent as the reason. Waits - A poll that fails on the way (a dropped connection, a proxy's 502, a rate limit) is asked again instead of ending the wait. - `run` stops waiting when the session ends under the flow (exit 4), or once the session's time is over, and keeps the flow's command id in the error. - `start --wait --json` names the session on stderr as soon as it exists. - `status --wait` waits for the device and its app. Flows - `run flow.yaml` uploads a flow that uses other files with them, as the MCP bridge already did, and runs it by its path inside the bundle. - With an entry, a bundle holds only the files that flow reaches, not every YAML file under the folder. - Flows in `.maestro/` are found; other dot-folders are still skipped. - A failed run shows the API's own wording of the failure and where it failed (file, line, command, and the runFlow lines that led there). Output and input - Action, launch, inspect, screenshot, logs and run print the session's warnings (idle timeout, crash, end of its time) after their result. - Text from the device, the app or another client is printed without escape sequences or control characters. - A failed action's message is fixed text: it never carries what was typed. - Error answers keep retry_after_s, limit, spent and phase in the --json envelope; an HTML error page is cut to its title. - logs takes --level and --grep, and says when the answer's size cap cut it, or when --follow missed lines. - run takes --env-file, and type takes --text-stdin, so a secret can stay out of the shell history. - `artifacts` with no id takes your most recent session, ended or not. - An empty --app is refused, a build URL ending in .apk or .zip implies the platform, points may be written as 50%,80%, a cost shows its half cent, and status says a person has control once. --- src/commands/device.ts | 560 +++++++++++++++++++---- src/gateways/device-gateway.ts | 61 ++- src/types/domain/device-session.types.ts | 49 +- src/utils/app-upload.ts | 18 + src/utils/device-bundle.ts | 200 ++++++-- src/utils/device-flags.ts | 169 +++++++ src/utils/device-output.ts | 144 +++++- src/utils/device-run.ts | 105 ++++- test/unit/device-bundle.test.ts | 46 +- test/unit/device-command.test.ts | 468 ++++++++++++++++++- test/unit/device-run.test.ts | 54 +++ 11 files changed, 1697 insertions(+), 177 deletions(-) create mode 100644 src/utils/device-flags.ts diff --git a/src/commands/device.ts b/src/commands/device.ts index 046d309..cc0c718 100644 --- a/src/commands/device.ts +++ b/src/commands/device.ts @@ -25,13 +25,14 @@ import { type DeviceSession, type DeviceSwipeDirection, ENDED_STATES, + LOG_LEVELS, type StartDeviceSessionRequest, SWIPE_DIRECTIONS, } from '../types/domain/device-session.types.js'; -import { platformOfAppFile, uploadLocalApp } from '../utils/app-upload.js'; +import { platformOfAppFile, platformOfAppUrl, uploadLocalApp } from '../utils/app-upload.js'; import { refreshAuth, resolveAuth } from '../utils/auth.js'; import { openBrowser } from '../utils/browser.js'; -import { uploadFlowBundle } from '../utils/device-bundle.js'; +import { bundlePath, flowFileBundle, uploadFlowBundle } from '../utils/device-bundle.js'; import { type DeviceArtifactFile, downloadArtifactFiles, @@ -42,10 +43,16 @@ import { } from '../utils/device-artifacts.js'; import { CliError, logger, validateEnum } from '../utils/cli.js'; import { resolveApiUrl } from '../utils/config-store.js'; +import { strictFlags } from '../utils/device-flags.js'; import { + checkSessionId, + DEVICE_EXIT, deviceProgress, humanFields, + printable, printSession, + printWarnings, + resolveRecentSessionId, resolveSessionId, runDeviceCommand, } from '../utils/device-output.js'; @@ -57,9 +64,19 @@ import { ui } from '../utils/ui.js'; const PLATFORMS = ['android', 'ios'] as const; /** What `--name` defaults to: shown in the console and the session timeline. */ const DEFAULT_CLIENT_LABEL = 'dcd-cli'; -const WAIT_POLL_MS = 2000; /** Longer than the API's own queue timeout, so that one is what ends a wait. */ const WAIT_TIMEOUT_MS = 20 * 60 * 1000; +/** The longest a session can run (60 minutes), and a little more: a flow can't run past its session. */ +const MAX_SESSION_MS = 65 * 60 * 1000; + +/** + * How the waits poll. `retryMs` is how long a wait keeps asking through + * failed requests before it gives up, and `retryBaseMs` the first pause + * between tries (doubled each time, up to 15s). `runGraceMs` is how long a + * wait for a flow goes on past its session's maximum duration, for the API + * to end the session. Changed by tests only. + */ +export const deviceTiming = { pollMs: 2000, retryBaseMs: 2000, retryMs: 90_000, runGraceMs: 60_000 }; /** States in which a session takes commands. */ const USABLE_STATES = new Set(['active', 'needs_human', 'ready']); @@ -118,6 +135,52 @@ function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } +/** + * A failure worth asking again: no answer came (a dropped connection, an + * unreadable reply), or the API or a proxy in front of it was busy or briefly + * down. A refusal (a 4xx other than 408 and 429) is final. + */ +export function transientFailure(error: unknown): boolean { + if (error instanceof DeviceApiError) return [408, 429, 500, 502, 503, 504].includes(error.status); + return !(error instanceof CliError); +} + +/** + * One request of a wait, asked again while it fails for a reason that passes + * (transientFailure), for up to deviceTiming.retryMs. A wait of many minutes + * must not end, and lose what it was waiting for, on one failed poll. + */ +async function pollOnce(ctx: Ctx, call: (auth: AuthContext) => Promise): Promise { + const giveUpAt = Date.now() + deviceTiming.retryMs; + for (let attempt = 0; ; attempt++) { + try { + return await call(await freshAuth(ctx)); + } catch (error) { + if (!transientFailure(error) || Date.now() >= giveUpAt) throw error; + const asked = error instanceof DeviceApiError ? Number(error.details.retry_after_s) : Number.NaN; + const pause = + Number.isFinite(asked) && asked > 0 + ? Math.min(asked * 1000, 60_000) + : Math.min(deviceTiming.retryBaseMs * 2 ** attempt, 15_000); + const reason = (error instanceof Error ? error.message : String(error)).split('\n')[0]; + ctx.progress(` ${colors.dim(`a request failed (${reason}); asking again in ${Math.ceil(pause / 1000)}s`)}`); + await sleep(pause); + } + } +} + +/** A session that has ended, as the error that exits 4. */ +function sessionEnded(id: string, session: DeviceSession, while_: string, details: Record = {}) { + return new DeviceApiError( + `Device session ${id} ended ${while_} (${session.release_reason ?? session.state}). An ended session is final: start a new one.`, + 410, + 'LIVE_SESSION_ENDED', + session, + false, + details, + ); +} + /** * Poll until the session takes commands. Reports each change of state (and * queue position) as progress. A session that ends while waiting is exit 4. @@ -126,16 +189,9 @@ async function waitUntilUsable(ctx: Ctx, id: string): Promise { const deadline = Date.now() + WAIT_TIMEOUT_MS; let last = ''; for (;;) { - const { session } = await DeviceGateway.status(ctx.apiUrl, await freshAuth(ctx), id); + const { session } = await pollOnce(ctx, (auth) => DeviceGateway.status(ctx.apiUrl, auth, id)); if (USABLE_STATES.has(session.state)) return session; - if (ENDED_STATES.includes(session.state)) { - throw new DeviceApiError( - `Device session ${id} ended while starting (${session.release_reason ?? session.state}).`, - 410, - 'LIVE_SESSION_ENDED', - session, - ); - } + if (ENDED_STATES.includes(session.state)) throw sessionEnded(id, session, 'while waiting for it to be ready'); const position = session.queue?.position; const line = position ? `${session.state} (position ${position} in the queue)` : session.state; @@ -153,7 +209,7 @@ async function waitUntilUsable(ctx: Ctx, id: string): Promise { ); } - await sleep(WAIT_POLL_MS); + await sleep(deviceTiming.pollMs); } } @@ -166,16 +222,9 @@ async function waitUntilUsable(ctx: Ctx, id: string): Promise { async function waitForInstall(ctx: Ctx, id: string, binaryId: string): Promise { const deadline = Date.now() + WAIT_TIMEOUT_MS; for (;;) { - const { session } = await DeviceGateway.status(ctx.apiUrl, await freshAuth(ctx), id); + const { session } = await pollOnce(ctx, (auth) => DeviceGateway.status(ctx.apiUrl, auth, id)); const install = session.install; - if (ENDED_STATES.includes(session.state)) { - throw new DeviceApiError( - `Device session ${id} ended while installing (${session.release_reason ?? session.state}).`, - 410, - 'LIVE_SESSION_ENDED', - session, - ); - } + if (ENDED_STATES.includes(session.state)) throw sessionEnded(id, session, 'while installing'); // Done, failed, superseded by another install, or an API too old to say. if (!install || install.binary_upload_id !== binaryId || install.status !== 'installing') { @@ -191,7 +240,7 @@ async function waitForInstall(ctx: Ctx, id: string, binaryId: string): Promise { const app = args.app as string | undefined; const binaryId = args['app-binary-id'] as string | undefined; + // `--app "$BUILD"` with BUILD unset would start a billed session with no app. + for (const [flag, value] of [['app', app], ['app-binary-id', binaryId]] as const) { + if (value !== undefined && !String(value).trim()) { + throw new CliError(`--${flag} is empty (a variable that was not set?). Give the build, or leave the flag out.`); + } + } + if (app && binaryId) throw new CliError('Pass --app or --app-binary-id, not both.'); const model = args.model as string | undefined; - const appPlatform = app && !isUrl(app) ? platformOfAppFile(app) : undefined; + const appPlatform = app ? (isUrl(app) ? platformOfAppUrl(app) : platformOfAppFile(app)) : undefined; let platform = validateEnum(args.platform as string | undefined, PLATFORMS, 'platform') ?? appPlatform; if (!platform && !model) { @@ -416,6 +472,14 @@ const startSub = defineCommand({ } ctx.progress(ui.success(`Session ${session.id} started`)); + // Under --json nothing else is printed until the wait ends, which can + // be many minutes. A caller that gives up before then must still know + // which session it started, to use or stop it. + if (json && args.wait) { + process.stderr.write( + `Session ${session.id} started; waiting until it is ready. Stop it with \`dcd device stop ${session.id}\` if you stop waiting.\n`, + ); + } // The session exists and bills from here on: every later failure must // still name it, so the caller can stop it. @@ -498,7 +562,9 @@ const listSub = defineCommand({ ui.fields( sessions.map((s) => [ colors.highlight(s.id), - [s.state, s.platform, s.model, s.client_label].filter(Boolean).join(' '), + printable([s.state, s.platform, s.model, s.client_label].filter(Boolean).join(' '), { + oneLine: true, + }), ]), ), ), @@ -511,12 +577,29 @@ const listSub = defineCommand({ const statusSub = defineCommand({ meta: { name: 'status', description: "A session's state, time left and cost" }, - args: { ...commonArgs, id: idArg }, + args: { + ...commonArgs, + id: idArg, + wait: { + type: 'boolean', + default: false, + description: 'Wait until the session is ready for commands and its app is installed (exit 4 if it ends first)', + }, + }, async run({ args }) { const json = Boolean(args.json); await runDeviceCommand(json, async () => { const ctx = await context(args); const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id as string | undefined); + if (args.wait) { + ctx.progress(ui.running(`Waiting for ${colors.highlight(id)}…`)); + const ready = await waitUntilUsable(ctx, id); + if (ready.install?.status === 'installing') { + ctx.progress(ui.running('Waiting for the app to install…')); + await waitForInstall(ctx, id, ready.install.binary_upload_id); + } + } + // The summary does not say whether a person handed the session back, // so ask. An API without the route (or a failure) just leaves it out. const [{ session }, human] = await Promise.all([ @@ -533,12 +616,16 @@ const statusSub = defineCommand({ logger.log(ui.section('Device session')); printSession(session); if (human?.handed_back) { - logger.log(ui.info(`A person handed it back${human.note ? `: ${human.note}` : ' (no note).'}`)); + logger.log( + ui.info(`A person handed it back${human.note ? `: ${printable(human.note, { oneLine: true })}` : ' (no note).'}`), + ); } // The API's own warning already says a person has control and how // to wait; only add ours when an older API leaves it out. - const apiSaysWaiting = (session.warnings ?? []).some((w) => w.startsWith('Waiting for a human')); + const apiSaysWaiting = (session.warnings ?? []).some( + (w) => w.startsWith('Waiting for a human') || w.startsWith('A person has control'), + ); if (human?.human_in_control && !apiSaysWaiting) { logger.log(ui.warn(`A person has control. Wait with \`dcd device human ${session.id} --wait\`.`)); } @@ -684,6 +771,8 @@ const installSub = defineCommand({ if (!args.wait) { logger.log(ui.note('The device installs it next. Commands answer "not ready" until it is done.')); } + + printWarnings(session); }, }; }); @@ -743,7 +832,8 @@ const launchSub = defineCommand({ ? ui.success(`Launched ${appId ?? 'the app'}`) : `${ui.statusSymbol('FAILED')} Launch failed`, ); - if (result.error) logger.log(colors.error(result.error)); + if (result.error) logger.log(colors.error(printable(result.error))); + printWarnings(session); }, }; }); @@ -761,9 +851,9 @@ const maestroArg = { description: 'Deprecated: has no effect. Device sessions have a single engine', } as const; -/** A percentage of the screen from a flag value, or a usage error. */ +/** A percentage of the screen from a flag value (`50` or `50%`), or a usage error. */ function percentArg(value: unknown, flag: string): number { - const n = typeof value === 'number' ? value : Number(value); + const n = typeof value === 'number' ? value : Number(typeof value === 'string' ? value.trim().replace(/%$/, '') : value); if (typeof value === 'boolean' || value === '' || !Number.isFinite(n) || n < 0 || n > 100) { throw new CliError(`--${flag} must be a number from 0 to 100 (a percentage of the screen).`, 1); } @@ -806,7 +896,7 @@ const LINK = /^[A-Za-z][A-Za-z0-9+.-]*:\S+$/; function pointArg(value: unknown, flag: string): DevicePoint { const parts = typeof value === 'string' ? value.split(',') : []; if (parts.length !== 2) { - throw new CliError(`--${flag} must be "x,y", percentages of the screen, e.g. --${flag} 50,80.`, 1); + throw new CliError(`--${flag} must be "x,y", percentages of the screen, e.g. --${flag} 50,80 or 50%,80%.`, 1); } return { x: percentArg(parts[0].trim(), flag), y: percentArg(parts[1].trim(), flag) }; } @@ -814,12 +904,17 @@ function pointArg(value: unknown, flag: string): DevicePoint { /** * Send one typed action and print its outcome, the way `launch` does: exit 2 * with the result when the device could not do it. + * + * `labels.done` and `labels.failed` are what a person reads, and may name + * what was typed or opened. `labels.failure` is the failure's message when + * the device gave no reason: fixed text, as it goes into the --json envelope + * and the command's failure record, and must never carry typed text. */ async function performAction( args: Record, id: string | undefined, body: DeviceActionRequest, - labels: { done: string; failed: string }, + labels: { done: string; failed: string; failure: string }, ) { const ctx = await context(args); const sessionId = await resolveSessionId(ctx.apiUrl, ctx.auth, id); @@ -834,11 +929,12 @@ async function performAction( session, data: { result } as { result: DeviceCommandResult }, ...(!result.success && { - failure: { code: null, message: result.error || labels.failed }, + failure: { code: null, message: result.error || labels.failure }, }), print() { logger.log(result.success ? ui.success(labels.done) : `${ui.statusSymbol('FAILED')} ${labels.failed}`); - if (result.error) logger.log(colors.error(result.error)); + if (result.error) logger.log(colors.error(printable(result.error))); + printWarnings(session); }, }; } @@ -890,6 +986,7 @@ const tapSub = defineCommand({ return performAction(args, args.id as string | undefined, body, { done: `Tapped ${what}`, failed: `Tap ${what} failed`, + failure: 'The tap failed.', }); }); }, @@ -904,6 +1001,12 @@ const typeSub = defineCommand({ // Not `required`: citty would reject a missing value before runDeviceCommand, // and --json would then print the top-level error instead of the envelope. text: { type: 'string', description: 'What to type' }, + 'text-stdin': { + type: 'boolean', + default: false, + description: + 'Read the text from standard input instead of --text, so a secret stays out of the shell history and the process list', + }, sensitive: { type: 'boolean', default: false, @@ -914,19 +1017,40 @@ const typeSub = defineCommand({ async run({ args }) { const json = Boolean(args.json); await runDeviceCommand(json, async () => { - const text = String(args.text ?? ''); - if (!text) throw new CliError('--text must not be empty.', 1); - const shown = args.sensitive ? `${text.length} character(s)` : `"${text}"`; + if (args['text-stdin'] && args.text !== undefined) { + throw new CliError('Pass --text or --text-stdin, not both.', 1); + } + + const text = args['text-stdin'] ? await readStdinText() : String(args.text ?? ''); + if (!text) throw new CliError(args['text-stdin'] ? 'Standard input was empty: nothing to type.' : '--text must not be empty.', 1); + const shown = args.sensitive ? `${text.length} character(s)` : `"${printable(text, { oneLine: true })}"`; return performAction( args, args.id as string | undefined, { type: 'type', text, ...(args.sensitive ? { sensitive: true } : {}) }, - { done: `Typed ${shown}`, failed: `Typing ${shown} failed` }, + { done: `Typed ${shown}`, failed: `Typing ${shown} failed`, failure: 'Typing failed.' }, ); }); }, }); +/** + * The text piped to this command, without the one line break a shell's + * `echo` adds. Refused at a terminal, where it would wait for typing. + */ +export async function readStdinText(stdin: NodeJS.ReadableStream & { isTTY?: boolean } = process.stdin): Promise { + if (stdin.isTTY) { + throw new CliError( + '--text-stdin reads the text from standard input: pipe it in, e.g. printf %s "$PASSWORD" | dcd device type --text-stdin --sensitive', + 1, + ); + } + + const chunks: Buffer[] = []; + for await (const chunk of stdin) chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : (chunk as Buffer)); + return Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/, ''); +} + const isDirection = (value: unknown): value is DeviceSwipeDirection => typeof value === 'string' && (SWIPE_DIRECTIONS as readonly string[]).includes(value); @@ -968,7 +1092,11 @@ const swipeSub = defineCommand({ body = { type: 'swipe', from: pointArg(args.from, 'from'), to: pointArg(args.to, 'to') }; what = `${String(args.from)} to ${String(args.to)}`; } - return performAction(args, id, body, { done: `Swiped ${what}`, failed: `Swipe ${what} failed` }); + return performAction(args, id, body, { + done: `Swiped ${what}`, + failed: `Swipe ${what} failed`, + failure: 'The swipe failed.', + }); }); }, }); @@ -992,7 +1120,12 @@ const pressKeySub = defineCommand({ if (!key || !(DEVICE_KEYS as readonly string[]).includes(key)) { throw new CliError(`key must be one of ${DEVICE_KEYS.join(', ')}.`, 1); } - return performAction(args, id, { type: 'press_key', key }, { done: `Pressed ${key}`, failed: `Press ${key} failed` }); + return performAction( + args, + id, + { type: 'press_key', key }, + { done: `Pressed ${key}`, failed: `Press ${key} failed`, failure: 'The key press failed.' }, + ); }); }, }); @@ -1033,7 +1166,7 @@ const openLinkSub = defineCommand({ args, id, { type: 'open_link', url, ...(args.sensitive ? { sensitive: true } : {}) }, - { done: `Opened ${shown}`, failed: `Opening ${shown} failed` }, + { done: `Opened ${shown}`, failed: `Opening ${shown} failed`, failure: 'Opening the link failed.' }, ); }); }, @@ -1058,7 +1191,11 @@ const setLocationSub = defineCommand({ args, args.id as string | undefined, { type: 'set_location', latitude, longitude }, - { done: `Location set to ${latitude}, ${longitude}`, failed: 'Setting the location failed' }, + { + done: `Location set to ${latitude}, ${longitude}`, + failed: 'Setting the location failed', + failure: 'Setting the location failed.', + }, ); }); }, @@ -1141,6 +1278,7 @@ const inspectSub = defineCommand({ } if (notes.length > 0) logger.log(ui.note(notes.join(' '))); + printWarnings(session); }, }; }); @@ -1149,11 +1287,14 @@ const inspectSub = defineCommand({ /** One element on one line: what to target it by, then its bounds. */ export function formatElement(el: DeviceScreenElement): string { + // An element's text is whatever the app or a web page shows: never let it + // drive the terminal. + const show = (value: string) => printable(value, { oneLine: true }); const parts: string[] = []; - if (el.txt) parts.push(`"${el.txt}"`); - if (el.a11y && el.a11y !== el.txt) parts.push(`a11y:"${el.a11y}"`); - if (el.rid) parts.push(`id:${el.rid}`); - if (el.hint) parts.push(`hint:"${el.hint}"`); + if (el.txt) parts.push(`"${show(el.txt)}"`); + if (el.a11y && el.a11y !== el.txt) parts.push(`a11y:"${show(el.a11y)}"`); + if (el.rid) parts.push(`id:${show(el.rid)}`); + if (el.hint) parts.push(`hint:"${show(el.hint)}"`); for (const state of ['checked', 'selected', 'focused'] as const) { if (el[state]) parts.push(state); } @@ -1198,6 +1339,7 @@ const screenshotSub = defineCommand({ print() { logger.log(ui.success(`Saved ${filePath}`)); if (!screenshot.fresh) logger.log(ui.note('No new frame came in time; this is the latest.')); + printWarnings(session); }, }; }); @@ -1208,6 +1350,42 @@ function isDirectory(p: string): boolean { return existsSync(p) && statSync(p).isDirectory(); } +/** + * `--env-file`: KEY=VALUE lines, as a .env file has them. Blank lines and + * `#` comments are skipped, `export ` is allowed, and one pair of quotes + * around a value is removed. A bad line is named by its number only: the + * line may hold a secret. + */ +export function parseEnvFile(file: string): Record { + let text: string; + try { + text = readFileSync(file, 'utf8'); + } catch (error) { + throw new CliError(`Could not read --env-file ${file}: ${(error as Error).message}`); + } + + const env: Record = {}; + for (const [index, raw] of text.split(/\r?\n/).entries()) { + const line = raw.trim(); + if (!line || line.startsWith('#')) continue; + const pair = line.startsWith('export ') ? line.slice(7).trimStart() : line; + const eq = pair.indexOf('='); + const key = eq > 0 ? pair.slice(0, eq).trim() : ''; + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) { + throw new CliError(`--env-file ${file}, line ${index + 1}: expected KEY=VALUE.`); + } + + let value = pair.slice(eq + 1).trim(); + if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.at(-1) === value[0]) { + value = value.slice(1, -1); + } + + env[key] = value; + } + + return env; +} + /** `--env KEY=VALUE`, given once or several times. */ export function parseEnvFlags(value: unknown): Record | undefined { if (value === undefined || value === false) return undefined; @@ -1222,19 +1400,67 @@ export function parseEnvFlags(value: unknown): Record | undefine return env; } -/** Wait for a flow that outlasted the API's own wait. */ -async function waitForCommand(ctx: Ctx, id: string, commandId: string): Promise { +/** The latest a flow can still be running: its session's maximum duration, and a little time for the API to end it. */ +function runDeadline(session: DeviceSession, now = Date.now()): number { + const left = session.time_remaining_s; + return typeof left === 'number' && left >= 0 ? now + left * 1000 + deviceTiming.runGraceMs : now + MAX_SESSION_MS; +} + +/** + * Wait for a flow that outlasted the API's own wait. It ends with the flow, + * or with the session: a flow can't outlive its session, so one that ends + * (exit 4), or runs past its maximum duration, stops the wait. + */ +async function waitForCommand(ctx: Ctx, id: string, first: DeviceRunResponse): Promise { + const commandId = first.command_id; + let response = first; + let deadline = runDeadline(first.session); let last = ''; for (;;) { - await sleep(WAIT_POLL_MS); - const response = await DeviceGateway.command(ctx.apiUrl, await freshAuth(ctx), id, commandId); if (response.status !== 'running') return response; - const line = `still running (${response.session.state})`; + const { session } = response; + if (ENDED_STATES.includes(session.state)) { + throw sessionEnded(id, session, 'before the flow finished', { command_id: commandId }); + } + + if (Date.now() >= deadline) { + throw new DeviceApiError( + `Gave up waiting for the flow: session ${id} has run past its maximum duration, yet still says ${session.state}. Check it with \`dcd device status ${id}\`.`, + 408, + null, + session, + false, + { command_id: commandId }, + ); + } + + const line = `still running (${session.state})`; if (line !== last) { last = line; ctx.progress(` ${colors.dim(line)}`); } + + await sleep(deviceTiming.pollMs); + response = await pollOnce(ctx, (auth) => DeviceGateway.command(ctx.apiUrl, auth, id, commandId)); + deadline = Math.min(deadline, runDeadline(response.session)); + } +} + +/** + * An error from waiting on a flow, with the flow's command id kept: the + * flow may still be running, and the id is how to find out. + */ +function withCommandId(error: unknown, id: string, commandId: string): DeviceApiError { + if (error instanceof DeviceApiError && error.details.command_id) return error; + const message = `${error instanceof Error ? error.message : String(error)} The flow may still be running on ${id}: its command id is ${commandId}.`; + if (error instanceof DeviceApiError) { + return new DeviceApiError(message, error.status, error.code, error.session, error.fromApi, { + ...error.details, + command_id: commandId, + }); } + + return new DeviceApiError(message, 502, null, null, false, { command_id: commandId }); } const runSub = defineCommand({ @@ -1263,7 +1489,12 @@ const runSub = defineCommand({ }, env: { type: 'string', - description: 'A variable for the flow, KEY=VALUE, used as ${KEY}. Repeatable. Sent sealed, never stored in plain text', + description: + 'A variable for the flow, KEY=VALUE, used as ${KEY}. Repeatable. Stored encrypted, never shown, and masked in the output. A value given here is in your shell history: use --env-file for secrets', + }, + 'env-file': { + type: 'string', + description: 'Variables for the flow from a file of KEY=VALUE lines (a .env file). --env wins over it for the same name', }, }, async run({ args, rawArgs }) { @@ -1284,8 +1515,12 @@ const runSub = defineCommand({ throw new CliError('--entry is a path inside the directory, e.g. flows/login.yaml.'); } + // A flow file that uses other files (runFlow, runScript, addMedia and + // the like) is uploaded with them, as a bundle. Sent alone, the device + // could not find them. + const bundled = flow && !dir && existsSync(flow) ? flowFileBundle(flow) : null; let yaml = inline; - if (flow && !dir) { + if (flow && !dir && !bundled) { try { yaml = readFileSync(flow, 'utf8'); } catch (error) { @@ -1294,12 +1529,26 @@ const runSub = defineCommand({ } const repeated = collectFlagValues('--env', rawArgs); - const env = parseEnvFlags(repeated.length > 0 ? repeated : args.env); + const envFile = args['env-file'] as string | undefined; + const fromFile = envFile ? parseEnvFile(envFile) : undefined; + const fromFlags = parseEnvFlags(repeated.length > 0 ? repeated : args.env); + const env = fromFile || fromFlags ? { ...fromFile, ...fromFlags } : undefined; const ctx = await context(args); id = await resolveSessionId(ctx.apiUrl, ctx.auth, id); let body: Parameters[3]; - if (dir) { + if (bundled) { + ctx.progress(ui.running(`${flow} uses other files: uploading it with them, from ${colors.highlight(bundled.dir)}…`)); + const bundle = await uploadFlowBundle({ + apiUrl: ctx.apiUrl, + auth: ctx.auth, + dir: bundled.dir, + entry: bundled.entry, + log: ctx.progress, + }); + ctx.progress(ui.success(`Uploaded ${bundle.files} files`)); + body = { flowUploadId: bundle.id, flow: bundlePath(bundled.entry), ...(env && { env }) }; + } else if (dir) { ctx.progress(ui.running(`Uploading the flows in ${colors.highlight(dir)}…`)); const bundle = await uploadFlowBundle({ apiUrl: ctx.apiUrl, @@ -1311,7 +1560,7 @@ const runSub = defineCommand({ ctx.progress(ui.success(`Uploaded ${bundle.files} files`)); body = { flowUploadId: bundle.id, - ...(entry && { flow: entry.split(path.sep).join('/') }), + ...(entry && { flow: bundlePath(path.normalize(entry)) }), ...(env && { env }), }; } else { @@ -1320,7 +1569,13 @@ const runSub = defineCommand({ ctx.progress(ui.running(`Running ${entry ?? flow ?? 'the flow'} on ${colors.highlight(id)}…`)); let response = await DeviceGateway.run(ctx.apiUrl, ctx.auth, id, body, Boolean(args.force)); - if (response.status === 'running') response = await waitForCommand(ctx, id, response.command_id); + if (response.status === 'running') { + try { + response = await waitForCommand(ctx, id, response); + } catch (error) { + throw withCommandId(error, id, response.command_id); + } + } const result = response.result ?? { success: false }; const passed = response.status === 'passed'; @@ -1332,6 +1587,7 @@ const runSub = defineCommand({ }), print() { printRunResult(logger.log, passed, result, entry ?? (flow ? path.basename(flow) : 'flow')); + printWarnings(response.session); }, }; }); @@ -1389,12 +1645,23 @@ export function newLogLines(prev: string[], next: string[]): string[] { const LOGS_FOLLOW_MS = 3000; +/** What the API's answer cap is, for the note that says it cut the answer. */ +const LOGS_CAP = '24 KB'; + const logsSub = defineCommand({ meta: { name: 'logs', description: "The installed app's recent device log lines" }, args: { ...commonArgs, id: idArg, lines: { type: 'string', default: '200', description: 'How many lines, up to 2000' }, + level: { + type: 'string', + description: `Only lines at this level and above: ${LOG_LEVELS.join(' or ')}`, + }, + grep: { + type: 'string', + description: 'Only lines that contain this text, ignoring case', + }, follow: { type: 'boolean', alias: ['f'], @@ -1414,33 +1681,48 @@ const logsSub = defineCommand({ const lines = Number.parseInt(String(args.lines), 10); await runDeviceCommand(json, async () => { if (!Number.isInteger(lines) || lines < 1) throw new CliError('--lines must be a whole number.'); + const level = validateEnum(args.level as string | undefined, LOG_LEVELS, 'level'); + const grep = (args.grep as string | undefined)?.trim() || undefined; + const filter = { ...(level && { level }), ...(grep && { grep }) }; const ctx = await context(args); const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id as string | undefined); - const first = await DeviceGateway.logs(ctx.apiUrl, ctx.auth, id, lines); + const first = await DeviceGateway.logs(ctx.apiUrl, ctx.auth, id, lines, filter); + const cutNote = `Only the newest lines that fit in ${LOGS_CAP} are shown. Ask for fewer with --lines, or narrow them with --level or --grep.`; if (!args.follow) { return { session: first.session, data: { logs: first.logs }, print() { if (first.logs.lines.length === 0) { - logger.log(ui.info(first.logs.source === 'none' ? 'No app installed yet, so no app logs.' : 'No log lines yet.')); + const none = level || grep ? 'No log lines match.' : 'No log lines yet.'; + logger.log(ui.info(first.logs.source === 'none' ? 'No app installed yet, so no app logs.' : none)); + printWarnings(first.session); return; } - for (const line of first.logs.lines) logger.log(line); + for (const line of first.logs.lines) logger.log(printable(line)); + if (first.logs.truncated) logger.log(ui.note(cutNote)); + printWarnings(first.session); }, }; } // --follow: print as lines arrive. Ends when the session does. - for (const line of first.logs.lines) logger.log(line); + for (const line of first.logs.lines) logger.log(printable(line)); let shown = first.logs.lines; let { session } = first; for (;;) { await sleep(LOGS_FOLLOW_MS); try { - const next = await DeviceGateway.logs(ctx.apiUrl, await freshAuth(ctx), id, lines); - for (const line of newLogLines(shown, next.logs.lines)) logger.log(line); + const next = await pollOnce(ctx, (auth) => DeviceGateway.logs(ctx.apiUrl, auth, id, lines, filter)); + const fresh = newLogLines(shown, next.logs.lines); + // Nothing in common with the last answer: more lines came in + // between than one answer holds, and some were never shown. + if (shown.length > 0 && fresh.length > 0 && fresh.length === next.logs.lines.length) { + logger.log(colors.dim(`… some lines were missed: more arrived in ${LOGS_FOLLOW_MS / 1000}s than one read returns (--lines ${lines}, at most ${LOGS_CAP}).`)); + } + + for (const line of fresh) logger.log(printable(line)); shown = next.logs.lines; session = next.session; } catch (error) { @@ -1514,7 +1796,7 @@ async function waitForHandBack(ctx: Ctx, id: string, first: HumanResponse): Prom if (!withPerson(current.human)) return current; await sleep(HUMAN_POLL_MS); - current = await DeviceGateway.human(ctx.apiUrl, await freshAuth(ctx), id); + current = await pollOnce(ctx, (auth) => DeviceGateway.human(ctx.apiUrl, auth, id)); } } @@ -1534,6 +1816,15 @@ const waitForPersonArg = { description: `Wait until the person hands the session back (checks every ${HUMAN_POLL_MS / 1000}s; Ctrl-C stops waiting)`, } as const; +/** Whether text has a session id's shape (it is never a sentence). */ +function isSessionIdShaped(text: string): boolean { + try { + return checkSessionId(text) !== undefined; + } catch { + return false; + } +} + const requestHumanSub = defineCommand({ meta: { name: 'request-human', @@ -1542,23 +1833,54 @@ const requestHumanSub = defineCommand({ args: { ...commonArgs, force: forceArg, - reason: { + message: { type: 'positional', // Checked in run, so a missing reason still fails with the --json envelope. required: false, - description: 'What the person should do, e.g. "Enter the 2FA code sent to the test phone"', + description: + 'What the person should do, e.g. "Enter the 2FA code sent to the test phone". With --reason, this is the session id', }, id: idArg, + reason: { + type: 'string', + description: 'What the person should do; then the session id may come first, as in every other command', + }, wait: waitForPersonArg, }, async run({ args }) { const json = Boolean(args.json); await runDeviceCommand(json, async () => { - const reason = String(args.reason ?? '').trim(); + // ` [id]`, or `[id] --reason `. + const byFlag = typeof args.reason === 'string' ? args.reason : undefined; + let given = args.message as string | undefined; + let sessionId = args.id as string | undefined; + if (byFlag !== undefined) { + if (given !== undefined && sessionId !== undefined) { + throw new CliError('With --reason, give at most one argument: the session id.'); + } + + sessionId ??= given; + given = byFlag; + } + + const reason = String(given ?? '').trim(); if (!reason) throw new CliError('Say what the person should do, e.g. dcd device request-human "Enter the 2FA code".'); if (reason.length > 500) throw new CliError('The reason is too long: keep it to 500 characters.'); const ctx = await context(args); - const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id as string | undefined); + // `request-human brave-teal-otter` meant the session, not a reason: + // sent, it would ask a person to "brave-teal-otter" and hold the + // session for them. + if (byFlag === undefined && sessionId === undefined && isSessionIdShaped(reason)) { + const { sessions } = await DeviceGateway.list(ctx.apiUrl, ctx.auth); + if (sessions.some((s) => s.id === reason)) { + throw new CliError( + `"${reason}" is a session id, not what the person should do. Say what they should do: dcd device request-human ${reason} --reason "Enter the 2FA code".`, + DEVICE_EXIT.usage, + ); + } + } + + const id = await resolveSessionId(ctx.apiUrl, ctx.auth, sessionId); let response = await DeviceGateway.requestHuman(ctx.apiUrl, ctx.auth, id, reason, Boolean(args.force)); ctx.progress(ui.success(`Asked for a person on ${id}`)); if (args.wait) response = await waitForHandBack(ctx, id, response); @@ -1614,7 +1936,10 @@ const artifactsSub = defineCommand({ }, args: { ...commonArgs, - id: idArg, + id: { + ...idArg, + description: 'Session id, e.g. brave-teal-otter. Optional: your most recent session, open or ended.', + }, output: { type: 'string', alias: ['o'], @@ -1630,7 +1955,8 @@ const artifactsSub = defineCommand({ const json = Boolean(args.json); await runDeviceCommand(json, async () => { const ctx = await context(args); - const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id as string | undefined); + // Most often run just after `stop`: your latest session, ended or not. + const id = await resolveRecentSessionId(ctx.apiUrl, ctx.auth, args.id as string | undefined); const { pages, session } = await fetchAllArtifacts(ctx.apiUrl, ctx.auth, id); const files = planArtifactFiles(pages); const pending = pendingArtifacts(pages); @@ -1689,33 +2015,81 @@ const artifactsSub = defineCommand({ }, }); +const subCommands = { + start: strictFlags(startSub), + list: strictFlags(listSub), + status: strictFlags(statusSub), + stop: strictFlags(stopSub), + install: strictFlags(installSub), + launch: strictFlags(launchSub), + tap: strictFlags(tapSub), + type: strictFlags(typeSub), + swipe: strictFlags(swipeSub), + 'press-key': strictFlags(pressKeySub), + 'open-link': strictFlags(openLinkSub), + 'set-location': strictFlags(setLocationSub), + models: strictFlags(modelsSub), + inspect: strictFlags(inspectSub), + screenshot: strictFlags(screenshotSub), + run: strictFlags(runSub), + logs: strictFlags(logsSub), + open: strictFlags(openSub), + artifacts: strictFlags(artifactsSub), + 'request-human': strictFlags(requestHumanSub), + human: strictFlags(humanSub), +}; + +/** The MCP and API names of things `dcd device` calls by another name. */ +const OTHER_NAMES: Record = { + get_device_status: 'status', + get_human_status: 'human', + get_logs: 'logs', + input_text: 'type', + inspect_screen: 'inspect', + install_app: 'install', + launch_app: 'launch', + list_devices: 'list', + start_device: 'start', + stop_device: 'stop', + take_screenshot: 'screenshot', + tap_on: 'tap', +}; + +/** + * The usage error for `dcd device ` when there is no such subcommand, + * with the one meant: `press_key` is `press-key` here. + */ +export function unknownSubcommandError(name: string | undefined): CliError { + const names = Object.keys(subCommands); + if (name === undefined) { + return new CliError(`Name a command: ${names.join(', ')}. See \`dcd device --help\`.`, DEVICE_EXIT.usage); + } + + const dashed = name.replaceAll('_', '-').toLowerCase(); + const meant = OTHER_NAMES[name] ?? (names.includes(dashed) ? dashed : undefined); + return new CliError( + `Unknown command "${name}".${meant ? ` Did you mean \`dcd device ${meant}\`?` : ''} The commands are: ${names.join(', ')}.`, + DEVICE_EXIT.usage, + ); +} + export const deviceCommand = defineCommand({ meta: { name: 'device', description: 'Cloud devices you (or an AI agent) can lease, drive and release [beta]', }, - subCommands: { - start: startSub, - list: listSub, - status: statusSub, - stop: stopSub, - install: installSub, - launch: launchSub, - tap: tapSub, - type: typeSub, - swipe: swipeSub, - 'press-key': pressKeySub, - 'open-link': openLinkSub, - 'set-location': setLocationSub, - models: modelsSub, - inspect: inspectSub, - screenshot: screenshotSub, - run: runSub, - logs: logsSub, - open: openSub, - artifacts: artifactsSub, - 'request-human': requestHumanSub, - human: humanSub, + // Before citty looks the subcommand up: an unknown one under --json gets + // the device envelope (exit 1), not the top-level `{ status, error }`. + async setup({ rawArgs }) { + const name = rawArgs.find((arg) => !arg.startsWith('-')); + if (name !== undefined && name in subCommands) return; + const json = rawArgs.includes('--json') || rawArgs.includes('--json=true'); + // A person who typed just `dcd device` gets citty's usage, with the list. + if (name === undefined && !json) return; + await runDeviceCommand(json, async () => { + throw unknownSubcommandError(name); + }); }, + subCommands, }); diff --git a/src/gateways/device-gateway.ts b/src/gateways/device-gateway.ts index a804a19..5efc5c6 100644 --- a/src/gateways/device-gateway.ts +++ b/src/gateways/device-gateway.ts @@ -8,6 +8,7 @@ import type { DeviceFlowBundle, DeviceHumanStatus, DeviceInstalledApp, + DeviceLogLevel, DeviceLogs, DeviceRunResponse, DeviceScreen, @@ -25,6 +26,13 @@ import { ApiGateway } from './api-gateway.js'; */ export class DeviceApiError extends Error { code: null | string; + /** + * What else the answer said that a script can act on: how long to wait + * (`retry_after_s`), the limit that was hit (`limit`, `spent`), how far + * the device got (`phase`), or the command a wait was for (`command_id`). + * Printed in the --json envelope's `error` beside `code` and `message`. + */ + details: Record; /** * The API itself answered (its `{ statusCode, message }` envelope), not a * proxy in front of it. A proxy's 502 can come after the API did the work. @@ -39,6 +47,7 @@ export class DeviceApiError extends Error { code: null | string, session: DeviceSession | null, fromApi = false, + details: Record = {}, ) { super(message); this.name = 'DeviceApiError'; @@ -46,7 +55,31 @@ export class DeviceApiError extends Error { this.code = code; this.session = session; this.fromApi = fromApi; + this.details = details; + } +} + +/** The fields of an error answer passed on to the caller, when the API sends them. */ +const ERROR_DETAILS = ['retry_after_s', 'limit', 'spent', 'phase'] as const; + +/** The longest error text kept from an answer that is not the API's JSON. */ +const MAX_PLAIN_ERROR = 300; + +/** + * The message for an answer that is not the API's JSON: a proxy's page or + * plain text. An HTML page is cut to its title, as a whole page in a + * terminal, an envelope or a log says nothing a person can read. + */ +export function plainErrorText(text: string, status: number): string { + const trimmed = text.trim(); + if (!trimmed) return `HTTP ${status}`; + if (/^<(?:!doctype|html|head|body)\b/i.test(trimmed) || /<\/html>\s*$/i.test(trimmed)) { + const title = /]*>([^<]*)<\/title>/i.exec(trimmed)?.[1]?.replaceAll(/\s+/g, ' ').trim(); + return `HTTP ${status}: ${title || 'an error page'} (an HTML page, not the API's answer)`; } + + const oneLine = trimmed.replaceAll(/\s+/g, ' '); + return oneLine.length > MAX_PLAIN_ERROR ? `${oneLine.slice(0, MAX_PLAIN_ERROR)}…` : oneLine; } /** How recent an open session must be to count as one a failed start may have made. */ @@ -70,7 +103,12 @@ export function startOutcomeUnknown(error: unknown): boolean { */ async function toDeviceApiError(res: Response, path: string): Promise { const text = await res.text(); - let body: { error?: unknown; message?: unknown; session?: unknown; statusCode?: unknown } = {}; + let body: Record & { + error?: unknown; + message?: unknown; + session?: unknown; + statusCode?: unknown; + } = {}; try { body = JSON.parse(text); } catch { @@ -78,7 +116,7 @@ async function toDeviceApiError(res: Response, path: string): Promise = {}; + if (fromApi) { + for (const key of ERROR_DETAILS) { + const value = body[key]; + if (typeof value === 'number' || typeof value === 'string') details[key] = value; + } + } + + return new DeviceApiError(message, res.status, code, session, fromApi, details); } async function request( @@ -233,13 +279,20 @@ export const DeviceGateway = { return request(baseUrl, auth, 'GET', `/device/sessions${all ? '?all=true' : ''}`); }, + /** The app's recent log lines; `level` and `grep` narrow them (the API ignores both before it knew them). */ logs( baseUrl: string, auth: AuthContext, id: string, lines: number, + filter: { grep?: string; level?: DeviceLogLevel } = {}, ): Promise<{ logs: DeviceLogs; session: DeviceSession }> { - return request(baseUrl, auth, 'GET', `${sessionPath(id)}/logs?lines=${lines}`); + const query = new URLSearchParams({ + lines: String(lines), + ...(filter.level && { level: filter.level }), + ...(filter.grep && { grep: filter.grep }), + }); + return request(baseUrl, auth, 'GET', `${sessionPath(id)}/logs?${query}`); }, models(baseUrl: string, auth: AuthContext): Promise { diff --git a/src/types/domain/device-session.types.ts b/src/types/domain/device-session.types.ts index f448279..9c9ef09 100644 --- a/src/types/domain/device-session.types.ts +++ b/src/types/domain/device-session.types.ts @@ -29,10 +29,23 @@ export interface DeviceSession { model: null | string; client_label: null | string; created_at: string; + /** When a device was assigned (billing starts); null while queued. Absent from older APIs. */ + started_at?: null | string; + /** When it ended; null while open. Absent from older APIs. */ + released_at?: null | string; + /** When its maximum duration ends it; null while queued and once ended. Absent from older APIs. */ + expires_at?: null | string; queue: { eta_s: null | number; position: null | number; - reason: 'fleet_busy' | 'waiting_for_device'; + /** + * Why it waits. org_concurrency_full: the org's tests and sessions hold + * every slot it has; fleet_busy: the platform is at its fleet-wide cap; + * waiting_for_device: waiting for a free device. + */ + reason: 'fleet_busy' | 'org_concurrency_full' | 'waiting_for_device'; + /** Seconds since the session was created. Absent from older APIs. */ + waited_s?: null | number; } | null; time_remaining_s: null | number; idle_remaining_s: null | number; @@ -126,8 +139,30 @@ export interface DeviceInstalledApp { reused: boolean; } +/** + * Where a flow failed, as the device worked it out from the flow files. + * Absent from older APIs, and when only a position is known. + */ +export interface DeviceFailureLocation { + /** The runFlow lines that led there, outermost first, e.g. `main.yaml:4`. */ + call_chain: string[]; + /** The command as written, on one line; null when only a line is known. */ + command: null | string; + /** The file, as a path inside the bundle; `flow.yaml` for a flow sent inline. */ + file: string; + /** 1-based line in that file. */ + line: number; +} + +/** Where a failure was: one place, or several that all fit the error. */ +export interface DeviceFailedAt { + failed_at?: DeviceFailureLocation; + /** Two or more commands fit the error, and any of them may have failed. */ + failed_at_candidates?: DeviceFailureLocation[]; +} + /** One flow of a run, as newer APIs report it in `result.flows`. */ -export interface DeviceFlowResult { +export interface DeviceFlowResult extends DeviceFailedAt { error: null | string; /** The flow's path inside the bundle; null for a single flow. */ file: null | string; @@ -185,7 +220,7 @@ export const DEVICE_KEYS = [ export const SWIPE_DIRECTIONS: readonly DeviceSwipeDirection[] = ['up', 'down', 'left', 'right']; /** The result of a typed action, a launch or a run. */ -export interface DeviceCommandResult { +export interface DeviceCommandResult extends DeviceFailedAt { error?: string; /** Each flow of a run. Absent from APIs older than this field. */ flows?: DeviceFlowResult[]; @@ -245,10 +280,18 @@ export interface DeviceRunResponse { export interface DeviceLogs { app_id: null | string; lines: string[]; + /** How many lines were looked through before the filters. Absent from older APIs. */ + scanned?: number; /** logcat, ios-unified-log, or none before an app is installed. */ source: string; + /** The answer's size cap (24 KB) dropped older lines. Absent when it did not. */ + truncated?: true; } +/** The filters GET .../logs takes. */ +export const LOG_LEVELS = ['warning', 'error'] as const; +export type DeviceLogLevel = (typeof LOG_LEVELS)[number]; + /** A short-lived download link for one stored artifact. */ export interface DeviceArtifactLink { bytes: null | number; diff --git a/src/utils/app-upload.ts b/src/utils/app-upload.ts index 86c0631..e60ce46 100644 --- a/src/utils/app-upload.ts +++ b/src/utils/app-upload.ts @@ -17,6 +17,24 @@ export function platformOfAppFile(filePath: string): 'android' | 'ios' | undefin return undefined; } +/** + * The platform a build at a URL is for, from the file name in its path: + * install from a URL takes an Android .apk or a zipped iOS simulator .app. + * Undefined when the path names neither (a signed link with no file name). + */ +export function platformOfAppUrl(url: string): 'android' | 'ios' | undefined { + let pathname: string; + try { + pathname = decodeURIComponent(new URL(url).pathname).toLowerCase(); + } catch { + return undefined; + } + + if (pathname.endsWith('.apk')) return 'android'; + if (pathname.endsWith('.zip')) return 'ios'; + return undefined; +} + export interface UploadLocalAppOptions { apiUrl: string; auth: AuthContext; diff --git a/src/utils/device-bundle.ts b/src/utils/device-bundle.ts index f17393a..9c682b4 100644 --- a/src/utils/device-bundle.ts +++ b/src/utils/device-bundle.ts @@ -1,10 +1,11 @@ import { createHash } from 'node:crypto'; -import { existsSync, readdirSync } from 'node:fs'; +import { existsSync, readdirSync, realpathSync } from 'node:fs'; import * as path from 'node:path'; import { DeviceGateway } from '../gateways/device-gateway.js'; import { compressFilesFromRelativePath } from '../methods.js'; import { resolveIncludedPaths } from '../services/execution-plan.service.js'; +import { computeCommonRoot } from '../services/flow-paths.js'; import { isWorkspaceConfigFile, loadWorkspaceConfig, @@ -25,43 +26,121 @@ import { /** The API's limit on a bundle (dcd plan 2.5b). */ export const MAX_BUNDLE_BYTES = 50 * 1024 * 1024; -/** Never bundled: version control, dependencies, and other dot-folders. */ -function skipped(relativePath: string): boolean { - return relativePath - .split(path.sep) - .some((part) => part === 'node_modules' || (part.startsWith('.') && part !== '.')); +/** + * Never walked for flows: dependencies, version control and other tools' + * dot-folders and dot-files. `.maestro`, where Maestro keeps flows by + * convention, is walked. + */ +function skipped(name: string): boolean { + return name === 'node_modules' || (name.startsWith('.') && name !== '.maestro'); } const YAML_FILE = /\.ya?ml$/i; -/** Every file under `dir`, relative to it. */ +/** Every file under `dir`, relative to it, without going into the folders `skipped` names. */ function allFiles(dir: string): string[] { - return readdirSync(dir, { recursive: true, withFileTypes: true }) - .filter((entry) => entry.isFile()) - .map((entry) => path.relative(dir, path.join(entry.parentPath, entry.name))) - .filter((file) => !skipped(file)); + const files: string[] = []; + const walk = (relative: string) => { + for (const entry of readdirSync(path.join(dir, relative), { withFileTypes: true })) { + if (skipped(entry.name)) continue; + const child = relative ? path.join(relative, entry.name) : entry.name; + if (entry.isDirectory()) walk(child); + else if (entry.isFile()) files.push(child); + } + }; + + walk(''); + return files; } /** - * The files under `dir` a bundle needs, relative to it, in a stable order: - * every YAML file (flows, subflows, config), the files the flows use - * (runScript, addMedia, assertScreenshot and the like), and config's - * includedPaths. Nothing else: an agent's samples folder sent 265 MB of .apk - * and .zip files with its flows. - * - * `entry` is the one flow that will run. Its files must all be inside `dir`. - * Without an entry every flow may run, so that goes for all of them. Another - * flow's missing file doesn't stop the entry running, so it is left out. + * The files a flow reaches: the flow, the files it uses (runFlow, runScript, + * addMedia, assertScreenshot and the like), and the files those use in turn. + * Absolute paths, the flow first. `problems` are the files it names that do + * not exist. A flow that can't be read throws; a YAML file it uses that is + * not a flow (a data file) is taken as it is. */ -export function bundleFiles(dir: string, entry?: string, warn: (message: string) => void = () => {}): string[] { - const root = path.resolve(dir); - const yamlFiles = allFiles(dir).filter((file) => YAML_FILE.test(file)); - const entryFile = entry === undefined ? undefined : path.normalize(entry); - if (entryFile !== undefined && !yamlFiles.includes(entryFile)) { - throw new CliError(`No flow ${entry} in ${dir}.`); +export function reachableFiles(flow: string): { files: string[]; problems: string[] } { + const first = path.resolve(flow); + const files: string[] = []; + const problems: string[] = []; + const queue = [first]; + const seen = new Set(); + while (queue.length > 0) { + const file = queue.shift()!; + if (seen.has(file)) continue; + seen.add(file); + files.push(file); + if (!YAML_FILE.test(file) || (file !== first && isWorkspaceConfigFile(file))) continue; + let deps: ReturnType; + try { + const { config, testSteps } = readTestYamlFileAsJson(file); + deps = processDependencies({ config, input: file, testSteps }); + } catch (error) { + if (file === first) throw new CliError((error as Error).message); + continue; + } + + problems.push(...deps.allErrors); + for (const dep of deps.allFiles) { + if (existsSync(dep)) queue.push(path.normalize(dep)); + } + } + + return { files, problems }; +} + +/** + * For a single flow file that uses other files (runFlow, runScript, addMedia + * and the like): the folder to upload as a bundle, and the file's path + * inside it. Sent as yaml on its own, the flow would fail on the device with + * an invalid file path, because the files it uses would not be there. The + * folder is the closest one that holds every file the flow reaches; only + * those files are uploaded. Null when the flow uses no other files, or can't + * be read (the device reports that itself). + */ +export function flowFileBundle(file: string): { dir: string; entry: string } | null { + const absolute = path.resolve(file); + let reached: ReturnType; + try { + reached = reachableFiles(absolute); + } catch { + return null; } - const needed = new Set(yamlFiles); + // A missing file goes this way too, so the upload names it. + if (reached.files.length === 1 && reached.problems.length === 0) return null; + const dir = computeCommonRoot([absolute], reached.files.slice(1)) || path.dirname(absolute); + return { dir, entry: path.relative(dir, absolute) }; +} + +/** A path inside a bundle as the API takes it: forward slashes on every platform. */ +export function bundlePath(relative: string): string { + return relative.split(path.sep).join('/'); +} + +/** + * The files under `dir` a bundle needs, relative to it, in a stable order. + * + * With an `entry`, the one flow that will run: that flow and the files it + * reaches (reachableFiles), which must all be inside `dir`. Nothing else is + * read or sent, so a folder high above the flow (a home directory, say) + * costs nothing and gives nothing away. + * + * Without one, every flow may run: every YAML file (flows, subflows, config) + * and the files they use. Either way, config's includedPaths too, and nothing + * else: an agent's samples folder sent 265 MB of .apk and .zip files with + * its flows. + */ +export function bundleFiles( + dir: string, + entry?: string, + warn: (message: string) => void = () => {}, + confineTo?: string, +): string[] { + const root = path.resolve(dir); + const configs = ['config.yaml', 'config.yml'].filter((name) => existsSync(path.join(root, name))); + const needed = new Set(); const problems: string[] = []; const add = (absolute: string, strict: boolean, from: string) => { const relative = path.relative(root, absolute); @@ -73,32 +152,57 @@ export function bundleFiles(dir: string, entry?: string, warn: (message: string) needed.add(relative); }; - for (const file of yamlFiles) { - const absolute = path.join(root, file); - const strict = entryFile === undefined || entryFile === file; - if (isWorkspaceConfigFile(absolute)) continue; - let deps: ReturnType; - try { - const { config, testSteps } = readTestYamlFileAsJson(absolute); - deps = processDependencies({ config, input: absolute, testSteps }); - } catch (error) { - // Not a flow (a data file, say), or one Maestro will report itself. - if (entryFile === file) throw new CliError((error as Error).message); - continue; - } + if (entry === undefined) { + const yamlFiles = allFiles(dir).filter((file) => YAML_FILE.test(file)); + for (const file of yamlFiles) needed.add(file); + for (const file of yamlFiles) { + const absolute = path.join(root, file); + if (isWorkspaceConfigFile(absolute)) continue; + let deps: ReturnType; + try { + const { config, testSteps } = readTestYamlFileAsJson(absolute); + deps = processDependencies({ config, input: absolute, testSteps }); + } catch { + // Not a flow (a data file, say), or one Maestro will report itself. + continue; + } - if (strict) problems.push(...deps.allErrors); - for (const dep of deps.allFiles) { - if (existsSync(dep)) add(dep, strict, file); + problems.push(...deps.allErrors); + for (const dep of deps.allFiles) { + if (existsSync(dep)) add(dep, true, file); + } + } + } else { + const entryFile = path.resolve(root, path.normalize(entry)); + const inside = path.relative(root, entryFile); + if (inside.startsWith('..') || path.isAbsolute(inside) || !YAML_FILE.test(entryFile) || !existsSync(entryFile)) { + throw new CliError(`No flow ${entry} in ${dir}.`); } + + const reached = reachableFiles(entryFile); + problems.push(...reached.problems); + for (const file of reached.files) add(file, true, entry); + for (const name of configs) needed.add(name); } - for (const name of ['config.yaml', 'config.yml']) { - if (!yamlFiles.includes(name)) continue; + for (const name of configs) { const config = loadWorkspaceConfig(path.join(root, name), warn); for (const file of resolveIncludedPaths(config, root, warn)) add(file, true, name); } + // For an agent's call (the dcd mcp bridge): a file that is a link to one + // outside the folder it may read would send that file's contents. + if (confineTo !== undefined) { + const allowed = realpathSync(confineTo); + for (const file of needed) { + const real = realpathSync(path.join(root, file)); + const relative = path.relative(allowed, real); + if (relative.startsWith('..') || path.isAbsolute(relative)) { + problems.push(`${file} is a link to a file outside ${confineTo}, which is not sent.`); + } + } + } + if (problems.length > 0) throw new CliError(problems.join('\n')); return [...needed].sort(); } @@ -132,6 +236,8 @@ export interface UploadFlowBundleOptions { /** The one flow that will run, a path inside `dir`. Omitted, all of them. */ entry?: string; log: (message: string) => void; + /** Send nothing that resolves outside this folder (links included). */ + confineTo?: string; } /** @@ -145,8 +251,8 @@ export interface UploadFlowBundleOptions { export async function uploadFlowBundle( opts: UploadFlowBundleOptions, ): Promise { - const { apiUrl, auth, dir, entry, log } = opts; - const files = bundleFiles(dir, entry, log); + const { apiUrl, auth, confineTo, dir, entry, log } = opts; + const files = bundleFiles(dir, entry, log, confineTo); if (!files.some((f) => YAML_FILE.test(f))) { throw new CliError(`No flow files (.yaml) in ${dir}.`); } diff --git a/src/utils/device-flags.ts b/src/utils/device-flags.ts new file mode 100644 index 0000000..0f5d973 --- /dev/null +++ b/src/utils/device-flags.ts @@ -0,0 +1,169 @@ +import type { ArgsDef, CommandContext, CommandDef } from 'citty'; + +import { CliError } from './cli.js'; +import { DEVICE_EXIT, runDeviceCommand } from './device-output.js'; + +/* + * citty accepts any flag and ignores the ones a command does not define. For + * `dcd device` that is unsafe: `type --text hunter2 --sensetive` typed a + * password in plain text and exited 0, and `--wiat` started a session + * without waiting. So every `dcd device` subcommand refuses a flag it does + * not know, and suggests the one that was meant. + */ + +const camel = (name: string): string => name.replaceAll(/-([a-z0-9])/g, (_, c: string) => c.toUpperCase()); +const kebab = (name: string): string => + name.replaceAll(/([a-z0-9])([A-Z])/g, '$1-$2').replaceAll(/([A-Z])([A-Z][a-z])/g, '$1-$2').toLowerCase(); + +interface FlagSpec { + /** Every spelling that sets it: its name, citty's camel and kebab forms, its aliases. */ + names: Set; + /** Its name as the help shows it. */ + primary: string; + /** It takes a value, so the token after `--flag` is that value. */ + takesValue: boolean; +} + +function flagSpecs(args: ArgsDef): FlagSpec[] { + return Object.entries(args) + .filter(([, def]) => def.type !== 'positional') + .map(([name, def]) => { + const alias = (def as { alias?: string | string[] }).alias; + const aliases = Array.isArray(alias) ? alias : alias ? [alias] : []; + const names = new Set(); + for (const n of [name, ...aliases]) { + names.add(n); + names.add(camel(n)); + names.add(kebab(n)); + } + + return { names, primary: name, takesValue: def.type === 'string' || def.type === 'enum' }; + }); +} + +/** The edit distance between two words, a swap of neighbours counting as one edit. */ +export function editDistance(a: string, b: string): number { + const d: number[][] = Array.from({ length: a.length + 1 }, (_, i) => + Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)), + ); + for (let i = 1; i <= a.length; i++) { + for (let j = 1; j <= b.length; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1); + } + } + } + + return d[a.length][b.length]; +} + +/** Words other tools use for a flag of ours. */ +const SYNONYMS: Record = { secret: 'sensitive', secure: 'sensitive' }; + +/** Flags people carry over from `dcd live` and the MCP tools, for the session id. */ +const SESSION_FLAGS = new Set(['id', 'session', 'session-id', 'sessionId', 'session_id']); + +/** What to say about one unknown flag: the flag meant, when it is clear. */ +function hint(given: string, specs: FlagSpec[], positionals: string[]): string { + const bare = given.replace(/^-+/, '').replace(/=.*$/, ''); + if (SESSION_FLAGS.has(bare) && positionals.includes('id')) { + return ' The session id is an argument, not a flag: `dcd device `.'; + } + + const negated = bare.startsWith('no-'); + const base = kebab(negated ? bare.slice(3) : bare); + const synonym = SYNONYMS[base]; + if (synonym && specs.some((s) => s.primary === synonym)) return ` Did you mean --${negated ? 'no-' : ''}${synonym}?`; + let best: { distance: number; name: string } | null = null; + for (const spec of specs) { + const distance = editDistance(base, spec.primary); + if (!best || distance < best.distance) best = { distance, name: spec.primary }; + } + + // Close enough to be a slip of the keys, not another word. + if (best && best.distance <= 2 && best.distance < base.length / 2) { + return ` Did you mean --${negated ? 'no-' : ''}${best.name}?`; + } + + return ''; +} + +/** + * The flags in `rawArgs` that `args` does not define, each as typed. A + * value after a flag that takes one is skipped, so `--yaml "- launchApp"` + * and `--longitude -0.1278` are read as values. `--` ends the flags. + */ +export function unknownFlags(rawArgs: string[], args: ArgsDef): string[] { + const specs = flagSpecs(args); + const find = (name: string) => specs.find((s) => s.names.has(name) || s.names.has(camel(name))); + const unknown: string[] = []; + for (let i = 0; i < rawArgs.length; i++) { + const token = rawArgs[i]; + if (token === '--') break; + if (!token.startsWith('-') || token === '-' || /^-\d/.test(token)) continue; + const eq = token.indexOf('='); + const name = (eq === -1 ? token : token.slice(0, eq)).replace(/^-{1,2}/, ''); + if (token.startsWith('--')) { + const spec = find(name) ?? (name.startsWith('no-') ? find(name.slice(3)) : undefined); + if (!spec) unknown.push(token.slice(0, eq === -1 ? undefined : eq)); + else if (spec.takesValue && eq === -1 && !name.startsWith('no-')) i++; + continue; + } + + // Short flags, e.g. -o file or -f: each letter must be one of ours, and + // one that takes a value ends the group (its value is the rest, or the + // next token). + for (let k = 0; k < name.length; k++) { + const spec = find(name[k]); + if (!spec) { + unknown.push(`-${name[k]}`); + break; + } + + if (spec.takesValue) { + if (k === name.length - 1 && eq === -1) i++; + break; + } + } + } + + return unknown; +} + +/** The usage error for unknown flags, or null when there are none. */ +export function unknownFlagsError(rawArgs: string[], args: ArgsDef): CliError | null { + const unknown = unknownFlags(rawArgs, args); + if (unknown.length === 0) return null; + const specs = flagSpecs(args); + const positionals = Object.entries(args) + .filter(([, def]) => def.type === 'positional') + .map(([name]) => name); + const lines = unknown.map((flag) => `Unknown flag ${flag}.${hint(flag, specs, positionals)}`); + return new CliError(`${lines.join(' ')} See --help for the flags this command takes.`, DEVICE_EXIT.usage); +} + +/** + * A `dcd device` subcommand that refuses unknown flags before it runs: with + * --json the refusal is the usual envelope, exit 1. + */ +export function strictFlags(sub: CommandDef): CommandDef { + const { run } = sub; + if (!run) return sub; + return { + ...sub, + async run(context: CommandContext) { + const args = (sub.args ?? {}) as ArgsDef; + const problem = unknownFlagsError(context.rawArgs ?? [], args); + if (problem) { + await runDeviceCommand(Boolean((context.args as Record).json), async () => { + throw problem; + }); + return; + } + + return run(context); + }, + }; +} diff --git a/src/utils/device-output.ts b/src/utils/device-output.ts index 9f86a6c..c582af4 100644 --- a/src/utils/device-output.ts +++ b/src/utils/device-output.ts @@ -1,3 +1,5 @@ +import { stripVTControlCharacters } from 'node:util'; + import { DeviceApiError, DeviceGateway } from '../gateways/device-gateway.js'; import type { AuthContext } from '../types/domain/auth.types.js'; import type { DeviceHumanStatus, DeviceSession, DeviceSessionStarter } from '../types/domain/device-session.types.js'; @@ -53,7 +55,12 @@ export interface DeviceEnvelope { ok: boolean; session?: DeviceSession | null; data: T | null; - error: { code: null | string; message: string } | null; + /** + * With `code` and `message`, whatever else the API said that a script can + * act on: `retry_after_s`, `limit`, `spent`, `phase`, and `command_id` when + * a wait for a flow gave up. + */ + error: ({ code: null | string; message: string } & Record) | null; } export interface DeviceOutcome { @@ -90,7 +97,10 @@ export async function runDeviceCommand( ok: false, session: error instanceof DeviceApiError ? error.session : null, data: null, - error: { code: error instanceof DeviceApiError ? error.code : null, message }, + error: + error instanceof DeviceApiError + ? { ...error.details, code: error.code, message } + : { code: null, message }, }; logger.json(envelope); logger.fail(message, exitCode); @@ -136,7 +146,7 @@ export async function resolveSessionId( auth: AuthContext, given: string | undefined, ): Promise { - const id = given?.trim(); + const id = checkSessionId(given); if (id) return id; const { sessions } = await DeviceGateway.list(apiUrl, auth); @@ -170,14 +180,109 @@ export async function resolveSessionId( ); } +/** + * A session id: its name (`brave-teal-otter`, `brave-teal-otter-0042`, or an + * older `teal-otter-42`), or its number. Words joined by dashes, so a single + * word is never one. + */ +const SESSION_ID = /^(?:[a-z][a-z0-9]*(?:-[a-z0-9]+)+|\d+)$/; + +/** What a shell or a script prints for a value it does not have. */ +const UNSET_WORDS = new Set(['', 'null', 'undefined', 'none', 'nan', 'nil', '[object object]']); + +/** + * The id given, trimmed, or undefined when none was. A value that cannot be + * a session id is a usage error, never sent: `undefined` from a script's + * unset variable would otherwise reach the API as a session name. + */ +export function checkSessionId(given: string | undefined): string | undefined { + if (given === undefined) return undefined; + const id = given.trim(); + if (!id) return undefined; + if (SESSION_ID.test(id)) return id; + const unset = UNSET_WORDS.has(id.toLowerCase()); + throw new CliError( + unset + ? `"${id}" is not a session id: it looks like a variable that was not set. A session id looks like brave-teal-otter; \`dcd device list\` shows yours.` + : `"${id}" is not a session id. A session id looks like brave-teal-otter; \`dcd device list\` shows yours.`, + DEVICE_EXIT.usage, + ); +} + +/** + * For commands that read what a session left behind (`artifacts`): the + * session given, or else your most recent one, ended or not. Others' sessions + * are never the default. An API that does not say who started each is read + * the old way: the only session in the list. + */ +export async function resolveRecentSessionId( + apiUrl: string, + auth: AuthContext, + given: string | undefined, +): Promise { + const id = checkSessionId(given); + if (id) return id; + + // Open sessions and those that ended in the last day, newest first by start. + const { sessions } = await DeviceGateway.list(apiUrl, auth, true); + const knowsOwners = sessions.some((s) => s.started_by !== undefined); + const newestFirst = (list: DeviceSession[]) => + [...list].sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at)); + if (knowsOwners) { + const [newest] = newestFirst(sessions.filter((s) => s.started_by?.you)); + if (newest) return newest.id; + } else if (sessions.length === 1) { + return sessions[0].id; + } + + if (sessions.length === 0) { + throw new CliError('No device session in the last day. Name one: `dcd device artifacts `.', DEVICE_EXIT.usage); + } + + const listed = newestFirst(sessions) + .map((s) => ` ${s.id} ${s.platform} ${s.state}${s.started_by ? ` (${startedByLabel(s.started_by)})` : ''}`) + .join('\n'); + throw new CliError( + knowsOwners + ? `None of the sessions of the last day is yours. Name one:\n${listed}` + : `Name the session:\n${listed}`, + DEVICE_EXIT.usage, + ); +} + /** Who started a session, in a few words: "you", an email, or an API key's name. */ export function startedByLabel(starter: DeviceSessionStarter): string { if (starter.you) return starter.this_client ? 'you, this connection' : 'you'; - if (starter.email) return `started by ${starter.email}`; - if (starter.api_key_name) return `started with API key "${starter.api_key_name}"`; + if (starter.email) return `started by ${printable(starter.email, { oneLine: true })}`; + if (starter.api_key_name) return `started with API key "${printable(starter.api_key_name, { oneLine: true })}"`; return 'started by someone else'; } +/** Control characters other than tab and newline, C1 controls, and bidirectional overrides. */ +// eslint-disable-next-line no-control-regex +const CONTROL = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u202A-\u202E\u2066-\u2069]/g; + +/** + * Text from the device, the app or another client, made safe to print in a + * terminal: escape sequences and control characters removed, so an element's + * label, a log line or a note can't retitle the terminal, move the cursor or + * draw a fake result line. `oneLine` also folds line breaks into spaces, for + * text shown inside a row. --json output keeps the text exactly as it came. + */ +export function printable(text: string, opts: { oneLine?: boolean } = {}): string { + const clean = stripVTControlCharacters(text).replaceAll(CONTROL, ''); + return opts.oneLine ? clean.replaceAll(/[\t\n]+/g, ' ') : clean; +} + +/** + * Dollars for a person. Sessions are billed in units of $0.015, so a cost + * is shown to the half cent when it has one: $0.015, not $0.01. + */ +export function formatCost(usd: number): string { + const tenths = Math.round(usd * 1000); + return tenths % 10 === 0 ? `$${usd.toFixed(2)}` : `$${(tenths / 1000).toFixed(3)}`; +} + export function formatSeconds(seconds: number): string { if (seconds < 60) return `${seconds}s`; const minutes = Math.floor(seconds / 60); @@ -192,8 +297,8 @@ export function sessionFields(session: DeviceSession): Field[] { ['state', session.release_reason ? `${session.state} (${session.release_reason})` : session.state], ['platform', session.platform], ]; - if (session.model) fields.push(['model', session.model]); - if (session.client_label) fields.push(['client', session.client_label]); + if (session.model) fields.push(['model', printable(session.model, { oneLine: true })]); + if (session.client_label) fields.push(['client', printable(session.client_label, { oneLine: true })]); if (session.started_by) fields.push(['started', startedByLabel(session.started_by)]); if (session.queue) { const position = session.queue.position === null ? '' : `#${session.queue.position}`; @@ -210,11 +315,14 @@ export function sessionFields(session: DeviceSession): Field[] { } if (session.cost_so_far_usd !== null) { - fields.push(['cost so far', `$${session.cost_so_far_usd.toFixed(2)}`]); + fields.push(['cost so far', formatCost(session.cost_so_far_usd)]); } if (session.last_crash) { - fields.push(['last crash', colors.error(`${session.last_crash.summary} (${session.last_crash.at})`)]); + fields.push([ + 'last crash', + colors.error(`${printable(session.last_crash.summary, { oneLine: true })} (${session.last_crash.at})`), + ]); } fields.push(['monitor', formatUrl(session.monitor_url)]); @@ -224,7 +332,17 @@ export function sessionFields(session: DeviceSession): Field[] { /** A session as a branch group, with its warnings after it. */ export function printSession(session: DeviceSession): void { logger.log(ui.branch(ui.fields(sessionFields(session)))); - for (const warning of session.warnings) logger.log(ui.warn(warning)); + printWarnings(session); +} + +/** + * The session's warnings (a crash, the idle timeout or the end of its time + * coming up, an install still going), after a command's own result: a + * person or an agent driving it without --json must see them before the + * session ends under them. + */ +export function printWarnings(session: DeviceSession | null | undefined): void { + for (const warning of session?.warnings ?? []) logger.log(ui.warn(printable(warning))); } /** @@ -253,7 +371,7 @@ export function humanState(human: DeviceHumanStatus): string { /** The rows that describe a request for a person, for {@link ui.fields}. */ export function humanFields(human: DeviceHumanStatus, now: number = Date.now()): Field[] { const fields: Field[] = [['state', humanState(human)]]; - if (human.reason) fields.push(['reason', human.reason]); + if (human.reason) fields.push(['reason', printable(human.reason, { oneLine: true })]); // A person who took control unasked: the reason is " took control", // and nobody asked for anything. const tookControl = human.human_in_control && !!human.reason?.endsWith(' took control'); @@ -266,6 +384,8 @@ export function humanFields(human: DeviceHumanStatus, now: number = Date.now()): fields.push(['handed back', formatWhen(human.handed_back_at, now)]); } - if (human.handed_back) fields.push(['note', human.note ?? colors.dim('none')]); + if (human.handed_back) { + fields.push(['note', human.note ? printable(human.note, { oneLine: true }) : colors.dim('none')]); + } return fields; } diff --git a/src/utils/device-run.ts b/src/utils/device-run.ts index bc03a5c..1a3bbe0 100644 --- a/src/utils/device-run.ts +++ b/src/utils/device-run.ts @@ -1,4 +1,10 @@ -import type { DeviceCommandResult, DeviceFlowResult } from '../types/domain/device-session.types.js'; +import type { + DeviceCommandResult, + DeviceFailedAt, + DeviceFailureLocation, + DeviceFlowResult, +} from '../types/domain/device-session.types.js'; +import { printable } from './device-output.js'; import { colors } from './styling.js'; import { type Field, ui } from './ui.js'; @@ -10,8 +16,11 @@ import { type Field, ui } from './ui.js'; * JSON: `{ success, device_id, total_flows, total_commands_executed, * results: [{ file, success, error, message }], env_vars, message }`. For one * flow it is the same without `results`. Newer APIs also send - * `result.flows`, which is used when present. None of the runner's own - * fields (device_id, command counts, env_vars) are shown. + * `result.flows`, which is used when present, and turn a failure's `error` + * into plain text that says which flows failed, where (`failed_at`), and how + * to fix a flow sent without the files it uses. That text is preferred to + * the runner's own. None of the runner's own fields (device_id, command + * counts, env_vars) are shown. */ export interface RunReport { flows: DeviceFlowResult[]; @@ -27,6 +36,29 @@ function text(value: unknown): null | string { return typeof value === 'string' && value.trim() ? value.trim() : null; } +/** Text that is not a JSON document: the API's own wording of a failure. */ +function plainText(value: string | undefined): null | string { + const t = text(value); + return t && !t.startsWith('{') ? t : null; +} + +function location(value: unknown): DeviceFailureLocation | null { + if (!isRecord(value) || typeof value.file !== 'string' || typeof value.line !== 'number') return null; + return { + call_chain: Array.isArray(value.call_chain) ? value.call_chain.filter((s): s is string => typeof s === 'string') : [], + command: typeof value.command === 'string' ? value.command : null, + file: value.file, + line: value.line, + }; +} + +function failedAt(raw: Record): DeviceFailedAt { + const one = location(raw.failed_at); + if (one) return { failed_at: one }; + const many = Array.isArray(raw.failed_at_candidates) ? raw.failed_at_candidates.map(location) : []; + return many.length > 1 && many.every(Boolean) ? { failed_at_candidates: many as DeviceFailureLocation[] } : {}; +} + function toFlow(raw: Record, file: null | string): DeviceFlowResult { const success = raw.success === true; return { @@ -34,6 +66,7 @@ function toFlow(raw: Record, file: null | string): DeviceFlowRe success, // A failed flow's reason is in `error`; some reports only have `message`. error: text(raw.error) ?? (success ? null : text(raw.message)), + ...failedAt(raw), }; } @@ -69,16 +102,59 @@ export function parseRunReport(result: DeviceCommandResult): null | RunReport { return { flows: result.flows.map((f) => toFlow({ ...f }, null)), message: null }; } - return parseRunnerJson(result.error) ?? parseRunnerJson(result.output); + const report = parseRunnerJson(result.error) ?? parseRunnerJson(result.output); + if (!report || result.success || report.flows.length !== 1) return report; + // One flow that failed: the API's wording says more than the runner's + // (where it failed, and why a file it uses was missing). + const [flow] = report.flows; + return { + ...report, + flows: [ + { + ...flow, + error: plainText(result.error) ?? flow.error, + ...(flow.failed_at || flow.failed_at_candidates ? {} : failedAt(result as unknown as Record)), + }, + ], + }; +} + +/** `sub/check.yaml:5`, the command if known, and how the flow got there. */ +export function describeLocation(where: DeviceFailedAt): null | string { + const at = (l: DeviceFailureLocation) => `${l.file}:${l.line}`; + if (where.failed_at) { + const l = where.failed_at; + const via = l.call_chain.slice(0, -1); + return [ + `at ${at(l)}`, + l.command ? ` ${printable(l.command, { oneLine: true })}` : '', + via.length > 0 ? ` (via ${via.join(' → ')})` : '', + ].join(''); + } + + if (where.failed_at_candidates) return `at one of ${where.failed_at_candidates.map(at).join(', ')}`; + return null; +} + +/** The text names the place already, as the API's wording of a failure does: "... (at login.yaml:7)". */ +function mentions(error: null | string | undefined, where: DeviceFailedAt): boolean { + const places = where.failed_at ? [where.failed_at] : (where.failed_at_candidates ?? []); + return Boolean(error) && places.length > 0 && places.every((l) => error!.includes(`${l.file}:${l.line}`)); } /** The failure message for a failed run: each failing flow and why. */ export function runFailureMessage(result: DeviceCommandResult, report: null | RunReport): string { + // The API's own text names the failing flows and where they failed. + const own = plainText(result.error); + if (own) return own; if (!report) return result.error || 'The flow failed.'; const failed = report.flows.filter((f) => !f.success); if (failed.length === 0) return report.message ?? 'The flow failed.'; return failed - .map((f) => `${f.file ?? 'flow'}: ${f.error ?? 'failed'}`) + .map((f) => { + const where = describeLocation(f); + return `${f.file ?? 'flow'}: ${f.error ?? 'failed'}${where ? ` (${where})` : ''}`; + }) .join('; '); } @@ -96,7 +172,7 @@ export function printRunResult( // What the app showed after the failure: why an assertion missed. if (!passed && result.screen_text?.length) { log(ui.section('On screen after the failure')); - log(ui.branch(result.screen_text.map((t) => `"${t}"`))); + log(ui.branch(result.screen_text.map((t) => `"${printable(t, { oneLine: true })}"`))); } } @@ -109,22 +185,25 @@ function printOutcome( const report = parseRunReport(result); if (!report || report.flows.length === 0) { log(passed ? ui.success('Flow passed') : `${ui.statusSymbol('FAILED')} Flow failed`); + const where = describeLocation(result); if (report) { - if (report.message) log(ui.note(report.message)); + if (report.message) log(ui.note(printable(report.message))); + if (!passed && where) log(ui.note(where)); return; } // Plain text, not a report the CLI can read: show it as it came. if (result.output) { log(ui.section('Output')); - log(result.output); + log(printable(result.output)); } if (result.error) { log(ui.section('Error')); - log(colors.error(result.error)); + log(colors.error(printable(result.error))); } + if (!passed && where && !mentions(result.error, result)) log(ui.note(where)); return; } @@ -138,10 +217,14 @@ function printOutcome( log(passed && failed === 0 ? ui.success(summary) : `${ui.statusSymbol('FAILED')} ${summary}`); const rows: Field[] = flows.map((f) => [ - f.file ?? label, + printable(f.file ?? label, { oneLine: true }), f.success ? ui.statusWord('PASSED') - : `${ui.statusWord('FAILED')}${f.error ? ` ${colors.error(f.error)}` : ''}`, + : `${ui.statusWord('FAILED')}${f.error ? ` ${colors.error(printable(f.error, { oneLine: true }))}` : ''}`, ]); log(ui.branch(ui.fields(rows))); + for (const f of flows) { + const where = f.success ? null : describeLocation(f); + if (where && !mentions(f.error, f)) log(ui.note(`${printable(f.file ?? label, { oneLine: true })} failed ${where}`)); + } } diff --git a/test/unit/device-bundle.test.ts b/test/unit/device-bundle.test.ts index f68d493..9e037c4 100644 --- a/test/unit/device-bundle.test.ts +++ b/test/unit/device-bundle.test.ts @@ -6,7 +6,7 @@ import * as path from 'node:path'; import StreamZip from 'node-stream-zip'; import { clearCompatibilityCache } from '../../src/utils/compatibility.js'; -import { bundleFiles, uploadFlowBundle } from '../../src/utils/device-bundle.js'; +import { bundleFiles, flowFileBundle, uploadFlowBundle } from '../../src/utils/device-bundle.js'; const API = 'https://api.devicecloud.dev'; const auth = { headers: {}, mode: 'apiKey' as const }; @@ -137,6 +137,50 @@ describe('dcd device run : flow bundles', () => { it('refuses an entry that is not in the directory', () => { expect(() => bundleFiles(dir, 'flows/nope.yaml')).to.throw('No flow flows/nope.yaml'); + expect(() => bundleFiles(dir, '../outside.yaml')).to.throw('No flow ../outside.yaml'); + }); + + it('with an entry, sends only what that flow reaches, and the config', () => { + write('flows/other.yaml', 'appId: x\n---\n- back\n'); + expect(bundleFiles(dir, 'flows/checkout.yaml')).to.deep.equal( + ['config.yaml', 'flows/checkout.yaml', 'media/card.png', 'scripts/seed.js', 'subflows/pay.yaml'].map((f) => + path.normalize(f), + ), + ); + }); + + it('confined to a folder, refuses a file that is a link out of it', () => { + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-bundle-outside-')); + try { + fs.writeFileSync(path.join(outside, 'id_rsa'), 'secret'); + fs.unlinkSync(path.join(dir, 'media', 'card.png')); + fs.symlinkSync(path.join(outside, 'id_rsa'), path.join(dir, 'media', 'card.png')); + expect(() => bundleFiles(dir, 'flows/checkout.yaml', () => {}, dir)).to.throw(/card\.png is a link to a file outside/); + // From the command line the link is the user's own, and is followed. + expect(bundleFiles(dir, 'flows/checkout.yaml')).to.include(path.normalize('media/card.png')); + } finally { + fs.rmSync(outside, { force: true, recursive: true }); + } + }); + + it("walks .maestro, Maestro's own folder, but no other dot-folder", () => { + write('.maestro/login.yaml', 'appId: x\n---\n- launchApp\n'); + write('.github/workflows/ci.yml', 'on: push\n'); + const all = bundleFiles(dir); + expect(all).to.include(path.normalize('.maestro/login.yaml')); + expect(all.some((f) => f.startsWith('.github'))).to.equal(false); + expect(bundleFiles(dir, '.maestro/login.yaml')).to.deep.equal([path.normalize('.maestro/login.yaml'), 'config.yaml']); + }); + + it("flowFileBundle takes the folder that holds every file the flow reaches, through its subflows' own files", () => { + write('app/e2e/main.yaml', 'appId: x\n---\n- runFlow: ../steps/login.yaml\n'); + write('app/steps/login.yaml', 'appId: x\n---\n- runScript: ../../shared/seed.js\n'); + write('shared/seed.js', 'output.ok = true'); + expect(flowFileBundle(path.join(dir, 'app', 'e2e', 'main.yaml'))).to.deep.equal({ + dir, + entry: path.join('app', 'e2e', 'main.yaml'), + }); + expect(flowFileBundle(path.join(dir, 'flows', 'login.yaml'))).to.equal(null); }); it('refuses a flow that uses a file outside the directory', () => { diff --git a/test/unit/device-command.test.ts b/test/unit/device-command.test.ts index cdae27e..0c4c024 100644 --- a/test/unit/device-command.test.ts +++ b/test/unit/device-command.test.ts @@ -6,24 +6,34 @@ import { stripVTControlCharacters } from 'node:util'; import { runCommand } from 'citty'; +import { Readable } from 'node:stream'; + import { collectFlagValues, decodeDataUrl, deviceCommand, + deviceTiming, formatElement, newLogLines, + parseEnvFile, parseEnvFlags, + readStdinText, startNextSteps, + unknownSubcommandError, } from '../../src/commands/device.js'; -import { DeviceApiError } from '../../src/gateways/device-gateway.js'; +import { DeviceApiError, plainErrorText } from '../../src/gateways/device-gateway.js'; import type { DeviceSession } from '../../src/types/domain/device-session.types.js'; -import { platformOfAppFile } from '../../src/utils/app-upload.js'; +import { platformOfAppFile, platformOfAppUrl } from '../../src/utils/app-upload.js'; import { CliError } from '../../src/utils/cli.js'; +import { editDistance, unknownFlags, unknownFlagsError } from '../../src/utils/device-flags.js'; import { + checkSessionId, DEVICE_EXIT, deviceExitCode, + formatCost, formatWhen, humanFields, + printable, resolveSessionId, } from '../../src/utils/device-output.js'; @@ -181,6 +191,25 @@ async function runArgv(rawArgs: string[]): Promise<{ exit: number; out: Record }; } +/** Run `fn`, capturing what it writes to stderr. */ +async function captureStderr(fn: () => Promise): Promise<{ result: T; stderr: string }> { + let stderr = ''; + const write = process.stderr.write.bind(process.stderr); + process.stderr.write = ((chunk: string) => { + stderr += chunk; + return true; + }) as typeof process.stderr.write; + try { + return { result: await fn(), stderr }; + } finally { + process.stderr.write = write; + } +} + +const ESC = String.fromCharCode(27); +const BEL = String.fromCharCode(7); +const CR = String.fromCharCode(13); + describe('dcd device', () => { const realFetch = globalThis.fetch; const ORIGINAL_ENV = { ...process.env }; @@ -804,12 +833,12 @@ describe('dcd device', () => { ? { body: { session: session('theirs', { state: 'released' }) } } : { body: { result: { success: true }, session: session('theirs') } }, ); - await runJson('stop', { id: 'theirs', force: true }); - expect(calls[0].url).to.equal(`${API}/device/sessions/theirs?force=true`); - await runJson('press-key', { id: 'theirs', key: 'back', force: true }); + await runJson('stop', { id: 'their-red-fox', force: true }); + expect(calls[0].url).to.equal(`${API}/device/sessions/their-red-fox?force=true`); + await runJson('press-key', { id: 'their-red-fox', key: 'back', force: true }); expect(calls[1].body).to.deep.equal({ force: true, key: 'back', type: 'press_key' }); // Without it, nothing extra is sent: an older API sees what it always did. - await runJson('press-key', { id: 'theirs', key: 'back' }); + await runJson('press-key', { id: 'their-red-fox', key: 'back' }); expect(calls[2].body).to.deep.equal({ key: 'back', type: 'press_key' }); }); @@ -1225,4 +1254,431 @@ describe('dcd device', () => { expect(platformOfAppFile('notes.txt')).to.equal(undefined); }); }); + + describe('flags and ids a command does not take', () => { + it('refuses an unknown flag, says which was meant, and sends nothing', async () => { + const calls = stubFetch(() => ({ body: {} })); + const { exit, out } = await runArgv(['type', 'a-b-c', '--text', 'hunter2', '--sensetive']); + expect(exit).to.equal(DEVICE_EXIT.usage); + const { message } = out.error as { message: string }; + expect(message).to.include('Unknown flag --sensetive.').and.include('Did you mean --sensitive?'); + expect(calls).to.have.length(0); + }); + + it('catches a swapped pair of letters, a misspelt negation, and the session given as a flag', async () => { + stubFetch(() => ({ body: {} })); + const wait = await runArgv(['start', '--platform', 'ios', '--wiat']); + expect((wait.out.error as { message: string }).message).to.include('Did you mean --wait?'); + const record = await runArgv(['start', '--platform', 'ios', '--no-recrod']); + expect((record.out.error as { message: string }).message).to.include('Did you mean --no-record?'); + const session = await runArgv(['tap', '--session', 'a-b-c', '--text', 'OK']); + expect((session.out.error as { message: string }).message).to.include('The session id is an argument'); + const secret = await runArgv(['type', 'a-b-c', '--text', 'x', '--secret']); + expect((secret.out.error as { message: string }).message).to.include('Did you mean --sensitive?'); + }); + + it("reads a flag's value as a value, even one that starts with a dash", () => { + const args = { + id: { type: 'positional' as const }, + json: { type: 'boolean' as const }, + output: { type: 'string' as const, alias: ['o'] }, + record: { type: 'boolean' as const, default: true }, + 'clear-state': { type: 'boolean' as const }, + yaml: { type: 'string' as const }, + }; + expect(unknownFlags(['a-b-c', '--yaml', '- launchApp', '-o', 'shot.jpg', '--no-record', '--json'], args)).to.deep.equal([]); + expect(unknownFlags(['--clearState', '--yaml=-x', '--', '--anything'], args)).to.deep.equal([]); + expect(unknownFlags(['-x', '--nope=1', '--yaml'], args)).to.deep.equal(['-x', '--nope']); + expect(unknownFlagsError(['--clear-sate'], args)!.message).to.include('Did you mean --clear-state?'); + // Nothing close: no guess. + expect(unknownFlagsError(['--banana'], args)!.message).not.to.include('Did you mean'); + expect(editDistance('wiat', 'wait')).to.equal(1); + expect(editDistance('sensetive', 'sensitive')).to.equal(1); + }); + + it('refuses an unknown command with the envelope, and names the one meant', async () => { + const calls = stubFetch(() => ({ body: {} })); + const { exit, out } = await runArgv(['press_key', 'back']); + expect(exit).to.equal(DEVICE_EXIT.usage); + expect(out.ok).to.equal(false); + expect((out.error as { message: string }).message).to.include('Did you mean `dcd device press-key`?'); + expect(calls).to.have.length(0); + expect(unknownSubcommandError('tap_on').message).to.include('`dcd device tap`'); + expect(unknownSubcommandError('frobnicate').message).not.to.include('Did you mean'); + }); + + it("refuses an id that can't be a session, such as a variable that was not set", async () => { + const calls = stubFetch(() => ({ body: {} })); + for (const id of ['undefined', 'null', 'None', '[object Object]']) { + const { exit, out } = await runJson('launch', { id }); + expect(exit).to.equal(DEVICE_EXIT.usage); + expect((out.error as { message: string }).message).to.include('was not set'); + } + + expect((await runJson('inspect', { id: 'Brave Teal Otter' })).exit).to.equal(DEVICE_EXIT.usage); + expect(calls).to.have.length(0); + expect(checkSessionId(' brave-teal-otter ')).to.equal('brave-teal-otter'); + expect(checkSessionId('brave-teal-otter-0042')).to.equal('brave-teal-otter-0042'); + expect(checkSessionId('teal-otter-42')).to.equal('teal-otter-42'); + expect(checkSessionId('1234')).to.equal('1234'); + expect(checkSessionId(' ')).to.equal(undefined); + }); + + it("passes on what the API said a script can act on: retry_after_s, limit, phase", async () => { + stubFetch(() => ({ + status: 429, + body: { statusCode: 429, message: 'Too many commands', error: 'LIVE_RATE_LIMITED', limit: 60, retry_after_s: 12 }, + })); + const limited = await runJson('tap', { id: 'a-b-c', text: 'OK' }); + expect(limited.exit).to.equal(DEVICE_EXIT.limit); + expect(limited.out.error).to.deep.equal({ + code: 'LIVE_RATE_LIMITED', + message: 'Too many commands', + limit: 60, + retry_after_s: 12, + }); + stubFetch(() => ({ + status: 409, + body: { statusCode: 409, message: 'The app is still installing', error: 'LIVE_NOT_READY', phase: 'installing_app' }, + })); + expect((await runJson('tap', { id: 'a-b-c', text: 'OK' })).out.error).to.include({ phase: 'installing_app' }); + }); + + it('shortens an HTML error page to its title', () => { + const page = '502 Bad Gateway' + 'x'.repeat(5000) + ''; + expect(plainErrorText(page, 502)).to.equal("HTTP 502: 502 Bad Gateway (an HTML page, not the API's answer)"); + expect(plainErrorText('', 503)).to.equal('HTTP 503'); + expect(plainErrorText('y'.repeat(1000), 500)).to.have.length(301); + }); + }); + + describe('waiting', () => { + const saved = { ...deviceTiming }; + beforeEach(() => Object.assign(deviceTiming, { pollMs: 5, retryBaseMs: 5, runGraceMs: 60_000 })); + afterEach(() => Object.assign(deviceTiming, saved)); + + const running = (extra: Partial = {}) => ({ + body: { command_id: 'c1', status: 'running', result: null, session: session('a-b-c', extra) }, + }); + + it('run stops waiting when the session ends under the flow: exit 4, with the command id', async () => { + stubFetch((call) => (call.method === 'POST' ? running() : running({ state: 'released', release_reason: 'idle_timeout' }))); + const { exit, out } = await runJson('run', { id: 'a-b-c', yaml: '- launchApp' }); + expect(exit).to.equal(DEVICE_EXIT.gone); + expect(out.error).to.include({ code: 'LIVE_SESSION_ENDED', command_id: 'c1' }); + expect((out.error as { message: string }).message).to.include('ended before the flow finished'); + }); + + it("run gives up once the session's time is over, with the command id", async () => { + deviceTiming.runGraceMs = 0; + stubFetch(() => running({ time_remaining_s: 0 })); + const { exit, out } = await runJson('run', { id: 'a-b-c', yaml: '- launchApp' }); + expect(exit).to.equal(DEVICE_EXIT.failed); + expect(out.error).to.include({ command_id: 'c1' }); + expect((out.error as { message: string }).message).to.include('maximum duration'); + }); + + it('run asks again when a poll fails on the way, and keeps waiting', async () => { + let polls = 0; + stubFetch((call) => { + if (call.method === 'POST') return running(); + polls += 1; + // A proxy's answer, not the API's: nothing was decided. + if (polls === 1) return { status: 502, body: { message: 'Application failed to respond' } }; + return { body: { command_id: 'c1', status: 'passed', result: { success: true }, session: session('a-b-c') } }; + }); + const { exit } = await runJson('run', { id: 'a-b-c', yaml: '- launchApp' }); + expect(exit).to.equal(0); + expect(polls).to.equal(2); + }); + + it('run keeps the command id when it has to give up asking', async () => { + deviceTiming.retryMs = 0; + stubFetch((call) => (call.method === 'POST' ? running() : { status: 502, body: { message: 'Application failed to respond' } })); + const { exit, out } = await runJson('run', { id: 'a-b-c', yaml: '- launchApp' }); + expect(exit).to.equal(DEVICE_EXIT.failed); + expect(out.error).to.include({ command_id: 'c1' }); + expect((out.error as { message: string }).message).to.include('may still be running on a-b-c: its command id is c1'); + }); + + it('start --wait --json names the session on stderr as soon as it exists', async () => { + let polls = 0; + stubFetch((call) => { + if (call.method === 'POST') return { body: { session: session('a-b-c', { state: 'queued' }) } }; + polls += 1; + return { body: { session: session('a-b-c', { state: polls < 2 ? 'provisioning' : 'ready' }) } }; + }); + const { result, stderr } = await captureStderr(() => runJson('start', { platform: 'ios', wait: true })); + expect(result.exit).to.equal(0); + expect(stderr).to.include('Session a-b-c started'); + expect(stderr).to.include('dcd device stop a-b-c'); + }); + + it('status --wait waits for the device and its app, and exits 4 when the session ends instead', async () => { + let polls = 0; + stubFetch((call) => { + if (call.url.endsWith('/human')) return { status: 404, body: { statusCode: 404, message: 'Not Found' } }; + polls += 1; + const install = { binary_upload_id: 'b1', error: null, status: polls < 3 ? ('installing' as const) : ('installed' as const) }; + return { body: { session: session('a-b-c', { state: polls < 2 ? 'provisioning' : 'ready', install }) } }; + }); + const ready = await runJson('status', { id: 'a-b-c', wait: true }); + expect(ready.exit).to.equal(0); + expect((ready.out.session as DeviceSession).install!.status).to.equal('installed'); + + stubFetch(() => ({ body: { session: session('a-b-c', { state: 'expired', release_reason: 'max_duration' }) } })); + const ended = await runJson('status', { id: 'a-b-c', wait: true }); + expect(ended.exit).to.equal(DEVICE_EXIT.gone); + }); + }); + + describe('flows that use other files', () => { + it('run uploads the flow with the files it uses, and runs it by its path inside', async () => { + const flows = path.join(tempDir, 'flows'); + fs.mkdirSync(path.join(flows, 'sub'), { recursive: true }); + fs.writeFileSync(path.join(flows, 'sub', 'login.yaml'), 'appId: x\n---\n- launchApp\n'); + fs.writeFileSync(path.join(flows, 'main.yaml'), 'appId: x\n---\n- runFlow: sub/login.yaml\n'); + fs.writeFileSync(path.join(flows, 'other.yaml'), 'appId: x\n---\n- back\n'); + const calls = stubFetch((call) => { + if (call.url.endsWith('/upload-url')) { + return { body: { id: 'b-1', upload: { path: 'p', signedUrl: 'https://sb/put' }, mirror: null } }; + } + + if (call.url === 'https://sb/put') return { body: {} }; + if (call.url.endsWith('/device/bundles')) { + return { body: { bundle: { id: 'b-1', sha: 's', bytes: 1, encrypted: false, created_at: 'now' } } }; + } + + if (call.url.endsWith('/run')) { + return { body: { command_id: 'c1', status: 'passed', result: { success: true }, session: session('a-b-c') } }; + } + + return { status: 404, body: {} }; + }); + const { exit } = await runJson('run', { id: 'a-b-c', flow: path.join(flows, 'main.yaml'), env: ['A=1'] }); + expect(exit).to.equal(0); + expect(calls.find((c) => c.url.endsWith('/run'))!.body).to.deep.equal({ + flowUploadId: 'b-1', + flow: 'main.yaml', + env: { A: '1' }, + }); + }); + + it('run --env-file reads KEY=VALUE lines, and --env wins for the same name', async () => { + const envFile = path.join(tempDir, '.env'); + fs.writeFileSync(envFile, '# test account\nexport USER=me\nPASS="p a s s"\n\nSAME=file\n'); + const calls = stubFetch(() => ({ + body: { command_id: 'c1', status: 'passed', result: { success: true }, session: session('a-b-c') }, + })); + await runJson('run', { id: 'a-b-c', yaml: '- launchApp', 'env-file': envFile, env: ['SAME=flag'] }); + expect((calls[0].body as { env: Record }).env).to.deep.equal({ + USER: 'me', + PASS: 'p a s s', + SAME: 'flag', + }); + }); + + it('parseEnvFile names a bad line by number only, since it may hold a secret', () => { + const envFile = path.join(tempDir, 'bad.env'); + fs.writeFileSync(envFile, 'GOOD=1\nhunter2\n'); + expect(() => parseEnvFile(envFile)).to.throw(/line 2: expected KEY=VALUE/); + expect(() => parseEnvFile(envFile)).not.to.throw(/hunter2/); + expect(() => parseEnvFile(path.join(tempDir, 'missing.env'))).to.throw(/Could not read --env-file/); + }); + }); + + describe('what a person reads', () => { + it('an action prints the session warnings after its result', async () => { + stubFetch(() => ({ + body: { + result: { success: true }, + session: session('a-b-c', { warnings: ['Idle timeout in 40s. Send a command to keep the session, or stop it if you are done.'] }), + }, + })); + const out = await runText('tap', { id: 'a-b-c', text: 'OK' }); + expect(out).to.include('Tapped "OK"'); + expect(out).to.include('Idle timeout in 40s'); + }); + + it("a failed action's message never carries the typed text", async () => { + stubFetch(() => ({ body: { result: { success: false }, session: session('a-b-c') } })); + const { exit, out } = await runJson('type', { id: 'a-b-c', text: 'hunter2' }); + expect(exit).to.equal(DEVICE_EXIT.failed); + expect(out.error).to.deep.equal({ code: null, message: 'Typing failed.' }); + }); + + it('strips escape sequences and control characters from device text', () => { + const hostile = `${ESC}]0;pwned${BEL}Hello${ESC}[2K${CR}World ${String.fromCharCode(0x202e)}gnp.exe`; + expect(printable(hostile)).to.equal('HelloWorld gnp.exe'); + expect(printable('a\nb\tc', { oneLine: true })).to.equal('a b c'); + const element = formatElement({ b: '[0,0][1,1]', txt: `${ESC}[31mRed${ESC}[0m`, hint: `x${CR}y` }); + // Only the CLI's own styling is left. + expect(element).not.to.include(`${ESC}[31m`); + expect(element).not.to.include(CR); + expect(stripVTControlCharacters(element)).to.include('"Red"'); + }); + + it('logs strips escapes from each line, and says when the size cap cut the answer', async () => { + stubFetch(() => ({ + body: { + logs: { lines: [`${ESC}]0;title${BEL}E crash here`], source: 'logcat', app_id: 'com.x', truncated: true }, + session: session('a-b-c'), + }, + })); + const out = await runText('logs', { id: 'a-b-c', lines: '200' }); + expect(out).not.to.include(ESC); + expect(out).to.include('E crash here'); + expect(out).to.include('Only the newest lines that fit in 24 KB are shown'); + }); + + it('logs passes on --level and --grep, and refuses a level it does not know', async () => { + const calls = stubFetch(() => ({ + body: { logs: { lines: [], source: 'logcat', app_id: 'com.x' }, session: session('a-b-c') }, + })); + await runJson('logs', { id: 'a-b-c', lines: '50', level: 'error', grep: ' NullPointer ' }); + expect(calls[0].url).to.equal(`${API}/device/sessions/a-b-c/logs?lines=50&level=error&grep=NullPointer`); + const { exit } = await runJson('logs', { id: 'a-b-c', level: 'debug' }); + expect(exit).to.equal(DEVICE_EXIT.usage); + }); + + it('status says a person has control once, as the API now words it', async () => { + const warning = 'A person has control: a@b.c took control. The session ends in 900s unless they hand it back.'; + stubFetch((call) => + call.url.endsWith('/human') + ? { + body: { + human: { + waiting: true, + reason: 'a@b.c took control', + since: null, + expires_at: null, + handed_back: false, + note: null, + handed_back_at: null, + human_in_control: true, + controller_user_id: 'u1', + }, + session: session('a-b-c', { state: 'needs_human' }), + }, + } + : { body: { session: session('a-b-c', { state: 'needs_human', warnings: [warning] }) } }, + ); + const out = await runText('status', { id: 'a-b-c' }); + expect(out.split('A person has control')).to.have.length(2); + }); + + it('formatCost shows the half cent a 30-second unit leaves', () => { + expect(formatCost(0.015)).to.equal('$0.015'); + expect(formatCost(0.045)).to.equal('$0.045'); + expect(formatCost(0.42)).to.equal('$0.42'); + expect(formatCost(1.8)).to.equal('$1.80'); + expect(formatCost(0)).to.equal('$0.00'); + }); + }); + + describe('smaller things', () => { + it('start refuses an empty --app (an unset variable), without starting a session', async () => { + const calls = stubFetch(() => ({ body: {} })); + for (const args of [{ app: '' }, { app: ' ' }, { 'app-binary-id': '' }]) { + const { exit, out } = await runJson('start', { platform: 'ios', ...args }); + expect(exit).to.equal(DEVICE_EXIT.usage); + expect((out.error as { message: string }).message).to.include('is empty'); + } + + expect(calls).to.have.length(0); + }); + + it('start --app takes the platform from the file name in the link', async () => { + const calls = stubFetch((call) => + call.url.endsWith('/install') + ? { body: { app: { app_id: 'com.x', binary_upload_id: 'b1', reused: false }, session: session('a-b-c') } } + : { body: { session: session('a-b-c', { state: 'queued' }) } }, + ); + const { exit } = await runJson('start', { app: 'https://ci.example.com/builds/app-release.apk?token=x' }); + expect(exit).to.equal(0); + expect((calls[0].body as { platform: string }).platform).to.equal('android'); + expect(platformOfAppUrl('https://x.example/My%20App.zip')).to.equal('ios'); + expect(platformOfAppUrl('https://x.example/download?id=1')).to.equal(undefined); + }); + + it('swipe and tap take points written with a percent sign', async () => { + const calls = stubFetch(() => ({ body: { result: { success: true }, session: session('a-b-c') } })); + await runJson('swipe', { id: 'a-b-c', from: '50%,80%', to: '50%, 20%' }); + expect(calls[0].body).to.deep.equal({ type: 'swipe', from: { x: 50, y: 80 }, to: { x: 50, y: 20 } }); + await runJson('tap', { id: 'a-b-c', x: '10%', y: '90' }); + expect(calls[1].body).to.deep.equal({ type: 'tap', x: 10, y: 90 }); + }); + + it('request-human takes --reason, so the session id may come first', async () => { + const calls = stubFetch(() => ({ + body: { + human: { + waiting: true, + reason: 'Enter the code', + since: null, + expires_at: null, + handed_back: false, + note: null, + handed_back_at: null, + human_in_control: false, + controller_user_id: null, + }, + session: session('a-b-c', { state: 'needs_human' }), + }, + })); + const { exit } = await runArgv(['request-human', 'a-b-c', '--reason', 'Enter the code']); + expect(exit).to.equal(0); + expect(calls).to.have.length(1); + expect(calls[0].url).to.equal(`${API}/device/sessions/a-b-c/request-human`); + expect(calls[0].body).to.deep.equal({ reason: 'Enter the code' }); + }); + + it("request-human refuses a lone argument that is an open session's id", async () => { + const calls = stubFetch(() => ({ body: { sessions: [session('a-b-c')] } })); + const { exit, out } = await runArgv(['request-human', 'a-b-c']); + expect(exit).to.equal(DEVICE_EXIT.usage); + expect((out.error as { message: string }).message).to.include('is a session id, not what the person should do'); + expect(calls.map((c) => c.method)).to.deep.equal(['GET']); + }); + + it('artifacts with no id takes your newest session, even one that has ended', async () => { + const mine = (id: string, created: string) => + session(id, { + state: 'released', + created_at: created, + started_by: { api_key_name: null, client_label: null, email: null, this_client: false, you: true }, + }); + const theirs = session('their-new-one', { + created_at: '2026-10-19T12:00:00Z', + started_by: { api_key_name: null, client_label: null, email: 'ann@example.com', this_client: false, you: false }, + }); + const calls = stubFetch((call) => + call.url.includes('/artifacts') + ? { body: { actions: [], logs: null, recording: null, next_before: null, session: session('my-newer-one') } } + : { body: { sessions: [theirs, mine('my-old-one', '2026-10-19T09:00:00Z'), mine('my-newer-one', '2026-10-19T11:00:00Z')] } }, + ); + const { exit } = await runJson('artifacts', { links: true }); + expect(exit).to.equal(0); + expect(calls[0].url).to.equal(`${API}/device/sessions?all=true`); + expect(calls[1].url).to.include('/device/sessions/my-newer-one/artifacts'); + }); + + it('readStdinText reads piped text without its last line break, and refuses a terminal', async () => { + expect(await readStdinText(Readable.from([Buffer.from('s3cret\n')]))).to.equal('s3cret'); + const terminal = Object.assign(Readable.from([]), { isTTY: true }); + try { + await readStdinText(terminal); + expect.fail('should have thrown'); + } catch (error) { + expect((error as Error).message).to.include('pipe it in'); + } + }); + + it('type refuses --text with --text-stdin', async () => { + const calls = stubFetch(() => ({ body: {} })); + const { exit } = await runJson('type', { id: 'a-b-c', text: 'x', 'text-stdin': true }); + expect(exit).to.equal(DEVICE_EXIT.usage); + expect(calls).to.have.length(0); + }); + }); }); diff --git a/test/unit/device-run.test.ts b/test/unit/device-run.test.ts index 5b46647..36ce33e 100644 --- a/test/unit/device-run.test.ts +++ b/test/unit/device-run.test.ts @@ -27,7 +27,61 @@ function printed(passed: boolean, result: Parameters[2], return lines.join('\n'); } +/** A single flow that failed, as a newer API answers: its own words in error, the report in output. */ +const FAILED_INLINE = { + success: false, + error: + 'Invalid File Path at flow.yaml:7:3. flow.yaml is the flow you sent inline; line 7 refers to another file (runFlow, runScript, addMedia), which was not sent with it.', + output: JSON.stringify({ success: false, device_id: 'x', message: 'Invalid File Path at flow.yaml:7:3' }), + failed_at: { file: 'flow.yaml', line: 7, command: 'runFlow: common/setup.yaml', call_chain: ['flow.yaml:7'] }, +}; + describe('dcd device run output', () => { + describe("the API's own words and where it failed", () => { + it("uses the API's text for a single failed flow, not the runner's", () => { + const report = parseRunReport(FAILED_INLINE)!; + expect(report.flows[0].error).to.equal(FAILED_INLINE.error); + expect(report.flows[0].failed_at).to.deep.equal(FAILED_INLINE.failed_at); + expect(runFailureMessage(FAILED_INLINE, report)).to.equal(FAILED_INLINE.error); + expect(printed(false, FAILED_INLINE)).to.include('which was not sent with it'); + }); + + it('says where each failed flow of a bundle failed, and how it got there', () => { + const result = { + success: false, + flows: [ + { file: 'a.yaml', success: true, error: null }, + { + file: 'main.yaml', + success: false, + error: 'Element not found', + failed_at: { file: 'sub/check.yaml', line: 5, command: 'tapOn: Next', call_chain: ['main.yaml:4', 'sub/check.yaml:5'] }, + }, + ], + }; + const out = printed(false, result); + expect(out).to.include('main.yaml failed at sub/check.yaml:5 tapOn: Next (via main.yaml:4)'); + expect(runFailureMessage(result, parseRunReport(result))).to.equal( + 'main.yaml: Element not found (at sub/check.yaml:5 tapOn: Next (via main.yaml:4))', + ); + }); + + it('does not say where twice when the text says it already', () => { + const result = { + success: false, + flows: [ + { + file: 'main.yaml', + success: false, + error: 'Element not found (at main.yaml:9)', + failed_at: { file: 'main.yaml', line: 9, command: null, call_chain: [] }, + }, + ], + }; + expect(printed(false, result)).not.to.include('failed at main.yaml:9'); + }); + }); + describe('parseRunReport', () => { it('reads a directory report from error, one row per flow', () => { expect(parseRunReport({ success: false, error: FAILED_DIR })).to.deep.equal({ From 3eca032bf207234a4196cd41a366f0f7c4aee1bd Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Wed, 18 Nov 2026 19:56:35 +0000 Subject: [PATCH 3/7] fix(mcp): keep local files in the working directory, and say why device tools are missing - The bridge's `run` reads a flow, and the files it uses, only from inside the working directory the server was started in, and only .yaml/.yml files; a bundle refuses a file that is a link out of it. An agent's tool call is not the user typing a path. - dcd_download_artifacts writes only inside the working directory and never replaces a file the server did not write. It writes files, so it is no longer annotated read-only (it stays in read-only mode: it changes nothing in the cloud). - start_device takes app_path: the build is uploaded before the session starts, so no device time is spent on the upload. - A directory's entry is sent with forward slashes, as the API takes it, also on Windows. - When the device tools can't be listed (not signed in, or none for the account), the bridge lists load_device_tools, whose description says why, and a device tool called anyway says why too. An empty or failed listing is no longer kept, and the bridge sends tools/list_changed once the tools load. --- src/mcp/bridge.ts | 194 +++++++++++++++++++--------- src/mcp/local-files.ts | 83 ++++++++++++ src/mcp/tools/download-artifacts.ts | 44 ++++--- test/unit/mcp-bridge.test.ts | 146 ++++++++++++++++++++- test/unit/mcp-local-files.test.ts | 98 ++++++++++++++ 5 files changed, 485 insertions(+), 80 deletions(-) create mode 100644 src/mcp/local-files.ts create mode 100644 test/unit/mcp-local-files.test.ts diff --git a/src/mcp/bridge.ts b/src/mcp/bridge.ts index ffc8480..caad843 100644 --- a/src/mcp/bridge.ts +++ b/src/mcp/bridge.ts @@ -5,9 +5,10 @@ * runs (createServer), reached over an in-memory transport. * - The device tools, proxied from the hosted endpoint at `/mcp`, so * they are defined (and contract-tested) once, in the API. The bridge adds - * what a remote server can't do: `install_app` takes a local `app_path`, - * and `run` takes a local `path` (a flow file, or a directory uploaded as - * a bundle). + * what a remote server can't do: `start_device` and `install_app` take a + * local `app_path`, and `run` takes a local `path` (a flow file, or a + * directory uploaded as a bundle), which must be inside the working + * directory (local-files.ts). * * Auth is the CLI's: an API key or a `dcd login` session (getContext). The * hosted endpoint accepts both. A session is renewed before it expires; the @@ -16,8 +17,8 @@ * stdout is the JSON-RPC channel: everything else goes to stderr. */ import { randomBytes } from 'node:crypto'; +import { realpathSync } from 'node:fs'; import { readFile, stat } from 'node:fs/promises'; -import * as path from 'node:path'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; @@ -31,16 +32,18 @@ import { } from '@modelcontextprotocol/sdk/types.js'; import { DeviceGateway, START_RECOVERY_WINDOW_MS } from '../gateways/device-gateway.js'; -import { processDependencies, readTestYamlFileAsJson } from '../services/execution-plan.utils.js'; -import { computeCommonRoot } from '../services/flow-paths.js'; import type { AuthContext } from '../types/domain/auth.types.js'; import { uploadLocalApp } from '../utils/app-upload.js'; import { getCliVersion } from '../utils/cli.js'; -import { uploadFlowBundle } from '../utils/device-bundle.js'; +import { bundlePath, flowFileBundle, uploadFlowBundle } from '../utils/device-bundle.js'; import { getContext, isReadOnly, logStderr } from './context.js'; import { errorResult, runTool } from './helpers.js'; +import { isInside, localInput, workingDirectory } from './local-files.js'; import { createServer } from './server.js'; +// Moved to utils/device-bundle.ts, where `dcd device run` uses it too. +export { flowFileBundle } from '../utils/device-bundle.js'; + /* * Sent at initialize, before this server knows which hosted tools the * account has: the hosted server only serves its tools to organizations that @@ -72,6 +75,16 @@ const READ_ONLY_INSTRUCTIONS = /** The inputs this bridge adds to hosted tools, and what they say. */ const LOCAL_INPUTS: Record }> = { + start_device: { + description: + ' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz): it is uploaded before the session starts, so no device time is spent on the upload.', + properties: { + app_path: { + type: 'string', + description: 'A build on this machine to upload and install when the device is ready. Pass this or app_binary_id.', + }, + }, + }, install_app: { description: ' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz), which is uploaded first.', @@ -84,16 +97,20 @@ const LOCAL_INPUTS: Record; - try { - const { config, testSteps } = readTestYamlFileAsJson(absolute); - deps = processDependencies({ config, input: absolute, testSteps }); - } catch { - return null; - } - - // A missing file goes this way too, so the upload names it. - if (deps.allFiles.length === 0 && deps.allErrors.length === 0) return null; - const dir = computeCommonRoot([absolute], deps.allFiles) || path.dirname(absolute); - return { dir, entry: path.relative(dir, absolute) }; -} - /** * Do the local part of a call (uploads, reading a file) and return the * arguments the hosted tool takes. @@ -140,9 +133,14 @@ export async function resolveLocalInputs( name: string, args: Record, ctx: { apiUrl: string; auth: AuthContext }, + root: string = workingDirectory(), ): Promise> { - if (name === 'install_app' && typeof args.app_path === 'string') { + if ((name === 'install_app' || name === 'start_device') && typeof args.app_path === 'string') { const { app_path: filePath, ...rest } = args; + if (rest.app_binary_id !== undefined || rest.app_url !== undefined) { + throw new Error('Pass app_path or app_binary_id (or app_url), not both.'); + } + logStderr(`Uploading ${filePath}…`); const binaryId = await uploadLocalApp({ ...ctx, @@ -154,28 +152,38 @@ export async function resolveLocalInputs( } if (name === 'run' && typeof args.path === 'string') { - const { path: flowPath, ...rest } = args; - const info = await stat(flowPath as string).catch(() => null); - if (!info) throw new Error(`No such file or directory: ${flowPath}`); + const { path: given, ...rest } = args; + // Only inside the working directory: an agent's call is not the user + // typing a path (local-files.ts). + const flowPath = localInput(given as string, root); + const info = await stat(flowPath); + // The API takes forward slashes; a path typed on Windows has backslashes. + const entry = typeof rest.flow === 'string' ? rest.flow.replaceAll('\\', '/') : undefined; if (info.isDirectory()) { logStderr(`Uploading the flows in ${flowPath}…`); - const bundle = await uploadFlowBundle({ - ...ctx, - dir: flowPath as string, - entry: typeof rest.flow === 'string' ? rest.flow : undefined, - log: logStderr, - }); - return { ...rest, flow_upload_id: bundle.id }; + const bundle = await uploadFlowBundle({ ...ctx, confineTo: root, dir: flowPath, entry, log: logStderr }); + return { ...rest, ...(entry !== undefined && { flow: entry }), flow_upload_id: bundle.id }; } - const bundled = flowFileBundle(flowPath as string); + if (!FLOW_FILE.test(flowPath)) { + throw new Error(`${given} is not a flow file: path takes a .yaml or .yml file, or a directory of flows.`); + } + + const bundled = flowFileBundle(flowPath); if (bundled) { - logStderr(`${flowPath} uses other files; uploading it with ${bundled.dir}…`); - const bundle = await uploadFlowBundle({ ...ctx, ...bundled, log: logStderr }); - return { ...rest, flow: bundled.entry, flow_upload_id: bundle.id }; + // The files it uses go too, so they must be inside as well. + if (!isInside(realpathSync(bundled.dir), root)) { + throw new Error( + `${given} uses files outside the working directory (${root}). This server uploads only from there: start it in a folder that holds the flow and every file it uses.`, + ); + } + + logStderr(`${given} uses other files; uploading it with them, from ${bundled.dir}…`); + const bundle = await uploadFlowBundle({ ...ctx, ...bundled, confineTo: root, log: logStderr }); + return { ...rest, flow: bundlePath(bundled.entry), flow_upload_id: bundle.id }; } - return { ...rest, yaml: await readFile(flowPath as string, 'utf8') }; + return { ...rest, yaml: await readFile(flowPath, 'utf8') }; } return args; @@ -225,6 +233,8 @@ export async function explainFailedStart( class RemoteDevices { private connecting: Promise | null = null; private tools: Tool[] | null = null; + /** Why the last listing gave no device tools, while it did not. */ + unavailable: null | string = null; /** Calls that arrive together share one connect. A failed one is retried by the next call. */ connect(): Promise { @@ -259,12 +269,28 @@ class RemoteDevices { return client; } + /** + * The hosted device tools. A list that came back empty is not kept, nor is + * a failure: the next call asks again, so signing in or the organization + * being enabled later is picked up without a restart. + */ async list(): Promise { if (this.tools) return this.tools; - const client = await this.connect(); - const { tools } = await client.listTools(); - this.tools = tools; - return tools; + try { + const client = await this.connect(); + const { tools } = await client.listTools(); + if (tools.length === 0) { + this.unavailable = NO_DEVICE_TOOLS; + return tools; + } + + this.tools = tools; + this.unavailable = null; + return tools; + } catch (error) { + this.unavailable = error instanceof Error ? error.message : String(error); + throw error; + } } has(name: string): boolean { @@ -277,10 +303,29 @@ class RemoteDevices { } } +/** Why an account sees no device tools when the endpoint answered. */ +const NO_DEVICE_TOOLS = + 'the hosted server offers no device tools to this account: Agent Devices may not be enabled for your organization'; + +/** + * Listed in place of the device tools while they can't be loaded, so the + * agent sees why (in its description) and can load them once that is fixed. + */ +export const LOAD_DEVICE_TOOLS = 'load_device_tools'; + +function loadDeviceToolsTool(reason: string): Tool { + return { + name: LOAD_DEVICE_TOOLS, + description: `The device tools (start_device and the rest, for driving a cloud phone) could not be loaded: ${reason}. Once that is fixed (for example after \`dcd login\`), call this to load them.`, + inputSchema: { type: 'object', properties: {} }, + annotations: { readOnlyHint: true }, + }; +} + /** * Build the `dcd mcp` server. Without a reachable hosted endpoint (no - * credentials yet, or an API without it), it still serves the dcd_* tools - * and says why on stderr. + * credentials yet, or an API without it), it still serves the dcd_* tools, + * says why on stderr, and lists load_device_tools, which says why too. */ export async function createBridgeServer( opts: { callTimeoutMs?: number } = {}, @@ -298,7 +343,8 @@ export async function createBridgeServer( const server = new Server( { name: 'devicecloud', version: getCliVersion() }, { - capabilities: { tools: {} }, + // listChanged: the device tools can arrive after the first listing. + capabilities: { tools: { listChanged: true } }, instructions: readOnly ? READ_ONLY_INSTRUCTIONS : INSTRUCTIONS, }, ); @@ -311,10 +357,13 @@ export async function createBridgeServer( // Read-only mode keeps only the tools that change nothing. .filter((t) => !readOnly || t.annotations?.readOnlyHint === true) .map((t) => withLocalInputs(t)); - } catch (error) { - logStderr( - `Device tools unavailable: ${error instanceof Error ? error.message : String(error)}. Serving the dcd_* tools only.`, - ); + } catch { + // remote.unavailable says why. + } + + if (remote.unavailable) { + logStderr(`Device tools unavailable: ${remote.unavailable}. Serving the dcd_* tools only.`); + return { tools: [...localTools, loadDeviceToolsTool(remote.unavailable)] }; } return { tools: [...localTools, ...deviceTools] }; @@ -330,8 +379,31 @@ export async function createBridgeServer( return (await local.callTool({ name, arguments: args }, undefined, options)) as CallToolResult; } + if (name === LOAD_DEVICE_TOOLS) { + return runTool(`device ${name}`, async () => { + const tools = await remote.list().catch(() => []); + if (tools.length === 0) { + return errorResult(`The device tools are still unavailable: ${remote.unavailable ?? 'no answer'}.`); + } + + await server.sendToolListChanged(); + return { + content: [ + { + type: 'text', + text: `Loaded the device tools: ${tools.map((t) => t.name).join(', ')}. List the tools again to see them.`, + }, + ], + }; + }); + } + return runTool(`device ${name}`, async () => { - await remote.list(); + await remote.list().catch(() => []); + if (remote.unavailable) { + return errorResult(`${name} is not available: the device tools could not be loaded (${remote.unavailable}).`); + } + if (!remote.has(name)) { // In read-only mode the hosted server lists only its read-only tools, // so a device tool that changes something is unknown here as well. diff --git a/src/mcp/local-files.ts b/src/mcp/local-files.ts new file mode 100644 index 0000000..65384f1 --- /dev/null +++ b/src/mcp/local-files.ts @@ -0,0 +1,83 @@ +/** + * The local files an MCP tool may read or write for the agent: only inside + * the working directory the server was started in (the agent's project), and + * a write never replaces a file this server did not write. An agent's tool + * call is not the user typing a path: without these limits a tool could + * send `~/.aws/credentials` as a flow, or write a report over `~/.zshrc`. + * Symbolic links are followed before the check, so a link can't lead out. + */ +import { existsSync, lstatSync, realpathSync } from 'node:fs'; +import * as path from 'node:path'; + +/** The working directory, as the file system names it (symbolic links resolved). */ +export function workingDirectory(): string { + return realpathSync(process.cwd()); +} + +/** Whether `child` is `parent` or inside it. Both absolute and resolved. */ +export function isInside(child: string, parent: string): boolean { + const relative = path.relative(parent, child); + return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); +} + +function outside(given: string, root: string): Error { + return new Error( + `${given} is outside the working directory (${root}). This server reads and writes files only there: start it in the folder that holds them, or copy them in.`, + ); +} + +/** An existing file or folder the agent named, resolved, inside the working directory. */ +export function localInput(given: string, root: string = workingDirectory()): string { + let real: string; + try { + real = realpathSync(path.resolve(root, given)); + } catch { + throw new Error(`No such file or directory: ${given}`); + } + + if (!isInside(real, root)) throw outside(given, root); + return real; +} + +/** Files this server wrote, which it may write again. */ +const written = new Set(); + +/** + * Where to write a file the agent asked for, resolved: inside the working + * directory, and not over a file this server did not write. Folders that do + * not exist yet are allowed; the writer makes them. + */ +export function localOutput(given: string, root: string = workingDirectory()): string { + const absolute = path.resolve(root, given); + // The deepest folder that exists, resolved; the rest is appended to it. + let existing = path.dirname(absolute); + const rest = [path.basename(absolute)]; + while (!existsSync(existing)) { + rest.unshift(path.basename(existing)); + const parent = path.dirname(existing); + if (parent === existing) break; + existing = parent; + } + + const target = path.join(realpathSync(existing), ...rest); + if (!isInside(target, root) || target === root) throw outside(given, root); + // lstat, not exists: a dangling symbolic link is a file there too. + let present: boolean; + try { + lstatSync(target); + present = true; + } catch { + present = false; + } + + if (present && !written.has(target)) { + throw new Error(`${given} already exists, and this server did not write it. Pass a new path, or remove the file first.`); + } + + return target; +} + +/** Record a file this server wrote, so a later call may write it again. */ +export function markWritten(file: string): void { + written.add(file); +} diff --git a/src/mcp/tools/download-artifacts.ts b/src/mcp/tools/download-artifacts.ts index 1a41988..fde0eaa 100644 --- a/src/mcp/tools/download-artifacts.ts +++ b/src/mcp/tools/download-artifacts.ts @@ -1,4 +1,4 @@ -import * as path from 'node:path'; +import { existsSync } from 'node:fs'; import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { z } from 'zod'; @@ -6,11 +6,15 @@ 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 { localOutput, markWritten } from '../local-files.js'; /** * Download a completed run's artifacts (zip) and/or a formatted report to local * disk. This reads cloud state and writes files locally — it does not change - * anything cloud-side, so it stays available in read-only mode. + * anything cloud-side, so it stays available in read-only mode. It does write + * files, so it is not annotated read-only: the files go inside the working + * directory only, and never over a file this server did not write + * (local-files.ts). * * The underlying service swallows download failures into `warnLogger` rather * than throwing (a missing-artifacts 404 isn't fatal), so we collect those @@ -23,6 +27,7 @@ export function registerDownloadArtifacts(server: McpServer): void { title: 'Download run artifacts', description: 'Download a completed test run\'s artifacts (videos/logs zip) and/or a formatted report to local disk. ' + + 'Paths are relative to the working directory this server runs in, and must stay inside it; an existing file this server did not write is never replaced. ' + 'Returns the resolved output paths and any warnings (a non-empty warnings array means a download could not be produced, e.g. no results yet).', inputSchema: { uploadId: z.string().describe('UUID of the upload to download artifacts for'), @@ -33,7 +38,7 @@ export function registerDownloadArtifacts(server: McpServer): void { artifactsPath: z .string() .optional() - .describe('Local path to write the artifacts zip (default ./artifacts.zip)'), + .describe('Where to write the artifacts zip, inside the working directory (default ./artifacts.zip)'), resultId: z .number() .int() @@ -59,10 +64,11 @@ export function registerDownloadArtifacts(server: McpServer): void { .string() .optional() .describe( - 'Local path for the report file (default ./report.xml for junit, ./report.html for allure, ./report.zip for html, which is a ZIP of report.html and its assets)', + 'Where to write the report, inside the working directory (default ./report.xml for junit, ./report.html for allure, ./report.zip for html, which is a ZIP of report.html and its assets)', ), }, - annotations: { readOnlyHint: true, openWorldHint: true }, + // It writes local files (nothing in the cloud), and never over one it did not write. + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, }, async (args) => runTool('dcd_download_artifacts', async () => { @@ -78,7 +84,16 @@ export function registerDownloadArtifacts(server: McpServer): void { logStderr(m); }; - const artifactsPath = args.artifactsPath ?? './artifacts.zip'; + // Both checked before anything is downloaded. + const artifactsPath = localOutput(args.artifactsPath ?? './artifacts.zip'); + const defaultReportPath = args.report + ? { allure: 'report.html', html: 'report.zip', junit: 'report.xml' }[args.report] + : undefined; + const reportPath = defaultReportPath ? localOutput(args.reportPath || defaultReportPath) : undefined; + if (reportPath && reportPath === artifactsPath) { + throw new Error('artifactsPath and reportPath name the same file. Give them different paths.'); + } + await service.downloadArtifacts({ apiUrl, auth, @@ -90,17 +105,11 @@ export function registerDownloadArtifacts(server: McpServer): void { logger: logStderr, warnLogger, }); + if (existsSync(artifactsPath)) markWritten(artifactsPath); - let reportPath: string | undefined; - if (args.report) { - // The HTML report is a ZIP of report.html plus assets; Allure's is - // a single HTML file. - const defaultReportPath = { - allure: 'report.html', - html: 'report.zip', - junit: 'report.xml', - }[args.report]; - reportPath = path.resolve(args.reportPath || defaultReportPath); + // The HTML report is a ZIP of report.html plus assets; Allure's is a + // single HTML file. + if (args.report && reportPath) { await service.downloadReports({ apiUrl, auth, @@ -112,11 +121,12 @@ export function registerDownloadArtifacts(server: McpServer): void { logger: logStderr, warnLogger, }); + if (existsSync(reportPath)) markWritten(reportPath); } return jsonResult({ uploadId: args.uploadId, - artifactsPath: path.resolve(artifactsPath), + artifactsPath, reportPath, warnings, }); diff --git a/test/unit/mcp-bridge.test.ts b/test/unit/mcp-bridge.test.ts index 937d1d5..81487fb 100644 --- a/test/unit/mcp-bridge.test.ts +++ b/test/unit/mcp-bridge.test.ts @@ -9,6 +9,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import { ToolListChangedNotificationSchema } from '@modelcontextprotocol/sdk/types.js'; import { z } from 'zod'; import { @@ -16,6 +17,7 @@ import { createBridgeServer, explainFailedStart, flowFileBundle, + LOAD_DEVICE_TOOLS, resolveLocalInputs, withLocalInputs, } from '../../src/mcp/bridge.js'; @@ -31,6 +33,8 @@ function startHosted(): Promise<{ http: HttpServer; ignoreReadOnly: boolean; inits: number; + /** Serve no tools, as for an organization without device sessions. */ + noTools: boolean; /** The connection name each request carried. */ instances: (string | undefined)[]; paths: string[]; @@ -43,6 +47,7 @@ function startHosted(): Promise<{ failStart: false, ignoreReadOnly: false, inits: 0, + noTools: false, instances: [] as (string | undefined)[], paths: [] as string[], sessions: [] as Record[], @@ -117,6 +122,8 @@ function startHosted(): Promise<{ for (const tool of registered) if (tool.annotations?.readOnlyHint !== true) tool.remove(); } + if (hosted.noTools) for (const tool of registered) tool.remove(); + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined }); await server.connect(transport); await transport.handleRequest(req, res, body); @@ -132,11 +139,14 @@ function startHosted(): Promise<{ describe('dcd mcp bridge', () => { const ORIGINAL_ENV = { ...process.env }; const ORIGINAL_ARGV = [...process.argv]; + const ORIGINAL_CWD = process.cwd(); let hosted: Awaited>; let tempDir: string; beforeEach(async () => { - tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-bridge-test-')); + // The bridge reads local files only inside its working directory. + tempDir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-bridge-test-'))); + process.chdir(tempDir); process.env.DCD_CONFIG_DIR = tempDir; process.env.DCD_TELEMETRY_DISABLED = '1'; process.env.DEVICE_CLOUD_API_KEY = 'test-key'; @@ -147,6 +157,7 @@ describe('dcd mcp bridge', () => { }); afterEach(async () => { + process.chdir(ORIGINAL_CWD); process.env = { ...ORIGINAL_ENV }; process.argv = [...ORIGINAL_ARGV]; clearContextCache(); @@ -328,6 +339,137 @@ describe('dcd mcp bridge', () => { await client.close(); }); + describe('when the device tools are missing', () => { + it('lists load_device_tools, saying why, and loads them once the account has them', async () => { + hosted.noTools = true; + const client = await connect(); + const first = (await client.listTools()).tools; + expect(first.map((t) => t.name)).to.include(LOAD_DEVICE_TOOLS).and.not.include('run'); + expect(first.find((t) => t.name === LOAD_DEVICE_TOOLS)!.description).to.include('may not be enabled'); + + // A device tool called anyway says why it can't run. + const refused = await client.callTool({ name: 'run', arguments: { yaml: 'x' } }); + expect(refused.isError).to.equal(true); + expect(JSON.stringify(refused.content)).to.include('could not be loaded'); + + let changed = 0; + client.setNotificationHandler(ToolListChangedNotificationSchema, async () => { + changed++; + }); + hosted.noTools = false; + const loaded = await client.callTool({ name: LOAD_DEVICE_TOOLS, arguments: {} }); + expect(loaded.isError).to.not.equal(true); + expect(JSON.stringify(loaded.content)).to.include('run'); + await new Promise((r) => setTimeout(r, 20)); + expect(changed).to.equal(1); + expect((await client.listTools()).tools.map((t) => t.name)).to.include('run').and.not.include(LOAD_DEVICE_TOOLS); + await client.close(); + }); + }); + + describe('local files', () => { + const ctx = () => ({ apiUrl: 'https://api.example.test', auth: { headers: {}, mode: 'apiKey' as const } }); + + it('refuses a flow outside the working directory, or a file that is not a flow', async () => { + const elsewhere = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-bridge-elsewhere-')); + try { + fs.writeFileSync(path.join(elsewhere, 'flow.yaml'), 'appId: x\n---\n- launchApp\n'); + for (const given of [path.join(elsewhere, 'flow.yaml'), path.join('..', path.basename(elsewhere), 'flow.yaml')]) { + try { + await resolveLocalInputs('run', { path: given }, ctx()); + expect.fail('should have thrown'); + } catch (error) { + expect((error as Error).message).to.include('outside the working directory'); + } + } + + // A link inside that leads out is the same thing. + fs.symlinkSync(path.join(elsewhere, 'flow.yaml'), path.join(tempDir, 'linked.yaml')); + try { + await resolveLocalInputs('run', { path: 'linked.yaml' }, ctx()); + expect.fail('should have thrown'); + } catch (error) { + expect((error as Error).message).to.include('outside the working directory'); + } + } finally { + fs.rmSync(elsewhere, { force: true, recursive: true }); + } + + fs.writeFileSync(path.join(tempDir, 'notes.txt'), 'secret'); + try { + await resolveLocalInputs('run', { path: 'notes.txt' }, ctx()); + expect.fail('should have thrown'); + } catch (error) { + expect((error as Error).message).to.include('is not a flow file'); + } + }); + + it('refuses a flow inside whose files reach outside the working directory', async () => { + const work = path.join(tempDir, 'work'); + fs.mkdirSync(path.join(tempDir, 'shared')); + fs.mkdirSync(work); + fs.writeFileSync(path.join(tempDir, 'shared', 'login.yaml'), 'appId: x\n---\n- tapOn: Log in\n'); + fs.writeFileSync(path.join(work, 'main.yaml'), 'appId: x\n---\n- runFlow: ../shared/login.yaml\n'); + try { + await resolveLocalInputs('run', { path: 'main.yaml' }, ctx(), work); + expect.fail('should have thrown'); + } catch (error) { + expect((error as Error).message).to.include('uses files outside the working directory'); + } + }); + + it('sends the entry of a directory with forward slashes, as the API takes it', async () => { + fs.mkdirSync(path.join(tempDir, 'flows', 'sub'), { recursive: true }); + fs.writeFileSync(path.join(tempDir, 'flows', 'sub', 'login.yaml'), 'appId: x\n---\n- launchApp\n'); + const realFetch = globalThis.fetch; + globalThis.fetch = (async (input: unknown) => { + const url = String(input); + if (url.endsWith('/device/bundles/upload-url')) { + return new Response(JSON.stringify({ id: 'b-1', upload: { path: 'p', signedUrl: 'https://sb.example/put' }, mirror: null })); + } + + if (url === 'https://sb.example/put') return new Response(null, { status: 200 }); + if (url.endsWith('/device/bundles')) { + return new Response(JSON.stringify({ bundle: { id: 'b-1', sha: 's', bytes: 1, encrypted: false, created_at: 'now' } })); + } + + return new Response('{}', { status: 404 }); + }) as typeof fetch; + try { + const args = await resolveLocalInputs('run', { path: 'flows', flow: 'sub\\login.yaml' }, ctx()); + expect(args).to.deep.equal({ flow: 'sub/login.yaml', flow_upload_id: 'b-1' }); + } finally { + globalThis.fetch = realFetch; + } + }); + + it('start_device takes app_path, and refuses it with app_binary_id', async () => { + const start = withLocalInputs({ + name: 'start_device', + description: 'Start.', + inputSchema: { type: 'object' as const, properties: { platform: {} } }, + }); + expect(start.inputSchema.properties).to.have.keys('platform', 'app_path'); + expect(start.description).to.include('uploaded before the session starts'); + try { + await resolveLocalInputs('start_device', { platform: 'ios', app_path: 'a.zip', app_binary_id: 'b1' }, ctx()); + expect.fail('should have thrown'); + } catch (error) { + expect((error as Error).message).to.include('not both'); + } + }); + + it('start_device uploads a local build before the session starts', async () => { + const client = await connect(); + await client.listTools(); + const result = await client.callTool({ name: 'start_device', arguments: { platform: 'ios', app_path: 'missing.zip' } }); + // The upload failed on the missing file, so no session was started. + expect(result.isError).to.equal(true); + expect(hosted.calls).to.deep.equal([]); + await client.close(); + }); + }); + describe('helpers', () => { it('explainFailedStart says it is safe to retry when no session started', async () => { hosted.sessions = []; @@ -382,7 +524,7 @@ describe('dcd mcp bridge', () => { }); it('resolveLocalInputs leaves calls without local inputs alone, and refuses a missing path', async () => { - const ctx = { apiUrl: 'http://x', auth: { headers: {}, mode: 'apiKey' as const } }; + const ctx = { apiUrl: 'http://localhost:9', auth: { headers: {}, mode: 'apiKey' as const } }; expect(await resolveLocalInputs('run', { yaml: 'y' }, ctx)).to.deep.equal({ yaml: 'y' }); try { await resolveLocalInputs('run', { path: path.join(tempDir, 'nope') }, ctx); diff --git a/test/unit/mcp-local-files.test.ts b/test/unit/mcp-local-files.test.ts new file mode 100644 index 0000000..6995545 --- /dev/null +++ b/test/unit/mcp-local-files.test.ts @@ -0,0 +1,98 @@ +import { expect } from 'chai'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; + +import { clearContextCache } from '../../src/mcp/context.js'; +import { isInside, localInput, localOutput, markWritten } from '../../src/mcp/local-files.js'; +import { createServer } from '../../src/mcp/server.js'; + +/** + * The files an MCP tool reads or writes for an agent stay inside the + * working directory, and a write never replaces a file the server did not + * write: an agent's tool call is not the user typing a path. + */ +describe('MCP local files', () => { + const ORIGINAL_CWD = process.cwd(); + const ORIGINAL_ENV = { ...process.env }; + let root: string; + let elsewhere: string; + + beforeEach(() => { + root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-local-files-'))); + elsewhere = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-local-elsewhere-'))); + }); + + afterEach(() => { + process.chdir(ORIGINAL_CWD); + process.env = { ...ORIGINAL_ENV }; + clearContextCache(); + fs.rmSync(root, { force: true, recursive: true }); + fs.rmSync(elsewhere, { force: true, recursive: true }); + }); + + it('isInside takes the folder itself and what is under it, and nothing beside it', () => { + expect(isInside('/a/b', '/a/b')).to.equal(true); + expect(isInside('/a/b/c.zip', '/a/b')).to.equal(true); + expect(isInside('/a/bc', '/a/b')).to.equal(false); + expect(isInside('/a', '/a/b')).to.equal(false); + }); + + it('localInput resolves a path inside, and refuses one outside or missing', () => { + fs.writeFileSync(path.join(root, 'flow.yaml'), ''); + fs.writeFileSync(path.join(elsewhere, 'secret.yaml'), ''); + expect(localInput('flow.yaml', root)).to.equal(path.join(root, 'flow.yaml')); + expect(() => localInput(path.join(elsewhere, 'secret.yaml'), root)).to.throw('outside the working directory'); + expect(() => localInput('nope.yaml', root)).to.throw('No such file or directory'); + }); + + it('localOutput writes inside only, into new folders too, and never over a file it did not write', () => { + expect(localOutput('out/new/artifacts.zip', root)).to.equal(path.join(root, 'out', 'new', 'artifacts.zip')); + expect(() => localOutput(path.join(elsewhere, 'a.zip'), root)).to.throw('outside the working directory'); + expect(() => localOutput('../a.zip', root)).to.throw('outside the working directory'); + + const existing = path.join(root, '.zshrc'); + fs.writeFileSync(existing, 'mine'); + expect(() => localOutput('.zshrc', root)).to.throw('already exists, and this server did not write it'); + + // One it wrote itself may be written again. + const report = localOutput('report.xml', root); + fs.writeFileSync(report, ''); + markWritten(report); + expect(localOutput('report.xml', root)).to.equal(report); + }); + + it('localOutput follows a link to its folder before the check', () => { + fs.symlinkSync(elsewhere, path.join(root, 'out')); + expect(() => localOutput('out/a.zip', root)).to.throw('outside the working directory'); + }); + + it('dcd_download_artifacts refuses a path outside the working directory before downloading, and says it writes files', async () => { + process.chdir(root); + process.env.DEVICE_CLOUD_API_KEY = 'test-key'; + process.env.DCD_TELEMETRY_DISABLED = '1'; + // Nothing should be fetched: the path is refused first. + process.env.DCD_API_URL = 'http://127.0.0.1:9'; + clearContextCache(); + const [a, b] = InMemoryTransport.createLinkedPair(); + await createServer().connect(b); + const client = new Client({ name: 'agent', version: '1' }); + await client.connect(a); + + const tool = (await client.listTools()).tools.find((t) => t.name === 'dcd_download_artifacts')!; + expect(tool.annotations?.readOnlyHint).to.equal(false); + expect(tool.annotations?.destructiveHint).to.equal(false); + + const result = await client.callTool({ + name: 'dcd_download_artifacts', + arguments: { uploadId: '00000000-0000-0000-0000-000000000000', artifactsPath: path.join(elsewhere, 'a.zip') }, + }); + expect(result.isError).to.equal(true); + expect(JSON.stringify(result.content)).to.include('outside the working directory'); + expect(fs.readdirSync(elsewhere)).to.deep.equal([]); + await client.close(); + }); +}); From b49be1bda50af8a697f9e2628655b85114694463 Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Wed, 18 Nov 2026 19:56:35 +0000 Subject: [PATCH 4/7] fix: check an API URL given by hand, and keep signed links out of telemetry - --api-url and DCD_API_URL are checked before credentials are sent: plain http is refused except to this machine, a user name in the URL is refused, and a host outside devicecloud.dev is allowed with a warning on stderr. - Telemetry drops the query, fragment and user info of every link in the command line and in error messages, so a signed build link given to `device start --app` or `device install` is not kept. Its events go to a hand-given API URL only when the command itself would use it. --- src/services/telemetry.service.ts | 31 ++++++++-- src/utils/api-url.ts | 59 +++++++++++++++++++ src/utils/config-store.ts | 23 +++++++- test/unit/api-url.test.ts | 79 ++++++++++++++++++++++++++ test/unit/telemetry-scrub-argv.test.ts | 26 ++++++++- 5 files changed, 209 insertions(+), 9 deletions(-) create mode 100644 src/utils/api-url.ts create mode 100644 test/unit/api-url.test.ts diff --git a/src/services/telemetry.service.ts b/src/services/telemetry.service.ts index 7b6a234..b19b894 100644 --- a/src/services/telemetry.service.ts +++ b/src/services/telemetry.service.ts @@ -19,6 +19,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { AuthContext } from '../types/domain/auth.types.js'; +import { checkApiUrl } from '../utils/api-url.js'; import { getCliVersion, getInstallMethod } from '../utils/cli.js'; import type { EncryptionSource } from '../utils/envelope.js'; @@ -149,7 +150,7 @@ class Telemetry { this.enqueue('error', 'cli.mcp', 'mcp tool failed', { tool, duration_ms: durationMs, - error_message: error instanceof Error ? error.message : String(error), + error_message: redactUrls(error instanceof Error ? error.message : String(error)), error_name: error instanceof Error ? error.name : 'Error', ...extra, }); @@ -228,11 +229,12 @@ class Telemetry { this.enqueue('error', 'cli.lifecycle', 'command failed', { duration_ms: Date.now() - this.startedAt, exit_code: opts.exitCode, - error_message: message, + // A failed install from a signed link says the link. + error_message: redactUrls(message), error_name: opts.error instanceof Error ? opts.error.name : 'CliError', error_stack: - opts.error instanceof Error ? opts.error.stack : undefined, + opts.error instanceof Error && opts.error.stack ? redactUrls(opts.error.stack) : undefined, ...this.encryptionExtra(), ...this.submitExtra(), }); @@ -362,6 +364,20 @@ const SENSITIVE_FLAG_NAMES = new Set([ const REDACTED = ''; +/** + * Links in `text` without their query, fragment and user info. A signed + * download link's query is its credential (`?X-Amz-Signature=…`), and `dcd + * device start --app ` and `install ` take one as a plain value. + * Where the link points stays, for telling failures apart. + */ +export function redactUrls(text: string): string { + return text.replaceAll( + /\b([a-z][a-z0-9+.-]*:\/\/)([^\s/?#]*@)?([^\s?#]*)(\?[^\s#]*)?(#\S*)?/gi, + (_match, scheme: string, user: string | undefined, rest: string, query: string | undefined, fragment: string | undefined) => + `${scheme}${user ? `${REDACTED}@` : ''}${rest}${query ? `?${REDACTED}` : ''}${fragment ? `#${REDACTED}` : ''}`, + ); +} + /** * The argv a command was run with, as telemetry may keep it: without the * values of the flags above, and without what two `dcd device` subcommands @@ -413,7 +429,7 @@ export function scrubArgv(args: string[]): string[] { scrubbed.push(arg); } } - return scrubbed; + return scrubbed.map((arg) => redactUrls(arg)); } // argv layout: node|tsx, script, command, ...flags. The first non-flag after @@ -434,11 +450,14 @@ const API_URL_FLAGS = ['--api-url', '--apiURL', '--apiUrl']; function inferApiUrlFromArgv(): string { 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); 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 args[i + 1]; - if (arg.startsWith(`${flag}=`)) return arg.slice(flag.length + 1); + 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; diff --git a/src/utils/api-url.ts b/src/utils/api-url.ts new file mode 100644 index 0000000..f7114b4 --- /dev/null +++ b/src/utils/api-url.ts @@ -0,0 +1,59 @@ +/** + * Checks for an API URL given by hand (`--api-url`, `DCD_API_URL`), before + * any credential is sent to it: the API key or login session goes with every + * request, and a repository's MCP config can set DCD_API_URL. No imports, so + * the telemetry service can use it too. + */ + +/** This machine: plain http is fine, for a local API. */ +function isLocalHost(host: string): boolean { + return host === 'localhost' || host.endsWith('.localhost') || host === '127.0.0.1' || host === '[::1]'; +} + +/** DeviceCloud's own hosts. */ +function isDeviceCloudHost(host: string): boolean { + return host === 'devicecloud.dev' || host.endsWith('.devicecloud.dev'); +} + +export type ApiUrlCheck = + | { ok: false; reason: string } + | { ok: true; origin: string; warning: null | string }; + +/** + * Whether credentials may be sent to `raw`: an http(s) URL with no user name + * or password in it, and plain http only to this machine. A host that is not + * devicecloud.dev passes with a warning (a staging or self-run API). + */ +export function checkApiUrl(raw: string): ApiUrlCheck { + let url: URL; + try { + url = new URL(raw); + } catch { + return { ok: false, reason: `The API URL "${raw}" is not a URL. Use one like https://api.devicecloud.dev.` }; + } + + const host = url.hostname.toLowerCase(); + if (url.protocol !== 'https:' && url.protocol !== 'http:') { + return { ok: false, reason: `The API URL must start with https://, not ${url.protocol}//.` }; + } + + if (url.username || url.password) { + return { ok: false, reason: 'The API URL must not contain a user name or password.' }; + } + + if (url.protocol === 'http:' && !isLocalHost(host)) { + return { + ok: false, + reason: `Refusing to send your API key or login session to ${url.origin} over plain http, where anyone on the way can read it. Use https.`, + }; + } + + const trusted = isDeviceCloudHost(host) || isLocalHost(host); + return { + ok: true, + origin: url.origin, + warning: trusted + ? null + : `The API URL ${url.origin} is not a devicecloud.dev host. Your API key or login session is sent to it with every request.`, + }; +} diff --git a/src/utils/config-store.ts b/src/utils/config-store.ts index 52133e4..f86fb4f 100644 --- a/src/utils/config-store.ts +++ b/src/utils/config-store.ts @@ -22,6 +22,8 @@ import { homedir } from 'node:os'; import * as path from 'node:path'; import { ENVIRONMENTS } from '../config/environments.js'; +import { checkApiUrl } from './api-url.js'; +import { CliError } from './cli.js'; export const CONFIG_SCHEMA_VERSION = 1; @@ -80,19 +82,36 @@ export function readConfig(): StoredConfig | null { } } +/** Hosts already warned about in this process: the MCP server resolves its URL again and again. */ +const warnedHosts = new Set(); + /** * Resolve the API URL a command should talk to. Precedence: - * 1. explicit --api-url flag + * 1. explicit --api-url flag (or DCD_API_URL, for the MCP server) * 2. api_url stored by `dcd login` (honors the env the user logged into) * 3. prod default * * Without this, session commands default to prod and a dev/staging Bearer * token is rejected with a misleading "Invalid or expired JWT". `switch-org` * has always done this; this helper extends it to every command. + * + * An explicit URL is checked first, since the credentials go to it + * (checkApiUrl): plain http is refused except to this machine, and a host + * other than devicecloud.dev gets a warning on stderr, once. */ export function resolveApiUrl(flag: string | undefined): string { const explicit = flag?.trim(); - if (explicit) return explicit; + if (explicit) { + const check = checkApiUrl(explicit); + if (!check.ok) throw new CliError(check.reason); + if (check.warning && !warnedHosts.has(check.origin)) { + warnedHosts.add(check.origin); + process.stderr.write(`Warning: ${check.warning}\n`); + } + + return explicit; + } + return readConfig()?.api_url ?? ENVIRONMENTS.prod.apiUrl; } diff --git a/test/unit/api-url.test.ts b/test/unit/api-url.test.ts new file mode 100644 index 0000000..67154f8 --- /dev/null +++ b/test/unit/api-url.test.ts @@ -0,0 +1,79 @@ +import { expect } from 'chai'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +import { checkApiUrl } from '../../src/utils/api-url.js'; +import { CliError } from '../../src/utils/cli.js'; +import { resolveApiUrl } from '../../src/utils/config-store.js'; + +/** + * Your API key or login session goes with every request to the API URL, so + * one given by hand (--api-url, DCD_API_URL) is checked before it is used. + */ +describe('an API URL given by hand', () => { + const ORIGINAL_ENV = { ...process.env }; + let configDir: string; + + beforeEach(() => { + configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-api-url-')); + process.env.DCD_CONFIG_DIR = configDir; + }); + + afterEach(() => { + process.env = { ...ORIGINAL_ENV }; + fs.rmSync(configDir, { force: true, recursive: true }); + }); + + it('accepts DeviceCloud hosts, and plain http only to this machine', () => { + expect(checkApiUrl('https://api.devicecloud.dev')).to.deep.equal({ + ok: true, + origin: 'https://api.devicecloud.dev', + warning: null, + }); + expect(checkApiUrl('https://dev-api.devicecloud.dev/').ok).to.equal(true); + for (const local of ['http://localhost:3001', 'http://127.0.0.1:3000', 'http://[::1]:8080', 'http://api.localhost']) { + expect(checkApiUrl(local)).to.include({ ok: true, warning: null }); + } + }); + + it('refuses plain http elsewhere, a user name in the URL, another scheme, and text that is not a URL', () => { + const reason = (url: string) => { + const check = checkApiUrl(url); + return check.ok ? '' : check.reason; + }; + + expect(reason('http://api.example.com')).to.include('over plain http'); + expect(reason('https://user:pass@api.devicecloud.dev')).to.include('user name or password'); + expect(reason('ftp://api.devicecloud.dev')).to.include('must start with https://'); + expect(reason('api.devicecloud.dev')).to.include('is not a URL'); + }); + + it('warns about a host that is not devicecloud.dev, but allows it', () => { + const check = checkApiUrl('https://api.example.com'); + expect(check.ok).to.equal(true); + expect(check.ok && check.warning).to.include('not a devicecloud.dev host'); + // A name that only ends in the same letters is not ours. + const lookalike = checkApiUrl('https://evildevicecloud.dev'); + expect(lookalike.ok).to.equal(true); + expect(lookalike.ok && lookalike.warning).to.include('not a devicecloud.dev host'); + }); + + it('resolveApiUrl refuses before anything is sent, and warns once per host on stderr', () => { + expect(() => resolveApiUrl('http://api.example.com')).to.throw(CliError, 'over plain http'); + let stderr = ''; + const write = process.stderr.write.bind(process.stderr); + process.stderr.write = ((chunk: string) => { + stderr += chunk; + return true; + }) as typeof process.stderr.write; + try { + expect(resolveApiUrl('https://staging.example.net')).to.equal('https://staging.example.net'); + expect(resolveApiUrl('https://staging.example.net/')).to.equal('https://staging.example.net/'); + } finally { + process.stderr.write = write; + } + + expect(stderr.split('not a devicecloud.dev host')).to.have.length(2); + }); +}); diff --git a/test/unit/telemetry-scrub-argv.test.ts b/test/unit/telemetry-scrub-argv.test.ts index 972987b..a2ae25e 100644 --- a/test/unit/telemetry-scrub-argv.test.ts +++ b/test/unit/telemetry-scrub-argv.test.ts @@ -1,6 +1,6 @@ import { expect } from 'chai'; -import { scrubArgv } from '../../src/services/telemetry.service.js'; +import { redactUrls, scrubArgv } from '../../src/services/telemetry.service.js'; /** * Telemetry keeps the argv of every command. What a caller gives a command @@ -10,6 +10,30 @@ import { scrubArgv } from '../../src/services/telemetry.service.js'; describe('telemetry: scrubArgv', () => { const R = ''; + it("keeps a signed build link's query, user and fragment out, wherever the link is given", () => { + expect( + scrubArgv(['device', 'start', '--app', 'https://bucket.example/app.apk?X-Amz-Signature=abc&X-Amz-Credential=def']), + ).to.deep.equal(['device', 'start', '--app', `https://bucket.example/app.apk?${R}`]); + expect(scrubArgv(['device', 'install', 'a-b-c', 'https://ci.example/build.zip?token=abc'])).to.deep.equal([ + 'device', + 'install', + 'a-b-c', + `https://ci.example/build.zip?${R}`, + ]); + expect(scrubArgv(['device', 'start', '--app=https://u:p@host.example/a.zip#frag'])).to.deep.equal([ + 'device', + 'start', + `--app=https://${R}@host.example/a.zip#${R}`, + ]); + }); + + it('redactUrls cleans links inside error text, and leaves other text alone', () => { + expect(redactUrls('Could not download https://x.example/a.apk?sig=1 (403).')).to.equal( + `Could not download https://x.example/a.apk?${R} (403).`, + ); + expect(redactUrls('No link here: brave-teal-otter')).to.equal('No link here: brave-teal-otter'); + }); + it('redacts the link of device open-link, with or without --sensitive, wherever it sits', () => { expect(scrubArgv(['device', 'open-link', 'myapp://sign-in?token=SECRET', '--sensitive'])).to.deep.equal([ 'device', From 62044a7efe0dde189bc61954aa2d8a64a7abb36d Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Wed, 18 Nov 2026 19:56:35 +0000 Subject: [PATCH 5/7] docs: describe where the MCP server reads and writes local files --- CLAUDE.md | 4 ++-- README.md | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a561baf..03717cf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -28,7 +28,7 @@ Top-level `defineCommand` in `src/index.ts` wires fourteen subcommands (`cloud`, **Flag composition.** Flag definitions are split by domain in `src/config/flags/*.flags.ts` (api, binary, device, environment, execution, github, output) and re-exported as a single `flags` object from `src/constants.ts`. Commands that need the full cloud surface spread `...flags` into their citty `args`; subset commands import individual flag groups. -**`dcd device` (Agent Devices).** Cloud device sessions that a person or an AI agent leases, drives and releases, over the API's `/device/sessions` routes (`src/gateways/device-gateway.ts`). Its rules differ from the other commands, and scripts and agents depend on them: `--json` prints one envelope, `{ ok, session, data, error }`, even on failure (`runDeviceCommand` in `src/utils/device-output.ts` prints it, so the top-level `{ status, error }` never appears); exit codes are 0 ok, 1 usage, 2 failed, 3 limit, 4 session ended or not found (`DEVICE_EXIT`); the session id may be left out when exactly one session is open (`resolveSessionId`); progress goes to stderr and there is no spinner unless stdin and stdout are TTYs. `DeviceApiError` keeps the API's machine code (`LIVE_NOT_FOUND`, …) and the `session` block an error carries, which `ApiError` drops. +**`dcd device` (Agent Devices).** Cloud device sessions that a person or an AI agent leases, drives and releases, over the API's `/device/sessions` routes (`src/gateways/device-gateway.ts`). Its rules differ from the other commands, and scripts and agents depend on them: `--json` prints one envelope, `{ ok, session, data, error }`, even on failure (`runDeviceCommand` in `src/utils/device-output.ts` prints it, so the top-level `{ status, error }` never appears); exit codes are 0 ok, 1 usage, 2 failed, 3 limit, 4 session ended or not found (`DEVICE_EXIT`); the session id may be left out when exactly one session of yours is open (`resolveSessionId`; `artifacts` takes your most recent one, ended or not), and one given must look like a session id (`checkSessionId`); progress goes to stderr and there is no spinner unless stdin and stdout are TTYs. Every subcommand refuses a flag it does not define (`strictFlags` in `src/utils/device-flags.ts`), since citty ignores unknown ones, and an unknown subcommand under `--json` still gets the envelope (`deviceCommand.setup`). Waits ask again through failed polls (`pollOnce`), and a wait for a flow ends with its session. `DeviceApiError` keeps the API's machine code (`LIVE_NOT_FOUND`, …) and the `session` block an error carries, which `ApiError` drops. **Output rendering.** All human-facing output goes through `src/utils/ui.ts` (the canonical layer: `section`/`branch`/`fields`/`status`/`success`/`info`/`warn`) on top of `src/utils/styling.ts` (`colors`, `symbols`, `statusPalette`). The visual language is a Claude Code-style tree (`⏺` section headings, `⎿` branch groups). Commands must not hand-roll layouts from `colors`/`symbols` or call `console.log`; the `--json` result goes through `logger.json`. Every command takes `--json` (`jsonFlag`), and `src/index.ts` turns thrown errors into `{ status: 'FAILED', error }` whenever `--json` is in argv. Full rules and a cookbook live in `STYLE_GUIDE.md`. @@ -53,7 +53,7 @@ Top-level `defineCommand` in `src/index.ts` wires fourteen subcommands (`cloud`, **MCP server.** `src/mcp/` is a third front-end onto the same service layer (a sibling to `src/commands/`), shipped as the `dcd-mcp` bin over stdio transport (`@modelcontextprotocol/sdk`, `zod` schemas). `index.ts` boots the server; `server.ts` registers tools; `context.ts` resolves auth + API URL **lazily**, and again when a `dcd login` session nears expiry (so `tools/list` works unauthenticated, auth errors surface as tool errors rather than a boot crash, and a long-lived server outlasts the one-hour access token) via the same `resolveAuth`/`resolveApiUrl` as the CLI — `DEVICE_CLOUD_API_KEY` env or stored `dcd login` session, with `DCD_API_URL` to override. **Critical invariant: stdout is the JSON-RPC channel** — tools must never call the `src/commands/*` layer or `utils/cli` `logger` (both write to stdout / can `process.exit`); they call services/gateways directly with `logStderr` and return data via `helpers.ts` `jsonResult`/`errorResult`. The `runTool` wrapper records `mcp tool …` telemetry and converts thrown errors to `isError` results. Tools: `dcd_list_devices`, `dcd_list_runs`, `dcd_get_status`, `dcd_download_artifacts`, `dcd_get_team_settings` (read-only), and `dcd_run_cloud_test` (billable — gated out by `--read-only` / `DCD_MCP_READONLY=1`, annotated destructive, async-by-default). `dcd_run_cloud_test` reuses `computeCommonRoot`/`buildTestMetadataMap` from `src/services/flow-paths.ts` (extracted from `cloud.ts` so both build identical server-side paths). Registry manifest: `server.json` at repo root. -**`dcd mcp` (the bridge).** A second stdio entry point, `src/mcp/bridge.ts`, run by the `dcd mcp` command. It is a low-level `Server` that routes between two MCP clients: the `dcd_*` tools from the same in-process `createServer()` (over an in-memory transport), and the device tools proxied from the hosted `/mcp`, so those are defined and contract-tested once, in the dcd API. It adds the inputs only a local process can serve: `install_app` takes `app_path` (uploaded with `uploadLocalApp`) and `run` takes `path` (a file is sent as `yaml`, a directory is uploaded as a flow bundle). Credentials are the CLI's (`getContext`): the hosted `/mcp` accepts an API key or a `dcd login` session with `x-dcd-org`. One connection is shared, and its `fetch` re-reads the auth headers from `getContext()` on every request, so a renewed session is picked up without remaking the connection (which would close it under a `run` still going). If the hosted endpoint can't be reached, it serves the `dcd_*` tools only and says why on stderr. Read-only mode keeps only device tools annotated `readOnlyHint`. `dcd-mcp` itself is unchanged. +**`dcd mcp` (the bridge).** A second stdio entry point, `src/mcp/bridge.ts`, run by the `dcd mcp` command. It is a low-level `Server` that routes between two MCP clients: the `dcd_*` tools from the same in-process `createServer()` (over an in-memory transport), and the device tools proxied from the hosted `/mcp`, so those are defined and contract-tested once, in the dcd API. It adds the inputs only a local process can serve: `start_device` and `install_app` take `app_path` (uploaded with `uploadLocalApp`, before the session starts for `start_device`) and `run` takes `path` (a file that uses no other files is sent as `yaml`; one that does, or a directory, is uploaded as a flow bundle of only what the entry reaches). `path`, and what `dcd_download_artifacts` writes, must be inside the working directory, and a write never replaces a file the server did not write (`src/mcp/local-files.ts`). When the device tools can't be listed it lists `load_device_tools` instead, whose description says why, and sends `tools/list_changed` once they load. Credentials are the CLI's (`getContext`): the hosted `/mcp` accepts an API key or a `dcd login` session with `x-dcd-org`. One connection is shared, and its `fetch` re-reads the auth headers from `getContext()` on every request, so a renewed session is picked up without remaking the connection (which would close it under a `run` still going). If the hosted endpoint can't be reached, it serves the `dcd_*` tools only and says why on stderr. Read-only mode keeps only device tools annotated `readOnlyHint`. `dcd-mcp` itself is unchanged. **`dcd mcp install [client]`** (`src/utils/mcp-install.ts`) adds the server to Claude Code (`claude mcp add --scope user`), VS Code (`code --add-mcp`), or Claude Desktop / Cursor (merges an entry into their JSON config, and refuses a file that isn't plain JSON rather than rewrite it). Entries always start dcd by **full path**, since desktop apps opened from the Dock don't read the shell rc that puts `~/.dcd/bin` on PATH: the standalone binary is `process.execPath`; an npm install is node (`stableNodePath`, the PATH entry rather than Homebrew's versioned Cellar path) plus `argv[1]` as started, not resolved. It refuses to run from source or from the npx cache. Note citty runs a parent's `run` **after** its subcommand, so `mcpCommand.run` returns early when a positional is present — without that, `dcd mcp install` would go on to start a server. diff --git a/README.md b/README.md index b465c52..3f5f607 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,9 @@ $ codex mcp add devicecloud -- dcd mcp If you use the npm package instead of the standalone binary, the command is `npx` with `"args": ["-y", "@devicecloud.dev/dcd", "mcp"]`. That needs Node 22 or newer on the app's PATH, and it checks npm each time it starts. -It signs in the same way as the CLI: with your `dcd login` session, which it renews as it runs, or with `DEVICE_CLOUD_API_KEY`. Point it at a non-prod environment with `DCD_API_URL`. +It signs in the same way as the CLI: with your `dcd login` session, which it renews as it runs, or with `DEVICE_CLOUD_API_KEY`. Point it at a non-prod environment with `DCD_API_URL` (https, or plain http to `localhost` only). + +The tools that take a local path read and write only inside the folder the server was started in, so start it from your project: a flow given to `run` (with the files it uses), and the files `dcd_download_artifacts` writes, which never replace a file the server did not write. ### Tools @@ -116,7 +118,7 @@ It signs in the same way as the CLI: with your `dcd login` session, which it ren | `dcd_list_devices` | Discover available devices, OS versions, and Maestro versions | | `dcd_list_runs` | List recent test runs (filter by name/date, paginated) | | `dcd_get_status` | Get the status + per-test results of a run | -| `dcd_download_artifacts` | Download a run's artifacts/report to disk | +| `dcd_download_artifacts` | Download a run's artifacts/report to disk, inside the working directory | | `dcd_get_team_settings` | Read your team's settings: concurrency, test runtime, integrations and more | | `dcd_run_cloud_test` | Submit a flow to run on the cloud (**billable**) | From f80e1c8db4831ca9d92b035d9b8895f772f94e84 Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Thu, 19 Nov 2026 11:25:52 +0000 Subject: [PATCH 6/7] fix(device): call the starting API key's name key_name started_by.api_key_name is renamed key_name, here and in the API. It is a key's label, such as "CI", never the key itself, but the old name read as a secret to code scanning, which flagged printing it. Nothing released sends or reads the old name. --- src/types/domain/device-session.types.ts | 5 +++-- src/utils/device-output.ts | 2 +- test/unit/device-command.test.ts | 6 +++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/types/domain/device-session.types.ts b/src/types/domain/device-session.types.ts index f448279..1941ad9 100644 --- a/src/types/domain/device-session.types.ts +++ b/src/types/domain/device-session.types.ts @@ -58,9 +58,10 @@ export interface DeviceSession { /** Who started a session. */ export interface DeviceSessionStarter { - /** The person who started it, when a person did. */ - api_key_name: null | string; + /** The name of the API key that started it, when one did: its label, never the key. */ + key_name: null | string; client_label: null | string; + /** The person who started it, when a person did. */ email: null | string; /** Started from this connection (the same `dcd mcp` process). */ this_client: boolean; diff --git a/src/utils/device-output.ts b/src/utils/device-output.ts index 9f86a6c..44285e2 100644 --- a/src/utils/device-output.ts +++ b/src/utils/device-output.ts @@ -174,7 +174,7 @@ export async function resolveSessionId( export function startedByLabel(starter: DeviceSessionStarter): string { if (starter.you) return starter.this_client ? 'you, this connection' : 'you'; if (starter.email) return `started by ${starter.email}`; - if (starter.api_key_name) return `started with API key "${starter.api_key_name}"`; + if (starter.key_name) return `started with API key "${starter.key_name}"`; return 'started by someone else'; } diff --git a/test/unit/device-command.test.ts b/test/unit/device-command.test.ts index cdae27e..7ec6e04 100644 --- a/test/unit/device-command.test.ts +++ b/test/unit/device-command.test.ts @@ -248,13 +248,13 @@ describe('dcd device', () => { it("takes your only session, never someone else's", async () => { stubFetch(() => ({ - body: { sessions: [session('theirs', { started_by: { api_key_name: null, client_label: 'claude-code', email: 'ann@example.com', this_client: false, you: false } }), session('yours', { started_by: { api_key_name: null, client_label: null, email: null, this_client: false, you: true } })] }, + body: { sessions: [session('theirs', { started_by: { key_name: null, client_label: 'claude-code', email: 'ann@example.com', this_client: false, you: false } }), session('yours', { started_by: { key_name: null, client_label: null, email: null, this_client: false, you: true } })] }, })); expect(await resolveSessionId(API, auth, undefined)).to.equal('yours'); }); it('is a usage error, naming who started each, when none of the open sessions is yours', async () => { - stubFetch(() => ({ body: { sessions: [session('theirs', { started_by: { api_key_name: null, client_label: 'claude-code', email: 'ann@example.com', this_client: false, you: false } })] } })); + stubFetch(() => ({ body: { sessions: [session('theirs', { started_by: { key_name: null, client_label: 'claude-code', email: 'ann@example.com', this_client: false, you: false } })] } })); try { await resolveSessionId(API, auth, undefined); expect.fail('should have thrown'); @@ -781,7 +781,7 @@ describe('dcd device', () => { it("stop --all stops your sessions and leaves others' unless --force", async () => { const calls = stubFetch((call) => call.method === 'GET' - ? { body: { sessions: [session('mine-1', { started_by: { api_key_name: null, client_label: null, email: null, this_client: false, you: true } }), session('theirs', { started_by: { api_key_name: null, client_label: 'claude-code', email: 'ann@example.com', this_client: false, you: false } })] } } + ? { body: { sessions: [session('mine-1', { started_by: { key_name: null, client_label: null, email: null, this_client: false, you: true } }), session('theirs', { started_by: { key_name: null, client_label: 'claude-code', email: 'ann@example.com', this_client: false, you: false } })] } } : { body: { session: session(call.url.split('/').pop()!.split('?')[0], { state: 'released' }) } }, ); const { out } = await runJson('stop', { all: true }); From 04ce2b7d15b48de12cf6146b50582717d5ce3f04 Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Thu, 19 Nov 2026 11:29:50 +0000 Subject: [PATCH 7/7] fix(mcp): take app_path from the working directory only dcd mcp held run's path and the artifact downloads to the working directory, but app_path on start_device and install_app went straight to the upload. An agent's call is not the user typing a path, so a call naming any .apk, .app, .zip or .tar.gz on the machine uploaded it to the team's storage. app_path is now resolved the way path is: inside the working directory, links followed, or refused before anything is uploaded. --- CLAUDE.md | 2 +- src/mcp/bridge.ts | 18 ++++++++++++------ test/unit/mcp-bridge.test.ts | 28 ++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 03717cf..0e9805f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,7 +53,7 @@ Top-level `defineCommand` in `src/index.ts` wires fourteen subcommands (`cloud`, **MCP server.** `src/mcp/` is a third front-end onto the same service layer (a sibling to `src/commands/`), shipped as the `dcd-mcp` bin over stdio transport (`@modelcontextprotocol/sdk`, `zod` schemas). `index.ts` boots the server; `server.ts` registers tools; `context.ts` resolves auth + API URL **lazily**, and again when a `dcd login` session nears expiry (so `tools/list` works unauthenticated, auth errors surface as tool errors rather than a boot crash, and a long-lived server outlasts the one-hour access token) via the same `resolveAuth`/`resolveApiUrl` as the CLI — `DEVICE_CLOUD_API_KEY` env or stored `dcd login` session, with `DCD_API_URL` to override. **Critical invariant: stdout is the JSON-RPC channel** — tools must never call the `src/commands/*` layer or `utils/cli` `logger` (both write to stdout / can `process.exit`); they call services/gateways directly with `logStderr` and return data via `helpers.ts` `jsonResult`/`errorResult`. The `runTool` wrapper records `mcp tool …` telemetry and converts thrown errors to `isError` results. Tools: `dcd_list_devices`, `dcd_list_runs`, `dcd_get_status`, `dcd_download_artifacts`, `dcd_get_team_settings` (read-only), and `dcd_run_cloud_test` (billable — gated out by `--read-only` / `DCD_MCP_READONLY=1`, annotated destructive, async-by-default). `dcd_run_cloud_test` reuses `computeCommonRoot`/`buildTestMetadataMap` from `src/services/flow-paths.ts` (extracted from `cloud.ts` so both build identical server-side paths). Registry manifest: `server.json` at repo root. -**`dcd mcp` (the bridge).** A second stdio entry point, `src/mcp/bridge.ts`, run by the `dcd mcp` command. It is a low-level `Server` that routes between two MCP clients: the `dcd_*` tools from the same in-process `createServer()` (over an in-memory transport), and the device tools proxied from the hosted `/mcp`, so those are defined and contract-tested once, in the dcd API. It adds the inputs only a local process can serve: `start_device` and `install_app` take `app_path` (uploaded with `uploadLocalApp`, before the session starts for `start_device`) and `run` takes `path` (a file that uses no other files is sent as `yaml`; one that does, or a directory, is uploaded as a flow bundle of only what the entry reaches). `path`, and what `dcd_download_artifacts` writes, must be inside the working directory, and a write never replaces a file the server did not write (`src/mcp/local-files.ts`). When the device tools can't be listed it lists `load_device_tools` instead, whose description says why, and sends `tools/list_changed` once they load. Credentials are the CLI's (`getContext`): the hosted `/mcp` accepts an API key or a `dcd login` session with `x-dcd-org`. One connection is shared, and its `fetch` re-reads the auth headers from `getContext()` on every request, so a renewed session is picked up without remaking the connection (which would close it under a `run` still going). If the hosted endpoint can't be reached, it serves the `dcd_*` tools only and says why on stderr. Read-only mode keeps only device tools annotated `readOnlyHint`. `dcd-mcp` itself is unchanged. +**`dcd mcp` (the bridge).** A second stdio entry point, `src/mcp/bridge.ts`, run by the `dcd mcp` command. It is a low-level `Server` that routes between two MCP clients: the `dcd_*` tools from the same in-process `createServer()` (over an in-memory transport), and the device tools proxied from the hosted `/mcp`, so those are defined and contract-tested once, in the dcd API. It adds the inputs only a local process can serve: `start_device` and `install_app` take `app_path` (uploaded with `uploadLocalApp`, before the session starts for `start_device`) and `run` takes `path` (a file that uses no other files is sent as `yaml`; one that does, or a directory, is uploaded as a flow bundle of only what the entry reaches). `path`, `app_path`, and what `dcd_download_artifacts` writes, must be inside the working directory, and a write never replaces a file the server did not write (`src/mcp/local-files.ts`). When the device tools can't be listed it lists `load_device_tools` instead, whose description says why, and sends `tools/list_changed` once they load. Credentials are the CLI's (`getContext`): the hosted `/mcp` accepts an API key or a `dcd login` session with `x-dcd-org`. One connection is shared, and its `fetch` re-reads the auth headers from `getContext()` on every request, so a renewed session is picked up without remaking the connection (which would close it under a `run` still going). If the hosted endpoint can't be reached, it serves the `dcd_*` tools only and says why on stderr. Read-only mode keeps only device tools annotated `readOnlyHint`. `dcd-mcp` itself is unchanged. **`dcd mcp install [client]`** (`src/utils/mcp-install.ts`) adds the server to Claude Code (`claude mcp add --scope user`), VS Code (`code --add-mcp`), or Claude Desktop / Cursor (merges an entry into their JSON config, and refuses a file that isn't plain JSON rather than rewrite it). Entries always start dcd by **full path**, since desktop apps opened from the Dock don't read the shell rc that puts `~/.dcd/bin` on PATH: the standalone binary is `process.execPath`; an npm install is node (`stableNodePath`, the PATH entry rather than Homebrew's versioned Cellar path) plus `argv[1]` as started, not resolved. It refuses to run from source or from the npx cache. Note citty runs a parent's `run` **after** its subcommand, so `mcpCommand.run` returns early when a positional is present — without that, `dcd mcp install` would go on to start a server. diff --git a/src/mcp/bridge.ts b/src/mcp/bridge.ts index caad843..dcf23ec 100644 --- a/src/mcp/bridge.ts +++ b/src/mcp/bridge.ts @@ -77,21 +77,23 @@ const READ_ONLY_INSTRUCTIONS = const LOCAL_INPUTS: Record }> = { start_device: { description: - ' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz): it is uploaded before the session starts, so no device time is spent on the upload.', + ' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz) inside the working directory this server runs in: it is uploaded before the session starts, so no device time is spent on the upload.', properties: { app_path: { type: 'string', - description: 'A build on this machine to upload and install when the device is ready. Pass this or app_binary_id.', + description: + 'A build on this machine to upload and install when the device is ready, relative to the working directory or inside it. Pass this or app_binary_id.', }, }, }, install_app: { description: - ' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz), which is uploaded first.', + ' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz) inside the working directory this server runs in, which is uploaded first.', properties: { app_path: { type: 'string', - description: 'A build on this machine to upload and install. Pass this, app_binary_id or app_url.', + description: + 'A build on this machine to upload and install, relative to the working directory or inside it. Pass this, app_binary_id or app_url.', }, }, }, @@ -141,10 +143,14 @@ export async function resolveLocalInputs( throw new Error('Pass app_path or app_binary_id (or app_url), not both.'); } - logStderr(`Uploading ${filePath}…`); + // Only inside the working directory, as run's path: an agent's call is + // not the user typing a path (local-files.ts), and a build from anywhere + // on disk would be uploaded to the team's storage. + const appFile = localInput(filePath as string, root); + logStderr(`Uploading ${appFile}…`); const binaryId = await uploadLocalApp({ ...ctx, - filePath: filePath as string, + filePath: appFile, log: logStderr, showProgress: false, }); diff --git a/test/unit/mcp-bridge.test.ts b/test/unit/mcp-bridge.test.ts index 81487fb..492fa27 100644 --- a/test/unit/mcp-bridge.test.ts +++ b/test/unit/mcp-bridge.test.ts @@ -443,6 +443,34 @@ describe('dcd mcp bridge', () => { } }); + it('refuses an app_path outside the working directory, before uploading anything', async () => { + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-bridge-outside-')); + fs.writeFileSync(path.join(outside, 'backup.zip'), 'not a build'); + const realFetch = globalThis.fetch; + let fetched = 0; + globalThis.fetch = (async () => { + fetched += 1; + return new Response('{}'); + }) as typeof fetch; + try { + for (const name of ['start_device', 'install_app']) { + for (const given of [path.join(outside, 'backup.zip'), path.relative(tempDir, path.join(outside, 'backup.zip'))]) { + try { + await resolveLocalInputs(name, { app_path: given }, ctx()); + expect.fail(`${name} took ${given}`); + } catch (error) { + expect((error as Error).message).to.include('outside the working directory'); + } + } + } + + expect(fetched).to.equal(0); + } finally { + globalThis.fetch = realFetch; + fs.rmSync(outside, { force: true, recursive: true }); + } + }); + it('start_device takes app_path, and refuses it with app_binary_id', async () => { const start = withLocalInputs({ name: 'start_device',