From a03d4da3c5ea13916dfbfdec1d6a7e8a1b52231c Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Wed, 18 Nov 2026 19:13:11 +0000 Subject: [PATCH 1/2] 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 f80e1c8db4831ca9d92b035d9b8895f772f94e84 Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Thu, 19 Nov 2026 11:25:52 +0000 Subject: [PATCH 2/2] 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 });