From 55fb4a196a086c4346f554e1c28633b70113e396 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Sat, 7 Nov 2026 03:43:25 +0000 Subject: [PATCH 01/20] feat: drop iPhone 16 Pro Max and gpu1 from help text (removed 9 Nov 2026) (#302) iphone-16-pro-max and the gpu1 runner type are removed on 9 November 2026. iphone-16-pro stays supported. - --ios-device help no longer lists iphone-16-pro-max. Validation already follows the live compatibility data, so the API's answer is what a run that names it gets. - --runner-type help, its error for an unknown value, and the dcd_run_cloud_test runnerType schema list default, m4, m1 and cpu1 only. - gpu1 is still accepted by --runner-type and by dcd_run_cloud_test, so scripts and agents that pass it keep working: the API runs it on cpu1. validateEnum takes an optional list of accepted values it leaves out of its error message, and the MCP schema's enum is overridden through zod metadata. --- src/commands/cloud.ts | 8 ++- src/config/flags/execution.flags.ts | 12 ++++- src/mcp/tools/run-cloud-test.ts | 14 +++-- src/types/domain/device.types.ts | 1 - src/utils/cli.ts | 12 +++-- test/unit/runner-type.test.ts | 84 +++++++++++++++++++++++++++++ 6 files changed, 120 insertions(+), 11 deletions(-) create mode 100644 test/unit/runner-type.test.ts diff --git a/src/commands/cloud.ts b/src/commands/cloud.ts index 13870b4..d1b5908 100644 --- a/src/commands/cloud.ts +++ b/src/commands/cloud.ts @@ -3,6 +3,10 @@ import { defineCommand } from 'citty'; import { existsSync } from 'node:fs'; import * as path from 'node:path'; +import { + RETIRED_RUNNER_TYPES, + RUNNER_TYPE_OPTIONS, +} from '../config/flags/execution.flags.js'; import { flags as allFlags } from '../constants.js'; import { ApiError, ApiGateway } from '../gateways/api-gateway.js'; import { @@ -83,7 +87,6 @@ process.on('warning', (warning) => { const DOWNLOAD_OPTIONS = ['ALL', 'FAILED'] as const; const REPORT_OPTIONS = ['allure', 'html', 'html-detailed', 'junit'] as const; const ORIENTATION_OPTIONS = ['0', '90'] as const; -const RUNNER_TYPE_OPTIONS = ['default', 'm4', 'm1', 'gpu1', 'cpu1'] as const; const PRIORITY_OPTIONS = ['low', 'normal', 'high'] as const; const RENDER_ENGINE_OPTIONS = ['lavapipe', 'swiftshader'] as const; @@ -252,6 +255,9 @@ export const cloudCommand = defineCommand({ args['runner-type'] as string | undefined, RUNNER_TYPE_OPTIONS, 'runner-type', + // gpu1 still validates so old scripts keep working; the API runs it + // on cpu1. + RETIRED_RUNNER_TYPES, ) ?? 'default'; const renderEngine = validateEnum( args['render-engine'] as string | undefined, diff --git a/src/config/flags/execution.flags.ts b/src/config/flags/execution.flags.ts index 3018962..7b619b7 100644 --- a/src/config/flags/execution.flags.ts +++ b/src/config/flags/execution.flags.ts @@ -1,5 +1,15 @@ import type { ArgsDef } from 'citty'; +/** The runner types offered in help text, error messages and the MCP schema. */ +export const RUNNER_TYPE_OPTIONS = ['default', 'm4', 'm1', 'cpu1'] as const; + +/** + * Runner types that were removed but are still accepted, so scripts that pass + * them keep working. gpu1 was removed on 9 November 2026 and the API runs it + * on cpu1. Never offered anywhere a user picks from. + */ +export const RETIRED_RUNNER_TYPES = ['gpu1'] as const; + /** * Test execution and flow management flags */ @@ -56,6 +66,6 @@ export const executionFlags = { type: 'string', default: 'default', description: - '[experimental] The type of runner to use (options: default, m4, m1, gpu1, cpu1) - note: anything other than default or cpu1 will incur premium pricing tiers; gpu1 is deprecated and will be removed on 9 November 2026 (gpu1 runs will then use cpu1). See https://docs.devicecloud.dev/configuration/runner-type for more information.', + '[experimental] The type of runner to use (options: default, m4, m1, cpu1) - note: anything other than default or cpu1 will incur premium pricing tiers. See https://docs.devicecloud.dev/configuration/runner-type for more information.', }, } as const satisfies ArgsDef; diff --git a/src/mcp/tools/run-cloud-test.ts b/src/mcp/tools/run-cloud-test.ts index 6801ed9..1910a82 100644 --- a/src/mcp/tools/run-cloud-test.ts +++ b/src/mcp/tools/run-cloud-test.ts @@ -3,6 +3,10 @@ import * as path from 'node:path'; import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { z } from 'zod'; +import { + RETIRED_RUNNER_TYPES, + RUNNER_TYPE_OPTIONS, +} from '../../config/flags/execution.flags.js'; import { ApiGateway } from '../../gateways/api-gateway.js'; import { type IExecutionPlan, plan } from '../../services/execution-plan.service.js'; import { @@ -104,12 +108,14 @@ export function registerRunCloudTest(server: McpServer): void { excludeFlows: z.array(z.string()).optional().describe('Flow paths/patterns to exclude'), maestroVersion: z.string().optional().describe('Pin a specific Maestro version'), retry: z.number().int().min(0).max(2).optional().describe('Auto-retry failed tests (max 2)'), + // A retired runner type still validates, so an agent configured with + // one keeps working (the API runs gpu1 on cpu1), but the schema's + // `enum` lists only the current ones: zod metadata overrides it. runnerType: z - .enum(['default', 'm4', 'm1', 'gpu1', 'cpu1']) + .enum([...RUNNER_TYPE_OPTIONS, ...RETIRED_RUNNER_TYPES]) + .meta({ enum: [...RUNNER_TYPE_OPTIONS] }) .optional() - .describe( - 'Runner type (default "default"). gpu1 is deprecated and will be removed on 9 November 2026; prefer cpu1.', - ), + .describe('Runner type (default "default").'), priority: z .enum(['low', 'normal', 'high']) .optional() diff --git a/src/types/domain/device.types.ts b/src/types/domain/device.types.ts index 3cce15e..eadaf1b 100644 --- a/src/types/domain/device.types.ts +++ b/src/types/domain/device.types.ts @@ -19,7 +19,6 @@ export enum EiOSDevices { 'iphone-14' = 'iphone-14', 'iphone-16' = 'iphone-16', 'iphone-16-pro' = 'iphone-16-pro', - 'iphone-16-pro-max' = 'iphone-16-pro-max', 'iphone-17' = 'iphone-17', 'iphone-18-pro' = 'iphone-18-pro', 'iphone-18-pro-max' = 'iphone-18-pro-max', diff --git a/src/utils/cli.ts b/src/utils/cli.ts index 31b0033..da4aba7 100644 --- a/src/utils/cli.ts +++ b/src/utils/cli.ts @@ -126,19 +126,23 @@ export function wantsJson(rawArgs: string[]): boolean { /** * Validate that a string flag value is one of the allowed options. * Returns the value untouched on success; throws CliError otherwise. + * + * `unlisted` values are accepted too but left out of the error message: a + * retired option that old scripts may still pass, which nobody should pick. */ -export function validateEnum( +export function validateEnum( value: string | undefined, allowed: readonly T[], flagName: string, -): T | undefined { + unlisted: readonly U[] = [], +): T | U | undefined { if (value === undefined || value === null || value === '') return undefined; - if (!allowed.includes(value as T)) { + if (!allowed.includes(value as T) && !unlisted.includes(value as U)) { throw new CliError( `Invalid value for --${flagName}: "${value}". Expected one of: ${allowed.join(', ')}`, ); } - return value as T; + return value as T | U; } /** diff --git a/test/unit/runner-type.test.ts b/test/unit/runner-type.test.ts new file mode 100644 index 0000000..6999d06 --- /dev/null +++ b/test/unit/runner-type.test.ts @@ -0,0 +1,84 @@ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { expect } from 'chai'; + +import { + executionFlags, + RETIRED_RUNNER_TYPES, + RUNNER_TYPE_OPTIONS, +} from '../../src/config/flags/execution.flags.js'; +import { registerRunCloudTest } from '../../src/mcp/tools/run-cloud-test.js'; +import { validateEnum } from '../../src/utils/cli.js'; + +/** + * gpu1 was removed on 9 November 2026 and the API runs it on cpu1. A script + * or agent that still passes it must keep working, but nothing may offer it. + */ +describe('retired runner types', () => { + describe('--runner-type', () => { + it('lists only the current runner types in its help', () => { + const help = executionFlags['runner-type'].description; + for (const retired of RETIRED_RUNNER_TYPES) { + expect(help).to.not.include(retired); + } + expect(help).to.include(`options: ${RUNNER_TYPE_OPTIONS.join(', ')}`); + }); + + it('still accepts a retired runner type', () => { + expect( + validateEnum('gpu1', RUNNER_TYPE_OPTIONS, 'runner-type', RETIRED_RUNNER_TYPES), + ).to.equal('gpu1'); + }); + + it('leaves retired runner types out of the error for an unknown one', () => { + expect(() => + validateEnum('gpu2', RUNNER_TYPE_OPTIONS, 'runner-type', RETIRED_RUNNER_TYPES), + ).to.throw( + 'Invalid value for --runner-type: "gpu2". Expected one of: default, m4, m1, cpu1', + ); + }); + }); + + describe('dcd_run_cloud_test runnerType', () => { + let client: Client; + + beforeEach(async () => { + const server = new McpServer({ name: 'test', version: '0.0.0' }); + registerRunCloudTest(server); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(b); + client = new Client({ name: 'agent', version: '1' }); + await client.connect(a); + }); + + afterEach(async () => { + await client.close(); + }); + + it('advertises only the current runner types', async () => { + const { tools } = await client.listTools(); + const tool = tools.find((t) => t.name === 'dcd_run_cloud_test')!; + const runnerType = tool.inputSchema.properties!.runnerType as { enum: string[] }; + expect(runnerType.enum).to.deep.equal([...RUNNER_TYPE_OPTIONS]); + }); + + // Passing both appFile and appBinaryId fails inside the handler, before + // any network call, so reaching that error means the input validated. + const call = (runnerType: string) => + client.callTool({ + arguments: { appBinaryId: 'b', appFile: 'a.apk', flowFile: 'f.yaml', runnerType }, + name: 'dcd_run_cloud_test', + }); + const text = (result: Awaited>) => + (result.content as { text: string }[])[0].text; + + it('still accepts a retired runner type', async () => { + expect(text(await call('gpu1'))).to.include('Provide only one of appFile or appBinaryId'); + }); + + it('rejects an unknown runner type', async () => { + expect(text(await call('gpu2'))).to.include('Input validation error'); + }); + }); +}); From c7450664d8a91771074c3adff25cbc77fd3dbb5c Mon Sep 17 00:00:00 2001 From: "dcd-release-please[bot]" <296541543+dcd-release-please[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:13:12 +0000 Subject: [PATCH 02/20] chore: merge production into dev after 5.12.0 (#301) * chore: pin the 5.12.0 promotion Release-As: 5.12.0 * chore(production): release 5.12.0 --------- Co-authored-by: finalerock44 Co-authored-by: finalerock44 <77282157+finalerock44@users.noreply.github.com> Co-authored-by: dcd-release-please[bot] <296541543+dcd-release-please[bot]@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 20 ++++++++++++++++++++ package.json | 2 +- server.json | 4 ++-- 4 files changed, 24 insertions(+), 4 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index dfdf2d8..c99ba65 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "5.11.1" + ".": "5.12.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 21611c0..4a1fe84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## [5.12.0](https://github.com/devicecloud-dev/dcd-cli/compare/v5.11.1...v5.12.0) (2026-11-06) + + +### Features + +* **report:** deprecate allure and html-detailed, removed on 7 Decemb… ([#298](https://github.com/devicecloud-dev/dcd-cli/issues/298)) ([9bfcdb9](https://github.com/devicecloud-dev/dcd-cli/commit/9bfcdb9105e4115649e23863476ad9d5a33170c4)) +* **report:** deprecate allure and html-detailed, removed on 7 December 2026 ([9bfcdb9](https://github.com/devicecloud-dev/dcd-cli/commit/9bfcdb9105e4115649e23863476ad9d5a33170c4)) + + +### Bug Fixes + +* **device:** a start that got no answer says a session may still have started ([7015a77](https://github.com/devicecloud-dev/dcd-cli/commit/7015a776740d796d8d944560e3993710debab256)) +* **device:** a start that got no answer says a session may still have… ([#297](https://github.com/devicecloud-dev/dcd-cli/issues/297)) ([7015a77](https://github.com/devicecloud-dev/dcd-cli/commit/7015a776740d796d8d944560e3993710debab256)) +* **install:** reject a DCD_VERSION that isn't a release version ([#296](https://github.com/devicecloud-dev/dcd-cli/issues/296)) ([4a2719c](https://github.com/devicecloud-dev/dcd-cli/commit/4a2719c9cae70eba7a12a952d84a43e49f2f370f)) + + +### Miscellaneous + +* pin the 5.12.0 promotion ([2d1ad50](https://github.com/devicecloud-dev/dcd-cli/commit/2d1ad50bd89669805812efd920804c4dce1e410f)) + ## [5.11.1](https://github.com/devicecloud-dev/dcd-cli/compare/v5.11.0...v5.11.1) (2026-11-02) diff --git a/package.json b/package.json index 04036ed..0833a58 100644 --- a/package.json +++ b/package.json @@ -68,7 +68,7 @@ "test:unit": "node scripts/test-runner.mjs --unit", "typecheck": "tsc --noEmit -p tsconfig.test.json" }, - "version": "5.11.1", + "version": "5.12.0", "bugs": { "url": "https://discord.gg/gm3mJwcNw8" }, diff --git a/server.json b/server.json index a8bf69f..59520c2 100644 --- a/server.json +++ b/server.json @@ -2,7 +2,7 @@ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "name": "dev.devicecloud/dcd", "description": "Run Maestro mobile app tests on devicecloud.dev: submit flows, check status, download artifacts.", - "version": "5.11.1", + "version": "5.12.0", "repository": { "url": "https://github.com/devicecloud-dev/dcd-cli", "source": "github" @@ -11,7 +11,7 @@ { "registryType": "npm", "identifier": "@devicecloud.dev/dcd", - "version": "5.11.1", + "version": "5.12.0", "runtimeHint": "npx", "runtimeArguments": [ { From 9fafa2f62347dd77debd46874d59bd599abc358b Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:03:19 +0000 Subject: [PATCH 03/20] feat(auth): say when a dcd login session has expired (#303) When Supabase Auth refuses to refresh a `dcd login` session, the CLI used to echo its message ("Failed to refresh session: Invalid Refresh Token: Session Expired. Run `dcd login` again."). It now names the two common causes, keyed on the error code Supabase sends: - `session_expired` (the session passed the project's maximum length or inactivity timeout): "Your session expired. Run `dcd login` to sign in again." - `session_not_found` / `refresh_token_not_found` (the session was ended): "Your session was signed out. Run `dcd login` to sign in again." Other refusals keep Supabase's message. The code is kept on SessionRefreshError. supabase-js reports `session_not_found` as an AuthSessionMissingError rather than an AuthApiError, so that case was treated as a transient failure and retried; it is now final like any other refusal. A poll that loses its session no longer repeats itself ("session expired and could not be refreshed: Your session expired"): it shows the refresh error, then the reconnect command. dcd-mcp gets the new text through runTool. --- src/gateways/cli-auth-gateway.ts | 38 +++++++-- src/services/results-polling.service.ts | 5 +- test/unit/session-refresh.test.ts | 41 ++++++++- test/unit/supabase-key.test.ts | 105 +++++++++++++++++++++++- 4 files changed, 173 insertions(+), 16 deletions(-) diff --git a/src/gateways/cli-auth-gateway.ts b/src/gateways/cli-auth-gateway.ts index 18caf9a..96686ef 100644 --- a/src/gateways/cli-auth-gateway.ts +++ b/src/gateways/cli-auth-gateway.ts @@ -5,7 +5,7 @@ * Does not talk to the dcd API — the dcd-side session exchange lives in the * login command's PKCE rendezvous flow (see src/commands/login.ts). */ -import { createClient, isAuthApiError } from '@supabase/supabase-js'; +import { createClient, isAuthApiError, isAuthSessionMissingError } from '@supabase/supabase-js'; import type { DcdEnvName } from '../config/environments.js'; import { getSupabaseKey } from '../config/supabase-key.js'; @@ -21,12 +21,29 @@ export class SessionRefreshError extends Error { constructor( message: string, readonly definitive: boolean, + /** Supabase Auth's error code (`session_expired`, …), when it sent one. */ + readonly code?: string, ) { super(message); this.name = 'SessionRefreshError'; } } +/** + * What to tell the user for the refusals that have a plain cause. Supabase + * Auth answers `session_expired` once a session passes the project's maximum + * length or inactivity timeout, and `session_not_found` / + * `refresh_token_not_found` once the session has been ended (signed out + * elsewhere, revoked, or removed after expiring). Any other refusal keeps + * Supabase's own message. + */ +const SIGNED_OUT = 'Your session was signed out. Run `dcd login` to sign in again.'; +const REFRESH_REFUSAL_MESSAGES = new Map([ + ['session_expired', 'Your session expired. Run `dcd login` to sign in again.'], + ['session_not_found', SIGNED_OUT], + ['refresh_token_not_found', SIGNED_OUT], +]); + export interface RefreshedSession { access_token: string; refresh_token: string; @@ -66,15 +83,22 @@ export const CliAuthGateway = { if (error || !data.session || !data.user) { // 4xx from GoTrue means the token itself was rejected; anything else // (fetch failure, 5xx) could succeed on retry with the same token. + // supabase-js turns GoTrue's `session_not_found` into an + // AuthSessionMissingError rather than an AuthApiError (it throws the same + // for an empty refresh token); only `dcd login` fixes either. + const apiError = error != null && isAuthApiError(error) ? error : undefined; + const sessionMissing = error != null && isAuthSessionMissingError(error); const definitive = - error != null && - isAuthApiError(error) && - error.status >= 400 && - error.status < 500; + sessionMissing || + (apiError !== undefined && apiError.status >= 400 && apiError.status < 500); + const code = apiError?.code ?? (sessionMissing ? 'session_not_found' : undefined); + const known = definitive && code ? REFRESH_REFUSAL_MESSAGES.get(code) : undefined; throw new SessionRefreshError( - `Failed to refresh session: ${error?.message ?? 'no session returned'}. ` + - `Run \`dcd login\` again.`, + known ?? + `Failed to refresh session: ${error?.message ?? 'no session returned'}. ` + + `Run \`dcd login\` again.`, definitive, + code, ); } const s = data.session; diff --git a/src/services/results-polling.service.ts b/src/services/results-polling.service.ts index 04589ea..11e7c99 100644 --- a/src/services/results-polling.service.ts +++ b/src/services/results-polling.service.ts @@ -628,8 +628,9 @@ export class ResultsPollingService { if (isDefinitiveAuthFailure(error)) { const reason = error instanceof Error ? error.message : String(error); throw new PollingAuthError( - `Your dcd login session expired and could not be refreshed: ${reason}\n\n` + - `The test is still running in the cloud. Run \`dcd login\`, then reconnect with:\n dcd status --upload-id ${uploadId}`, + // The reason already says to run `dcd login`, so don't repeat it. + `${reason}\n\n` + + `The test is still running in the cloud. Once you've signed in again, reconnect with:\n dcd status --upload-id ${uploadId}`, ); } diff --git a/test/unit/session-refresh.test.ts b/test/unit/session-refresh.test.ts index 646f1a5..a0cf242 100644 --- a/test/unit/session-refresh.test.ts +++ b/test/unit/session-refresh.test.ts @@ -329,7 +329,11 @@ describe('session refresh for long-running processes', () => { stubRealtime(); const seen = stubResults(); CliAuthGateway.refresh = async () => { - throw new SessionRefreshError('Invalid Refresh Token: Already Used', true); + throw new SessionRefreshError( + 'Failed to refresh session: Invalid Refresh Token: Already Used. Run `dcd login` again.', + true, + 'refresh_token_already_used', + ); }; const started = realNow(); @@ -341,14 +345,43 @@ describe('session refresh for long-running processes', () => { } expect(caught).to.be.instanceOf(PollingAuthError); - expect((caught as Error).message).to.include('Invalid Refresh Token'); - expect((caught as Error).message).to.include('dcd login'); - expect((caught as Error).message).to.include('dcd status --upload-id u1'); + const message = (caught as Error).message; + expect(message).to.include('Invalid Refresh Token'); + // Said once, by the refresh error, not again by the poll. + expect(message.match(/dcd login/g)).to.have.length(1); + expect(message).to.include('dcd status --upload-id u1'); expect(seen).to.deep.equal([]); // No trip through the 30-attempt retry budget and its backoff. expect(realNow() - started).to.be.below(2000); }); + it('leads with the expiry when the session passed its limit', async () => { + storeSession('stale', 10); + stubRealtime(); + stubResults(); + CliAuthGateway.refresh = async () => { + throw new SessionRefreshError( + 'Your session expired. Run `dcd login` to sign in again.', + true, + 'session_expired', + ); + }; + + let caught: unknown; + try { + await poll(expiredBearer('stale')); + } catch (error) { + caught = error; + } + + expect(caught).to.be.instanceOf(PollingAuthError); + expect((caught as Error).message).to.equal( + 'Your session expired. Run `dcd login` to sign in again.\n\n' + + "The test is still running in the cloud. Once you've signed in again, reconnect with:\n" + + ' dcd status --upload-id u1', + ); + }); + it('downloads the report after a long poll with a refreshed token', async () => { storeSession('fresh', 3600); const headers: Array> = []; diff --git a/test/unit/supabase-key.test.ts b/test/unit/supabase-key.test.ts index 20bd390..32ce7bf 100644 --- a/test/unit/supabase-key.test.ts +++ b/test/unit/supabase-key.test.ts @@ -15,11 +15,12 @@ describe('Supabase key from /cli-config', () => { const realFetch = globalThis.fetch; let requested: string[]; - function stubFetch(respond: () => Response | Promise): void { + function stubFetch(respond: (url: string) => Response | Promise): void { requested = []; globalThis.fetch = (async (input: string | URL | Request) => { - requested.push(String(input)); - return respond(); + const url = input instanceof Request ? input.url : String(input); + requested.push(url); + return respond(url); }) as typeof fetch; } @@ -93,4 +94,102 @@ describe('Supabase key from /cli-config', () => { // Not definitive, so resolveAuth will not delete the user's login. expect((caught as SessionRefreshError).definitive).to.equal(false); }); + + /** + * Supabase Auth refuses a refresh with a 4xx and an error code: in `code` + * when the response is versioned (2024-01-01 and later), in `error_code` + * before that. The CLI names the common causes instead of echoing them. + */ + describe('when Supabase refuses the refresh', () => { + const storedSession = { + access_token: 'a', + refresh_token: 'r', + expires_at: 0, + user_email: 'u@example.com', + user_id: 'u1', + }; + + function refuseRefresh(token: () => Response): void { + stubFetch((url) => + url.endsWith('/cli-config') + ? json({ supabase_publishable_key: 'sb_publishable_abc' }) + : token(), + ); + } + + const versioned = (status: number, code: string, message: string) => + new Response(JSON.stringify({ code, message }), { + status, + headers: { + 'content-type': 'application/json', + 'x-supabase-api-version': '2024-01-01', + }, + }); + + async function refreshError(): Promise { + try { + await CliAuthGateway.refresh('https://cloud.devicecloud.dev', 'prod', storedSession); + } catch (error) { + expect(error).to.be.instanceOf(SessionRefreshError); + return error as SessionRefreshError; + } + throw new Error('expected the refresh to fail'); + } + + it('says the session expired', async () => { + refuseRefresh(() => versioned(403, 'session_expired', 'Invalid Refresh Token: Session Expired')); + + const error = await refreshError(); + + expect(error.message).to.equal('Your session expired. Run `dcd login` to sign in again.'); + expect(error.code).to.equal('session_expired'); + expect(error.definitive).to.equal(true); + expect(requested[1]).to.equal( + 'https://cloud.devicecloud.dev/auth/v1/token?grant_type=refresh_token', + ); + }); + + it('reads the code from an unversioned response too', async () => { + refuseRefresh(() => + json( + { code: 403, error_code: 'session_expired', msg: 'Invalid Refresh Token: Session Expired (Inactivity)' }, + 403, + ), + ); + + const error = await refreshError(); + + expect(error.message).to.equal('Your session expired. Run `dcd login` to sign in again.'); + expect(error.code).to.equal('session_expired'); + expect(error.definitive).to.equal(true); + }); + + it('says the session was signed out when it no longer exists', async () => { + for (const code of ['refresh_token_not_found', 'session_not_found']) { + refuseRefresh(() => versioned(400, code, 'Invalid Refresh Token: Refresh Token Not Found')); + + const error = await refreshError(); + + expect(error.message).to.equal( + 'Your session was signed out. Run `dcd login` to sign in again.', + ); + expect(error.code).to.equal(code); + expect(error.definitive).to.equal(true); + } + }); + + it("keeps Supabase's message for any other refusal", async () => { + refuseRefresh(() => + versioned(400, 'refresh_token_already_used', 'Invalid Refresh Token: Already Used'), + ); + + const error = await refreshError(); + + expect(error.message).to.equal( + 'Failed to refresh session: Invalid Refresh Token: Already Used. Run `dcd login` again.', + ); + expect(error.code).to.equal('refresh_token_already_used'); + expect(error.definitive).to.equal(true); + }); + }); }); From 6bebbefd6c94df0191a72f0b5648c18951e3829d Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:43:29 +0000 Subject: [PATCH 04/20] ci: Replace release-please with a custom version that handles our dev -> prod flow (#305) * ci: cut a stable release with one workflow run and one PR A stable release used to take a hand-built promotion branch (dev, a merge of production, and an empty Release-As pin commit), a promotion PR, then release-please's own Release PR, then the back-merge PR. A new "Promote to stable" workflow (promote.yml) now builds the release branch: dev, with production merged in, plus one commit that sets the version in package.json and server.json and adds the CHANGELOG.md section. It opens that as the only PR into production. Merging it is the release: the Release workflow tags the untagged version, creates the GitHub Release from the changelog section, and publishes npm, the binaries and the back-merge as before. scripts/stable-release.mjs derives the version from the Conventional Commit PR titles since the last release, as release-please did, but never derives a major: a breaking marker stops the run until the version is given explicitly. Its changelog lists each PR once, using the full title when GitHub cut it short, where release-please listed such PRs twice. Production is merged in on every run because dev only allows squash merges, so the back-merge can never make production an ancestor of dev. release-please, its config and manifest, and the Release-As promotion-pin check are removed. A release-check job verifies every PR into production instead. Release PRs skip claude-review, like back-merge PRs, because the review action rejects bot actors. The Release workflow keeps the release-please.yml filename, because npm's trusted publisher is registered against it. * ci: keep the stable release PR open and current on every push to dev Promote to stable now also runs on every push to dev. It rebuilds one fixed branch, promote/cli-next, and opens the release PR into production or updates the open one, so the PR always carries all of dev with the version and changelog to match. Nothing ships until someone merges it. - A push with nothing releasable since the last release (docs, the back-merge) does nothing. - A version set by hand is kept on later runs (plan --keep) whenever it is above the derived one, so a major has to be given only once, and a breaking marker still never derives one. - If production moved during the run, nothing is pushed; the back-merge push rebuilds the PR. The force-push is leased against the branch tip the run saw, and skipped when the content is unchanged. - A PR into production from any other branch is left alone: push runs warn and stop. --- .github/PULL_REQUEST_TEMPLATE.md | 4 +- .github/dependabot.yml | 2 +- .github/workflows/cla.yml | 10 +- .github/workflows/claude-code-review.yml | 14 +- .github/workflows/cli-ci.yml | 77 +--- .github/workflows/npm-publish.yml | 16 +- .github/workflows/pr-title-lint.yml | 8 +- .github/workflows/promote.yml | 240 +++++++++++ .github/workflows/release-beta.yml | 6 +- .github/workflows/release-binaries.yml | 9 +- .github/workflows/release-please.yml | 133 +++--- .release-please-manifest.json | 3 - CLAUDE.md | 38 +- CONTRIBUTING.md | 17 +- release-please-config.json | 34 -- scripts/stable-release.mjs | 497 +++++++++++++++++++++++ test/unit/server-json.test.ts | 28 +- test/unit/stable-release.test.ts | 332 +++++++++++++++ 18 files changed, 1230 insertions(+), 238 deletions(-) create mode 100644 .github/workflows/promote.yml delete mode 100644 .release-please-manifest.json delete mode 100644 release-please-config.json create mode 100644 scripts/stable-release.mjs create mode 100644 test/unit/stable-release.test.ts diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 288cc94..1c22b44 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,6 +1,6 @@ @@ -27,7 +27,7 @@ - [ ] `pnpm lint` passes - [ ] `pnpm typecheck` passes - [ ] `pnpm build` passes -- [ ] I have **not** bumped the version or edited `CHANGELOG.md` (release-please handles this) +- [ ] I have **not** bumped the version or edited `CHANGELOG.md` (the release workflow handles this) - [ ] I have signed the CLA (the bot will prompt on first contribution) - [ ] Docs / `README.md` / `STYLE_GUIDE.md` updated if behaviour or output changed diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 3ffe6e3..13d6a53 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -16,7 +16,7 @@ updates: open-pull-requests-limit: 10 commit-message: # Conventional Commit prefix so the squashed PR title matches our PR-title - # lint and release-please picks dependency bumps into the changelog. + # lint and the release changelog lists dependency bumps. prefix: deps prefix-development: chore groups: diff --git a/.github/workflows/cla.yml b/.github/workflows/cla.yml index 24fe627..cf0be43 100644 --- a/.github/workflows/cla.yml +++ b/.github/workflows/cla.yml @@ -21,13 +21,13 @@ name: CLA Assistant # the org access policy set. Do not flip it private. # # AUTH: mints a token from the shared automation GitHub App (the same App -# release-please uses), so signature commits show as the bot and there's no +# the release workflows use), so signature commits show as the bot and there's no # personal token to expire. # # SETUP REQUIRED before this enforces anything: # 1. Create/install the automation GitHub App (Contents R/W, Pull requests R/W, # Issues R/W) and add BOT_APP_ID + BOT_APP_PRIVATE_KEY repo secrets — the -# same secrets release-please uses. +# same secrets the release workflows use. # 2. Create the `cla-signatures` branch (empty orphan) so the action has # somewhere to write `signatures/version1/cla.json`. # 3. Finalise CLA.md (legal review) — it's the document contributors agree to. @@ -73,9 +73,9 @@ jobs: path-to-document: "https://github.com/devicecloud-dev/dcd-cli/blob/dev/CLA.md" branch: "cla-signatures" # Do NOT lock the PR on merge (the action's default is true). release-please - # comments on its release PR *after* merge; a locked conversation makes that - # comment fail and takes down the whole Release job (npm publish + binaries - # never run). Keeping this false is load-bearing for the release pipeline. + # used to comment on its release PR *after* merge, and a locked conversation + # failed that comment and the whole Release job with it. Nothing comments + # after merge now, but locking gains nothing, so it stays off. lock-pullrequest-aftermerge: false # Internal maintainers (covered by employment/CCLA) + bots skip the prompt. allowlist: riglar,finalerock44,dependabot[bot],renovate[bot],*[bot] diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml index 8e8a6dc..77e3e97 100644 --- a/.github/workflows/claude-code-review.yml +++ b/.github/workflows/claude-code-review.yml @@ -14,13 +14,13 @@ jobs: claude-review: # Skip PRs we shouldn't (or can't) review: # - Dependabot / forks: no CLAUDE_CODE_OAUTH_TOKEN, so the action would fail. - # - release-please release PRs: just version bumps + changelog — nothing to - # review, and it must never block a release. - # - Back-merge PRs (production -> dev, opened by release-please.yml): only - # carry code already reviewed on its way through dev, and the action - # rejects their bot actor ("Workflow initiated by non-human actor"), - # which blocks the merge since claude-review is a required check. - if: ${{ github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && !startsWith(github.head_ref, 'release-please--') && !startsWith(github.head_ref, 'chore/back-merge-') }} + # - Release PRs (dev -> production, opened by promote.yml) and back-merge + # PRs (production -> dev, opened by release-please.yml): they only carry + # code already reviewed on its way through dev, plus the version and + # changelog commit, and the action rejects their bot actor ("Workflow + # initiated by non-human actor"), which blocks the merge since + # claude-review is a required check. + if: ${{ github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && !(github.base_ref == 'production' && startsWith(github.head_ref, 'promote/cli-')) && !startsWith(github.head_ref, 'chore/back-merge-') }} runs-on: ubuntu-latest permissions: contents: read diff --git a/.github/workflows/cli-ci.yml b/.github/workflows/cli-ci.yml index fddf327..cdd1a83 100644 --- a/.github/workflows/cli-ci.yml +++ b/.github/workflows/cli-ci.yml @@ -102,71 +102,24 @@ jobs: working-directory: ./cli run: pnpm audit --audit-level moderate - # Promotions to `production` MUST pin the stable version with a `Release-As:` - # footer on a commit. Without it release-please derives the stable version - # from the most recent tag reachable from `production` — and because a - # promotion is a merge commit, every beta tag is reachable, so it picks up a - # `-beta` version. That is exactly how 5.6.0 ended up with `production` - # carrying 5.6.0-beta.1 in package.json and a release PR that could not - # publish. 5.5.0 got a pin (`chore: pin the 5.5.0 promotion`) and came out - # correct; 5.6.0's was abandoned and did not. - # - # It has to be on a NORMAL commit, not the merge commit — release-please's - # commit splitting is unreliable on merges. - # - # Release-please's own release PR also targets `production` but is not a - # promotion: it never carries a pin, so the check would always fail on it. - promotion-pin: - if: github.event_name == 'pull_request' && github.base_ref == 'production' && !startsWith(github.head_ref, 'release-please--') + # Every PR into `production` is a release, built by promote.yml: `dev` with + # `production` merged in, plus a commit that sets a new version in + # package.json and server.json and adds its CHANGELOG.md section. This checks + # that commit is there and consistent, against the merge result, so a hand-made + # PR can't land something the Release workflow would skip (version already + # tagged) or refuse (version files out of step). + release-check: + if: github.event_name == 'pull_request' && github.base_ref == 'production' runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: + # Tags, to check the version is new and above every stable release. fetch-depth: 0 - - name: Require a stable Release-As pin - env: - BASE_SHA: ${{ github.event.pull_request.base.sha }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - run: | - set -euo pipefail - git fetch --quiet origin dev - - # Scope matters more than the pattern here. A promotion merges the whole - # of `dev`, whose history carries a `Release-As:` footer from every past - # promotion (5.0.0, 5.1.0, 5.1.1, 5.2.0, 5.3.0, 5.3.1 …). Scanning - # `base..head` therefore always finds one and passes vacuously — checked - # against the real #176, which it waved through. Only commits unique to - # this promotion branch count: everything on `production` and everything - # on `dev` is excluded. `--no-merges` because release-please's commit - # splitting is unreliable on merge commits, so a pin has to sit on an - # ordinary one. - # - # NB `^ref` not `--not ref`: --not is a TOGGLE over everything that - # follows, so `--not A --not B` excludes A and re-includes B. - MESSAGES=$(git log --no-merges --format=%B "$HEAD_SHA" "^$BASE_SHA" "^origin/dev") - - if echo "$MESSAGES" | grep -qE '^Release-As:[[:space:]]*[0-9]+\.[0-9]+\.[0-9]+[[:space:]]*$'; then - echo "Found $(echo "$MESSAGES" | grep -oE '^Release-As:[[:space:]]*[0-9]+\.[0-9]+\.[0-9]+' | head -1)" - exit 0 - fi - - if echo "$MESSAGES" | grep -qE '^Release-As:'; then - echo "::error::This promotion pins a PRERELEASE version. The stable line must be pinned to a plain X.Y.Z." - echo "$MESSAGES" | grep -E '^Release-As:' >&2 - exit 1 - fi - - echo "::error::No 'Release-As: X.Y.Z' footer on any non-merge commit unique to this promotion." - { - echo "Add one as its own commit on the promotion branch:" - echo " git commit --allow-empty -m 'chore: pin the X.Y.Z promotion' -m 'Release-As: X.Y.Z'" - echo - echo "Do not skip it on the grounds that the conventional commits since the last" - echo "stable already imply the right bump. They do not: a promotion is a merge, so" - echo "every beta tag becomes reachable from production, and release-please picks the" - echo "newest reachable tag as its base. That is how the 5.6.0 promotion — which" - echo "reasoned exactly that way — produced a 'chore(production): release 5.6.0-beta.1'" - echo "release PR and left production carrying a prerelease in package.json." - } >&2 - exit 1 + - uses: actions/setup-node@v7 + with: + node-version: '24.x' + + - name: Check this PR is a well-formed release + run: node scripts/stable-release.mjs verify diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index b2a74b7..7c92770 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -1,7 +1,8 @@ name: Publish Package to npmjs # Publishes the STABLE package to npm's `latest` tag. Called by -# release-please.yml after a stable Release PR merges on `production`. +# release-please.yml (the Release workflow) after a release PR merges on +# `production`. # # Betas do NOT come through here — .github/workflows/release-beta.yml publishes # those directly. This file used to take a `release_type` of prod or beta, but @@ -60,10 +61,10 @@ jobs: - run: pnpm install --frozen-lockfile # Stable publishes land on the npm `latest` tag and must only ever come - # from the `production` branch (release-please's prod target branch). - # Without this guard, workflow_dispatch could publish any ref as `latest`, - # bypassing release-please. workflow_call is unaffected: release-please.yml - # only runs on pushes to `production`, so github.ref_name matches there. + # from the `production` branch. Without this guard, workflow_dispatch + # could publish any ref as `latest`, bypassing the release PR. + # workflow_call is unaffected: release-please.yml only runs on + # `production`, so github.ref_name matches there. - name: Enforce production branch if: ${{ github.ref_name != 'production' }} run: | @@ -72,8 +73,9 @@ jobs: # Catches the failure mode that stalled 5.6.0: a promotion merge dragged # `dev`'s beta version onto `production`, so package.json read - # 5.6.0-beta.1 while the stable manifest still said 5.5.0. Publishing that - # to `latest` would have shipped a prerelease to every default install. + # 5.6.0-beta.1. Publishing that to `latest` would have shipped a + # prerelease to every default install. stable-release.mjs verify refuses + # such a version before the tag is made; this is the last backstop. - name: Validate Production Version run: | VERSION=$(node -p "require('./package.json').version") diff --git a/.github/workflows/pr-title-lint.yml b/.github/workflows/pr-title-lint.yml index e3f8cb8..d102449 100644 --- a/.github/workflows/pr-title-lint.yml +++ b/.github/workflows/pr-title-lint.yml @@ -1,9 +1,9 @@ name: PR Title # Enforces Conventional Commits on the PR *title*. Because PRs are squash-merged -# with the title as the commit subject, this is what release-please parses to -# compute version bumps and the changelog — so the allowed types below must stay -# in sync with `changelog-sections` in release-please-config.json. +# with the title as the commit subject, this is what scripts/stable-release.mjs +# parses to compute version bumps and the changelog, so the allowed types below +# must stay in sync with SECTIONS and HIDDEN there. # # Uses pull_request_target so it also runs (and reports a required status check) # on PRs from forks. It only reads the title — no untrusted code is checked out. @@ -27,7 +27,7 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: - # Keep in lockstep with release-please-config.json changelog-sections. + # Keep in lockstep with SECTIONS and HIDDEN in scripts/stable-release.mjs. types: | feat fix diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml new file mode 100644 index 0000000..8211a5a --- /dev/null +++ b/.github/workflows/promote.yml @@ -0,0 +1,240 @@ +name: Promote to stable + +# Keeps a stable release PR open and current. It runs on every push to `dev`, +# and by hand from the Actions tab or `gh workflow run promote.yml --ref dev`. +# +# It builds `promote/cli-next`: `dev`, with `production` merged in, plus one +# commit that sets the version in package.json and server.json and adds the +# CHANGELOG.md section. It opens that branch as a PR into `production`, or +# updates the PR already open, so the release PR always carries everything on +# `dev`. Nothing ships until someone merges it (with a merge commit, the only +# method `production` allows). Merging is the release: release-please.yml tags +# it, creates the GitHub Release, publishes npm `latest` and the binaries, and +# opens the back-merge PR into `dev`. +# +# The version comes from the Conventional Commit PR titles since the last +# stable release (feat -> minor, fix/perf/deps/revert/refactor -> patch). When +# nothing since then is releasable, a push run does nothing. A major is never +# derived: a breaking marker fails the run until someone runs this by hand with +# the version, and later runs keep a version set by hand rather than go below +# it. See scripts/stable-release.mjs. +# +# `production` is merged in because `dev` only allows squash merges, so the +# back-merge after a release can never make `production` an ancestor of `dev`. +on: + push: + branches: [dev] + workflow_dispatch: + inputs: + version: + description: 'Stable version, e.g. 6.0.0. Leave blank to derive it from the PR titles since the last release.' + required: false + type: string + dry_run: + description: 'Work out the version and changelog and build the branch, but push nothing and open no PR.' + required: false + default: false + type: boolean + +permissions: + contents: read + +# One run at a time, and only the newest waiting run is kept: it rebuilds from +# the latest `dev`, which covers every push before it. +concurrency: + group: promote-to-stable + cancel-in-progress: false + +env: + BRANCH: promote/cli-next + +jobs: + promote: + runs-on: ubuntu-latest + env: + BOT_APP_ID: ${{ secrets.BOT_APP_ID }} + steps: + # The App token is required, not preferred: a PR opened with GITHUB_TOKEN + # does not trigger the checks `production` requires, so it could never merge. + - name: Check how this was started + run: | + if [ "$GITHUB_REF_NAME" != "dev" ]; then + echo "::error::Run this workflow from dev, not $GITHUB_REF_NAME." + exit 1 + fi + if [ -z "$BOT_APP_ID" ]; then + echo "::error::BOT_APP_ID is not set. The release PR has to be opened by the automation App so the required checks run on it." + exit 1 + fi + + - uses: actions/create-github-app-token@v3 + id: app-token + with: + app-id: ${{ secrets.BOT_APP_ID }} + private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }} + + - uses: actions/checkout@v7 + with: + ref: dev + # Full history and tags: the version is derived from the commits since + # the last release and checked against every existing tag. + fetch-depth: 0 + token: ${{ steps.app-token.outputs.token }} + + - uses: actions/setup-node@v7 + with: + node-version: '24.x' + + # The release PR this run updates, if one is open. Any other open PR into + # production was made by hand; this leaves it alone rather than open a + # second release beside it. + - name: Find the open release PR + id: pr + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + EVENT: ${{ github.event_name }} + DRY_RUN: ${{ inputs.dry_run }} + run: | + set -euo pipefail + prs=$(gh pr list --base production --state open --json number,headRefName,title) + other=$(jq -r --arg b "$BRANCH" '.[] | select(.headRefName != $b) | "#\(.number) (\(.headRefName))"' <<<"$prs" | paste -sd, -) + if [ -n "$other" ]; then + message="A PR into production that this workflow did not open is open: ${other}." + if [ "$EVENT" = "push" ]; then + echo "::warning::${message} Not updating the release PR until it is merged or closed." + echo "blocked=true" >> "$GITHUB_OUTPUT" + exit 0 + elif [ "$DRY_RUN" = "true" ]; then + echo "::warning::${message} A real run would stop here." + else + echo "::error::${message} Merge or close it first." + exit 1 + fi + fi + number=$(jq -r --arg b "$BRANCH" '.[] | select(.headRefName == $b) | .number' <<<"$prs") + keep=$(jq -r --arg b "$BRANCH" '.[] | select(.headRefName == $b) | .title | capture("release (?[0-9]+\\.[0-9]+\\.[0-9]+)$").v // empty' <<<"$prs") + echo "Open release PR: ${number:-none}${keep:+ (${keep})}" + { echo "blocked=false"; echo "number=${number}"; echo "keep=${keep}"; } >> "$GITHUB_OUTPUT" + + - name: Work out the version and changelog + id: plan + if: steps.pr.outputs.blocked != 'true' + env: + INPUT_VERSION: ${{ inputs.version }} + KEEP: ${{ steps.pr.outputs.keep }} + EVENT: ${{ github.event_name }} + run: | + args=(--base origin/production --head origin/dev --notes-out "$RUNNER_TEMP/notes.md") + if [ -n "$INPUT_VERSION" ]; then args+=(--version "$INPUT_VERSION"); fi + if [ -n "$KEEP" ]; then args+=(--keep "$KEEP"); fi + # A push with nothing releasable (a docs change, the back-merge) is + # not an error; a run started by hand that finds nothing is. + if [ "$EVENT" = "push" ]; then args+=(--skip-if-nothing); fi + node scripts/stable-release.mjs plan "${args[@]}" + + - name: Build the release branch + if: steps.plan.outputs.release == 'true' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + APP_SLUG: ${{ steps.app-token.outputs.app-slug }} + VERSION: ${{ steps.plan.outputs.version }} + run: | + set -euo pipefail + # Commit as the App's bot user, so the commits are attributed to it and + # the CLA check, which allowlists bots, passes. + user_id=$(gh api "/users/${APP_SLUG}[bot]" --jq .id) + git config user.name "${APP_SLUG}[bot]" + git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" + + git checkout -B "$BRANCH" origin/dev + + if git merge-base --is-ancestor origin/production HEAD; then + echo "dev already contains production." + elif ! git merge --no-ff -m "chore: merge production into the ${VERSION} release" origin/production; then + conflicts=$(git diff --name-only --diff-filter=U | paste -sd, -) + git merge --abort + echo "::error::Merging production into dev conflicts in ${conflicts}. Build this release by hand; see Releases in CLAUDE.md." + exit 1 + fi + + node scripts/stable-release.mjs apply --version "$VERSION" --notes "$RUNNER_TEMP/notes.md" + git add package.json server.json CHANGELOG.md + git commit -m "chore: release ${VERSION}" + + # The same check CI runs on the PR, so a bad branch fails here instead. + node scripts/stable-release.mjs verify + + - name: Write the PR body + if: steps.plan.outputs.release == 'true' + env: + VERSION: ${{ steps.plan.outputs.version }} + PREVIOUS: ${{ steps.plan.outputs.previous }} + BUMP: ${{ steps.plan.outputs.bump }} + DRY_RUN: ${{ inputs.dry_run }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -euo pipefail + case "$BUMP" in + requested) how="version set by hand; previous release ${PREVIOUS}" ;; + kept) how="version kept from an earlier run; previous release ${PREVIOUS}" ;; + *) how="${BUMP} bump from ${PREVIOUS}, derived from the PR titles" ;; + esac + dev_sha=$(git rev-parse --short origin/dev) + { + echo "Releases **${VERSION}** to npm \`latest\` (${how})." + echo + cat "$RUNNER_TEMP/notes.md" + echo + echo "---" + echo + echo "Kept current by the [Promote to stable](${RUN_URL}) workflow, which rebuilds this branch on every push to \`dev\`: \`dev\` at ${dev_sha}, with \`production\` merged in, plus a commit that sets the version in package.json and server.json and adds the CHANGELOG.md section above." + echo + echo "- Merge with **Create a merge commit**, the only method \`production\` allows, when you want to release." + echo "- Merging is the release: the Release workflow tags \`v${VERSION}\`, creates the GitHub Release from the section above, publishes npm \`latest\` and the binaries, and opens the back-merge PR into \`dev\`." + echo "- Leave it open until then; closing it only means the next push to \`dev\` opens a new one." + } > "$RUNNER_TEMP/body.md" + { + if [ "$DRY_RUN" = "true" ]; then echo "### ${VERSION} (dry run: nothing pushed)"; else echo "### ${VERSION}"; fi + echo + cat "$RUNNER_TEMP/body.md" + echo + echo '```' + git log --oneline --graph -n 4 + git diff --shortstat origin/production HEAD + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + - name: Push the branch and open or update the release PR + if: steps.plan.outputs.release == 'true' && !inputs.dry_run + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + VERSION: ${{ steps.plan.outputs.version }} + NUMBER: ${{ steps.pr.outputs.number }} + run: | + set -euo pipefail + # If production moved while this ran, a release just merged and this + # build is stale. Its back-merge into dev starts a fresh run. + if [ "$(git ls-remote origin refs/heads/production | cut -f1)" != "$(git rev-parse origin/production)" ]; then + echo "::notice::production moved during this run, so nothing was pushed. The next push to dev rebuilds the release PR." + exit 0 + fi + + # The branch belongs to this workflow, so it is force-pushed, but only + # over what this run saw: a concurrent change makes the push fail. + seen=$(git rev-parse -q --verify "refs/remotes/origin/${BRANCH}" || true) + if [ -n "$seen" ] && [ -n "$NUMBER" ] && git diff --quiet "$seen" HEAD; then + echo "The release PR #${NUMBER} already has this content; nothing to push." + exit 0 + fi + git push --force-with-lease="refs/heads/${BRANCH}:${seen}" origin "HEAD:refs/heads/${BRANCH}" + + title="chore: release ${VERSION}" + if [ -n "$NUMBER" ]; then + gh pr edit "$NUMBER" --title "$title" --body-file "$RUNNER_TEMP/body.md" + url=$(gh pr view "$NUMBER" --json url --jq .url) + echo "Updated ${url}" + else + url=$(gh pr create --base production --head "$BRANCH" --title "$title" --body-file "$RUNNER_TEMP/body.md") + echo "Opened ${url}" + fi + { echo; echo "Release PR: ${url}"; } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/release-beta.yml b/.github/workflows/release-beta.yml index cb5f7b1..a42a53f 100644 --- a/.github/workflows/release-beta.yml +++ b/.github/workflows/release-beta.yml @@ -9,8 +9,8 @@ name: Release beta # version is derived from the registry, so a beta is always above the current # stable by construction. See scripts/next-beta-version.mjs. # -# Stable releases are unaffected and stay automatic — release-please on -# `production`, driven by .github/workflows/release-please.yml. +# Stable releases are separate: .github/workflows/promote.yml opens the release +# PR into `production`, and .github/workflows/release-please.yml publishes it. on: workflow_dispatch: inputs: @@ -51,7 +51,7 @@ jobs: runs-on: ubuntu-latest steps: # Betas come off `dev` or a feature branch. `production` is the stable line - # and release-please owns its package.json version there; cutting a beta + # and the release PR sets its package.json version there; cutting a beta # from it would build from a tree that another process is also writing. - name: Reject beta releases from production if: github.ref_name == 'production' diff --git a/.github/workflows/release-binaries.yml b/.github/workflows/release-binaries.yml index f8cbd7a..251ff77 100644 --- a/.github/workflows/release-binaries.yml +++ b/.github/workflows/release-binaries.yml @@ -1,9 +1,10 @@ name: Publish standalone binaries -# Invoked by release-please.yml after a GitHub Release is created, so a single -# release produces both the npm package and the standalone binaries. The infra -# Railway proxy (`get.devicecloud.dev`) reads from the GitHub Releases API at -# runtime, so no separate manifest deploy is needed. +# Invoked by release-please.yml (the Release workflow) after it creates the +# GitHub Release, so a single release produces both the npm package and the +# standalone binaries. The infra Railway proxy (`get.devicecloud.dev`) reads +# from the GitHub Releases API at runtime, so no separate manifest deploy is +# needed. on: workflow_call: inputs: diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 48e012c..9404984 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -1,55 +1,81 @@ name: Release -# Drives the STABLE release pipeline. A push to `production` makes release-please -# open/update a Release PR; merging that PR creates the tag + GitHub Release whose -# body is the freshly-rendered changelog section, and the same workflow run chains -# into npm publish + binary uploads. (Chained as jobs because GITHUB_TOKEN-created -# releases don't trigger workflows listening on `release: published`.) +# Publishes a STABLE release once its release PR lands on `production`. # -# Betas are NOT handled here — they are cut by hand from -# .github/workflows/release-beta.yml. They used to be a second release-please -# track on `dev` with its own config and manifest, which numbered itself without -# reference to what stable had shipped and so kept publishing betas that sorted -# below `@latest`. See that workflow's header for the full story. +# The release PR is built by .github/workflows/promote.yml: `dev`, with +# `production` merged in, plus a commit that sets the version in package.json and +# server.json and adds the CHANGELOG.md section. So a push to `production` that +# carries an untagged version is a release: this tags it, creates the GitHub +# Release from that changelog section, and chains into npm publish, the binary +# uploads and the back-merge into `dev`. A push whose version is already tagged +# is not a release, and does nothing. +# +# The file keeps its old name because npm's trusted publisher is registered +# against `release-please.yml`: npm checks the filename of the workflow that +# started the run, so renaming this means updating that registration first. +# release-please itself is gone. It needed a promotion PR, a `Release-As:` pin +# on it (or it based the version on a beta tag), and then its own Release PR. +# +# Betas are NOT handled here: they are cut by hand from +# .github/workflows/release-beta.yml. on: push: branches: [production] + # Re-run lever: does the same as a push, so it releases `production`'s + # version if that is still untagged and does nothing otherwise. workflow_dispatch: permissions: - contents: write - pull-requests: write + contents: read jobs: - release-please-prod: + release: if: github.ref_name == 'production' runs-on: ubuntu-latest - # Empty until the automation GitHub App secrets are configured (the same App - # powers the CLA workflow). We use an App token (not GITHUB_TOKEN) so the - # Release PR triggers CI / PR-title / CLA - # checks — PRs opened by GITHUB_TOKEN do not, which would deadlock branch - # protection. Falls back to GITHUB_TOKEN (today's behaviour) until the App - # is set up, so this is safe to merge before then. - env: - BOT_APP_ID: ${{ secrets.BOT_APP_ID }} + permissions: + contents: write outputs: release_created: ${{ steps.release.outputs.release_created }} tag_name: ${{ steps.release.outputs.tag_name }} version: ${{ steps.release.outputs.version }} steps: - - uses: actions/create-github-app-token@v3 - id: app-token - if: env.BOT_APP_ID != '' + - uses: actions/checkout@v7 with: - app-id: ${{ secrets.BOT_APP_ID }} - private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }} - - uses: googleapis/release-please-action@v5 - id: release + # Tags, for the "already released" and "above every stable tag" checks. + fetch-depth: 0 + + - uses: actions/setup-node@v7 with: - token: ${{ steps.app-token.outputs.token || secrets.GITHUB_TOKEN }} - target-branch: production - config-file: release-please-config.json - manifest-file: .release-please-manifest.json + node-version: '24.x' + + # GITHUB_TOKEN, so the `release: published` event triggers no workflow; + # the publishing jobs below are chained with `needs:` instead. + - name: Tag and create the GitHub Release + id: release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + version=$(node -p "require('./package.json').version") + tag="v${version}" + if git rev-parse -q --verify "refs/tags/${tag}" >/dev/null; then + echo "${tag} is already tagged, so this push is not a release." + echo "release_created=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + + node scripts/stable-release.mjs verify + node scripts/stable-release.mjs notes --version "$version" > "$RUNNER_TEMP/notes.md" + gh release create "$tag" \ + --target "$GITHUB_SHA" \ + --title "$tag" \ + --notes-file "$RUNNER_TEMP/notes.md" \ + --latest + { + echo "release_created=true" + echo "tag_name=${tag}" + echo "version=${version}" + } >> "$GITHUB_OUTPUT" publish-npm-prod: # Must be granted here too: a reusable workflow can never hold a @@ -59,28 +85,32 @@ jobs: permissions: contents: read id-token: write - needs: release-please-prod - if: needs.release-please-prod.outputs.release_created == 'true' + needs: release + if: needs.release.outputs.release_created == 'true' uses: ./.github/workflows/npm-publish.yml secrets: inherit publish-binaries-prod: - needs: release-please-prod - if: needs.release-please-prod.outputs.release_created == 'true' + # Granted here for the same reason: release-binaries.yml uploads the + # release assets, and this workflow's top-level block is read-only. + permissions: + contents: write + needs: release + if: needs.release.outputs.release_created == 'true' uses: ./.github/workflows/release-binaries.yml with: - tag_name: ${{ needs.release-please-prod.outputs.tag_name }} + tag_name: ${{ needs.release.outputs.tag_name }} secrets: inherit - # Stable releases land on `production` and were never merged back, so `dev` - # accumulated a permanent one-way divergence: 26 commits at the last count, - # every one of them release bookkeeping, growing by ~3 per release forever. - # That also left `dev`'s package.json and CHANGELOG.md stale between releases. - # This opens the back-merge automatically so the next promotion's diff is only - # the commits since this release. + # Brings the release commit back to `dev`, so its package.json, server.json + # and CHANGELOG.md match what shipped (CHANGELOG.md on `dev` is the one the + # repo's front page shows). `dev` only allows squash merges, so this lands as + # one commit with `production`'s content but not its history. That is fine: + # promote.yml merges `production` into every release branch, which is what + # keeps the next release PR mergeable. back-merge: - needs: release-please-prod - if: needs.release-please-prod.outputs.release_created == 'true' + needs: release + if: needs.release.outputs.release_created == 'true' runs-on: ubuntu-latest permissions: contents: write @@ -88,9 +118,8 @@ jobs: env: BOT_APP_ID: ${{ secrets.BOT_APP_ID }} steps: - # See release-please-prod for why this prefers an App token: a PR opened by - # GITHUB_TOKEN does not trigger the required checks, and `dev`'s `Require - # CI` ruleset has NO bypass actors, so such a PR can never be merged. + # Prefers the App token: a PR opened by GITHUB_TOKEN does not trigger the + # required checks, so it could only be merged by an admin bypass. - uses: actions/create-github-app-token@v3 id: app-token if: env.BOT_APP_ID != '' @@ -107,7 +136,7 @@ jobs: - name: Open the back-merge PR env: GH_TOKEN: ${{ steps.app-token.outputs.token || secrets.GITHUB_TOKEN }} - VERSION: ${{ needs.release-please-prod.outputs.version }} + VERSION: ${{ needs.release.outputs.version }} run: | set -euo pipefail BRANCH="chore/back-merge-${VERSION}" @@ -116,9 +145,7 @@ jobs: git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git checkout -b "$BRANCH" - # A merge commit, never a squash or rebase: it is what keeps `dev` and - # `production` ancestors of each other. Rewriting the commits here is - # what left the two branches permanently divergent before 5.5.0. + # A merge, so the PR's diff is exactly what `production` changed. if ! git merge --no-ff origin/production -m "chore: merge production into dev after ${VERSION}"; then echo "Back-merge of production into dev conflicts — resolve it by hand." >&2 git merge --abort || true @@ -135,4 +162,4 @@ jobs: --base dev \ --head "$BRANCH" \ --title "chore: merge production into dev after ${VERSION}" \ - --body "Back-merge of the ${VERSION} stable release so \`dev\` carries the released package.json, CHANGELOG.md and manifest. Opened automatically by the Release workflow." + --body "Back-merge of the ${VERSION} stable release so \`dev\` carries the released package.json, server.json and CHANGELOG.md. Squash-merge it (the only method \`dev\` allows). Opened automatically by the Release workflow." diff --git a/.release-please-manifest.json b/.release-please-manifest.json deleted file mode 100644 index c99ba65..0000000 --- a/.release-please-manifest.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - ".": "5.12.0" -} diff --git a/CLAUDE.md b/CLAUDE.md index 2e2a5a9..570d0d8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -64,40 +64,36 @@ Full guide in `CONTRIBUTING.md`; the operationally important parts (the ones tha - ⚠️ **This repo is public — write PR titles and bodies, commit messages, code comments, test names and issues for a stranger.** Work here is often prompted by a support ticket or incident in the private `dcd` repo; that context stays there. Keep out: customer or org names and ids, ticket refs (`SUP-…`), private-repo issue/PR numbers, customer usage numbers, internal hostnames, Supabase project refs and dashboard links, and anything about our own security posture — key rotations or revocations, when they happened, which CLI versions they broke. Describe the fault generically ("a dropped B2 request failed the upload") and link the private issue from the private side instead. Edits don't undo a leak: GitHub keeps every revision of a PR or issue body, and a pushed commit stays readable from the PR after a later commit fixes it, so get it right before the first push. - **Branch off `dev`** (the default branch) and open PRs **against `dev`**. `production` is the maintainer-only stable track — never target it directly. -- PRs are **squash-merged**, so the **PR title becomes the commit** and must be a [Conventional Commit](https://www.conventionalcommits.org). The title — not the branch commits — is what release-please reads to compute the next version, so it matters even though individual commits are squashed away. A `PR Title` CI check enforces it. +- PRs are **squash-merged**, so the **PR title becomes the commit** and must be a [Conventional Commit](https://www.conventionalcommits.org). The title — not the branch commits — is what the release reads to compute the next version and the changelog entry (`scripts/stable-release.mjs`), so it matters even though individual commits are squashed away. A `PR Title` CI check enforces it. - Type → bump: `feat` **minor**; `fix`/`perf`/`deps`/`revert`/`refactor` **patch**; `docs`/`chore`/`test`/`ci`/`build`/`style` are hidden and bump nothing. Allowed scopes are free-form. -- ⚠️ **A `!` (or `BREAKING CHANGE:` footer) bumps the MAJOR — do not use it casually.** The configs set `bump-minor-pre-major: true`, but that only applies **below 1.0.0**; we are on 5.x, so it is inert and a breaking marker means exactly what semver says. A `refactor(cloud)!:` PR title once produced a `6.0.0-beta.1` release PR for what was only a flag rename in an unconsumed beta. Because PRs are squash-merged, **the PR title IS the commit** — the `!` lands even if no branch commit carried it. -- **Never hand-edit `package.json` version, `CHANGELOG.md`, or `.release-please-manifest.json`** — release-please owns all three, and hand-editing them is what left the 5.6.0 release PR internally inconsistent. (`CHANGELOG-beta.md` is frozen; nothing writes it any more.) `src/types/generated/schema.types.ts` is likewise generated (openapi-typescript). +- ⚠️ **A `!` (or `BREAKING CHANGE:` footer) means a MAJOR — do not use it casually.** A `refactor(cloud)!:` PR title once produced a `6.0.0-beta.1` release PR for what was only a flag rename in an unconsumed beta. Because PRs are squash-merged, **the PR title IS the commit** — the `!` lands even if no branch commit carried it. The release never derives a major from one: it stops and lists the breaking commits, and a major has to be given as the version. +- **Never hand-edit the `package.json` or `server.json` version, or `CHANGELOG.md`** — the release commit that `promote.yml` writes owns all three, and hand-editing them is what left the 5.6.0 release PR internally inconsistent. (`CHANGELOG-beta.md` is frozen; nothing writes it any more.) `src/types/generated/schema.types.ts` is likewise generated (openapi-typescript). - A first-time contributor must sign the CLA (the CLA Assistant bot comments on the first PR); the CLA check must be green to merge. - **CI (`.github/workflows/cli-ci.yml`) runs the same steps on every PR** — fork, Dependabot and same-repo alike, with no privileged path: gitleaks secret scan, `pnpm lint`, `pnpm typecheck`, `pnpm test:unit`, `pnpm build`, `pnpm audit --audit-level moderate`. **`test/integration/*` is not run by CI at all** (see the Commands section: this public repo no longer reaches into the private `devicecloud-dev/dcd` repo for a mock API), so a green PR says nothing about the integration suite — run it locally with `MOCK_API_DIR` set if a change touches the API surface. gitleaks also runs as a pre-commit hook (allowlist in `.gitleaks.toml`); without the binary installed the hook self-skips and CI is the backstop. ## Releases -**Stable releases are automatic; betas are cut by hand.** +**A stable release is merging the release PR that a workflow keeps open; betas are cut by hand.** -| Line | Trigger | Version | npm tag | +| Line | How | Version | npm tag | | --- | --- | --- | --- | -| **stable** | push to `production` -> release-please opens a Release PR; merging it tags, publishes and uploads binaries | `X.Y.Z` | `latest` | -| **beta** | run the **Release beta** workflow (`release-beta.yml`) by hand from `dev` | `X.Y.Z-beta.N` | `beta` | +| **stable** | every push to `dev` runs **Promote to stable** (`promote.yml`), which keeps one release PR into `production` current; merging it tags, publishes and uploads binaries | `X.Y.Z` | `latest` | +| **beta** | run **Release beta** (`release-beta.yml`) by hand from `dev` | `X.Y.Z-beta.N` | `beta` | -Stable is driven by `release-please.yml` off `release-please-config.json` / `.release-please-manifest.json`, writing `CHANGELOG.md`. Merging the Release PR creates the tag + GitHub Release and the same run **chains** (as `needs:` jobs, because a `GITHUB_TOKEN`-created release won't fire `release: published`) into `npm-publish.yml` and `release-binaries.yml`. `get.devicecloud.dev` serves the binaries by reading the GitHub Releases API at runtime, so there's no separate manifest to deploy. After a stable release the workflow also opens a **back-merge PR** into `dev`, so the two branches don't drift apart the way they did up to 5.5.0. +**Cutting a stable release.** You don't start one: you merge the open `chore: release X.Y.Z` PR from `promote/cli-next` into `production`. Use a **merge commit**, the only method `production` allows. That push runs `release-please.yml`. It finds an untagged version on `production`, tags it, and creates the GitHub Release from the changelog section. It then **chains** into `npm-publish.yml` and `release-binaries.yml` as `needs:` jobs, because a `GITHUB_TOKEN`-created release won't fire `release: published`. Last, it opens a **back-merge PR** into `dev`. `get.devicecloud.dev` serves the binaries by reading the GitHub Releases API at runtime, so there's no separate manifest to deploy. To hold a release, just don't merge the PR. Closing it doesn't pause releases, because the next push to `dev` opens a new one. -Betas have **no release-please track and no manifest**. `release-beta.yml` derives the version from the npm registry (`scripts/next-beta-version.mjs`): it bumps the published `latest` and appends the next `-beta.N`, so a beta is always above the current stable. There was a second release-please track until 5.6.0, and because its manifest numbered itself with no reference to what stable had shipped, `@beta` ended up *older* than `@latest` three times (5.0.0, 5.2.0, 5.5.0) — each needing a hand-written `Release-As` to escape. `CHANGELOG-beta.md` is frozen at 5.6.0-beta.2; beta notes now live on the GitHub prerelease. +**How the release PR is kept current.** `promote.yml` runs on every push to `dev`. It rebuilds `promote/cli-next` from `origin/dev`, with `origin/production` merged in, plus one `chore: release X.Y.Z` commit that sets the version in `package.json` and `server.json` and adds the `CHANGELOG.md` section. Then it force-pushes the branch and opens the PR, or updates the open one's title and body. So the PR always carries all of `dev`, and its version moves up as `feat`s land. A push with nothing releasable since the last release, such as a docs change or the back-merge, does nothing. If `production` moved during the run because a release just merged, the run pushes nothing, and the back-merge's push into `dev` rebuilds the PR. If an open PR into `production` came from another branch, push runs warn and leave it alone. The workflow can also be run by hand (`gh workflow run promote.yml --ref dev`, or the Actions tab) to set the `version`. `dry_run: true` shows the version and changelog in the run summary and pushes nothing. The `CHANGELOG.md` date is the day the PR was last rebuilt. -**Promoting beta -> stable** is a maintainer opening a PR from `dev` into `production` and merging it with a **merge commit** — that push to `production` is what triggers the stable Release PR. Use a merge commit, never squash or rebase: the merge is what makes `production` a descendant of `dev`, so the two branches stay reconcilable and the next promotion's diff is only the commits since the last one. A squash or rebase promotion rewrites the commits, leaves the histories permanently divergent, and forces the next promotion to be reconstructed by hand — that is exactly what the pre-5.5.0 promotions did. +`scripts/stable-release.mjs` does the version and changelog work (`plan`, `apply`, `verify`, `notes`). `test/unit/stable-release.test.ts` drives it against throwaway git repos. -### Every promotion must carry a `Release-As:` pin +- **Version.** It is derived from the PR titles of the non-merge commits in `origin/production..origin/dev`, using the type → bump table above. When nothing is releasable, a push run does nothing, and a run started by hand fails unless a version is given. A breaking marker **never derives a major**: every push run fails and lists the breaking commits. To proceed, run the workflow by hand with the major as `version`. Later runs keep the open PR's version (`--keep`) whenever it is above the derived one, so a version set by hand is never lowered, and a major set once stays. The version must be above every stable tag. +- **Changelog.** It keeps release-please's layout, with one entry per PR. A title cut short with `…` is replaced by the full line from the squash body. release-please listed that line as a second entry. +- **Checks.** `release-check` in `cli-ci.yml` runs `verify` on every PR into `production`. It checks that `package.json`, `server.json` and the newest `CHANGELOG.md` section agree on a version that is untagged and above every stable tag. The Release workflow runs the same check before it tags. A push to `production` whose version is already tagged releases nothing. -Put the stable version on its own commit in the promotion branch: +**Why `production` is merged in every time.** `dev`'s rulesets allow only squash merges with linear history. So the back-merge lands as one commit with `production`'s content but not its history, and `production` never becomes an ancestor of `dev`. The back-merge keeps `dev`'s version files and changelog current. The merge in `promote.yml` is what keeps the release PR mergeable. If that merge conflicts, the workflow stops. That only happens when both branches changed the same lines, for example a hand edit on `production`. Then build the branch by hand the same way: from `origin/dev`, merge `origin/production` and resolve the conflict. Run `node scripts/stable-release.mjs plan --notes-out notes.md`, then `apply --version X.Y.Z --notes notes.md`, and commit `chore: release X.Y.Z`. Push it as `promote/cli-next` and open the PR. Later push runs fail on the same conflict until it is merged. -``` -git commit --allow-empty -m "chore: pin the X.Y.Z promotion" -m "Release-As: X.Y.Z" -``` +**`release-please.yml` keeps its name, although release-please is gone.** npm's trusted publisher is registered against that filename, and npm checks the name of the workflow that started the run. So a rename needs that registration updated on npmjs.com first. release-please needed a promotion PR, then a `Release-As:` pin on it, then its own Release PR. The pin was needed because a promotion makes every beta tag reachable from `production`, and release-please took the newest one as its base. That is how 5.6.0 got a `5.6.0-beta.1` release PR. -It must be an ordinary commit, not the merge commit — release-please's commit splitting is unreliable on merges. The `promotion-pin` check in `cli-ci.yml` enforces this. +Betas have **no manifest**. `release-beta.yml` derives the version from the npm registry (`scripts/next-beta-version.mjs`). It bumps the published `latest` and appends the next `-beta.N`, so a beta is always above the current stable. Until 5.6.0 there was a release-please beta track. Its manifest numbered itself without reference to what stable had shipped, so `@beta` ended up *older* than `@latest` three times (5.0.0, 5.2.0, 5.5.0). `CHANGELOG-beta.md` is frozen at 5.6.0-beta.2, and beta notes now live on the GitHub prerelease. -**Do not skip it on the grounds that the conventional commits since the last stable already imply the right bump.** They don't. A promotion is a merge, so every beta tag becomes reachable from `production`, and release-please takes the newest reachable tag as its base — which is a `-beta` one. The 5.6.0 promotion reasoned exactly that way, skipped the pin, and produced a `chore(production): release 5.6.0-beta.1` release PR while leaving `production` carrying `5.6.0-beta.1` in `package.json` against a stable manifest still reading `5.5.0`. `npm-publish.yml`'s version guard then refuses to publish, which is the intended backstop, not the fix. - -Also **keep `production`'s `version` line** when resolving the promotion's `package.json` conflict, not `dev`'s. Taking `dev`'s puts a prerelease on the stable branch for as long as the Release PR is open; release-please rewrites it from the manifest when that PR lands, but if the PR stalls — as 5.6.0's did — the stable branch sits on a `-beta`. - -Releases prefer an automation GitHub App token (`BOT_APP_ID`) so the Release PR and the back-merge PR trigger the CI / PR-title / CLA checks that branch protection requires, falling back to `GITHUB_TOKEN` until the App secrets are configured. +The release PR and the back-merge PR are opened with the automation GitHub App token (`BOT_APP_ID`). That way they trigger the CI, PR-title and CLA checks the rulesets require, which a `GITHUB_TOKEN` PR does not. `promote.yml` requires the App token; the back-merge falls back to `GITHUB_TOKEN`. Both PRs skip `claude-review`, which rejects bot actors. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 562769f..6907aa1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -140,15 +140,14 @@ deps: bump @modelcontextprotocol/sdk to 1.x You don't need to do anything for releases — **do not bump the version in `package.json` or edit `CHANGELOG.md`** in your PR. -Stable releases are automated by -[release-please](https://github.com/googleapis/release-please): maintainers -promote `dev` → `production` (always with a **merge commit**, so the two branches -stay in sync), which opens a Release PR; merging that publishes to npm under the -`latest` tag. - -release-please reads the Conventional Commit titles of merged PRs to compute the -next version and generate the changelog — which is exactly why the PR title -convention matters. +Stable releases are automated. After every merge into `dev`, the **Promote to +stable** workflow updates a release PR from `dev` into `production` that carries +the next version and changelog. When a maintainer merges that PR, the release +is tagged and published to npm under the `latest` tag. + +The workflow reads the Conventional Commit titles of merged PRs to work out the +next version and write the changelog, which is why the PR title convention +matters. Betas are published on demand by a maintainer running the **Release beta** workflow, so your change reaches npm's `beta` tag whenever the next one is cut diff --git a/release-please-config.json b/release-please-config.json deleted file mode 100644 index 4869ae1..0000000 --- a/release-please-config.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", - "release-type": "node", - "include-v-in-tag": true, - "include-component-in-tag": false, - "bump-minor-pre-major": true, - "bump-patch-for-minor-pre-major": false, - "draft": false, - "prerelease": false, - "changelog-sections": [ - { "type": "feat", "section": "Features" }, - { "type": "fix", "section": "Bug Fixes" }, - { "type": "perf", "section": "Performance" }, - { "type": "deps", "section": "Dependencies" }, - { "type": "revert", "section": "Reverts" }, - { "type": "refactor", "section": "Code Refactoring" }, - { "type": "docs", "section": "Documentation", "hidden": true }, - { "type": "chore", "section": "Miscellaneous", "hidden": true }, - { "type": "test", "section": "Tests", "hidden": true }, - { "type": "ci", "section": "Continuous Integration", "hidden": true }, - { "type": "build", "section": "Build System", "hidden": true }, - { "type": "style", "section": "Styles", "hidden": true } - ], - "packages": { - ".": { - "package-name": "@devicecloud.dev/dcd", - "changelog-path": "CHANGELOG.md", - "extra-files": [ - { "type": "json", "path": "server.json", "jsonpath": "$.version" }, - { "type": "json", "path": "server.json", "jsonpath": "$.packages[*].version" } - ] - } - } -} diff --git a/scripts/stable-release.mjs b/scripts/stable-release.mjs new file mode 100644 index 0000000..6a01af1 --- /dev/null +++ b/scripts/stable-release.mjs @@ -0,0 +1,497 @@ +#!/usr/bin/env node +/** + * Stable releases: work out the next version, write it, and check it. + * + * A stable release is ONE pull request into `production`, built by + * .github/workflows/promote.yml: `dev`, with `production` merged in, plus a + * commit that sets the version in package.json and server.json and adds the + * CHANGELOG.md section. Merging it is the release: release-please.yml sees an + * untagged version on `production`, tags it, creates the GitHub Release from + * the changelog section, and publishes. + * + * This replaced release-please, which needed a promotion PR, a `Release-As:` + * pin on it (or it based the version on a beta tag), and then a second Release + * PR. Here the version is derived from the same Conventional Commit PR titles, + * in one place, and the release PR is the only PR. + * + * Usage: + * node scripts/stable-release.mjs plan [--version X.Y.Z] [--keep X.Y.Z] [--skip-if-nothing] + * [--base ] [--head ] + * [--date YYYY-MM-DD] [--notes-out ] + * node scripts/stable-release.mjs apply --version X.Y.Z --notes + * node scripts/stable-release.mjs verify + * node scripts/stable-release.mjs notes [--version X.Y.Z] + * + * plan Derives the version from the commits in base..head (default + * origin/production..HEAD) and renders the changelog section. Writes + * nothing but --notes-out. Prints the version on stdout. + * --keep is the version of the release PR already open: a derived + * version never goes below it, so a version set by hand (a major, say) + * survives the automatic rebuilds on later pushes to dev. + * --skip-if-nothing exits 0 with release=false when nothing is + * releasable, instead of failing. + * apply Sets the version in package.json and server.json, and puts the section + * at the top of CHANGELOG.md, in the working tree. + * verify Checks the working tree is an unreleased, self-consistent release. The + * CI check on PRs into production and the Release workflow both run it. + * notes Prints a version's CHANGELOG.md section (default: package.json's). + * + * plan and verify append key=value lines to $GITHUB_OUTPUT when it is set. + */ +import { execFileSync } from 'node:child_process'; +import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'; +import { isDeepStrictEqual } from 'node:util'; + +// Conventional Commit type -> changelog section, in the order the sections are +// printed. A type in a section bumps the patch (feat: the minor); the hidden +// types are left out of the changelog and bump nothing. Keep both lists in +// lockstep with the allowed types in .github/workflows/pr-title-lint.yml. +const SECTIONS = [ + ['feat', 'Features'], + ['fix', 'Bug Fixes'], + ['perf', 'Performance'], + ['deps', 'Dependencies'], + ['revert', 'Reverts'], + ['refactor', 'Code Refactoring'], +]; +const HIDDEN = new Set(['docs', 'chore', 'test', 'ci', 'build', 'style']); +const RELEASABLE = new Set(SECTIONS.map(([type]) => type)); + +// Stable versions only. The stable line never carries a prerelease; betas are +// cut separately by release-beta.yml and never come through here. +const STABLE = /^(\d+)\.(\d+)\.(\d+)$/; + +const HEADER = /^(\w+)(?:\(([^()\r\n]+)\))?(!)?: (.+)$/; +const PR_SUFFIX = / \(#(\d+)\)$/; +const BREAKING_FOOTER = /^BREAKING[ -]CHANGE:/; + +class ReleaseError extends Error {} + +// GitHub Actions annotations in CI, plain prefixes everywhere else. +const IN_ACTIONS = process.env.GITHUB_ACTIONS === 'true'; +const ERROR = IN_ACTIONS ? '::error::' : 'Error: '; +const WARNING = IN_ACTIONS ? '::warning::' : 'Warning: '; + +// --------------------------------------------------------------------------- +// Versions + +function parseVersion(version) { + const match = STABLE.exec(version ?? ''); + return match ? match.slice(1).map(Number) : null; +} + +function compareVersions(a, b) { + const [pa, pb] = [parseVersion(a), parseVersion(b)]; + for (let i = 0; i < 3; i++) { + if (pa[i] !== pb[i]) return pa[i] < pb[i] ? -1 : 1; + } + return 0; +} + +function bumpVersion(version, bump) { + const [major, minor, patch] = parseVersion(version); + if (bump === 'major') return `${major + 1}.0.0`; + if (bump === 'minor') return `${major}.${minor + 1}.0`; + return `${major}.${minor}.${patch + 1}`; +} + +// --------------------------------------------------------------------------- +// Commits + +/** + * One commit, as the changelog sees it. PRs are squash-merged, so the subject + * is the PR title: `type(scope)!: description (#123)`. + * + * Long PR titles reach us cut short with an ellipsis. GitHub does that when it + * builds a title from a long commit subject, and again when it builds the + * squash subject from a long title, and puts the uncut text in the body. So a + * subject ending in `…` is replaced by the body line it is the start of, when + * there is one. release-please split those bodies into extra commits instead, + * which listed every such PR twice. + */ +function parseCommit(sha, message) { + const [first = '', ...body] = message.replace(/\r\n/g, '\n').trim().split('\n'); + let subject = first.trim(); + + let pr = null; + const prMatch = PR_SUFFIX.exec(subject); + if (prMatch) { + pr = Number(prMatch[1]); + subject = subject.slice(0, prMatch.index); + } + + if (subject.endsWith('…')) { + const stem = subject.slice(0, -1); + const full = body + .map((line) => line.trim()) + .find((line) => line.length > stem.length && line.startsWith(stem)); + if (full) subject = full.replace(PR_SUFFIX, ''); + } + + const header = HEADER.exec(subject); + if (!header) return { sha, subject, type: null, scope: null, description: subject, pr, breaking: false }; + + const [, type, scope, bang, description] = header; + const breaking = Boolean(bang) || body.some((line) => BREAKING_FOOTER.test(line.trim())); + return { sha, subject, type: type.toLowerCase(), scope: scope ?? null, description, pr, breaking }; +} + +/** null when nothing in `commits` calls for a release. */ +function bumpFor(commits) { + let bump = null; + for (const commit of commits) { + if (commit.breaking) return 'major'; + if (commit.type === 'feat') bump = 'minor'; + else if (!bump && RELEASABLE.has(commit.type)) bump = 'patch'; + } + return bump; +} + +// --------------------------------------------------------------------------- +// Changelog + +function entry(commit, repoUrl) { + const scope = commit.scope ? `**${commit.scope}:** ` : ''; + const pr = commit.pr ? ` ([#${commit.pr}](${repoUrl}/issues/${commit.pr}))` : ''; + return `* ${scope}${commit.description}${pr} ([${commit.sha.slice(0, 7)}](${repoUrl}/commit/${commit.sha}))`; +} + +// Unscoped entries first, then by scope, then by description: the order +// release-please used, so the file reads the same above and below the switch. +function byScopeThenDescription(a, b) { + if (a.scope !== b.scope) { + if (!a.scope) return -1; + if (!b.scope) return 1; + return a.scope.localeCompare(b.scope); + } + return a.description.localeCompare(b.description); +} + +/** + * The CHANGELOG.md section for a release, in release-please's layout (two + * blank lines before each subsection). It is also the GitHub Release body. + */ +function renderSection({ version, previous, date, commits, repoUrl }) { + const groups = []; + const breaking = commits.filter((c) => c.breaking); + if (breaking.length > 0) groups.push(['⚠ BREAKING CHANGES', breaking]); + for (const [type, title] of SECTIONS) { + const inSection = commits.filter((c) => c.type === type); + if (inSection.length > 0) groups.push([title, inSection]); + } + + const lines = [`## [${version}](${repoUrl}/compare/v${previous}...v${version}) (${date})`]; + if (groups.length === 0) { + lines.push('', '', 'No user-facing changes.'); + } + for (const [title, inGroup] of groups) { + lines.push('', '', `### ${title}`, ''); + lines.push(...[...inGroup].sort(byScopeThenDescription).map((c) => entry(c, repoUrl))); + } + return `${lines.join('\n')}\n`; +} + +const SECTION_HEADING = /^## \[([^\]]+)\]/; + +function firstSectionVersion(changelog) { + for (const line of changelog.split('\n')) { + const match = SECTION_HEADING.exec(line); + if (match) return match[1]; + } + return null; +} + +function insertSection(changelog, section) { + const lines = changelog.split('\n'); + const at = lines.findIndex((line) => SECTION_HEADING.test(line)); + if (at === -1) return `${changelog.trimEnd()}\n\n${section}`; + const head = lines.slice(0, at).join('\n'); + const rest = lines.slice(at).join('\n'); + return `${head}${head ? '\n' : ''}${section}\n${rest}`; +} + +function extractSection(changelog, version) { + const lines = changelog.split('\n'); + const start = lines.findIndex((line) => SECTION_HEADING.exec(line)?.[1] === version); + if (start === -1) return null; + let end = lines.findIndex((line, i) => i > start && SECTION_HEADING.test(line)); + if (end === -1) end = lines.length; + return `${lines.slice(start, end).join('\n').trimEnd()}\n`; +} + +// --------------------------------------------------------------------------- +// Version files + +/** + * Rewrites the version strings in a JSON file without reformatting it: a + * textual replace of `"version": ""`, checked against the same edit + * made on the parsed object, so a stray match or a missed field fails loudly. + */ +function rewriteJsonVersions(path, previous, version, setVersions) { + const text = readFileSync(path, 'utf8'); + const expected = JSON.parse(text); + setVersions(expected, version); + + const pattern = new RegExp(`("version"\\s*:\\s*")${previous.replaceAll('.', '\\.')}"`, 'g'); + const rewritten = text.replace(pattern, `$1${version}"`); + if (!isDeepStrictEqual(JSON.parse(rewritten), expected)) { + throw new ReleaseError( + `${path}: rewriting "version": "${previous}" to ${version} did not produce the expected file. ` + + `Its version fields must all read ${previous} before a release.`, + ); + } + writeFileSync(path, rewritten); +} + +const setPackageVersion = (pkg, version) => { + pkg.version = version; +}; + +// server.json is the MCP registry manifest: its own version and every npm +// package entry's version track the release. Nothing else in it may carry a +// version (see test/unit/server-json.test.ts). +const setServerVersions = (server, version) => { + server.version = version; + for (const pkg of server.packages ?? []) pkg.version = version; +}; + +function readJson(path) { + return JSON.parse(readFileSync(path, 'utf8')); +} + +// --------------------------------------------------------------------------- +// Git + +function git(...args) { + return execFileSync('git', args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }); +} + +function tagExists(tag) { + try { + git('rev-parse', '--quiet', '--verify', `refs/tags/${tag}^{commit}`); + return true; + } catch { + return false; + } +} + +function highestStableTag() { + const versions = git('tag', '--list', 'v*') + .split('\n') + .map((tag) => tag.trim().replace(/^v/, '')) + .filter((v) => parseVersion(v)); + return versions.sort(compareVersions).at(-1) ?? null; +} + +const RECORD = '\u001E'; +const FIELD = '\u001F'; + +/** Non-merge commits in base..head, oldest first. */ +function commitsBetween(base, head) { + return git('log', '--no-merges', '--reverse', `--format=%H${FIELD}%B${RECORD}`, `${base}..${head}`) + .split(RECORD) + .map((record) => record.trim()) + .filter(Boolean) + .map((record) => { + const [sha, message = ''] = record.split(FIELD); + return parseCommit(sha.trim(), message); + }); +} + +function repoUrl(pkg) { + const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository?.url; + if (!url) throw new ReleaseError('package.json has no repository url to link the changelog to'); + return url.replace(/^git\+/, '').replace(/\.git$/, ''); +} + +// --------------------------------------------------------------------------- +// Commands + +function arg(name) { + const i = process.argv.indexOf(`--${name}`); + return i === -1 ? '' : (process.argv[i + 1] ?? '').trim(); +} + +function output(values) { + if (!process.env.GITHUB_OUTPUT) return; + appendFileSync( + process.env.GITHUB_OUTPUT, + Object.entries(values) + .map(([key, value]) => `${key}=${value}\n`) + .join(''), + ); +} + +function describe(commit) { + return ` ${commit.sha.slice(0, 7)} ${commit.subject}${commit.pr ? ` (#${commit.pr})` : ''}`; +} + +function majorError(commits, previous) { + const breaking = commits.filter((c) => c.breaking).map(describe).join('\n'); + return new ReleaseError( + `these commits are marked breaking, which calls for ${bumpVersion(previous, 'major')}:\n${breaking}\n` + + 'A major is never derived. If it is intended, run "Promote to stable" with that version once; ' + + 'later runs keep it.', + ); +} + +function plan() { + const base = arg('base') || 'origin/production'; + const head = arg('head') || 'HEAD'; + const requested = arg('version'); + const keep = arg('keep'); + const date = arg('date') || new Date().toISOString().slice(0, 10); + if (keep && !parseVersion(keep)) throw new ReleaseError(`--keep "${keep}" is not a stable X.Y.Z version`); + + const basePackage = JSON.parse(git('show', `${base}:package.json`)); + const previous = basePackage.version; + if (!parseVersion(previous)) { + throw new ReleaseError(`${base} is on "${previous}", which is not a stable X.Y.Z version`); + } + if (!tagExists(`v${previous}`)) { + throw new ReleaseError(`${base} is on ${previous}, but there is no v${previous} tag to release on top of`); + } + + const commits = commitsBetween(base, head); + const bump = bumpFor(commits); + const derived = bump && bump !== 'major' ? bumpVersion(previous, bump) : null; + // A kept version only counts while it is still ahead of the base: once its + // release has merged, the open PR it came from is gone anyway. + const kept = keep && compareVersions(keep, previous) > 0 ? keep : null; + + let version; + let how; + if (requested) { + if (!parseVersion(requested)) throw new ReleaseError(`"${requested}" is not a stable X.Y.Z version`); + version = requested; + how = 'requested'; + } else if (!bump && !kept) { + const message = `nothing to release: no ${[...RELEASABLE].join('/')} commits in ${base}..${head}`; + if (process.argv.includes('--skip-if-nothing')) { + console.error(`${message}.`); + output({ release: 'false' }); + return; + } + throw new ReleaseError(`${message}. Pass a version to release anyway.`); + } else if (kept && (!derived || compareVersions(kept, derived) > 0)) { + // CLAUDE.md: a `!` in a PR title once turned a flag rename into a 6.0.0 + // release PR. A major is never derived; it has to be asked for once, and + // is kept from then on. + if (bump === 'major' && compareVersions(kept, bumpVersion(previous, 'major')) < 0) { + throw majorError(commits, previous); + } + version = kept; + how = 'kept'; + } else if (bump === 'major') { + throw majorError(commits, previous); + } else { + version = derived; + how = bump; + } + + if (compareVersions(version, previous) <= 0) { + throw new ReleaseError(`${version} is not above ${previous}, the version ${base} is on`); + } + const highest = highestStableTag(); + if (highest && compareVersions(version, highest) <= 0) { + throw new ReleaseError(`${version} is not above v${highest}, the highest stable tag`); + } + if (tagExists(`v${version}`)) throw new ReleaseError(`tag v${version} already exists`); + + const section = renderSection({ version, previous, date, commits, repoUrl: repoUrl(basePackage) }); + const notesOut = arg('notes-out'); + if (notesOut) writeFileSync(notesOut, section); + + const listed = commits.filter((c) => RELEASABLE.has(c.type) || c.breaking); + const hidden = commits.filter((c) => HIDDEN.has(c.type) && !c.breaking); + const unparsed = commits.filter((c) => !c.type); + console.error(`${previous} -> ${version} (${how}), ${base}..${head}`); + console.error(`In the changelog (${listed.length}):\n${listed.map(describe).join('\n') || ' none'}`); + if (hidden.length > 0) console.error(`Left out, hidden types (${hidden.length}):\n${hidden.map(describe).join('\n')}`); + if (unparsed.length > 0) { + console.error(`${WARNING}Left out, not Conventional Commits (${unparsed.length}):\n${unparsed.map(describe).join('\n')}`); + } + + console.log(version); + output({ release: 'true', version, previous, bump: how, tag: `v${version}` }); +} + +function apply() { + const version = arg('version'); + const notes = arg('notes'); + if (!parseVersion(version)) throw new ReleaseError('apply needs --version X.Y.Z'); + if (!notes) throw new ReleaseError('apply needs --notes (from plan --notes-out)'); + + const previous = readJson('package.json').version; + const section = readFileSync(notes, 'utf8'); + if (firstSectionVersion(section) !== version) { + throw new ReleaseError(`${notes} is not the changelog section for ${version}`); + } + + rewriteJsonVersions('package.json', previous, version, setPackageVersion); + rewriteJsonVersions('server.json', previous, version, setServerVersions); + writeFileSync('CHANGELOG.md', insertSection(readFileSync('CHANGELOG.md', 'utf8'), section)); + console.error(`package.json, server.json and CHANGELOG.md now carry ${version}`); +} + +function verify() { + const version = readJson('package.json').version; + const problems = []; + + if (!parseVersion(version)) problems.push(`package.json is on "${version}", not a stable X.Y.Z version`); + + const server = readJson('server.json'); + const serverVersions = [server.version, ...(server.packages ?? []).map((p) => p.version)]; + if (serverVersions.some((v) => v !== version)) { + problems.push(`server.json versions (${serverVersions.join(', ')}) do not all match package.json's ${version}`); + } + + const changelogVersion = firstSectionVersion(readFileSync('CHANGELOG.md', 'utf8')); + if (changelogVersion !== version) { + problems.push(`CHANGELOG.md's newest section is ${changelogVersion ?? 'missing'}, not ${version}`); + } + + if (parseVersion(version)) { + if (tagExists(`v${version}`)) { + problems.push(`v${version} is already tagged, so this would release nothing`); + } else { + const highest = highestStableTag(); + if (highest && compareVersions(version, highest) <= 0) { + problems.push(`${version} is not above v${highest}, the highest stable tag`); + } + } + } + + if (problems.length > 0) { + throw new ReleaseError( + `not a releasable stable version:\n${problems.map((p) => ` - ${p}`).join('\n')}\n` + + 'Stable releases are built by the "Promote to stable" workflow (.github/workflows/promote.yml).', + ); + } + console.error(`${version} is ready to release`); + console.log(version); + output({ version, tag: `v${version}` }); +} + +function notes() { + const version = arg('version') || readJson('package.json').version; + const section = extractSection(readFileSync('CHANGELOG.md', 'utf8'), version); + if (!section) throw new ReleaseError(`CHANGELOG.md has no section for ${version}`); + process.stdout.write(section); +} + +const COMMANDS = { plan, apply, verify, notes }; +const command = COMMANDS[process.argv[2]]; +if (!command) { + console.error(`Usage: node scripts/stable-release.mjs <${Object.keys(COMMANDS).join('|')}> [options]`); + process.exit(2); +} +try { + command(); +} catch (error) { + if (!(error instanceof ReleaseError)) throw error; + console.error(`${ERROR}${error.message.split('\n')[0]}`); + const rest = error.message.split('\n').slice(1).join('\n'); + if (rest) console.error(rest); + process.exit(1); +} diff --git a/test/unit/server-json.test.ts b/test/unit/server-json.test.ts index d3b711e..f0e51db 100644 --- a/test/unit/server-json.test.ts +++ b/test/unit/server-json.test.ts @@ -11,7 +11,8 @@ import { readFileSync } from 'node:fs'; * The runtime arguments end with a bare `--package`, so the * `@` the client appends becomes its value, and * `dcd-mcp` follows as the package argument. The pin therefore lives only in - * `packages[].version`, a bare version string release-please can rewrite. + * `packages[].version`, a bare version string the release can rewrite + * (scripts/stable-release.mjs, tested in stable-release.test.ts). */ interface Argument { name?: string; @@ -30,13 +31,6 @@ interface ServerJson { version: string; } -interface ReleasePleaseConfig { - packages: Record< - string, - { 'extra-files'?: Array<{ jsonpath?: string; path: string; type: string }> } - >; -} - const readJson = (file: string): T => JSON.parse(readFileSync(new URL(`../../${file}`, import.meta.url), 'utf8')) as T; @@ -70,29 +64,17 @@ describe('server.json (MCP registry manifest)', () => { }); it('pins the last stable release, and only in the bare version fields', () => { - const { '.': stable } = readJson>( - '.release-please-manifest.json', - ); + const { version: stable } = readJson<{ version: string }>('package.json'); expect(server.version).to.equal(stable); expect(npmPackage.version).to.equal(stable); - // A version embedded in an argument can't be kept current: release-please's - // json updater replaces the whole matched value with the bare version. + // A version embedded in an argument can't be kept current: the release + // only rewrites bare `"version": "X.Y.Z"` fields. const argv = [ ...render(npmPackage.runtimeArguments), ...render(npmPackage.packageArguments), ]; expect(argv.filter((a) => /@\d/.test(a))).to.deep.equal([]); }); - - it('only lets release-please rewrite bare version fields in server.json', () => { - const config = readJson('release-please-config.json'); - const serverJsonPaths = Object.values(config.packages) - .flatMap((pkg) => pkg['extra-files'] ?? []) - .filter((file) => file.path === 'server.json') - .map((file) => file.jsonpath); - - expect(serverJsonPaths).to.have.members(['$.version', '$.packages[*].version']); - }); }); diff --git a/test/unit/stable-release.test.ts b/test/unit/stable-release.test.ts new file mode 100644 index 0000000..a632dd1 --- /dev/null +++ b/test/unit/stable-release.test.ts @@ -0,0 +1,332 @@ +import { expect } from 'chai'; +import { execFileSync, spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** + * scripts/stable-release.mjs works out, writes and checks a stable release + * (.github/workflows/promote.yml and release-please.yml). It is driven here as + * those workflows drive it: as a subprocess, inside a throwaway git repo with a + * `production` branch tagged at the last release and a `dev` branch ahead of it. + */ +const ROOT = fileURLToPath(new URL('../../', import.meta.url)); +const SCRIPT = path.join(ROOT, 'scripts/stable-release.mjs'); +const REPO = 'https://github.com/devicecloud-dev/dcd-cli'; + +// git without the developer's own config: no signing, hooks or default branch. +const GIT_ENV = { + ...process.env, + GIT_AUTHOR_EMAIL: 'test@example.com', + GIT_AUTHOR_NAME: 'Test', + GIT_COMMITTER_EMAIL: 'test@example.com', + GIT_COMMITTER_NAME: 'Test', + GIT_CONFIG_GLOBAL: os.devNull, + GIT_CONFIG_NOSYSTEM: '1', +}; + +const PACKAGE_JSON = `{ + "name": "@devicecloud.dev/dcd", + "repository": { + "type": "git", + "url": "git+${REPO}.git" + }, + "version": "1.4.0", + "devDependencies": { + "pinned": "1.4.0" + } +} +`; + +const SERVER_JSON = `{ + "name": "dev.devicecloud/dcd", + "version": "1.4.0", + "packages": [ + { + "identifier": "@devicecloud.dev/dcd", + "version": "1.4.0" + } + ] +} +`; + +const OLD_SECTION = `## [1.4.0](${REPO}/compare/v1.3.0...v1.4.0) (2026-01-01) + + +### Features + +* an older feature +`; + +describe('scripts/stable-release.mjs', () => { + let dir: string; + let outputFile: string; + + const git = (...args: string[]): string => + execFileSync('git', args, { cwd: dir, encoding: 'utf8', env: GIT_ENV }); + const commit = (message: string): string => { + git('commit', '--allow-empty', '--quiet', '-m', message); + return git('rev-parse', 'HEAD').trim(); + }; + const read = (file: string): string => fs.readFileSync(path.join(dir, file), 'utf8'); + const write = (file: string, text: string): void => + fs.writeFileSync(path.join(dir, file), text); + + const run = (...args: string[]) => { + fs.writeFileSync(outputFile, ''); + const result = spawnSync(process.execPath, [SCRIPT, ...args], { + cwd: dir, + encoding: 'utf8', + env: { ...GIT_ENV, GITHUB_ACTIONS: '', GITHUB_OUTPUT: outputFile }, + }); + return { ...result, outputs: fs.readFileSync(outputFile, 'utf8') }; + }; + const plan = (...args: string[]) => + run('plan', '--base', 'production', '--date', '2026-11-09', '--notes-out', 'notes.md', ...args); + + const link = (sha: string) => `([${sha.slice(0, 7)}](${REPO}/commit/${sha}))`; + const pr = (n: number) => `([#${n}](${REPO}/issues/${n}))`; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-stable-release-')); + outputFile = path.join(dir, '.github-output'); + git('init', '--quiet', '--initial-branch', 'production'); + write('.gitignore', 'notes.md\n.github-output\n'); + write('package.json', PACKAGE_JSON); + write('server.json', SERVER_JSON); + write('CHANGELOG.md', `# Changelog\n\n${OLD_SECTION}`); + git('add', '.'); + commit('chore: release 1.4.0'); + git('tag', 'v1.4.0'); + git('checkout', '--quiet', '-b', 'dev'); + }); + + afterEach(() => { + fs.rmSync(dir, { force: true, recursive: true }); + }); + + it('derives a minor from a feat and lists each releasable PR once', () => { + const fix = commit('fix(cloud): retry a dropped upload (#11)'); + const feat = commit('feat: add a --quiet flag (#12)'); + commit('chore: tidy the scripts (#13)'); + commit('docs: explain the flag'); + + const result = plan(); + + expect(result.status, result.stderr).to.equal(0); + expect(result.stdout).to.equal('1.5.0\n'); + expect(result.outputs).to.include('version=1.5.0\n').and.include('previous=1.4.0\n').and.include('bump=minor\n'); + expect(read('notes.md')).to.equal( + [ + `## [1.5.0](${REPO}/compare/v1.4.0...v1.5.0) (2026-11-09)`, + '', + '', + '### Features', + '', + `* add a --quiet flag ${pr(12)} ${link(feat)}`, + '', + '', + '### Bug Fixes', + '', + `* **cloud:** retry a dropped upload ${pr(11)} ${link(fix)}`, + '', + ].join('\n'), + ); + // plan writes nothing but the notes. + expect(read('package.json')).to.equal(PACKAGE_JSON); + }); + + it("derives a patch from dev's own commits, leaving out production's and merges", () => { + commit('fix: handle an empty flow directory (#21)'); + commit('deps: bump the minor-and-patch group (#22)'); + git('checkout', '--quiet', 'production'); + commit('feat: a commit that only production has'); + git('checkout', '--quiet', 'dev'); + git('merge', '--quiet', '--no-ff', '-m', 'Merge branch production into dev', 'production'); + + const result = plan(); + + expect(result.status, result.stderr).to.equal(0); + expect(result.stdout).to.equal('1.4.1\n'); + expect(read('notes.md')) + .to.include('### Bug Fixes') + .and.include('### Dependencies') + .and.not.include('only production has') + .and.not.include('Merge branch'); + }); + + it('uses the untruncated title from the body when the subject was cut short', () => { + commit( + 'feat(report): deprecate allure and html-detailed, removed on 7 Decemb… (#298)\n\n' + + 'feat(report): deprecate allure and html-detailed, removed on 7 December 2026\n\n' + + 'The allure and html-detailed report formats are deprecated.', + ); + + const result = plan(); + + expect(result.status, result.stderr).to.equal(0); + expect(read('notes.md')) + .to.include(`* **report:** deprecate allure and html-detailed, removed on 7 December 2026 ${pr(298)}`) + .and.not.include('…'); + }); + + it('never derives a major, but releases one that is asked for', () => { + commit('refactor(cloud)!: rename --flows to --flow-dir (#30)'); + + const derived = plan(); + expect(derived.status).to.equal(1); + expect(derived.stderr).to.include('2.0.0').and.include('rename --flows'); + expect(fs.existsSync(path.join(dir, 'notes.md'))).to.equal(false); + + const requested = plan('--version', '2.0.0'); + expect(requested.status, requested.stderr).to.equal(0); + expect(requested.outputs).to.include('bump=requested\n'); + expect(read('notes.md')) + .to.include('### ⚠ BREAKING CHANGES\n\n* **cloud:** rename --flows to --flow-dir') + .and.include('### Code Refactoring\n\n* **cloud:** rename --flows to --flow-dir'); + }); + + it('treats a BREAKING CHANGE footer as breaking too', () => { + commit('fix: drop the legacy upload path (#31)\n\nBREAKING CHANGE: CLIs older than 5.9.0 cannot upload.'); + + expect(plan().stderr).to.include('2.0.0'); + }); + + it('refuses a release with nothing in it unless a version is given', () => { + commit('chore: tidy (#40)'); + commit('ci: cache pnpm (#41)'); + + const derived = plan(); + expect(derived.status).to.equal(1); + expect(derived.stderr).to.include('nothing to release'); + + const requested = plan('--version', '1.4.1'); + expect(requested.status, requested.stderr).to.equal(0); + expect(read('notes.md')).to.include('No user-facing changes.'); + }); + + it('skips quietly with --skip-if-nothing, as a push run does', () => { + commit('docs: explain the flag (#42)'); + + const result = plan('--skip-if-nothing'); + expect(result.status, result.stderr).to.equal(0); + expect(result.stdout).to.equal(''); + expect(result.outputs).to.equal('release=false\n'); + expect(fs.existsSync(path.join(dir, 'notes.md'))).to.equal(false); + }); + + it("keeps the open release PR's version unless the commits now call for more", () => { + commit('fix: handle an empty flow directory (#43)'); + + // A version set by hand, above what the commits call for, survives. + const kept = plan('--keep', '1.6.0'); + expect(kept.stdout).to.equal('1.6.0\n'); + expect(kept.outputs).to.include('bump=kept\n'); + + // A kept version equal to or below the derived one gives way to it. + expect(plan('--keep', '1.4.1').outputs).to.include('version=1.4.1\n').and.include('bump=patch\n'); + commit('feat: add a --quiet flag (#44)'); + expect(plan('--keep', '1.4.1').stdout).to.equal('1.5.0\n'); + + // One that is no longer ahead of production (its release merged) is ignored. + expect(plan('--keep', '1.4.0').stdout).to.equal('1.5.0\n'); + }); + + it('keeps a major once it has been set by hand, but never derives one', () => { + commit('refactor(cloud)!: rename --flows to --flow-dir (#45)'); + + expect(plan('--keep', '1.5.0').status).to.equal(1); + expect(plan('--keep', '2.0.0').stdout).to.equal('2.0.0\n'); + expect(plan('--keep', '2.0.0', '--skip-if-nothing').stdout).to.equal('2.0.0\n'); + }); + + it('refuses a version that is not new', () => { + commit('feat: something (#50)'); + + expect(plan('--version', '1.4.0').stderr).to.include('not above 1.4.0'); + expect(plan('--version', '1.5.0-beta.1').stderr).to.include('not a stable X.Y.Z version'); + + git('tag', 'v1.6.0'); + expect(plan('--version', '1.5.0').stderr).to.include('not above v1.6.0'); + expect(plan('--version', '1.6.0').stderr).to.include('not above v1.6.0'); + }); + + it('writes the release into the version files and changelog, which verify accepts', () => { + commit('feat: add a --quiet flag (#12)'); + expect(plan().status).to.equal(0); + + const apply = run('apply', '--version', '1.5.0', '--notes', 'notes.md'); + expect(apply.status, apply.stderr).to.equal(0); + + expect(read('package.json')).to.equal(PACKAGE_JSON.replace('"version": "1.4.0"', '"version": "1.5.0"')); + expect(read('server.json')).to.equal(SERVER_JSON.replaceAll('1.4.0', '1.5.0')); + expect(read('CHANGELOG.md')).to.equal(`# Changelog\n\n${read('notes.md')}\n${OLD_SECTION}`); + + const verify = run('verify'); + expect(verify.status, verify.stderr).to.equal(0); + expect(verify.outputs).to.include('version=1.5.0\n').and.include('tag=v1.5.0\n'); + + expect(run('notes').stdout).to.equal(read('notes.md')); + expect(run('notes', '--version', '1.4.0').stdout).to.equal(OLD_SECTION); + expect(run('notes', '--version', '1.3.0').status).to.equal(1); + }); + + it('verify rejects a tree that would not release cleanly', () => { + const released = run('verify'); + expect(released.status).to.equal(1); + expect(released.stderr).to.include('v1.4.0 is already tagged'); + + commit('feat: add a --quiet flag (#12)'); + plan(); + run('apply', '--version', '1.5.0', '--notes', 'notes.md'); + write('server.json', SERVER_JSON.replace('"version": "1.4.0"', '"version": "1.5.0"')); + write('CHANGELOG.md', `# Changelog\n\n${OLD_SECTION}`); + + const stale = run('verify'); + expect(stale.status).to.equal(1); + expect(stale.stderr).to.include('server.json versions (1.5.0, 1.4.0)').and.include("newest section is 1.4.0, not 1.5.0"); + }); + + it('refuses to apply when a version field it should not touch matches', () => { + write('package.json', PACKAGE_JSON.replace('"pinned": "1.4.0"', '"version": "1.4.0"')); + git('commit', '--quiet', '--all', '-m', 'chore: a nested version field'); + commit('feat: something (#60)'); + plan(); + + const apply = run('apply', '--version', '1.5.0', '--notes', 'notes.md'); + expect(apply.status).to.equal(1); + expect(apply.stderr).to.include('package.json'); + }); + + it("changes only the version fields of the repo's own package.json and server.json", () => { + const realPackage = fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'); + const realServer = fs.readFileSync(path.join(ROOT, 'server.json'), 'utf8'); + const current = (JSON.parse(realPackage) as { version: string }).version; + const [major, minor] = current.split('.').map(Number); + const next = `${major}.${minor + 1}.0`; + + git('checkout', '--quiet', 'production'); + write('package.json', realPackage); + write('server.json', realServer); + git('commit', '--quiet', '--all', '-m', `chore: release ${current}`); + git('tag', `v${current}`); + git('checkout', '--quiet', 'dev'); + git('merge', '--quiet', 'production'); + commit('feat: something (#70)'); + + expect(plan().stdout).to.equal(`${next}\n`); + const apply = run('apply', '--version', next, '--notes', 'notes.md'); + expect(apply.status, apply.stderr).to.equal(0); + + const changed = (before: string, after: string) => { + const lines = after.split('\n'); + return before.split('\n').flatMap((line, i) => (line === lines[i] ? [] : [lines[i].trim()])); + }; + expect(changed(realPackage, read('package.json'))).to.deep.equal([`"version": "${next}",`]); + expect(changed(realServer, read('server.json'))).to.deep.equal([ + `"version": "${next}",`, + `"version": "${next}",`, + ]); + }); +}); From dab495bf501059b2866ead21603b3693ae14dcbc Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:52:57 +0000 Subject: [PATCH 05/20] =?UTF-8?q?feat(mcp):=20set=20up=20Codex=20with=20dc?= =?UTF-8?q?d=20mcp=20install,=20and=20document=20every=20host=E2=80=A6=20(?= =?UTF-8?q?#306)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit feat(mcp): set up Codex with dcd mcp install, and document every hosted client - dcd mcp install codex runs codex mcp add (after codex mcp remove, so a rerun replaces the entry). Codex keeps servers in ~/.codex/config.toml, shared by its CLI, IDE extension and desktop app, so its own CLI writes the entry. --print shows the command. - In read-only mode, dcd mcp asks the hosted server for its read-only tools too (/mcp?read_only=true). The local filter stays, so an API without the flag is still read-only here. - README: the hosted server's setup for Claude Code, Cursor, VS Code, Codex and Claude Desktop, its read-only URL (quoted, since ? is a zsh glob), API-key sign-in, and Codex for dcd mcp. --- README.md | 56 +++++++++++++++++++++++++++++++---- src/commands/mcp.ts | 21 +++++++++++-- src/mcp/bridge.ts | 6 +++- src/utils/mcp-install.ts | 15 ++++++++-- test/unit/mcp-bridge.test.ts | 8 ++++- test/unit/mcp-install.test.ts | 5 ++++ 6 files changed, 98 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index ddb1fcb..9df9430 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ See full documentation: [Docs](https://docs.devicecloud.dev) ## MCP server -devicecloud.dev has an [MCP](https://modelcontextprotocol.io) server, so AI agents (Claude, Cursor, VS Code) can run cloud tests and drive cloud devices. You don't run it yourself. You add it to your MCP client's config, and the client starts it. +devicecloud.dev has an [MCP](https://modelcontextprotocol.io) server, so AI agents (Claude, Codex, Cursor, VS Code) can run cloud tests and drive cloud devices. You don't run it yourself. You add it to your MCP client's config, and the client starts it. There are three ways to connect: @@ -54,10 +54,10 @@ There are three ways to connect: ```sh-session $ dcd login -$ dcd mcp install cursor # or claude-code, claude-desktop, vscode +$ dcd mcp install cursor # or claude-code, claude-desktop, codex, vscode ``` -Leave out the client name to pick from a list. Add `--read-only` for a server that only offers tools that change nothing, or `--print` to see what would be added without changing anything. For Claude Code and VS Code it runs `claude mcp add` and `code --add-mcp`. For Claude Desktop and Cursor it adds an entry to their JSON config file and keeps everything else in it. Restart the app afterwards. +Leave out the client name to pick from a list. Add `--read-only` for a server that only offers tools that change nothing, or `--print` to see what would be added without changing anything. For Claude Code, Codex and VS Code it runs `claude mcp add`, `codex mcp add` and `code --add-mcp`. For Claude Desktop and Cursor it adds an entry to their JSON config file and keeps everything else in it. Restart the app afterwards. **Setting it up by hand.** Start dcd by its **full path**. Desktop apps such as Claude Desktop and Cursor are usually opened from the Dock or Start menu, so they don't see the PATH your shell sets up, and a bare `dcd` gives "command not found". The installer prints the path at the end; it's `~/.dcd/bin/dcd` by default, written out in full because config files don't expand `~`. @@ -88,10 +88,19 @@ VS Code (`.vscode/mcp.json`, or the user `mcp.json`) uses `servers` and a `type` } ``` -Claude Code, run from a terminal, does see your PATH: +Codex (`~/.codex/config.toml`, shared by the Codex CLI, IDE extension and desktop app): + +```toml +[mcp_servers.devicecloud] +command = "/Users/you/.dcd/bin/dcd" +args = ["mcp"] +``` + +Claude Code and the Codex CLI, run from a terminal, do see your PATH: ```sh-session $ claude mcp add --scope user devicecloud -- dcd mcp +$ 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. @@ -102,12 +111,47 @@ It signs in the same way as the CLI: run `dcd login` once, or set `DEVICE_CLOUD_ ### Hosted -Point an HTTP-capable client at the URL. It signs you in through the browser (OAuth), and you can disconnect it later under Settings → Connected apps. +Point a client that speaks Streamable HTTP at `https://api.devicecloud.dev/mcp`. It signs you in through the browser (OAuth) the first time it connects, and you can disconnect it later under Settings → Account → Connected apps. + +Claude Code (then run `/mcp` in Claude Code and choose `devicecloud` to sign in): ```sh-session -$ claude mcp add --transport http devicecloud https://api.devicecloud.dev/mcp +$ claude mcp add --scope user --transport http devicecloud https://api.devicecloud.dev/mcp +``` + +Cursor (`~/.cursor/mcp.json`): + +```jsonc +{ + "mcpServers": { + "devicecloud": { "url": "https://api.devicecloud.dev/mcp" } + } +} ``` +VS Code (`.vscode/mcp.json`, or the user `mcp.json`), or `code --add-mcp '{"name":"devicecloud","type":"http","url":"https://api.devicecloud.dev/mcp"}'`: + +```jsonc +{ + "servers": { + "devicecloud": { "type": "http", "url": "https://api.devicecloud.dev/mcp" } + } +} +``` + +Codex: + +```sh-session +$ codex mcp add devicecloud --url https://api.devicecloud.dev/mcp +$ codex mcp login devicecloud +``` + +Claude Desktop: open Settings → Connectors, choose **Add custom connector**, name it DeviceCloud and paste the URL. Its config file only takes local servers. + +**Read-only.** `https://api.devicecloud.dev/mcp?read_only=true` serves only the device tools that change nothing (`list_devices`, `get_device_status`, `inspect_screen`, `take_screenshot`, `get_command_status`, `get_logs`, `get_human_status`, `cheat_sheet`). Quote it on a command line, since `?` is a wildcard in zsh: `claude mcp add --scope user --transport http devicecloud 'https://api.devicecloud.dev/mcp?read_only=true'`. Like `--read-only` locally, it keeps an agent from changing anything by mistake; it isn't a permission. + +**API key instead of signing in.** For an agent that can't open a browser, such as one in CI, send an API key from the console (Settings → API Keys) as `Authorization: Bearer `, for example with `claude mcp add ... --header "Authorization: Bearer "`. + ### `dcd-mcp` The older server, with the `dcd_*` tools only. Add it to your MCP client config: diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts index be7cb71..5680254 100644 --- a/src/commands/mcp.ts +++ b/src/commands/mcp.ts @@ -18,6 +18,7 @@ import { CLIENT_LABELS, claudeCodeAddArgs, clientConfigPath, + codexAddArgs, MCP_CLIENTS, type McpClient, mcpServersSnippet, @@ -35,6 +36,7 @@ import { type Field, ui } from '../utils/ui.js'; const RELOAD_HINT: Record = { 'claude-code': 'Start a new Claude Code session to load it.', 'claude-desktop': 'Restart Claude Desktop to load it.', + codex: 'Start a new Codex session to load it.', cursor: 'Restart Cursor, or reload its MCP servers, to load it.', vscode: 'VS Code asks you to trust the server the first time it starts.', }; @@ -84,6 +86,18 @@ function install(client: McpClient, launch: ServerLaunch): InstallResult { return { target: shellLine('claude', add), replaced: removed.ok }; } + if (client === 'codex') { + const add = codexAddArgs(launch); + const removed = runTool('codex', ['mcp', 'remove', SERVER_NAME]); + if (!removed) { + throw new CliError(`The codex command isn't on PATH. Run this where it is:\n ${shellLine('codex', add)}`); + } + + const added = runTool('codex', add)!; + if (!added.ok) throw new CliError(`codex mcp add failed: ${added.output}`); + return { target: shellLine('codex', add), replaced: removed.ok }; + } + if (client === 'vscode') { const add = vscodeAddArgs(launch); const added = runTool('code', add); @@ -110,6 +124,7 @@ function install(client: McpClient, launch: ServerLaunch): InstallResult { /** What `--print` shows: the command to run, or the file and the entry for it. */ function preview(client: McpClient, launch: ServerLaunch): { target: string; text: string } { if (client === 'claude-code') return { target: 'command', text: shellLine('claude', claudeCodeAddArgs(launch)) }; + if (client === 'codex') return { target: 'command', text: shellLine('codex', codexAddArgs(launch)) }; if (client === 'vscode') return { target: 'command', text: shellLine('code', vscodeAddArgs(launch)) }; return { target: clientConfigPath(client) ?? 'your MCP config file', @@ -120,7 +135,7 @@ function preview(client: McpClient, launch: ServerLaunch): { target: string; tex const installSub = defineCommand({ meta: { name: 'install', - description: 'Add the DeviceCloud MCP server to Claude Code, Claude Desktop, Cursor or VS Code', + description: 'Add the DeviceCloud MCP server to Claude Code, Claude Desktop, Codex, Cursor or VS Code', }, args: { client: { @@ -177,7 +192,7 @@ const installSub = defineCommand({ ui.success(`${result.replaced ? 'Updated' : 'Added'} DeviceCloud in ${CLIENT_LABELS[client]}`), ); const rows: Field[] = [ - [client === 'claude-code' || client === 'vscode' ? 'ran' : 'wrote', result.target], + [client === 'claude-code' || client === 'codex' || client === 'vscode' ? 'ran' : 'wrote', result.target], ['starts', colors.highlight(shellLine(launch.command, launch.args))], ]; logger.log(ui.branch(ui.fields(rows))); @@ -199,7 +214,7 @@ const installSub = defineCommand({ export const mcpCommand = defineCommand({ meta: { name: 'mcp', - description: 'MCP server for AI agents, started by your MCP client (Claude, Cursor, VS Code)', + description: 'MCP server for AI agents, started by your MCP client (Claude, Codex, Cursor, VS Code)', }, args: { 'read-only': { diff --git a/src/mcp/bridge.ts b/src/mcp/bridge.ts index 91ee0f5..be2d395 100644 --- a/src/mcp/bridge.ts +++ b/src/mcp/bridge.ts @@ -221,8 +221,12 @@ class RemoteDevices { private async open(): Promise { const { apiUrl } = await getContext(); const client = new Client({ name: 'dcd-mcp-bridge', version: getCliVersion() }); + // In read-only mode, ask the hosted server for its read-only tools too, so + // it refuses the rest as well. The filter here stays: an API without the + // flag ignores it, and a refused call still gets the read-only message. + const url = new URL(`${apiUrl}/mcp${isReadOnly() ? '?read_only=true' : ''}`); await client.connect( - new StreamableHTTPClientTransport(new URL(`${apiUrl}/mcp`), { + new StreamableHTTPClientTransport(url, { fetch: async (url, init) => { const { auth } = await getContext(); const headers = new Headers(init?.headers); diff --git a/src/utils/mcp-install.ts b/src/utils/mcp-install.ts index 5d5faf0..a33d006 100644 --- a/src/utils/mcp-install.ts +++ b/src/utils/mcp-install.ts @@ -15,12 +15,13 @@ import { CliError, type InstallMethod } from './cli.js'; /** The server's name in every client's config. */ export const SERVER_NAME = 'devicecloud'; -export const MCP_CLIENTS = ['claude-code', 'claude-desktop', 'cursor', 'vscode'] as const; +export const MCP_CLIENTS = ['claude-code', 'claude-desktop', 'codex', 'cursor', 'vscode'] as const; export type McpClient = (typeof MCP_CLIENTS)[number]; export const CLIENT_LABELS: Record = { 'claude-code': 'Claude Code', 'claude-desktop': 'Claude Desktop', + codex: 'Codex', cursor: 'Cursor', vscode: 'VS Code', }; @@ -92,7 +93,8 @@ export function stableNodePath( /** * The JSON config file a client reads, or undefined when it is configured - * through its own CLI (Claude Code, VS Code) or has no known location here. + * through its own CLI (Claude Code, Codex, VS Code) or has no known location + * here. */ export function clientConfigPath( client: McpClient, @@ -160,6 +162,15 @@ export function claudeCodeAddArgs(launch: ServerLaunch): string[] { return ['mcp', 'add', '--scope', 'user', SERVER_NAME, '--', launch.command, ...launch.args]; } +/** + * `codex mcp add` arguments. Codex keeps MCP servers in ~/.codex/config.toml, + * which its CLI, IDE extension and desktop app share, so its own CLI writes + * the entry rather than this one parsing TOML. + */ +export function codexAddArgs(launch: ServerLaunch): string[] { + return ['mcp', 'add', SERVER_NAME, '--', launch.command, ...launch.args]; +} + /** `code --add-mcp` arguments, which add the server to the VS Code user profile. */ export function vscodeAddArgs(launch: ServerLaunch): string[] { return ['--add-mcp', JSON.stringify({ name: SERVER_NAME, ...launch })]; diff --git a/test/unit/mcp-bridge.test.ts b/test/unit/mcp-bridge.test.ts index ead46a9..14c5b69 100644 --- a/test/unit/mcp-bridge.test.ts +++ b/test/unit/mcp-bridge.test.ts @@ -29,11 +29,12 @@ function startHosted(): Promise<{ failStart: boolean; http: HttpServer; inits: number; + paths: string[]; sessions: Record[]; url: string; }> { const calls: { args: unknown; auth?: string; name: string }[] = []; - const hosted = { calls, failStart: false, inits: 0, sessions: [] as Record[] }; + const hosted = { calls, failStart: false, inits: 0, paths: [] as string[], sessions: [] as Record[] }; const http = createHttpServer(async (req, res) => { // The open sessions, as GET /device/sessions answers. if (req.method === 'GET' && req.url === '/device/sessions') { @@ -47,6 +48,7 @@ function startHosted(): Promise<{ return; } + hosted.paths.push(req.url ?? ''); const chunks: Buffer[] = []; for await (const c of req) chunks.push(c as Buffer); const body = JSON.parse(Buffer.concat(chunks).toString() || '{}'); @@ -155,6 +157,7 @@ describe('dcd mcp bridge', () => { const result = await client.callTool({ name: 'inspect_screen', arguments: {} }); expect(result.isError).to.not.equal(true); expect(hosted.calls).to.deep.equal([{ name: 'inspect_screen', args: {}, auth: 'test-key' }]); + expect(new Set(hosted.paths)).to.deep.equal(new Set(['/mcp'])); await client.close(); }); @@ -247,6 +250,9 @@ describe('dcd mcp bridge', () => { expect(hosted.calls).to.deep.equal([]); await client.callTool({ name: 'inspect_screen', arguments: {} }); expect(hosted.calls.map((c) => c.name)).to.deep.equal(['inspect_screen']); + // The hosted server is asked for its read-only tools too. + expect(hosted.paths).to.not.be.empty; + expect(new Set(hosted.paths)).to.deep.equal(new Set(['/mcp?read_only=true'])); await client.close(); }); diff --git a/test/unit/mcp-install.test.ts b/test/unit/mcp-install.test.ts index 05c133b..b945943 100644 --- a/test/unit/mcp-install.test.ts +++ b/test/unit/mcp-install.test.ts @@ -7,6 +7,7 @@ import { CliError } from '../../src/utils/cli.js'; import { claudeCodeAddArgs, clientConfigPath, + codexAddArgs, serverLaunch, shellLine, stableNodePath, @@ -67,6 +68,7 @@ describe('dcd mcp install', () => { ); expect(clientConfigPath('claude-desktop', 'linux', '/h')).to.equal(undefined); expect(clientConfigPath('claude-code', 'darwin', '/h')).to.equal(undefined); + expect(clientConfigPath('codex', 'darwin', '/h')).to.equal(undefined); }); describe('writeClientConfig', () => { @@ -105,5 +107,8 @@ describe('dcd mcp install', () => { expect(shellLine('claude', claudeCodeAddArgs(launch))).to.equal( "claude mcp add --scope user devicecloud -- '/Users/a b/.dcd/bin/dcd' mcp --read-only", ); + expect(shellLine('codex', codexAddArgs(launch))).to.equal( + "codex mcp add devicecloud -- '/Users/a b/.dcd/bin/dcd' mcp --read-only", + ); }); }); From 02d99b9274b7b8b4659bda94c2b94a7f14998fbd Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:21:56 +0000 Subject: [PATCH 06/20] ci: lint PR titles on pull_request instead of pull_request_target (#308) GitHub blocks pull_request_target by default in public repositories from 2026-12-02. The PR title check only reads the event payload, so it runs on pull_request, which also fires for fork PRs with a read-only token. The CLA workflow has to write to fork PRs, so it stays on pull_request_target. A repository Actions policy allows that trigger for cla.yml only. Its header now says so. --- .github/workflows/cla.yml | 8 ++++++++ .github/workflows/pr-title-lint.yml | 10 +++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/.github/workflows/cla.yml b/.github/workflows/cla.yml index cf0be43..4a19664 100644 --- a/.github/workflows/cla.yml +++ b/.github/workflows/cla.yml @@ -34,6 +34,14 @@ name: CLA Assistant # # Until the App secrets exist the CLA step self-skips, so the check is green # (not failing) on every PR and auto-activates once they're set. +# +# TRIGGER: this stays on pull_request_target because it must write to fork PRs +# (comments, statuses, the signatures branch). GitHub blocks pull_request_target +# by default in public repositories from 2026-12-02. A repository Actions policy +# (Settings > Actions > Policies, "Allow pull_request_target for CLA") allows +# issue_comment and pull_request_target for this file only. If you rename this +# file or add a trigger, update that policy too, or runs fail at startup with +# no `cla` check. Never check out or run PR code in this workflow. on: issue_comment: types: [created] diff --git a/.github/workflows/pr-title-lint.yml b/.github/workflows/pr-title-lint.yml index d102449..82f3e3f 100644 --- a/.github/workflows/pr-title-lint.yml +++ b/.github/workflows/pr-title-lint.yml @@ -5,10 +5,14 @@ name: PR Title # parses to compute version bumps and the changelog, so the allowed types below # must stay in sync with SECTIONS and HIDDEN there. # -# Uses pull_request_target so it also runs (and reports a required status check) -# on PRs from forks. It only reads the title — no untrusted code is checked out. +# Runs on pull_request, which also fires for PRs from forks. Fork runs get a +# read-only token and no secrets, and that is all a title check needs: it reads +# the title from the event payload and checks out no code. It used to run on +# pull_request_target, which GitHub blocks by default in public repositories +# from 2026-12-02, so don't switch back. A first-time contributor's fork PR waits +# for a maintainer to approve the run before this check reports. on: - pull_request_target: + pull_request: types: - opened - edited From 9a54e3a21b3175fd67158dc68be071099b7c8cb7 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:35:09 +0000 Subject: [PATCH 07/20] fix(mcp): say why a tool is missing in read-only mode (#307) With --read-only, dcd mcp asks the hosted server for its read-only tools, and the server then doesn't list the others at all. A call to one of them, such as run, came back as a bare "Unknown tool: run". In read-only mode an unknown tool now says the server offers only the tools that change nothing. The test stand-in for the hosted server now honours ?read_only=true as the API does, which is how this slipped through. A second test plays an API that lists every tool, so the local refusal stays covered. --- src/mcp/bridge.ts | 17 +++++-- test/unit/mcp-bridge.test.ts | 98 ++++++++++++++++++++++++------------ 2 files changed, 78 insertions(+), 37 deletions(-) diff --git a/src/mcp/bridge.ts b/src/mcp/bridge.ts index be2d395..bc446b7 100644 --- a/src/mcp/bridge.ts +++ b/src/mcp/bridge.ts @@ -222,8 +222,8 @@ class RemoteDevices { const { apiUrl } = await getContext(); const client = new Client({ name: 'dcd-mcp-bridge', version: getCliVersion() }); // In read-only mode, ask the hosted server for its read-only tools too, so - // it refuses the rest as well. The filter here stays: an API without the - // flag ignores it, and a refused call still gets the read-only message. + // it refuses the rest as well. The filter here stays for an API without + // the flag, which ignores it and lists every tool. const url = new URL(`${apiUrl}/mcp${isReadOnly() ? '?read_only=true' : ''}`); await client.connect( new StreamableHTTPClientTransport(url, { @@ -311,8 +311,17 @@ export async function createBridgeServer( return runTool(`device ${name}`, async () => { await remote.list(); - if (!remote.has(name)) return errorResult(`Unknown tool: ${name}`); - // The list hides these in read-only mode; refuse them if called anyway. + 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. + return errorResult( + readOnly + ? `Unknown tool: ${name}. In read-only mode this server offers only the tools that change nothing.` + : `Unknown tool: ${name}`, + ); + } + + // An API without the read-only flag lists every tool; refuse these here. if (readOnly && !remote.isReadOnly(name)) { return errorResult(`${name} is not available in read-only mode.`); } diff --git a/test/unit/mcp-bridge.test.ts b/test/unit/mcp-bridge.test.ts index 14c5b69..c15683e 100644 --- a/test/unit/mcp-bridge.test.ts +++ b/test/unit/mcp-bridge.test.ts @@ -28,13 +28,21 @@ function startHosted(): Promise<{ calls: { args: unknown; auth?: string; name: string }[]; failStart: boolean; http: HttpServer; + ignoreReadOnly: boolean; inits: number; paths: string[]; sessions: Record[]; url: string; }> { const calls: { args: unknown; auth?: string; name: string }[] = []; - const hosted = { calls, failStart: false, inits: 0, paths: [] as string[], sessions: [] as Record[] }; + const hosted = { + calls, + failStart: false, + ignoreReadOnly: false, + inits: 0, + paths: [] as string[], + sessions: [] as Record[], + }; const http = createHttpServer(async (req, res) => { // The open sessions, as GET /device/sessions answers. if (req.method === 'GET' && req.url === '/device/sessions') { @@ -64,37 +72,46 @@ function startHosted(): Promise<{ calls.push({ name, args, auth }); return { content: [{ type: 'text' as const, text: JSON.stringify({ ok: name }) }] }; }; - server.registerTool( - 'install_app', - { - description: 'Install an app.', - inputSchema: { session_id: z.string().optional(), app_binary_id: z.string().optional() }, - }, - record('install_app'), - ); - server.registerTool( - 'run', - { description: 'Run Maestro.', inputSchema: { yaml: z.string().optional(), flow_upload_id: z.string().optional() } }, - record('run'), - ); - server.registerTool( - 'get_logs', - { description: 'Slow.', inputSchema: { ms: z.number() }, annotations: { readOnlyHint: true } }, - async ({ ms }) => { - await new Promise((r) => setTimeout(r, ms)); - return { content: [{ type: 'text' as const, text: 'late' }] }; - }, - ); - server.registerTool( - 'start_device', - { description: 'Start a device.', inputSchema: { platform: z.string() } }, - record('start_device'), - ); - server.registerTool( - 'inspect_screen', - { description: 'Inspect.', inputSchema: {}, annotations: { readOnlyHint: true } }, - record('inspect_screen'), - ); + const registered = [ + server.registerTool( + 'install_app', + { + description: 'Install an app.', + inputSchema: { session_id: z.string().optional(), app_binary_id: z.string().optional() }, + }, + record('install_app'), + ), + server.registerTool( + 'run', + { description: 'Run Maestro.', inputSchema: { yaml: z.string().optional(), flow_upload_id: z.string().optional() } }, + record('run'), + ), + server.registerTool( + 'get_logs', + { description: 'Slow.', inputSchema: { ms: z.number() }, annotations: { readOnlyHint: true } }, + async ({ ms }) => { + await new Promise((r) => setTimeout(r, ms)); + return { content: [{ type: 'text' as const, text: 'late' }] }; + }, + ), + server.registerTool( + 'start_device', + { description: 'Start a device.', inputSchema: { platform: z.string() } }, + record('start_device'), + ), + server.registerTool( + 'inspect_screen', + { description: 'Inspect.', inputSchema: {}, annotations: { readOnlyHint: true } }, + record('inspect_screen'), + ), + ]; + // As the API does: /mcp?read_only=true serves only the tools that change + // nothing. ignoreReadOnly plays an older API, which lists every tool. + const readOnlyAsked = new URL(req.url ?? '/', 'http://hosted').searchParams.get('read_only') === 'true'; + if (readOnlyAsked && !hosted.ignoreReadOnly) { + for (const tool of registered) if (tool.annotations?.readOnlyHint !== true) tool.remove(); + } + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined }); await server.connect(transport); await transport.handleRequest(req, res, body); @@ -246,7 +263,7 @@ describe('dcd mcp bridge', () => { // Hidden is not enough: a call made anyway is refused, never forwarded. const refused = await client.callTool({ name: 'run', arguments: { yaml: 'x' } }); expect(refused.isError).to.equal(true); - expect(JSON.stringify(refused.content)).to.include('read-only mode'); + expect(JSON.stringify(refused.content)).to.include('Unknown tool: run. In read-only mode'); expect(hosted.calls).to.deep.equal([]); await client.callTool({ name: 'inspect_screen', arguments: {} }); expect(hosted.calls.map((c) => c.name)).to.deep.equal(['inspect_screen']); @@ -256,6 +273,21 @@ describe('dcd mcp bridge', () => { await client.close(); }); + it('read-only mode still refuses on an API that lists every tool', async () => { + hosted.ignoreReadOnly = true; + process.env.DCD_MCP_READONLY = '1'; + const client = await connect(); + const names = (await client.listTools()).tools.map((t) => t.name); + expect(names).to.include('inspect_screen'); + expect(names).to.not.include.members(['install_app', 'run', 'start_device']); + + const refused = await client.callTool({ name: 'run', arguments: { yaml: 'x' } }); + expect(refused.isError).to.equal(true); + expect(JSON.stringify(refused.content)).to.include('run is not available in read-only mode'); + expect(hosted.calls).to.deep.equal([]); + await client.close(); + }); + it('still serves the dcd_* tools when the hosted endpoint is unreachable', async () => { process.env.DCD_API_URL = 'http://127.0.0.1:9'; clearContextCache(); From 882e877f7aca8eee7945cc29f7f40dfef5170672 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:30:13 +0000 Subject: [PATCH 08/20] docs(mcp): dcd mcp for cloud tests and headless use (#309) The README's MCP section is now about dcd mcp: setting it up with dcd mcp install, running it headless with DEVICE_CLOUD_API_KEY (for example in CI), setting it up by hand, its dcd_* tools and read-only mode, and the older dcd-mcp. The server's instructions are sent before it knows which hosted tools an account has, so they now name only the dcd_* tools; other tools explain themselves in their own descriptions. --- README.md | 103 ++++++++++------------------------- src/mcp/bridge.ts | 10 +++- test/unit/mcp-bridge.test.ts | 13 +++++ 3 files changed, 50 insertions(+), 76 deletions(-) diff --git a/README.md b/README.md index 9df9430..646a023 100644 --- a/README.md +++ b/README.md @@ -36,21 +36,11 @@ See full documentation: [Docs](https://docs.devicecloud.dev) ## MCP server -devicecloud.dev has an [MCP](https://modelcontextprotocol.io) server, so AI agents (Claude, Codex, Cursor, VS Code) can run cloud tests and drive cloud devices. You don't run it yourself. You add it to your MCP client's config, and the client starts it. +`dcd mcp` is an [MCP](https://modelcontextprotocol.io) server, so AI agents (Claude, Codex, Cursor, VS Code) can run cloud tests and read their results. You don't run it yourself. You add it to your MCP client's config, and the client starts it. It works the same on your machine and headless, such as in CI. -There are three ways to connect: +### Set it up with `dcd mcp install` -| | Install | Tools | Use it when | -| --- | --- | --- | --- | -| **`dcd mcp`** (recommended) | the CLI | device tools + `dcd_*` cloud-test tools | you want everything, including installing a local build or running local flow files | -| **Hosted** `https://api.devicecloud.dev/mcp` | nothing | device tools | the agent only drives devices, with apps and flows that are already uploaded or at a URL | -| **`dcd-mcp`** | the CLI | `dcd_*` cloud-test tools | you only run cloud tests (the older server; `dcd mcp` covers it) | - -### `dcd mcp` - -`dcd mcp` connects to the hosted server and passes its device tools through. It adds what only a local process can do: `install_app` takes `app_path` (a build on your machine, uploaded first) and `run` takes `path` (a flow file, or a directory uploaded as a bundle). It also serves the `dcd_*` tools below. - -**Set it up with `dcd mcp install`.** Install the CLI (see the top of this page), sign in, then add the server to your AI tool: +Install the CLI (see the top of this page), sign in, then add the server to your AI tool: ```sh-session $ dcd login @@ -59,7 +49,19 @@ $ dcd mcp install cursor # or claude-code, claude-desktop, codex, vscode Leave out the client name to pick from a list. Add `--read-only` for a server that only offers tools that change nothing, or `--print` to see what would be added without changing anything. For Claude Code, Codex and VS Code it runs `claude mcp add`, `codex mcp add` and `code --add-mcp`. For Claude Desktop and Cursor it adds an entry to their JSON config file and keeps everything else in it. Restart the app afterwards. -**Setting it up by hand.** Start dcd by its **full path**. Desktop apps such as Claude Desktop and Cursor are usually opened from the Dock or Start menu, so they don't see the PATH your shell sets up, and a bare `dcd` gives "command not found". The installer prints the path at the end; it's `~/.dcd/bin/dcd` by default, written out in full because config files don't expand `~`. +### Headless, with an API key + +For an agent that runs without you, such as in CI or a script, sign in with an API key instead of `dcd login`. Create one in the console under Settings → API Keys, and give it to the server as `DEVICE_CLOUD_API_KEY` in its environment. For example, for Claude Code in CI: + +```sh-session +$ claude mcp add --scope user devicecloud -e DEVICE_CLOUD_API_KEY="$DEVICE_CLOUD_API_KEY" -- dcd mcp +``` + +In a JSON config, put it in the server's `env`: `"env": { "DEVICE_CLOUD_API_KEY": "" }`. Store the key as a secret in your CI provider, never in the repository. + +### Setting it up by hand + +Start dcd by its **full path**. Desktop apps such as Claude Desktop and Cursor are usually opened from the Dock or Start menu, so they don't see the PATH your shell sets up, and a bare `dcd` gives "command not found". The installer prints the path at the end; it's `~/.dcd/bin/dcd` by default, written out in full because config files don't expand `~`. Claude Desktop (`claude_desktop_config.json`) and Cursor (`~/.cursor/mcp.json`): @@ -105,56 +107,25 @@ $ 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: run `dcd login` once, or set `DEVICE_CLOUD_API_KEY` in `env`. Add `--read-only` to the args (or set `DCD_MCP_READONLY=1`) to serve only the tools that change nothing. If the hosted server can't be reached, it serves the `dcd_*` tools only and says why on stderr. - -**Device tools:** `list_devices`, `start_device`, `get_device_status`, `install_app`, `launch_app`, `inspect_screen`, `take_screenshot`, `run`, `get_command_status`, `get_logs`, `request_human`, `get_human_status`, `stop_device`, and `cheat_sheet` (Maestro syntax for the agent). - -### Hosted +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`. -Point a client that speaks Streamable HTTP at `https://api.devicecloud.dev/mcp`. It signs you in through the browser (OAuth) the first time it connects, and you can disconnect it later under Settings → Account → Connected apps. +### Tools -Claude Code (then run `/mcp` in Claude Code and choose `devicecloud` to sign in): - -```sh-session -$ claude mcp add --scope user --transport http devicecloud https://api.devicecloud.dev/mcp -``` - -Cursor (`~/.cursor/mcp.json`): - -```jsonc -{ - "mcpServers": { - "devicecloud": { "url": "https://api.devicecloud.dev/mcp" } - } -} -``` - -VS Code (`.vscode/mcp.json`, or the user `mcp.json`), or `code --add-mcp '{"name":"devicecloud","type":"http","url":"https://api.devicecloud.dev/mcp"}'`: - -```jsonc -{ - "servers": { - "devicecloud": { "type": "http", "url": "https://api.devicecloud.dev/mcp" } - } -} -``` - -Codex: - -```sh-session -$ codex mcp add devicecloud --url https://api.devicecloud.dev/mcp -$ codex mcp login devicecloud -``` - -Claude Desktop: open Settings → Connectors, choose **Add custom connector**, name it DeviceCloud and paste the URL. Its config file only takes local servers. +| Tool | What it does | +| --- | --- | +| `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_run_cloud_test` | Submit a flow to run on the cloud (**billable**) | -**Read-only.** `https://api.devicecloud.dev/mcp?read_only=true` serves only the device tools that change nothing (`list_devices`, `get_device_status`, `inspect_screen`, `take_screenshot`, `get_command_status`, `get_logs`, `get_human_status`, `cheat_sheet`). Quote it on a command line, since `?` is a wildcard in zsh: `claude mcp add --scope user --transport http devicecloud 'https://api.devicecloud.dev/mcp?read_only=true'`. Like `--read-only` locally, it keeps an agent from changing anything by mistake; it isn't a permission. +By default `dcd_run_cloud_test` is async: it returns an `uploadId` immediately, which you poll with `dcd_get_status`. Pass `wait: true` (bounded by `waitTimeoutSeconds`) to block until completion, or `dryRun: true` to preview the flows without submitting. -**API key instead of signing in.** For an agent that can't open a browser, such as one in CI, send an API key from the console (Settings → API Keys) as `Authorization: Bearer `, for example with `claude mcp add ... --header "Authorization: Bearer "`. +**Read-only mode.** `dcd_run_cloud_test` consumes test minutes, so it is annotated as non-read-only/destructive (clients can prompt before calling it). To hide it entirely, which is recommended for autonomous or untrusted agents, add `--read-only` after `mcp` in the args (or pass it to `dcd mcp install`), or set `DCD_MCP_READONLY=1` in `env`. ### `dcd-mcp` -The older server, with the `dcd_*` tools only. Add it to your MCP client config: +The npm package also ships `dcd-mcp`, an older server with the same `dcd_*` tools. `dcd mcp` covers it, so you only need it for a setup that already uses it: ```jsonc { @@ -168,23 +139,7 @@ The older server, with the `dcd_*` tools only. Add it to your MCP client config: } ``` -`--package` matters: the package's default bin is `dcd`, so `npx @devicecloud.dev/dcd dcd-mcp` would run `dcd dcd-mcp` (an unknown command) instead of the server. - -Auth is inherited from the CLI: set `DEVICE_CLOUD_API_KEY` as above, or run `dcd login` once and the server picks up the stored session. Point it at a non-prod environment with `DCD_API_URL`. - -**`dcd_*` tools** (served by both `dcd mcp` and `dcd-mcp`) - -| Tool | What it does | -| --- | --- | -| `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_run_cloud_test` | Submit a flow to run on the cloud (**billable**) | - -**Read-only mode.** `dcd_run_cloud_test` consumes test minutes, so it is annotated as non-read-only/destructive (clients can prompt before calling it). To hide it entirely — recommended for autonomous or untrusted agents — pass `--read-only` at the end of `args` (`["-y", "--package=@devicecloud.dev/dcd", "dcd-mcp", "--read-only"]`), or set `DCD_MCP_READONLY=1` in `env`. - -By default `dcd_run_cloud_test` is async: it returns an `uploadId` immediately, which you poll with `dcd_get_status`. Pass `wait: true` (bounded by `waitTimeoutSeconds`) to block until completion, or `dryRun: true` to preview the flows without submitting. +`--package` matters: the package's default bin is `dcd`, so `npx @devicecloud.dev/dcd dcd-mcp` would run `dcd dcd-mcp` (an unknown command) instead of the server. It signs in like `dcd mcp`, and takes `--read-only` and `DCD_MCP_READONLY=1` the same way. ## Development diff --git a/src/mcp/bridge.ts b/src/mcp/bridge.ts index bc446b7..5614c77 100644 --- a/src/mcp/bridge.ts +++ b/src/mcp/bridge.ts @@ -40,8 +40,14 @@ import { getContext, isReadOnly, logStderr } from './context.js'; import { errorResult, runTool } from './helpers.js'; import { createServer } from './server.js'; +/* + * Sent at initialize, before this server knows which hosted tools the + * account has: the hosted server only serves its tools to organizations that + * have them. So these name only the dcd_* tools, and the hosted tools explain + * themselves in their own descriptions. + */ const INSTRUCTIONS = - 'DeviceCloud tools. dcd_* tools run Maestro test suites in the cloud. The device tools lease a cloud iOS or Android device for you to drive: start_device, then inspect_screen / take_screenshot, launch_app, run, and stop_device when done. Call cheat_sheet first for Maestro syntax. Local files: install_app takes app_path and run takes path (a flow file or a directory), which this server uploads for you.'; + '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. 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.'; /** * How long one forwarded call may take. Longer than dcd_run_cloud_test's @@ -51,7 +57,7 @@ const INSTRUCTIONS = export const CALL_TIMEOUT_MS = 2 * 60 * 60 * 1000; const READ_ONLY_INSTRUCTIONS = - 'DeviceCloud tools, read-only: nothing here starts a device, runs a test or changes anything. dcd_* tools read cloud test runs and their results. The device tools read open device sessions: list_devices, get_device_status, inspect_screen, take_screenshot, get_logs.'; + 'DeviceCloud tools, read-only: nothing here runs a test or changes anything. dcd_* tools read cloud test runs and their results. Any other tools describe their own use.'; /** The inputs this bridge adds to hosted tools, and what they say. */ const LOCAL_INPUTS: Record }> = { diff --git a/test/unit/mcp-bridge.test.ts b/test/unit/mcp-bridge.test.ts index c15683e..e946c73 100644 --- a/test/unit/mcp-bridge.test.ts +++ b/test/unit/mcp-bridge.test.ts @@ -273,6 +273,19 @@ describe('dcd mcp bridge', () => { await client.close(); }); + it("names only the dcd_* tools in its instructions, since the hosted ones depend on the account", async () => { + for (const readOnly of [false, true]) { + if (readOnly) process.env.DCD_MCP_READONLY = '1'; + const client = await connect(); + const instructions = client.getInstructions() ?? ''; + expect(instructions).to.include('dcd_'); + for (const hosted of ['start_device', 'inspect_screen', 'install_app', 'cheat_sheet', 'device session']) { + expect(instructions).to.not.include(hosted); + } + await client.close(); + } + }); + it('read-only mode still refuses on an API that lists every tool', async () => { hosted.ignoreReadOnly = true; process.env.DCD_MCP_READONLY = '1'; From 18efa4f3309d8a7d2719720c10e3195bc708ad2d Mon Sep 17 00:00:00 2001 From: Tom Riglar Date: Tue, 10 Nov 2026 15:13:15 +0000 Subject: [PATCH 09/20] fix(mcp): find code and claude .cmd shims on Windows (#286) * fix(mcp): find code and claude .cmd shims on Windows On Windows, VS Code's command line is code.cmd and npm installs Claude Code as claude.cmd. Node's spawn without a shell skips .cmd files on PATH and refuses to start them, so `dcd mcp install vscode` and `dcd mcp install claude-code` said the command wasn't on PATH. Find the command on PATH with PATHEXT ourselves. Run an .exe directly, and a .cmd or .bat through cmd.exe with each argument escaped for both of cmd's parse passes, so the --add-mcp JSON arrives unchanged. Fixes #281 Co-Authored-By: Claude Opus 5.5 * fix(mcp): refuse a line break in an argument passed through cmd.exe A line break ends cmd's command line, so caret escaping can't protect an argument that holds one. No argument we pass can contain one today, but refuse it rather than rely on that. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: finalerock44 <77282157+finalerock44@users.noreply.github.com> --- src/commands/mcp.ts | 8 ++- src/utils/tool-spawn.ts | 86 +++++++++++++++++++++++ test/unit/tool-spawn.test.ts | 128 +++++++++++++++++++++++++++++++++++ 3 files changed, 221 insertions(+), 1 deletion(-) create mode 100644 src/utils/tool-spawn.ts create mode 100644 test/unit/tool-spawn.test.ts diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts index 5680254..f744a76 100644 --- a/src/commands/mcp.ts +++ b/src/commands/mcp.ts @@ -31,6 +31,7 @@ import { writeClientConfig, } from '../utils/mcp-install.js'; import { colors } from '../utils/styling.js'; +import { toolSpawn } from '../utils/tool-spawn.js'; import { type Field, ui } from '../utils/ui.js'; const RELOAD_HINT: Record = { @@ -43,7 +44,12 @@ const RELOAD_HINT: Record = { /** Run another tool's CLI without a shell. Undefined when it isn't installed. */ function runTool(command: string, args: string[]): { ok: boolean; output: string } | undefined { - const result = spawnSync(command, args, { encoding: 'utf8' }); + const spawn = toolSpawn(command, args); + if (!spawn) return undefined; + const result = spawnSync(spawn.command, spawn.args, { + encoding: 'utf8', + windowsVerbatimArguments: spawn.windowsVerbatimArguments, + }); if ((result.error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT') return undefined; return { ok: result.status === 0, output: `${result.stdout ?? ''}${result.stderr ?? ''}`.trim() }; } diff --git a/src/utils/tool-spawn.ts b/src/utils/tool-spawn.ts new file mode 100644 index 0000000..2beed46 --- /dev/null +++ b/src/utils/tool-spawn.ts @@ -0,0 +1,86 @@ +/** + * How to start another tool's CLI (`code`, `claude`) without a shell. + * + * On Windows these are often batch files (`code.cmd`, and npm's `claude.cmd` + * shim). Node's spawn searches PATH only for .com and .exe, and refuses to + * start a .cmd or .bat at all without a shell (CVE-2024-27980). So we find the + * file ourselves and, for a batch file, run it through cmd.exe with every + * argument escaped for cmd. This doesn't lean on how Node or Bun resolve + * commands, so the npm install and the standalone binary behave the same. + */ +import { existsSync } from 'node:fs'; +import * as path from 'node:path'; + +import { CliError } from './cli.js'; + +export interface ToolSpawn { + command: string; + args: string[]; + /** Pass the arguments to cmd.exe as written, already quoted. */ + windowsVerbatimArguments?: boolean; +} + +/** Characters cmd.exe treats specially, each escaped with a caret. */ +const CMD_META = /([ !"%&()*,;<>?[\]^`|])/g; + +/** + * What to spawn for `command args`, or undefined when Windows has no such + * command on PATH. Elsewhere the command is spawned as given, and a missing + * one shows up as ENOENT. + */ +export function toolSpawn( + command: string, + args: string[], + platform: NodeJS.Platform = process.platform, + env: NodeJS.ProcessEnv = process.env, + exists: (file: string) => boolean = existsSync, +): ToolSpawn | undefined { + if (platform !== 'win32') return { command, args }; + + const file = findOnWindowsPath(command, env, exists); + if (!file) return undefined; + if (!/\.(cmd|bat)$/i.test(file)) return { command: file, args }; + // A line break ends cmd's line, and no escaping can stop that. + if (args.some((arg) => /[\0\n\r]/.test(arg))) { + throw new CliError(`Can't pass a line break to ${path.win32.basename(file)} through cmd.exe.`); + } + + // /s strips the outer quotes and runs the rest as one line. + const line = [file.replace(CMD_META, '^$1'), ...args.map((arg) => cmdArgument(arg))].join(' '); + return { + command: env.ComSpec ?? env.COMSPEC ?? 'cmd.exe', + args: ['/d', '/s', '/c', `"${line}"`], + windowsVerbatimArguments: true, + }; +} + +/** The file Windows would run for `command`: each PATH folder, each PATHEXT extension. */ +export function findOnWindowsPath( + command: string, + env: NodeJS.ProcessEnv, + exists: (file: string) => boolean, +): string | undefined { + const exts = (env.PATHEXT ?? env.Pathext ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean); + const dirs = (env.PATH ?? env.Path ?? '').split(';').filter(Boolean); + const hasExt = exts.some((ext) => command.toLowerCase().endsWith(ext.toLowerCase())); + const names = hasExt ? [command] : exts.map((ext) => command + ext.toLowerCase()); + for (const dir of dirs) { + for (const name of names) { + const candidate = path.win32.join(dir.replaceAll('"', ''), name); + if (exists(candidate)) return candidate; + } + } + + return undefined; +} + +/** + * One argument for a batch file started by cmd.exe. First quote it the way + * the program's own parser expects (CommandLineToArgvW), then caret-escape + * every cmd character twice: once for the `cmd /c` line, and once more + * because the batch file passes it on with %*, which cmd parses again. + */ +export function cmdArgument(arg: string): string { + const quoted = `"${arg.replaceAll(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, '$1$1')}"`; + return quoted.replace(CMD_META, '^$1').replace(CMD_META, '^$1'); +} diff --git a/test/unit/tool-spawn.test.ts b/test/unit/tool-spawn.test.ts new file mode 100644 index 0000000..c31fb59 --- /dev/null +++ b/test/unit/tool-spawn.test.ts @@ -0,0 +1,128 @@ +import { expect } from 'chai'; + +import { vscodeAddArgs } from '../../src/utils/mcp-install.js'; +import { cmdArgument, findOnWindowsPath, toolSpawn } from '../../src/utils/tool-spawn.js'; + +/** One cmd.exe parse pass: carets escape outside quotes, quotes toggle, & | < > outside quotes are operators. */ +function cmdPass(line: string): string { + let out = ''; + let quoted = false; + for (let i = 0; i < line.length; i++) { + const ch = line[i]; + if (!quoted && ch === '^') { + out += line[++i] ?? ''; + continue; + } + + if (!quoted && '&|<>'.includes(ch)) throw new Error(`cmd would treat ${ch} as an operator in: ${line}`); + if (ch === '"') quoted = !quoted; + out += ch; + } + + return out; +} + +/** CommandLineToArgvW's rules for the arguments after the program name. */ +function argv(line: string): string[] { + const args: string[] = []; + let i = 0; + while (i < line.length) { + while (line[i] === ' ' || line[i] === '\t') i++; + if (i >= line.length) break; + let arg = ''; + let quoted = false; + while (i < line.length && (quoted || (line[i] !== ' ' && line[i] !== '\t'))) { + let slashes = 0; + while (line[i] === '\\') { + slashes++; + i++; + } + + if (line[i] === '"') { + arg += '\\'.repeat(Math.floor(slashes / 2)); + if (slashes % 2) arg += '"'; + else quoted = !quoted; + i++; + } else { + arg += '\\'.repeat(slashes); + if (i < line.length) arg += line[i++]; + } + } + + args.push(arg); + } + + return args; +} + +/** What a program started by `code.cmd ... %*` sees for the given arguments. */ +function throughBatch(args: string[]): string[] { + // `cmd /s /c ""` parses the line once; the batch file's %* line is parsed again. + return argv(cmdPass(cmdPass(args.map((arg) => cmdArgument(arg)).join(' ')))); +} + +describe('toolSpawn', () => { + const files = new Set([ + String.raw`C:\Program Files\Microsoft VS Code\bin\code.cmd`, + String.raw`C:\Users\a\AppData\Roaming\npm\claude.cmd`, + String.raw`C:\tools\claude.exe`, + ]); + const exists = (file: string) => files.has(file); + const env = { + ComSpec: String.raw`C:\Windows\system32\cmd.exe`, + PATH: String.raw`C:\Windows;"C:\Program Files\Microsoft VS Code\bin";C:\Users\a\AppData\Roaming\npm`, + PATHEXT: '.COM;.EXE;.BAT;.CMD', + }; + + it('spawns the command as given off Windows', () => { + expect(toolSpawn('code', ['--add-mcp', '{}'], 'darwin', env, exists)).to.deep.equal({ + args: ['--add-mcp', '{}'], + command: 'code', + }); + }); + + it('finds a .cmd on PATH, and an .exe before a .cmd in a later folder', () => { + expect(findOnWindowsPath('code', env, exists)).to.equal(String.raw`C:\Program Files\Microsoft VS Code\bin\code.cmd`); + expect(findOnWindowsPath('claude', { ...env, PATH: `C:\\tools;${env.PATH}` }, exists)).to.equal( + String.raw`C:\tools\claude.exe`, + ); + expect(findOnWindowsPath('cursor', env, exists)).to.equal(undefined); + }); + + it('is undefined on Windows when the command is not on PATH', () => { + expect(toolSpawn('cursor', [], 'win32', env, exists)).to.equal(undefined); + }); + + it('spawns an .exe directly', () => { + expect(toolSpawn('claude', ['mcp'], 'win32', { ...env, PATH: 'C:\\tools' }, exists)).to.deep.equal({ + args: ['mcp'], + command: String.raw`C:\tools\claude.exe`, + }); + }); + + it('runs a .cmd through cmd.exe with verbatim arguments', () => { + const spawn = toolSpawn('code', ['--add-mcp', '{}'], 'win32', env, exists)!; + expect(spawn.command).to.equal(env.ComSpec); + expect(spawn.windowsVerbatimArguments).to.equal(true); + expect(spawn.args.slice(0, 3)).to.deep.equal(['/d', '/s', '/c']); + expect(cmdPass(spawn.args[3].slice(1, -1))).to.match(/^C:\\Program Files\\Microsoft VS Code\\bin\\code\.cmd /); + }); + + it('refuses a line break in an argument to a .cmd', () => { + expect(() => toolSpawn('code', ['a\nb'], 'win32', env, exists)).to.throw(/line break/); + expect(toolSpawn('claude', ['a\nb'], 'win32', { ...env, PATH: 'C:\\tools' }, exists)?.args).to.deep.equal(['a\nb']); + }); + + it('gets the --add-mcp JSON to VS Code unchanged', () => { + const add = vscodeAddArgs({ + args: [String.raw`C:\Users\a b\AppData\Roaming\npm\node_modules\@devicecloud.dev\dcd\dist\index.js`, 'mcp', '--read-only'], + command: String.raw`C:\Program Files (x86)\nodejs\node.exe`, + }); + expect(throughBatch(add)).to.deep.equal(add); + }); + + it('keeps cmd characters, quotes and trailing backslashes intact', () => { + const args = ['a&b|c', '', '100%PATH%', 'say "hi"', String.raw`C:\dir\ `, String.raw`end\\`, '^caret!', '"&"', 'x" | "y', '']; + expect(throughBatch(args)).to.deep.equal(args); + }); +}); From 12f4da5dc1d2b742239f2a6c0ae4d669c978d9f3 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:09:24 +0000 Subject: [PATCH 10/20] feat(device): tap, type, swipe and press-key subcommands (#310) `dcd device` could drive a session only with `run` (a Maestro flow). The API's typed action route, POST /device/sessions/:id/actions, performs one tap, typed text, swipe or key press and answers once the screen has settled, so these four subcommands expose it: dcd device tap [id] --text "Log in" | --rid login_button | --x 50 --y 80 dcd device type [id] --text "hello" [--sensitive] dcd device swipe [id] up|down|left|right | --from 90,50 --to 10,50 dcd device press-key [id] back|home|enter|backspace|tab|volume_up|volume_down|lock|power Same rules as the other subcommands: the session id may be left out when one session is open, --json prints the envelope, a failed action exits 2 with the result. --maestro runs the action as a Maestro flow instead. --- src/commands/device.ts | 202 +++++++++++++++++++++++ src/gateways/device-gateway.ts | 13 +- src/types/domain/device-session.types.ts | 38 +++++ test/unit/device-command.test.ts | 92 +++++++++++ 4 files changed, 344 insertions(+), 1 deletion(-) diff --git a/src/commands/device.ts b/src/commands/device.ts index f23eaaf..4788bc9 100644 --- a/src/commands/device.ts +++ b/src/commands/device.ts @@ -13,15 +13,20 @@ import { } from '../gateways/device-gateway.js'; import type { AuthContext } from '../types/domain/auth.types.js'; import { + DEVICE_KEYS, + type DeviceActionRequest, type DeviceCatalogue, type DeviceCommandResult, type DeviceHumanStatus, type DeviceInstalledApp, + type DevicePoint, type DeviceRunResponse, type DeviceScreenElement, type DeviceSession, + type DeviceSwipeDirection, ENDED_STATES, type StartDeviceSessionRequest, + SWIPE_DIRECTIONS, } from '../types/domain/device-session.types.js'; import { platformOfAppFile, uploadLocalApp } from '../utils/app-upload.js'; import { refreshAuth, resolveAuth } from '../utils/auth.js'; @@ -713,6 +718,199 @@ const launchSub = defineCommand({ }, }); +/** Shared by the typed-action subcommands: the Maestro switch. */ +const maestroArg = { + type: 'boolean', + default: false, + description: 'Run the action as a Maestro flow instead of directly on the device', +} as const; + +/** A percentage of the screen from a flag value, or a usage error. */ +function percentArg(value: unknown, flag: string): number { + const n = typeof value === 'number' ? value : Number(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); + } + return n; +} + +/** "x,y" (percentages) from a flag value, or a usage error. */ +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); + } + return { x: percentArg(parts[0].trim(), flag), y: percentArg(parts[1].trim(), flag) }; +} + +/** + * Send one typed action and print its outcome, the way `launch` does: exit 2 + * with the result when the device could not do it. + */ +async function performAction( + args: Record, + id: string | undefined, + body: DeviceActionRequest, + labels: { done: string; failed: string }, +) { + 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, + ...(args.maestro ? { mode: 'maestro' as const } : {}), + }); + return { + session, + data: { result } as { result: DeviceCommandResult }, + ...(!result.success && { + failure: { code: null, message: result.error || labels.failed }, + }), + print() { + logger.log(result.success ? ui.success(labels.done) : `${ui.statusSymbol('FAILED')} ${labels.failed}`); + if (result.error) logger.log(colors.error(result.error)); + }, + }; +} + +const tapSub = defineCommand({ + meta: { name: 'tap', description: 'Tap an element by text or id, or a point on the screen' }, + args: { + ...commonArgs, + 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`)' }, + x: { type: 'string', description: 'With --y: a point, as percentages of the screen (0-100)' }, + y: { type: 'string', description: 'See --x' }, + maestro: maestroArg, + }, + async run({ args }) { + const json = Boolean(args.json); + await runDeviceCommand(json, async () => { + const targets = [ + args.text !== undefined, + args.rid !== undefined, + args.x !== undefined || args.y !== undefined, + ].filter(Boolean).length; + if (targets !== 1) { + throw new CliError('tap takes exactly one target: --text, --rid, or --x and --y.', 1); + } + const body: DeviceActionRequest = + args.text !== undefined + ? { type: 'tap', text: String(args.text) } + : args.rid !== undefined + ? { type: 'tap', id: String(args.rid) } + : { type: 'tap', x: percentArg(args.x, 'x'), y: percentArg(args.y, 'y') }; + const what = + args.text !== undefined + ? `"${String(args.text)}"` + : args.rid !== undefined + ? `id ${String(args.rid)}` + : `${String(args.x)}%,${String(args.y)}%`; + return performAction(args, args.id as string | undefined, body, { + done: `Tapped ${what}`, + failed: `Tap ${what} failed`, + }); + }); + }, +}); + +const typeSub = defineCommand({ + meta: { name: 'type', description: 'Type text into the focused field' }, + args: { + ...commonArgs, + id: idArg, + text: { type: 'string', description: 'What to type', required: true }, + sensitive: { + type: 'boolean', + default: false, + description: 'The text is a secret: stored encrypted, never shown, masked in the output', + }, + maestro: maestroArg, + }, + 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}"`; + return performAction( + args, + args.id as string | undefined, + { type: 'type', text, ...(args.sensitive ? { sensitive: true } : {}) }, + { done: `Typed ${shown}`, failed: `Typing ${shown} failed` }, + ); + }); + }, +}); + +const isDirection = (value: unknown): value is DeviceSwipeDirection => + typeof value === 'string' && (SWIPE_DIRECTIONS as readonly string[]).includes(value); + +const swipeSub = defineCommand({ + meta: { name: 'swipe', description: 'Swipe up, down, left or right, or from one point to another' }, + args: { + ...commonArgs, + id: idArg, + direction: { + type: 'positional', + required: false, + description: 'up, down, left or right (a swipe across most of the screen)', + }, + from: { type: 'string', description: 'With --to: where the swipe starts, as "x,y" percentages' }, + to: { type: 'string', description: 'Where it ends, as "x,y" percentages' }, + maestro: maestroArg, + }, + async run({ args }) { + const json = Boolean(args.json); + await runDeviceCommand(json, async () => { + let id = args.id as string | undefined; + let direction = args.direction as string | undefined; + // `dcd device swipe up`: the one positional is the direction, not a session. + if (id && !direction && isDirection(id)) [id, direction] = [undefined, id]; + const byPoints = args.from !== undefined || args.to !== undefined; + if ((direction === undefined) === !byPoints) { + throw new CliError('swipe takes a direction (up, down, left, right), or --from and --to.', 1); + } + let body: DeviceActionRequest; + let what: string; + if (direction !== undefined) { + if (!isDirection(direction)) { + throw new CliError(`direction must be one of ${SWIPE_DIRECTIONS.join(', ')}.`, 1); + } + body = { type: 'swipe', direction }; + what = direction; + } else { + 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` }); + }); + }, +}); + +const pressKeySub = defineCommand({ + meta: { name: 'press-key', description: `Press a key: ${DEVICE_KEYS.join(', ')}` }, + args: { + ...commonArgs, + id: idArg, + key: { type: 'positional', required: false, description: `One of ${DEVICE_KEYS.join(', ')}` }, + maestro: maestroArg, + }, + async run({ args }) { + const json = Boolean(args.json); + await runDeviceCommand(json, async () => { + let id = args.id as string | undefined; + let key = args.key as string | undefined; + // `dcd device press-key back`: the one positional is the key, not a session. + if (id && !key && (DEVICE_KEYS as readonly string[]).includes(id)) [id, key] = [undefined, id]; + 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` }); + }); + }, +}); + const modelsSub = defineCommand({ meta: { name: 'models', description: 'The devices a session can ask for' }, args: { @@ -1343,6 +1541,10 @@ export const deviceCommand = defineCommand({ stop: stopSub, install: installSub, launch: launchSub, + tap: tapSub, + type: typeSub, + swipe: swipeSub, + 'press-key': pressKeySub, models: modelsSub, inspect: inspectSub, screenshot: screenshotSub, diff --git a/src/gateways/device-gateway.ts b/src/gateways/device-gateway.ts index e192396..bd99951 100644 --- a/src/gateways/device-gateway.ts +++ b/src/gateways/device-gateway.ts @@ -1,10 +1,11 @@ import type { AuthContext } from '../types/domain/auth.types.js'; import type { + DeviceActionRequest, DeviceArtifactsPage, DeviceBundleUploadUrls, - DeviceFlowBundle, DeviceCatalogue, DeviceCommandResult, + DeviceFlowBundle, DeviceHumanStatus, DeviceInstalledApp, DeviceLogs, @@ -277,6 +278,16 @@ export const DeviceGateway = { return request(baseUrl, auth, 'POST', `${sessionPath(id)}/request-human`, { reason }); }, + /** One typed action: tap, type, swipe or press_key. Synchronous: answers with the outcome. */ + action( + baseUrl: string, + auth: AuthContext, + id: string, + body: DeviceActionRequest, + ): Promise<{ result: DeviceCommandResult; session: DeviceSession }> { + return request(baseUrl, auth, 'POST', `${sessionPath(id)}/actions`, body); + }, + run( baseUrl: string, auth: AuthContext, diff --git a/src/types/domain/device-session.types.ts b/src/types/domain/device-session.types.ts index ea4d063..993539a 100644 --- a/src/types/domain/device-session.types.ts +++ b/src/types/domain/device-session.types.ts @@ -117,6 +117,44 @@ export interface DeviceFlowResult { success: boolean; } +export type DeviceSwipeDirection = 'down' | 'left' | 'right' | 'up'; +export interface DevicePoint { + /** Percentages of the screen's width and height, 0 to 100. */ + x: number; + y: number; +} + +/** + * One typed action for POST /device/sessions/:id/actions. `mode: 'maestro'` + * runs it as a Maestro flow instead of on the device directly. + */ +export type DeviceActionRequest = + | { id?: string; mode?: 'maestro'; text?: string; type: 'tap'; x?: number; y?: number } + | { key: string; mode?: 'maestro'; type: 'press_key' } + | { mode?: 'maestro'; sensitive?: boolean; text: string; type: 'type' } + | { + direction?: DeviceSwipeDirection; + from?: DevicePoint; + mode?: 'maestro'; + to?: DevicePoint; + type: 'swipe'; + }; + +/** The keys press_key takes, as the API names them. */ +export const DEVICE_KEYS = [ + 'back', + 'home', + 'enter', + 'backspace', + 'tab', + 'volume_up', + 'volume_down', + 'lock', + 'power', +] as const; + +export const SWIPE_DIRECTIONS: readonly DeviceSwipeDirection[] = ['up', 'down', 'left', 'right']; + /** The result of a typed action, a launch or a run. */ export interface DeviceCommandResult { error?: string; diff --git a/test/unit/device-command.test.ts b/test/unit/device-command.test.ts index c656f28..028fbba 100644 --- a/test/unit/device-command.test.ts +++ b/test/unit/device-command.test.ts @@ -293,6 +293,98 @@ describe('dcd device', () => { }); }); + describe('typed actions (tap, type, swipe, press-key)', () => { + const ok = () => ({ body: { result: { success: true }, session: session('a-b-c') } }); + + it('tap sends one target to /actions: text, id, or a point', async () => { + const calls = stubFetch(ok); + await runJson('tap', { id: 'a-b-c', text: 'Log in' }); + await runJson('tap', { id: 'a-b-c', rid: 'login_button' }); + await runJson('tap', { id: 'a-b-c', x: '50', y: '80.5' }); + expect(calls.map((c) => [c.method, c.url, c.body])).to.deep.equal([ + ['POST', `${API}/device/sessions/a-b-c/actions`, { type: 'tap', text: 'Log in' }], + ['POST', `${API}/device/sessions/a-b-c/actions`, { type: 'tap', id: 'login_button' }], + ['POST', `${API}/device/sessions/a-b-c/actions`, { type: 'tap', x: 50, y: 80.5 }], + ]); + expect(calls[0].headers['x-dcd-source']).to.equal('cli'); + }); + + it('tap refuses no target, two targets and a bad percentage without calling the API', async () => { + const calls = stubFetch(ok); + for (const args of [ + { id: 'a-b-c' }, + { id: 'a-b-c', text: 'x', rid: 'y' }, + { id: 'a-b-c', x: '150', y: '10' }, + { id: 'a-b-c', x: 'left', y: '10' }, + ]) { + const { exit, out } = await runJson('tap', args); + expect(exit).to.equal(DEVICE_EXIT.usage); + expect(out.ok).to.equal(false); + } + expect(calls).to.have.length(0); + }); + + it('--maestro asks for the Maestro path', async () => { + const calls = stubFetch(ok); + await runJson('tap', { id: 'a-b-c', text: 'OK', maestro: true }); + expect(calls[0].body).to.deep.equal({ type: 'tap', text: 'OK', mode: 'maestro' }); + }); + + it('type sends the text, sensitive when asked, and keeps it out of the envelope', async () => { + const calls = stubFetch(ok); + const { out } = await runJson('type', { id: 'a-b-c', text: 'hunter2', sensitive: true }); + expect(calls[0].body).to.deep.equal({ type: 'type', text: 'hunter2', sensitive: true }); + expect(JSON.stringify(out)).to.not.include('hunter2'); + await runJson('type', { id: 'a-b-c', text: 'hello' }); + expect(calls[1].body).to.deep.equal({ type: 'type', text: 'hello' }); + }); + + it('swipe takes a direction as its only positional, or --from and --to', async () => { + const calls = stubFetch((call) => + call.url.endsWith('/device/sessions') ? { body: { sessions: [session('a-b-c')] } } : ok(), + ); + await runJson('swipe', { id: 'up' }); + await runJson('swipe', { id: 'a-b-c', direction: 'left' }); + await runJson('swipe', { id: 'a-b-c', from: '90,50', to: '10, 50' }); + const posts = calls.filter((c) => c.method === 'POST'); + expect(posts.map((c) => c.body)).to.deep.equal([ + { type: 'swipe', direction: 'up' }, + { type: 'swipe', direction: 'left' }, + { type: 'swipe', from: { x: 90, y: 50 }, to: { x: 10, y: 50 } }, + ]); + const { exit } = await runJson('swipe', { id: 'a-b-c', direction: 'sideways' }); + expect(exit).to.equal(DEVICE_EXIT.usage); + const both = await runJson('swipe', { id: 'a-b-c', direction: 'up', from: '1,1', to: '2,2' }); + expect(both.exit).to.equal(DEVICE_EXIT.usage); + }); + + it('press-key takes the key as its only positional when the session is implied', async () => { + const calls = stubFetch((call) => + call.url.endsWith('/device/sessions') ? { body: { sessions: [session('a-b-c')] } } : ok(), + ); + await runJson('press-key', { id: 'back' }); + await runJson('press-key', { id: 'a-b-c', key: 'enter' }); + const posts = calls.filter((c) => c.method === 'POST'); + expect(posts.map((c) => [c.url, c.body])).to.deep.equal([ + [`${API}/device/sessions/a-b-c/actions`, { type: 'press_key', key: 'back' }], + [`${API}/device/sessions/a-b-c/actions`, { type: 'press_key', key: 'enter' }], + ]); + const { exit } = await runJson('press-key', { id: 'a-b-c', key: 'menu' }); + expect(exit).to.equal(DEVICE_EXIT.usage); + }); + + it('exits 2 with the result when the device could not do the action', async () => { + stubFetch(() => ({ + body: { result: { success: false, error: 'Element not found: "Nope"' }, session: session('a-b-c') }, + })); + const { exit, out } = await runJson('tap', { id: 'a-b-c', text: 'Nope' }); + expect(exit).to.equal(DEVICE_EXIT.failed); + expect(out.ok).to.equal(false); + expect(out.data).to.deep.equal({ result: { success: false, error: 'Element not found: "Nope"' } }); + expect(out.error).to.deep.equal({ code: null, message: 'Element not found: "Nope"' }); + }); + }); + describe('install --wait', () => { const installed = { app: { binary_upload_id: 'b-2', app_id: 'com.x', reused: true } }; const withInstall = (status: 'failed' | 'installed' | 'installing', error: null | string = null) => From 9f16ca2dfc3159b827c1447c3e9287933eff2de8 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:44:14 +0000 Subject: [PATCH 11/20] fix(device): keep a missing --text on `type` inside the --json envelope (#311) `type --text` was marked required, so citty rejected a missing value before runDeviceCommand ran, and --json then printed the top-level { status, error } instead of the device envelope the command promises. The flag is optional now; the command's own check answers the usage error (exit 1) inside the envelope. --- src/commands/device.ts | 4 +++- test/unit/device-command.test.ts | 10 ++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/commands/device.ts b/src/commands/device.ts index 4788bc9..eb96746 100644 --- a/src/commands/device.ts +++ b/src/commands/device.ts @@ -819,7 +819,9 @@ const typeSub = defineCommand({ args: { ...commonArgs, id: idArg, - text: { type: 'string', description: 'What to type', required: true }, + // 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' }, sensitive: { type: 'boolean', default: false, diff --git a/test/unit/device-command.test.ts b/test/unit/device-command.test.ts index 028fbba..00f33f0 100644 --- a/test/unit/device-command.test.ts +++ b/test/unit/device-command.test.ts @@ -339,6 +339,16 @@ describe('dcd device', () => { expect(calls[1].body).to.deep.equal({ type: 'type', text: 'hello' }); }); + it('type without --text is a usage error inside the envelope, not a citty error', async () => { + const calls = stubFetch(ok); + const { exit, out } = await runJson('type', { id: 'a-b-c' }); + expect(exit).to.equal(DEVICE_EXIT.usage); + expect(out).to.have.keys('ok', 'session', 'data', 'error'); + expect(out.ok).to.equal(false); + expect((out.error as { message: string }).message).to.include('--text'); + expect(calls).to.have.length(0); + }); + it('swipe takes a direction as its only positional, or --from and --to', async () => { const calls = stubFetch((call) => call.url.endsWith('/device/sessions') ? { body: { sessions: [session('a-b-c')] } } : ok(), From f5db0b0376ba1b07f15ba6d5dfb5b3065cfbd0f7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:57:44 +0000 Subject: [PATCH 12/20] deps: bump @supabase/supabase-js from 2.118.0 to 2.119.0 in the minor-and-patch group across 1 directory (#304) deps: bump @supabase/supabase-js Bumps the minor-and-patch group with 1 update in the / directory: [@supabase/supabase-js](https://github.com/supabase/supabase-js/tree/HEAD/packages/core/supabase-js). Updates `@supabase/supabase-js` from 2.118.0 to 2.119.0 - [Release notes](https://github.com/supabase/supabase-js/releases) - [Changelog](https://github.com/supabase/supabase-js/blob/master/packages/core/supabase-js/CHANGELOG.md) - [Commits](https://github.com/supabase/supabase-js/commits/v2.119.0/packages/core/supabase-js) --- updated-dependencies: - dependency-name: "@supabase/supabase-js" dependency-version: 2.119.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: minor-and-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pnpm-lock.yaml | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5e22f9a..3a7ad7a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -49,7 +49,7 @@ importers: version: 1.32.2(zod@4.6.7) '@supabase/supabase-js': specifier: ^2.108.2 - version: 2.118.0 + version: 2.119.0 bplist-parser: specifier: ^0.5.0 version: 0.5.0 @@ -412,31 +412,31 @@ packages: resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} engines: {node: '>= 8'} - '@supabase/auth-js@2.118.0': - resolution: {integrity: sha512-xWfPXyhS2KDSfAneMtI6p/tBnbdiz/5vaRKXEqUfzfC9WCniKr2Ds5o5G7RIGig0bom4z6wUY9zaV07WDVTfnQ==} + '@supabase/auth-js@2.119.0': + resolution: {integrity: sha512-WI7KqJRxqZjm77PlRO/VfKretL4SG8g8stWfBmpyx9To+fFapZlSbXA8QkduoMvr72rRpIF24ZLrjktBrp+ZFA==} engines: {node: '>=22.0.0'} - '@supabase/functions-js@2.118.0': - resolution: {integrity: sha512-4ofletPa/noKAU6KHeqsd3FztGzRPUEJRey1MKY0o+PIHaVePqRPShIXtl37gcVyIWaFM+zNg6r9zh0uUSFOSA==} + '@supabase/functions-js@2.119.0': + resolution: {integrity: sha512-0aOdF/Y4lA+62K02nwZClfAthXmFEml0od42q3yy/9t3bBitomAOYEatTFSnxT/5UeeIDNn2DOnXTdAP0sqGNQ==} engines: {node: '>=22.0.0'} '@supabase/phoenix@0.4.5': resolution: {integrity: sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw==} - '@supabase/postgrest-js@2.118.0': - resolution: {integrity: sha512-JXy+37KPApHsyotaQACovv/Jy9E22rfiWLRuT+2UjoEAcAIelDFIrsF/FY47Dy19mO7lI0Tq+zDCX8oJ2Ozfiw==} + '@supabase/postgrest-js@2.119.0': + resolution: {integrity: sha512-qBmcjEFO7Ptyf5qvOXYJa1s4bfA4zsMIFf2i+h2zd6RRTDLwquX8z1mnS9djNOJjbiO1OGFh5Y2Lc2k2pA8TMw==} engines: {node: '>=22.0.0'} - '@supabase/realtime-js@2.118.0': - resolution: {integrity: sha512-pzCIEWjqD5/xqEZQerpt+q9rsgYkcrkgCJgf0W2ULqC4fYUeB/p9CFa3t9vn+IVh6dMN9r4ZCE262lZvUC+Bfw==} + '@supabase/realtime-js@2.119.0': + resolution: {integrity: sha512-fPzxt+SAYweqsZUCSZma2dvN+HT6lVjwWj8BbkVwapW6wNf1odUi+ATYN7svX4Zm9vt0kz0l0VzINAUAA38FEg==} engines: {node: '>=22.0.0'} - '@supabase/storage-js@2.118.0': - resolution: {integrity: sha512-5MNkKt2Moy7Jud/sPX7/28BwdDxZMCVHGJT00b8op3KRa9LKSjOAYU5IcfGWIstaasAqY8GkbA6oI3IRDgB1YQ==} + '@supabase/storage-js@2.119.0': + resolution: {integrity: sha512-htx1dSCnSJVPlx2BNSgLSUDvLMxuGbYa6pUPl5xoCs4as4cIhBVwuxj78zbggCyPHxLnEXjsV/qvlDsVjpodKw==} engines: {node: '>=22.0.0'} - '@supabase/supabase-js@2.118.0': - resolution: {integrity: sha512-FxI8UXMVC2UG7IkeiI8fuQZqq2oI3JeSuN8MPIC2RLVaoEAxKS0nqE6kii9Ewpq8f9gNPM6git1Y8f0vN/QLFw==} + '@supabase/supabase-js@2.119.0': + resolution: {integrity: sha512-MKP49G6bJbPhvsZDegZ/IXS/ITApPgplDCF5+F65KZ5kIArS5Y90WFxwvWYALx2bsxdrSuHvkCiXHYr3dU8+sw==} engines: {node: '>=22.0.0'} peerDependencies: '@opentelemetry/api': '>=1.0.0' @@ -1926,37 +1926,37 @@ snapshots: '@nodelib/fs.scandir': 2.1.5 fastq: 1.20.1 - '@supabase/auth-js@2.118.0': + '@supabase/auth-js@2.119.0': dependencies: tslib: 2.8.1 - '@supabase/functions-js@2.118.0': + '@supabase/functions-js@2.119.0': dependencies: tslib: 2.8.1 '@supabase/phoenix@0.4.5': {} - '@supabase/postgrest-js@2.118.0': + '@supabase/postgrest-js@2.119.0': dependencies: tslib: 2.8.1 - '@supabase/realtime-js@2.118.0': + '@supabase/realtime-js@2.119.0': dependencies: '@supabase/phoenix': 0.4.5 tslib: 2.8.1 - '@supabase/storage-js@2.118.0': + '@supabase/storage-js@2.119.0': dependencies: iceberg-js: 0.8.1 tslib: 2.8.1 - '@supabase/supabase-js@2.118.0': + '@supabase/supabase-js@2.119.0': dependencies: - '@supabase/auth-js': 2.118.0 - '@supabase/functions-js': 2.118.0 - '@supabase/postgrest-js': 2.118.0 - '@supabase/realtime-js': 2.118.0 - '@supabase/storage-js': 2.118.0 + '@supabase/auth-js': 2.119.0 + '@supabase/functions-js': 2.119.0 + '@supabase/postgrest-js': 2.119.0 + '@supabase/realtime-js': 2.119.0 + '@supabase/storage-js': 2.119.0 '@types/chai@5.2.3': dependencies: From 14ae83dc50018ac70a1a5d7ed4c75fd854e3e0c6 Mon Sep 17 00:00:00 2001 From: Tom Riglar Date: Thu, 12 Nov 2026 15:30:16 +0000 Subject: [PATCH 13/20] refactor(auth): stop calling Supabase directly for logout, login checks and live status (#312) * refactor(auth): stop calling Supabase directly for logout, login checks and live status - dcd logout now just deletes the stored session. It never revoked anything server-side, so the Supabase round trip did nothing useful. - dcd login no longer probes Supabase's /auth/v1/user when the API rejects a new token. The error still names the token's issuer. - dcd cloud / status no longer open a Supabase Realtime socket. It was only a speed-up over polling. Logged-in users now poll every 20s, the same as API-key users (was 60s plus realtime pushes). Co-Authored-By: Claude Opus 5.5 * test: zero the renamed poll interval in the poll-cache loop test Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- src/commands/cloud.ts | 6 +- src/commands/login.ts | 36 +---- src/commands/logout.ts | 7 +- src/gateways/cli-auth-gateway.ts | 22 --- src/gateways/realtime-gateway.ts | 183 ------------------------ src/services/results-polling.service.ts | 158 ++++---------------- src/types/domain/auth.types.ts | 4 +- test/unit/results-poll-cache.test.ts | 2 +- test/unit/session-refresh.test.ts | 27 +--- 9 files changed, 41 insertions(+), 404 deletions(-) delete mode 100644 src/gateways/realtime-gateway.ts diff --git a/src/commands/cloud.ts b/src/commands/cloud.ts index d1b5908..9dd38ac 100644 --- a/src/commands/cloud.ts +++ b/src/commands/cloud.ts @@ -358,12 +358,12 @@ export const cloudCommand = defineCommand({ const auth = await resolveAuth({ apiKeyFlag }); - // Nudge interactive api-key users toward `dcd login`, which unlocks live - // (realtime) status updates. Suppressed in CI and non-interactive output. + // Nudge interactive api-key users toward `dcd login`. Suppressed in CI and + // non-interactive output. if (auth.mode === 'apiKey' && !json && !quiet && !isCI()) { out( colors.dim( - 'Tip: run `dcd login` for live test updates and a smoother experience than passing --api-key.', + 'Tip: run `dcd login` for a smoother experience than passing --api-key.', ), ); } diff --git a/src/commands/login.ts b/src/commands/login.ts index 553cf2b..5ec68df 100644 --- a/src/commands/login.ts +++ b/src/commands/login.ts @@ -36,12 +36,10 @@ import { defineCommand } from 'citty'; import { createHash, randomBytes } from 'node:crypto'; import { - type DcdEnvName, ENVIRONMENTS, inferEnvFromApiUrl, resolveFrontendUrl, } from '../config/environments.js'; -import { getSupabaseKey } from '../config/supabase-key.js'; import { jsonFlag } from '../config/flags/output.flags.js'; import { openBrowser } from '../utils/browser.js'; import { canPrompt } from '../utils/ci.js'; @@ -201,17 +199,11 @@ export const loginCommand = defineCommand({ try { orgs = await fetchOrgs(apiUrl, bearerHeaders); } catch (err) { - // The api rejected the JWT. Before blaming the api, hit Supabase's - // own /auth/v1/user directly with the same token — if Supabase also - // rejects it, the token itself is bad; if Supabase accepts, the - // api's JwtService is misconfigured. + // The api rejected the JWT it just minted. Name the token's issuer, so + // a token from the wrong environment is plain from the error. const iss = decodeJwtIssuer(payload.access_token); - const supabaseUser = await probeSupabaseUser(iss, env, payload.access_token); - const parts = [ - iss ? `token iss: ${iss}` : null, - `supabase /auth/v1/user: ${supabaseUser}`, - ].filter(Boolean); - throw new CliError(`${(err as Error).message} [${parts.join(' | ')}]`); + const message = (err as Error).message; + throw new CliError(iss ? `${message} [token iss: ${iss}]` : message); } const { org: chosen, fromLastLogin } = await selectOrg(orgs, { requested: requestedOrg, @@ -319,26 +311,6 @@ function base64url(buf: Buffer): string { return buf.toString('base64').replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); } -async function probeSupabaseUser( - iss: string | null, - env: DcdEnvName, - token: string, -): Promise { - if (!iss) return 'skipped (no iss)'; - try { - const res = await fetch(`${iss}/user`, { - headers: { - authorization: `Bearer ${token}`, - apikey: await getSupabaseKey(env), - }, - }); - const bodyText = await res.text().catch(() => ''); - return `HTTP ${res.status}${bodyText ? ` — ${bodyText.slice(0, 200)}` : ''}`; - } catch (err) { - return `network error: ${(err as Error).message}`; - } -} - function decodeJwtIssuer(token: string): string | null { try { const [, payloadB64] = token.split('.'); diff --git a/src/commands/logout.ts b/src/commands/logout.ts index be2a163..bd72e2f 100644 --- a/src/commands/logout.ts +++ b/src/commands/logout.ts @@ -1,11 +1,11 @@ /** - * `dcd logout` — clears the stored Supabase session and best-effort revokes - * it on Supabase. Leaves DEVICE_CLOUD_API_KEY (env/flag) untouched. + * `dcd logout` — deletes the stored session. Local only: nothing is revoked + * server-side, so the user stays signed in to the web app and any other CLI. + * Leaves DEVICE_CLOUD_API_KEY (env/flag) untouched. */ import { defineCommand } from 'citty'; import { jsonFlag } from '../config/flags/output.flags.js'; -import { CliAuthGateway } from '../gateways/cli-auth-gateway.js'; import { logger } from '../utils/cli.js'; import { clearConfig, getConfigPath, readConfig } from '../utils/config-store.js'; import { colors } from '../utils/styling.js'; @@ -32,7 +32,6 @@ export const logoutCommand = defineCommand({ return; } - await CliAuthGateway.signOut(config.supabase_url, config.env, config.session); clearConfig(); if (json) { logger.json({ status: 'SUCCESS', loggedOut: true, user: config.session.user_email }); diff --git a/src/gateways/cli-auth-gateway.ts b/src/gateways/cli-auth-gateway.ts index 96686ef..bee282e 100644 --- a/src/gateways/cli-auth-gateway.ts +++ b/src/gateways/cli-auth-gateway.ts @@ -112,26 +112,4 @@ export const CliAuthGateway = { user_id: u.id, }; }, - - async signOut( - supabaseUrl: string, - env: DcdEnvName, - session: StoredSession, - ): Promise { - // `scope: 'local'` clears this client's SDK state only — no server call, - // no revocation. supabase-js defaults to `scope: 'global'`, which revokes - // EVERY session for the user (browser, mobile, other CLIs), so - // `dcd logout` would kick the user out of the web app. We don't want - // that — logging out locally should be local. - try { - const sb = client(supabaseUrl, await getSupabaseKey(env)); - await sb.auth.setSession({ - access_token: session.access_token, - refresh_token: session.refresh_token, - }); - await sb.auth.signOut({ scope: 'local' }); - } catch { - // Best effort — the local config will be wiped regardless. - } - }, }; diff --git a/src/gateways/realtime-gateway.ts b/src/gateways/realtime-gateway.ts deleted file mode 100644 index 2ede962..0000000 --- a/src/gateways/realtime-gateway.ts +++ /dev/null @@ -1,183 +0,0 @@ -/** - * Supabase Realtime subscription to test-result status changes. - * - * This is a *latency optimisation* layered on top of HTTP polling, not a - * replacement for it. A logged-in (bearer) user's JWT authorises a - * `postgres_changes` subscription on the `results` table (RLS scopes rows to - * the user's org via `app_metadata.org_ids`). Each relevant change fires - * `onChange`, which the polling loop uses to fetch immediately instead of - * waiting out the full backstop interval. - * - * We deliberately only read the `new` row's `test_upload_id` — Postgres always - * ships the full new tuple on INSERT/UPDATE regardless of REPLICA IDENTITY, so - * no DB change is required. Mirrors the frontend pattern in - * dcd/frontend/app/stores/Results.store.ts. - */ -import { - createClient, - REALTIME_SUBSCRIBE_STATES, - type RealtimeChannel, - type SupabaseClient, -} from '@supabase/supabase-js'; - -import { ENVIRONMENTS, type DcdEnvName } from '../config/environments.js'; -import { getSupabaseKey } from '../config/supabase-key.js'; - -export interface RealtimeResultsSubscription { - /** - * Whether the channel is currently subscribed and receiving pushes. False - * until the socket subscribes, and again if it errors/closes — the backstop - * poll always covers the gap. - */ - isConnected(): boolean; - /** Tear down the channel and close the socket. Best-effort, never throws. */ - unsubscribe(): Promise; - /** - * Hand the socket a refreshed JWT. RLS authorises the channel with the token - * it joined with, and the server drops the channel once that expires — so a - * poll that outlives the token passes the new one on. Best-effort, never - * throws. - */ - updateAccessToken(accessToken: string): void; -} - -export interface RealtimeSubscribeOptions { - /** Supabase JWT (AuthContext.accessToken) — authorises the socket for RLS. */ - accessToken: string; - debug?: boolean; - env: DcdEnvName; - /** Stderr-safe logger; stdout is reserved by some callers (MCP). */ - log?: (message: string) => void; - /** Fired when a result row for this upload changes. */ - onChange: () => void; - /** Fired whenever the connection state flips (subscribed ↔ disconnected). */ - onConnectionChange?: (connected: boolean) => void; - orgId: string; - uploadId: string; -} - -/** - * The `new` record we care about from a `results` row change. Loosely typed — - * we only ever read `test_upload_id`. - */ -interface ResultChangePayload { - new?: { test_upload_id?: string } | null; -} - -export class RealtimeResultsGateway { - /** - * Open a realtime subscription to `results` changes for the given upload. - * Construction never throws — on any failure the caller simply keeps polling. - */ - static subscribe( - options: RealtimeSubscribeOptions, - ): RealtimeResultsSubscription { - const { accessToken, debug, env, log, onChange, onConnectionChange, orgId, uploadId } = options; - const dbg = (message: string) => { - if (debug && log) log(`[DEBUG] [realtime] ${message}`); - }; - - let connected = false; - const setConnected = (next: boolean) => { - if (next === connected) return; - connected = next; - onConnectionChange?.(next); - }; - - let client: SupabaseClient | undefined; - let channel: RealtimeChannel | undefined; - let closed = false; - // The latest JWT, so a refresh that lands while the key is still being - // fetched is the one the socket joins with. - let token = accessToken; - - // The publishable key comes from the API (dcd#1112), so the socket opens - // asynchronously. `subscribe` stays synchronous for the caller: until it - // connects, `isConnected` is false and the backstop poll covers the gap. - const ready = getSupabaseKey(env) - .then((supabaseKey) => { - if (closed) return; - const sb = createClient(ENVIRONMENTS[env].supabase.url, supabaseKey, { - // Match SupabaseClientGateway / the frontend; no session persistence — - // we set the token explicitly below. - auth: { autoRefreshToken: false, persistSession: false }, - realtime: { params: { eventsPerSecond: 10 } }, - }); - client = sb; - - // Attach the user's JWT to the socket so RLS is enforced on the channel. - sb.realtime.setAuth(token); - - channel = sb - .channel(`results-cli-${uploadId}`) - .on( - // The typings don't cover the postgres_changes overload cleanly. - 'postgres_changes' as never, - { - event: '*', - schema: 'public', - table: 'results', - filter: `org_id=eq.${orgId}`, - } as never, - (payload: ResultChangePayload) => { - if (payload.new?.test_upload_id === uploadId) { - dbg(`change for upload ${uploadId}`); - onChange(); - } - }, - ) - .subscribe((status) => { - if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) { - dbg('subscribed'); - setConnected(true); - } else if ( - status === REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR || - status === REALTIME_SUBSCRIBE_STATES.TIMED_OUT || - status === REALTIME_SUBSCRIBE_STATES.CLOSED - ) { - // Don't try to recover — the backstop poll covers us. Surface in - // debug so a network-blocked websocket is diagnosable. - dbg(`channel ${status}; relying on backstop poll`); - setConnected(false); - } - }); - }) - .catch((error: unknown) => { - dbg(`failed to subscribe: ${error instanceof Error ? error.message : String(error)}`); - // Best-effort cleanup of a half-built client, then degrade to polling. - try { - client?.realtime.disconnect(); - } catch { - /* ignore */ - } - client = undefined; - channel = undefined; - }); - - return { - isConnected: () => connected, - async unsubscribe() { - closed = true; - setConnected(false); - await ready; - if (!client) return; - try { - if (channel) await client.removeChannel(channel); - await client.realtime.disconnect(); - } catch { - /* best effort — process is exiting anyway */ - } - }, - updateAccessToken(nextToken: string) { - token = nextToken; - // setAuth updates the join payload and pushes the token to joined - // channels. A failure only costs realtime; the backstop poll stays. - client?.realtime.setAuth(nextToken).catch((error: unknown) => { - dbg( - `failed to update the socket's token: ${error instanceof Error ? error.message : String(error)}`, - ); - }); - }, - }; - } -} diff --git a/src/services/results-polling.service.ts b/src/services/results-polling.service.ts index 11e7c99..8840d82 100644 --- a/src/services/results-polling.service.ts +++ b/src/services/results-polling.service.ts @@ -1,10 +1,6 @@ import * as path from 'node:path'; import { ApiGateway, type ResultsPollCache } from '../gateways/api-gateway.js'; -import { - RealtimeResultsGateway, - type RealtimeResultsSubscription, -} from '../gateways/realtime-gateway.js'; import { formatDurationSeconds } from '../methods.js'; import type { AuthContext } from '../types/domain/auth.types.js'; import { paths } from '../types/generated/schema.types.js'; @@ -170,11 +166,9 @@ export class ResultsPollingService { // giving up. Losing a run to a brief hiccup is far more costly than waiting a // bit longer. private readonly MAX_SEQUENTIAL_FAILURES = 30; - // Backstop poll cadence. Logged-in (bearer) users also get realtime pushes - // (see RealtimeResultsGateway), so they only need an occasional reconciling - // poll; api-key users have no realtime and rely on the faster interval. - private readonly BEARER_POLL_INTERVAL_MS = 60_000; - private readonly APIKEY_POLL_INTERVAL_MS = 20_000; + // Poll cadence, the same for API-key and `dcd login` auth. A poll that finds + // nothing changed costs an empty 304 (see ResultsPollCache). + private readonly POLL_INTERVAL_MS = 20_000; // Base unit for the backoff applied between *failed* polls, and its cap. private readonly ERROR_BACKOFF_BASE_MS = 10_000; private readonly MAX_ERROR_BACKOFF_MS = 30_000; @@ -219,48 +213,12 @@ export class ResultsPollingService { // gets an empty 304 instead of the whole set again. const resultsCache: ResultsPollCache = {}; - const pollIntervalMs = - auth.mode === 'bearer' - ? this.BEARER_POLL_INTERVAL_MS - : this.APIKEY_POLL_INTERVAL_MS; - - // "Poke" mechanism: a realtime change resolves the current inter-poll wait - // early. If a poke lands while we're mid-fetch (not waiting) it's latched - // and consumed by the next wait, so events are never silently dropped. - let resolveWake: (() => void) | null = null; - let pendingPoke = false; - const poke = () => { - if (resolveWake) { - const r = resolveWake; - resolveWake = null; - r(); - } else { - pendingPoke = true; - } - }; - const waitForNextPoll = (ms: number): Promise => { - if (pendingPoke) { - pendingPoke = false; - return Promise.resolve(); - } - return new Promise((resolve) => { - const timer = setTimeout(() => { - resolveWake = null; - resolve(); - }, ms); - resolveWake = () => { - clearTimeout(timer); - resolve(); - }; - }); - }; + const pollIntervalMs = this.POLL_INTERVAL_MS; // Live display state, recomposed by renderStatus() so the footer (countdown - // to the next backstop poll + realtime connection state) stays current - // between polls without re-fetching. `nextPollAt` is an epoch-ms deadline - // while waiting, or null while a fetch is in flight. - let subscription: RealtimeResultsSubscription | undefined; - let realtimeEnabled = false; + // to the next poll) stays current between polls without re-fetching. + // `nextPollAt` is an epoch-ms deadline while waiting, or null while a + // fetch is in flight. let statusBody = ''; let nextPollAt: null | number = null; // The animated footer/countdown only makes sense on a TTY. In CI/pipes it @@ -273,39 +231,10 @@ export class ResultsPollingService { ux.action.status = statusBody; return; } - const footer = this.buildStatusFooter( - realtimeEnabled, - subscription?.isConnected() ?? false, - nextPollAt, - quiet, - ); + const footer = this.buildStatusFooter(nextPollAt, quiet); ux.action.status = footer ? `${statusBody}\n${footer}` : statusBody; }; - // Realtime is a latency optimisation over the backstop poll; only logged-in - // (bearer) users can authenticate the socket under RLS. Any failure inside - // the gateway degrades silently to pure polling. - if (auth.mode === 'bearer' && auth.accessToken && auth.orgId && auth.env) { - realtimeEnabled = true; - subscription = RealtimeResultsGateway.subscribe({ - accessToken: auth.accessToken, - debug, - env: auth.env, - log: logger, - onChange: poke, - // Reflect connect/disconnect in the live footer immediately rather than - // waiting for the next ticker frame. - onConnectionChange: renderStatus, - orgId: auth.orgId, - uploadId, - }); - if (debug && logger) { - logger( - `[DEBUG] Realtime enabled; backstop poll every ${pollIntervalMs / 1000}s`, - ); - } - } - if (debug && logger) { logger(`[DEBUG] Starting polling loop for results`); } @@ -327,7 +256,7 @@ export class ResultsPollingService { nextPollAt = null; renderStatus(); - auth = await this.refreshPollingAuth(auth, uploadId, subscription, debug, logger); + auth = await this.refreshPollingAuth(auth, uploadId, debug, logger); const updatedResults = await this.fetchAndLogResults( apiUrl, auth, @@ -360,11 +289,10 @@ export class ResultsPollingService { // Reset failure counter on successful poll sequentialPollFailures = 0; - // Wait for the next backstop poll, or a realtime poke, whichever comes - // first, while the footer counts down to the deadline. + // Wait for the next poll while the footer counts down to it. nextPollAt = Date.now() + pollIntervalMs; renderStatus(); - await waitForNextPoll(pollIntervalMs); + await this.sleep(pollIntervalMs); } catch (error) { // Re-throw RunFailedError immediately (test failures, not polling // errors), and an expired login no retry can fix. @@ -397,12 +325,6 @@ export class ResultsPollingService { if (ticker) { clearInterval(ticker); } - if (subscription) { - if (debug && logger) { - logger('[DEBUG] Closing realtime subscription'); - } - await subscription.unsubscribe(); - } } } @@ -604,12 +526,11 @@ export class ResultsPollingService { /** * Swap in a fresh `dcd login` token when the current one is about to - * expire, and hand it to the realtime socket too; API-key auth comes back - * as-is. A transient refresh failure is thrown as-is, to be retried like - * any failed poll; one only `dcd login` can fix becomes a PollingAuthError. + * expire; API-key auth comes back as-is. A transient refresh failure is + * thrown as-is, to be retried like any failed poll; one only `dcd login` + * can fix becomes a PollingAuthError. * @param auth The credential the previous poll used * @param uploadId Upload being polled, for the reconnect hint - * @param subscription Realtime subscription to pass a new token to * @param debug Whether debug logging is enabled * @param logger Optional logger function * @returns The credential for the next poll @@ -617,7 +538,6 @@ export class ResultsPollingService { private async refreshPollingAuth( auth: AuthContext, uploadId: string, - subscription: RealtimeResultsSubscription | undefined, debug: boolean, logger?: (message: string) => void, ): Promise { @@ -637,14 +557,8 @@ export class ResultsPollingService { throw error; } - if (next !== auth) { - if (debug && logger) { - logger('[DEBUG] Refreshed the dcd login session for polling'); - } - - if (next.accessToken && next.accessToken !== auth.accessToken) { - subscription?.updateAccessToken(next.accessToken); - } + if (next !== auth && debug && logger) { + logger('[DEBUG] Refreshed the dcd login session for polling'); } return next; @@ -851,7 +765,7 @@ export class ResultsPollingService { /** * Build the body of the live status display (the per-test table, or just the - * one-line summary in quiet mode). The footer (countdown + realtime state) is + * one-line summary in quiet mode). The footer (the countdown) is * appended separately by {@link buildStatusFooter} so it can re-render on a * timer without re-fetching. */ @@ -876,38 +790,20 @@ export class ResultsPollingService { } /** - * Build the live footer shown under the status display: whether realtime - * updates are connected (for logged-in users) and how long until the next - * backstop poll. While a fetch is in flight (`nextPollAt` is null) the - * countdown reads "refreshing…". In quiet mode the countdown is omitted. + * Build the live footer shown under the status display: how long until the + * next poll. While a fetch is in flight (`nextPollAt` is null) it reads + * "refreshing…". In quiet mode (geared at CI) the footer is omitted. */ - private buildStatusFooter( - realtimeEnabled: boolean, - realtimeConnected: boolean, - nextPollAt: null | number, - quiet: boolean, - ): string { - const parts: string[] = []; - - if (realtimeEnabled) { - parts.push( - realtimeConnected - ? colors.success('● realtime connected') - : colors.warning('○ realtime connecting…'), - ); + private buildStatusFooter(nextPollAt: null | number, quiet: boolean): string { + if (quiet) { + return ''; } - // The countdown to the next backstop poll is noise in quiet mode (geared at - // CI), so suppress it there while keeping the realtime indicator. - if (!quiet) { - if (nextPollAt === null) { - parts.push(colors.dim('refreshing…')); - } else { - const secondsLeft = Math.max(0, Math.ceil((nextPollAt - Date.now()) / 1000)); - parts.push(colors.dim(`next refresh in ${secondsLeft}s`)); - } + if (nextPollAt === null) { + return colors.dim('refreshing…'); } - return parts.join(colors.dim(' · ')); + const secondsLeft = Math.max(0, Math.ceil((nextPollAt - Date.now()) / 1000)); + return colors.dim(`next refresh in ${secondsLeft}s`); } } diff --git a/src/types/domain/auth.types.ts b/src/types/domain/auth.types.ts index 716029e..a6eab1b 100644 --- a/src/types/domain/auth.types.ts +++ b/src/types/domain/auth.types.ts @@ -8,8 +8,8 @@ export interface AuthContext { headers: Record; mode: 'apiKey' | 'bearer'; /** - * Supabase JWT — present when mode === 'bearer'. Lets realtime subscriptions - * authenticate the socket (RLS) without re-reading the session from disk. + * Supabase JWT — present when mode === 'bearer'. Kept beside the headers so + * a refresh can swap it without re-reading the session from disk. */ accessToken?: string; /** Environment the session belongs to — present when mode === 'bearer'. */ diff --git a/test/unit/results-poll-cache.test.ts b/test/unit/results-poll-cache.test.ts index e24a981..8fca80a 100644 --- a/test/unit/results-poll-cache.test.ts +++ b/test/unit/results-poll-cache.test.ts @@ -192,7 +192,7 @@ describe('results poll: summary view and ETag revalidation', () => { ); const service = new ResultsPollingService(); // Poll back to back instead of every 20s. - (service as unknown as { APIKEY_POLL_INTERVAL_MS: number }).APIKEY_POLL_INTERVAL_MS = 0; + (service as unknown as { POLL_INTERVAL_MS: number }).POLL_INTERVAL_MS = 0; const logs: string[] = []; const result = await service.pollUntilComplete({ diff --git a/test/unit/session-refresh.test.ts b/test/unit/session-refresh.test.ts index a0cf242..dc468fa 100644 --- a/test/unit/session-refresh.test.ts +++ b/test/unit/session-refresh.test.ts @@ -8,7 +8,6 @@ import { CliAuthGateway, SessionRefreshError, } from '../../src/gateways/cli-auth-gateway.js'; -import { RealtimeResultsGateway } from '../../src/gateways/realtime-gateway.js'; import { clearContextCache, getContext } from '../../src/mcp/context.js'; import { ReportDownloadService } from '../../src/services/report-download.service.js'; import { @@ -34,7 +33,6 @@ const ORIGINAL_ENV = { ...process.env }; const realNow = Date.now; const realRefresh = CliAuthGateway.refresh; const realGetResults = ApiGateway.getResultsForUpload; -const realSubscribe = RealtimeResultsGateway.subscribe; const realFetch = (global as any).fetch; const nowSeconds = () => Math.floor(Date.now() / 1000); @@ -97,7 +95,6 @@ describe('session refresh for long-running processes', () => { Date.now = realNow; CliAuthGateway.refresh = realRefresh; ApiGateway.getResultsForUpload = realGetResults; - RealtimeResultsGateway.subscribe = realSubscribe; (global as any).fetch = realFetch; clearContextCache(); process.env = { ...ORIGINAL_ENV }; @@ -250,22 +247,6 @@ describe('session refresh for long-running processes', () => { return seen; } - /** Stand in for the Supabase socket and record the tokens it is handed. */ - function stubRealtime(): { joinedWith: string[]; updatedTo: string[] } { - const calls = { joinedWith: [] as string[], updatedTo: [] as string[] }; - RealtimeResultsGateway.subscribe = (options) => { - calls.joinedWith.push(options.accessToken); - return { - isConnected: () => false, - async unsubscribe() {}, - updateAccessToken(token: string) { - calls.updatedTo.push(token); - }, - }; - }; - return calls; - } - const poll = (auth: AuthContext, service = new ResultsPollingService()) => service.pollUntilComplete({ auth, @@ -275,10 +256,9 @@ describe('session refresh for long-running processes', () => { uploadId: 'u1', }); - it('polls with a refreshed token, and hands it to the realtime socket', async () => { + it('polls with a refreshed token', async () => { storeSession('fresh', 3600, '99'); const seen = stubResults(); - const realtime = stubRealtime(); const result = await poll(expiredBearer('stale', '42')); @@ -287,8 +267,6 @@ describe('session refresh for long-running processes', () => { // identity headers (dcd#1622), which this test is not about. expect(seen).to.have.length(1); expect(seen[0]).to.include({ authorization: 'Bearer fresh', 'x-dcd-org': '42' }); - expect(realtime.joinedWith).to.deep.equal(['stale']); - expect(realtime.updatedTo).to.deep.equal(['fresh']); }); it('leaves API-key polling exactly as it was', async () => { @@ -299,7 +277,6 @@ describe('session refresh for long-running processes', () => { it('retries a refresh that failed on a network blip, like any failed poll', async () => { storeSession('stale', 10); - stubRealtime(); const seen = stubResults(); let attempts = 0; CliAuthGateway.refresh = async () => { @@ -326,7 +303,6 @@ describe('session refresh for long-running processes', () => { it('stops at once, with a reconnect hint, when only `dcd login` can help', async () => { storeSession('stale', 10); - stubRealtime(); const seen = stubResults(); CliAuthGateway.refresh = async () => { throw new SessionRefreshError( @@ -357,7 +333,6 @@ describe('session refresh for long-running processes', () => { it('leads with the expiry when the session passed its limit', async () => { storeSession('stale', 10); - stubRealtime(); stubResults(); CliAuthGateway.refresh = async () => { throw new SessionRefreshError( From 25d09cab0f255ebfeadd74793a7984534126dbeb Mon Sep 17 00:00:00 2001 From: Tom Riglar Date: Thu, 12 Nov 2026 17:01:49 +0000 Subject: [PATCH 14/20] fix: treat dev-api.devicecloud.dev as the dev environment (#314) The dev API is now at dev-api.devicecloud.dev. Make it the dev apiUrl and keep api.dev.devicecloud.dev as a legacy URL, so saved configs and CI flags that name it still resolve to dev. inferEnvFromApiUrl only recognised 'api.dev.', so a dev-api URL fell through to prod and the Supabase copy of an upload would target the prod project. Both hostnames now map to dev. Co-authored-by: Claude Opus 5.5 --- src/config/environments.ts | 33 +++++++++++++++++++++----- test/unit/environments.test.ts | 42 ++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 6 deletions(-) create mode 100644 test/unit/environments.test.ts diff --git a/src/config/environments.ts b/src/config/environments.ts index 1d79cd7..07b8509 100644 --- a/src/config/environments.ts +++ b/src/config/environments.ts @@ -13,6 +13,12 @@ export type DcdEnvName = 'dev' | 'prod'; export interface DcdEnvironment { apiUrl: string; + /** + * Older API URLs that still reach this environment. A config saved by an + * earlier `dcd login`, or a `--api-url` in someone's CI, may still name one, + * so it must keep resolving to this environment. + */ + legacyApiUrls?: string[]; frontendUrl: string; supabase: { url: string; @@ -30,7 +36,8 @@ export const ENVIRONMENTS: Record = { }, }, dev: { - apiUrl: 'https://api.dev.devicecloud.dev', + apiUrl: 'https://dev-api.devicecloud.dev', + legacyApiUrls: ['https://api.dev.devicecloud.dev'], frontendUrl: 'https://dev.console.devicecloud.dev', supabase: { url: 'https://lbmsowehtjwnqlurpemb.supabase.co', @@ -39,18 +46,32 @@ export const ENVIRONMENTS: Record = { }, }; -/** Exact-match lookup of a known environment by API URL (trailing slashes ignored). */ +/** + * Exact-match lookup of a known environment by API URL, current or legacy + * (trailing slashes ignored). + */ export function findEnvByApiUrl(apiUrl: string): DcdEnvironment | undefined { const normalize = (u: string) => u.replace(/\/+$/, ''); const needle = normalize(apiUrl); - return Object.values(ENVIRONMENTS).find( - (env) => normalize(env.apiUrl) === needle, + return Object.values(ENVIRONMENTS).find((env) => + [env.apiUrl, ...(env.legacyApiUrls ?? [])].some((u) => normalize(u) === needle), ); } -/** Map a caller-supplied API URL to one of the known environments. */ +/** + * Map a caller-supplied API URL to one of the known environments. This picks + * the Supabase project uploads go to, so a dev URL must never fall through to + * prod: both dev hostnames (`dev-api.` and the older `api.dev.`) and + * localhost are dev. + */ export function inferEnvFromApiUrl(apiUrl: string): DcdEnvName { - if (apiUrl.includes('api.dev.') || apiUrl.includes('localhost')) return 'dev'; + if ( + apiUrl.includes('dev-api.') || + apiUrl.includes('api.dev.') || + apiUrl.includes('localhost') + ) { + return 'dev'; + } return 'prod'; } diff --git a/test/unit/environments.test.ts b/test/unit/environments.test.ts new file mode 100644 index 0000000..d5461ac --- /dev/null +++ b/test/unit/environments.test.ts @@ -0,0 +1,42 @@ +import { expect } from 'chai'; +import { + ENVIRONMENTS, + findEnvByApiUrl, + inferEnvFromApiUrl, + resolveFrontendUrl, +} from '../../src/config/environments.js'; + +/** + * The dev API answers on two hostnames: `dev-api.devicecloud.dev` (current) + * and `api.dev.devicecloud.dev` (older). Both must resolve to dev. A dev URL + * that fell through to prod would send uploads to the prod Supabase project. + */ +describe('environments', () => { + const DEV_URLS = [ + 'https://dev-api.devicecloud.dev', + 'https://dev-api.devicecloud.dev/', + 'https://api.dev.devicecloud.dev', + 'https://api.dev.devicecloud.dev/', + ]; + + it('treats both dev hostnames as dev', () => { + for (const url of DEV_URLS) { + expect(inferEnvFromApiUrl(url), url).to.equal('dev'); + expect(findEnvByApiUrl(url), url).to.equal(ENVIRONMENTS.dev); + expect(resolveFrontendUrl(url), url).to.equal('https://dev.console.devicecloud.dev'); + } + }); + + it('uses dev-api as the dev API URL', () => { + expect(ENVIRONMENTS.dev.apiUrl).to.equal('https://dev-api.devicecloud.dev'); + }); + + it('keeps prod as prod', () => { + expect(inferEnvFromApiUrl('https://api.devicecloud.dev')).to.equal('prod'); + expect(findEnvByApiUrl('https://api.devicecloud.dev')).to.equal(ENVIRONMENTS.prod); + }); + + it('treats localhost as dev', () => { + expect(inferEnvFromApiUrl('http://localhost:8000')).to.equal('dev'); + }); +}); From e4d3f07388dc0964a0f51e87d311a67976568f5e Mon Sep 17 00:00:00 2001 From: Tom Riglar Date: Fri, 13 Nov 2026 10:59:26 +0000 Subject: [PATCH 15/20] chore: release 5.13.0 --- CHANGELOG.md | 28 ++++++++++++++++++++++++++++ package.json | 2 +- server.json | 4 ++-- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a1fe84..a030fb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,33 @@ # Changelog +## [5.13.0](https://github.com/devicecloud-dev/dcd-cli/compare/v5.12.0...v5.13.0) (2026-11-13) + + +### Features + +* drop iPhone 16 Pro Max and gpu1 from help text (removed 9 Nov 2026) ([#302](https://github.com/devicecloud-dev/dcd-cli/issues/302)) ([55fb4a1](https://github.com/devicecloud-dev/dcd-cli/commit/55fb4a196a086c4346f554e1c28633b70113e396)) +* **auth:** say when a dcd login session has expired ([#303](https://github.com/devicecloud-dev/dcd-cli/issues/303)) ([9fafa2f](https://github.com/devicecloud-dev/dcd-cli/commit/9fafa2f62347dd77debd46874d59bd599abc358b)) +* **device:** tap, type, swipe and press-key subcommands ([#310](https://github.com/devicecloud-dev/dcd-cli/issues/310)) ([12f4da5](https://github.com/devicecloud-dev/dcd-cli/commit/12f4da5dc1d2b742239f2a6c0ae4d669c978d9f3)) +* **mcp:** set up Codex with dcd mcp install, and document every hosted client ([#306](https://github.com/devicecloud-dev/dcd-cli/issues/306)) ([dab495b](https://github.com/devicecloud-dev/dcd-cli/commit/dab495bf501059b2866ead21603b3693ae14dcbc)) + + +### Bug Fixes + +* treat dev-api.devicecloud.dev as the dev environment ([#314](https://github.com/devicecloud-dev/dcd-cli/issues/314)) ([25d09ca](https://github.com/devicecloud-dev/dcd-cli/commit/25d09cab0f255ebfeadd74793a7984534126dbeb)) +* **device:** keep a missing --text on `type` inside the --json envelope ([#311](https://github.com/devicecloud-dev/dcd-cli/issues/311)) ([9f16ca2](https://github.com/devicecloud-dev/dcd-cli/commit/9f16ca2dfc3159b827c1447c3e9287933eff2de8)) +* **mcp:** find code and claude .cmd shims on Windows ([#286](https://github.com/devicecloud-dev/dcd-cli/issues/286)) ([18efa4f](https://github.com/devicecloud-dev/dcd-cli/commit/18efa4f3309d8a7d2719720c10e3195bc708ad2d)) +* **mcp:** say why a tool is missing in read-only mode ([#307](https://github.com/devicecloud-dev/dcd-cli/issues/307)) ([9a54e3a](https://github.com/devicecloud-dev/dcd-cli/commit/9a54e3a21b3175fd67158dc68be071099b7c8cb7)) + + +### Dependencies + +* bump @supabase/supabase-js from 2.118.0 to 2.119.0 in the minor-and-patch group across 1 directory ([#304](https://github.com/devicecloud-dev/dcd-cli/issues/304)) ([f5db0b0](https://github.com/devicecloud-dev/dcd-cli/commit/f5db0b0376ba1b07f15ba6d5dfb5b3065cfbd0f7)) + + +### Code Refactoring + +* **auth:** stop calling Supabase directly for logout, login checks and live status ([#312](https://github.com/devicecloud-dev/dcd-cli/issues/312)) ([14ae83d](https://github.com/devicecloud-dev/dcd-cli/commit/14ae83dc50018ac70a1a5d7ed4c75fd854e3e0c6)) + ## [5.12.0](https://github.com/devicecloud-dev/dcd-cli/compare/v5.11.1...v5.12.0) (2026-11-06) diff --git a/package.json b/package.json index 0833a58..4addfef 100644 --- a/package.json +++ b/package.json @@ -68,7 +68,7 @@ "test:unit": "node scripts/test-runner.mjs --unit", "typecheck": "tsc --noEmit -p tsconfig.test.json" }, - "version": "5.12.0", + "version": "5.13.0", "bugs": { "url": "https://discord.gg/gm3mJwcNw8" }, diff --git a/server.json b/server.json index 59520c2..d713cc5 100644 --- a/server.json +++ b/server.json @@ -2,7 +2,7 @@ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "name": "dev.devicecloud/dcd", "description": "Run Maestro mobile app tests on devicecloud.dev: submit flows, check status, download artifacts.", - "version": "5.12.0", + "version": "5.13.0", "repository": { "url": "https://github.com/devicecloud-dev/dcd-cli", "source": "github" @@ -11,7 +11,7 @@ { "registryType": "npm", "identifier": "@devicecloud.dev/dcd", - "version": "5.12.0", + "version": "5.13.0", "runtimeHint": "npx", "runtimeArguments": [ { From 84dd84233f5ebc9dd2b6d74aca08c30b04e11e41 Mon Sep 17 00:00:00 2001 From: Tom Riglar Date: Fri, 13 Nov 2026 11:12:05 +0000 Subject: [PATCH 16/20] deps: raise the hono override to 4.13.16 for new moderate advisories (#316) Co-authored-by: Claude Opus 5.5 --- package.json | 2 +- pnpm-lock.yaml | 22 +++++++++++----------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/package.json b/package.json index 0833a58..ec3e3d6 100644 --- a/package.json +++ b/package.json @@ -111,7 +111,7 @@ "esbuild@<0.28.1": ">=0.28.1", "qs@<6.16.1": "6.16.1", "fast-uri@>=3.0.0 <3.1.9": "3.1.9", - "hono@>=4.0.0 <4.13.11": "4.13.11", + "hono@>=4.0.0 <4.13.16": "4.13.16", "source-map-js@<1.2.2": "1.2.2", "micromatch>picomatch": "^2.3.2", "tinyglobby>picomatch": "^4.0.4" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3a7ad7a..4734621 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -32,7 +32,7 @@ overrides: esbuild@<0.28.1: '>=0.28.1' qs@<6.16.1: 6.16.1 fast-uri@>=3.0.0 <3.1.9: 3.1.9 - hono@>=4.0.0 <4.13.11: 4.13.11 + hono@>=4.0.0 <4.13.16: 4.13.16 source-map-js@<1.2.2: 1.2.2 micromatch>picomatch: ^2.3.2 tinyglobby>picomatch: ^4.0.4 @@ -348,11 +348,11 @@ packages: resolution: {integrity: sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} - '@hono/node-server@2.1.5': - resolution: {integrity: sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==} + '@hono/node-server@2.1.8': + resolution: {integrity: sha512-jdf7FHh6A1lzjpHHQUgxsg2GeER2vMetnAOfeActzcoli6jamlK+NAwL6Dsr5Fl3BS3tYUQzCdtZjU8Qxv7bEA==} engines: {node: '>=20'} peerDependencies: - hono: 4.13.11 + hono: 4.13.16 '@humanfs/core@0.19.2': resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} @@ -1004,8 +1004,8 @@ packages: resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} engines: {node: '>= 0.4'} - hono@4.13.11: - resolution: {integrity: sha512-/SMX/RQNJn7oNmFwH6DtwDqcrzZU2otm1FD6OJe2cWF6cfy/F8hq0XVBv7xW3FTJshRQwuBnXHDq2kNsdZnshg==} + hono@4.13.16: + resolution: {integrity: sha512-AOLOEhvrV+iH92xXCnFr/5+3KjPKcI3xP63XJtX5spAnkznPdHijlIsUTpi7/9EhWqrTCekw5c5zh1K+YsVw7A==} engines: {node: '>=16.9.0'} hookified@1.15.1: @@ -1858,9 +1858,9 @@ snapshots: '@eslint/core': 1.2.1 levn: 0.4.1 - '@hono/node-server@2.1.5(hono@4.13.11)': + '@hono/node-server@2.1.8(hono@4.13.16)': dependencies: - hono: 4.13.11 + hono: 4.13.16 '@humanfs/core@0.19.2': dependencies: @@ -1894,7 +1894,7 @@ snapshots: '@modelcontextprotocol/sdk@1.32.2(zod@4.6.7)': dependencies: - '@hono/node-server': 2.1.5(hono@4.13.11) + '@hono/node-server': 2.1.8(hono@4.13.16) ajv: 8.20.0 ajv-formats: 3.0.1(ajv@8.20.0) content-type: 1.0.5 @@ -1904,7 +1904,7 @@ snapshots: eventsource-parser: 3.1.1 express: 5.3.0 express-rate-limit: 8.7.2(express@5.3.0) - hono: 4.13.11 + hono: 4.13.16 jose: 6.2.14 json-schema-typed: 8.0.2 pkce-challenge: 5.0.1 @@ -2612,7 +2612,7 @@ snapshots: dependencies: function-bind: 1.1.2 - hono@4.13.11: {} + hono@4.13.16: {} hookified@1.15.1: {} From 07df10717c556b212caf7e233a0850142d20d92a Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:45:55 +0000 Subject: [PATCH 17/20] =?UTF-8?q?fix(device):=20make=20--maestro=20a=20no-?= =?UTF-8?q?op=20now=20that=20device=20sessions=20have=20one=E2=80=A6=20(#3?= =?UTF-8?q?17)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix(device): make --maestro a no-op now that device sessions have one engine Device sessions run on a single engine (agent-device) and no longer on Maestro, so there is no second path for a typed action to ask for. `--maestro` on `dcd device tap|type|swipe|press-key` is still accepted, so scripts that pass it keep working, but it is no longer sent to the API (which accepts `mode: "maestro"` and ignores it) and its help says so. `dcd device run` still takes Maestro YAML. Its help now says a device session runs the common Maestro commands and no flow scripts. --- src/commands/device.ts | 20 +++++++++++++------- src/types/domain/device-session.types.ts | 5 +++-- test/unit/device-command.test.ts | 7 ++++--- 3 files changed, 20 insertions(+), 12 deletions(-) diff --git a/src/commands/device.ts b/src/commands/device.ts index eb96746..db11dfb 100644 --- a/src/commands/device.ts +++ b/src/commands/device.ts @@ -718,11 +718,15 @@ const launchSub = defineCommand({ }, }); -/** Shared by the typed-action subcommands: the Maestro switch. */ +/** + * Shared by the typed-action subcommands. It chose Maestro over the device's + * direct path when a device session had two engines. It has one now, so the + * flag is still taken, for scripts that pass it, and does nothing. + */ const maestroArg = { type: 'boolean', default: false, - description: 'Run the action as a Maestro flow instead of directly on the device', + 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. */ @@ -755,10 +759,7 @@ 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, - ...(args.maestro ? { mode: 'maestro' as const } : {}), - }); + const { result, session } = await DeviceGateway.action(ctx.apiUrl, ctx.auth, sessionId, body); return { session, data: { result } as { result: DeviceCommandResult }, @@ -1087,7 +1088,12 @@ async function waitForCommand(ctx: Ctx, id: string, commandId: string): Promise< } const runSub = defineCommand({ - meta: { name: 'run', description: 'Run a Maestro flow (or a directory of flows) on the device, and wait for the result' }, + meta: { + name: 'run', + description: + 'Run a Maestro flow (or a directory of flows) on the device, and wait for the result. ' + + 'A device session runs the common Maestro commands and no flow scripts (runScript, evalScript)', + }, args: { ...commonArgs, id: idArg, diff --git a/src/types/domain/device-session.types.ts b/src/types/domain/device-session.types.ts index 993539a..774b978 100644 --- a/src/types/domain/device-session.types.ts +++ b/src/types/domain/device-session.types.ts @@ -125,8 +125,9 @@ export interface DevicePoint { } /** - * One typed action for POST /device/sessions/:id/actions. `mode: 'maestro'` - * runs it as a Maestro flow instead of on the device directly. + * One typed action for POST /device/sessions/:id/actions. `mode` is + * deprecated: the API still accepts `'maestro'` and ignores it, and the CLI + * no longer sends it. */ export type DeviceActionRequest = | { id?: string; mode?: 'maestro'; text?: string; type: 'tap'; x?: number; y?: number } diff --git a/test/unit/device-command.test.ts b/test/unit/device-command.test.ts index 00f33f0..cf2529c 100644 --- a/test/unit/device-command.test.ts +++ b/test/unit/device-command.test.ts @@ -324,10 +324,11 @@ describe('dcd device', () => { expect(calls).to.have.length(0); }); - it('--maestro asks for the Maestro path', async () => { + it('--maestro is still accepted and changes nothing: device sessions have one engine', async () => { const calls = stubFetch(ok); - await runJson('tap', { id: 'a-b-c', text: 'OK', maestro: true }); - expect(calls[0].body).to.deep.equal({ type: 'tap', text: 'OK', mode: 'maestro' }); + const { exit } = await runJson('tap', { id: 'a-b-c', text: 'OK', maestro: true }); + expect(exit).to.equal(0); + expect(calls[0].body).to.deep.equal({ type: 'tap', text: 'OK' }); }); it('type sends the text, sensitive when asked, and keeps it out of the envelope', async () => { From adc276966b982d392f774ffe4be4143718bdb6d6 Mon Sep 17 00:00:00 2001 From: Tom Riglar Date: Fri, 13 Nov 2026 12:33:57 +0000 Subject: [PATCH 18/20] ci: resolve version-file conflicts in the back-merge to production's side (#320) * ci: resolve version-file conflicts in the back-merge to production's side Co-Authored-By: Claude Opus 5.5 * ci: resolve back-merge version conflicts hunk by hunk, keeping dev's other edits Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .github/workflows/release-please.yml | 30 +++++++++++++++++++++++++--- CLAUDE.md | 2 +- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 9404984..7b941fc 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -146,10 +146,34 @@ jobs: git checkout -b "$BRANCH" # A merge, so the PR's diff is exactly what `production` changed. + # + # The version files can conflict: the last back-merge was squashed, + # so git still sees dev's and production's version lines as two + # separate edits (5.12.1 hit this). `production` holds what was just + # released, so its side is right for those three files. Any other + # conflict still stops the job for a human. if ! git merge --no-ff origin/production -m "chore: merge production into dev after ${VERSION}"; then - echo "Back-merge of production into dev conflicts — resolve it by hand." >&2 - git merge --abort || true - exit 1 + conflicts=$(git diff --name-only --diff-filter=U) + others=$(grep -vxE 'package\.json|server\.json|CHANGELOG\.md' <<<"$conflicts" || true) + if [ -n "$others" ]; then + echo "::error::Back-merge of production into dev conflicts in $(paste -sd, - <<<"$others"). Resolve it by hand." + git merge --abort || true + exit 1 + fi + # Hunk by hunk, not `checkout --theirs`: that would take production's + # whole file and drop anything else dev changed in it, such as a + # dependency bump in package.json. + # merge-file needs real files; it can't read process substitutions. + tmp=$(mktemp -d) + for f in $conflicts; do + git show ":1:$f" > "$tmp/base" + git show ":2:$f" > "$tmp/ours" + git show ":3:$f" > "$tmp/theirs" + git merge-file -p --theirs "$tmp/ours" "$tmp/base" "$tmp/theirs" > "$f" + done + echo "::notice::Took production's side of the conflicting lines in: $(paste -sd, - <<<"$conflicts")" + git add -- $conflicts + git commit --no-edit fi if git diff --quiet "origin/dev..HEAD"; then diff --git a/CLAUDE.md b/CLAUDE.md index 570d0d8..c73acc9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -80,7 +80,7 @@ Full guide in `CONTRIBUTING.md`; the operationally important parts (the ones tha | **stable** | every push to `dev` runs **Promote to stable** (`promote.yml`), which keeps one release PR into `production` current; merging it tags, publishes and uploads binaries | `X.Y.Z` | `latest` | | **beta** | run **Release beta** (`release-beta.yml`) by hand from `dev` | `X.Y.Z-beta.N` | `beta` | -**Cutting a stable release.** You don't start one: you merge the open `chore: release X.Y.Z` PR from `promote/cli-next` into `production`. Use a **merge commit**, the only method `production` allows. That push runs `release-please.yml`. It finds an untagged version on `production`, tags it, and creates the GitHub Release from the changelog section. It then **chains** into `npm-publish.yml` and `release-binaries.yml` as `needs:` jobs, because a `GITHUB_TOKEN`-created release won't fire `release: published`. Last, it opens a **back-merge PR** into `dev`. `get.devicecloud.dev` serves the binaries by reading the GitHub Releases API at runtime, so there's no separate manifest to deploy. To hold a release, just don't merge the PR. Closing it doesn't pause releases, because the next push to `dev` opens a new one. +**Cutting a stable release.** You don't start one: you merge the open `chore: release X.Y.Z` PR from `promote/cli-next` into `production`. Use a **merge commit**, the only method `production` allows. That push runs `release-please.yml`. It finds an untagged version on `production`, tags it, and creates the GitHub Release from the changelog section. It then **chains** into `npm-publish.yml` and `release-binaries.yml` as `needs:` jobs, because a `GITHUB_TOKEN`-created release won't fire `release: published`. Last, it opens a **back-merge PR** into `dev`. If that merge conflicts only in `package.json`, `server.json` or `CHANGELOG.md`, it takes `production`'s side, which holds the version just released. A conflict in any other file stops the job, and you build the back-merge by hand. `get.devicecloud.dev` serves the binaries by reading the GitHub Releases API at runtime, so there's no separate manifest to deploy. To hold a release, just don't merge the PR. Closing it doesn't pause releases, because the next push to `dev` opens a new one. **How the release PR is kept current.** `promote.yml` runs on every push to `dev`. It rebuilds `promote/cli-next` from `origin/dev`, with `origin/production` merged in, plus one `chore: release X.Y.Z` commit that sets the version in `package.json` and `server.json` and adds the `CHANGELOG.md` section. Then it force-pushes the branch and opens the PR, or updates the open one's title and body. So the PR always carries all of `dev`, and its version moves up as `feat`s land. A push with nothing releasable since the last release, such as a docs change or the back-merge, does nothing. If `production` moved during the run because a release just merged, the run pushes nothing, and the back-merge's push into `dev` rebuilds the PR. If an open PR into `production` came from another branch, push runs warn and leave it alone. The workflow can also be run by hand (`gh workflow run promote.yml --ref dev`, or the Actions tab) to set the `version`. `dry_run: true` shows the version and changelog in the run summary and pushes nothing. The `CHANGELOG.md` date is the day the PR was last rebuilt. From 68a8250e271e3f13394197350b1f97202424d4a5 Mon Sep 17 00:00:00 2001 From: Tom Riglar Date: Fri, 13 Nov 2026 12:34:25 +0000 Subject: [PATCH 19/20] chore: merge production into dev after 5.12.1 (#319) * chore: pin the 5.12.0 promotion Release-As: 5.12.0 * chore(production): release 5.12.0 * ci: Replace release-please with a custom version that handles our dev -> prod flow (#305) * ci: cut a stable release with one workflow run and one PR A stable release used to take a hand-built promotion branch (dev, a merge of production, and an empty Release-As pin commit), a promotion PR, then release-please's own Release PR, then the back-merge PR. A new "Promote to stable" workflow (promote.yml) now builds the release branch: dev, with production merged in, plus one commit that sets the version in package.json and server.json and adds the CHANGELOG.md section. It opens that as the only PR into production. Merging it is the release: the Release workflow tags the untagged version, creates the GitHub Release from the changelog section, and publishes npm, the binaries and the back-merge as before. scripts/stable-release.mjs derives the version from the Conventional Commit PR titles since the last release, as release-please did, but never derives a major: a breaking marker stops the run until the version is given explicitly. Its changelog lists each PR once, using the full title when GitHub cut it short, where release-please listed such PRs twice. Production is merged in on every run because dev only allows squash merges, so the back-merge can never make production an ancestor of dev. release-please, its config and manifest, and the Release-As promotion-pin check are removed. A release-check job verifies every PR into production instead. Release PRs skip claude-review, like back-merge PRs, because the review action rejects bot actors. The Release workflow keeps the release-please.yml filename, because npm's trusted publisher is registered against it. * ci: keep the stable release PR open and current on every push to dev Promote to stable now also runs on every push to dev. It rebuilds one fixed branch, promote/cli-next, and opens the release PR into production or updates the open one, so the PR always carries all of dev with the version and changelog to match. Nothing ships until someone merges it. - A push with nothing releasable since the last release (docs, the back-merge) does nothing. - A version set by hand is kept on later runs (plan --keep) whenever it is above the derived one, so a major has to be given only once, and a breaking marker still never derives one. - If production moved during the run, nothing is pushed; the back-merge push rebuilds the PR. The force-push is leased against the branch tip the run saw, and skipped when the content is unchanged. - A PR into production from any other branch is left alone: push runs warn and stop. (cherry picked from commit 6bebbefd6c94df0191a72f0b5648c18951e3829d) * ci: lint PR titles on pull_request instead of pull_request_target (#308) GitHub blocks pull_request_target by default in public repositories from 2026-12-02. The PR title check only reads the event payload, so it runs on pull_request, which also fires for fork PRs with a read-only token. The CLA workflow has to write to fork PRs, so it stays on pull_request_target. A repository Actions policy allows that trigger for cla.yml only. Its header now says so. (cherry picked from commit 02d99b9274b7b8b4659bda94c2b94a7f14998fbd) * fix: treat dev-api.devicecloud.dev as the dev environment (#314) The dev API is now at dev-api.devicecloud.dev. Make it the dev apiUrl and keep api.dev.devicecloud.dev as a legacy URL, so saved configs and CI flags that name it still resolve to dev. inferEnvFromApiUrl only recognised 'api.dev.', so a dev-api URL fell through to prod and the Supabase copy of an upload would target the prod project. Both hostnames now map to dev. Co-authored-by: Claude Opus 5.5 (cherry picked from commit 25d09cab0f255ebfeadd74793a7984534126dbeb) * deps: raise the hono override to 4.13.16 for new moderate advisories Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 2476581042ff4a8b4c31bd3e40d9618fd810f31c) * chore: release 5.12.1 --------- Co-authored-by: finalerock44 Co-authored-by: finalerock44 <77282157+finalerock44@users.noreply.github.com> Co-authored-by: dcd-release-please[bot] <296541543+dcd-release-please[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 12 ++++++++++++ package.json | 2 +- server.json | 4 ++-- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a1fe84..685c55a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## [5.12.1](https://github.com/devicecloud-dev/dcd-cli/compare/v5.12.0...v5.12.1) (2026-11-13) + + +### Bug Fixes + +* treat dev-api.devicecloud.dev as the dev environment ([#314](https://github.com/devicecloud-dev/dcd-cli/issues/314)) ([d65131f](https://github.com/devicecloud-dev/dcd-cli/commit/d65131f8d11db684c3c66cfb46287b9b8dbda80b)) + + +### Dependencies + +* raise the hono override to 4.13.16 for new moderate advisories ([bcbcc2f](https://github.com/devicecloud-dev/dcd-cli/commit/bcbcc2ff6296b9e2bfe42acaf691b9ebf8efac47)) + ## [5.12.0](https://github.com/devicecloud-dev/dcd-cli/compare/v5.11.1...v5.12.0) (2026-11-06) diff --git a/package.json b/package.json index ec3e3d6..a4f2a5d 100644 --- a/package.json +++ b/package.json @@ -68,7 +68,7 @@ "test:unit": "node scripts/test-runner.mjs --unit", "typecheck": "tsc --noEmit -p tsconfig.test.json" }, - "version": "5.12.0", + "version": "5.12.1", "bugs": { "url": "https://discord.gg/gm3mJwcNw8" }, diff --git a/server.json b/server.json index 59520c2..598d447 100644 --- a/server.json +++ b/server.json @@ -2,7 +2,7 @@ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "name": "dev.devicecloud/dcd", "description": "Run Maestro mobile app tests on devicecloud.dev: submit flows, check status, download artifacts.", - "version": "5.12.0", + "version": "5.12.1", "repository": { "url": "https://github.com/devicecloud-dev/dcd-cli", "source": "github" @@ -11,7 +11,7 @@ { "registryType": "npm", "identifier": "@devicecloud.dev/dcd", - "version": "5.12.0", + "version": "5.12.1", "runtimeHint": "npx", "runtimeArguments": [ { From 6ad06a3e66dc5f1de30887b45f8b1454a961dca0 Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Fri, 13 Nov 2026 17:11:54 +0000 Subject: [PATCH 20/20] chore: release 5.13.0 --- CHANGELOG.md | 28 ++++++++++++++++++++++++++++ package.json | 2 +- server.json | 4 ++-- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 685c55a..a454e6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,33 @@ # Changelog +## [5.13.0](https://github.com/devicecloud-dev/dcd-cli/compare/v5.12.1...v5.13.0) (2026-11-13) + + +### Features + +* drop iPhone 16 Pro Max and gpu1 from help text (removed 9 Nov 2026) ([#302](https://github.com/devicecloud-dev/dcd-cli/issues/302)) ([55fb4a1](https://github.com/devicecloud-dev/dcd-cli/commit/55fb4a196a086c4346f554e1c28633b70113e396)) +* **auth:** say when a dcd login session has expired ([#303](https://github.com/devicecloud-dev/dcd-cli/issues/303)) ([9fafa2f](https://github.com/devicecloud-dev/dcd-cli/commit/9fafa2f62347dd77debd46874d59bd599abc358b)) +* **device:** tap, type, swipe and press-key subcommands ([#310](https://github.com/devicecloud-dev/dcd-cli/issues/310)) ([12f4da5](https://github.com/devicecloud-dev/dcd-cli/commit/12f4da5dc1d2b742239f2a6c0ae4d669c978d9f3)) +* **mcp:** set up Codex with dcd mcp install, and document every hosted client ([#306](https://github.com/devicecloud-dev/dcd-cli/issues/306)) ([dab495b](https://github.com/devicecloud-dev/dcd-cli/commit/dab495bf501059b2866ead21603b3693ae14dcbc)) + + +### Bug Fixes + +* **device:** keep a missing --text on `type` inside the --json envelope ([#311](https://github.com/devicecloud-dev/dcd-cli/issues/311)) ([9f16ca2](https://github.com/devicecloud-dev/dcd-cli/commit/9f16ca2dfc3159b827c1447c3e9287933eff2de8)) +* **device:** make --maestro a no-op now that device sessions have one engine ([#317](https://github.com/devicecloud-dev/dcd-cli/issues/317)) ([07df107](https://github.com/devicecloud-dev/dcd-cli/commit/07df10717c556b212caf7e233a0850142d20d92a)) +* **mcp:** find code and claude .cmd shims on Windows ([#286](https://github.com/devicecloud-dev/dcd-cli/issues/286)) ([18efa4f](https://github.com/devicecloud-dev/dcd-cli/commit/18efa4f3309d8a7d2719720c10e3195bc708ad2d)) +* **mcp:** say why a tool is missing in read-only mode ([#307](https://github.com/devicecloud-dev/dcd-cli/issues/307)) ([9a54e3a](https://github.com/devicecloud-dev/dcd-cli/commit/9a54e3a21b3175fd67158dc68be071099b7c8cb7)) + + +### Dependencies + +* bump @supabase/supabase-js from 2.118.0 to 2.119.0 in the minor-and-patch group across 1 directory ([#304](https://github.com/devicecloud-dev/dcd-cli/issues/304)) ([f5db0b0](https://github.com/devicecloud-dev/dcd-cli/commit/f5db0b0376ba1b07f15ba6d5dfb5b3065cfbd0f7)) + + +### Code Refactoring + +* **auth:** stop calling Supabase directly for logout, login checks and live status ([#312](https://github.com/devicecloud-dev/dcd-cli/issues/312)) ([14ae83d](https://github.com/devicecloud-dev/dcd-cli/commit/14ae83dc50018ac70a1a5d7ed4c75fd854e3e0c6)) + ## [5.12.1](https://github.com/devicecloud-dev/dcd-cli/compare/v5.12.0...v5.12.1) (2026-11-13) diff --git a/package.json b/package.json index a4f2a5d..638ccaf 100644 --- a/package.json +++ b/package.json @@ -68,7 +68,7 @@ "test:unit": "node scripts/test-runner.mjs --unit", "typecheck": "tsc --noEmit -p tsconfig.test.json" }, - "version": "5.12.1", + "version": "5.13.0", "bugs": { "url": "https://discord.gg/gm3mJwcNw8" }, diff --git a/server.json b/server.json index 598d447..d713cc5 100644 --- a/server.json +++ b/server.json @@ -2,7 +2,7 @@ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "name": "dev.devicecloud/dcd", "description": "Run Maestro mobile app tests on devicecloud.dev: submit flows, check status, download artifacts.", - "version": "5.12.1", + "version": "5.13.0", "repository": { "url": "https://github.com/devicecloud-dev/dcd-cli", "source": "github" @@ -11,7 +11,7 @@ { "registryType": "npm", "identifier": "@devicecloud.dev/dcd", - "version": "5.12.1", + "version": "5.13.0", "runtimeHint": "npx", "runtimeArguments": [ {