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/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/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. diff --git a/README.md b/README.md index ddb1fcb..646a023 100644 --- a/README.md +++ b/README.md @@ -36,30 +36,32 @@ 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. +`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) | +Install the CLI (see the top of this page), sign in, then add the server to your AI tool: -### `dcd mcp` +```sh-session +$ dcd login +$ 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. -`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. +### Headless, with an API key -**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: +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 -$ dcd login -$ dcd mcp install cursor # or claude-code, claude-desktop, vscode +$ claude mcp add --scope user devicecloud -e DEVICE_CLOUD_API_KEY="$DEVICE_CLOUD_API_KEY" -- dcd mcp ``` -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. +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 -**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 `~`. +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`): @@ -88,29 +90,42 @@ 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. -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. +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`. -**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). +### Tools -### Hosted +| 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**) | -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. +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. -```sh-session -$ claude mcp add --transport http devicecloud https://api.devicecloud.dev/mcp -``` +**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 { @@ -124,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/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/pnpm-lock.yaml b/pnpm-lock.yaml index ffdd80c..4734621 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: 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": [ { diff --git a/src/commands/cloud.ts b/src/commands/cloud.ts index 13870b4..9dd38ac 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, @@ -352,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/device.ts b/src/commands/device.ts index f23eaaf..db11dfb 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,202 @@ const launchSub = defineCommand({ }, }); +/** + * 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: '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. */ +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); + 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, + // 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, + 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: { @@ -887,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, @@ -1343,6 +1549,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/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/commands/mcp.ts b/src/commands/mcp.ts index be7cb71..f744a76 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, @@ -30,18 +31,25 @@ 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 = { '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.', }; /** 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() }; } @@ -84,6 +92,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 +130,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 +141,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 +198,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 +220,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/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/gateways/cli-auth-gateway.ts b/src/gateways/cli-auth-gateway.ts index 18caf9a..bee282e 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; @@ -88,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/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/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/mcp/bridge.ts b/src/mcp/bridge.ts index 91ee0f5..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 }> = { @@ -221,8 +227,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 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(new URL(`${apiUrl}/mcp`), { + new StreamableHTTPClientTransport(url, { fetch: async (url, init) => { const { auth } = await getContext(); const headers = new Headers(init?.headers); @@ -307,8 +317,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/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/services/results-polling.service.ts b/src/services/results-polling.service.ts index 04589ea..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 { @@ -628,22 +548,17 @@ 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}`, ); } 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; @@ -850,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. */ @@ -875,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/src/types/domain/device-session.types.ts b/src/types/domain/device-session.types.ts index ea4d063..774b978 100644 --- a/src/types/domain/device-session.types.ts +++ b/src/types/domain/device-session.types.ts @@ -117,6 +117,45 @@ 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` 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 } + | { 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/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/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/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/device-command.test.ts b/test/unit/device-command.test.ts index c656f28..cf2529c 100644 --- a/test/unit/device-command.test.ts +++ b/test/unit/device-command.test.ts @@ -293,6 +293,109 @@ 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 is still accepted and changes nothing: device sessions have one engine', async () => { + const calls = stubFetch(ok); + 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 () => { + 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('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(), + ); + 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) => diff --git a/test/unit/mcp-bridge.test.ts b/test/unit/mcp-bridge.test.ts index ead46a9..e946c73 100644 --- a/test/unit/mcp-bridge.test.ts +++ b/test/unit/mcp-bridge.test.ts @@ -28,12 +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, 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') { @@ -47,6 +56,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() || '{}'); @@ -62,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); @@ -155,6 +174,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(); }); @@ -243,10 +263,41 @@ 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']); + // 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(); + }); + + 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'; + 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(); }); 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", + ); }); }); 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/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'); + }); + }); +}); diff --git a/test/unit/session-refresh.test.ts b/test/unit/session-refresh.test.ts index 646f1a5..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,10 +303,13 @@ 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('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 +321,42 @@ 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); + 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); + }); + }); }); 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); + }); +});