# Midscene Contribution Guide Thanks for showing interest in contributing to Midscene. Before starting your contribution, please take a moment to read the following guidelines. --- ## Setup the Environment ### Fork the Repo [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local machine. ### Install Node.js We recommend using Node.js 20.19.0. You can check your currently used Node.js version with the following command: ```bash node -v ``` If you do not have Node.js installed in your current environment, you can use [nvm](https://github.com/nvm-sh/nvm) or [fnm](https://github.com/Schniz/fnm) to install it. Here is an example of how to install the Node.js 20.19.0 version via nvm: ```bash # Install the LTS version of Node.js 20 nvm install 20.19.0 --lts # Make the newly installed Node.js 20 as the default version nvm alias default 20.19.0 # Switch to the newly installed Node.js 20 nvm use 20.19.0 ``` ### Install Dependencies Enable [pnpm](https://pnpm.io/) with corepack: ```sh corepack enable ``` Install dependencies: ```sh pnpm install ``` What this will do: - Install all dependencies - Create symlinks between packages in the monorepo - Run the `prepare` script to build all packages, powered by [nx](https://nx.dev/). ### Set Git Email Please make sure you have your email set up in ``. This will be needed later when you want to submit a pull request. Check that your git client is already configured with the email: ```sh git config --list | grep email ``` Set the email to global config: ```sh git config --global user.email "SOME_EMAIL@example.com" ``` Set the email for local repo: ```sh git config user.email "SOME_EMAIL@example.com" ``` --- ## Repo Map - `packages/core`: agent execution, planning, model integration, device abstractions. The package name is `@midscene/core`. - `packages/web-integration`: source for npm package `@midscene/web`; Playwright/Puppeteer integration and main web e2e coverage. The package name is `@midscene/web`. - `packages/shared`: shared utilities used across the monorepo. The package name is `@midscene/shared`. - `packages/test`: Midscene Test, an extensible YAML testing framework and Node SDK. The package name is `@midscene/test`. - `packages/{android,ios,computer,harmony}`: platform runtimes. Matching `*-playground` packages live alongside them. The package names are `@midscene/android`, `@midscene/ios`, `@midscene/computer`, `@midscene/harmony`. - `packages/visualizer` and `apps/report`: report rendering and viewer UI. - `apps/site`: documentation site. The Nx project name is `doc`, not `site`. - `apps/chrome-extension`, `apps/playground`, `apps/report`, `apps/recorder-form`: user-facing apps. ### Commands That Matter - Install deps: `pnpm install` - Lint: `pnpm run lint` - Focused build: `npx nx build ` - Focused test: `npx nx test ` - Web e2e: `npx nx e2e @midscene/web` - AI tests: `npx nx test:ai @midscene/core` or `npx nx test:ai @midscene/web` --- ## Making Changes and Building Once you have set up the local development environment in your forked repo, we can start development. ### Checkout A New Branch It is recommended to develop on a new branch, as it will make things easier later when you submit a pull request: ```sh git checkout -b MY_BRANCH_NAME ``` ### Build the Package Use [nx build](https://nx.dev/nx-api/nx/documents/run) to build the package you want to change: ```sh npx nx build @midscene/web ``` Build all packages: ```sh pnpm run build ``` ### Development Workflows Use the root dev command only when you need monorepo-wide watch/build wiring: ```sh pnpm run dev ``` This command runs `scripts/dev-prepare.js` first, prepares the report and playground assets, and then starts Nx watch builds across packages. If you only need to debug a single app, start that app's own dev server instead of the root dev command: ```sh cd apps/report && pnpm run dev cd apps/site && pnpm run dev cd apps/playground && pnpm run dev cd apps/chrome-extension && pnpm run dev ``` ### Report template contains an unresolved placeholder / Cannot find module './report-html-template.js' #### Background: Core's embedded Report template Core embeds a complete Report HTML template so it can generate reports without a runtime dependency on `@midscene/report`. Because Report itself depends on Core, the Core source contains only a placeholder; `@midscene/report:build` owns writing the real HTML into the Core CJS and ESM template modules. An actual Core build also tries to synchronize an existing Report HTML as a best-effort convenience. #### When the unresolved-placeholder error occurs This usually happens in one of these development scenarios: - Core is built before Report has produced a valid `apps/report/dist/index.html`, for example because Report has not been built or its build failed. Core's best-effort synchronization then leaves the generated placeholder modules in place. - Placeholder modules already exist on disk, and a cached Core build skips the synchronization hook that could have replaced them. Core can still load in both cases, but report generation throws this error instead of producing an invalid report. #### When the missing-module error occurs Nx does not save or restore the two template modules as part of the `@midscene/core:build` cache. The missing-module error occurs only when all of the following are true: 1. A valid local Core build cache already exists. 2. `packages/core/dist`, or its template modules, is removed without clearing that cache. 3. Only Core is rebuilt, and the build is restored from the cache, so neither the real build nor its synchronization hook runs. The excluded template modules are not restored, so loading Core fails immediately. Current CI does not restore `.nx/cache` or use Nx remote caching, and `pnpm clean` removes both cache and dist, so this is unlikely in normal workflows. #### Resolution Both errors can be resolved by building Report, which produces the HTML and both Core template modules: ```sh pnpm exec nx build @midscene/report ``` For either error, if `apps/report/dist/index.html` already exists and only the Core template modules need to be repaired, synchronize them directly: ```sh pnpm --filter @midscene/core sync-report-template ``` --- ### Testing To change the AI-related code of this repository, you need to create a '.env 'file in the root directory, which reads as follows: ``` OPENAI_API_KEY="your_token" MIDSCENE_MODEL_NAME="qwen3-vl-plus" ``` ### Report Development and Test Scope Prioritize Report's core user workflows and data correctness during development, review, and testing: loading reports, reading outcomes and metrics, filtering and sorting, navigating Cases and attempts, inspecting failures and evidence, and using replay and mobile navigation. Use final Report outcomes consistently: Passed, Failed and Not run. Recovery after an earlier failed attempt is diagnostic history within Passed, never a separate filter, navigation group or additional Case count. Keep earlier attempts and File/Project errors available for debugging. Keep e2e assertions concise and focused on observable functional outcomes. Use enough context to locate the intended control, while allowing the layout and visual design to evolve. Preserve AI interaction and assertion coverage; use JavaScript for deterministic browser integration such as history, focus, and value comparisons. Cosmetic details such as spacing, colors, borders, shadows, corner radii, icon appearance, and exact dimensions should not become default test or review gates. Do not replace brittle e2e style checks with equally brittle CSS or markup assertions in unit tests. Use unit tests for aggregation, serialization, state transitions, and other behavioral rules. Add targeted visual checks when an explicit design requirement calls for them. Treat content clipping, overlap, or scrolling and keyboard problems that hide important information or prevent an action as functional defects. Cover the affected workflow without locking in incidental styling. See the Report e2e guidelines in [English](./apps/report/e2e/README.md) or [中文](./apps/report/e2e/README.zh.md) for coverage and authoring guidance. ### Artifact and logging conventions - Use `MIDSCENE_RUN_DIR` to choose the artifact root (default `midscene_run/`). Keep reports in `report/`, results and diagnostic records in `test-results/`, and logs in `log/`. Use `getMidsceneRunSubDir()` during execution and respect the current run's root and explicit path overrides. - Default to self-contained single HTML. Native Test owns one integrated report; its Agents contribute records. External reports must include their dependencies and remain readable after moving the directory. - Freeze snapshot data and collection status together. Retain failure, timeout, retry, and setup/teardown evidence before releasing execution references. - Clean only owned progress files after successful publication. Overwrite only the selected output target, preserve diagnostic sources on failure, and coordinate shared-report updates across processes. - Reuse existing report and image helpers. Deduplicate external and exported images while preserving step associations; keep pending writes and retained image data bounded. - Use `getDebug('module:topic')` for diagnostics, `getDebug(topic, { console: true })` for user-visible warnings, and `logReport()` for report paths. Keep required evidence in structured results; avoid secrets, full dumps, and Base64 images in ordinary logs. - Cover affected report formats and consumers with focused tests, including Agent, legacy YAML, Native Test, CLI append/export, and Playground where relevant. ### Add New Tests If you've fixed a bug or added code that should be tested, then add some tests. You can add unit test cases in the `/tests` folder. The test runner is based on [Rstest](https://rstest.rs/). ### Run Unit Tests Before submitting a pull request, it's important to make sure that the changes haven't introduced any regressions or bugs. You can run the unit tests for the project by executing the following command: ```sh pnpm run test # Test with AI-related features, it will need to create a .env file pnpm run test:ai ``` You can also run the unit tests of a single package: ```sh npx nx test @midscene/web # Test with AI-related features, it will need to create a .env file npx nx test:ai @midscene/web ``` ### Run E2E Tests Midscene uses - [playwright](https://github.com/microsoft/playwright) to run end-to-end tests. - [adb](https://developer.android.com/tools/adb) to run end-to-end tests on Android. You can run the `e2e` command to run E2E tests for playwright: ```sh pnpm run e2e ``` If you need to run a specified test: ```sh npx nx e2e @midscene/web ``` If you need to run E2E tests for adb: > Before running the test, you need to start the adb server first, please refer to the [README.md](./packages/web-integration/README.md) for details. ```sh cd packages/web-integration && pnpm run test:ai -- adb ``` ### Run native default-scroll regression tests The Android Emulator and iOS Simulator workflows run a model-free scroll regression before their existing smoke and AI tests. Native lists and pagers measure content offsets while the built SDK executes the `Scroll` action. Each platform runs 32 cases covering both orientations, all four directions, stability at top/bottom boundaries, and scrolling from the middle to the top/bottom. iOS also runs 36 bounded horizontal gesture cases: oversized distances from 15%, 50%, and 85% of the screen width, in both directions and orientations, with three trials per combination. These inspect the real WDA dispatch: preserve the chosen origin and 500 ms duration, clamp the endpoint, and prohibit reverse content motion. A clipped Scroll may settle on the same native page. An additional 16 iOS cases reject invalid distances through the Scroll action entry point, and 12 cases exercise explicit Swipe paging paths at three vertical positions in both directions and orientations. Eight more cases start in the middle of native horizontal pagers and non-paging scroll views and require scrollToLeft/scrollToRight to reach the measured content boundary in both orientations. The iOS runner executes 104 cases in total. A valid Scroll gesture does not guarantee a page transition: very short clipped paths can snap back, and system-reserved or non-interactive regions may ignore a touch. Do not move a located origin silently or infer a universal minimum paging distance from this fixture. For a paging interaction, use Swipe with an explicit path inside the target control and verify the resulting page. Clipping does not shorten the Scroll duration: accelerating the gesture can cause an ordinary scroll container to fling. Explicit Swipe controls its own duration. Build the target package first (`pnpm exec nx build @midscene/android` or `pnpm exec nx build @midscene/ios`). Then run from the repository root: ```sh # Requires a booted Android emulator, adb, an Android SDK, and a JDK. # The fixture build downloads checksum-pinned AndroidX dependencies. ANDROID_HOME=/path/to/android-sdk MIDSCENE_ANDROID_SERIAL=emulator-5554 \ node scripts/mobile-scroll-regression.mjs android # Requires a booted iOS simulator and WDA serving that simulator. MIDSCENE_IOS_SIMULATOR_UDID= MIDSCENE_IOS_WDA_PORT=8100 \ node scripts/mobile-scroll-regression.mjs ios ``` The runner installs the disposable `dev.midscene.scrollprobe` fixture. Android runs replace any previous installation of that fixture and temporarily set the emulator resolution and density. The runner restores the original resolution, density, or orientation when it finishes. Vertical content must move between 60% and 95% of the visible list height, preserving overlap. A horizontal gesture must move exactly one native page within a 3% measurement tolerance. Boundary gestures must settle within one coordinate unit of the original boundary. Separate `scrollToTop` and `scrollToBottom` cases start inside the list and must reach its measured native boundary. These checks validate this fixture's behavior, not identical displacement in every application. Before/after screenshots, native offset traces, the source commit, and assertion results are written under `midscene_run/-scroll/scroll`. CI uses the platform diagnostics directory and uploads these files with the existing diagnostics artifact. A failed assertion fails the simulator workflow even if the later smoke or AI tests pass. --- ## Linting To help maintain consistency and readability of the codebase, we use [Biome](https://github.com/biomejs/biome) to lint the codes. You can run the linter by executing the following command: ```sh pnpm run lint ``` For VS Code users, you can install the [Biome VS Code extension](https://marketplace.visualstudio.com/items?itemName=biomejs.biome) to see lints while typing. --- ## Documentation You can find the Midscene documentation in the [website](./apps/site) folder. Production site builds fetch the current GitHub star count and require an authenticated GitHub API token. Set `GITHUB_TOKEN` in the deployment environment, or provide it when building locally: ```sh GITHUB_TOKEN=$(gh auth token) pnpm --filter doc build ``` The site development server does not require a token. If GitHub is unavailable, it renders a non-numeric placeholder instead of a stale star count. --- ## Submitting Changes ### Committing your Changes Commit your changes to your forked repo, and [create a pull request](https://help.github.com/articles/creating-a-pull-request/). > Normally, the commits in a PR will be squashed into one commit, so you don't need to rebase locally. ### Format of PR titles and Commit Messages We use [Conventional Commits](https://www.conventionalcommits.org/) for PR titles and commit messages. This helps in automating changelog generation and keeps the commit history clean and understandable. **Structure:** ``` (): ^ ^ ^ | | |__ Subject: Concise description of the change (imperative mood, lowercase). | |__________ Scope: The specific part of the codebase affected. **This is mandatory.** |_______________ Type: Indicates the kind of change. ``` **Allowed Types:** * `feat`: A new feature. * `fix`: A bug fix. * `refactor`: Code changes that neither fix a bug nor add a feature. * `chore`: Changes to the build process, auxiliary tools, libraries, documentation generation etc. * `docs`: Documentation only changes. * Other conventional types like `perf`, `style`, `test`, `ci`, `build` are also acceptable. **Mandatory & Allowed Scopes:** Every commit **must** include a scope. The scope must be one of the following: * `workflow` * `llm` * `playwright` * `puppeteer` * `bridge` * *(All top-level directories in the apps and packages directories)* * *(Consider adding other relevant top-level packages or areas here if needed)* **Examples:** * `feat(bridge): add screenshot tool with element selection` * `fix(android): correct adb connection issue on windows` * `refactor(llm): simplify prompt generation logic` * `chore(workflow): update commitlint configuration` * `docs(bridge): clarify AgentOverChromeBridge usage` Your commit will be rejected by a pre-commit hook if it doesn't adhere to these rules. --- ## Versioning All Midscene packages will use a fixed unified version. The release notes are automatically generated by [GitHub releases](https://github.com/web-infra-dev/midscene/releases). ## Releasing Repository maintainers can publish a new version of all packages to npm. Here are the steps to publish (we generally use CI for releases and avoid publishing npm packages locally): 1. Prepare bilingual highlights for the target version in [.github/release-notes](./.github/release-notes/README.md). The `major` and `minor` inputs require both English and Chinese highlights; patch highlights are optional but must be supplied as a pair. 2. [Run the release action](https://github.com/web-infra-dev/midscene/actions/workflows/release.yml). Stable releases generate bilingual version archives and update the website's changelogs before committing the version bump and pushing its tag. Historical changelog content outside the generated regions is preserved. 3. The workflow publishes those same notes to [GitHub Releases](https://github.com/web-infra-dev/midscene/releases). Stable releases also attempt to submit the packaged Chrome extension to the Chrome Web Store from CI. Configure these repository secrets before running a stable release: - `CHROME_WEB_STORE_PUBLISHER_ID` - `CHROME_WEB_STORE_CLIENT_ID` - `CHROME_WEB_STORE_CLIENT_SECRET` - `CHROME_WEB_STORE_REFRESH_TOKEN` If Chrome Web Store publishing fails, the GitHub Release and packaged extension zip are still generated. You can then download the zip from the release artifacts and upload it manually in the Chrome Web Store dashboard. ## Chrome Extension ### Directory Structure ``` midscene/ ├── apps/ │ ├── chrome-extension/ # Chrome extension application │ │ ├── dist/ # Build output directory │ │ ├── extension/ # Packaged Chrome extension directory │ │ ├── scripts/ # Build and utility scripts │ │ ├── src/ # Source code │ │ │ ├── extension/ # Chrome extension-specific code │ │ │ └── ... │ │ ├── static/ # Static resources │ │ └── ... │ └── ... ├── packages/ │ ├── core/ # Core functionality │ ├── visualizer/ # Visualization components │ ├── web-integration/ # Web integration │ │ └── ... └── ... ``` ### Developing the Chrome DevTools Extension The Chrome DevTools extension uses the Rsbuild build system. Development workflow is as follows: 1. **Build base packages**: ```sh # First build the base packages pnpm run build ``` 2. **Development mode**: ```sh # Navigate to chrome-extension directory cd apps/chrome-extension # Start the development server pnpm run dev ``` 3. **Build the extension**: ```sh # Build the Chrome extension cd apps/chrome-extension pnpm run build ``` 4. **Install the extension**: The built `dist` directory can be directly installed as a Chrome extension. In Chrome browser: - Open `chrome://extensions/` - Enable "Developer mode" in the top-right corner - Click "Load unpacked" in the top-left corner - Select the `apps/chrome-extension/dist` directory Alternatively, you can use the packaged extension: - Select the `apps/chrome-extension/extension_output/midscene-extension-v{version}.zip` file For stable releases, this packaged zip is also the artifact used by the Chrome Web Store publish job. If that job fails, you can still use the same zip for manual store upload. For more detailed information, please refer to [Chrome DevTools README](./apps/chrome-extension/README.md). ## FAQ ### Errors like 'Template does not contain {{dump}} placeholder' Due to some issues with circular dependencies, you need to execute the full build process within the entire repository to compile the Midscene project, rather than compiling the ⁠@midscene/core package separately.