Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools
Rust ai-agentautomationclaudeclaude-codedockeriosiphonelinuxmcpmcp-servermodel-context-protocolrustwebdriveragent
release: 0.2.0 — native installs, first-run guide, new control page (#40)
Qinghe Li10d5cf935186
diff --git a/.dockerignore b/.dockerignoredeleted file mode 100644index 3790471..0000000--- a/.dockerignore+++ /dev/null@@ -1,12 +0,0 @@-# 构建上下文只需要源码;秘密和运行时数据绝不能进来(会留在构建层和缓存里)-target-.git-.github-data-secrets-.env-.env.*-docs-**/*.rs.bk-README.md-websitediff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 9a633a0..ed46431 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -27,19 +27,18 @@ body:attributes:label: How do you run it / 运行方式options:- - Docker (compose)- - Linux prebuilt binary- - Linux from source (systemd user service or manual)+ - install.sh (one-line installer)+ - Homebrew+ - .deb package+ - From source (service or started by hand)- Linux from source as root- - macOS prebuilt binary- - macOS from sourcevalidations:required: true- type: inputid: versionattributes:label: Version or commit / 版本或提交- placeholder: v0.1.5, or the output of `git rev-parse --short HEAD`+ placeholder: v0.2.0, or the output of `git rev-parse --short HEAD`- type: textareaid: doctorattributes:@@ -49,5 +48,5 @@ body:id: logsattributes:label: Relevant logs / 相关日志- description: "`docker logs iphone-control`, `data/logs/daemon.log`, or `journalctl --user -u iphone-control`; for MCP problems, the tool call and its result."+ description: "`iphone-control status`, `~/.local/share/iphone-control/logs/daemon.log`, `journalctl --user -u iphone-control` (Linux) or `~/Library/Logs/iphone-control/daemon.log` (macOS); for MCP problems, the tool call and its result."render: textdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c7f1537..0a49644 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -39,7 +39,7 @@ jobs:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v7- # 锁定工具链(与 Docker 构建镜像一致):新版 clippy 的 lint 不会在代码没变时把 CI 弄挂+ # 锁定工具链(与发布一致):新版 clippy 的 lint 不会在代码没变时把 CI 弄挂- uses: dtolnay/[email protected]with:components: clippy, rustfmt@@ -67,6 +67,49 @@ jobs:- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings- run: cargo test --workspace --all-features --locked+ # 安装方式能用:deb 打得出、装得上;install.sh 过 shellcheck、真能从最新的 Release 装上;Homebrew formula 能生成+ packages:+ needs: [changes]+ if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.outputs.code == 'true') }}+ # 和发布的二进制同一个系统(glibc 2.35)+ runs-on: ubuntu-22.04+ steps:+ - uses: actions/checkout@v7+ - uses: dtolnay/[email protected]+ - uses: Swatinem/rust-cache@v2+ with:+ key: packages+ - run: cargo build --release --locked -p iphone-control+ - uses: taiki-e/install-action@v2+ with:+ tool: cargo-deb,[email protected]+ # 第三方许可证清单(deb 里要带):依赖里出现白名单(packaging/licenses/about.toml)以外的许可证时失败+ - run: cargo about generate --locked -m apps/iphone-control/Cargo.toml -c packaging/licenses/about.toml packaging/licenses/about.hbs -o THIRD_PARTY_LICENSES.html+ - name: Debian package installs+ run: |+ cargo deb -p iphone-control --no-build --output dist/iphone-control.deb+ sudo apt-get update+ sudo apt-get install -y ./dist/iphone-control.deb+ dpkg -s iphone-control | grep -E '^(Version|Depends):'+ dpkg -L iphone-control+ test -x /usr/sbin/usbmuxd+ test -f /usr/lib/systemd/user/iphone-control.service+ grep -q '^ExecStart=/usr/bin/iphone-control daemon$' /usr/lib/systemd/user/iphone-control.service+ iphone-control --version+ sudo apt-get remove -y iphone-control+ - name: install.sh+ run: |+ shellcheck -s sh install.sh+ sh install.sh --no-service --prefix "$RUNNER_TEMP/ictl"+ "$RUNNER_TEMP/ictl/bin/iphone-control" --version+ sh install.sh --uninstall --prefix "$RUNNER_TEMP/ictl"+ test ! -e "$RUNNER_TEMP/ictl/bin/iphone-control"+ - name: Homebrew formula+ run: |+ shellcheck -s sh packaging/homebrew/formula.sh+ sh packaging/homebrew/formula.sh v0.0.0 aaa bbb ccc > iphone-control.rb+ ruby -c iphone-control.rb+# Cargo.toml 声明的最低版本(rust-version)要真能编译msrv:runs-on: ubuntu-latest@@ -85,18 +128,3 @@ jobs:- uses: gitleaks/gitleaks-action@v3env:GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}-- image:- runs-on: ubuntu-latest- needs: [rust]- steps:- - uses: actions/checkout@v7- - uses: docker/setup-buildx-action@v4- # 只验证镜像能构建,不推送- - uses: docker/build-push-action@v6- with:- context: .- file: docker/Dockerfile- push: false- cache-from: type=gha- cache-to: type=gha,mode=maxdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 5ab4828..3b26fa6 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -1,7 +1,7 @@name: Release-# 推送 v* tag 时:多架构镜像推到 ghcr(各架构在原生 runner 上构建,不用 QEMU 模拟),-# 附 SBOM 和构建来源证明;Linux 和 macOS 二进制及 sha256 附在 GitHub Release 上,发布说明取自 CHANGELOG.md 和 CHANGELOG.zh-CN.md。+# 推送 v* tag 时:Linux(x86_64、aarch64)和 macOS(Apple Silicon)的压缩包、Linux 的 .deb 及 sha256 附在 GitHub Release 上,+# 发布说明取自 CHANGELOG.md 和 CHANGELOG.zh-CN.md;最后更新 Homebrew 源 Derrors/homebrew-tap。不再发布 Docker 镜像on:push:tags: ["v*"]@@ -9,23 +9,23 @@ on:permissions:contents: read-env:- IMAGE: ghcr.io/derrors/iphone-control-jobs:- # 从源码运行(不用 Docker)的用户直接下载。在 Ubuntu 22.04 上编译(glibc 2.35),+ # install.sh、Homebrew、deb 都用这里的包。在 Ubuntu 22.04 上编译(glibc 2.35),# 所以 Debian 12、Ubuntu 22.04 及更新的发行版都能运行binaries:strategy:matrix:include:# 文件名用 linux-<arch>(arch 与 uname -m 一致),不用 Rust 的 target 名(x86_64-unknown-linux-gnu)+ # debarch: the architecture name in the .deb (Debian's names)- runner: ubuntu-22.04target: x86_64-unknown-linux-gnuarch: x86_64+ debarch: amd64- runner: ubuntu-22.04-armtarget: aarch64-unknown-linux-gnuarch: aarch64+ debarch: arm64runs-on: ${{ matrix.runner }}steps:- uses: actions/checkout@v7@@ -34,114 +34,40 @@ jobs:with:key: release-${{ matrix.target }}- run: cargo build --release --locked -p iphone-control+ # 第三方 Rust 组件许可证清单(cargo-about,按 Cargo.lock 生成);白名单(packaging/licenses/about.toml)以外的许可证让发布失败+ - uses: taiki-e/install-action@v2+ with:+ tool: [email protected]+ - run: cargo about generate --locked -m apps/iphone-control/Cargo.toml -c packaging/licenses/about.toml packaging/licenses/about.hbs -o THIRD_PARTY_LICENSES.html- name: Packagerun: |name="iphone-control-${GITHUB_REF_NAME}-linux-${{ matrix.arch }}"mkdir -p "dist/$name"cp target/release/iphone-control LICENSE THIRD_PARTY.md README.md README.zh-CN.md CHANGELOG.md CHANGELOG.zh-CN.md "dist/$name/"- cp -r deploy "dist/$name/"- cp .env.example "dist/$name/env.example"+ cp packaging/env.example "dist/$name/env.example"+ cp THIRD_PARTY_LICENSES.html "dist/$name/"tar -C dist -czf "dist/$name.tar.gz" "$name"(cd dist && sha256sum "$name.tar.gz" > "$name.tar.gz.sha256")- - uses: actions/upload-artifact@v7- with:- name: bin-${{ matrix.arch }}- path: dist/*.tar.gz*- if-no-files-found: error-- image:- strategy:- matrix:- include:- - runner: ubuntu-24.04- platform: linux/amd64- - runner: ubuntu-24.04-arm- platform: linux/arm64- runs-on: ${{ matrix.runner }}- permissions:- contents: read- packages: write- steps:- - uses: actions/checkout@v7- - name: Platform name- run: echo "PAIR=${PLATFORM//\//-}" >> "$GITHUB_ENV"- env:- PLATFORM: ${{ matrix.platform }}- - id: meta- uses: docker/metadata-action@v6+ # Debian/Ubuntu package (metadata in apps/iphone-control/Cargo.toml): the binary, a systemd user service,+ # depends on usbmuxd. `sudo apt install ./iphone-control_<version>_<arch>.deb`+ - uses: taiki-e/install-action@v2with:- images: ${{ env.IMAGE }}- - uses: docker/setup-buildx-action@v4- - uses: docker/login-action@v4- with:- registry: ghcr.io- username: ${{ github.actor }}- password: ${{ secrets.GITHUB_TOKEN }}- # 按 digest 推送,最后一步再合成一个多架构清单打标签- - id: build- uses: docker/build-push-action@v6- with:- context: .- file: docker/Dockerfile- platforms: ${{ matrix.platform }}- labels: ${{ steps.meta.outputs.labels }}- outputs: type=image,name=${{ env.IMAGE }},push-by-digest=true,name-canonical=true,push=true- cache-from: type=gha,scope=${{ env.PAIR }}- cache-to: type=gha,mode=max,scope=${{ env.PAIR }}- sbom: true- provenance: mode=max- - name: Export digest+ tool: cargo-deb+ - name: Debian packagerun: |- mkdir -p /tmp/digests- touch "/tmp/digests/${DIGEST#sha256:}"- env:- DIGEST: ${{ steps.build.outputs.digest }}+ deb="iphone-control_${GITHUB_REF_NAME#v}_${{ matrix.debarch }}.deb"+ cargo deb -p iphone-control --no-build --output "dist/$deb"+ (cd dist && sha256sum "$deb" > "$deb.sha256")- uses: actions/upload-artifact@v7with:- name: digests-${{ env.PAIR }}- path: /tmp/digests/*+ name: bin-${{ matrix.arch }}+ path: |+ dist/*.tar.gz*+ dist/*.deb*if-no-files-found: error- publish-image:- needs: image- runs-on: ubuntu-24.04- permissions:- contents: read- packages: write- steps:- - uses: actions/download-artifact@v8- with:- path: /tmp/digests- pattern: digests-*- merge-multiple: true- - id: meta- uses: docker/metadata-action@v6- with:- images: ${{ env.IMAGE }}- # v1.2.3 → 1.2.3、1.2、latest(预发布版本如 v1.2.3-rc.1 只打自己的版本号,不动 latest)- tags: |- type=semver,pattern={{version}}- type=semver,pattern={{major}}.{{minor}}- - uses: docker/setup-buildx-action@v4- - uses: docker/login-action@v4- with:- registry: ghcr.io- username: ${{ github.actor }}- password: ${{ secrets.GITHUB_TOKEN }}- - name: Create multi-arch manifest- working-directory: /tmp/digests- run: |- # shellcheck disable=SC2046- docker buildx imagetools create \- $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \- $(printf "$IMAGE@sha256:%s " *)- - name: Inspect- run: docker buildx imagetools inspect "$IMAGE:$VERSION"- env:- VERSION: ${{ steps.meta.outputs.version }}-release:- needs: [binaries, publish-image]+ needs: [binaries]runs-on: ubuntu-24.04permissions:contents: write@@ -175,8 +101,8 @@ jobs:echo "## English"; echo; echo "$en"; echoecho "## 中文"; echo; echo "$zh"; echoecho "---"; echo- echo "**Docker:** \`${IMAGE}:${version}\` (linux/amd64, linux/arm64)"; echo- echo "**Binaries / 二进制:** \`linux-x86_64\`, \`linux-aarch64\` (glibc 2.34+), \`macos-arm64\` (macOS 11+, Apple Silicon)"+ echo "**Binaries / 二进制:** \`linux-x86_64\`, \`linux-aarch64\` (glibc 2.34+), \`macos-arm64\` (macOS 11+, Apple Silicon); \`.deb\` amd64, arm64 (Debian 12+, Ubuntu 22.04+)"; echo+ echo "**Install / 安装:** \`curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh\` (macOS, Linux) · \`brew install derrors/tap/iphone-control\` · Debian/Ubuntu: \`sudo apt install ./iphone-control_${version}_amd64.deb\` (or \`_arm64.deb\`)"} > notes.md- name: Create releaserun: |@@ -202,6 +128,11 @@ jobs:with:key: release-aarch64-apple-darwin- run: cargo build --release --locked -p iphone-control+ # 第三方 Rust 组件许可证清单(cargo-about,按 Cargo.lock 生成);白名单(packaging/licenses/about.toml)以外的许可证让发布失败+ - uses: taiki-e/install-action@v2+ with:+ tool: [email protected]+ - run: cargo about generate --locked -m apps/iphone-control/Cargo.toml -c packaging/licenses/about.toml packaging/licenses/about.hbs -o THIRD_PARTY_LICENSES.html- name: Checkrun: |file target/release/iphone-control@@ -213,10 +144,42 @@ jobs:name="iphone-control-${GITHUB_REF_NAME}-macos-arm64"mkdir -p "dist/$name"cp target/release/iphone-control LICENSE THIRD_PARTY.md README.md README.zh-CN.md CHANGELOG.md CHANGELOG.zh-CN.md "dist/$name/"- cp .env.example "dist/$name/env.example"+ cp packaging/env.example "dist/$name/env.example"+ cp THIRD_PARTY_LICENSES.html "dist/$name/"tar -C dist -czf "dist/$name.tar.gz" "$name"(cd dist && shasum -a 256 "$name.tar.gz" > "$name.tar.gz.sha256")- name: Upload to the releaserun: gh release upload "$GITHUB_REF_NAME" dist/*.tar.gz dist/*.tar.gz.sha256 --clobberenv:GH_TOKEN: ${{ github.token }}++ # The Homebrew formula in Derrors/homebrew-tap, once all three archives are on the release. Pushed with a deploy key+ # that can write to that repository only (secret HOMEBREW_TAP_DEPLOY_KEY). Pre-releases (v1.2.3-rc.1) are skipped+ homebrew:+ needs: [release, macos-binary]+ if: ${{ !contains(github.ref_name, '-') }}+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v7+ - name: Formula+ run: |+ gh release download "$GITHUB_REF_NAME" --pattern '*.tar.gz.sha256' --dir sha+ sha() { awk '{print $1}' "sha/iphone-control-${GITHUB_REF_NAME}-$1.tar.gz.sha256"; }+ sh packaging/homebrew/formula.sh "$GITHUB_REF_NAME" "$(sha macos-arm64)" "$(sha linux-x86_64)" "$(sha linux-aarch64)" > iphone-control.rb+ ruby -c iphone-control.rb+ env:+ GH_TOKEN: ${{ github.token }}+ - name: Push to Derrors/homebrew-tap+ run: |+ mkdir -p ~/.ssh+ printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/tap && chmod 600 ~/.ssh/tap+ export GIT_SSH_COMMAND="ssh -i ~/.ssh/tap -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"+ git clone [email protected]:Derrors/homebrew-tap.git tap+ mkdir -p tap/Formula && cp iphone-control.rb tap/Formula/iphone-control.rb+ cd tap+ git config user.name "github-actions[bot]"+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"+ git add Formula/iphone-control.rb+ git diff --cached --quiet || { git commit -m "iphone-control ${GITHUB_REF_NAME#v}" && git push; }+ env:+ DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}diff --git a/.gitignore b/.gitignoreindex b8bde24..b466db7 100644--- a/.gitignore+++ b/.gitignore@@ -11,3 +11,4 @@# tests/device/run.py 的虚拟环境和真机截图(截图里可能有个人信息).venv/shots/+THIRD_PARTY_LICENSES.htmldiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3446f95..2efe9f2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,8 +6,57 @@ All notable changes to this project are documented here. The format is based on## [Unreleased]+## [0.2.0] - 2026-11-11++### Upgrade notes++- Docker is no longer released: no image on ghcr, no `compose.yaml`. Move to the one-line `install.sh`, Homebrew or the `.deb` (see Added). Stop the container first (`docker compose down`) so it doesn't hold the phone.+- Your data was in the container's volume (`./data` next to `compose.yaml`, owned by root). Before the first run, copy it to `~/.local/share/iphone-control` and make it yours (`sudo cp -a ./data ~/.local/share/iphone-control && sudo chown -R "$(id -un)": ~/.local/share/iphone-control`; see [Data and backups](https://derrors.github.io/iphone-control/en/deploy/backup)) to keep the Apple ID session, the signed WebDriverAgent and auto-unlock passcodes. Pairing records now live with the system usbmuxd, so the phone may ask you to trust the computer again.+- Settings move from `.env` to `~/.config/iphone-control/env` (same `KEY=value` lines; mode 0600). The first-run guide writes it, or copy your values over and run `iphone-control service restart`.+- `ICTL_MANAGE_USBMUXD` and `ICTL_USBMUXD_BIN` are gone: the daemon no longer starts usbmuxd. On Linux install the system one (`sudo apt install usbmuxd`; the `.deb` depends on it), and unmask it if you masked it for the container (`sudo systemctl unmask usbmuxd`).+- Register the MCP server again: the old `docker exec` registration no longer works. The first-run guide does it, or run the command `iphone-control mcp-config` prints.++### Added++- First-run guide: after installing, connect the phone and run `iphone-control`. The first time it walks you through setup in the terminal: language, proxy, the background service, pairing, Developer Mode, Apple ID, signing and installing WebDriverAgent, the optional auto-unlock passcode and notifications (Bark or Telegram, with a test message), and registering the MCP server with Claude Code and Codex. Steps already done are skipped; afterwards `iphone-control` shows the status and starts the service if it isn't running.+- `iphone-control setup --reconfigure` redoes all of setup or one part: language, proxy, background service, Apple ID (sign in again and re-sign WebDriverAgent), phone, auto-unlock passcode, notifications or MCP registration.+- `iphone-control service install|uninstall|start|stop|restart|status` manages the background service (launchd on macOS, a systemd user unit on Linux), whichever installed it: `install.sh`, `brew services` or the `.deb`.+- Settings file `~/.config/iphone-control/env`: the service loads it, and so does every command (a variable already set in the environment wins). After editing it by hand, run `iphone-control service restart`.+- `THIRD_PARTY_LICENSES.html` (licenses of all Rust dependencies) is in every release archive and in the `.deb`.+- The control page follows the device the daemon controls: when it is switched elsewhere (another tab, `iphone-control select`, the MCP tool, or automatically after an unplug), the page notices within about 10 seconds, says so, and moves its picture and panels over. Actions carry the device the page shows and are refused, never sent to another phone, once the daemon controls a different one.+- The control page says why a device has no picture (not connected, needs pairing or Developer Mode, WebDriverAgent starting or why it failed to start, needs unlocking), and offers a "Sign and install WDA" button for a device without WebDriverAgent when an Apple ID is signed in.+- Recovery from a revoked signing certificate: a free Apple ID holds at most two certificates, and signing with it somewhere else (another machine, moving from Docker to a native install, another sideloading tool) creates one and revokes an old one, after which WDA signed with that certificate won't start on any device although its profile still looks valid. When a device now refuses to start WDA, the daemon checks whether that WDA was signed with this machine's certificate and whether this machine's certificate is still in the Apple ID's team, and re-signs the device automatically if not (at most once per device every 6 hours).+- `doctor` shows both certificate checks; signing that creates or revokes a certificate is logged and notified (a new notification type `cert`, try it with `notify-test cert`).+- Simpler installs: `curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh` on macOS (Apple Silicon) and Linux installs the release binary and runs the daemon as a per-user service (launchd on macOS, which had none before; systemd on Linux), and upgrades or uninstalls it again; `brew install derrors/tap/iphone-control` with `brew services start iphone-control`; and a `.deb` for Debian 12+ and Ubuntu 22.04+ (amd64, arm64) with a systemd user service, depending on usbmuxd. The release workflow builds the packages and updates the Homebrew tap.+- AI tasks in the live viewer: type a task on the page and a local agent (Claude Code or Codex, picked on the page) carries it out on the phone through the MCP tools, while the page shows each step with what the agent says it is doing, the result and screenshots, and marks where it taps. Pause, resume, take over (act on the phone yourself) and hand back, or stop. Before paying, deleting, sending a message or changing account settings the agent asks on the page (`iphone_confirm`) and waits; a rejected step isn't done. The steps, holds and confirmations go through `iphone-control mcp` itself, so they work the same with either agent; the agent runs with only the phone tools (no shell or file tools for Claude Code, a read-only sandbox for Codex).++### Changed++- New viewer page: AI assistant, live screen with zoom, and a device panel with state and readiness checks, installed apps (launch, quit, open a URL) and on-screen elements (highlight on the picture, tap by name, wait for text). The device can be switched from the page, and the picture follows. While an AI task runs, manual actions are refused until you take over.+- On iOS 27 and later the viewer's picture works like a touchscreen: pressing, moving and releasing the mouse moves a finger on the phone as you go (over CoreDevice HID), so a list scrolls while you drag, and the mouse wheel or trackpad scrolls the page under the pointer without holding the button. A tap round trip is about 20 ms instead of about 530 ms, and a drag no longer waits for the list to stop (1.8 to 3 s before). Older iOS versions keep whole gestures sent on release. While the viewer is used, the HID session's screen stream keeps the phone awake, until 30 seconds after the last touch.+- The live picture runs at about 50 frames a second at 75% size (WDA's default was 10 at full size).+- The viewer page is in English or Chinese: it follows `IPHONE_CONTROL_LANG`, and a button switches it. The daemon's messages and the AI task (instructions, tool results) use the page's language.+- The viewer's task history shows one plain sentence per step (what the agent said it is doing, or a description of the action), without screenshots, tool names, parameters or raw results; a step that didn't work says so. Screenshots are no longer passed from the agent's tools to the viewer.+- The viewer no longer draws marks for your own taps and swipes, and no longer shows a message for each successful manual action; errors are still shown.+- The viewer serves more read-only JSON (`/api/daemon`, `/status`, `/devices`, `/apps`, `/elements`) and refuses reads that a browser marks as sent by another site (`Sec-Fetch-Site`), since reading elements can unlock the phone.++### Removed++- The Docker image (`ghcr.io/derrors/iphone-control`), `compose.yaml`, `docker/Dockerfile` and `.dockerignore`. A container can't reach the local Claude Code or Codex that the control page hands tasks to, and the native installs are simpler.+- The daemon no longer starts or watches usbmuxd (`ICTL_MANAGE_USBMUXD`, `ICTL_USBMUXD_BIN`); the system usbmuxd is used on Linux and macOS.+- `deploy/iphone-control.service`: `install.sh` and `iphone-control service install` write the unit now.+- `iphone-control mcp-config --container`: `mcp-config` takes no arguments and prints a path that survives Homebrew upgrades.+### Fixed+- Control page: the mouse wheel works again on devices below iOS 27 (whole-gesture mode). It waited for a leftover scroll amount that never drains in that mode, so no swipe went out and later wheel events piled up.+- Pressing Home right after an app comes to the front, while its transition is still running, was ignored by iPadOS for both ways of pressing (about one time in three on an iPad mini 5 / iPadOS 26.6.1). When neither brings back the home screen, Home is now pressed once more.+- When WebDriverAgent fails to start with only `unexpected response`, the hint adds the second likely cause: if the developer is already trusted, the signing certificate may have changed; run `iphone-control sign` to re-sign the device. In that case the control page offers a "Re-sign and install WDA" button when an Apple ID is signed in.+- In automatic mode the daemon, after a restart, goes on with the last device that was ready instead of whichever usbmuxd lists first (with an iPhone and an iPad connected, a restart could switch to a device whose WebDriverAgent can't start).+- `iphone-control viewer` no longer exits when the daemon isn't up yet and several devices are connected: it starts anyway and the page follows once the daemon has picked a device.+- Control page: on a device below iOS 27 without WebDriverAgent, the route shows "Unavailable" instead of the HID fallback (which needs iOS 27); an unknown lock state is no longer shown as "Unlocked"; when WebDriverAgent fails to start, the picture area shows why instead of "usually 10–60 seconds".+- "WDA failed to start: WDA failed to start:" is no longer doubled in the log and the state.+- `devices`, `select` and `doctor` on the command line also name `iphone-control select` / `iphone-control status`, not only the MCP tools; when the daemon can't be reached, the hint is `iphone-control service start`.- `lock` no longer takes about 10 seconds on newer iPhones: the power key is pressed for 0.1 s instead of held for 0.5 s, which an iPhone 18 Pro Max (iOS 27.2.1) ignored, so every lock fell through to WebDriverAgent's slower lock and logged a timeout.- `home` takes about 1.3 seconds instead of 3.7 on devices that ignore the IOHID Home event (iPhone 18 Pro Max, iOS 27.2.1): when only the XCTest press works, the daemon remembers that for the device and uses it first. Devices where only the IOHID press works (iPhone 12 mini) keep their order.- Taps and long presses no longer take about 26 seconds while something on screen keeps animating (seen tapping a search result in Settings with the keyboard up, iPhone 18 Pro Max, iOS 27.2.1): like swipes, they no longer wait for WebDriverAgent's animation cool-off. The result came back in about 1.4 seconds.@@ -128,7 +177,8 @@ First public release.- Docker image (single binary plus Debian's usbmuxd, not privileged) with a generated third-party license list, published to `ghcr.io/derrors/iphone-control` for linux/amd64 and linux/arm64.- Running without Docker, from source or from the prebuilt Linux binaries (x86_64, aarch64): as a regular user with the system usbmuxd, XDG data and socket paths, the unsigned WebDriverAgent downloaded and checksum-verified before the first signing, `mcp-config` printing a direct command, and a systemd user service.-[Unreleased]: https://github.com/Derrors/iphone-control/compare/v0.1.5...HEAD+[Unreleased]: https://github.com/Derrors/iphone-control/compare/v0.2.0...HEAD+[0.2.0]: https://github.com/Derrors/iphone-control/compare/v0.1.5...v0.2.0[0.1.5]: https://github.com/Derrors/iphone-control/compare/v0.1.4...v0.1.5[0.1.4]: https://github.com/Derrors/iphone-control/compare/v0.1.3...v0.1.4[0.1.3]: https://github.com/Derrors/iphone-control/compare/v0.1.2...v0.1.3diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex f2f9d66..9cd997c 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -6,8 +6,57 @@## [Unreleased]+## [0.2.0] - 2026-11-11++### 升级注意事项++- 不再发布 Docker:ghcr 上不再有镜像,也没有 `compose.yaml`。请改用一行命令的 `install.sh`、Homebrew 或 `.deb`(见「新增」)。先停掉容器(`docker compose down`),免得它占着手机。+- 原来的数据在容器挂的卷里(`compose.yaml` 旁边的 `./data`,属于 root)。第一次运行前把它拷到 `~/.local/share/iphone-control` 并改成自己的(`sudo cp -a ./data ~/.local/share/iphone-control && sudo chown -R "$(id -un)": ~/.local/share/iphone-control`,见[数据与备份](https://derrors.github.io/iphone-control/deploy/backup)),Apple ID 会话、签好的 WebDriverAgent 和自动解锁密码就都还在。配对记录现在由系统的 usbmuxd 保存,手机可能会再问一次是否信任这台电脑。+- 设置从 `.env` 搬到 `~/.config/iphone-control/env`(同样是 `KEY=value`,权限 0600)。首次运行引导会写好它;也可以把原来的值抄过去,再运行 `iphone-control service restart`。+- `ICTL_MANAGE_USBMUXD`、`ICTL_USBMUXD_BIN` 已删除:守护进程不再自己启动 usbmuxd。Linux 上请装系统的 usbmuxd(`sudo apt install usbmuxd`,`.deb` 会自动装上);以前为容器 mask 过的,要 `sudo systemctl unmask usbmuxd`。+- 重新注册 MCP:原来 `docker exec` 形式的注册不能用了。首次运行引导会注册,或者运行 `iphone-control mcp-config` 打印的命令。++### 新增++- 首次运行引导:装好后接上手机,运行 `iphone-control`。第一次会在终端里一步步带你完成设置:语言、代理、后台服务、配对、开发者模式、Apple ID、签名并安装 WebDriverAgent,可选的自动解锁密码和通知(Bark 或 Telegram,发一条测试消息),以及把 MCP 注册到 Claude Code 和 Codex。做过的步骤会跳过;设置好以后再运行 `iphone-control` 只显示状态,后台服务没在运行时先启动它。+- `iphone-control setup --reconfigure`:全部重新设置,或只改一项:语言、代理、后台服务、Apple ID(重新登录并重签 WebDriverAgent)、手机、自动解锁密码、通知、注册 MCP。+- `iphone-control service install|uninstall|start|stop|restart|status` 管理后台服务(macOS 是 launchd,Linux 是 systemd 用户服务),不管是 `install.sh`、`brew services` 还是 `.deb` 装的。+- 设置文件 `~/.config/iphone-control/env`:后台服务读它,每个命令启动时也读它(环境里已经设了的变量优先)。手改后运行 `iphone-control service restart`。+- 每个发布的压缩包和 `.deb` 里都带 `THIRD_PARTY_LICENSES.html`(所有 Rust 依赖的许可证)。+- 控制台跟着守护进程控制的设备走:在别处切换了设备(另一个标签页、`iphone-control select`、MCP 工具,或拔掉后自动换了一台),页面约 10 秒内发现、提示,并把画面和各面板换过去。操作带着页面显示的那台设备,守护进程已经在控制别的设备时会被拒绝,不会发到另一部手机上。+- 控制台没有画面时说明原因(没连上、要配对或开开发者模式、WebDriverAgent 正在启动或启动失败的原因、要先解锁);没装 WebDriverAgent 的设备,登录了 Apple ID 时会显示「签名并安装 WDA」按钮。+- 签名证书被吊销时自动恢复:免费 Apple ID 同时最多两张证书,在别处(换机器、从 Docker 换成本机安装、别的侧载工具)用同一个 Apple ID 签名会新建证书并吊销一张旧的,用它签的 WDA 在每台设备上都起不来,描述文件却看着还有效。现在设备拒绝启动 WDA 时,守护进程会检查设备上的 WDA 是不是本机证书签的、本机证书还在不在 Apple ID 的团队里,有问题就自动重签这台(同一台 6 小时内最多一次)。+- `doctor` 显示这两项证书检查;签名时新建或吊销证书会写日志并发通知(新的通知类型 `cert`,`notify-test cert` 可以试发)。+- 安装更简单:macOS(Apple Silicon)和 Linux 上 `curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh` 一行装好 Release 的程序,并把守护进程装成用户服务(macOS 用 launchd,以前没有;Linux 用 systemd),再运行一次就是升级,也能卸载;`brew install derrors/tap/iphone-control` 加 `brew services start iphone-control`;Debian 12+ 和 Ubuntu 22.04+ 的 `.deb`(amd64、arm64),带 systemd 用户服务、依赖 usbmuxd。发布流程会打好这些包并更新 Homebrew 源。+- 实时画面页面里的 AI 任务:在页面上写下任务,本机的 agent(Claude Code 或 Codex,在页面上选)用 MCP 工具在手机上完成;页面逐步显示 agent 说它要做什么、结果和截图,并在画面上标出点击位置。可以暂停、继续、接管(自己动手)后交还,或者停止。付款、删除、发消息、改账号设置之前,agent 会在页面上请你确认(`iphone_confirm`)并等你回答,拒绝的那一步不会执行。步骤、暂停和确认都经过 `iphone-control mcp` 本身,所以两种 agent 表现一样;agent 只能用操作手机的工具(Claude Code 不带命令行和文件工具,Codex 用只读沙箱)。++### 变更++- 新的实时画面页面:AI 助手、可缩放的实时画面,以及设备面板(状态和就绪检查、已安装的 App(启动、结束、打开链接)、屏幕上的元素(在画面上框出、按名字点、等文字出现))。可以在页面上切换设备,画面跟着换。AI 任务执行中手动操作会被拒绝,接管后才能操作。+- iOS 27 起,viewer 的画面像触摸屏一样用:按下、移动、松开鼠标,手机上的手指跟着动(经 CoreDevice HID),拖动时列表跟着滚;在画面上滚动鼠标滚轮或触控板,不用按住鼠标就能滚动光标下的页面。点击往返从约 530 毫秒降到约 20 毫秒,拖动不再等列表停下(原来 1.8~3 秒)。iOS 27 以下仍在松开后发整段手势。用 viewer 操作时,HID 会话的屏幕媒体流会让手机保持亮屏,最后一次触摸 30 秒后关闭。+- 实时画面约每秒 50 帧、75% 尺寸(WDA 默认每秒 10 帧、原尺寸)。+- viewer 页面有中英文:默认跟着 `IPHONE_CONTROL_LANG`,页面上有按钮切换。守护进程的提示和 AI 任务(给 agent 的说明、工具结果)都跟着页面的语言。+- viewer 的执行记录每一步只显示一句看得懂的话(agent 说它要做什么,没说时按操作写一句),不再显示截图、工具名、参数和原始结果;没成功的一步注明「这一步没成功」。agent 工具的截图也不再传给 viewer。+- viewer 不再给自己的点击、滑动画轨迹,手动操作成功时也不再弹提示;出错照样提示。+- viewer 新增只读的 JSON 接口(`/api/daemon`、`/status`、`/devices`、`/apps`、`/elements`),并拒绝浏览器标明来自其他网站的读取(`Sec-Fetch-Site`),因为读元素可能会解锁手机。++### 移除++- Docker 镜像(`ghcr.io/derrors/iphone-control`)、`compose.yaml`、`docker/Dockerfile` 和 `.dockerignore`。容器够不到控制台要交任务的本机 Claude Code 或 Codex,原生安装也更简单。+- 守护进程不再启动、看护 usbmuxd(`ICTL_MANAGE_USBMUXD`、`ICTL_USBMUXD_BIN`),Linux 和 macOS 都用系统的 usbmuxd。+- `deploy/iphone-control.service`:改由 `install.sh` 和 `iphone-control service install` 写服务文件。+- `iphone-control mcp-config --container`:`mcp-config` 不再带参数,打印的路径在 Homebrew 升级后也有效。+### 修复+- 控制台:iOS 27 以下的设备(整段手势模式)上,滚轮滚动不再没反应。原来滚轮一直在等一个这种模式下永远不会归零的剩余量,滑动发不出去,之后的滚轮也一起积压。+- 刚启动 App、转场动画还没走完时按 Home,iPadOS 会把两种按法都忽略(iPad mini 5 / iPadOS 26.6.1 上约三次有一次)。现在两种都没回到主屏时,会再补按一次。+- WebDriverAgent 启动失败、只报 `unexpected response` 时,提示里加上第二种可能:已经信任过开发者的,可能是签名证书变了,运行 `iphone-control sign` 重签这台设备。控制台在这种情况下,登录了 Apple ID 时会给出「重新签名并安装 WDA」按钮。+- 自动选择设备时,守护进程重启后接着用上次就绪过的那台,不再按 usbmuxd 列表的顺序换到另一台(接着 iPhone 和 iPad 时,重启后可能换到一台起不来 WebDriverAgent 的设备)。+- `iphone-control viewer` 在守护进程还没起来、又接着多台设备时不再直接退出:先照常启动,守护进程选好设备后页面自动跟上。+- 控制台:iOS 27 以下的设备在 WebDriverAgent 没起来时,「操作通道」显示「不可用」,不再说改走 HID 后备(HID 后备要 iOS 27);不知道锁没锁时不再显示「未锁定」;WebDriverAgent 启动失败时画面区域显示失败原因,不再一直说「通常 10–60 秒」。+- 日志和状态里的「WDA 启动失败:WDA 启动失败:」不再重复。+- 命令行里 `devices`、`select`、`doctor` 的提示同时给出 `iphone-control select` / `iphone-control status`,不再只写 MCP 工具名;连不上守护进程时提示 `iphone-control service start`。- 新款 iPhone 上 `lock` 不再要 10 秒左右:电源键改为按 0.1 秒,不再按住 0.5 秒。iPhone 18 Pro Max(iOS 27.2.1)不认按住,每次锁屏都退到 WebDriverAgent 较慢的锁屏,还在日志里记一次超时。- 不认 IOHID Home 事件的设备(iPhone 18 Pro Max,iOS 27.2.1)上 `home` 从约 3.7 秒变为约 1.3 秒:只有 XCTest 的按法有效时,守护进程按设备记住,之后先用它。只认 IOHID 按法的设备(iPhone 12 mini)顺序不变。- 界面上一直有动画时,点击和长按不再要 26 秒左右(iPhone 18 Pro Max、iOS 27.2.1 上,键盘弹着时在设置里点搜索结果每次都这样):和滑动一样,不再等 WebDriverAgent 的动画冷却。同一个点击现在约 1.4 秒。@@ -126,7 +175,8 @@- `setup`、`doctor`、`status`、`mcp-config`、`wda-bridge`、`notify-test` 命令。- Docker 镜像(非 privileged,linux/amd64、linux/arm64);也可不用 Docker,从源码或预编译二进制以普通用户运行,附 systemd 用户服务。-[Unreleased]: https://github.com/Derrors/iphone-control/compare/v0.1.5...HEAD+[Unreleased]: https://github.com/Derrors/iphone-control/compare/v0.2.0...HEAD+[0.2.0]: https://github.com/Derrors/iphone-control/compare/v0.1.5...v0.2.0[0.1.5]: https://github.com/Derrors/iphone-control/compare/v0.1.4...v0.1.5[0.1.4]: https://github.com/Derrors/iphone-control/compare/v0.1.3...v0.1.4[0.1.3]: https://github.com/Derrors/iphone-control/compare/v0.1.2...v0.1.3diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex f6e76e9..77a4485 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -6,7 +6,7 @@ Most of the code comments, design documents and commit messages in this reposito## Before you start-- **Bugs:** include the iPhone or iPad model, iOS version, how you run it (Docker, prebuilt binary or source; Linux or macOS), and the output of `iphone-control doctor`, with private data removed. The [issue template](.github/ISSUE_TEMPLATE/bug_report.yml) asks for these.+- **Bugs:** include the iPhone or iPad model, iOS version, how you installed it (install.sh, Homebrew, .deb or source; Linux or macOS), and the output of `iphone-control doctor`, with private data removed. The [issue template](.github/ISSUE_TEMPLATE/bug_report.yml) asks for these.- **Larger changes:** open an issue first. The key design decisions and their reasons are in [docs/decisions.md](docs/decisions.md); the regression cases every change must keep passing are in [docs/dev/regression-cases.md](docs/dev/regression-cases.md).- **Security problems:** don't open an issue — see [SECURITY.md](SECURITY.md).@@ -35,15 +35,16 @@ The pure logic — element-tree parsing, occlusion, the auto-unlock rules (again## Testing on a real phone-Anything that touches the device, timing or WebDriverAgent behaviour needs a real phone. With the daemon running (container or source):+Anything that touches the device, timing or WebDriverAgent behaviour needs a real phone. With the daemon running:```bashpython3 -m venv .venv && .venv/bin/pip install -r tests/device/requirements.txt+export MCP_CMD="iphone-control mcp" # run.py still defaults to the old container command.venv/bin/python tests/device/run.py # default steps: harmless (Home, Clock tabs, Spotlight search).venv/bin/python tests/device/run.py '[["iphone_launch_app", {"app": "设置"}], ["iphone_screenshot", {}]]'```-`run.py` prints every result with its wall time and saves screenshots to `./shots`. Set `MCP_CMD` for a source install (for example `MCP_CMD="iphone-control mcp"`). Please mention in the pull request what you ran on which device and iOS version.+`run.py` prints every result with its wall time and saves screenshots to `./shots`. Use the full path of the binary in `MCP_CMD` if it isn't on your `PATH`. Please mention in the pull request what you ran on which device and iOS version.On macOS, the full checklist (setup, `debug` checks, coexistence with Finder, reconnect) is in [docs/dev/macos-verification.md](docs/dev/macos-verification.md).@@ -67,13 +68,13 @@ Notes:- **Pin exact versions** (`=x.y.z`) and keep `Cargo.lock` committed; upgrade dependencies in separate commits ([D9](docs/decisions.md)).- **Don't break the MCP interface:** tool names, parameters and default outputs stay compatible; add optional parameters instead ([D10](docs/decisions.md)).- **Vendored code** (`vendor/`) keeps its license. Record any change in [THIRD_PARTY.md](THIRD_PARTY.md); changed MPL-2.0 files stay MPL-2.0.-- **Never commit** `data/`, `.env`, certificates, provisioning profiles, pairing records or anything Apple ships (Developer Disk Images, frameworks).+- **Never commit** `data/`, `~/.config/iphone-control/env` or other settings files with secrets, certificates, provisioning profiles, pairing records or anything Apple ships (Developer Disk Images, frameworks).- Comments explain *why*, especially device quirks; put measured numbers next to timeouts and thresholds.## Pull requests- Keep them focused; describe what changed and how you tested it (offline and/or which device).-- CI must pass: format, clippy with `-D warnings`, tests (on Linux and macOS), the MSRV check, gitleaks and the image build.+- CI must pass: format, clippy with `-D warnings`, tests (on Linux and macOS), the MSRV check, gitleaks and the package checks (`.deb`, `install.sh`, the Homebrew formula).- User-visible changes get a line in [CHANGELOG.md](CHANGELOG.md) and [CHANGELOG.zh-CN.md](CHANGELOG.zh-CN.md) under *Unreleased* (a Chinese line is welcome but optional for outside contributors; maintainers add it before release).## Documentation site@@ -84,9 +85,7 @@ The user guide at [derrors.github.io/iphone-control](https://derrors.github.io/i1. Move the *Unreleased* entries in [CHANGELOG.md](CHANGELOG.md) and [CHANGELOG.zh-CN.md](CHANGELOG.zh-CN.md) under `## [x.y.z] - YYYY-MM-DD` and update the compare links at the bottom. Both files need the section — the release notes are built from the two (English, then Chinese) and the workflow fails if either is missing. Keep entries short: one line per user-visible change, no implementation details.2. Set `version` in the root `Cargo.toml` (`[workspace.package]`) and run `cargo check --workspace` to update `Cargo.lock`.-3. Update `V=vx.y.z` in `README.md`, `README.zh-CN.md`, `website/deploy/macos.md` and `website/en/deploy/macos.md`, and the pinned image examples (`:x.y.z`) in `website/deploy/docker.md` and `website/en/deploy/docker.md`.-4. Commit, tag `vx.y.z`, push the tag. [`release.yml`](.github/workflows/release.yml) builds the amd64/arm64 images on native runners and pushes them to `ghcr.io/derrors/iphone-control` (tags `x.y.z`, `x.y`, `latest`; pre-releases such as `v0.2.0-rc.1` only get their own tag), builds the Linux binaries (`iphone-control-vx.y.z-linux-x86_64.tar.gz`, `…-linux-aarch64.tar.gz`), and creates the GitHub release from the two changelog sections. The macOS binary (`…-macos-arm64.tar.gz`) is built afterwards and uploaded to the release; if GitHub has no macOS runner available the job is cancelled after about 15 minutes — re-run just that job.-5. Update Glama: on glama.ai, the build steps under this server's *Admin → Dockerfile* pin the version. Change it and rebuild.-6. First release only: make the ghcr package public (*Package settings → Change visibility*) — new packages start private.+3. Commit, tag `vx.y.z`, push the tag. [`release.yml`](.github/workflows/release.yml) builds the Linux archives (`iphone-control-vx.y.z-linux-x86_64.tar.gz`, `…-linux-aarch64.tar.gz`) and `.deb` packages (amd64, arm64), each with `THIRD_PARTY_LICENSES.html`, and creates the GitHub release from the two changelog sections. The macOS archive (`…-macos-arm64.tar.gz`) is built afterwards and uploaded to the release; if GitHub has no macOS runner available the job is cancelled after about 15 minutes — re-run just that job. Once all three archives are there, the workflow pushes the formula to [Derrors/homebrew-tap](https://github.com/Derrors/homebrew-tap) (pre-releases such as `v0.2.0-rc.1` are skipped).+4. Update Glama: on glama.ai, the build steps under this server's *Admin → Dockerfile* pin the version. Change it and rebuild.By contributing you agree that your contributions are licensed under the MIT license, except for changes to vendored files, which stay under their original licenses.diff --git a/Cargo.lock b/Cargo.lockindex f1f3959..274af32 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1947,7 +1947,7 @@ dependencies = [[[package]]name = "ictl-daemon"-version = "0.1.5"+version = "0.2.0"dependencies = ["anyhow","base64 0.23.1",@@ -1969,7 +1969,7 @@ dependencies = [[[package]]name = "ictl-device"-version = "0.1.5"+version = "0.2.0"dependencies = ["ictl-l10n","ictl-webinspector",@@ -1985,14 +1985,14 @@ dependencies = [[[package]]name = "ictl-l10n"-version = "0.1.5"+version = "0.2.0"dependencies = ["tokio",][[package]]name = "ictl-mcp"-version = "0.1.5"+version = "0.2.0"dependencies = ["anyhow","ictl-l10n",@@ -2004,7 +2004,7 @@ dependencies = [[[package]]name = "ictl-protocol"-version = "0.1.5"+version = "0.2.0"dependencies = ["ictl-l10n","libc",@@ -2015,21 +2015,23 @@ dependencies = [[[package]]name = "ictl-sign"-version = "0.1.5"+version = "0.2.0"dependencies = ["ictl-l10n","plist","plume_core","plume_store",+ "rsa","thiserror 2.0.21","tracing","uuid",+ "x509-certificate","zip",][[package]]name = "ictl-unlock"-version = "0.1.5"+version = "0.2.0"dependencies = ["ictl-l10n","ictl-wda",@@ -2042,7 +2044,7 @@ dependencies = [[[package]]name = "ictl-wda"-version = "0.1.5"+version = "0.2.0"dependencies = ["base64 0.23.1","ictl-device",@@ -2058,7 +2060,7 @@ dependencies = [[[package]]name = "ictl-webinspector"-version = "0.1.5"+version = "0.2.0"dependencies = ["idevice","plist",@@ -2268,7 +2270,7 @@ dependencies = [[[package]]name = "iphone-control"-version = "0.1.5"+version = "0.2.0"dependencies = ["anyhow","clap",@@ -2278,11 +2280,13 @@ dependencies = ["ictl-mcp","ictl-sign","ictl-wda",+ "libc","rustls","serde_json","tokio","tracing","tracing-subscriber",+ "uuid",][[package]]diff --git a/Cargo.toml b/Cargo.tomlindex ae09835..7b07f59 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -17,7 +17,7 @@ members = [exclude = ["vendor"][workspace.package]-version = "0.1.5"+version = "0.2.0"edition = "2024"# rmcp 3.8 要求 1.88;Impactor/idevice 用 edition 2024rust-version = "1.88"@@ -66,6 +66,9 @@ base64 = "=0.23.1"anyhow = "=1.0.104"plist = "=1.10.3"uuid = { version = "=1.26.1", features = ["v4"] }+# 和 plume_core 同一份:比对证书和本机签名私钥的公钥(ictl-sign)+rsa = "=0.9.10"+x509-certificate = "=0.24.0"zip = { version = "=9.4.1", default-features = false, features = ["deflate"] }regex = "=1.13.1"libc = "=0.2.191"@@ -92,6 +95,10 @@ apple-codesign = { path = "vendor/apple-codesign" }# idevice 0.1.68 的 cryptexd install 会挂住(persistence 字段错、隧道 MSS),修复在上游 master 但还没发版idevice = { git = "https://github.com/jkcoxson/idevice", rev = "89702099f4d7552f704f93b4526756abda319ceb" }+# 测试里现场生成 RSA 密钥(ictl-sign):不开优化的话大数运算要十几秒+[profile.dev.package.num-bigint-dig]+opt-level = 3+[profile.release]lto = "thin"codegen-units = 1diff --git a/README.md b/README.mdindex 031b351..f8b7fb8 100644--- a/README.md+++ b/README.md@@ -64,33 +64,41 @@ iphone-control does it all in **one Rust binary** on Linux or macOS, built on [i## Quick Start-You need an iPhone or iPad on iOS 17+ connected by a **data** cable, a free Apple ID (use a dedicated one), and a Linux host with Docker or an Apple Silicon Mac.+You need an iPhone or iPad on iOS 17+ connected by a **data** cable, a free Apple ID (use a dedicated one), and an Apple Silicon Mac or a Linux machine.-**Linux (Docker)**+**macOS or Linux, one command**```bash-git clone https://github.com/Derrors/iphone-control.git && cd iphone-control-cp .env.example .env # optional: proxy, notifications-docker compose up -d --build # the first build takes a few minutes-docker exec -it iphone-control iphone-control setup # guided setup; safe to re-run-claude mcp add iphone -s user -- docker exec -i iphone-control iphone-control mcp+curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh```-**macOS** (Docker can't pass USB through on a Mac, so run the binary directly)+It downloads the release for your machine, checks its sha256, installs `iphone-control` into `~/.local/bin` and runs the daemon as a per-user service that starts at login (launchd on macOS, systemd on Linux). It never runs as root. Run it again to upgrade; `… | sh -s -- --uninstall` removes it and keeps your data.++**Or with a package manager**++```bash+# macOS or Linux (Homebrew)+brew install derrors/tap/iphone-control && brew services start iphone-control++# Debian 12+ / Ubuntu 22.04+: the .deb from Releases (amd64 or arm64), pulls in usbmuxd+sudo apt install ./iphone-control_<version>_amd64.deb && systemctl --user enable --now iphone-control+```++On Linux the system usbmuxd is needed (`sudo apt install usbmuxd`; the .deb brings it). On an Intel Mac, build from source.++**Then, on every system**++Connect the phone with the cable and run:```bash-V=v0.1.5 # latest release-curl -fsSL https://github.com/Derrors/iphone-control/releases/download/$V/iphone-control-$V-macos-arm64.tar.gz | tar xz-mkdir -p ~/.local/bin && install -m 755 iphone-control-$V-macos-arm64/iphone-control ~/.local/bin/-echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zprofile && source ~/.zprofile-iphone-control daemon # keep this terminal open-iphone-control setup # in a second terminal-iphone-control mcp-config # prints the `claude mcp add` command to run+iphone-control```-`setup` walks you through pairing, Developer Mode, Apple ID sign-in and installing WebDriverAgent; do what it asks on the phone. Then open a new Claude Code session and ask, for example, *“Open Clock, switch to the stopwatch and start it.”*+The first time, it walks you through setup in the terminal, one step at a time: language, proxy, the background service, pairing, Developer Mode, Apple ID, signing and installing WebDriverAgent, the optional auto-unlock and notifications, and registering with Claude Code and Codex. Do what it asks on the phone. Steps already done are skipped; afterwards, `iphone-control` just shows the status.-More: [step-by-step guide](https://derrors.github.io/iphone-control/en/guide/getting-started) · [prebuilt image](https://derrors.github.io/iphone-control/en/deploy/docker) · [binary / source](https://derrors.github.io/iphone-control/en/deploy/source) · [macOS guide](https://derrors.github.io/iphone-control/en/deploy/macos) · [other MCP clients](https://derrors.github.io/iphone-control/en/guide/mcp-clients).+Then open a new Claude Code or Codex session and ask, for example, *“Open Clock, switch to the stopwatch and start it.”* Or run `iphone-control viewer` for the control page in the browser (http://127.0.0.1:8200), where you can act on the live screen and hand tasks to a local Claude Code or Codex.++More: [step-by-step guide](https://derrors.github.io/iphone-control/en/guide/getting-started) · [build from source](https://derrors.github.io/iphone-control/en/deploy/source) · [macOS guide](https://derrors.github.io/iphone-control/en/deploy/macos) · [other MCP clients](https://derrors.github.io/iphone-control/en/guide/mcp-clients).## MCP Tools@@ -118,15 +126,15 @@ Tool texts, results, CLI output and logs are in Simplified Chinese by default; s## Everyday Commands-Run them as `docker exec -it iphone-control iphone-control <command>`, or directly for a source install and on macOS.-| Command | What it does || --- | --- |-| `daemon` | The long-running daemon: the container's entry point; on a source install or macOS you start it yourself |+| *(none)* | The first time, the setup guide; after that, the status (and starts the service if it isn't running) |+| `setup [--reconfigure]` | Run the setup guide again; `--reconfigure` redoes one part (language, proxy, service, Apple ID, phone, auto-unlock, notifications, MCP registration) |+| `service install\|uninstall\|start\|stop\|restart\|status` | The background service (launchd on macOS, systemd user unit on Linux) |+| `daemon` | The long-running daemon; the service runs it, or start it by hand || `mcp` | The MCP server; your AI client starts it || `status` | Daemon state, time left on the signing profile, recent log || `doctor` | Layer-by-layer health check with a fix for each failure |-| `setup` | Guided setup; re-run any time || `login` | Sign in to the Apple ID again when the session expires || `sign` | Sign and install WebDriverAgent now || `resign [--force]` | Re-sign WebDriverAgent if it expires soon (or now) |@@ -136,11 +144,11 @@ Run them as `docker exec -it iphone-control iphone-control <command>`, or direct| `notify-test [event]` | Send test notifications || `mcp-config` | Print the command that registers the MCP server || `wda-bridge [--port]` | Expose WebDriverAgent on 127.0.0.1 for other tools; stop it when done |-| `viewer [--port]` | Watch the screen live in a browser and tap, swipe and type on it, on 127.0.0.1:8200; stop it when done |+| `viewer [--port]` | Control page on 127.0.0.1:8200: live screen you can tap, swipe and type on, device panel, and AI tasks run by a local Claude Code or Codex; stop it when done |All commands and options: [CLI reference](https://derrors.github.io/iphone-control/en/guide/cli).-Upgrade with `git pull && docker compose up -d --build` (or `docker compose pull && docker compose up -d --no-build` for the prebuilt image); for the binary and macOS, see [Source / binary](https://derrors.github.io/iphone-control/en/deploy/source#upgrade) and [macOS](https://derrors.github.io/iphone-control/en/deploy/macos#upgrade). Read the upgrade notes in the [changelog](CHANGELOG.md) first. Settings live in `.env` — see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration). All state lives in `data/`: pairing records, the Apple ID session and signing key, and the passcode if auto-unlock is on. **Back it up; never commit or share it.**+Upgrade by running `install.sh` again, with `brew upgrade iphone-control`, or by installing the new `.deb`; for a source build, see [build from source](https://derrors.github.io/iphone-control/en/deploy/source). Read the upgrade notes in the [changelog](CHANGELOG.md) first. Uninstall with `install.sh --uninstall`, `brew uninstall iphone-control` or `sudo apt remove iphone-control`; your data stays. Settings live in `~/.config/iphone-control/env`: the guide writes it, and after editing it by hand run `iphone-control service restart` — see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration). All state lives in `~/.local/share/iphone-control`: the Apple ID session and signing key, and the passcode if auto-unlock is on. **Back it up; never commit or share it.**## Documentation@@ -148,7 +156,7 @@ Upgrade with `git pull && docker compose up -d --build` (or `docker compose pull| --- | --- || Guide | [What is it](https://derrors.github.io/iphone-control/en/guide/what-is-iphone-control) · [Limitations](https://derrors.github.io/iphone-control/en/guide/what-is-iphone-control#limitations) · [Getting started](https://derrors.github.io/iphone-control/en/guide/getting-started) · [AI clients](https://derrors.github.io/iphone-control/en/guide/mcp-clients) · [Tools](https://derrors.github.io/iphone-control/en/guide/tools) || Usage | [Configuration](https://derrors.github.io/iphone-control/en/guide/configuration) · [CLI](https://derrors.github.io/iphone-control/en/guide/cli) · [Several devices](https://derrors.github.io/iphone-control/en/guide/multi-device) · [Notifications](https://derrors.github.io/iphone-control/en/guide/notifications) · [Auto-unlock](https://derrors.github.io/iphone-control/en/guide/auto-unlock) |-| Deployment | [Docker](https://derrors.github.io/iphone-control/en/deploy/docker) · [Source / binary](https://derrors.github.io/iphone-control/en/deploy/source) · [macOS](https://derrors.github.io/iphone-control/en/deploy/macos) · [Data and backups](https://derrors.github.io/iphone-control/en/deploy/backup) |+| Deployment | [Install](https://derrors.github.io/iphone-control/en/guide/getting-started#install) · [Build from source](https://derrors.github.io/iphone-control/en/deploy/source) · [macOS](https://derrors.github.io/iphone-control/en/deploy/macos) · [Data and backups](https://derrors.github.io/iphone-control/en/deploy/backup) || Problems | [FAQ](https://derrors.github.io/iphone-control/en/troubleshoot/faq) · [Troubleshooting](docs/troubleshooting.md) · [Issues](https://github.com/Derrors/iphone-control/issues) || Security | [SECURITY.md](SECURITY.md): what is stored, who can reach it, reporting vulnerabilities || Development | [Contributing](CONTRIBUTING.md) · [Architecture](docs/architecture.md) · [Decisions](docs/decisions.md) · [Changelog](CHANGELOG.md) |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 403d097..a286979 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -64,33 +64,41 @@ iphone-control 在 Linux 或 macOS 上用**一个 Rust 二进制**把这些事## 快速开始-需要一部 iOS 17 以上的 iPhone 或 iPad 和能**传数据**的线、一个免费 Apple ID(建议专门注册一个),以及一台装了 Docker 的 Linux 主机或一台 Apple Silicon 的 Mac。+需要一部 iOS 17 以上的 iPhone 或 iPad 和能**传数据**的线、一个免费 Apple ID(建议专门注册一个),以及一台 Apple Silicon 的 Mac 或一台 Linux 机器。-**Linux(Docker)**+**macOS 或 Linux,一行命令安装**```bash-git clone https://github.com/Derrors/iphone-control.git && cd iphone-control-cp .env.example .env # 可选:代理、通知;国内网络一般要配代理-docker compose up -d --build # 首次构建需要几分钟-docker exec -it iphone-control iphone-control setup # 安装向导,可重复运行-claude mcp add iphone -s user -- docker exec -i iphone-control iphone-control mcp+curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh```-**macOS**(Mac 上的 Docker 不能直通 USB,直接运行二进制)+它会下载适合这台机器的版本、校验 sha256,把 `iphone-control` 装到 `~/.local/bin`,并把守护进程装成登录后自动启动的用户服务(macOS 用 launchd,Linux 用 systemd)。它不会以 root 运行。再运行一次就是升级;`… | sh -s -- --uninstall` 卸载,数据保留。国内网络下载 Release 慢的话,先在终端里设好 `HTTPS_PROXY` 再运行。++**或者用包管理器**++```bash+# macOS 或 Linux(Homebrew)+brew install derrors/tap/iphone-control && brew services start iphone-control++# Debian 12+ / Ubuntu 22.04+:从 Releases 下载 .deb(amd64 或 arm64),会自动装上 usbmuxd+sudo apt install ./iphone-control_<版本>_amd64.deb && systemctl --user enable --now iphone-control+```++Linux 上要用系统的 usbmuxd(`sudo apt install usbmuxd`,.deb 会自动装上)。Intel 芯片的 Mac 请从源码编译。++**装好以后,各系统都一样**++用数据线接好手机,运行:```bash-V=v0.1.5 # 最新版本号-curl -fsSL https://github.com/Derrors/iphone-control/releases/download/$V/iphone-control-$V-macos-arm64.tar.gz | tar xz-mkdir -p ~/.local/bin && install -m 755 iphone-control-$V-macos-arm64/iphone-control ~/.local/bin/-echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zprofile && source ~/.zprofile-iphone-control daemon # 这个终端保持开着-iphone-control setup # 在另一个终端运行-iphone-control mcp-config # 打印 `claude mcp add` 命令,复制运行+iphone-control```-`setup` 会引导完成配对、开发者模式、登录 Apple ID、安装 WebDriverAgent,按提示在手机上操作即可。然后打开一个新的 Claude Code 会话,试着说:「打开时钟,切到秒表并启动」。+第一次运行时,它在终端里一步步带你完成设置:语言、代理、后台服务、配对、开发者模式、Apple ID、签名并安装 WebDriverAgent,可选的自动解锁和通知,最后注册到 Claude Code 和 Codex。按提示在手机上操作即可。做过的步骤会跳过;设置好以后再运行 `iphone-control` 只显示状态。-更多:[分步指南](https://derrors.github.io/iphone-control/guide/getting-started) · [预构建镜像](https://derrors.github.io/iphone-control/deploy/docker) · [二进制 / 源码](https://derrors.github.io/iphone-control/deploy/source) · [macOS 指南](https://derrors.github.io/iphone-control/deploy/macos) · [其他 MCP 客户端](https://derrors.github.io/iphone-control/guide/mcp-clients)+然后打开一个新的 Claude Code 或 Codex 会话,试着说:「打开时钟,切到秒表并启动」。也可以运行 `iphone-control viewer` 打开浏览器里的控制台(http://127.0.0.1:8200),在实时画面上直接操作,或把任务交给本机的 Claude Code 或 Codex。++更多:[分步指南](https://derrors.github.io/iphone-control/guide/getting-started) · [从源码编译](https://derrors.github.io/iphone-control/deploy/source) · [macOS 指南](https://derrors.github.io/iphone-control/deploy/macos) · [其他 MCP 客户端](https://derrors.github.io/iphone-control/guide/mcp-clients)## MCP 工具@@ -118,15 +126,15 @@ iphone-control mcp-config # 打印 `claude mcp add` 命令,复制运行## 常用命令-用 `docker exec -it iphone-control iphone-control <命令>` 运行;从源码运行和在 macOS 上直接调用。-| 命令 | 作用 || --- | --- |-| `daemon` | 常驻守护进程:容器的入口;从源码运行和 macOS 上要自己启动 |+| (不带命令) | 第一次是设置引导;设置好以后显示状态(后台服务没在运行时先启动它) |+| `setup [--reconfigure]` | 重新走一遍设置引导;`--reconfigure` 只改其中一项(语言、代理、后台服务、Apple ID、手机、自动解锁、通知、注册 MCP) |+| `service install\|uninstall\|start\|stop\|restart\|status` | 后台服务(macOS 是 launchd,Linux 是 systemd 用户服务) |+| `daemon` | 常驻守护进程;由后台服务运行,也可以手动启动 || `mcp` | MCP 服务,由 AI 客户端拉起 || `status` | 守护进程状态、描述文件还剩多久、最近日志 || `doctor` | 逐层诊断,每项失败都给出修复办法 |-| `setup` | 安装向导,随时可以重新运行 || `login` | Apple ID 会话失效时重新登录 || `sign` | 立即签名并安装 WebDriverAgent || `resign [--force]` | 快过期才重签 WebDriverAgent(或立即重签) |@@ -136,11 +144,11 @@ iphone-control mcp-config # 打印 `claude mcp add` 命令,复制运行| `notify-test [事件]` | 发送测试通知 || `mcp-config` | 打印注册 MCP 的命令 || `wda-bridge [--port]` | 把 WebDriverAgent 桥接到 127.0.0.1 给别的工具用,用完就停 |-| `viewer [--port]` | 在浏览器里看实时画面,并点击、滑动、输入,地址 127.0.0.1:8200;用完就停 |+| `viewer [--port]` | 控制台页面,地址 127.0.0.1:8200:实时画面可直接点击、滑动、输入,设备面板,还能把任务交给本机的 Claude Code 或 Codex 执行;用完就停 |全部命令和参数见[命令行](https://derrors.github.io/iphone-control/guide/cli)。-升级:`git pull && docker compose up -d --build`(用预构建镜像时改为 `docker compose pull && docker compose up -d --no-build`);二进制和 macOS 见[从源码 / 二进制](https://derrors.github.io/iphone-control/deploy/source#升级)、[macOS](https://derrors.github.io/iphone-control/deploy/macos#升级)。升级前先看[更新日志](CHANGELOG.zh-CN.md)里的升级注意事项。配置写在 `.env`,见[配置说明](https://derrors.github.io/iphone-control/guide/configuration)。所有状态都在 `data/`:配对记录、Apple ID 会话和签名私钥,开启自动解锁时还有锁屏密码。**要备份,不要提交或分享。**+升级:再运行一次 `install.sh`、`brew upgrade iphone-control`,或装上新的 `.deb`;从源码编译的见[从源码编译](https://derrors.github.io/iphone-control/deploy/source)。升级前先看[更新日志](CHANGELOG.zh-CN.md)里的升级注意事项。卸载:`install.sh --uninstall`、`brew uninstall iphone-control` 或 `sudo apt remove iphone-control`,数据保留。设置在 `~/.config/iphone-control/env`,由设置引导写好;手改后运行 `iphone-control service restart`,见[配置说明](https://derrors.github.io/iphone-control/guide/configuration)。所有状态都在 `~/.local/share/iphone-control`:Apple ID 会话和签名私钥,开启自动解锁时还有锁屏密码。**要备份,不要提交或分享。**## 文档@@ -148,7 +156,7 @@ iphone-control mcp-config # 打印 `claude mcp add` 命令,复制运行| --- | --- || 入门 | [什么是 iphone-control](https://derrors.github.io/iphone-control/guide/what-is-iphone-control) · [限制](https://derrors.github.io/iphone-control/guide/what-is-iphone-control#限制) · [快速开始](https://derrors.github.io/iphone-control/guide/getting-started) · [接入 AI 客户端](https://derrors.github.io/iphone-control/guide/mcp-clients) · [工具一览](https://derrors.github.io/iphone-control/guide/tools) || 使用 | [配置](https://derrors.github.io/iphone-control/guide/configuration) · [命令行](https://derrors.github.io/iphone-control/guide/cli) · [多台设备](https://derrors.github.io/iphone-control/guide/multi-device) · [通知](https://derrors.github.io/iphone-control/guide/notifications) · [自动解锁](https://derrors.github.io/iphone-control/guide/auto-unlock) |-| 安装 | [Docker](https://derrors.github.io/iphone-control/deploy/docker) · [从源码 / 二进制](https://derrors.github.io/iphone-control/deploy/source) · [macOS](https://derrors.github.io/iphone-control/deploy/macos) · [数据与备份](https://derrors.github.io/iphone-control/deploy/backup) |+| 安装 | [安装](https://derrors.github.io/iphone-control/guide/getting-started#install) · [从源码编译](https://derrors.github.io/iphone-control/deploy/source) · [macOS](https://derrors.github.io/iphone-control/deploy/macos) · [数据与备份](https://derrors.github.io/iphone-control/deploy/backup) || 问题 | [常见问题](https://derrors.github.io/iphone-control/troubleshoot/faq) · [排错(英文)](docs/troubleshooting.md) · [Issues](https://github.com/Derrors/iphone-control/issues) || 安全 | [SECURITY.md](SECURITY.md):存了什么、谁能访问、怎么报告漏洞 || 开发 | [贡献指南](CONTRIBUTING.md) · [架构](docs/architecture.md) · [关键取舍](docs/decisions.md) · [更新日志](CHANGELOG.zh-CN.md) |diff --git a/SECURITY.md b/SECURITY.mdindex e11b117..4c8ca4e 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -12,39 +12,39 @@ iphone-control is, by design, a remote control for a phone. Anyone who can talk| Asset | Where | Who can reach it ||---|---|---|-| Phone control (taps, typing, screenshots, apps) | Control socket: `/run/iphone-control/ctl.sock` inside the container, `$XDG_RUNTIME_DIR/iphone-control/ctl.sock` for a source install on Linux, `~/.local/share/iphone-control/ctl.sock` on macOS; mode 0600 | Root on the host; anyone who can `docker exec` into the container; the user running a source install or the macOS binary |-| WebDriverAgent (no authentication) | On the phone, reached through usbmuxd; nothing listens on the network unless you run `wda-bridge` | With `wda-bridge`: **every local user** on the host, because the container uses host networking. Browsers are blocked by a Host-header check (DNS rebinding), other local processes are not |-| Live viewer (`iphone-control viewer`, opt-in) | A page on `127.0.0.1` (port 8200 by default); nothing listens unless you run it. Bound to the device controlled when it starts | **Every local user** on the host can watch the screen and control the phone through the port: it has no login. Other web pages in a browser are blocked by the `Host`, `Origin` and JSON checks, other local processes are not |+| Phone control (taps, typing, screenshots, apps) | Control socket: `$XDG_RUNTIME_DIR/iphone-control/ctl.sock` on Linux, `~/.local/share/iphone-control/ctl.sock` on macOS; mode 0600 | The user the daemon runs as, and root |+| WebDriverAgent (no authentication) | On the phone, reached through usbmuxd; nothing listens on the network unless you run `wda-bridge` | With `wda-bridge`: **every local user** on the host, since the port is on 127.0.0.1. Browsers are blocked by a Host-header check (DNS rebinding), other local processes are not |+| Live viewer (`iphone-control viewer`, opt-in) | A page on `127.0.0.1` (port 8200 by default); nothing listens unless you run it. Follows the device the daemon controls. Its AI tasks run Claude Code or Codex as the user who started the viewer, and their MCP servers report to it over a Unix socket next to the control socket (`viewer-<port>.sock`, mode 0600, a secret token per task) | **Every local user** on the host can watch the screen, control the phone and start AI tasks (which use that user's agent login) through the port: it has no login. Other web pages in a browser are blocked by the `Host`, `Origin`, JSON and `Sec-Fetch-Site` checks, other local processes are not || Apple ID session tokens, development signing key and certificate | `account/` in the data directory (0700, key 0600) | Whoever can read the data directory. The Apple ID password itself is never stored |-| Pairing records | `lockdown/` in the data directory (container), the system's `/var/lib/lockdown` (source install on Linux) or `/var/db/lockdown` (macOS, shared with Finder) | Root on the host. A pairing record lets its holder talk to the phone over USB without another *Trust* prompt |+| Pairing records | The system's `/var/lib/lockdown` (Linux, kept by usbmuxd) or `/var/db/lockdown` (macOS, shared with Finder) | Root on the host. A pairing record lets its holder talk to the phone over USB without another *Trust* prompt || Lock-screen passcodes | `secrets/passcodes/<UDID>` in the data directory (0600), one file per device, **plain text**, only if you ran `passcode set`. A `secrets/passcode` file from an older version is moved to the device's file when exactly one device is connected, and stays where it is until then | Whoever can read the data directory |-| Notification credentials (Bark key, Telegram token) | `.env` or `~/.config/iphone-control/env` | Whoever can read that file |+| Notification credentials (Bark key, Telegram token) | `~/.config/iphone-control/env` (mode 0600) | Whoever can read that file |-The data directory is `./data` next to `compose.yaml` for the container (root-owned, mode 0700) and `~/.local/share/iphone-control` for a source install and on macOS.+The data directory is `~/.local/share/iphone-control`. Everything runs as your regular user; `install.sh` refuses to run as root.## Design choices that limit exposure-- No network listener by default. WebDriverAgent is reached through usbmuxd. `wda-bridge` and `viewer` are opt-in and bind 127.0.0.1 only, and both are meant to be stopped after use. `wda-bridge` only forwards requests whose Host header is a loopback name. `viewer` checks the Host header the same way; its actions also need an `Origin` of the viewer page itself and a JSON body, so other web pages can't act through it, and each action carries the UDID of the device the viewer was started for, so the daemon refuses it once another device is controlled.+- No network listener by default. WebDriverAgent is reached through usbmuxd. `wda-bridge` and `viewer` are opt-in and bind 127.0.0.1 only, and both are meant to be stopped after use. `wda-bridge` only forwards requests whose Host header is a loopback name. `viewer` checks the Host header the same way; its actions also need an `Origin` of the viewer page itself and a JSON body, so other web pages can't act through it, reads a browser marks as coming from another site (`Sec-Fetch-Site`) are refused, and each action carries the UDID of the device the page follows, so the daemon refuses it once another device is controlled.- The control socket is a Unix socket with mode 0600, not TCP.-- The container is not `privileged`: it is only allowed USB character devices (major 189), and the tunnel to the phone uses a user-space TCP stack, so no network interface or routing changes on the host.+- The tunnel to the phone uses a user-space TCP stack, so no network interface or routing changes on the host, and the daemon needs no root.- Auto-unlock is off by default. When enabled, it stops for good after a single wrong attempt (it writes a stop marker, `logs/UNLOCK-DISABLED`, before entering the second digit) and sends a notification; it never retries a passcode that might be wrong. The marker is global: a failure on one device stops auto-unlock on all of them until you run `unlock-reset`. It does not work before the first unlock after a reboot (BFU) — that always needs a person.-- Dependencies are pinned to exact versions, `Cargo.lock` is committed, base images are pinned by digest, and the WebDriverAgent download is checked against a sha256. CI runs gitleaks on every push.+- Dependencies are pinned to exact versions, `Cargo.lock` is committed, release archives come with a sha256 that `install.sh` checks, and the WebDriverAgent download is checked against a sha256. CI runs gitleaks on every push.## Known risks and recommendations-- **The container runs as root.** It needs read-write access to the USB device nodes and must restart `usbmuxd` after the phone is re-plugged (the container has no udev). Running it unprivileged would need host udev rules and is not supported yet. Keep the host itself locked down.+- **Anyone who can act as your user can control the phone.** The daemon runs as a per-user service and talks to the phone through the system usbmuxd. Keep the account and the host locked down.- **Third-party anisette server.** Apple ID logins need "anisette" data that normally only Apple hardware produces. By default it comes from a public server (`https://mac-ani.jkcoxson.com`, the default of the Impactor/omnisette libraries). The server does not receive your Apple ID password, but your logins depend on an identity it provisions, and it sees when you log in. Set `ICTL_ANISETTE_URL` to an [anisette-v3 server](https://github.com/Dadoum/anisette-v3-server) you run yourself to avoid this.- **Use a dedicated Apple ID.** The session token and signing key on disk are enough to manage that account's development certificates and devices. A separate free account limits the damage if the host is compromised and keeps your main account clear of developer-account restrictions.- **Auto-unlock stores your passcode in plain text.** Anyone with root on the host, or access to backups of the data directory, can read it — and the passcode is also what protects the phone's data and Apple ID. Only enable it on a host you fully control, and prefer leaving Auto-Lock off on a phone dedicated to automation.-- **Agents act with your hands.** An agent with these tools can send messages, make purchases and change settings. The MCP server tells agents to ask before paying, deleting, sending messages or changing account or privacy settings, but that is an instruction, not an enforcement mechanism. Use a phone and accounts you are comfortable automating.-- **Back up the data directory securely**, and never commit it. `.gitignore` and `.dockerignore` exclude `data/`, `.env` and key material, so they don't end up in git or in image layers.+- **Agents act with your hands.** An agent with these tools can send messages, make purchases and change settings. The MCP server tells agents to ask before paying, deleting, sending messages or changing account or privacy settings, but that is an instruction, not an enforcement mechanism. The same goes for AI tasks started from the viewer: the agent is told to call `iphone_confirm` first and the page waits for your answer, and a step you reject is refused, but an agent that skips the call isn't stopped. There it gets only the phone tools (Claude Code without its shell and file tools, Codex in a read-only sandbox). Use a phone and accounts you are comfortable automating.+- **Back up the data directory securely**, and never commit it or the settings file. `.gitignore` excludes `data/`, `secrets/` and key material in case you keep copies next to the source.## Developer tools`IPHONE_CONTROL_DEV_TOOLS=1` adds six MCP tools that reach well beyond the screen. They are off by default; turn them on for the work that needs them and off again afterwards.- **`iphone_web_eval` runs arbitrary JavaScript** in any inspectable page, including Safari tabs. A script can read cookies that aren't HttpOnly and `localStorage`, and submit forms or send requests as the logged-in user.-- **`iphone_install_app` accepts any path on the machine that runs the daemon.** In the container the daemon is root.+- **`iphone_install_app` accepts any path on the machine that runs the daemon** that the daemon's user can read.- **`iphone_app_logs` reads the system log of every process**, and `iphone_crash_reports` returns full crash reports. Both end up in the agent's context and can contain private data.- **`iphone_uninstall_app` deletes an app and its data.** It refuses the WebDriverAgent runner and only accepts a bundle ID or the app's exact display name.- **The switch is not a permission boundary.** `IPHONE_CONTROL_DEV_TOOLS` only decides whether the MCP server offers these tools. The daemon always accepts the requests, so anyone who can reach the control socket (mode 0600, so the same user or root) can use them with the switch off.diff --git a/THIRD_PARTY.md b/THIRD_PARTY.mdindex f02d429..da7099f 100644--- a/THIRD_PARTY.md+++ b/THIRD_PARTY.md@@ -14,11 +14,11 @@| Impactor `plume_utils` | 同上 | MIT | 未 vendor;`crates/ictl-sign/src/bundle.rs` 改写自其 `bundle.rs` | 增加 `BundleType::XCTest`,修复 `.xctest` 漏签 || idevice tools | v0.1.68 | MIT | `crates/ictl-device/src/media.rs`、`hid.rs` 的按键/键码表改写自 `tools/src/coredevice_stream.rs`、`hid.rs` | 去掉日志、改错误类型 || idevice os_trace_relay | 上游 master `89702099` | MIT | `crates/ictl-device/src/oslog.rs` 的日志条目格式取自 `idevice/src/services/os_trace_relay.rs` | 请求里去掉 Debug 位,解析加越界检查 |-| [WebDriverAgent](https://github.com/appium/WebDriverAgent) | v16.15.3(Appium 官方构建,sha256 2176793538d9…) | BSD-3-Clause | 镜像构建时下载校验,打成未签名 IPA;计划改为本项目 macOS CI 编译 | 不嵌入苹果框架 |-| [usbmuxd](https://github.com/libimobiledevice/usbmuxd) | Debian 包 | GPL-3.0 | 独立进程,不链接 | 无 |+| [WebDriverAgent](https://github.com/appium/WebDriverAgent) | v16.15.3(Appium 官方构建,sha256 2176793538d9…) | BSD-3-Clause | 第一次签名前在用户的机器上下载、校验,打成未签名 IPA,不随项目分发;计划改为本项目 macOS CI 编译 | 不嵌入苹果框架 |+| [usbmuxd](https://github.com/libimobiledevice/usbmuxd) | 系统包(Linux;macOS 自带) | GPL-3.0 | 独立进程,不链接,不随项目分发(.deb 只声明依赖它) | 无 |**不随项目分发**:开发者镜像(DDI/Cryptex)、XCTest.framework 等苹果文件;证书、描述文件、配对记录、Apple ID 会话等用户数据。因为不启用 omnisette 的默认 feature,AGPL-3.0 的过程宏 `remove-async-await` 和没有许可证声明的 `android-loader`/`sysv64` 都不会被编译。-完整的传递依赖许可证清单由 cargo-about 0.9.3 按 `Cargo.lock` 生成(配置 `docker/about.toml`),随镜像放在 `/usr/share/doc/iphone-control/THIRD_PARTY_LICENSES.html`。vendor 组件的许可证另放在 `/usr/share/licenses/<组件>/`(plume_store 的 MIT 许可证在 `/usr/share/licenses/plume_store/LICENSE`),WDA 的在 `/usr/share/licenses/WebDriverAgent/`。这些只随镜像分发:预编译二进制的压缩包只带 `LICENSE` 和本文件。+完整的传递依赖许可证清单 `THIRD_PARTY_LICENSES.html` 由 cargo-about 0.9.3 按 `Cargo.lock` 生成(配置 `packaging/licenses/about.toml`),放在每个发布的压缩包里,.deb 里在 `/usr/share/doc/iphone-control/THIRD_PARTY_LICENSES.html`。vendor 组件的许可证文件在仓库的 `vendor/<组件>/` 里。diff --git a/apps/iphone-control/Cargo.toml b/apps/iphone-control/Cargo.tomlindex 0c8c38b..a741505 100644--- a/apps/iphone-control/Cargo.toml+++ b/apps/iphone-control/Cargo.toml@@ -21,6 +21,8 @@ tokio.workspace = trueanyhow.workspace = truerustls.workspace = trueserde_json.workspace = true+uuid.workspace = true+libc.workspace = truetracing.workspace = truetracing-subscriber.workspace = true@@ -28,3 +30,27 @@ tracing-subscriber.workspace = true# `iphone-control debug …` 真机诊断子命令(直接调设备层和 WDA,不经守护进程),开发时用,默认不编进去:# cargo build --features debug-cmdsdebug-cmds = ["dep:ictl-wda"]++# `cargo deb -p iphone-control` (release workflow): the Debian/Ubuntu package+[package.metadata.deb]+name = "iphone-control"+maintainer = "Derrors <[email protected]>"+copyright = "Derrors"+license-file = ["../../LICENSE", "0"]+extended-description = """\+Lets an AI agent operate a real iPhone or iPad over USB: a long-running daemon owns the phone (tunnel, \+WebDriverAgent, HID) and exposes it to Claude Code or any MCP client, plus a control page in the browser that \+hands tasks to a local Claude Code or Codex. Runs as a systemd user service; see /usr/share/doc/iphone-control."""+section = "utils"+priority = "optional"+depends = "$auto, usbmuxd"+maintainer-scripts = "../../deploy/deb"+assets = [+ ["target/release/iphone-control", "usr/bin/", "755"],+ ["../../deploy/deb/iphone-control.service", "usr/lib/systemd/user/", "644"],+ ["../../packaging/env.example", "usr/share/doc/iphone-control/env.example", "644"],+ ["../../THIRD_PARTY_LICENSES.html", "usr/share/doc/iphone-control/", "644"],+ ["../../README.md", "usr/share/doc/iphone-control/", "644"],+ ["../../README.zh-CN.md", "usr/share/doc/iphone-control/", "644"],+ ["../../THIRD_PARTY.md", "usr/share/doc/iphone-control/", "644"],+]diff --git a/apps/iphone-control/src/agent.rs b/apps/iphone-control/src/agent.rsnew file mode 100644index 0000000..457f26a--- /dev/null+++ b/apps/iphone-control/src/agent.rs@@ -0,0 +1,989 @@+//! AI tasks for the web viewer: a prompt typed on the page goes to a local agent (Claude Code or Codex), which works+//! the phone through `iphone-control mcp`, and the page follows every step.+//!+//! - The agent runs as a child process (`claude -p … --output-format stream-json` or `codex exec --json …`) in its+//! own process group, with only this program's MCP server and none of its built-in tools that touch the machine.+//! - Its MCP server gets the task gate ([`ictl_mcp::gate`]): before each tool call it asks the viewer over a Unix+//! socket next to the daemon's ([`GateServer`]), after the call it reports the result. That is where steps come+//! from, where a pause or the user taking over holds the agent, and where [`ictl_mcp::gate::CONFIRM_TOOL`] waits+//! for the user's answer. The agent's own output only adds what it says it is doing (attached to the next step)+//! and its final summary.+//! - The page gets the task as server-sent events: `step`, `confirm`, `state`, `done`. Every event is kept, so a+//! page that (re)connects gets the whole task replayed.+//!+//! One task at a time: there is one phone. While a task runs and the user hasn't taken over, the viewer refuses the+//! page's manual actions ([`Agents::manual_allowed`]), so the user and the agent don't tap at the same time.++use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use serde_json::{Map, Value, json};+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};+use tokio::sync::{Notify, broadcast, oneshot};++/// Longest prompt accepted (the page limits the text box to the same)+pub const MAX_PROMPT: usize = 4000;+/// Finished tasks kept for replay; each can hold dozens of screenshots+const KEEP_FINISHED: usize = 4;+/// A thought printed by the agent this soon after a step started belongs to that step (it reached the viewer+/// through the agent's stdout, slightly after the tool call reached the gate)+const LATE_THOUGHT: Duration = Duration::from_secs(2);+/// Tools that look without acting: allowed right after the user hands control back+const LOOKING: [&str; 3] = ["iphone_screenshot", "iphone_list_elements", "iphone_status"];++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Backend {+ Claude,+ Codex,+}++impl Backend {+ pub const ALL: [Backend; 2] = [Backend::Claude, Backend::Codex];++ pub fn id(self) -> &'static str {+ match self {+ Self::Claude => "claude",+ Self::Codex => "codex",+ }+ }++ pub fn name(self) -> &'static str {+ match self {+ Self::Claude => "Claude Code",+ Self::Codex => "Codex",+ }+ }++ pub fn parse(s: &str) -> Option<Self> {+ Self::ALL.into_iter().find(|b| b.id() == s)+ }++ /// The CLI on `PATH`+ pub fn find(self) -> Option<PathBuf> {+ let path = std::env::var_os("PATH")?;+ std::env::split_paths(&path).map(|d| d.join(self.id())).find(|p| is_executable(p))+ }+}++fn is_executable(p: &Path) -> bool {+ use std::os::unix::fs::PermissionsExt;+ std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)+}++/// `[{ id, name, available }]` for the page's agent picker+pub fn backends() -> Value {+ Value::Array(+ Backend::ALL.iter().map(|b| json!({"id": b.id(), "name": b.name(), "available": b.find().is_some()})).collect(),+ )+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Status {+ Running,+ Paused,+ Takeover,+ Waiting,+ Done,+}++impl Status {+ fn name(self) -> &'static str {+ match self {+ Self::Running => "running",+ Self::Paused => "paused",+ Self::Takeover => "takeover",+ Self::Waiting => "waiting",+ Self::Done => "done",+ }+ }+}++/// One event for the page: SSE event name and its JSON data+#[derive(Debug, Clone)]+pub struct Event {+ pub name: &'static str,+ pub data: Value,+}++struct TaskState {+ status: Status,+ log: Vec<Event>,+ next_step: u64,+ /// What the agent said it is about to do, for the next step+ thought: Option<String>,+ /// The latest step: id, when it started, still running, has a thought+ last: Option<(u64, Instant, bool, bool)>,+ /// Steps by id whose tool taps by text: where it tapped comes with the result+ taps_by_text: Vec<u64>,+ /// The user handed control back: the agent looks at the screen again before acting+ recheck: bool,+ confirm: Option<(u64, oneshot::Sender<bool>)>,+ /// The agent's last words, the summary when it ends without a result line+ last_text: Option<String>,+ summary: Option<String>,+ failure: Option<String>,+ pid: Option<u32>,+ stopped: bool,+ /// The user turned down a step: the task ends as stopped, not as done+ rejected: bool,+}++pub struct Task {+ pub id: String,+ token: String,+ /// The page's language when the task started: its messages and the agent's tools use it+ lang: ictl_l10n::Lang,+ st: Mutex<TaskState>,+ tx: broadcast::Sender<Event>,+ /// Wakes calls held at the gate when the status changes+ changed: Notify,+}++impl Task {+ fn lock(&self) -> std::sync::MutexGuard<'_, TaskState> {+ self.st.lock().unwrap_or_else(|p| p.into_inner())+ }++ fn emit(&self, st: &mut TaskState, name: &'static str, data: Value) {+ let e = Event { name, data };+ st.log.push(e.clone());+ let _ = self.tx.send(e);+ }++ fn set_status(&self, st: &mut TaskState, s: Status) {+ if st.status != s && st.status != Status::Done {+ st.status = s;+ if s != Status::Done {+ self.emit(st, "state", json!({"state": s.name()}));+ }+ self.changed.notify_waiters();+ }+ }++ /// The whole task so far, and the events after it (taken together, so nothing falls between)+ pub fn subscribe(&self) -> (Vec<Event>, broadcast::Receiver<Event>, bool) {+ let st = self.lock();+ (st.log.clone(), self.tx.subscribe(), st.status == Status::Done)+ }++ fn thought(&self, text: &str) {+ let text = text.trim();+ if text.is_empty() {+ return;+ }+ let mut st = self.lock();+ st.last_text = Some(text.to_owned());+ match st.last {+ // arrived just after its step reached the gate+ Some((id, at, true, false)) if at.elapsed() < LATE_THOUGHT => {+ st.last = Some((id, at, true, true));+ self.emit(&mut st, "step", json!({"id": id, "thought": text}));+ }+ _ => st.thought = Some(text.to_owned()),+ }+ }++ fn finish(&self, ok: bool, stopped: bool, summary: String) {+ let mut st = self.lock();+ if st.status == Status::Done {+ return;+ }+ st.status = Status::Done;+ if let Some((_, tx)) = st.confirm.take() {+ let _ = tx.send(false);+ }+ self.emit(&mut st, "done", json!({"ok": ok, "stopped": stopped, "summary": summary}));+ self.changed.notify_waiters();+ }++ fn is_done(&self) -> bool {+ self.lock().status == Status::Done+ }+}++#[derive(Default)]+struct Registry {+ tasks: Vec<Arc<Task>>,+}++pub struct Agents {+ reg: Mutex<Registry>,+ /// This program, for the agent's MCP server+ exe: PathBuf,+ socket: PathBuf,+ gate: PathBuf,+ workdir: PathBuf,+}++impl Agents {+ pub fn new(socket: &Path, gate: PathBuf) -> anyhow::Result<Arc<Self>> {+ let workdir = std::env::temp_dir().join(format!("iphone-control-agent-{}", unsafe { libc::getuid() }));+ std::fs::create_dir_all(&workdir)?;+ Ok(Arc::new(Self {+ reg: Mutex::default(),+ exe: std::env::current_exe()?,+ socket: socket.to_path_buf(),+ gate,+ workdir,+ }))+ }++ fn reg(&self) -> std::sync::MutexGuard<'_, Registry> {+ self.reg.lock().unwrap_or_else(|p| p.into_inner())+ }++ pub fn task(&self, id: &str) -> Option<Arc<Task>> {+ self.reg().tasks.iter().find(|t| t.id == id).cloned()+ }++ fn active(&self) -> Option<Arc<Task>> {+ self.reg().tasks.iter().find(|t| !t.is_done()).cloned()+ }++ /// The page may act on the phone itself: no task, or the user has taken over+ pub fn manual_allowed(&self) -> bool {+ self.active().is_none_or(|t| t.lock().status == Status::Takeover)+ }++ pub fn busy(&self) -> bool {+ self.active().is_some()+ }++ /// Starts a task; `Err` is a message for the page+ pub fn start(self: &Arc<Self>, prompt: &str, backend: &str) -> Result<String, String> {+ let prompt = prompt.trim();+ if prompt.is_empty() {+ return Err(ictl_l10n::tr!("先写下要 AI 做的事", "Write what the AI should do first").into());+ }+ if prompt.chars().count() > MAX_PROMPT {+ return Err(ictl_l10n::trf!(+ "任务描述太长,最多 {MAX_PROMPT} 个字",+ "The task is too long, at most {MAX_PROMPT} characters"+ ));+ }+ let Some(backend) = Backend::parse(backend) else {+ return Err(ictl_l10n::trf!("不认识的 agent「{backend}」", "Unknown agent “{backend}”"));+ };+ let Some(program) = backend.find() else {+ return Err(ictl_l10n::trf!(+ "这台机器上没有找到 {}(PATH 里没有 {})",+ "{} isn't installed on this machine ({} isn't on PATH)",+ backend.name(),+ backend.id()+ ));+ };+ let task = {+ let mut reg = self.reg();+ if reg.tasks.iter().any(|t| !t.is_done()) {+ return Err(ictl_l10n::tr!(+ "已经有一个任务在执行,等它结束或先停止它",+ "A task is already running; wait for it to end or stop it first"+ )+ .into());+ }+ // all finished by now: keep the newest few for pages that reconnect+ while reg.tasks.len() >= KEEP_FINISHED {+ reg.tasks.remove(0);+ }+ let task = Arc::new(Task {+ id: uuid::Uuid::new_v4().simple().to_string()[..12].to_owned(),+ token: uuid::Uuid::new_v4().simple().to_string(),+ lang: ictl_l10n::lang(),+ st: Mutex::new(TaskState {+ status: Status::Running,+ log: Vec::new(),+ next_step: 1,+ thought: None,+ last: None,+ taps_by_text: Vec::new(),+ recheck: false,+ confirm: None,+ last_text: None,+ summary: None,+ failure: None,+ pid: None,+ stopped: false,+ rejected: false,+ }),+ tx: broadcast::channel(1024).0,+ changed: Notify::new(),+ });+ reg.tasks.push(task.clone());+ task+ };+ let me = self.clone();+ let (t, prompt) = (task.clone(), prompt.to_owned());+ let lang = task.lang;+ tokio::spawn(ictl_l10n::scope(lang, async move {+ if let Err(e) = me.run(&t, backend, &program, &prompt).await {+ t.finish(+ false,+ false,+ ictl_l10n::trf!("{} 没能启动或中途出错:{e}", "{} didn't start or failed: {e}", backend.name()),+ );+ }+ }));+ Ok(task.id.clone())+ }++ /// pause / resume / takeover / handback / stop / confirm from the page+ pub fn control(&self, id: &str, action: &str, body: &Value) -> Result<(), String> {+ let Some(task) = self.task(id) else { return Err(ictl_l10n::tr!("没有这个任务", "No such task").into()) };+ let mut st = task.lock();+ if st.status == Status::Done {+ return Err(ictl_l10n::tr!("任务已经结束", "The task has ended").into());+ }+ match (action, st.status) {+ ("pause", Status::Running) => task.set_status(&mut st, Status::Paused),+ ("resume", Status::Paused) => task.set_status(&mut st, Status::Running),+ ("takeover", Status::Running | Status::Paused) => task.set_status(&mut st, Status::Takeover),+ ("handback", Status::Takeover) => {+ st.recheck = true;+ task.set_status(&mut st, Status::Running);+ }+ ("confirm", Status::Waiting) => {+ let approve = body["approve"].as_bool().unwrap_or(false);+ let want = body["step"].as_u64();+ match st.confirm.take() {+ Some((step, tx)) if want.is_none_or(|w| w == step) => {+ let _ = tx.send(approve);+ }+ other => {+ st.confirm = other;+ return Err(ictl_l10n::tr!(+ "这一步已经不在等确认了",+ "That step is no longer waiting for confirmation"+ )+ .into());+ }+ }+ }+ ("stop", _) => {+ st.stopped = true;+ let pid = st.pid;+ let n = st.next_step - 1;+ drop(st);+ if let Some(pid) = pid {+ kill_group(pid);+ }+ task.finish(+ false,+ true,+ ictl_l10n::trf!(+ "在第 {n} 步停下了。已经做完的操作不会撤销。",+ "Stopped at step {n}. What was already done isn't undone."+ ),+ );+ return Ok(());+ }+ (a, s) => return Err(ictl_l10n::trf!("现在({})不能{a}", "Can't {a} now ({})", s.name())),+ }+ Ok(())+ }++ async fn run(&self, task: &Arc<Task>, backend: Backend, program: &Path, prompt: &str) -> anyhow::Result<()> {+ let mut cmd = tokio::process::Command::new(program);+ cmd.args(self.agent_args(backend, &task.token, prompt))+ .current_dir(&self.workdir)+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped())+ // the agent's tool calls can wait for the user (a pause, a confirmation): no MCP timeout in practice+ .env("MCP_TOOL_TIMEOUT", "86400000")+ .process_group(0)+ .kill_on_drop(true);+ let mut child = cmd.spawn()?;+ task.lock().pid = child.id();+ let stdout = child.stdout.take().ok_or_else(|| anyhow::anyhow!("no stdout"))?;+ let stderr = child.stderr.take().ok_or_else(|| anyhow::anyhow!("no stderr"))?;+ let errs = tokio::spawn(async move {+ let mut tail: Vec<String> = Vec::new();+ let mut lines = BufReader::new(stderr).lines();+ while let Ok(Some(l)) = lines.next_line().await {+ tail.push(l);+ if tail.len() > 20 {+ tail.remove(0);+ }+ }+ tail+ });+ let mut lines = BufReader::new(stdout).lines();+ while let Some(line) = lines.next_line().await? {+ let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };+ match parse_line(backend, &v) {+ Some(Out::Thought(t)) => task.thought(&t),+ Some(Out::Summary(t)) => task.lock().summary = Some(t),+ Some(Out::Failure(t)) => task.lock().failure = Some(t),+ None => {}+ }+ }+ let status = child.wait().await?;+ let tail = errs.await.unwrap_or_default();+ let (summary, failure, stopped, rejected) = {+ let st = task.lock();+ (st.summary.clone().or_else(|| st.last_text.clone()), st.failure.clone(), st.stopped, st.rejected)+ };+ if stopped {+ return Ok(());+ }+ if rejected && failure.is_none() {+ let s = summary.unwrap_or_else(|| {+ ictl_l10n::tr!(+ "你拒绝了一步操作,任务在那里停下了。",+ "You rejected a step, so the task stopped there."+ )+ .into()+ });+ task.finish(false, true, s);+ return Ok(());+ }+ let ok = status.success() && failure.is_none();+ let summary = match (ok, summary, failure) {+ (true, Some(s), _) => s,+ (true, None, _) => {+ ictl_l10n::tr!("任务结束了,agent 没有给出总结。", "The task ended without a summary from the agent.")+ .into()+ }+ (false, s, f) => {+ let why = f+ .or_else(|| tail.iter().rev().find(|l| !l.trim().is_empty()).cloned())+ .unwrap_or_else(|| ictl_l10n::trf!("{} 退出({status})", "{} exited ({status})", backend.name()));+ match s {+ Some(s) => format!("{s}\n({why})"),+ None => why,+ }+ }+ };+ task.finish(ok, false, summary);+ Ok(())+ }++ fn agent_args(&self, backend: Backend, token: &str, prompt: &str) -> Vec<String> {+ let exe = self.exe.to_string_lossy().into_owned();+ let socket = self.socket.to_string_lossy().into_owned();+ let gate = self.gate.to_string_lossy().into_owned();+ let mut env = Map::new();+ env.insert(ictl_mcp::gate::GATE_ENV.into(), gate.clone().into());+ env.insert(ictl_mcp::gate::TOKEN_ENV.into(), token.into());+ // the agent's tools answer in the task's language (this runs in its scope, see `start`)+ env.insert("IPHONE_CONTROL_LANG".into(), ictl_l10n::lang().code().into());+ let s = |v: &str| v.to_owned();+ match backend {+ Backend::Claude => {+ let mcp = json!({"mcpServers": {"iphone": {"command": exe, "args": ["--socket", socket, "mcp"], "env": env}}});+ vec![+ s("-p"),+ s(prompt),+ s("--output-format"),+ s("stream-json"),+ s("--verbose"),+ s("--strict-mcp-config"),+ s("--mcp-config"),+ mcp.to_string(),+ // none of the built-in tools (shell, files, web): only the phone+ s("--tools"),+ s(""),+ s("--allowedTools"),+ s("mcp__iphone"),+ s("--permission-mode"),+ s("dontAsk"),+ s("--no-session-persistence"),+ s("--append-system-prompt"),+ s(instructions()),+ ]+ }+ Backend::Codex => {+ // TOML values; a JSON string is a valid TOML basic string+ let q = |v: &str| Value::from(v).to_string();+ let env_toml = env.iter().map(|(k, v)| format!("{k}={}", v)).collect::<Vec<_>>().join(",");+ vec![+ s("exec"),+ s("--json"),+ s("--skip-git-repo-check"),+ s("--ephemeral"),+ // the agent's own shell can read but not change anything; it is told to use only the phone tools+ s("--sandbox"),+ s("read-only"),+ s("-C"),+ self.workdir.to_string_lossy().into_owned(),+ s("-c"),+ format!("mcp_servers.iphone.command={}", q(&exe)),+ s("-c"),+ format!("mcp_servers.iphone.args=[{},{},{}]", q("--socket"), q(&socket), q("mcp")),+ s("-c"),+ format!("mcp_servers.iphone.env={{{env_toml}}}"),+ s("-c"),+ s("mcp_servers.iphone.tool_timeout_sec=86400"),+ // the task gate asks the user where it matters (iphone_confirm); Codex's own approval for+ // tools marked destructive would refuse every tap in a non-interactive run+ s("-c"),+ s("mcp_servers.iphone.default_tools_approval_mode=\"approve\""),+ s("-c"),+ s("suppress_unstable_features_warning=true"),+ format!("{}\n\n{}{prompt}", instructions(), ictl_l10n::tr!("任务:", "Task: ")),+ ]+ }+ }+ }++ /// One gate message from the agent's MCP server; the reply line+ async fn gate(&self, msg: Value) -> Value {+ let token = msg["token"].as_str().unwrap_or_default();+ let task = self.reg().tasks.iter().find(|t| t.token == token).cloned();+ let Some(task) = task else {+ return refuse(ictl_l10n::tr!(+ "这个任务已经不在了:停下来,不要再操作手机",+ "This task no longer exists: stop and don't act on the phone any more"+ ));+ };+ ictl_l10n::scope(task.lang, async {+ match msg["op"].as_str() {+ Some("before") => task.before(msg["tool"].as_str().unwrap_or_default(), &msg["args"]).await,+ Some("after") => {+ task.after(&msg);+ json!({})+ }+ Some("confirm") => task.confirm(&msg).await,+ _ => refuse("bad gate message"),+ }+ })+ .await+ }+}++fn refuse(message: &str) -> Value {+ json!({"go": false, "approve": false, "message": message})+}++impl Task {+ /// Holds the call while the task is paused, taken over or waiting; then records it as a step+ async fn before(&self, tool: &str, args: &Value) -> Value {+ loop {+ let notified = self.changed.notified();+ {+ let mut st = self.lock();+ if st.status == Status::Done || st.stopped {+ return refuse(ictl_l10n::tr!(+ "用户停止了这个任务:不要再调用任何工具,直接结束",+ "The user stopped this task: don't call any more tools, just finish"+ ));+ }+ if st.status == Status::Running {+ if tool == "iphone_select_device" {+ return refuse(ictl_l10n::tr!(+ "网页上的任务不能切换设备,继续操作当前这台",+ "A task from the web page can't switch devices; keep using the current one"+ ));+ }+ if st.recheck && !LOOKING.contains(&tool) {+ st.recheck = false;+ return refuse(ictl_l10n::tr!(+ "用户刚才接管并操作过手机,界面可能已经变了:先用 iphone_screenshot 重新看一遍,再决定下一步",+ "The user took over and used the phone, so the screen may have changed: look again with iphone_screenshot before the next step"+ ));+ }+ st.recheck = false;+ let id = st.next_step;+ st.next_step += 1;+ let thought = st.thought.take();+ st.last = Some((id, Instant::now(), true, thought.is_some()));+ let mut d = json!({"id": id, "tool": tool, "args": args, "status": "running"});+ if let Some(t) = thought {+ d["thought"] = t.into();+ }+ if let Some(g) = gesture(tool, args, "") {+ d["gesture"] = g;+ }+ if tool == "iphone_tap_element" {+ st.taps_by_text.push(id);+ }+ self.emit(&mut st, "step", d);+ return json!({"go": true, "step": id});+ }+ }+ notified.await;+ }+ }++ fn after(&self, msg: &Value) {+ let mut st = self.lock();+ let Some(id) = msg["step"].as_u64() else { return };+ if let Some((last, at, _, th)) = st.last+ && last == id+ {+ st.last = Some((last, at, false, th));+ }+ let ok = msg["ok"].as_bool().unwrap_or(true);+ let text = msg["text"].as_str().unwrap_or_default();+ let mut d = json!({"id": id, "status": if ok { "ok" } else { "error" }, "ms": msg["ms"], "result": first_lines(text, 6)});+ // where iphone_tap_element tapped is only known now, from its result+ let by_text = st.taps_by_text.iter().position(|&s| s == id).map(|i| st.taps_by_text.swap_remove(i));+ if ok+ && by_text.is_some()+ && let Some(g) = gesture("iphone_tap_element", &Value::Null, text)+ {+ d["gesture"] = g;+ }+ self.emit(&mut st, "step", d);+ }++ async fn confirm(&self, msg: &Value) -> Value {+ let (rx, id) = {+ let mut st = self.lock();+ if st.status == Status::Done || st.stopped {+ return refuse(ictl_l10n::tr!("用户停止了这个任务", "The user stopped this task"));+ }+ let id = st.next_step;+ st.next_step += 1;+ let thought = st.thought.take();+ let (action, detail) =+ (msg["action"].as_str().unwrap_or_default(), msg["detail"].as_str().unwrap_or_default());+ let args = json!({"action": action, "detail": detail});+ let mut d = json!({"id": id, "tool": "iphone_confirm", "args": args, "status": "waiting"});+ if let Some(t) = thought {+ d["thought"] = t.into();+ }+ st.last = Some((id, Instant::now(), true, d.get("thought").is_some()));+ self.emit(&mut st, "step", d);+ self.emit(&mut st, "confirm", json!({"step": id, "action": action, "detail": detail}));+ let (tx, rx) = oneshot::channel();+ st.confirm = Some((id, tx));+ self.set_status(&mut st, Status::Waiting);+ (rx, id)+ };+ let approve = rx.await.unwrap_or(false);+ let mut st = self.lock();+ st.last = None;+ let stopped = st.status == Status::Done || st.stopped;+ st.rejected |= !approve && !stopped;+ let (status, result) = match (approve, stopped) {+ (true, false) => ("ok", ictl_l10n::tr!("你同意了,继续执行。", "You approved; carrying on.")),+ (_, true) => ("stopped", ictl_l10n::tr!("任务已停止。", "The task was stopped.")),+ (false, false) => {+ ("rejected", ictl_l10n::tr!("你拒绝了这一步,没有执行。", "You rejected this step; it wasn't done."))+ }+ };+ self.emit(&mut st, "step", json!({"id": id, "status": status, "result": result}));+ if !stopped {+ self.set_status(&mut st, Status::Running);+ }+ if approve && !stopped {+ json!({"approve": true, "message": ictl_l10n::tr!("用户同意了,继续执行这一步。", "The user approved; go ahead with this step.")})+ } else if stopped {+ refuse(ictl_l10n::tr!(+ "用户停止了这个任务:不要再调用任何工具,直接结束",+ "The user stopped this task: don't call any more tools, just finish"+ ))+ } else {+ refuse(ictl_l10n::tr!(+ "用户拒绝了这一步:不要执行,也不要换别的方式去做。停下来,说明没做这一步",+ "The user rejected this step: don't do it, and don't do it another way. Stop and say it wasn't done"+ ))+ }+ }+}++/// Where a step touches the screen, for the mark on the page: `{ kind, x, y, x2?, y2? }`.+/// For `iphone_tap_element` it comes from the result text (`… @(x,y) WxH`)+fn gesture(tool: &str, args: &Value, result: &str) -> Option<Value> {+ let f = |k: &str| args.get(k).and_then(Value::as_f64);+ match tool {+ "iphone_tap" => Some(json!({"kind": "tap", "x": f("x")?, "y": f("y")?})),+ "iphone_long_press" => Some(json!({"kind": "long_press", "x": f("x")?, "y": f("y")?})),+ "iphone_swipe" => {+ Some(json!({"kind": "swipe", "x": f("from_x")?, "y": f("from_y")?, "x2": f("to_x")?, "y2": f("to_y")?}))+ }+ "iphone_tap_element" if !result.is_empty() => {+ let first = result.lines().next()?;+ let at = &first[first.find(" @(")? + 3..];+ let (x, rest) = at.split_once(',')?;+ let y = rest.split(')').next()?;+ Some(json!({"kind": "tap", "x": x.trim().parse::<f64>().ok()?, "y": y.trim().parse::<f64>().ok()?}))+ }+ _ => None,+ }+}++fn first_lines(text: &str, n: usize) -> String {+ let mut out: Vec<&str> = text.lines().take(n).collect();+ if text.lines().count() > n {+ out.push("…");+ }+ out.join("\n")+}++#[derive(Debug, PartialEq)]+enum Out {+ Thought(String),+ Summary(String),+ Failure(String),+}++/// One line of the agent's JSON output+fn parse_line(backend: Backend, v: &Value) -> Option<Out> {+ match backend {+ Backend::Claude => match v["type"].as_str()? {+ "assistant" => {+ let text: Vec<&str> = v["message"]["content"]+ .as_array()?+ .iter()+ .filter(|c| c["type"] == "text")+ .filter_map(|c| c["text"].as_str())+ .collect();+ (!text.is_empty()).then(|| Out::Thought(text.join("\n")))+ }+ "result" if v["is_error"].as_bool() == Some(true) => Some(Out::Failure(+ v["result"]+ .as_str()+ .filter(|s| !s.is_empty())+ .unwrap_or(v["subtype"].as_str().unwrap_or("error"))+ .to_owned(),+ )),+ "result" => v["result"].as_str().map(|s| Out::Summary(s.trim().to_owned())),+ _ => None,+ },+ Backend::Codex => match v["type"].as_str()? {+ "item.completed" if v["item"]["type"] == "agent_message" => {+ v["item"]["text"].as_str().map(|s| Out::Thought(s.trim().to_owned()))+ }+ "turn.failed" => Some(Out::Failure(+ v["error"]["message"]+ .as_str()+ .unwrap_or(ictl_l10n::tr!("Codex 没能完成这一轮", "Codex couldn't finish the turn"))+ .to_owned(),+ )),+ "error" => v["message"].as_str().map(|s| Out::Failure(s.to_owned())),+ _ => None,+ },+ }+}++/// SIGTERM to the agent and everything it started (its MCP server), SIGKILL a little later if still there+fn kill_group(pid: u32) {+ let pgid = pid as libc::pid_t;+ unsafe { libc::kill(-pgid, libc::SIGTERM) };+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_secs(3)).await;+ unsafe { libc::kill(-pgid, libc::SIGKILL) };+ });+}++/// What the agent is told, besides the task, in the task's language+fn instructions() -> &'static str {+ ictl_l10n::tr!(+ "你在通过 iphone_* 工具操作用户的一台真实 iPhone 或 iPad,完成用户在网页上交给你的任务。用户在网页上实时看着你的每一步。\n\+- 只用 iphone_* 工具。先看清屏幕(iphone_screenshot 或 iphone_list_elements)再操作,每步之后确认结果。\n\+- 每次调用工具之前,用一句简短的中文说明这一步要做什么。\n\+- 付款、购买、下单、转账;删除或清空数据;发送消息、邮件、评论、帖子;修改账号、密码、隐私或安全设置;其他不可撤销的操作:在真正执行那一步之前,先调用 iphone_confirm 等用户同意。用户拒绝就停下,不要换别的方式去做。\n\+- 工具说用户接管过手机时,先截图重新看界面;工具说任务已停止时,立即结束,不要再调用任何工具。\n\+- 做完后用一两句中文总结结果;没能完成就说明卡在哪一步、为什么。",+ "You are operating the user's real iPhone or iPad through the iphone_* tools, to carry out a task the user gave you on a web page. The user watches every step live on that page.\n\+- Use only the iphone_* tools. Look at the screen first (iphone_screenshot or iphone_list_elements), then act, and check the result after each step.\n\+- Before each tool call, say in one short sentence what the step does.\n\+- Payments, purchases, orders, transfers; deleting or clearing data; sending messages, emails, comments, posts; changing account, password, privacy or security settings; anything else that can't be undone: call iphone_confirm right before that step and wait for the user to agree. If the user rejects it, stop; don't do it another way.\n\+- When a tool says the user took over the phone, take a screenshot and look again first; when a tool says the task was stopped, finish at once without calling any more tools.\n\+- When done, sum up the result in a sentence or two; if you couldn't finish, say at which step and why."+ )+}++/// The Unix socket the agents' MCP servers ask (see the module docs). Only this user can connect (the file is+/// 0600 in the daemon's directory), and every message carries the task's token+pub struct GateServer;++impl GateServer {+ pub async fn serve(path: PathBuf, agents: Arc<Agents>) -> anyhow::Result<()> {+ use std::os::unix::fs::PermissionsExt;+ let _ = std::fs::remove_file(&path);+ let listener = tokio::net::UnixListener::bind(&path)?;+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;+ tokio::spawn(async move {+ while let Ok((s, _)) = listener.accept().await {+ let agents = agents.clone();+ tokio::spawn(async move {+ let (r, mut w) = s.into_split();+ let mut line = String::new();+ let mut r = BufReader::new(r);+ if r.read_line(&mut line).await.is_err() || line.len() > 4 * 1024 * 1024 {+ return;+ }+ let Ok(msg) = serde_json::from_str::<Value>(&line) else { return };+ // the MCP server gives up on a call (the agent cancelled it): stop waiting for the user+ let reply = tokio::select! {+ v = agents.gate(msg) => v,+ _ = closed(&mut r) => return,+ };+ let mut out = reply.to_string();+ out.push('\n');+ let _ = w.write_all(out.as_bytes()).await;+ });+ }+ });+ Ok(())+ }+}++/// Resolves when the other side closes the connection+async fn closed(r: &mut BufReader<tokio::net::unix::OwnedReadHalf>) {+ let mut b = [0u8; 1];+ loop {+ match tokio::io::AsyncReadExt::read(r, &mut b).await {+ Ok(0) | Err(_) => return,+ Ok(_) => {}+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn claude_lines() {+ let a = json!({"type": "assistant", "message": {"content": [{"type": "text", "text": "先看屏幕"}, {"type": "tool_use", "name": "x"}]}});+ assert_eq!(parse_line(Backend::Claude, &a), Some(Out::Thought("先看屏幕".into())));+ let only_tool = json!({"type": "assistant", "message": {"content": [{"type": "tool_use", "name": "x"}]}});+ assert_eq!(parse_line(Backend::Claude, &only_tool), None);+ let r = json!({"type": "result", "subtype": "success", "is_error": false, "result": " 完成了 "});+ assert_eq!(parse_line(Backend::Claude, &r), Some(Out::Summary("完成了".into())));+ let e = json!({"type": "result", "subtype": "error_max_turns", "is_error": true});+ assert_eq!(parse_line(Backend::Claude, &e), Some(Out::Failure("error_max_turns".into())));+ }++ #[test]+ fn codex_lines() {+ let m = json!({"type": "item.completed", "item": {"type": "agent_message", "text": "打开设置\n"}});+ assert_eq!(parse_line(Backend::Codex, &m), Some(Out::Thought("打开设置".into())));+ // the unstable-features warning comes as an error item: not a failure+ let w = json!({"type": "item.completed", "item": {"type": "error", "message": "Under-development features"}});+ assert_eq!(parse_line(Backend::Codex, &w), None);+ let f = json!({"type": "turn.failed", "error": {"message": "quota"}});+ assert_eq!(parse_line(Backend::Codex, &f), Some(Out::Failure("quota".into())));+ }++ #[test]+ fn gestures_for_the_marks() {+ assert_eq!(+ gesture("iphone_tap", &json!({"x": 10, "y": 20.5}), ""),+ Some(json!({"kind": "tap", "x": 10.0, "y": 20.5}))+ );+ assert_eq!(+ gesture("iphone_swipe", &json!({"from_x": 1, "from_y": 2, "to_x": 3, "to_y": 4}), ""),+ Some(json!({"kind": "swipe", "x": 1.0, "y": 2.0, "x2": 3.0, "y2": 4.0}))+ );+ let r = "已点击 Button \"通用\" id=\"com.apple.settings.general\" @(220,776) 400x52";+ assert_eq!(+ gesture("iphone_tap_element", &Value::Null, r),+ Some(json!({"kind": "tap", "x": 220.0, "y": 776.0}))+ );+ assert_eq!(gesture("iphone_tap_element", &Value::Null, "没找到包含 \"x\" 的元素"), None);+ assert_eq!(gesture("iphone_screenshot", &json!({}), ""), None);+ }++ fn task() -> Arc<Task> {+ Arc::new(Task {+ id: "t".into(),+ token: "k".into(),+ lang: ictl_l10n::Lang::Zh,+ st: Mutex::new(TaskState {+ status: Status::Running,+ log: Vec::new(),+ next_step: 1,+ thought: None,+ last: None,+ taps_by_text: Vec::new(),+ recheck: false,+ confirm: None,+ last_text: None,+ summary: None,+ failure: None,+ pid: None,+ stopped: false,+ rejected: false,+ }),+ tx: broadcast::channel(16).0,+ changed: Notify::new(),+ })+ }++ #[tokio::test]+ async fn a_paused_task_holds_the_call_until_resumed() {+ let t = task();+ t.thought("先看一下屏幕");+ t.set_status(&mut t.lock(), Status::Paused);+ let held = {+ let t = t.clone();+ tokio::spawn(async move { t.before("iphone_tap", &json!({"x": 1, "y": 2})).await })+ };+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert!(!held.is_finished(), "paused: the call waits");+ t.set_status(&mut t.lock(), Status::Running);+ let v = held.await.unwrap();+ assert_eq!((v["go"].as_bool(), v["step"].as_u64()), (Some(true), Some(1)));+ let log = t.lock().log.clone();+ let step = log.iter().find(|e| e.name == "step").unwrap();+ assert_eq!(step.data["thought"], "先看一下屏幕");+ assert_eq!(step.data["gesture"]["kind"], "tap");+ }++ #[tokio::test]+ async fn only_a_tap_by_text_gets_a_mark_from_its_result() {+ let t = task();+ let listed = t.before("iphone_list_elements", &json!({})).await["step"].as_u64().unwrap();+ t.after(&json!({"step": listed, "ok": true, "text": "NavigationBar \"世界时钟\" @(220,115) 440x106"}));+ assert!(t.lock().log.last().unwrap().data.get("gesture").is_none());+ let tapped = t.before("iphone_tap_element", &json!({"text": "秒表"})).await["step"].as_u64().unwrap();+ t.after(&json!({"step": tapped, "ok": true, "text": "已点击 Button \"秒表\" @(267,904) 108x54"}));+ assert_eq!(t.lock().log.last().unwrap().data["gesture"], json!({"kind": "tap", "x": 267.0, "y": 904.0}));+ }++ #[tokio::test]+ async fn after_a_takeover_the_agent_looks_again_before_acting() {+ let t = task();+ t.lock().recheck = true;+ assert_eq!(t.before("iphone_tap", &json!({"x": 1, "y": 2})).await["go"], false);+ t.lock().recheck = true;+ assert_eq!(t.before("iphone_screenshot", &json!({})).await["go"], true);+ assert_eq!(t.before("iphone_tap", &json!({"x": 1, "y": 2})).await["go"], true, "only once");+ }++ #[tokio::test]+ async fn a_rejected_confirmation_tells_the_agent_not_to_do_it() {+ let t = task();+ let asked = {+ let t = t.clone();+ tokio::spawn(async move { t.confirm(&json!({"action": "发送消息", "detail": "给妈妈"})).await })+ };+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert_eq!(t.lock().status, Status::Waiting);+ let (step, tx) = t.lock().confirm.take().unwrap();+ assert_eq!(step, 1);+ tx.send(false).unwrap();+ let v = asked.await.unwrap();+ assert_eq!(v["approve"], false);+ assert_eq!(t.lock().status, Status::Running);+ assert!(t.lock().rejected, "the task will end as stopped");+ assert!(t.lock().log.iter().any(|e| e.name == "confirm" && e.data["action"] == "发送消息"));+ }++ #[tokio::test]+ async fn a_stopped_task_refuses_everything() {+ let t = task();+ t.finish(false, true, "停了".into());+ assert_eq!(t.before("iphone_screenshot", &json!({})).await["go"], false);+ assert_eq!(t.confirm(&json!({"action": "a"})).await["approve"], false);+ assert_eq!(t.lock().log.last().unwrap().name, "done");+ }++ #[test]+ fn a_late_thought_joins_the_step_it_belongs_to() {+ let t = task();+ t.lock().last = Some((3, Instant::now(), true, false));+ t.thought("点「通用」");+ assert_eq!(t.lock().log.last().unwrap().data, json!({"id": 3, "thought": "点「通用」"}));+ // a finished step keeps it for the next one (the final summary doesn't land on the last step)+ t.lock().last = Some((4, Instant::now(), false, false));+ t.thought("都做完了");+ assert_eq!(t.lock().thought.as_deref(), Some("都做完了"));+ }+}diff --git a/apps/iphone-control/src/debug.rs b/apps/iphone-control/src/debug.rsindex a144176..a8544f1 100644--- a/apps/iphone-control/src/debug.rs+++ b/apps/iphone-control/src/debug.rs@@ -1,6 +1,6 @@//! `iphone-control debug …`:真机诊断(`--features debug-cmds` 才编译)。直接调用设备层和 WDA 客户端,//! 不经守护进程。`wda`、`e2e` 会启动 XCTest、`hid` 会开屏幕媒体流,和守护进程同时跑会互相干扰:-//! 先停掉守护进程(例如在另一个只跑 usbmuxd 的容器里运行)。+//! 先停掉守护进程。use std::path::PathBuf;use std::time::{Duration, Instant};diff --git a/apps/iphone-control/src/envfile.rs b/apps/iphone-control/src/envfile.rsnew file mode 100644index 0000000..db8921f--- /dev/null+++ b/apps/iphone-control/src/envfile.rs@@ -0,0 +1,185 @@+//! The settings file `~/.config/iphone-control/env`: `KEY=value` lines, the format systemd's `EnvironmentFile=`,+//! a POSIX shell (`set -a; . file`) and this program all read. The service (launchd, systemd, `brew services`) loads+//! it for the daemon; every other command loads it at start-up ([`load_into_process`]), so `login`, `notify-test` and+//! the first-run guide see the same settings.+//!+//! The first-run guide writes it with [`EnvFile::set`]: a changed key is replaced in place, a new one appended, comments+//! and other keys are kept. A new file starts from `packaging/env.example`, so it documents itself. Mode 0600: it holds+//! notification secrets.++use std::io::Write;+use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};+use std::path::{Path, PathBuf};++use anyhow::{Context, bail};++const TEMPLATE: &str = include_str!("../../../packaging/env.example");++pub fn config_dir() -> PathBuf {+ std::env::var_os("XDG_CONFIG_HOME")+ .filter(|v| !v.is_empty())+ .map(PathBuf::from)+ .unwrap_or_else(|| home().join(".config"))+ .join("iphone-control")+}++pub fn home() -> PathBuf {+ std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"))+}++pub fn path() -> PathBuf {+ config_dir().join("env")+}++pub struct EnvFile {+ path: PathBuf,+ text: String,+}++impl EnvFile {+ pub fn open(path: &Path) -> anyhow::Result<Self> {+ let text = match std::fs::read_to_string(path) {+ Ok(t) => t,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => TEMPLATE.to_owned(),+ Err(e) => return Err(e).with_context(|| path.display().to_string()),+ };+ Ok(Self { path: path.to_owned(), text })+ }++ /// The value of `key` (last assignment wins, as when the shell or systemd reads it); empty counts as unset+ pub fn get(&self, key: &str) -> Option<String> {+ parse(&self.text).into_iter().rev().find(|(k, _)| k == key).map(|(_, v)| v).filter(|v| !v.is_empty())+ }++ /// Sets `key` (or clears it with `None`/empty). Returns whether anything changed+ pub fn set(&mut self, key: &str, value: Option<&str>) -> anyhow::Result<bool> {+ let value = value.map(str::trim).unwrap_or_default();+ if self.get(key).as_deref().unwrap_or_default() == value {+ return Ok(false);+ }+ let line = format!("{key}={}", quote(value)?);+ let mut out = Vec::new();+ let mut done = false;+ for l in self.text.lines() {+ if !done && line_key(l) == Some(key) {+ out.push(line.clone());+ done = true;+ } else if line_key(l) == Some(key) {+ // a later duplicate would win over the one just set+ continue;+ } else {+ out.push(l.to_owned());+ }+ }+ if !done {+ out.push(line);+ }+ self.text = out.join("\n") + "\n";+ Ok(true)+ }++ pub fn save(&self) -> anyhow::Result<()> {+ if let Some(dir) = self.path.parent() {+ std::fs::create_dir_all(dir)?;+ }+ let tmp = self.path.with_extension("tmp");+ let mut f = std::fs::OpenOptions::new().create(true).write(true).truncate(true).mode(0o600).open(&tmp)?;+ f.set_permissions(std::fs::Permissions::from_mode(0o600))?;+ f.write_all(self.text.as_bytes())?;+ f.sync_all()?;+ std::fs::rename(&tmp, &self.path)?;+ Ok(())+ }+}++/// The key a line assigns, if it is an assignment (`KEY=…`, `export KEY=…`)+fn line_key(l: &str) -> Option<&str> {+ let l = l.trim_start();+ let l = l.strip_prefix("export ").unwrap_or(l);+ let (k, _) = l.split_once('=')?;+ (!k.is_empty() && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')).then_some(k)+}++pub fn parse(text: &str) -> Vec<(String, String)> {+ text.lines()+ .filter_map(|l| {+ let k = line_key(l)?;+ let v = l.trim_start().strip_prefix("export ").unwrap_or(l.trim_start())[k.len() + 1..].trim();+ Some((k.to_owned(), unquote(v)))+ })+ .collect()+}++fn unquote(v: &str) -> String {+ for q in ['\'', '"'] {+ if v.len() >= 2 && v.starts_with(q) && v.ends_with(q) {+ return v[1..v.len() - 1].to_owned();+ }+ }+ v.to_owned()+}++/// Bare when that is safe for both the shell and systemd, single-quoted otherwise. A value with a single quote, a+/// backslash or a newline would mean different things to the two readers, so it is refused+fn quote(v: &str) -> anyhow::Result<String> {+ if v.bytes().all(|b| b.is_ascii_alphanumeric() || b"_./:@%+,=-".contains(&b)) {+ return Ok(v.to_owned());+ }+ if v.contains(['\'', '\\', '\n', '\r']) {+ bail!(+ "{}",+ ictl_l10n::tr!(+ "这个值里不能有单引号、反斜杠或换行",+ "The value can't contain a single quote, a backslash or a newline"+ )+ );+ }+ Ok(format!("'{v}'"))+}++/// Puts the file's settings into this process's environment, without overriding what is already set (a variable on+/// the command line wins). Called once at start-up, before any thread is started+pub fn load_into_process() {+ let Ok(text) = std::fs::read_to_string(path()) else { return };+ for (k, v) in parse(&text) {+ if v.is_empty() || std::env::var_os(&k).is_some() {+ continue;+ }+ // SAFETY: single-threaded: main() calls this before building the async runtime+ unsafe { std::env::set_var(&k, &v) };+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn set_replaces_in_place_and_keeps_comments() {+ let dir = std::env::temp_dir().join(format!("ictl-env-{}", std::process::id()));+ let p = dir.join("env");+ let mut f = EnvFile { path: p.clone(), text: "# proxy\nHTTP_PROXY=\nBARK_KEY=old\nBARK_KEY=older\n".into() };+ assert_eq!(f.get("BARK_KEY").as_deref(), Some("older"), "the last one wins");+ assert!(f.set("BARK_KEY", Some("new")).unwrap());+ assert!(!f.set("BARK_KEY", Some("new")).unwrap(), "unchanged");+ assert!(f.set("HTTP_PROXY", Some("http://127.0.0.1:7890")).unwrap());+ assert!(f.set("TG_CHAT_ID", Some("-100 1")).unwrap());+ assert_eq!(f.text, "# proxy\nHTTP_PROXY=http://127.0.0.1:7890\nBARK_KEY=new\nTG_CHAT_ID='-100 1'\n");+ assert_eq!(f.get("TG_CHAT_ID").as_deref(), Some("-100 1"));+ assert!(f.set("HTTP_PROXY", None).unwrap());+ assert_eq!(f.get("HTTP_PROXY"), None);+ assert!(f.set("X", Some("it's")).is_err());+ f.save().unwrap();+ let mode = std::fs::metadata(&p).unwrap().permissions().mode() & 0o777;+ assert_eq!(mode, 0o600);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_new_file_starts_from_the_example() {+ let f = EnvFile::open(Path::new("/nonexistent/ictl/env")).unwrap();+ assert!(f.text.contains("IPHONE_CONTROL_LANG="));+ assert_eq!(f.get("IPHONE_CONTROL_LANG"), None);+ assert_eq!(f.get("BARK_SERVER").as_deref(), Some("https://api.day.app"));+ }+}diff --git a/apps/iphone-control/src/guide.rs b/apps/iphone-control/src/guide.rsnew file mode 100644index 0000000..1c3a222--- /dev/null+++ b/apps/iphone-control/src/guide.rs@@ -0,0 +1,636 @@+//! The first-run guide: `iphone-control` with no arguments.+//!+//! Until setup has been completed once it walks the user through everything, one step at a time, in a terminal:+//! language, proxy, the background service, the phone (pairing, Developer Mode, Apple ID, WebDriverAgent), the+//! optional auto-unlock passcode and notifications, and registering the MCP server with Claude Code and Codex.+//! Steps that are already done say so and move on, so it is safe to run again. Settings go to+//! `~/.config/iphone-control/env` ([`crate::envfile`]); the daemon is restarted when they change.+//!+//! When it is done it leaves a marker ([`marker`]); from then on `iphone-control` only makes sure the daemon runs+//! and shows the status. `iphone-control setup --reconfigure` redoes all of it or one part.++use std::io::IsTerminal;+use std::path::{Path, PathBuf};+use std::time::Duration;++use anyhow::bail;+use ictl_l10n::Lang;++use crate::envfile::{self, EnvFile};+use crate::{Cli, service};++fn marker() -> PathBuf {+ envfile::config_dir().join("setup-done")+}++pub fn done() -> bool {+ marker().is_file()+}++fn mark_done() -> anyhow::Result<()> {+ std::fs::create_dir_all(envfile::config_dir())?;+ let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs();+ std::fs::write(marker(), format!("version={}\ncompleted_at={now}\n", env!("CARGO_PKG_VERSION")))?;+ Ok(())+}++fn heading(zh: &str, en: &str) {+ println!("\n━━ {} ━━", if ictl_l10n::is_en() { en } else { zh });+}++fn need_terminal() -> anyhow::Result<()> {+ if !std::io::stdin().is_terminal() {+ bail!(+ "{}",+ ictl_l10n::tr!(+ "设置要在终端里交互完成:直接在终端里运行 iphone-control",+ "Setup is interactive: run iphone-control in a terminal"+ )+ );+ }+ Ok(())+}++/// `[Y/n]` or `[y/N]`; Enter takes the default+fn ask_yes(prompt: &str, default: bool) -> anyhow::Result<bool> {+ let hint = if default { "[Y/n]" } else { "[y/N]" };+ loop {+ let a = crate::read_line(&format!("{prompt} {hint} "))?.to_ascii_lowercase();+ match a.as_str() {+ "" => return Ok(default),+ "y" | "yes" | "是" | "好" => return Ok(true),+ "n" | "no" | "否" | "不" => return Ok(false),+ _ => println!("{}", ictl_l10n::tr!(" 输入 y 或 n", " Enter y or n")),+ }+ }+}++/// A numbered choice; Enter takes `default` (0-based). Returns the index+fn choose(prompt: &str, options: &[&str], default: usize) -> anyhow::Result<usize> {+ println!("{prompt}");+ for (i, o) in options.iter().enumerate() {+ println!(" {}) {o}{}", i + 1, if i == default { ictl_l10n::tr!("(默认)", " (default)") } else { "" });+ }+ loop {+ let a = crate::read_line(ictl_l10n::tr!("选择: ", "Choice: "))?;+ if a.is_empty() {+ return Ok(default);+ }+ match a.parse::<usize>() {+ Ok(n) if (1..=options.len()).contains(&n) => return Ok(n - 1),+ _ => println!("{}", ictl_l10n::trf!(" 输入 1 到 {}", " Enter 1 to {}", options.len())),+ }+ }+}++/// `iphone-control` with no arguments+pub async fn first_run(cli: &Cli) -> anyhow::Result<()> {+ if done() {+ return already_set_up(cli).await;+ }+ need_terminal()?;+ println!(+ "{}",+ ictl_l10n::tr!(+ "欢迎使用 iphone-control。接下来一步步完成设置,已经做好的步骤会自动跳过,中途退出后再运行 iphone-control 会接着做。",+ "Welcome to iphone-control. Setup goes step by step; steps already done are skipped, and if you stop halfway, running iphone-control again picks up where you left."+ )+ );+ full(cli).await+}++/// `iphone-control setup [--reconfigure]`+pub async fn setup(cli: &Cli, reconfigure: bool) -> anyhow::Result<()> {+ need_terminal()?;+ if !reconfigure {+ return full(cli).await;+ }+ let items = [+ ictl_l10n::tr!("全部重新走一遍", "All of it"),+ ictl_l10n::tr!("语言", "Language"),+ ictl_l10n::tr!("代理", "Proxy"),+ ictl_l10n::tr!("后台服务", "Background service"),+ ictl_l10n::tr!("Apple ID(重新登录并重签 WDA)", "Apple ID (sign in again and re-sign WDA)"),+ ictl_l10n::tr!("手机(配对、开发者模式、安装 WDA)", "Phone (pairing, Developer Mode, WDA)"),+ ictl_l10n::tr!("自动解锁密码", "Auto-unlock passcode"),+ ictl_l10n::tr!("通知", "Notifications"),+ ictl_l10n::tr!("注册 MCP(Claude Code、Codex)", "MCP registration (Claude Code, Codex)"),+ ];+ let pick = choose(ictl_l10n::tr!("要重新设置哪一项?", "What do you want to set up again?"), &items, 0)?;+ let mut env = EnvFile::open(&envfile::path())?;+ match pick {+ 0 => {+ let _ = std::fs::remove_file(marker());+ return full_with(cli, true).await;+ }+ 1 => {+ if language(&mut env, true)? {+ env.save()?;+ daemon(cli, true).await?;+ }+ }+ 2 => {+ if proxy(&mut env, true)? {+ env.save()?;+ daemon(cli, true).await?;+ }+ }+ 3 => reinstall_service(cli).await?,+ 4 => {+ daemon(cli, false).await?;+ crate::login(&cli.data_dir, None).await?;+ println!("{}", ictl_l10n::tr!("用新的账号重签 WDA…", "Re-signing WDA with the account…"));+ crate::print_text(&cli.socket, ictl_daemon::protocol::Request::Resign { force: true }).await?;+ }+ 5 => {+ daemon(cli, false).await?;+ crate::device_setup(cli).await?;+ }+ 6 => {+ daemon(cli, false).await?;+ passcode(cli, true).await?;+ }+ 7 => {+ notify_step(cli, &mut env, true).await?;+ }+ _ => register_mcp(cli, true)?,+ }+ println!("\n{}", ictl_l10n::tr!("完成。", "Done."));+ Ok(())+}++async fn full(cli: &Cli) -> anyhow::Result<()> {+ full_with(cli, false).await+}++/// Every step; `force` asks again about the optional ones that are already set+async fn full_with(cli: &Cli, force: bool) -> anyhow::Result<()> {+ let mut env = EnvFile::open(&envfile::path())?;++ heading("语言 / Language", "Language / 语言");+ let mut changed = language(&mut env, force)?;+ heading("代理", "Proxy");+ changed |= proxy(&mut env, force)?;+ if changed {+ env.save()?;+ }++ heading("后台服务", "Background service");+ daemon(cli, changed).await?;++ heading("手机", "Phone");+ crate::device_setup(cli).await?;++ heading("自动解锁(可选)", "Auto-unlock (optional)");+ passcode(cli, force).await?;++ heading("通知(可选)", "Notifications (optional)");+ notify_step(cli, &mut env, force).await?;++ heading("注册 MCP", "MCP registration");+ register_mcp(cli, force)?;++ mark_done()?;+ heading("完成", "All set");+ println!(+ "{}",+ ictl_l10n::trf!(+ "设置保存在 {},以后直接运行 iphone-control 就能查看状态,不用再设置。\n\+ - 在 AI 客户端里使用:开一个新的 Claude Code 或 Codex 会话,试着说「打开时钟,切到秒表并启动」\n\+ - 在浏览器里看画面、操作手机、交给本机的 AI 执行任务:iphone-control viewer\n\+ - 改设置:iphone-control setup --reconfigure",+ "Settings are in {}. From now on, running iphone-control just shows the status; no more setup.\n\+ - In an AI client: open a new Claude Code or Codex session and ask, for example, “Open Clock, switch to the stopwatch and start it”\n\+ - In a browser, to watch and control the phone and hand tasks to a local AI: iphone-control viewer\n\+ - To change settings: iphone-control setup --reconfigure",+ envfile::path().display()+ )+ );+ Ok(())+}++/// Already set up: make sure the daemon runs, then show where things stand+async fn already_set_up(cli: &Cli) -> anyhow::Result<()> {+ if crate::snapshot(&cli.socket).await.is_err()+ && let Some(s) = service::find()+ {+ println!("{}", ictl_l10n::tr!("守护进程没在运行,正在启动…", "The daemon isn't running, starting it…"));+ service::start(&s)?;+ wait_daemon(&cli.socket, Duration::from_secs(60)).await;+ }+ crate::status(&cli.socket).await?;+ println!(+ "\n{}",+ ictl_l10n::tr!(+ "浏览器控制台:iphone-control viewer · 排查问题:iphone-control doctor · 改设置:iphone-control setup --reconfigure",+ "Control page: iphone-control viewer · Troubleshoot: iphone-control doctor · Change settings: iphone-control setup --reconfigure"+ )+ );+ Ok(())+}++/// Asks for the language and switches this run to it. Returns whether the file changed+fn language(env: &mut EnvFile, force: bool) -> anyhow::Result<bool> {+ let current = env.get(ictl_l10n::ENV).and_then(|v| ictl_l10n::parse(&v));+ if let (Some(l), false) = (current, force) {+ ictl_l10n::set(l);+ println!("{}", ictl_l10n::tr!(" 中文(已设置)", " English (already set)"));+ return Ok(false);+ }+ let default = usize::from(current.unwrap_or_else(ictl_l10n::own_lang) == Lang::En);+ let l = if choose("界面语言 / Language", &["中文", "English"], default)? == 1 { Lang::En } else { Lang::Zh };+ ictl_l10n::set(l);+ env.set(ictl_l10n::ENV, Some(l.code()))+}++fn proxy(env: &mut EnvFile, force: bool) -> anyhow::Result<bool> {+ let current = env.get("HTTPS_PROXY").or_else(|| env.get("HTTP_PROXY"));+ if !force && let Some(p) = ¤t {+ println!("{}", ictl_l10n::trf!(" 已设置:{p}", " Already set: {p}"));+ return Ok(false);+ }+ println!(+ "{}",+ ictl_l10n::tr!(+ "下载开发者镜像和 WebDriverAgent、登录 Apple ID、发通知都要访问外网;直连访问 GitHub 慢的话可以设代理。",+ "Downloading the developer disk image and WebDriverAgent, signing in to the Apple ID and sending notifications go out to the internet; set a proxy if GitHub is slow to reach directly."+ )+ );+ if !ask_yes(ictl_l10n::tr!("要用代理吗?", "Use a proxy?"), current.is_some())? {+ let a = env.set("HTTP_PROXY", None)?;+ return Ok(env.set("HTTPS_PROXY", None)? | a);+ }+ let prompt = match ¤t {+ Some(p) => ictl_l10n::trf!("代理地址(回车保留 {p}): ", "Proxy URL (Enter keeps {p}): "),+ None => {+ ictl_l10n::tr!("代理地址,例如 http://127.0.0.1:7890 : ", "Proxy URL, e.g. http://127.0.0.1:7890 : ").into()+ }+ };+ let mut url = crate::read_line(&prompt)?;+ if url.is_empty() {+ url = current.unwrap_or_default();+ }+ if !url.is_empty() && !url.contains("://") {+ url = format!("http://{url}");+ }+ let a = env.set("HTTP_PROXY", Some(&url))?;+ Ok(env.set("HTTPS_PROXY", Some(&url))? | a)+}++async fn wait_daemon(socket: &Path, timeout: Duration) -> bool {+ crate::wait_until(timeout, Duration::from_secs(1), || async { crate::snapshot(socket).await.is_ok() }).await+}++/// Makes sure the daemon runs (as a service if the user agrees); `restart` reloads changed settings+async fn daemon(cli: &Cli, restart: bool) -> anyhow::Result<()> {+ let running = crate::snapshot(&cli.socket).await.is_ok();+ match (running, service::find()) {+ (true, Some(s)) if restart => {+ println!(+ "{}",+ ictl_l10n::tr!(" 重启守护进程,让新设置生效…", " Restarting the daemon so the new settings apply…")+ );+ service::restart(&s)?;+ // stopping takes up to half a minute (it ends the phone's sessions first)+ tokio::time::sleep(Duration::from_secs(2)).await;+ if !wait_daemon(&cli.socket, Duration::from_secs(60)).await {+ bail!(+ "{}",+ ictl_l10n::tr!(+ "守护进程 1 分钟内没起来,运行 iphone-control service status 看看",+ "The daemon didn't come up within a minute; see iphone-control service status"+ )+ );+ }+ }+ (true, Some(s)) => println!("{}", ictl_l10n::trf!(" 在运行:{}", " Running: {}", s.describe())),+ (true, None) => {+ println!(+ "{}",+ ictl_l10n::tr!(+ " 守护进程是手动启动的(不是后台服务)。要改成登录后自动启动、崩溃后自动重启的后台服务,先把它停掉(在它的终端里按 Ctrl-C),再运行 iphone-control service install。",+ " The daemon was started by hand (not as a service). To run it as a service that starts at login and restarts after a crash, stop it (Ctrl-C in its terminal), then run iphone-control service install."+ )+ );+ if restart {+ println!(+ "{}",+ ictl_l10n::tr!(" 改过的设置要重启它才生效。", " Restart it for the changed settings to apply.")+ );+ }+ }+ (false, Some(s)) => {+ println!("{}", ictl_l10n::trf!(" 启动 {}…", " Starting {}…", s.describe()));+ service::start(&s)?;+ if !wait_daemon(&cli.socket, Duration::from_secs(60)).await {+ bail!(+ "{}",+ ictl_l10n::tr!(+ "守护进程 1 分钟内没起来,运行 iphone-control service status 看看",+ "The daemon didn't come up within a minute; see iphone-control service status"+ )+ );+ }+ println!("{}", ictl_l10n::tr!(" 已启动", " Started"));+ }+ (false, None) => {+ println!(+ "{}",+ ictl_l10n::tr!(+ " 守护进程负责和手机保持连接,并在签名过期前自动重签。建议装成后台服务:登录后自动启动,崩溃后自动重启。",+ " The daemon keeps the connection to the phone and re-signs before the signature expires. A background service is recommended: it starts at login and restarts after a crash."+ )+ );+ if ask_yes(ictl_l10n::tr!(" 装成后台服务?", " Set it up as a service?"), true)? {+ let s = service::install()?;+ println!("{}", ictl_l10n::trf!(" 已安装并启动:{}", " Installed and started: {}", s.describe()));+ if !wait_daemon(&cli.socket, Duration::from_secs(60)).await {+ bail!(+ "{}",+ ictl_l10n::tr!(+ "守护进程 1 分钟内没起来,运行 iphone-control service status 看看",+ "The daemon didn't come up within a minute; see iphone-control service status"+ )+ );+ }+ } else {+ println!(+ "{}",+ ictl_l10n::tr!(+ " 在另一个终端运行 iphone-control daemon,这里会等它起来…",+ " Run iphone-control daemon in another terminal; waiting for it…"+ )+ );+ if !wait_daemon(&cli.socket, Duration::from_secs(600)).await {+ bail!("{}", ictl_l10n::tr!("10 分钟内没等到守护进程", "The daemon didn't start within 10 minutes"));+ }+ }+ }+ }+ Ok(())+}++async fn reinstall_service(cli: &Cli) -> anyhow::Result<()> {+ match service::find() {+ Some(s) => {+ println!("{}", ictl_l10n::trf!("后台服务:{}", "Service: {}", s.describe()));+ service::restart(&s)?;+ wait_daemon(&cli.socket, Duration::from_secs(60)).await;+ println!("{}", ictl_l10n::tr!("已重启", "Restarted"));+ Ok(())+ }+ None => daemon(cli, false).await,+ }+}++async fn passcode(cli: &Cli, force: bool) -> anyhow::Result<()> {+ let cfg = ictl_daemon::Config::from_env(&cli.data_dir);+ let device = crate::target_device(&cli.socket, None).await?;+ let set = cfg.passcode_file_for(&device.udid).is_file();+ println!(+ "{}",+ ictl_l10n::tr!(+ " 手机锁屏时,操作前用锁屏密码自动解锁。不设的话,锁屏后要有人手动解锁。",+ " When the phone is locked, actions unlock it with the passcode first. Without it, someone has to unlock it by hand."+ )+ );+ if set && !force {+ println!("{}", ictl_l10n::tr!(" 这台设备已设置", " Already set for this device"));+ return Ok(());+ }+ let what = if set {+ choose(+ ictl_l10n::tr!(" 这台设备已设置自动解锁密码:", " This device has an auto-unlock passcode:"),+ &[+ ictl_l10n::tr!("保留", "Keep it"),+ ictl_l10n::tr!("重新输入", "Enter it again"),+ ictl_l10n::tr!("删除(关闭自动解锁)", "Delete it (auto-unlock off)"),+ ],+ 0,+ )?+ } else if ask_yes(ictl_l10n::tr!(" 设置自动解锁?", " Set up auto-unlock?"), false)? {+ 1+ } else {+ 0+ };+ match what {+ 1 => crate::passcode(&cli.data_dir, &cli.socket, crate::PasscodeAction::Set { device: None }).await,+ 2 => {+ crate::passcode(&cli.data_dir, &cli.socket, crate::PasscodeAction::Clear { device: None, all: false }).await+ }+ _ => Ok(()),+ }+}++/// Asks for a notification channel. Returns whether the file changed, and the settings to test if there are any+fn notifications(env: &mut EnvFile, force: bool) -> anyhow::Result<(bool, Option<ictl_daemon::config::NotifyConfig>)> {+ let bark = env.get("BARK_KEY");+ let tg = env.get("TG_BOT_TOKEN").zip(env.get("TG_CHAT_ID"));+ println!(+ "{}",+ ictl_l10n::tr!(+ " 重签失败、Apple ID 会话过期、手机离线、重启后要输密码时推送提醒。",+ " Alerts when re-signing fails, the Apple ID session expires, the phone goes offline or needs its passcode after a restart."+ )+ );+ if !force && (bark.is_some() || tg.is_some()) {+ println!("{}", ictl_l10n::tr!(" 已配置", " Already configured"));+ return Ok((false, None));+ }+ let pick = choose(+ ictl_l10n::tr!(" 用哪种方式推送?", " How should alerts reach you?"),+ &[+ ictl_l10n::tr!("不需要", "None"),+ ictl_l10n::tr!("Bark(iPhone 上的 App)", "Bark (an iPhone app)"),+ "Telegram",+ ],+ if bark.is_some() {+ 1+ } else if tg.is_some() {+ 2+ } else {+ 0+ },+ )?;+ let mut changed = false;+ match pick {+ 1 => {+ let key = crate::read_secret(ictl_l10n::tr!(+ " Bark 的 key(App 里复制的地址里那一段,输入不显示): ",+ " Bark key (the part in the URL the app shows, hidden): "+ ))?;+ if key.is_empty() {+ bail!("{}", ictl_l10n::tr!("没有输入 key", "No key entered"));+ }+ let server = crate::read_line(ictl_l10n::tr!(+ " Bark 服务器(回车用 https://api.day.app): ",+ " Bark server (Enter for https://api.day.app): "+ ))?;+ changed |= env.set("BARK_KEY", Some(&key))?;+ changed |= env.set("BARK_SERVER", Some(if server.is_empty() { "https://api.day.app" } else { &server }))?;+ changed |= env.set("TG_BOT_TOKEN", None)? | env.set("TG_CHAT_ID", None)?;+ }+ 2 => {+ let token = crate::read_secret(ictl_l10n::tr!(+ " 机器人 token(@BotFather 给的,输入不显示): ",+ " Bot token (from @BotFather, hidden): "+ ))?;+ let chat = crate::read_line(ictl_l10n::tr!(+ " chat id(给机器人发条消息后,用 @userinfobot 查): ",+ " Chat id (message the bot first, then ask @userinfobot): "+ ))?;+ if token.is_empty() || chat.is_empty() {+ bail!("{}", ictl_l10n::tr!("token 和 chat id 都要填", "Both the token and the chat id are needed"));+ }+ changed |= env.set("TG_BOT_TOKEN", Some(&token))? | env.set("TG_CHAT_ID", Some(&chat))?;+ changed |= env.set("BARK_KEY", None)?;+ }+ _ => {+ changed |= env.set("BARK_KEY", None)? | env.set("TG_BOT_TOKEN", None)? | env.set("TG_CHAT_ID", None)?;+ return Ok((changed, None));+ }+ }+ if !changed {+ return Ok((false, None));+ }+ Ok((+ true,+ Some(ictl_daemon::config::NotifyConfig {+ tg_bot_token: env.get("TG_BOT_TOKEN"),+ tg_chat_id: env.get("TG_CHAT_ID"),+ bark_server: env.get("BARK_SERVER").unwrap_or_else(|| "https://api.day.app".into()),+ bark_key: env.get("BARK_KEY"),+ }),+ ))+}++async fn notify_step(cli: &Cli, env: &mut EnvFile, force: bool) -> anyhow::Result<()> {+ let (changed, test) = notifications(env, force)?;+ if changed {+ env.save()?;+ daemon(cli, true).await?;+ }+ if let Some(t) = test {+ send_test(&t).await;+ }+ Ok(())+}++async fn send_test(cfg: &ictl_daemon::config::NotifyConfig) {+ let ok = ictl_daemon::notify::send(+ cfg,+ ictl_l10n::tr!("[测试] iphone-control 通知已配置", "[test] iphone-control notifications are set up"),+ ictl_l10n::tr!("收到这条说明通知能用。", "If this arrived, notifications work."),+ )+ .await;+ println!(+ "{}",+ if ok > 0 {+ ictl_l10n::tr!(" 已发一条测试通知,看看手机收到没有", " Sent a test notification; check that it arrived")+ } else {+ ictl_l10n::tr!(+ " 测试通知没发出去:检查 key 或 token、代理,之后可以用 iphone-control notify-test 再试",+ " The test notification wasn't sent: check the key or token and the proxy, then try iphone-control notify-test"+ )+ }+ );+}++/// Registers the MCP server with the AI clients found on PATH+fn register_mcp(cli: &Cli, force: bool) -> anyhow::Result<()> {+ let exe = service::stable_exe()?;+ let socket = cli.socket.to_string_lossy().into_owned();+ let exe = exe.to_string_lossy().into_owned();+ let mut env_args: Vec<String> = Vec::new();+ if ictl_l10n::is_en() {+ env_args.push(format!("{}=en", ictl_l10n::ENV));+ }+ if ictl_mcp::dev_tools_enabled() {+ env_args.push("IPHONE_CONTROL_DEV_TOOLS=1".into());+ }+ let server = [exe.as_str(), "--socket", socket.as_str(), "mcp"];+ let mut any = false;+ for backend in crate::agent::Backend::ALL {+ let Some(program) = backend.find() else { continue };+ any = true;+ let name = backend.name();+ let registered = registered(backend);+ if registered && !force {+ println!("{}", ictl_l10n::trf!(" {name}:已注册", " {name}: already registered"));+ continue;+ }+ if !ask_yes(&ictl_l10n::trf!(" 注册到 {name}?", " Register with {name}?"), true)? {+ continue;+ }+ let mut cmd = std::process::Command::new(&program);+ match backend {+ crate::agent::Backend::Claude => {+ let _ = std::process::Command::new(&program)+ .args(["mcp", "remove", "iphone", "-s", "user"])+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status();+ cmd.args(["mcp", "add", "iphone", "-s", "user"]);+ for e in &env_args {+ cmd.args(["-e", e]);+ }+ }+ crate::agent::Backend::Codex => {+ let _ = std::process::Command::new(&program)+ .args(["mcp", "remove", "iphone"])+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status();+ cmd.args(["mcp", "add", "iphone"]);+ for e in &env_args {+ cmd.args(["--env", e]);+ }+ }+ }+ cmd.arg("--").args(server).stdout(std::process::Stdio::null());+ match cmd.status() {+ Ok(s) if s.success() => println!(+ "{}",+ ictl_l10n::trf!(+ " 已注册到 {name},新开的会话里可以用",+ " Registered with {name}; available in new sessions"+ )+ ),+ _ => println!(+ "{}",+ ictl_l10n::trf!(+ " 注册到 {name} 失败,可以手动运行:iphone-control mcp-config",+ " Registering with {name} failed; do it by hand: iphone-control mcp-config"+ )+ ),+ }+ }+ if !any {+ println!(+ "{}",+ ictl_l10n::trf!(+ " 这台机器上没找到 Claude Code 或 Codex。装好后运行 iphone-control setup --reconfigure 选「注册 MCP」;其他 MCP 客户端用这条命令注册:\n {}",+ " Neither Claude Code nor Codex was found. Once one is installed, run iphone-control setup --reconfigure and pick MCP registration; for other MCP clients the server command is:\n {}",+ server.join(" ")+ )+ );+ }+ Ok(())+}++/// Whether the client already has an `iphone` server: read from its config file, since asking the CLI also+/// connects to every server and takes seconds+fn registered(backend: crate::agent::Backend) -> bool {+ let home = envfile::home();+ match backend {+ crate::agent::Backend::Claude => std::fs::read_to_string(home.join(".claude.json"))+ .ok()+ .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())+ .is_some_and(|v| v["mcpServers"]["iphone"].is_object()),+ crate::agent::Backend::Codex => {+ let dir = std::env::var_os("CODEX_HOME").map(PathBuf::from).unwrap_or_else(|| home.join(".codex"));+ std::fs::read_to_string(dir.join("config.toml"))+ .is_ok_and(|t| t.lines().any(|l| l.trim() == "[mcp_servers.iphone]"))+ }+ }+}diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex b8c75f4..c135663 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -1,7 +1,8 @@//! iphone-control:唯一的可执行程序。守护进程、MCP 服务和运维命令都在这里。//!+//! 不带参数运行是首次运行引导([`guide`]):没设置好就一步步引导,设置好以后只显示状态。//! 运维命令(status、doctor、resign、unlock-reset)经控制接口问守护进程;-//! setup、login、passcode 需要交互,直接在本进程里做。+//! setup、login、passcode 需要交互,直接在本进程里做。每个命令启动时先读 ~/.config/iphone-control/env([`envfile`])。use std::io::{BufRead, Write};use std::path::{Path, PathBuf};@@ -12,8 +13,12 @@ use clap::{Parser, Subcommand};use ictl_daemon::config::env as env_nonempty;use ictl_daemon::protocol::{self, Request, Response};+mod agent;#[cfg(feature = "debug-cmds")]mod debug;+mod envfile;+mod guide;+mod service;mod viewer;#[derive(Parser)]@@ -25,28 +30,34 @@ struct Cli {#[arg(help = ictl_l10n::tr!("守护进程控制接口。默认:root 是 /run/iphone-control/ctl.sock,普通用户是 $XDG_RUNTIME_DIR/iphone-control/ctl.sock", "Daemon control socket. Default: /run/iphone-control/ctl.sock for root, $XDG_RUNTIME_DIR/iphone-control/ctl.sock for a regular user"))]#[arg(long, env = "ICTL_SOCKET", default_value_os_t = protocol::default_socket())]socket: PathBuf,+ /// 不给就是首次运行引导(设置好以后显示状态)#[command(subcommand)]- command: Command,+ command: Option<Command>,}#[derive(Subcommand)]enum Command {- #[command(about = ictl_l10n::tr!("常驻守护进程(容器入口;从源码运行时由 systemd 或手动启动)", "The long-running daemon (the container's entry point; for a source install started by systemd or by hand)"))]+ #[command(about = ictl_l10n::tr!("常驻守护进程(安装时装成用户服务:macOS 是 launchd,Linux 是 systemd;也可以手动启动)", "The long-running daemon (installed as a user service: launchd on macOS, systemd on Linux; can also be started by hand)"))]Daemon,#[command(about = ictl_l10n::tr!("MCP stdio 服务(由 agent 拉起)", "MCP stdio server (started by the agent)"))]Mcp,- #[command(about = ictl_l10n::tr!("打印把 MCP 注册到 Claude Code 的命令:在容器里打印 docker exec 的写法,否则直接调用本程序", "Print the command that registers the MCP server with Claude Code: a docker exec form inside a container, otherwise this program directly"))]- McpConfig {- #[arg(help = ictl_l10n::tr!("容器名;给了就按容器部署打印", "Container name; if given, print the container form"))]- #[arg(long)]- container: Option<String>,- },+ #[command(about = ictl_l10n::tr!("打印把 MCP 注册到 Claude Code 的命令", "Print the command that registers the MCP server with Claude Code"))]+ McpConfig,#[command(about = ictl_l10n::tr!("守护进程和设备状态、最近的日志", "Daemon and device state, recent log"))]Status,#[command(about = ictl_l10n::tr!("逐层诊断,每项失败都给出修复办法", "Layer-by-layer health check with a fix for each failure"))]Doctor,- #[command(about = ictl_l10n::tr!("首次安装向导:配对 → 开发者模式 → 登录 Apple ID → 签名安装 WDA(可重复运行)", "Guided setup: pairing → Developer Mode → Apple ID sign-in → sign and install WDA (safe to re-run)"))]- Setup,+ #[command(about = ictl_l10n::tr!("设置引导:语言、代理、后台服务、配对、开发者模式、Apple ID、安装 WDA、自动解锁、通知、注册 MCP(可重复运行,做过的步骤跳过)", "Guided setup: language, proxy, background service, pairing, Developer Mode, Apple ID, WDA, auto-unlock, notifications, MCP registration (safe to re-run; done steps are skipped)"))]+ Setup {+ #[arg(help = ictl_l10n::tr!("重新设置:全部重走,或只改其中一项", "Set up again: all of it, or one part"))]+ #[arg(long)]+ reconfigure: bool,+ },+ #[command(about = ictl_l10n::tr!("后台服务(macOS 是 launchd,Linux 是 systemd 用户服务):install / uninstall / start / stop / restart / status", "The background service (launchd on macOS, a systemd user service on Linux): install / uninstall / start / stop / restart / status"))]+ Service {+ #[command(subcommand)]+ action: ServiceAction,+ },#[command(about = ictl_l10n::tr!("登录 Apple ID(密码和双重认证验证码只在这里输入)", "Sign in to the Apple ID (the password and two-factor code are only entered here)"))]Login {#[arg(help = ictl_l10n::tr!("Apple ID 邮箱;不给就交互输入", "Apple ID email; asked for interactively if not given"))]@@ -78,7 +89,7 @@ enum Command {#[arg(long, default_value_t = 8100)]port: u16,},- #[command(about = ictl_l10n::tr!("在浏览器里看实时画面并操作手机:只开在 127.0.0.1,点击、滑动、输入和按键都经守护进程(默认不监听任何端口)", "Watch and control the phone live in a browser: serves 127.0.0.1 only, taps, swipes, typing and buttons go through the daemon (by default no port is opened)"))]+ #[command(about = ictl_l10n::tr!("浏览器里的控制台:实时画面上直接操作手机、看设备状态,把任务交给本机的 Claude Code 或 Codex 执行。只开在 127.0.0.1,操作都经守护进程(默认不监听任何端口)", "Control page in a browser: act on the live screen, see the device's state, and hand tasks to a local Claude Code or Codex. Serves 127.0.0.1 only, every action goes through the daemon (by default no port is opened)"))]Viewer {#[arg(long, default_value_t = 8200)]port: u16,@@ -94,6 +105,19 @@ enum Command {},}+#[derive(Subcommand)]+enum ServiceAction {+ #[command(about = ictl_l10n::tr!("装成登录后自动启动的后台服务并启动(已有就直接启动)", "Set up the service that starts at login and start it (just start it if it exists)"))]+ Install,+ #[command(about = ictl_l10n::tr!("停止并移除本程序装的后台服务(数据保留)", "Stop and remove the service this program set up (data is kept)"))]+ Uninstall,+ Start,+ Stop,+ #[command(about = ictl_l10n::tr!("重启,改过 ~/.config/iphone-control/env 后用", "Restart, after editing ~/.config/iphone-control/env"))]+ Restart,+ Status,+}+/// 锁屏密码按设备分开存:一台的密码不会输进另一台#[derive(Subcommand)]enum PasscodeAction {@@ -112,13 +136,18 @@ enum PasscodeAction {},}-#[tokio::main]-async fn main() -> anyhow::Result<()> {+fn main() -> anyhow::Result<()> {+ // 设置文件先读进环境(命令行上已设的优先),要在启动任何线程之前:语言、代理、通知等对所有命令都生效+ envfile::load_into_process();+ tokio::runtime::Runtime::new()?.block_on(run())+}++async fn run() -> anyhow::Result<()> {// 依赖树里 rustls 的 ring 和 aws-lc-rs 都开着,不装默认 provider 的话第一个 HTTPS 请求就 paniclet _ = rustls::crypto::ring::default_provider().install_default();- let cli = Cli::parse();- let quiet = matches!(cli.command, Command::Mcp);- // ICTL_LOG 留空(.env 里常见的 `ICTL_LOG=`)当作没设;原来空值会生成一个什么都不放行的过滤器+ let mut cli = Cli::parse();+ let quiet = matches!(cli.command, Some(Command::Mcp));+ // ICTL_LOG 留空(配置文件里常见的 `ICTL_LOG=`)当作没设;原来空值会生成一个什么都不放行的过滤器let filter =env_nonempty("ICTL_LOG").and_then(|v| tracing_subscriber::EnvFilter::try_new(v).ok()).unwrap_or_else(|| {tracing_subscriber::EnvFilter::new(if quiet { "warn" } else { "info,idevice=warn,apple_codesign=warn" })@@ -129,20 +158,22 @@ async fn main() -> anyhow::Result<()> {.with_env_filter(filter).init();- match cli.command {+ let Some(command) = cli.command.take() else { return guide::first_run(&cli).await };+ match command {Command::Daemon => {let mut cfg = ictl_daemon::Config::from_env(&cli.data_dir);cfg.socket = cli.socket;ictl_daemon::run(cfg).await}Command::Mcp => ictl_mcp::serve_stdio(cli.socket).await,- Command::McpConfig { container } => {- println!("{}", mcp_config(container, &cli.socket)?);+ Command::McpConfig => {+ println!("{}", mcp_config(&cli.socket)?);Ok(())}Command::Status => status(&cli.socket).await,Command::Doctor => print_text(&cli.socket, Request::Doctor).await,- Command::Setup => setup(&cli).await,+ Command::Setup { reconfigure } => guide::setup(&cli, reconfigure).await,+ Command::Service { action } => service_cmd(&cli.socket, action).await,Command::Login { email } => login(&cli.data_dir, email).await,Command::Sign => print_text(&cli.socket, Request::Resign { force: true }).await,Command::Resign { force } => print_text(&cli.socket, Request::Resign { force }).await,@@ -151,7 +182,7 @@ async fn main() -> anyhow::Result<()> {Command::Devices => print_text(&cli.socket, Request::ListDevices).await,Command::Select { device } => print_text(&cli.socket, Request::SelectDevice { device }).await,Command::WdaBridge { port } => wda_bridge(&cli.socket, port).await,- Command::Viewer { port } => viewer::run(&cli.socket, port).await,+ Command::Viewer { port } => viewer::run(&cli.socket, &cli.data_dir, port).await,#[cfg(feature = "debug-cmds")]Command::Debug(args) => debug::run(env_nonempty("IPHONE_UDID").as_deref(), args).await,Command::NotifyTest { event } => notify_test(&cli.data_dir, event.as_deref()).await,@@ -167,9 +198,9 @@ async fn notify_test(data_dir: &Path, only: Option<&str>) -> anyhow::Result<()>bail!("{}",ictl_l10n::tr!(- "没有配置通知渠道:填 BARK_KEY,或 TG_BOT_TOKEN + TG_CHAT_ID(容器部署在 .env 里填、重建容器;\- 从源码运行在守护进程的环境文件里填、重启守护进程)",- "No notification channel configured: set BARK_KEY, or TG_BOT_TOKEN + TG_CHAT_ID (container: in .env, then recreate the container; source install: in the daemon's env file, then restart the daemon)"+ "没有配置通知渠道:运行 iphone-control setup --reconfigure 选「通知」,\+ 或在 ~/.config/iphone-control/env 里填 BARK_KEY、或 TG_BOT_TOKEN + TG_CHAT_ID,再重启守护进程",+ "No notification channel configured: run iphone-control setup --reconfigure and pick notifications, or set BARK_KEY, or TG_BOT_TOKEN + TG_CHAT_ID, in ~/.config/iphone-control/env and restart the daemon"));}@@ -208,33 +239,64 @@ async fn notify_test(data_dir: &Path, only: Option<&str>) -> anyhow::Result<()>Ok(())}-/// 容器部署:MCP 进程由 `docker exec -i` 在容器里拉起。从源码运行:直接调用本程序,-/// 显式带上 socket,免得 Claude Code 的环境里没有 XDG_RUNTIME_DIR 时算出别的位置-fn mcp_config(container: Option<String>, socket: &Path) -> anyhow::Result<String> {- let in_container = Path::new("/.dockerenv").exists() || Path::new("/run/.containerenv").exists();- let container = container- .or_else(|| in_container.then(|| env_nonempty("CONTAINER_NAME").unwrap_or_else(|| "iphone-control".into())));- // 英文时把语言写进注册命令:直接调用时 MCP 客户端不带用户 shell 的环境;容器里一般由 .env 继承,- // 但只给这一次 docker exec 设了语言(.env 里没有)时,不写进去 MCP 就还是中文- let lang = |flag: &str| if ictl_l10n::is_en() { format!("{flag} {}=en ", ictl_l10n::ENV) } else { String::new() };- let dev = || if ictl_mcp::dev_tools_enabled() { "-e IPHONE_CONTROL_DEV_TOOLS=1 " } else { "" };- Ok(match container {- // 开发者工具开关同理:只给这次 docker exec 设了、.env 里没有时也要写进去- Some(c) => {- format!("claude mcp add iphone -s user -- docker exec -i {}{}{c} iphone-control mcp", lang("-e"), dev())- }- None => {- let exe = std::env::current_exe()- .context(ictl_l10n::tr!("找不到本程序的路径", "can't find the path of this program"))?;- let lang = lang("-e");- let dev = dev();- format!(- "claude mcp add iphone -s user {lang}{dev}-- {} --socket {} mcp",- shell_quote(&exe.to_string_lossy()),- shell_quote(&socket.to_string_lossy())+/// MCP 进程由客户端直接拉起本程序:显式带上 socket,免得 Claude Code 的环境里没有 XDG_RUNTIME_DIR 时算出别的位置。+/// 英文、开发者工具开关写进注册命令:MCP 客户端不带用户 shell 的环境+fn mcp_config(socket: &Path) -> anyhow::Result<String> {+ Ok(mcp_command(&service::stable_exe()?, socket))+}++async fn service_cmd(socket: &Path, action: ServiceAction) -> anyhow::Result<()> {+ let none = || {+ anyhow::anyhow!(+ "{}",+ ictl_l10n::tr!(+ "没有装后台服务:iphone-control service install",+ "No service is set up: iphone-control service install")+ )+ };+ match action {+ ServiceAction::Install => {+ let s = service::install()?;+ println!("{}", ictl_l10n::trf!("已安装并启动:{}", "Installed and started: {}", s.describe()));}- })+ ServiceAction::Uninstall => service::uninstall()?,+ ServiceAction::Start => service::start(&service::find().ok_or_else(none)?)?,+ ServiceAction::Stop => service::stop(&service::find().ok_or_else(none)?)?,+ ServiceAction::Restart => service::restart(&service::find().ok_or_else(none)?)?,+ ServiceAction::Status => {+ match service::find() {+ Some(s) => println!("{}", ictl_l10n::trf!("后台服务 {}", "Service {}", s.describe())),+ None => println!(+ "{}",+ ictl_l10n::tr!(+ "后台服务 没有装(iphone-control service install)",+ "Service not set up (iphone-control service install)"+ )+ ),+ }+ let up = snapshot(socket).await.is_ok();+ println!(+ "{}",+ if up {+ ictl_l10n::tr!("守护进程 在运行", "Daemon running")+ } else {+ ictl_l10n::tr!("守护进程 没在运行", "Daemon not running")+ }+ );+ }+ }+ Ok(())+}++fn mcp_command(exe: &Path, socket: &Path) -> String {+ let lang = if ictl_l10n::is_en() { format!("-e {}=en ", ictl_l10n::ENV) } else { String::new() };+ let dev = if ictl_mcp::dev_tools_enabled() { "-e IPHONE_CONTROL_DEV_TOOLS=1 " } else { "" };+ format!(+ "claude mcp add iphone -s user {lang}{dev}-- {} --socket {} mcp",+ shell_quote(&exe.to_string_lossy()),+ shell_quote(&socket.to_string_lossy())+ )}fn shell_quote(s: &str) -> String {@@ -252,8 +314,8 @@ async fn ask(socket: &Path, req: Request) -> anyhow::Result<Response> {_ => Some(Duration::from_secs(180)),};protocol::call(socket, &req, timeout).await.with_context(|| {- ictl_l10n::trf!("连不上守护进程({}):先启动 iphone-control daemon(容器里是入口进程);\- 守护进程以别的用户运行时,用 --socket 或 ICTL_SOCKET 指到它的控制接口", "Can't reach the daemon ({}): start iphone-control daemon first (in the container it is the entry process); if the daemon runs as another user, point --socket or ICTL_SOCKET at its control socket",+ ictl_l10n::trf!("连不上守护进程({}):先启动它(iphone-control service start;没装后台服务的,运行 iphone-control 按引导装,或在另一个终端运行 iphone-control daemon);\+ 守护进程以别的用户运行时,用 --socket 或 ICTL_SOCKET 指到它的控制接口", "Can't reach the daemon ({}): start it first (iphone-control service start; without a background service, run iphone-control and let the guide set one up, or run iphone-control daemon in another terminal); if the daemon runs as another user, point --socket or ICTL_SOCKET at its control socket",socket.display())})@@ -401,8 +463,8 @@ fn read_line(prompt: &str) -> anyhow::Result<String> {bail!("{}",ictl_l10n::tr!(- "读不到输入(标准输入已关闭):在终端里运行;容器部署用 docker exec -it",- "Can't read input (stdin is closed): run it in a terminal; for a container use docker exec -it"+ "读不到输入(标准输入已关闭):在终端里运行",+ "Can't read input (stdin is closed): run it in a terminal"));}@@ -638,12 +700,11 @@ where}}-async fn setup(cli: &Cli) -> anyhow::Result<()> {+/// The phone's part of the guide: connect, pair, Developer Mode, Apple ID, sign and install WDA, wait for WDA.+/// Needs the daemon running ([`guide`] starts it first)+async fn device_setup(cli: &Cli) -> anyhow::Result<()> {use ictl_device::{Device, DeviceError};let socket = &cli.socket;- snapshot(socket)- .await- .context(ictl_l10n::tr!("setup 需要守护进程在运行", "setup needs the daemon to be running"))?;println!("{}", ictl_l10n::tr!("[1/6] 等待手机连接", "[1/6] Waiting for the phone"));let found = wait_until(Duration::from_secs(600), Duration::from_secs(5), || async {@@ -760,23 +821,42 @@ async fn setup(cli: &Cli) -> anyhow::Result<()> {));}- print_text(socket, Request::Resign { force: true }).await?;+ // already on the phone, signed by this Apple ID, and not about to expire: running the guide again doesn't re-sign+ // (the daemon re-signs by itself before it expires)+ let left = snapshot(socket).await.ok().and_then(|s| match s.device_profile {+ ictl_daemon::core::DeviceProfile::Expires(_) => s.device_profile.left(&s.persisted),+ _ => None,+ });+ match left.filter(|l| *l > Duration::from_secs(2 * 86400)) {+ Some(l) => println!(+ "{}",+ ictl_l10n::trf!(+ " 已签名安装,描述文件还剩 {} 天,到期前会自动重签",+ " Already signed and installed, the profile has {} days left and is re-signed automatically before it expires",+ l.as_secs() / 86400+ )+ ),+ None => print_text(socket, Request::Resign { force: true }).await?,+ }println!("{}", ictl_l10n::tr!("[6/6] 等待 WDA 启动", "[6/6] Waiting for WDA to start"));- println!(- "{}",- ictl_l10n::tr!(- " 首次安装:在手机 设置 → 通用 → VPN 与设备管理 里找到你的 Apple ID,点「信任」(需要联网)。",- " First install: on the phone, open Settings → General → VPN & Device Management, find your Apple ID and tap “Trust” (needs internet)."- )- );- println!(- "{}",- ictl_l10n::tr!(- " 如果弹出「为 XCTest 输入 iPhone 密码」,输入锁屏密码。",- " If “Enter iPhone passcode for XCTest” appears, enter the passcode."- )- );+ let ready_now = snapshot(socket).await.is_ok_and(|s| s.state == ictl_daemon::machine::DeviceState::Ready);+ if !ready_now {+ println!(+ "{}",+ ictl_l10n::tr!(+ " 首次安装:在手机 设置 → 通用 → VPN 与设备管理 里找到你的 Apple ID,点「信任」(需要联网)。",+ " First install: on the phone, open Settings → General → VPN & Device Management, find your Apple ID and tap “Trust” (needs internet)."+ )+ );+ println!(+ "{}",+ ictl_l10n::tr!(+ " 如果弹出「为 XCTest 输入 iPhone 密码」,输入锁屏密码。",+ " If “Enter iPhone passcode for XCTest” appears, enter the passcode."+ )+ );+ }let ready = wait_until(Duration::from_secs(600), Duration::from_secs(10), || async {snapshot(socket).await.map(|s| s.state == ictl_daemon::machine::DeviceState::Ready).unwrap_or(false)})@@ -792,32 +872,11 @@ async fn setup(cli: &Cli) -> anyhow::Result<()> {)});-- println!("{}", ictl_l10n::tr!("\n可选设置", "\nOptional"));- println!(- "{}",- ictl_l10n::tr!(- " 通知:填 TG_* 或 BARK_*(容器部署在 .env 里,然后重建容器;从源码运行在守护进程的环境文件里,然后重启它)",- " Notifications: set TG_* or BARK_* (container: in .env, then recreate the container; source install: in the daemon's env file, then restart it)"- )- );- println!(- "{}",- ictl_l10n::tr!(" 自动解锁:iphone-control passcode set", " Auto-unlock: iphone-control passcode set")- );- println!(- "{}",- ictl_l10n::tr!(- " 注册到 Claude Code:iphone-control mcp-config",- " Register with Claude Code: iphone-control mcp-config"- )- );- println!();- print_text(socket, Request::Doctor).await+ Ok(())}/// 显式开启:127.0.0.1:port → 手机上的 WDA 8100。只绑本机回环地址。-/// 容器用 host 网络,所以这就是宿主机的回环地址:本机的其他用户、浏览器里的网页都能访问到,而 WDA 没有认证。+/// 本机的其他用户、浏览器里的网页都能访问到,而 WDA 没有认证。/// 浏览器那条路(DNS rebinding)靠检查 Host 头挡住;本机其他用户挡不住,用完就停。async fn wda_bridge(socket: &Path, port: u16) -> anyhow::Result<()> {// 和守护进程控制同一台(WDA 只在那台上跑着)@@ -915,18 +974,18 @@ fn host_is_loopback(head: &[u8]) -> bool {#[cfg(test)]mod tests {- use super::{host_is_loopback, mcp_config};+ use super::{host_is_loopback, mcp_command};use ictl_l10n::{Lang, with_lang};use std::path::Path;- /// 英文时注册命令带上语言(容器里也带:只给这次 docker exec 设了语言时,.env 里没有);中文和以前一样+ /// 英文时注册命令带上语言(MCP 客户端不带用户 shell 的环境);中文时不带#[test]fn mcp_config_carries_english() {- let cmd = |l| with_lang(l, || mcp_config(Some("ic".into()), Path::new("/s")).unwrap());- assert_eq!(cmd(Lang::Zh), "claude mcp add iphone -s user -- docker exec -i ic iphone-control mcp");+ let cmd = |l| with_lang(l, || mcp_command(Path::new("/b/iphone-control"), Path::new("/s")));+ assert_eq!(cmd(Lang::Zh), "claude mcp add iphone -s user -- /b/iphone-control --socket /s mcp");assert_eq!(cmd(Lang::En),- "claude mcp add iphone -s user -- docker exec -i -e IPHONE_CONTROL_LANG=en ic iphone-control mcp"+ "claude mcp add iphone -s user -e IPHONE_CONTROL_LANG=en -- /b/iphone-control --socket /s mcp");}diff --git a/apps/iphone-control/src/service.rs b/apps/iphone-control/src/service.rsnew file mode 100644index 0000000..42bef3b--- /dev/null+++ b/apps/iphone-control/src/service.rs@@ -0,0 +1,290 @@+//! The daemon as a per-user service: a launchd agent on macOS, a systemd user unit on Linux.+//!+//! The same service `install.sh` sets up (launchd label [`LABEL`], unit `iphone-control.service` in+//! `~/.config/systemd/user`), and also the ones a package brings: the `.deb`'s unit in `/usr/lib/systemd/user` and+//! the agent or unit `brew services` writes. `install` only writes our own file when none of these exists; the other+//! commands act on whichever is there. The service reads `~/.config/iphone-control/env`, starts at login and is+//! restarted after a crash.++use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};++use anyhow::{Context, bail};++use crate::envfile::home;++pub const LABEL: &str = "io.github.derrors.iphone-control";+const UNIT: &str = "iphone-control";++#[derive(Debug, Clone, PartialEq)]+pub enum Service {+ /// launchd agent: label and plist+ Launchd { label: String, plist: PathBuf, ours: bool },+ /// systemd user unit (name without `.service`)+ Systemd { unit: String, ours: bool },+}++impl Service {+ pub fn describe(&self) -> String {+ match self {+ Self::Launchd { label, plist, ours: true } => format!("launchd {label} ({})", plist.display()),+ Self::Launchd { label, .. } => format!("launchd {label} (brew services)"),+ Self::Systemd { unit, .. } => format!("systemd --user {unit}.service"),+ }+ }+}++/// The program path to put in a service or an MCP registration: one that survives upgrades. Homebrew's real path+/// has the version in it (`…/Cellar/iphone-control/0.1.5/bin`); its `opt` link doesn't+pub fn stable_exe() -> anyhow::Result<PathBuf> {+ let exe =+ std::env::current_exe().context(ictl_l10n::tr!("找不到本程序的路径", "can't find the path of this program"))?;+ Ok(stable_path(&exe))+}++fn stable_path(exe: &Path) -> PathBuf {+ let s = exe.to_string_lossy();+ if let Some(i) = s.find("/Cellar/iphone-control/") {+ let rest = &s[i + "/Cellar/iphone-control/".len()..];+ if let Some(j) = rest.find('/') {+ return PathBuf::from(format!("{}/opt/iphone-control{}", &s[..i], &rest[j..]));+ }+ }+ exe.to_owned()+}++fn uid() -> u32 {+ unsafe { libc::getuid() }+}++fn launch_agents() -> PathBuf {+ home().join("Library/LaunchAgents")+}++fn our_plist() -> PathBuf {+ launch_agents().join(format!("{LABEL}.plist"))+}++fn our_unit() -> PathBuf {+ crate::envfile::config_dir().parent().unwrap_or(Path::new("/")).join("systemd/user/iphone-control.service")+}++fn run(cmd: &mut Command) -> bool {+ cmd.stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success())+}++fn systemctl(args: &[&str]) -> bool {+ run(Command::new("systemctl").arg("--user").args(args))+}++fn has_systemd_user() -> bool {+ systemctl(&["show-environment"])+}++/// The service set up for this user, if any (ours first, then a package's)+pub fn find() -> Option<Service> {+ if cfg!(target_os = "macos") {+ if our_plist().is_file() {+ return Some(Service::Launchd { label: LABEL.into(), plist: our_plist(), ours: true });+ }+ // brew services: homebrew.mxcl.iphone-control.plist, or sh.brew.iphone-control.plist in newer versions+ let found = std::fs::read_dir(launch_agents()).ok()?.flatten().map(|e| e.path()).find(|p| {+ p.extension().is_some_and(|x| x == "plist")+ && p.file_stem().is_some_and(|s| s.to_string_lossy().ends_with(".iphone-control"))+ })?;+ let label = found.file_stem()?.to_string_lossy().into_owned();+ return Some(Service::Launchd { label, plist: found, ours: false });+ }+ if !has_systemd_user() {+ return None;+ }+ for unit in [UNIT, "homebrew.iphone-control"] {+ if systemctl(&["cat", unit]) {+ return Some(Service::Systemd { unit: unit.into(), ours: unit == UNIT && our_unit().is_file() });+ }+ }+ None+}++fn launchd_loaded(label: &str) -> bool {+ run(Command::new("launchctl").arg("print").arg(format!("gui/{}/{label}", uid())))+}++pub fn start(s: &Service) -> anyhow::Result<()> {+ let ok = match s {+ Service::Launchd { label, plist, .. } => {+ if launchd_loaded(label) {+ run(Command::new("launchctl").arg("kickstart").arg(format!("gui/{}/{label}", uid())))+ } else {+ run(Command::new("launchctl").arg("bootstrap").arg(format!("gui/{}", uid())).arg(plist))+ }+ }+ Service::Systemd { unit, .. } => systemctl(&["enable", "--now", unit]),+ };+ if !ok {+ bail!("{}", ictl_l10n::trf!("启动服务失败:{}", "Starting the service failed: {}", s.describe()));+ }+ Ok(())+}++pub fn stop(s: &Service) -> anyhow::Result<()> {+ let ok = match s {+ Service::Launchd { label, .. } => {+ !launchd_loaded(label)+ || run(Command::new("launchctl").arg("bootout").arg(format!("gui/{}/{label}", uid())))+ }+ Service::Systemd { unit, .. } => systemctl(&["stop", unit]),+ };+ if !ok {+ bail!("{}", ictl_l10n::trf!("停止服务失败:{}", "Stopping the service failed: {}", s.describe()));+ }+ Ok(())+}++/// Restarts it so it reads the settings again (or starts it if it isn't running)+pub fn restart(s: &Service) -> anyhow::Result<()> {+ let ok = match s {+ Service::Launchd { label, .. } if launchd_loaded(label) => {+ run(Command::new("launchctl").arg("kickstart").arg("-k").arg(format!("gui/{}/{label}", uid())))+ }+ Service::Launchd { .. } => return start(s),+ Service::Systemd { unit, .. } => systemctl(&["restart", unit]),+ };+ if !ok {+ bail!("{}", ictl_l10n::trf!("重启服务失败:{}", "Restarting the service failed: {}", s.describe()));+ }+ Ok(())+}++/// Sets up our own service for this program, unless one already exists, and starts it+pub fn install() -> anyhow::Result<Service> {+ if let Some(s) = find() {+ start(&s)?;+ return Ok(s);+ }+ let exe = stable_exe()?;+ let exe = exe.to_string_lossy();+ if exe.contains(['"', '\'', '\\', '&', '<', '>']) {+ bail!(+ "{}",+ ictl_l10n::trf!(+ "程序路径里有特殊字符,装不了服务:{exe}",+ "The program path has special characters, can't set up a service: {exe}"+ )+ );+ }+ if cfg!(target_os = "macos") {+ let logs = home().join("Library/Logs/iphone-control");+ std::fs::create_dir_all(&logs)?;+ std::fs::create_dir_all(launch_agents())?;+ let log = logs.join("daemon.log");+ let plist = format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key><string>{LABEL}</string>+ <key>ProgramArguments</key>+ <array>+ <string>/bin/sh</string>+ <string>-c</string>+ <string>set -a; f="$HOME/.config/iphone-control/env"; [ -f "$f" ] && . "$f"; set +a; exec "{exe}" daemon</string>+ </array>+ <key>RunAtLoad</key><true/>+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>+ <key>ThrottleInterval</key><integer>10</integer>+ <key>ExitTimeOut</key><integer>30</integer>+ <key>StandardOutPath</key><string>{log}</string>+ <key>StandardErrorPath</key><string>{log}</string>+</dict>+</plist>+"#,+ log = log.display()+ );+ std::fs::write(our_plist(), plist)?;+ let s = Service::Launchd { label: LABEL.into(), plist: our_plist(), ours: true };+ start(&s)?;+ return Ok(s);+ }+ if !has_systemd_user() {+ bail!(+ "{}",+ ictl_l10n::tr!(+ "没有可用的 systemd 用户会话,装不了服务;在另一个终端运行 iphone-control daemon",+ "No systemd user session, so no service can be set up; run iphone-control daemon in another terminal"+ )+ );+ }+ let unit = our_unit();+ std::fs::create_dir_all(unit.parent().unwrap_or(Path::new("/")))?;+ std::fs::write(+ &unit,+ format!(+ "# Written by iphone-control. Settings: ~/.config/iphone-control/env\n[Unit]\n\+ Description=iphone-control daemon (iPhone over USB, MCP)\nAfter=network-online.target\n\n[Service]\n\+ ExecStart={exe} daemon\nEnvironmentFile=-%h/.config/iphone-control/env\nEnvironment=MALLOC_ARENA_MAX=2\n\+ Restart=on-failure\nRestartSec=10\nTimeoutStopSec=30\n\n[Install]\nWantedBy=default.target\n"+ ),+ )?;+ systemctl(&["daemon-reload"]);+ let s = Service::Systemd { unit: UNIT.into(), ours: true };+ start(&s)?;+ Ok(s)+}++/// Stops and removes our own service. A package's service stays; says how to remove it+pub fn uninstall() -> anyhow::Result<()> {+ let Some(s) = find() else {+ println!("{}", ictl_l10n::tr!("没有装后台服务", "No service is set up"));+ return Ok(());+ };+ match &s {+ Service::Launchd { plist, ours: true, .. } => {+ stop(&s)?;+ std::fs::remove_file(plist)?;+ }+ Service::Systemd { unit, ours: true } => {+ systemctl(&["disable", "--now", unit]);+ std::fs::remove_file(our_unit())?;+ systemctl(&["daemon-reload"]);+ }+ Service::Launchd { .. } => bail!(+ "{}",+ ictl_l10n::tr!(+ "这是 brew services 装的服务:brew services stop iphone-control",+ "This service belongs to brew services: brew services stop iphone-control"+ )+ ),+ Service::Systemd { unit, .. } => {+ systemctl(&["disable", "--now", unit]);+ println!(+ "{}",+ ictl_l10n::trf!(+ "已停用 {unit}(服务文件属于安装包,留着)",+ "Disabled {unit} (its file belongs to the package and stays)"+ )+ );+ return Ok(());+ }+ }+ println!("{}", ictl_l10n::trf!("已移除后台服务 {}", "Removed the service {}", s.describe()));+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn homebrew_paths_use_the_opt_link() {+ assert_eq!(+ stable_path(Path::new("/opt/homebrew/Cellar/iphone-control/0.1.5/bin/iphone-control")),+ PathBuf::from("/opt/homebrew/opt/iphone-control/bin/iphone-control")+ );+ assert_eq!(+ stable_path(Path::new("/home/linuxbrew/.linuxbrew/Cellar/iphone-control/0.2.0/bin/iphone-control")),+ PathBuf::from("/home/linuxbrew/.linuxbrew/opt/iphone-control/bin/iphone-control")+ );+ assert_eq!(stable_path(Path::new("/usr/bin/iphone-control")), PathBuf::from("/usr/bin/iphone-control"));+ }+}diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.htmlindex 8bf2ef9..5b83ca6 100644--- a/apps/iphone-control/src/viewer.html+++ b/apps/iphone-control/src/viewer.html@@ -1,129 +1,2520 @@<!doctype html>-<html lang="en">+<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">-<title>iphone-control viewer</title>+<title>iphone-control 控制台</title>+<link rel="icon" href="data:,"><style>- :root { color-scheme: light dark; --bg: #f4f4f5; --fg: #18181b; --muted: #71717a; --panel: #fff; --line: #d4d4d8; --err: #b91c1c; }- @media (prefers-color-scheme: dark) { :root { --bg: #18181b; --fg: #f4f4f5; --muted: #a1a1aa; --panel: #27272a; --line: #3f3f46; --err: #f87171; } }- * { box-sizing: border-box; }- body { margin: 0; background: var(--bg); color: var(--fg); font: 14px/1.4 system-ui, sans-serif; display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 12px; min-height: 100vh; }- #screen { position: relative; height: min(80vh, 900px); aspect-ratio: 393 / 852; background: #000; border-radius: 28px; overflow: hidden; touch-action: none; user-select: none; }- #screen.landscape { height: auto; width: min(95vw, 1000px); }- #screen img { width: 100%; height: 100%; object-fit: contain; display: block; cursor: crosshair; -webkit-user-drag: none; }- #screen .msg { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; text-align: center; padding: 24px; color: #d4d4d8; }- #screen .msg[hidden] { display: none; }- .row { display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; width: min(100%, 520px); }- button, input { font: inherit; color: inherit; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px; }- button { cursor: pointer; }- button:disabled { opacity: .5; cursor: default; }- input { flex: 1; min-width: 0; }- #status { color: var(--muted); min-height: 1.4em; max-width: 520px; text-align: center; white-space: pre-wrap; }- #status.err { color: var(--err); }+/* OD-LAYOUT-PRIMITIVES v1 — structure only: display, flex/grid, overflow, wrapping, ratio, geometry.+ Put this @layer first; product CSS outside the layer wins ordinary layout rules.+ Native hidden and closed-dialog states take precedence over component display rules. */+@layer od-layout {+ [hidden]:not([hidden="until-found" i]) { display: none !important; }+ dialog:not([open]) { display: none !important; }++ :where(.od-stack,.od-row,.od-row-top,.od-cluster,.od-grid,.od-field,.od-stat,.od-cell,.od-tile) > :where(*) { min-width: 0; }++ /* containers */+ .od-stack { display: flex; flex-direction: column; gap: var(--od-gap, 8px); }+ .od-row { display: flex; align-items: center; gap: var(--od-gap, 8px); }+ .od-row-top { display: flex; align-items: flex-start; gap: var(--od-gap, 8px); }+ .od-cluster { display: flex; flex-wrap: wrap; align-items: center; gap: var(--od-gap, 8px); }+ .od-fill { flex: 1 1 0; min-width: 0; }+ .od-fixed { flex: none; }+ .od-grid { display: grid; gap: var(--od-gap, 12px); grid-template-columns: repeat(var(--od-cols, 3), minmax(0, 1fr)); }++ /* stacked information: each piece is its own line — never sibling inline spans */+ .od-stat, .od-field, .od-cell { display: grid; gap: var(--od-gap, 2px); }+ :where(.od-stat,.od-field,.od-cell) > :where(*) { display: block; }+ .od-tile { display: grid; grid-template-rows: auto 1fr; }+ :where(.od-tile) > :where(*) { display: block; }++ /* media keeps its intrinsic ratio by default; never a distorted or cropped+ cover by accident. height:auto lets the ratio win over an <img height="…">+ attribute. Cropping to a uniform box is an explicit opt-in: set --od-ratio+ AND add .od-media-cover together (per the core rule, only where a crop is+ deliberate — tile thumbs, decorative fills — never on full-frame content). */+ .od-media { display: block; width: 100%; height: auto; aspect-ratio: var(--od-ratio, auto); }+ .od-media-cover { object-fit: cover; }++ /* functional inline SVG icons opt into bounded geometry; content SVGs keep their own */+ .od-icon { display: inline-block; inline-size: var(--od-icon-size, 1em); block-size: var(--od-icon-size, 1em); flex: none; }++ /* data text only — authored copy is rewritten to its budget instead */+ .od-truncate { display: block; max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }+ .od-clamp-2, .od-clamp-3 { display: -webkit-box; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }+ .od-clamp-2 { -webkit-line-clamp: 2; }+ .od-clamp-3 { -webkit-line-clamp: 3; }+ .od-lines-2 { min-height: calc(2 * 1.4em); } /* block-level reservation for a shared baseline */+ .od-nowrap { white-space: nowrap; } /* 数字+单位 · 价格+起 · 日期+星期 */+ .od-keep { word-break: keep-all; overflow-wrap: anywhere; } /* CJK labels break at spaces / <wbr> first */++ /* screen skeleton (optional): bars take their own space, the middle scrolls — no padding guessed for chrome */+ .od-screen { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; height: 100%; }+ .od-scroll { overflow-y: auto; overscroll-behavior: contain; min-height: 0; }++ /* horizontal rail: the next item peeks at the edge; trailing room survives overflow */+ .od-rail { display: flex; gap: var(--od-gap, 8px); overflow-x: auto; scroll-snap-type: x proximity; scrollbar-width: none;+ padding-inline: var(--od-rail-pad, 16px); scroll-padding-inline: var(--od-rail-pad, 16px); }+ .od-rail::-webkit-scrollbar { display: none; }+ :where(.od-rail) > :where(*) { flex: none; scroll-snap-align: start; }+ :where(.od-rail) > :where(:last-child) { margin-inline-end: var(--od-rail-pad, 16px); }++ .od-spacer { flex: none; visibility: hidden; pointer-events: none; }+ .od-touch { min-width: 44px; min-height: 44px; }+}+:root [hidden]:where(:not([hidden="until-found" i])) { display: none; }+/* /OD-LAYOUT-PRIMITIVES v1 */++/* ================= 设计变量 ================= */+:root {+ color-scheme: light dark;+ --font-ui: system-ui, -apple-system, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;+ --font-mono: ui-monospace, "SF Mono", "JetBrains Mono", "Cascadia Mono", Menlo, Consolas, monospace;++ --fs-2xs: 12px; --fs-xs: 13px; --fs-sm: 14px; --fs-md: 16px; --fs-lg: 18px; --fs-xl: 26px;+ --sp-1: 4px; --sp-2: 8px; --sp-3: 12px; --sp-4: 16px; --sp-5: 20px; --sp-6: 24px; --sp-8: 32px; --sp-10: 40px;+ --r-xs: 6px; --r-sm: 8px; --r-md: 10px; --r-lg: 14px; --r-xl: 18px; --r-2xl: 20px;+ --gutter: 12px;+ --head-h: 64px;+ --w-agent: 460px; --w-dev: 344px;+ --dur-fast: 150ms; --dur: 220ms; --dur-slow: 300ms; --dur-exit: 150ms;+ --ease-out: cubic-bezier(.2, .7, .2, 1); --ease-in: cubic-bezier(.4, 0, 1, 1);++ /* 浅色:冷调浅灰底,白色面板浮在上面;深青绿只用来点睛 */+ --canvas: #eaedf0; --panel: #ffffff; --sunken: #f4f6f8; --hover: #eff2f4; --press: #e5e9ec;+ --line: #e3e7ea; --line-strong: #cbd2d8; --panel-edge: rgba(16, 24, 32, .07);+ --text: #11161a; --text-2: #3b444c; --muted: #5f6a73;+ --accent: #0d6e5f; --accent-hover: #0a5a4e; --on-accent: #ffffff; --accent-soft: #e5f3ef; --accent-line: #c3e3d9; --accent-text: #0a5a4e;+ --user: #2457d6; --user-soft: #e9effc; --user-text: #1f48b3;+ --ai: #10937c;+ --danger: #c0352b; --danger-hover: #9f2a22; --on-danger: #ffffff; --danger-soft: #fdeeec; --danger-line: #f4cdc8; --danger-text: #a52c23;+ --warn: #b7791f; --warn-soft: #fdf4e3; --warn-line: #efdaa9; --warn-text: #845005;+ --ok-text: #0b6b4f; --ok-soft: #e5f3ef;+ --focus: #2457d6;+ --bezel: #141a18; --bezel-edge: #2e3835;+ --shadow-xs: 0 1px 2px rgba(16, 24, 32, .06);+ --shadow-panel: 0 1px 2px rgba(16, 24, 32, .04), 0 8px 24px rgba(16, 24, 32, .05);+ --shadow-float: 0 2px 6px rgba(16, 24, 32, .06), 0 12px 32px rgba(16, 24, 32, .10);+ --shadow-phone: 0 4px 10px rgba(16, 24, 32, .08), 0 36px 64px -16px rgba(16, 24, 32, .32);+}+@media (prefers-color-scheme: dark) {+ :root {+ --canvas: #07090a; --panel: #111518; --sunken: #0b0e10; --hover: #191e22; --press: #20262b;+ --line: #20262b; --line-strong: #333b42; --panel-edge: rgba(255, 255, 255, .07);+ --text: #e8ecef; --text-2: #c2c9cf; --muted: #96a0aa;+ --accent: #3ccaa9; --accent-hover: #67dbc0; --on-accent: #03201a; --accent-soft: rgba(60, 202, 169, .12); --accent-line: rgba(60, 202, 169, .30); --accent-text: #7ae0c8;+ --user: #8ab4f8; --user-soft: rgba(138, 180, 248, .14); --user-text: #aac8fa;+ --ai: #3ccaa9;+ --danger: #f2827a; --danger-hover: #f6a39d; --on-danger: #2a0806; --danger-soft: rgba(242, 130, 122, .12); --danger-line: rgba(242, 130, 122, .30); --danger-text: #f8b0aa;+ --warn: #f0b544; --warn-soft: rgba(245, 190, 80, .12); --warn-line: rgba(245, 190, 80, .30); --warn-text: #f5cf7a;+ --ok-text: #7ae0c8; --ok-soft: rgba(60, 202, 169, .12);+ --focus: #8ab4f8;+ --bezel: #000000; --bezel-edge: #2f363c;+ --shadow-xs: 0 1px 2px rgba(0, 0, 0, .4);+ --shadow-panel: none;+ --shadow-float: 0 2px 6px rgba(0, 0, 0, .4), 0 12px 32px rgba(0, 0, 0, .45);+ --shadow-phone: 0 36px 64px -16px rgba(0, 0, 0, .7);+ }+}++/* ================= 基础 ================= */+* { box-sizing: border-box; }+html, body { height: 100%; }+body { margin: 0; background: var(--canvas); color: var(--text); font: var(--fs-md)/1.55 var(--font-ui); -webkit-font-smoothing: antialiased; }+h1, h2, h3, p, ol, ul { margin: 0; }+ol, ul { padding: 0; list-style: none; }+button, input, textarea, select { font: inherit; color: inherit; }+code, .mono { font-family: var(--font-mono); }+:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }+.ic { display: inline-flex; }+.spin { animation: spin 900ms linear infinite; }+@keyframes spin { to { transform: rotate(360deg); } }+@keyframes rise { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }+@keyframes pulse { 50% { opacity: .45; } }+.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }++/* 按钮 */+.btn {+ display: inline-flex; align-items: center; justify-content: center; gap: var(--sp-2);+ min-height: 40px; padding: 0 var(--sp-4); border-radius: var(--r-md);+ border: 1px solid var(--line); background: var(--panel); color: var(--text); box-shadow: var(--shadow-xs);+ font-size: var(--fs-sm); font-weight: 600; cursor: pointer; white-space: nowrap; --od-icon-size: 18px;+ transition: background-color var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out);+}+@media (hover: hover) { .btn:hover:not(:disabled) { background: var(--hover); border-color: var(--line-strong); color: var(--text); } }+.btn:active:not(:disabled) { background: var(--press); box-shadow: none; }+.btn:disabled { background: var(--sunken); border-color: var(--line); color: var(--muted); box-shadow: none; cursor: not-allowed; opacity: .7; }+.btn-primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }+@media (hover: hover) { .btn-primary:hover:not(:disabled) { background: var(--accent-hover); border-color: var(--accent-hover); color: var(--on-accent); } }+.btn-primary:active:not(:disabled) { background: var(--accent-hover); }+.btn-primary:disabled { background: var(--press); border-color: var(--press); color: var(--muted); }+.btn-ghost { background: transparent; border-color: transparent; box-shadow: none; }+@media (hover: hover) { .btn-ghost:hover:not(:disabled) { background: var(--hover); border-color: transparent; } }+.btn-danger { color: var(--danger-text); }+@media (hover: hover) { .btn-danger:hover:not(:disabled) { background: var(--danger-soft); border-color: var(--danger-line); color: var(--danger-text); } }+.btn-danger-solid { background: var(--danger); border-color: var(--danger); color: var(--on-danger); }+@media (hover: hover) { .btn-danger-solid:hover:not(:disabled) { background: var(--danger-hover); border-color: var(--danger-hover); color: var(--on-danger); } }+.btn-sm { min-height: 32px; padding: 0 var(--sp-3); font-size: var(--fs-xs); border-radius: var(--r-sm); --od-icon-size: 16px; }+.btn-icon { width: 40px; padding: 0; }+.btn-icon.btn-sm { width: 32px; }++.badge { display: inline-flex; align-items: center; gap: 6px; padding: 2px var(--sp-2); border-radius: var(--r-xs); font-size: var(--fs-2xs); font-weight: 600; line-height: 20px; white-space: nowrap; --od-icon-size: 14px; }+.tone-accent { background: var(--accent-soft); color: var(--accent-text); }+.tone-user { background: var(--user-soft); color: var(--user-text); }+.tone-warn { background: var(--warn-soft); color: var(--warn-text); }+.tone-ok { background: var(--ok-soft); color: var(--ok-text); }+.tone-danger { background: var(--danger-soft); color: var(--danger-text); }+.tone-muted { background: var(--sunken); color: var(--muted); box-shadow: inset 0 0 0 1px var(--line); }+.t-accent { color: var(--accent-text); } .t-ok { color: var(--ok-text); } .t-danger { color: var(--danger-text); } .t-warn { color: var(--warn-text); } .t-muted { color: var(--muted); } .t-user { color: var(--user-text); }++.input, .select {+ width: 100%; min-height: 40px; padding: 0 var(--sp-3); border-radius: var(--r-md);+ border: 1px solid transparent; background: var(--sunken); color: var(--text); font-size: var(--fs-sm);+ transition: background-color var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out);+}+@media (hover: hover) { .input:hover:not(:disabled):not(:focus) { border-color: var(--line); } }+.input:focus { background: var(--panel); border-color: var(--line-strong); }+.input::placeholder, .textarea::placeholder { color: var(--muted); opacity: 1; }+.input:disabled, .select:disabled { color: var(--muted); cursor: not-allowed; }+.input:focus-visible, .select:focus-visible { outline: 2px solid var(--focus); outline-offset: -1px; border-color: transparent; }+.label { display: block; font-size: var(--fs-xs); font-weight: 600; color: var(--muted); margin-bottom: 6px; }++/* ================= 外壳:浮在浅底上的三栏 ================= */+.shell { display: grid; grid-template-columns: var(--w-agent) minmax(0, 1fr) var(--w-dev); grid-template-rows: minmax(0, 1fr); gap: var(--gutter); padding: var(--gutter); height: 100dvh; }+.mbar { display: none; }+.pane { display: grid; grid-template-rows: var(--head-h) minmax(0, 1fr) auto; min-height: 0; min-width: 0; }+.pane-agent, .pane-dev { position: relative; background: var(--panel); border-radius: var(--r-2xl); box-shadow: 0 0 0 1px var(--panel-edge), var(--shadow-panel); }+/* 拖拽手柄放在面板之间的缝隙里:悬停、聚焦、拖动时显示主色细线 */+.resizer { position: absolute; top: var(--sp-4); bottom: var(--sp-4); right: calc(var(--gutter) * -1); width: var(--gutter); z-index: 5; cursor: col-resize; touch-action: none; display: flex; justify-content: center; }+.resizer.resizer-left { right: auto; left: calc(var(--gutter) * -1); }+.resizer::after { content: ""; width: 3px; height: 100%; border-radius: 2px; background: transparent; transition: background-color var(--dur-fast) var(--ease-out); }+@media (hover: hover) { .resizer:hover::after { background: var(--accent-line); } }+.resizer:focus-visible { outline: none; }+.resizer:focus-visible::after, .resizer.dragging::after { background: var(--accent); }+body.resizing { cursor: col-resize; user-select: none; -webkit-user-select: none; }+body.resizing .stage, body.resizing iframe { pointer-events: none; }+.pane-head { display: flex; align-items: center; gap: var(--sp-3); padding: 0 var(--sp-5); border-bottom: 1px solid var(--line); min-width: 0; }+.pane-body { overflow-y: auto; overscroll-behavior: contain; min-height: 0; scrollbar-width: thin; scrollbar-color: var(--line-strong) transparent; }++.brand { display: flex; align-items: center; gap: 10px; min-width: 0; }+.brand-mark { flex: none; width: 32px; height: 32px; padding: 3px; border-radius: 9px; background: var(--accent-soft); color: var(--accent-text); }+.brand-text { display: grid; line-height: 1.25; }+.brand-name { display: block; font-family: var(--font-mono); font-size: var(--fs-sm); font-weight: 600; letter-spacing: -.01em; }+.brand-sub { display: block; font-size: var(--fs-2xs); color: var(--muted); }+.pane-head .badge { margin-left: auto; }+.clear-btn { flex: none; }+.lang-btn { flex: none; margin-left: auto; min-width: 44px; font-weight: 600; }++/* ================= 左栏:AI 助手 ================= */+.convo { padding: var(--sp-8) var(--sp-6) var(--sp-4); display: flex; flex-direction: column; gap: var(--sp-6); }+.intro { display: flex; flex-direction: column; gap: var(--sp-5); }+.intro-title { font-size: var(--fs-xl); font-weight: 700; letter-spacing: -.02em; line-height: 1.25; outline-offset: 4px; }+.intro-text { color: var(--text-2); }+.caps { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--sp-3) var(--sp-4); }+.cap { display: flex; align-items: center; gap: 10px; font-size: var(--fs-sm); color: var(--text-2); min-width: 0; }+.cap .ic { flex: none; width: 32px; height: 32px; display: grid; place-items: center; border-radius: 9px; background: var(--sunken); box-shadow: inset 0 0 0 1px var(--line); color: var(--accent-text); --od-icon-size: 16px; }+.demo-note { font-size: var(--fs-xs); color: var(--warn-text); background: var(--warn-soft); padding: 10px var(--sp-3); border-radius: var(--r-md); }++.turns { display: flex; flex-direction: column; gap: var(--sp-8); }+.turn { display: flex; flex-direction: column; gap: var(--sp-3); animation: rise var(--dur) var(--ease-out) both; }+.msg-user { align-self: flex-end; max-width: 86%; display: grid; gap: 2px; justify-items: end; }+.bubble {+ display: block; max-width: 100%; padding: 10px 14px; border: 0; border-radius: 16px 16px 4px 16px;+ background: var(--accent-soft); color: var(--text); box-shadow: inset 0 0 0 1px var(--accent-line);+ font: inherit; line-height: 1.5; text-align: left; overflow-wrap: anywhere; cursor: pointer;+ transition: background-color var(--dur-fast) var(--ease-out);+}+@media (hover: hover) { .bubble:hover:not(:disabled) { background: var(--accent-line); color: var(--text); } }+.bubble:disabled { cursor: default; }+.msg-meta { display: flex; align-items: center; gap: 2px; flex-wrap: wrap; justify-content: flex-end; min-height: 28px; }+.msg-time { display: block; font-size: var(--fs-2xs); color: var(--muted); font-variant-numeric: tabular-nums; margin-right: var(--sp-1); }+.mini { display: inline-flex; align-items: center; gap: 4px; min-height: 28px; padding: 0 var(--sp-2); border: 0; border-radius: var(--r-sm); background: transparent; color: var(--muted); font-size: var(--fs-2xs); font-weight: 600; cursor: pointer; white-space: nowrap; --od-icon-size: 14px; transition: opacity var(--dur-fast) var(--ease-out), background-color var(--dur-fast) var(--ease-out); }+@media (hover: hover) {+ .mini:hover:not(:disabled) { background: var(--hover); color: var(--text); }+ .mini.danger:hover:not(:disabled) { background: var(--danger-soft); color: var(--danger-text); }+ /* 重新执行、删除平时收起,悬停或键盘聚焦这条记录时出现 */+ .msg-meta .mini { opacity: 0; }+ .turn:hover .msg-meta .mini, .msg-meta:focus-within .mini, .msg-meta .mini.confirm-del, .msg-meta .mini.confirm-del + .mini { opacity: 1; }+}+.mini:disabled { opacity: .45; cursor: not-allowed; }+.mini.confirm-del { background: var(--danger); color: var(--on-danger); }+@media (hover: hover) { .mini.confirm-del:hover { background: var(--danger-hover); color: var(--on-danger); } }+@media (pointer: coarse) { .mini { min-height: 44px; } }+.msg-agent { display: flex; flex-direction: column; gap: var(--sp-3); }+.agent-line { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }+.avatar { width: 28px; height: 28px; border-radius: 9px; background: var(--accent); color: var(--on-accent); display: grid; place-items: center; flex: none; --od-icon-size: 16px; }+.agent-name { font-weight: 600; font-size: var(--fs-sm); }+.agent-meta { font-size: var(--fs-2xs); color: var(--muted); font-variant-numeric: tabular-nums; }+.agent-line .badge { margin-left: auto; }+.toggle-steps { align-self: flex-start; display: inline-flex; align-items: center; gap: 6px; min-height: 32px; padding: 0 var(--sp-2); margin-left: -8px; border: 0; border-radius: var(--r-sm); background: transparent; color: var(--muted); font-size: var(--fs-xs); font-weight: 600; cursor: pointer; --od-icon-size: 14px; }+@media (hover: hover) { .toggle-steps:hover { background: var(--hover); color: var(--text); } }+.toggle-steps .od-icon { transition: transform var(--dur) var(--ease-out); }+.toggle-steps[aria-expanded="true"] .od-icon { transform: rotate(180deg); }++.steps { display: flex; flex-direction: column; padding-left: 4px; }+.step { display: grid; grid-template-columns: 20px minmax(0, 1fr); column-gap: var(--sp-3); animation: rise var(--dur) var(--ease-out) both; }+.step-rail { display: flex; flex-direction: column; align-items: center; padding-top: 2px; }+.step-dot { width: 20px; height: 20px; border-radius: 50%; display: grid; place-items: center; flex: none; --od-icon-size: 12px; }+.step-line { flex: 1; width: 1.5px; border-radius: 1px; background: var(--line); margin-top: 4px; min-height: 8px; }+.step:last-child .step-line { visibility: hidden; }+.step-body { display: flex; flex-direction: column; gap: 6px; padding-bottom: var(--sp-5); min-width: 0; }+.step-thought { font-size: var(--fs-md); line-height: 1.5; color: var(--text); overflow-wrap: anywhere; }+.step-result { font-size: var(--fs-sm); color: var(--muted); overflow-wrap: anywhere; }+.step-result.err { color: var(--danger-text); }+.confirm { display: flex; flex-direction: column; gap: var(--sp-2); padding: var(--sp-4); border-radius: var(--r-lg); background: var(--warn-soft); box-shadow: inset 0 0 0 1px var(--warn-line); margin-top: var(--sp-1); }+.confirm-title { display: flex; align-items: center; gap: var(--sp-2); font-weight: 600; color: var(--warn-text); --od-icon-size: 18px; }+.confirm-detail { overflow-wrap: anywhere; color: var(--text); }+.confirm .od-cluster { margin-top: var(--sp-1); }+.answer { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: var(--sp-3); padding: 14px var(--sp-4); border-radius: var(--r-lg); --od-icon-size: 20px; }+.answer.tone-ok { box-shadow: inset 0 0 0 1px var(--accent-line); }+.answer.tone-danger { box-shadow: inset 0 0 0 1px var(--danger-line); }+.answer > .od-icon { margin-top: 2px; }+.answer-text { display: grid; gap: 2px; }+.answer-title { display: block; font-weight: 600; font-size: var(--fs-sm); }+.answer-body { display: block; color: var(--text); overflow-wrap: anywhere; }++.agent-foot { padding: var(--sp-3) var(--sp-4) var(--sp-4); display: flex; flex-direction: column; gap: var(--sp-2); }+.composer { display: flex; flex-direction: column; border: 1px solid var(--line); border-radius: var(--r-xl); background: var(--panel); box-shadow: var(--shadow-float); overflow: hidden; transition: border-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out); }+.composer:focus-within { border-color: var(--accent); box-shadow: 0 0 0 4px var(--accent-soft), var(--shadow-float); }+.composer.invalid { border-color: var(--danger); }+/* 执行中的暂停 / 接管 / 停止并到输入框顶部 */+.runbar { display: flex; align-items: center; gap: var(--sp-2); flex-wrap: wrap; padding: var(--sp-2) var(--sp-2) var(--sp-2) 14px; background: var(--sunken); border-bottom: 1px solid var(--line); }+.runbar-state { flex: 1 1 120px; display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-sm); font-weight: 600; min-width: 0; --od-icon-size: 16px; }+.runbar-time { font-weight: 500; color: var(--muted); font-variant-numeric: tabular-nums; }+.textarea { display: block; width: 100%; min-height: 60px; max-height: 176px; resize: none; padding: 14px var(--sp-4) 0; border: 0; background: transparent; color: var(--text); font-size: var(--fs-md); line-height: 1.55; overflow-y: auto; }+.textarea:focus-visible { outline: none; }+.textarea:disabled { color: var(--muted); cursor: not-allowed; }+.composer-row { display: flex; align-items: center; gap: var(--sp-2); padding: var(--sp-2) var(--sp-2) var(--sp-2) var(--sp-4); }+.composer-hint { flex: 1; font-size: var(--fs-2xs); color: var(--muted); }+.agent-pick { flex: none; }+.agent-pick .select { min-height: 30px; max-width: 160px; padding: 0 26px 0 10px; border-radius: var(--r-sm); background: var(--sunken); color: var(--text-2); font-size: var(--fs-2xs); font-weight: 500; transition: background var(--dur-fast) var(--ease-out); }+.agent-pick .select:hover:not(:disabled) { background: var(--hover); }+.agent-pick .select:disabled { opacity: .6; cursor: default; }+.agent-pick .select-chev { margin-right: 6px; --od-icon-size: 14px; }+.send { width: 44px; height: 44px; padding: 0; border-radius: 12px; --od-icon-size: 20px; }+.field-error { font-size: var(--fs-xs); color: var(--danger-text); font-weight: 500; padding: 0 var(--sp-2); }++/* ================= 中间:设备舞台 ================= */+.pane-stage { grid-template-rows: var(--head-h) minmax(0, 1fr) auto; }+.stage-head { border-bottom: 0; padding: 0 var(--sp-1); gap: var(--sp-3); }+/* 设备选择和状态合成一条分段状态栏 */+.statusbar { display: flex; align-items: center; min-width: 0; height: 44px; padding: 4px; border-radius: var(--r-lg); background: var(--panel); box-shadow: 0 0 0 1px var(--panel-edge), var(--shadow-xs); }+.dev-select { display: flex; align-items: center; gap: 6px; min-width: 0; padding-left: 10px; }+.dev-select .label { margin: 0; white-space: nowrap; font-size: var(--fs-2xs); }+/* 地方不够时设备名先省略(右侧设备面板里有全名,至少留约 6 个字),状态标签尽量完整,再不够才横向滚动 */+.dev-select { flex: 0 100 auto; }+.dev-select .select-wrap { min-width: 6.5em; }+.dev-select .select-wrap { grid-template-columns: minmax(0, auto); flex: 0 1 auto; }+.dev-select .select { width: 100%; min-width: 0; max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+/* 设备名缩到最窄之后,状态标签才开始让(收缩按 flex-shrink × 宽度分摊,所以这里取很小的值) */+.statusbar .chips { flex-shrink: 0.01; }+/* 中间栏的各行跟着栏宽收缩,不按内容最小宽度把栏撑出窗口 */+.pane-stage > * { min-width: 0; }+.select-wrap { display: grid; min-width: 0; }+.select-wrap > * { grid-area: 1 / 1; }+.select { appearance: none; -webkit-appearance: none; min-height: 36px; padding: 0 30px 0 var(--sp-2); border: 0; border-radius: var(--r-md); background: transparent; font-weight: 600; cursor: pointer; max-width: 240px; }+@media (hover: hover) { .select:hover:not(:disabled) { background: var(--hover); } }+.select-chev { justify-self: end; align-self: center; margin-right: 8px; pointer-events: none; color: var(--muted); --od-icon-size: 16px; }+.chips { display: flex; align-items: center; gap: 2px; flex-wrap: nowrap; min-width: 0; overflow-x: auto; scrollbar-width: none; margin-left: 6px; padding-left: 8px; border-left: 1px solid var(--line); }+.chips:empty { display: none; }+.chips::-webkit-scrollbar { display: none; }+.chip { flex: none; display: inline-flex; align-items: center; gap: 6px; height: 32px; padding: 0 var(--sp-2); border-radius: var(--r-sm); font-size: var(--fs-2xs); font-weight: 500; color: var(--text-2); white-space: nowrap; }+.chip-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--muted); flex: none; box-shadow: 0 0 0 3px var(--sunken); }+.chip-dot.ok { background: var(--ai); } .chip-dot.warn { background: var(--warn); } .chip-dot.off { background: var(--danger); }+.chip .k { color: var(--muted); }+.head-tools { margin-left: auto; display: flex; gap: var(--sp-2); }+.head-tools .btn { min-height: 44px; border: 0; background: var(--panel); box-shadow: 0 0 0 1px var(--panel-edge), var(--shadow-xs); border-radius: var(--r-lg); }+.head-tools .btn-icon { width: 44px; }+@media (hover: hover) { .head-tools .btn:hover:not(:disabled) { background: var(--hover); } }+.dev-toggle { display: none; }++/* 画面区:外层放提示,内层可滚动;放大到超出可视区时可以滚动查看,机身始终居中 */+.stage-area { position: relative; min-height: 0; display: grid; grid-template: minmax(0, 1fr) / minmax(0, 1fr); }+.stage-wrap { min-height: 0; container-type: size; display: grid; place-items: start; overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-color: var(--line-strong) transparent; padding: var(--sp-4) var(--sp-6) var(--sp-6); }+.stage-wrap > .frame { margin: auto; }+.frame[data-zoom="fixed"] { width: var(--fixed-w); }+/* 缩放控件 */+.zoom { display: flex; align-items: center; gap: 2px; height: 44px; padding: 4px; border-radius: var(--r-lg); background: var(--panel); box-shadow: 0 0 0 1px var(--panel-edge), var(--shadow-xs); }+.zoom button { height: 36px; min-width: 36px; padding: 0 var(--sp-2); border: 0; border-radius: var(--r-md); background: transparent; color: var(--text-2); display: inline-flex; align-items: center; justify-content: center; font-size: var(--fs-xs); font-weight: 600; cursor: pointer; white-space: nowrap; --od-icon-size: 18px; transition: background-color var(--dur-fast) var(--ease-out); }+@media (hover: hover) { .zoom button:hover:not(:disabled) { background: var(--hover); color: var(--text); } }+.zoom button:disabled { color: var(--muted); opacity: .45; cursor: not-allowed; }+.zoom .zoom-val { min-width: 52px; font-variant-numeric: tabular-nums; }+.zoom .zoom-fit[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent-text); }+.frame {+ --ratio: .4613; --pad: 11px;+ width: min(100cqw - 48px, calc((100cqh - 40px - var(--pad) * 2) * var(--ratio) + var(--pad) * 2));+ padding: var(--pad); border-radius: 54px; background: var(--bezel);+ box-shadow: inset 0 0 0 1.5px var(--bezel-edge), inset 0 0 0 4px rgba(255, 255, 255, .03), var(--shadow-phone);+ transition: box-shadow var(--dur) var(--ease-out);+}+.frame[data-ctl="ai"] { box-shadow: inset 0 0 0 1.5px var(--bezel-edge), 0 0 0 3px var(--ai), 0 0 0 8px var(--accent-soft), var(--shadow-phone); }+.frame[data-ctl="takeover"] { box-shadow: inset 0 0 0 1.5px var(--bezel-edge), 0 0 0 3px var(--user), 0 0 0 8px var(--user-soft), var(--shadow-phone); }+.stage { width: 100%; aspect-ratio: 393 / 852; display: grid; grid-template: minmax(0, 1fr) / minmax(0, 1fr); background: #000; border-radius: 43px; overflow: hidden; touch-action: none; user-select: none; -webkit-user-select: none; cursor: crosshair; }+.frame[data-ctl="ai"] .stage { cursor: not-allowed; }+/* iPad:边框更厚、屏幕圆角更小,跟实际机身比例一致 */+.frame[data-kind="ipad"] { --pad: 14px; border-radius: 34px; }+.frame[data-kind="ipad"] .stage { border-radius: 20px; }+.stage > * { grid-area: 1 / 1; }+.stage img { width: 100%; height: 100%; object-fit: contain; display: block; -webkit-user-drag: none; }+.stage-msg { place-self: center; padding: var(--sp-6); color: #d4d7dc; text-align: center; font-size: var(--fs-sm); max-width: 34ch; }+.stage-msg code { font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.92em; color: #fff; overflow-wrap: anywhere; }+.stage-msg .btn { margin-top: var(--sp-3); }+.stage-msg .stage-err { display: inline-block; margin-top: var(--sp-2); font-size: var(--fs-xs); color: #f2b8b5; overflow-wrap: anywhere; }+.marks { width: 100%; height: 100%; pointer-events: none; overflow: visible; }+/* 操作结果:画面下方淡入淡出的小提示,不占布局 */+.toast {+ position: absolute; left: 50%; bottom: var(--sp-2); z-index: 3; max-width: min(90%, 520px);+ padding: var(--sp-2) 14px; border-radius: 999px; background: var(--text); color: var(--panel); box-shadow: var(--shadow-float);+ font-size: var(--fs-sm); line-height: 1.4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; pointer-events: none;+ opacity: 0; transform: translate(-50%, 6px); transition: opacity var(--dur-exit) var(--ease-in), transform var(--dur-exit) var(--ease-in);+}+.toast.show { opacity: 1; transform: translate(-50%, 0); transition: opacity var(--dur) var(--ease-out), transform var(--dur) var(--ease-out); }+.toast.err { background: var(--danger); color: var(--on-danger); }+.toast.warn { background: var(--warn-soft); color: var(--warn-text); box-shadow: 0 0 0 1px var(--warn-line), var(--shadow-float); }++.mk { transform-box: fill-box; transform-origin: center; animation: mk-in var(--dur) var(--ease-out) both; }+.mk.out { animation: mk-out var(--dur-exit) var(--ease-in) both; }+@keyframes mk-in { from { opacity: 0; transform: scale(.6); } to { opacity: 1; transform: scale(1); } }+@keyframes mk-out { from { opacity: 1; } to { opacity: 0; } }+.mk-user .mk-shape, .mk-user .mk-dot { fill: rgba(138, 180, 248, .3); stroke: #8ab4f8; stroke-width: 3; }+.mk-ai .mk-shape, .mk-ai .mk-dot { fill: rgba(60, 202, 169, .3); stroke: #3ccaa9; stroke-width: 3; }+.mk-user .mk-line { stroke: #8ab4f8; stroke-width: 5; stroke-linecap: round; }+.mk-ai .mk-line { stroke: #3ccaa9; stroke-width: 5; stroke-linecap: round; stroke-dasharray: 10 8; }+.mk-ring { fill: none; stroke-width: 2; }+.mk-user .mk-ring { stroke: #8ab4f8; } .mk-ai .mk-ring { stroke: #3ccaa9; }+.mk-tag { font: 700 14px var(--font-mono); fill: #3ccaa9; paint-order: stroke; stroke: #000; stroke-width: 3px; }+.mk-hl { fill: rgba(245, 190, 80, .18); stroke: #f5be50; stroke-width: 2.5; }+.hover-dot .ring { fill: rgba(255, 255, 255, .22); stroke: #ffffff; stroke-width: 2; paint-order: stroke; filter: drop-shadow(0 0 1.5px rgba(0, 0, 0, .7)); }+.hover-dot .core { fill: #ffffff; filter: drop-shadow(0 0 1px rgba(0, 0, 0, .8)); }+.hover-dot .dot-scale { transform-box: fill-box; transform-origin: center; transition: transform var(--dur-fast) var(--ease-out); }+.hover-dot.pressed .dot-scale { transform: scale(.75); }++.stage-foot { display: flex; flex-direction: column; align-items: center; gap: var(--sp-2); padding: 0 var(--sp-6) var(--sp-3); }+/* 提示条叠在按键工具条的位置上:工具条只是隐藏、仍占位,任何宽度下设备画面都不会因此变小 */+.dock-slot { display: grid; width: 100%; justify-items: center; align-items: stretch; }+.dock-slot > * { grid-area: 1 / 1; }+.dock.is-covered { visibility: hidden; }+.dock { display: flex; align-items: center; gap: 6px; flex-wrap: nowrap; justify-content: center; padding: 6px; border-radius: var(--r-xl); background: var(--panel); box-shadow: 0 0 0 1px var(--panel-edge), var(--shadow-float); max-width: 100%; }+.keys { flex: none; display: flex; gap: 2px; padding: 2px; border-radius: 12px; background: var(--sunken); }+.key { width: 40px; height: 40px; border: 0; border-radius: var(--r-md); background: transparent; color: var(--text-2); display: grid; place-items: center; cursor: pointer; --od-icon-size: 20px; transition: background-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out); }+@media (hover: hover) { .key:hover:not(:disabled) { background: var(--panel); color: var(--text); box-shadow: var(--shadow-xs), 0 0 0 1px var(--panel-edge); } }+.key:active:not(:disabled) { background: var(--press); box-shadow: none; }+.key:disabled { color: var(--muted); opacity: .45; cursor: not-allowed; }+.type-field { display: flex; align-items: center; gap: 2px; flex: 0 1 auto; min-width: 0; }+.type-field .input { width: 220px; min-width: 96px; flex: 1 1 220px; min-height: 44px; border-radius: 12px; }+.type-field .btn { min-height: 44px; border-radius: 12px; }+.type-field .btn-icon { width: 44px; }+.guard { width: min(100%, 560px); min-height: 56px; align-self: stretch; display: flex; align-items: center; gap: var(--sp-3); flex-wrap: nowrap; padding: 0 var(--sp-2) 0 var(--sp-4); border-radius: var(--r-xl); background: var(--panel); box-shadow: 0 0 0 1px var(--panel-edge), var(--shadow-float); --od-icon-size: 18px; }+.guard-text { flex: 1 1 0; min-width: 0; display: grid; line-height: 1.35; }+.guard-title { display: block; font-weight: 600; font-size: var(--fs-sm); }+.guard-sub { display: block; font-size: var(--fs-xs); color: var(--muted); }+.guard.tone-accent .guard-title { color: var(--accent-text); } .guard.tone-warn .guard-title { color: var(--warn-text); } .guard.tone-user .guard-title { color: var(--user-text); }+.guard.nudge { animation: nudge 360ms var(--ease-out); }+@keyframes nudge { 0%, 100% { transform: translateX(0); } 25% { transform: translateX(-4px); } 75% { transform: translateX(4px); } }+.meta-row { display: flex; justify-content: center; font-size: var(--fs-2xs); color: var(--muted); max-width: 100%; }+.feed { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; }+.feed-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ai); flex: none; }+.feed-dot.off { background: var(--danger); } .feed-dot.wait { background: var(--muted); }++/* ================= 右栏:设备面板 ================= */+.seg { display: flex; gap: 2px; padding: 3px; border-radius: 12px; background: var(--sunken); flex: 1; }+.seg button { flex: 1; min-height: 36px; border: 0; border-radius: 9px; background: transparent; color: var(--muted); font-size: var(--fs-sm); font-weight: 600; cursor: pointer; white-space: nowrap; transition: background-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out); }+.seg button[aria-selected="true"] { background: var(--panel); color: var(--text); box-shadow: var(--shadow-xs), 0 0 0 1px var(--panel-edge); }+@media (hover: hover) { .seg button:hover { color: var(--text); } }+.dev-close { display: inline-flex; }+@media (min-width: 1280px) {+ .shell[data-dev-hidden="true"] { grid-template-columns: var(--w-agent) minmax(0, 1fr); }+ .shell[data-dev-hidden="true"] .pane-dev { display: none; }+ .shell[data-dev-hidden="true"] .dev-toggle { display: inline-flex; }+}+.tabpanel { padding: var(--sp-5); display: flex; flex-direction: column; gap: var(--sp-6); }+.sec { display: flex; flex-direction: column; gap: var(--sp-3); }+.sec-head { display: flex; align-items: center; gap: var(--sp-2); }+.sec-title { font-size: var(--fs-xs); font-weight: 600; color: var(--muted); letter-spacing: .04em; flex: 1; }+.empty-note { font-size: var(--fs-sm); color: var(--muted); padding: var(--sp-4); border-radius: var(--r-lg); background: var(--sunken); }+.empty-note.err { color: var(--danger-text); background: var(--danger-soft); }++.device-card { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 14px; align-items: center; padding: var(--sp-4); border-radius: var(--r-lg); background: var(--sunken); }+.device-ic { width: 48px; height: 48px; border-radius: 12px; background: var(--panel); box-shadow: var(--shadow-xs), 0 0 0 1px var(--panel-edge); display: grid; place-items: center; color: var(--accent-text); --od-icon-size: 24px; }+.device-name { display: block; font-weight: 700; font-size: var(--fs-lg); line-height: 1.3; }+.device-sub { display: block; font-size: var(--fs-xs); color: var(--muted); }+.facts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--sp-2); }+.fact { padding: 10px var(--sp-3); border-radius: var(--r-md); box-shadow: inset 0 0 0 1px var(--line); display: grid; gap: 2px; min-width: 0; }+.fact-k { display: block; font-size: var(--fs-2xs); color: var(--muted); }+.fact-v { display: block; font-size: var(--fs-sm); font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.fact-v.mono { font-size: var(--fs-2xs); font-weight: 500; }+.checks { display: flex; flex-direction: column; padding: 14px 14px 2px; border-radius: var(--r-lg); background: var(--sunken); }+.check { display: grid; grid-template-columns: 24px minmax(0, 1fr); column-gap: var(--sp-3); }+.check-rail { display: flex; flex-direction: column; align-items: center; }+.check-dot { width: 24px; height: 24px; border-radius: 50%; display: grid; place-items: center; --od-icon-size: 14px; }+.check-dot.pending { box-shadow: inset 0 0 0 1.5px var(--line-strong); color: var(--muted); }+.check-line { flex: 1; width: 1.5px; background: var(--line-strong); opacity: .6; min-height: 10px; margin: 2px 0; }+.check:last-child .check-line { visibility: hidden; }+.check-body { padding: 2px 0 var(--sp-3); display: grid; gap: 2px; min-width: 0; }+.check-name { display: block; font-size: var(--fs-sm); font-weight: 600; }+.check.pending .check-name { color: var(--muted); font-weight: 500; }+.check-hint { display: block; font-size: var(--fs-xs); color: var(--text-2); }+.check-hint code { font-size: var(--fs-2xs); padding: 1px 6px; border-radius: 4px; background: var(--panel); box-shadow: inset 0 0 0 1px var(--line); }+.check-err { display: block; font-size: var(--fs-2xs); color: var(--danger-text); font-family: var(--font-mono); overflow-wrap: anywhere; }++.url-row { display: flex; gap: var(--sp-2); }+.search { display: grid; }+.search > * { grid-area: 1 / 1; }+.search .input { padding-left: 36px; }+.search-ic { align-self: center; margin-left: 12px; color: var(--muted); pointer-events: none; --od-icon-size: 16px; }+.switch-row { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-xs); color: var(--text-2); cursor: pointer; }+.switch-row input { width: 16px; height: 16px; accent-color: var(--accent); margin: 0; }+.list { display: flex; flex-direction: column; gap: 2px; margin: 0 calc(var(--sp-2) * -1); }+.app-row { display: grid; grid-template-columns: 40px minmax(0, 1fr) auto; gap: var(--sp-3); align-items: center; padding: var(--sp-2); border-radius: 12px; transition: background-color var(--dur-fast) var(--ease-out); }+.app-tile { width: 40px; height: 40px; border-radius: 11px; display: grid; place-items: center; font-size: 17px; font-weight: 700; box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .06), var(--shadow-xs); }+.app-text { display: grid; min-width: 0; }+.app-name { font-size: var(--fs-sm); font-weight: 600; }+.app-id { font-family: var(--font-mono); font-size: var(--fs-2xs); color: var(--muted); }+.app-actions, .el-actions { display: flex; gap: var(--sp-1); transition: opacity var(--dur-fast) var(--ease-out); }+.el-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: var(--sp-2); align-items: center; padding: var(--sp-2) 10px; border-radius: 12px; transition: background-color var(--dur-fast) var(--ease-out); }+.el-row:focus-within, .el-row.hl { background: var(--hover); }+@media (hover: hover) {+ .app-row:hover, .el-row:hover { background: var(--hover); }+ /* 启动 / 结束 / 点它:悬停或键盘聚焦这一行时才出现 */+ .app-actions, .el-actions { opacity: 0; }+ .app-row:hover .app-actions, .app-row:focus-within .app-actions, .el-row:hover .el-actions, .el-row:focus-within .el-actions { opacity: 1; }+}+.el-text { display: grid; min-width: 0; }+.el-label { font-size: var(--fs-sm); font-weight: 500; }+.el-meta { font-family: var(--font-mono); font-size: var(--fs-2xs); color: var(--muted); }+.panel-tools { display: flex; gap: var(--sp-2); }+.panel-tools .search { flex: 1; }+.count { font-size: var(--fs-2xs); color: var(--muted); font-variant-numeric: tabular-nums; }+.wait-result { font-size: var(--fs-sm); }+/* 读取中的骨架占位 */+.skel-row { display: grid; grid-template-columns: 40px minmax(0, 1fr); gap: var(--sp-3); align-items: center; padding: var(--sp-2); }+.skel-row.no-tile { grid-template-columns: minmax(0, 1fr); padding: 10px; }+.skel { display: block; background: var(--press); border-radius: var(--r-xs); animation: pulse 1.2s ease-in-out infinite; }+.skel.tile { width: 40px; height: 40px; border-radius: 11px; }+.skel-lines { display: grid; gap: 6px; }+.skel.l1 { height: 12px; width: 55%; }+.skel.l2 { height: 10px; width: 80%; }+.skel-row:nth-child(2n) .skel.l1 { width: 40%; }+.skel-row:nth-child(3n) .skel.l2 { width: 65%; }++/* 确认弹窗 */+.dialog { width: min(420px, calc(100vw - 32px)); padding: var(--sp-6); border: 0; border-radius: var(--r-2xl); background: var(--panel); color: var(--text); box-shadow: 0 0 0 1px var(--panel-edge), var(--shadow-float); }+.dialog::backdrop { background: rgba(10, 14, 18, .4); }+.dialog[open] { animation: rise var(--dur) var(--ease-out); }+.dialog h2 { font-size: var(--fs-lg); margin-bottom: var(--sp-2); }+.dialog p { color: var(--text-2); }+.dialog-actions { display: flex; justify-content: flex-end; gap: var(--sp-2); margin-top: var(--sp-6); }++/* ================= 演示画面(代码绘制的模拟界面;iPhone 393×852 点,iPad mini 横屏 1133×744 点) ================= */+.ph { width: var(--dw, 393px); height: var(--dh, 852px); transform: scale(var(--k, 1)); transform-origin: 0 0; justify-self: start; align-self: start; display: grid; grid-template-rows: 54px minmax(0, 1fr) 34px; overflow: hidden; background: #1f2b35; color: #fff; font: 17px/1.3 -apple-system, "SF Pro Text", "PingFang SC", system-ui, sans-serif; }+.ph--light { background: #fff; color: #000; } .ph--gray { background: #f2f2f7; color: #000; } .ph--black { background: #000; color: #fff; }+.ph-status { display: flex; align-items: center; justify-content: space-between; padding: 14px 30px 0 48px; font-weight: 600; font-size: 16px; }+.ph-sys { display: flex; align-items: center; gap: 6px; font-size: 13px; }+.ph-batt { width: 25px; height: 12px; border: 1.5px solid currentColor; border-radius: 4px; padding: 1.5px; display: block; }+.ph-batt::after { content: ""; display: block; width: 72%; height: 100%; background: currentColor; border-radius: 1.5px; }+.ph-main { min-height: 0; display: flex; flex-direction: column; overflow: hidden; }+.ph-ind { display: grid; place-items: center; }+.ph-ind::after { content: ""; width: 134px; height: 5px; border-radius: 3px; background: currentColor; }+.ph-home { flex: 1; display: flex; flex-direction: column; padding: 20px 20px 8px; }+.ph-grid { display: grid; grid-template-columns: repeat(4, 1fr); row-gap: 24px; justify-items: center; }+.ph-app { display: flex; flex-direction: column; align-items: center; gap: 6px; width: 78px; }+.ph-icon { width: 62px; height: 62px; border-radius: 14px; display: grid; place-items: center; font-size: 26px; font-weight: 600; }+.ph-app-name { font-size: 12px; color: #fff; white-space: nowrap; }+.ph-dock { margin-top: auto; display: grid; grid-template-columns: repeat(4, 1fr); justify-items: center; padding: 16px 6px; border-radius: 30px; background: rgba(255, 255, 255, .16); }+.ph--ipad { grid-template-rows: 40px minmax(0, 1fr) 24px; }+.ph--ipad .ph-status { padding: 10px 32px 0; }+.ph--ipad .ph-home { padding: 28px 96px 8px; }+.ph--ipad .ph-grid { grid-template-columns: repeat(8, 1fr); row-gap: 32px; }+.ph--ipad .ph-dock { align-self: center; grid-template-columns: repeat(4, 96px); padding: 14px 24px; }+.ph--ipad .ph-body, .ph--ipad .ph-set, .ph--ipad .ph-msgs { padding-left: 64px; padding-right: 64px; }+.ph--ipad .ph-sw { padding-top: 64px; }+.ph--ipad .sw-time { font-size: 112px; }+.ph--ipad .ph-sw-btns { justify-content: center; gap: 320px; margin-top: 48px; }+.ph--ipad .ph-lock { padding-top: 24px; }+.ph--ipad .ph-kb { height: 300px; }+.ph-clock { flex: 1; display: flex; flex-direction: column; min-height: 0; }+.ph-body { flex: 1; min-height: 0; padding: 4px 20px; display: flex; flex-direction: column; }+.ph-title { font-size: 34px; font-weight: 700; margin: 8px 0 12px; }+.ph-row { display: flex; justify-content: space-between; align-items: center; padding: 14px 0; border-bottom: .5px solid #3a3a3c; }+.ph-row-main { display: flex; flex-direction: column; gap: 2px; }+.ph-row-sub { font-size: 14px; color: #8e8e93; }+.ph-row-big { font-size: 44px; font-weight: 300; font-variant-numeric: tabular-nums; }+.ph-row.off .ph-row-big { color: #8e8e93; }+.ph-toggle { width: 51px; height: 31px; border-radius: 16px; background: #39393d; padding: 2px; display: flex; }+.ph-toggle::after { content: ""; width: 27px; height: 27px; border-radius: 50%; background: #fff; }+.ph-toggle.on { background: #30d158; justify-content: flex-end; }+.ph-sw { display: flex; flex-direction: column; flex: 1; padding-top: 110px; }+.sw-time { font-size: 82px; font-weight: 200; text-align: center; font-variant-numeric: tabular-nums; letter-spacing: -1px; }+.ph-sw-btns { display: flex; justify-content: space-between; margin-top: 100px; }+.ph-round { width: 84px; height: 84px; border-radius: 50%; display: grid; place-items: center; font-size: 17px; }+.ph-round.gray { background: #333; color: #fff; } .ph-round.green { background: #0e3a1b; color: #30d158; } .ph-round.red { background: #3d1210; color: #ff453a; }+.ph-laps { margin-top: 20px; border-top: .5px solid #3a3a3c; }+.ph-lap { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: .5px solid #3a3a3c; font-variant-numeric: tabular-nums; }+.ph-tabbar { display: grid; grid-template-columns: repeat(4, 1fr); border-top: .5px solid #3a3a3c; padding: 12px 0 4px; font-size: 12px; text-align: center; color: #8e8e93; }+.ph-tab { padding: 6px 0; } .ph-tab.on { color: #ff9f0a; font-weight: 600; }+.ph-set { flex: 1; padding: 0 16px; display: flex; flex-direction: column; }+.ph-nav { min-height: 40px; display: flex; align-items: center; }+.ph-group { background: #fff; border-radius: 12px; margin-bottom: 24px; overflow: hidden; }+.ph-cell { display: flex; justify-content: space-between; align-items: center; gap: 12px; min-height: 46px; padding: 0 16px; border-bottom: .5px solid #e5e5ea; }+.ph-cell:last-child { border-bottom: 0; }+.ph-cell-v { color: #8e8e93; }+.ph-msgs { flex: 1; padding: 0 16px; display: flex; flex-direction: column; }+.ph-search { background: #eeeef0; border-radius: 10px; padding: 8px 12px; color: #8e8e93; font-size: 16px; margin-bottom: 8px; }+.ph-thread { display: grid; grid-template-columns: 46px minmax(0, 1fr) auto; gap: 12px; align-items: center; padding: 10px 0; border-bottom: .5px solid #e5e5ea; }+.ph-avatar { width: 46px; height: 46px; border-radius: 50%; background: #a9a9b0; color: #fff; display: grid; place-items: center; font-size: 18px; font-weight: 600; }+.ph-thread-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }+.ph-thread-name { font-weight: 600; }+.ph-thread-prev { color: #8e8e93; font-size: 15px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.ph-thread-time { color: #8e8e93; font-size: 14px; align-self: start; margin-top: 4px; }+.ph-chat { flex: 1; display: flex; flex-direction: column; min-height: 0; }+.ph-chat-head { display: grid; grid-template-columns: 96px 1fr 96px; align-items: center; padding: 2px 8px 10px; border-bottom: .5px solid #e5e5ea; background: #f7f7f8; }+.ph-back { color: #0a84ff; font-size: 17px; padding: 6px 0; }+.ph-chat-who { display: flex; flex-direction: column; align-items: center; gap: 4px; font-size: 12px; }+.ph-chat-who .ph-avatar { width: 40px; height: 40px; font-size: 16px; }+.ph-chat-body { flex: 1; min-height: 0; padding: 12px 14px; display: flex; flex-direction: column; gap: 8px; overflow: hidden; justify-content: flex-end; }+.ph-bubble { max-width: 72%; padding: 8px 13px; border-radius: 18px; font-size: 17px; overflow-wrap: anywhere; }+.ph-bubble.in { background: #e9e9eb; align-self: flex-start; } .ph-bubble.out { background: #0a84ff; color: #fff; align-self: flex-end; }+.ph-chat-input { display: flex; align-items: center; gap: 8px; padding: 8px 12px; }+.ph-field { flex: 1; border: 1px solid #c7c7cc; border-radius: 18px; padding: 7px 14px; min-height: 36px; overflow-wrap: anywhere; }+.ph-field.empty { color: #8e8e93; } .ph-field.focus { border-color: #0a84ff; box-shadow: 0 0 0 1px #0a84ff; }+.ph-send { width: 34px; height: 34px; border-radius: 50%; background: #0a84ff; color: #fff; display: grid; place-items: center; font-size: 13px; font-weight: 700; }+.ph-send.off { background: #c7c7cc; }+.ph-kb { height: 250px; background: #d1d3d9; display: grid; place-items: center; color: #6b6b70; font-size: 15px; }+.ph-generic { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 32px; text-align: center; }+.ph-generic-sub { color: #6b6b70; font-size: 15px; overflow-wrap: anywhere; }+.ph-lock { flex: 1; display: flex; flex-direction: column; align-items: center; padding-top: 48px; }+.ph-lock-date { font-size: 20px; font-weight: 500; }+.ph-lock-time { font-size: 96px; font-weight: 600; line-height: 1.05; font-variant-numeric: tabular-nums; }+.ph-lock-hint { margin-top: auto; margin-bottom: 12px; font-size: 15px; opacity: .8; }++/* ================= 响应式 ================= */+@media (max-width: 1279.98px) {+ .shell { grid-template-columns: var(--w-agent) minmax(0, 1fr); }+ .dev-toggle { display: inline-flex; }+ .pane-dev { position: fixed; top: var(--gutter); right: var(--gutter); bottom: var(--gutter); z-index: 30; width: min(var(--w-dev), calc(92vw - var(--gutter) * 2)); box-shadow: 0 0 0 1px var(--panel-edge), var(--shadow-float); transform: translateX(calc(100% + var(--gutter) * 2)); transition: transform var(--dur-exit) var(--ease-in); }+ .shell[data-dev-open="true"] .pane-dev { transform: none; transition: transform var(--dur-slow) var(--ease-out); }+ .dev-close { display: inline-flex; }+}+@media (min-width: 1280px) and (max-width: 1439.98px) {+ /* 三栏里中间最窄的一段:「控制设备」只给读屏,让出地方给状态标签 */+ .dev-select .label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }+ .dev-select { padding-left: 4px; }+}+@media (min-width: 1024px) and (max-width: 1279.98px) {+ /* 两栏时中间只有 500 多点宽:「设备面板」只留图标,「控制设备」只给读屏,底栏两边收窄,不出横向滚动 */+ .dev-toggle { width: 44px; padding: 0; justify-content: center; }+ .dev-toggle > span:not(.ic), .dev-select .label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }+ .dev-select { padding-left: 4px; }+ .stage-foot { padding-inline: var(--sp-3); }+}+@media (max-width: 1023.98px) {+ .shell { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); gap: 0; padding: 0; }+ .mbar { display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-2) var(--sp-4); background: var(--panel); border-bottom: 1px solid var(--line); flex-wrap: wrap; }+ .mbar .seg { flex: 0 1 300px; margin-left: auto; }+ .pane-agent, .pane-stage, .pane-dev { grid-row: 2; grid-column: 1; }+ .pane-agent, .pane-dev { border-radius: 0; box-shadow: none; }+ .pane-dev { position: static; width: auto; transform: none; transition: none; }+ .shell[data-view="agent"] .pane-stage, .shell[data-view="agent"] .pane-dev,+ .shell[data-view="screen"] .pane-agent, .shell[data-view="screen"] .pane-dev,+ .shell[data-view="device"] .pane-agent, .shell[data-view="device"] .pane-stage { display: none; }+ .agent-brand, .dev-toggle, .dev-close, .resizer { display: none; }+ .pane-agent .pane-head { padding: 0 var(--sp-4); }+ .stage-head { padding: 0 var(--sp-4); }+}+@media (max-width: 767.98px) {+ .mbar .brand-sub { display: none; }+ .mbar .seg { flex-basis: 100%; }+ .stage-head { flex-wrap: wrap; height: auto; padding: var(--sp-3) var(--sp-3) 0; }+ .statusbar { flex: 1 1 0; }+ .pane-stage { grid-template-rows: auto minmax(0, 1fr) auto; }+ .chips { display: none; }+ .stage-wrap { padding: var(--sp-4) var(--sp-3) var(--sp-4); }+ .stage-foot { padding: 0 var(--sp-3) var(--sp-3); }+ .dock { flex-wrap: wrap; }+ .type-field { flex: 1 1 100%; }+ .type-field .input { width: auto; flex: 1; }+ .convo { padding: var(--sp-6) var(--sp-4) var(--sp-4); }+ .tabpanel { padding: var(--sp-4); }+ .caps { grid-template-columns: minmax(0, 1fr); }+}+@media (prefers-reduced-motion: reduce) {+ *, *::before, *::after { animation-duration: 1ms !important; animation-iteration-count: 1 !important; transition-duration: 1ms !important; }+ .spin { animation: none !important; }+}</style></head><body>-<div id="screen">- <img id="img" src="/stream" alt="Live screen of the phone" draggable="false">- <div class="msg" id="msg">Connecting…</div>-</div>-<div class="row">- <button data-button="home">Home</button>- <button data-button="lock">Lock</button>- <button data-button="volume_down">Vol −</button>- <button data-button="volume_up">Vol +</button>+<div class="shell" id="shell" data-view="agent" data-dev-open="false">++ <!-- 窄屏顶栏 -->+ <header class="mbar">+ <div class="brand">+ <svg class="brand-mark" viewBox="0 0 32 32" width="28" height="28" aria-hidden="true"><rect x="9" y="3" width="14" height="26" rx="3.5" fill="none" stroke="currentColor" stroke-width="2"/><path d="M13.5 25h5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><circle cx="16" cy="14" r="3" fill="var(--accent)"/></svg>+ <div class="brand-text"><span class="brand-name">iphone-control</span><span class="brand-sub">控制台</span></div>+ </div>+ <div class="seg" role="tablist" aria-label="切换视图">+ <button type="button" role="tab" id="vt-agent" aria-selected="true" aria-controls="pane-agent" data-action="view" data-view="agent"><span id="vt-agent-label">AI 助手</span></button>+ <button type="button" role="tab" id="vt-screen" aria-selected="false" aria-controls="pane-stage" data-action="view" data-view="screen">屏幕</button>+ <button type="button" role="tab" id="vt-device" aria-selected="false" aria-controls="pane-dev" data-action="view" data-view="device">设备</button>+ </div>+ </header>++ <!-- 左:AI 助手 -->+ <aside class="pane pane-agent" id="pane-agent" aria-label="AI 助手">+ <div class="resizer" id="resizer" role="separator" aria-orientation="vertical" aria-controls="pane-agent" aria-label="调整 AI 助手栏宽度" title="拖动调整宽度,双击恢复默认" tabindex="0"></div>+ <div class="pane-head">+ <div class="brand agent-brand">+ <svg class="brand-mark" viewBox="0 0 32 32" width="28" height="28" aria-hidden="true"><rect x="9" y="3" width="14" height="26" rx="3.5" fill="none" stroke="currentColor" stroke-width="2"/><path d="M13.5 25h5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><circle cx="16" cy="14" r="3" fill="var(--accent)"/></svg>+ <div class="brand-text"><span class="brand-name">iphone-control</span></div>+ </div>+ <span id="agent-badge"></span>+ <button type="button" class="btn btn-ghost btn-sm clear-btn" id="clear-btn" data-action="clear" data-focus="clear" hidden><span class="ic" data-icon="trash"></span><span>清空记录</span></button>+ <button type="button" class="btn btn-ghost btn-sm lang-btn" id="lang-btn" aria-label="切换语言" title="切换语言">EN</button>+ </div>+ <div class="pane-body" id="agent-scroll">+ <div class="convo">+ <div class="intro" id="intro">+ <h1 class="intro-title" tabindex="-1" id="intro-title">让 AI 操作你的 Apple 设备</h1>+ <p class="intro-text">用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。</p>+ <ul class="caps" aria-label="AI 能用的操作">+ <li class="cap"><span class="ic" data-icon="eye"></span><span>看屏幕、读元素</span></li>+ <li class="cap"><span class="ic" data-icon="tap"></span><span>点按、滑动、长按</span></li>+ <li class="cap"><span class="ic" data-icon="keyboard"></span><span>输入文字</span></li>+ <li class="cap"><span class="ic" data-icon="grid"></span><span>启动、关闭 App</span></li>+ <li class="cap"><span class="ic" data-icon="link"></span><span>打开链接</span></li>+ <li class="cap"><span class="ic" data-icon="home"></span><span>实体按键</span></li>+ </ul>+ <p class="demo-note" id="demo-note" hidden>演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。</p>+ </div>+ <ol class="turns" id="turns" aria-label="任务记录"></ol>+ </div>+ </div>+ <div class="agent-foot">+ <div class="composer" id="composer">+ <div class="runbar" id="runbar" role="group" aria-label="任务控制" hidden></div>+ <label class="sr-only" for="prompt">交给 AI 的任务</label>+ <textarea class="textarea" id="prompt" rows="2" maxlength="4000" aria-describedby="composer-hint prompt-error" placeholder="想让设备做什么?"></textarea>+ <div class="composer-row">+ <div class="select-wrap agent-pick" id="agent-pick" hidden>+ <label class="sr-only" for="agent">执行任务的 AI</label>+ <select class="select" id="agent" title="执行任务的本地 AI"></select>+ <span class="select-chev" data-icon="chevron"></span>+ </div>+ <span class="composer-hint" id="composer-hint">Enter 发送 · Shift+Enter 换行</span>+ <button type="button" class="btn btn-primary send" id="send" data-action="send" data-focus="send" aria-label="开始任务"><span class="ic" data-icon="send"></span></button>+ </div>+ </div>+ <p class="field-error" id="prompt-error" hidden></p>+ </div>+ </aside>++ <!-- 中:设备舞台 -->+ <main class="pane pane-stage" id="pane-stage" aria-label="设备屏幕">+ <div class="pane-head stage-head">+ <div class="statusbar">+ <div class="dev-select">+ <label class="label" for="device">控制设备</label>+ <div class="select-wrap">+ <select class="select" id="device" disabled><option>正在查找…</option></select>+ <span class="select-chev" data-icon="chevron"></span>+ </div>+ </div>+ <div class="chips" id="chips"></div>+ </div>+ <div class="head-tools">+ <div class="zoom" role="group" aria-label="画面缩放">+ <button type="button" data-action="zoom-out" id="zoom-out" aria-label="缩小画面" title="缩小(也可以按住 Ctrl/⌘ 滚动滚轮)"><span class="ic" data-icon="zoomout"></span></button>+ <button type="button" class="zoom-val" data-action="zoom-actual" id="zoom-val" title="切换到实际尺寸(100%)" aria-label="当前缩放比例,点击切换到实际尺寸">100%</button>+ <button type="button" data-action="zoom-in" id="zoom-in" aria-label="放大画面" title="放大(也可以按住 Ctrl/⌘ 滚动滚轮)"><span class="ic" data-icon="zoomin"></span></button>+ <button type="button" class="zoom-fit" data-action="zoom-fit" id="zoom-fit" aria-pressed="true" title="按窗口大小自动适应">适应</button>+ </div>+ <button type="button" class="btn btn-ghost btn-icon" data-action="reconnect" aria-label="刷新画面" title="刷新画面"><span class="ic" data-icon="refresh"></span></button>+ <button type="button" class="btn dev-toggle" data-action="dev-open" id="dev-toggle" aria-controls="pane-dev" aria-expanded="false"><span class="ic" data-icon="panel"></span><span>设备面板</span></button>+ </div>+ </div>+ <div class="stage-area">+ <div class="stage-wrap" id="stage-wrap">+ <div class="frame" id="frame" data-ctl="user">+ <div class="stage" id="stage" role="group" aria-label="设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按" aria-describedby="status">+ <img id="live" alt="设备的实时画面" draggable="false" hidden>+ <div id="demo" class="ph" aria-hidden="true" hidden></div>+ <svg id="marks" class="marks" viewBox="0 0 393 852" aria-hidden="true"></svg>+ <div class="stage-msg" id="stage-msg">正在连接 iphone-control 服务…</div>+ </div>+ </div>+ </div>+ <p class="toast" id="status" role="status" aria-live="polite"></p>+ </div>+ <div class="stage-foot">+ <div class="dock-slot">+ <div class="guard" id="guard" role="status" hidden></div>+ <div class="dock" id="dock" role="group" aria-label="设备按键和输入">+ <div class="keys" role="group" aria-label="实体按键">+ <button type="button" class="key" data-key="home" aria-label="主屏幕" title="主屏幕"><span class="ic" data-icon="home"></span></button>+ <button type="button" class="key" data-key="lock" aria-label="锁屏" title="锁屏"><span class="ic" data-icon="lock"></span></button>+ <button type="button" class="key" data-key="volume_down" aria-label="音量减" title="音量减"><span class="ic" data-icon="voldown"></span></button>+ <button type="button" class="key" data-key="volume_up" aria-label="音量加" title="音量加"><span class="ic" data-icon="volup"></span></button>+ </div>+ <div class="type-field">+ <label class="sr-only" for="type-text">向设备输入文字</label>+ <input class="input" id="type-text" autocomplete="off" placeholder="向设备输入文字">+ <button type="button" class="btn btn-ghost" id="type-btn">输入</button>+ <button type="button" class="btn btn-ghost btn-icon" id="type-submit" aria-label="输入并回车" title="输入并回车"><span class="ic" data-icon="enter"></span></button>+ </div>+ <button type="button" class="btn btn-primary" id="dock-handback" data-action="handback" data-focus="dock-handback" hidden><span class="ic" data-icon="play"></span><span>交还 AI</span></button>+ </div>+ </div>+ <div class="meta-row">+ <div class="feed"><span class="feed-dot wait" id="feed-dot"></span><span class="od-truncate" id="feed-text">正在连接…</span></div>+ </div>+ </div>+ </main>++ <!-- 右:设备面板 -->+ <aside class="pane pane-dev" id="pane-dev" aria-label="设备面板">+ <div class="resizer resizer-left" id="resizer-dev" role="separator" aria-orientation="vertical" aria-controls="pane-dev" aria-label="调整设备面板宽度" title="拖动调整宽度,双击恢复默认" tabindex="0"></div>+ <div class="pane-head">+ <div class="seg" role="tablist" aria-label="设备面板">+ <button type="button" role="tab" id="tab-status" aria-selected="true" aria-controls="tp-status" data-action="dev-tab" data-tab="status">状态</button>+ <button type="button" role="tab" id="tab-apps" aria-selected="false" aria-controls="tp-apps" data-action="dev-tab" data-tab="apps">应用</button>+ <button type="button" role="tab" id="tab-elements" aria-selected="false" aria-controls="tp-elements" data-action="dev-tab" data-tab="elements">元素</button>+ </div>+ <button type="button" class="btn btn-ghost btn-icon dev-close" id="dev-close" data-action="dev-close" aria-label="隐藏设备面板" title="隐藏设备面板"><span class="ic" data-icon="panel"></span></button>+ </div>+ <div class="pane-body">+ <section class="tabpanel" id="tp-status" role="tabpanel" aria-labelledby="tab-status"></section>+ <section class="tabpanel" id="tp-apps" role="tabpanel" aria-labelledby="tab-apps" hidden>+ <div class="sec">+ <label class="label" for="url">打开链接</label>+ <div class="url-row">+ <input class="input" id="url" type="url" inputmode="url" autocomplete="off" placeholder="https://… 或 App 的 URL scheme">+ <button type="button" class="btn" data-action="open-url" id="url-btn">打开</button>+ </div>+ </div>+ <div class="sec">+ <div class="sec-head"><span class="sec-title">已安装的 App</span><span class="count" id="apps-count"></span><button type="button" class="btn btn-ghost btn-icon btn-sm" data-action="load-apps" aria-label="刷新 App 列表" title="刷新"><span class="ic" data-icon="refresh"></span></button></div>+ <div class="search"><label class="sr-only" for="app-q">搜索 App</label><input class="input" id="app-q" type="search" autocomplete="off" placeholder="按名称或 bundle id 搜索"><span class="search-ic" data-icon="search"></span></div>+ <label class="switch-row"><input type="checkbox" id="app-sys" checked><span>包含系统 App</span></label>+ <ul class="list" id="apps"></ul>+ </div>+ </section>+ <section class="tabpanel" id="tp-elements" role="tabpanel" aria-labelledby="tab-elements" hidden>+ <div class="sec">+ <div class="sec-head"><span class="sec-title">当前界面的元素</span><span class="count" id="el-count"></span></div>+ <div class="panel-tools">+ <div class="search"><label class="sr-only" for="el-q">筛选元素</label><input class="input" id="el-q" type="search" autocomplete="off" placeholder="按文字或类型筛选"><span class="search-ic" data-icon="search"></span></div>+ <button type="button" class="btn" data-action="load-elements" id="el-btn"><span class="ic" data-icon="refresh"></span><span>读取</span></button>+ </div>+ <ul class="list" id="elements"></ul>+ </div>+ <div class="sec">+ <label class="label" for="wait-q">等一段文字出现</label>+ <div class="url-row">+ <input class="input" id="wait-q" autocomplete="off" placeholder="例如:秒表">+ <button type="button" class="btn" data-action="wait-for" id="wait-btn">等待 5 秒</button>+ </div>+ <p class="wait-result" id="wait-result" role="status" hidden></p>+ </div>+ </section>+ </div>+ </aside></div>-<form class="row" id="type">- <input id="text" placeholder="Text to type on the phone" autocomplete="off">- <button type="submit">Type</button>- <button type="button" id="submit">Type + Return</button>-</form>-<div id="status">Click to tap, drag to swipe, hold to long-press.</div>++<dialog class="dialog" id="clear-dialog" aria-labelledby="clear-title" aria-describedby="clear-desc">+ <h2 id="clear-title">清空全部操作记录?</h2>+ <p id="clear-desc">只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。</p>+ <div class="dialog-actions">+ <button type="button" class="btn" id="clear-cancel">取消</button>+ <button type="button" class="btn btn-danger-solid" id="clear-confirm">清空</button>+ </div>+</dialog>++<dialog class="dialog" id="stop-dialog" aria-labelledby="stop-title" aria-describedby="stop-desc">+ <h2 id="stop-title">停止这个任务?</h2>+ <p id="stop-desc">AI 会立刻停下。已经在设备上做完的操作不会撤销。</p>+ <div class="dialog-actions">+ <button type="button" class="btn" id="stop-cancel">继续执行</button>+ <button type="button" class="btn btn-danger-solid" id="stop-confirm">停止任务</button>+ </div>+</dialog>+<script>-const img = document.getElementById('img'), screenEl = document.getElementById('screen');-const msg = document.getElementById('msg'), statusEl = document.getElementById('status');-let size = null; // screen size in points, portrait+'use strict';-function show(text, err) { statusEl.textContent = text; statusEl.classList.toggle('err', !!err); }+/* ================================================================+ * 语言:页面的文字中英两套。默认跟着 viewer(IPHONE_CONTROL_LANG,服务端写在 <html data-lang>),页面上切换后记在浏览器里。+ * 每个请求带上 X-Ictl-Lang,守护进程的回复和 AI 任务也用这种语言+ * ================================================================ */+const LANG = (() => {+ let v = null;+ try { v = localStorage.getItem('ictl.lang'); } catch { /* 预览环境可能禁用存储 */ }+ return v === 'en' || v === 'zh' ? v : document.documentElement.dataset.lang === 'en' ? 'en' : 'zh';+})();+document.documentElement.lang = LANG === 'en' ? 'en' : 'zh-CN';+const EN = {" · 演示数据":" · demo data"," 等":" and more","<div class=\"ph-kb\" data-type=\"Keyboard\">键盘</div>":"<div class=\"ph-kb\" data-type=\"Keyboard\">Keyboard</div>","<li class=\"empty-note\">打开这一页时会读取已安装的 App。</li>":"<li class=\"empty-note\">The installed apps are read when this tab opens.</li>","<li class=\"sr-only\">正在读取 App 列表…</li>":"<li class=\"sr-only\">Reading the app list…</li>","<li class=\"sr-only\">正在读取元素…</li>":"<li class=\"sr-only\">Reading elements…</li>","<option>没有可用的 AI</option>":"<option>No AI available</option>","<p class=\"empty-note\">正在连接 iphone-control 服务…</p>":"<p class=\"empty-note\">Connecting to the iphone-control service…</p>","<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>演示模式</span></span>":"<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>Demo</span></span>","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","放大(也可以按住 Ctrl/⌘ 滚动滚轮)":"Zoom in (or Ctrl/⌘ + scroll)","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","缩小(也可以按住 Ctrl/⌘ 滚动滚轮)":"Zoom out (or Ctrl/⌘ + scroll)","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。":"Run <code>iphone-control sign</code> to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 <code>iphone-control setup --reconfigure</code> 选「手机」,在设备上点「信任」。":"Run <code>iphone-control setup --reconfigure</code>, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA"};+/* 中文原文 → 当前语言 */+function tr(zh) { return LANG === 'en' ? (EN[zh] ?? zh) : zh; }+/* 静态标记里的文字和提示(aria-label、title、placeholder、alt)开始时译一次 */+(function translateStatic() {+ if (LANG !== 'en') return;+ document.title = tr(document.title);+ const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);+ for (let n = walk.nextNode(); n; n = walk.nextNode()) {+ const s = n.nodeValue.trim();+ if (s && EN[s] !== undefined) n.nodeValue = n.nodeValue.replace(s, EN[s]);+ }+ document.querySelectorAll('[aria-label],[title],[placeholder],[alt]').forEach(el => {+ for (const a of ['aria-label', 'title', 'placeholder', 'alt']) { const v = el.getAttribute(a); if (v && EN[v] !== undefined) el.setAttribute(a, EN[v]); }+ });+})();+document.getElementById('lang-btn').textContent = LANG === 'en' ? '中文' : 'EN';+document.getElementById('lang-btn').addEventListener('click', () => {+ try { localStorage.setItem('ictl.lang', LANG === 'en' ? 'zh' : 'en'); } catch { /* 存不了就只换这一次 */ }+ location.reload();+});+/* ================================================================+ * 接口(apps/iphone-control/src/viewer.rs、agent.rs)+ *+ * 画面与手动操作,都经守护进程,和 MCP 工具一样排队、自动解锁、只作用于这个页面跟着的设备:+ * GET /stream → WebDriverAgent 的 MJPEG 画面+ * GET /api/info → { width, height, udid, device, warning? }+ * POST /api/tap | swipe | long_press | type | button | launch_app | terminate_app | open_url | tap_element | wait_for+ * → { ok, message }+ *+ * 设备面板:+ * GET /api/daemon → { state, state_text, last_error?, device: { name, model, ios, udid }, auto_unlock }+ * GET /api/status → { wda_ready, locked, foreground, foreground_id, width, height, route: "wda"|"hid"|"none" }+ * GET /api/devices → { devices: [{ udid, name, model, ios, controlled }], fixed, auto }+ * POST /api/select { device } // UDID、设备名或 "auto"+ * GET /api/apps?system=1 → { apps: [{ name, bundle_id }] }+ * GET /api/elements?filter= → { elements: [{ type, label, x, y, width, height }] } // x、y 是左上角,单位点+ * state 取值:Absent | NeedsTrust | DeveloperModeOff | NeedsSigning | WdaStarting | NeedsUnlock | NeedsAutomationPin | Ready+ *+ * AI 任务:交给本机的 Claude Code 或 Codex,它只能用 iphone-control 的 MCP 工具;每一步都经 viewer 过一道闸,+ * 所以暂停、接管、确认在这里生效,和用哪个 agent 无关:+ * GET /api/agent/backends → { backends: [{ id, name, available }] }+ * POST /api/agent/tasks { prompt, agent } → { id }+ * GET /api/agent/tasks/{id}/events SSE:step | confirm | state | done(连上时先重放已有的事件)+ * step { id, thought?, tool?, args?, status: running|ok|error|waiting|rejected|stopped, ms?, result?, screenshot?, gesture? }+ * confirm { step, action, detail }+ * state { state: running|paused|takeover|waiting }+ * done { ok, stopped?, summary }+ * POST /api/agent/tasks/{id}/pause | resume | takeover | handback | stop+ * POST /api/agent/tasks/{id}/confirm { step, approve }+ * 任务进行中(没有接管时)服务端也拒绝手动操作,返回 409 和原因。+ *+ * 所有 POST 要求同源 Origin + JSON。打不开 /api/info 时(例如直接打开这个文件)进入演示模式,所有数据都在本地模拟。+ * ================================================================ */-async function post(action, body) {- try {- const r = await fetch('/api/' + action, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });- const v = await r.json();- show(v.message || (v.ok ? 'OK' : 'Failed'), !v.ok);- return v.ok;- } catch (e) { show(String(e), true); return false; }+const $ = (s, r = document) => r.querySelector(s);+const $$ = (s, r = document) => Array.from(r.querySelectorAll(s));+const sleep = ms => new Promise(res => setTimeout(res, ms));+const round1 = v => Math.round(v * 10) / 10;+const pad = n => String(n).padStart(2, '0');+const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+const hhmm = (d = new Date()) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;+const mmss = ms => { const s = Math.max(0, Math.floor(ms / 1000)); return `${pad(Math.floor(s / 60))}:${pad(s % 60)}`; };+const fmtSw = ms => { const cs = Math.floor(ms / 10); return `${pad(Math.floor(cs / 6000))}:${pad(Math.floor(cs / 100) % 60)}.${pad(cs % 100)}`; };++/* ---------- 图标:一套 24 网格描边图标 ---------- */+const ICONS = {+ home: '<path d="M3.5 10.5 12 3.5l8.5 7V20a1 1 0 0 1-1 1H15v-6H9v6H4.5a1 1 0 0 1-1-1z"/>',+ lock: '<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7.5a4 4 0 0 1 8 0V11"/>',+ voldown: '<path d="M11 5 6.5 9H3v6h3.5L11 19z"/><path d="M15.5 12h5"/>',+ volup: '<path d="M11 5 6.5 9H3v6h3.5L11 19z"/><path d="M15.5 12h5M18 9.5v5"/>',+ enter: '<path d="M19 5v7a3 3 0 0 1-3 3H6"/><path d="m10 11-4 4 4 4"/>',+ send: '<path d="M12 19V5"/><path d="m6 11 6-6 6 6"/>',+ trash: '<path d="M4.5 7h15M10 11v6M14 11v6"/><path d="M6.5 7l.8 11.2a2 2 0 0 0 2 1.8h5.4a2 2 0 0 0 2-1.8L17.5 7"/><path d="M9.5 7V5a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v2"/>',+ arrow: '<path d="M5 12h14"/><path d="m13 6 6 6-6 6"/>',+ chevron: '<path d="m6 9 6 6 6-6"/>',+ pause: '<path d="M9 5v14M15 5v14"/>',+ play: '<path d="M7.5 5v14l11-7z"/>',+ cursor: '<path d="M5 3.5 18.5 10l-6 1.8-2.3 6.2z"/>',+ stop: '<rect x="6" y="6" width="12" height="12" rx="1.5"/>',+ check: '<path d="m5 12.5 4.5 4.5L19 7.5"/>',+ x: '<path d="M6 6l12 12M18 6 6 18"/>',+ alert: '<path d="M12 4 2.5 20h19z"/><path d="M12 10v4.5M12 17.2v.3"/>',+ loader: '<path d="M12 3a9 9 0 1 1-9 9"/>',+ phone: '<rect x="7" y="2.5" width="10" height="19" rx="2.5"/><path d="M11 18.5h2"/>',+ tablet: '<rect x="4.5" y="2.5" width="15" height="19" rx="2.5"/><path d="M11 18.5h2"/>',+ refresh: '<path d="M20 12a8 8 0 1 1-2.4-5.7"/><path d="M20 4v5h-5"/>',+ info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v5.5M12 7.8v.2"/>',+ dot: '<circle cx="12" cy="12" r="4"/>',+ eye: '<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z"/><circle cx="12" cy="12" r="3"/>',+ tap: '<circle cx="12" cy="12" r="3"/><circle cx="12" cy="12" r="8"/>',+ keyboard: '<rect x="3" y="6" width="18" height="12" rx="2"/><path d="M7 10h.01M11 10h.01M15 10h.01M7.5 14h9"/>',+ grid: '<rect x="4" y="4" width="6.5" height="6.5" rx="1.5"/><rect x="13.5" y="4" width="6.5" height="6.5" rx="1.5"/><rect x="4" y="13.5" width="6.5" height="6.5" rx="1.5"/><rect x="13.5" y="13.5" width="6.5" height="6.5" rx="1.5"/>',+ link: '<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>',+ panel: '<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><path d="M14.5 4.5v15"/>',+ search: '<circle cx="11" cy="11" r="6.5"/><path d="m16 16 4 4"/>',+ zoomin: '<circle cx="11" cy="11" r="6.5"/><path d="m16 16 4 4M8.5 11h5M11 8.5v5"/>',+ zoomout: '<circle cx="11" cy="11" r="6.5"/><path d="m16 16 4 4M8.5 11h5"/>',+ bot: '<rect x="4.5" y="7.5" width="15" height="11" rx="3"/><path d="M12 3.5v4M9.5 12.5v1.5M14.5 12.5v1.5"/>'+};+function icon(name, extra = '') {+ return `<svg class="od-icon ${extra}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${ICONS[name] || ''}</svg>`;}+function hydrateIcons(root = document) { $$('[data-icon]', root).forEach(el => { el.innerHTML = icon(el.dataset.icon); }); }-async function loadInfo() {- try {- const v = await (await fetch('/api/info')).json();- // a size recorded for another device would put taps in the wrong place: better none- size = v.width && v.height ? { w: v.width, h: v.height } : null;- if (v.warning) show(v.warning, true);- } catch (e) { /* retried with the stream */ }+const TASK_STATUS = {+ idle: { label: tr('空闲'), tone: 'muted', icon: 'dot' },+ running: { label: tr('执行中'), tone: 'accent', icon: 'loader' },+ paused: { label: tr('已暂停'), tone: 'warn', icon: 'pause' },+ takeover: { label: tr('你在接管'), tone: 'user', icon: 'cursor' },+ waiting: { label: tr('等你确认'), tone: 'warn', icon: 'alert' },+ success: { label: tr('已完成'), tone: 'ok', icon: 'check' },+ failed: { label: tr('没有完成'), tone: 'danger', icon: 'x' },+ stopped: { label: tr('已停止'), tone: 'muted', icon: 'stop' }+};+const STEP_STATUS = {+ running: { label: tr('执行中'), tone: 'accent', icon: 'loader' },+ ok: { label: tr('完成'), tone: 'ok', icon: 'check' },+ error: { label: tr('失败'), tone: 'danger', icon: 'x' },+ waiting: { label: tr('等你确认'), tone: 'warn', icon: 'alert' },+ rejected: { label: tr('已拒绝'), tone: 'muted', icon: 'x' },+ stopped: { label: tr('已中止'), tone: 'muted', icon: 'stop' }+};+const ACTIVE = ['running', 'paused', 'takeover', 'waiting'];+const badge = st => `<span class="badge tone-${st.tone}">${icon(st.icon, st.icon === 'loader' ? 'spin' : '')}<span>${esc(st.label)}</span></span>`;++/* ---------- 元素与状态 ---------- */+const shell = $('#shell'), stage = $('#stage'), frame = $('#frame'), live = $('#live'), demoEl = $('#demo'), marks = $('#marks'), stageMsg = $('#stage-msg');+const statusEl = $('#status'), promptEl = $('#prompt'), promptErr = $('#prompt-error'), typeEl = $('#type-text');+const turnsEl = $('#turns'), stopDialog = $('#stop-dialog'), deviceEl = $('#device');++const S = {+ mode: 'detecting', // detecting | live | demo+ size: null, stream: 'connecting', rtt: null,+ view: 'agent', devOpen: false, devTab: 'status',+ daemon: null, dstatus: null, statusErr: '',+ devices: [], devicesErr: '',+ apps: [], appsState: 'idle', appsErr: '',+ elements: [], elState: 'idle', elErr: '',+ tasks: [], expanded: new Set(), seq: 0,+ udid: null, deviceName: '', switching: false, signing: false, // 本页显示的设备:画面、操作、面板都跟着它+ agents: [], agent: null // 本机可用的 AI(claude / codex)和选中的那个+};+const activeTask = () => S.tasks.find(t => ACTIVE.includes(t.status)) || null;+const guarded = () => { const t = activeTask(); return !!t && t.status !== 'takeover'; };++let statusTimer = 0;+function show(text, kind) {+ statusEl.textContent = text;+ statusEl.classList.toggle('err', kind === 'err');+ statusEl.classList.toggle('warn', kind === 'warn');+ clearTimeout(statusTimer);+ statusEl.classList.add('show');+ statusTimer = setTimeout(() => statusEl.classList.remove('show'), kind ? 6000 : 3500);}-function connect() {- msg.textContent = 'Connecting…'; msg.hidden = false;- img.src = '/stream?t=' + Date.now();-}-img.onload = () => {- msg.hidden = true;- // the frame's own shape: iPhone, iPad, portrait or landscape- screenEl.style.aspectRatio = img.naturalWidth + ' / ' + img.naturalHeight;- screenEl.classList.toggle('landscape', img.naturalWidth > img.naturalHeight);+/* ================================================================+ * 演示画面:模拟的 iPhone 界面+ * ================================================================ */+const APPS = [+ { id: 'clock', name: tr('时钟'), bundle: 'com.apple.mobiletimer', glyph: tr('时'), bg: '#1c1c1e', fg: '#fff' },+ { id: 'calendar', name: tr('日历'), bundle: 'com.apple.mobilecal', glyph: String(new Date().getDate()), bg: '#fff', fg: '#ff3b30' },+ { id: 'photos', name: tr('照片'), bundle: 'com.apple.mobileslideshow', glyph: tr('照'), bg: '#fff', fg: '#ff9500' },+ { id: 'camera', name: tr('相机'), bundle: 'com.apple.camera', glyph: tr('摄'), bg: '#8e8e93', fg: '#1c1c1e' },+ { id: 'messages', name: tr('信息'), bundle: 'com.apple.MobileSMS', glyph: tr('信'), bg: '#34c759', fg: '#fff' },+ { id: 'notes', name: tr('备忘录'), bundle: 'com.apple.mobilenotes', glyph: tr('记'), bg: '#ffcc00', fg: '#1c1c1e' },+ { id: 'weather', name: tr('天气'), bundle: 'com.apple.weather', glyph: tr('晴'), bg: '#2f80ed', fg: '#fff' },+ { id: 'maps', name: tr('地图'), bundle: 'com.apple.Maps', glyph: tr('图'), bg: '#7cc576', fg: '#1c1c1e' },+ { id: 'settings', name: tr('设置'), bundle: 'com.apple.Preferences', glyph: tr('设'), bg: '#8e8e93', fg: '#fff' },+ { id: 'appstore', name: 'App Store', bundle: 'com.apple.AppStore', glyph: 'A', bg: '#0a84ff', fg: '#fff' },+ { id: 'health', name: tr('健康'), bundle: 'com.apple.Health', glyph: tr('康'), bg: '#fff', fg: '#ff2d55' },+ { id: 'wallet', name: tr('钱包'), bundle: 'com.apple.Passbook', glyph: tr('钱'), bg: '#1c1c1e', fg: '#fff' }+];+const DOCK = [+ { id: 'phone', name: tr('电话'), bundle: 'com.apple.mobilephone', glyph: tr('话'), bg: '#34c759', fg: '#fff' },+ { id: 'safari', name: 'Safari', bundle: 'com.apple.mobilesafari', glyph: 'S', bg: '#fff', fg: '#0a84ff' },+ { id: 'mail', name: tr('邮件'), bundle: 'com.apple.mobilemail', glyph: tr('邮'), bg: '#2f80ed', fg: '#fff' },+ { id: 'music', name: tr('音乐'), bundle: 'com.apple.Music', glyph: tr('乐'), bg: '#fa2d48', fg: '#fff' }+];+const ALL_APPS = [...APPS, ...DOCK];+const appById = id => ALL_APPS.find(a => a.id === id);+const appByAny = s => ALL_APPS.find(a => a.name === s || a.bundle === s || a.id === s);+const CLOCK_TABS = [['world', tr('世界时钟')], ['alarm', tr('闹钟')], ['stopwatch', tr('秒表')], ['timer', tr('计时器')]];+const ALARMS = [{ time: '07:00', note: tr('工作日'), on: true }, { time: '08:30', note: tr('周末'), on: false }];+const SETTINGS = {+ root: { title: tr('设置'), back: null, groups: [[[tr('无线局域网'), tr('已连接'), 'set:none'], [tr('蓝牙'), tr('打开'), 'set:none']], [[tr('通用'), '', 'set:general'], [tr('显示与亮度'), '', 'set:none'], [tr('电池'), '', 'set:none'], [tr('隐私与安全性'), '', 'set:none']]] },+ general: { title: tr('通用'), back: [tr('设置'), 'set:root'], groups: [[[tr('关于本机'), '', 'set:about'], [tr('软件更新'), '', 'set:none']], [[tr('日期与时间'), '', 'set:none'], [tr('键盘'), '', 'set:none']]] },+ about: { title: tr('关于本机'), back: [tr('通用'), 'set:general'], groups: [[[tr('名称'), 'iPhone', null], [tr('iOS 版本'), '18.1', null], [tr('型号名称'), 'iPhone 15 Pro', null], [tr('容量'), '256 GB', null]]] }};-img.onerror = () => {- msg.textContent = 'No picture: the stream comes from WebDriverAgent, which is not running right now. Retrying…';- msg.hidden = false;- setTimeout(() => { loadInfo(); connect(); }, 3000);+const DEMO_DEVICES = [+ { udid: '00008130-001A2B3C4D5E001E', name: 'iPhone 15 Pro', model: 'iPhone16,1', ios: '18.1', kind: 'iphone', w: 393, h: 852 },+ { udid: '00008112-000C1D2E3F4A5B6C', name: tr('iPad mini(第 6 代)'), model: 'iPad14,1', ios: '18.1', kind: 'ipad', w: 1133, h: 744 } // iPad 默认横屏+];+let demoDev = DEMO_DEVICES[0];+const DW = () => demoDev.w, DH = () => demoDev.h;+const isPad = dev => dev && (dev.kind === 'ipad' || /^iPad/.test(dev.model || ''));+const osName = dev => isPad(dev) ? 'iPadOS' : 'iOS';++const D = {+ screen: 'home', clockTab: 'world', setPage: 'root', generic: '', genericSub: '',+ sw: { running: false, start: 0, acc: 0, laps: [] },+ chats: {+ [tr('妈妈')]: [{ me: false, text: tr('晚上回来吃饭吗?'), t: '18:12' }],+ [tr('王磊')]: [{ me: false, text: tr('明天的评审改到上午十点了'), t: '17:40' }],+ [tr('快递通知')]: [{ me: false, text: tr('您的包裹已到驿站,凭取件码取件'), t: tr('昨天') }]+ },+ chatWho: tr('妈妈'), draft: '', focused: false};+const swElapsed = () => D.sw.acc + (D.sw.running ? performance.now() - D.sw.start : 0);+function screenName() {+ switch (D.screen) {+ case 'home': return tr('主屏幕');+ case 'lock': return tr('锁定屏幕');+ case 'clock': return `${tr('时钟')} · ${CLOCK_TABS.find(t => t[0] === D.clockTab)[1]}`;+ case 'settings': return D.setPage === 'root' ? tr('设置') : `${tr('设置')} · ${SETTINGS[D.setPage].title}`;+ case 'messages': return tr('信息');+ case 'chat': return `${tr('与「')}${D.chatWho}${tr('」的对话')}`;+ default: return D.generic;+ }+}+function foreground() { return { home: tr('主屏幕'), lock: tr('主屏幕'), clock: tr('时钟'), settings: tr('设置'), messages: tr('信息'), chat: tr('信息') }[D.screen] || D.generic; }++function appTile(a, dock) {+ return `<div class="ph-app" data-act="app:${a.id}" data-label="${esc(a.name)}" data-type="Icon"><div class="ph-icon" style="background:${a.bg};color:${a.fg}">${esc(a.glyph)}</div>${dock ? '' : `<div class="ph-app-name">${esc(a.name)}</div>`}</div>`;+}+const tz = zone => new Date().toLocaleTimeString('zh-CN', { timeZone: zone, hour: '2-digit', minute: '2-digit', hour12: false });+function clockBody() {+ if (D.clockTab === 'stopwatch') {+ const run = D.sw.running;+ const laps = D.sw.laps.map((ms, i) => `<div class="ph-lap" data-label="${tr('计次')} ${i + 1}" data-type="Cell"><span>${tr('计次')} ${i + 1}</span><span>${fmtSw(ms)}</span></div>`).reverse().join('');+ return `<div class="ph-sw"><div class="sw-time" data-label="${tr('秒表时间')}" data-type="StaticText">${fmtSw(swElapsed())}</div>+ <div class="ph-sw-btns"><div class="ph-round gray" data-act="sw:${run ? 'lap' : 'reset'}" data-label="${run ? tr('计次') : tr('复位')}" data-type="Button">${run ? tr('计次') : tr('复位')}</div><div class="ph-round ${run ? 'red' : 'green'}" data-act="sw:toggle" data-label="${run ? tr('停止') : tr('启动')}" data-type="Button">${run ? tr('停止') : tr('启动')}</div></div>+ <div class="ph-laps">${laps}</div></div>`;+ }+ if (D.clockTab === 'world') {+ const rows = [[tr('北京'), 'Asia/Shanghai', tr('今天')], [tr('伦敦'), 'Europe/London', tr('今天,−8 小时')], [tr('纽约'), 'America/New_York', tr('今天,−13 小时')]];+ return `<div class="ph-title" data-label="${tr('世界时钟')}" data-type="StaticText">${tr('世界时钟')}</div>${rows.map(([c, z, sub]) => `<div class="ph-row" data-label="${c}" data-type="Cell"><div class="ph-row-main"><span class="ph-row-sub">${sub}</span><span>${c}</span></div><span class="ph-row-big">${tz(z)}</span></div>`).join('')}`;+ }+ if (D.clockTab === 'alarm') {+ return `<div class="ph-title" data-label="${tr('闹钟')}" data-type="StaticText">${tr('闹钟')}</div>${ALARMS.map(a => `<div class="ph-row${a.on ? '' : ' off'}" data-label="${tr('闹钟')} ${a.time} ${a.note} ${a.on ? tr('开') : tr('关')}" data-type="Cell"><div class="ph-row-main"><span class="ph-row-big">${a.time}</span><span class="ph-row-sub">${tr('闹钟,')}${a.note}</span></div><span class="ph-toggle${a.on ? ' on' : ''}"></span></div>`).join('')}`;+ }+ return `<div class="ph-title" data-label="${tr('计时器')}" data-type="StaticText">${tr('计时器')}</div><div class="sw-time" style="margin-top:80px">05:00</div>+ <div class="ph-sw-btns" style="margin-top:80px"><div class="ph-round gray" data-label="${tr('取消')}" data-type="Button">${tr('取消')}</div><div class="ph-round green" data-act="timer:start" data-label="${tr('启动')}" data-type="Button">${tr('启动')}</div></div>`;+}+function screenHtml() {+ switch (D.screen) {+ case 'home': return `<div class="ph-home"><div class="ph-grid">${APPS.map(a => appTile(a)).join('')}</div><div class="ph-dock">${DOCK.map(a => appTile(a, true)).join('')}</div></div>`;+ case 'lock': { const d = new Date(); return `<div class="ph-lock"><div class="ph-lock-date">${d.toLocaleDateString(LANG === 'en' ? 'en-US' : 'zh-CN', { month: 'long', day: 'numeric', weekday: 'long' })}</div><div class="ph-lock-time">${hhmm(d)}</div><div class="ph-lock-hint" data-label="${tr('向上轻扫以打开')}" data-type="StaticText">${tr('向上轻扫以打开')}</div></div>`; }+ case 'clock': return `<div class="ph-clock"><div class="ph-body">${clockBody()}</div><div class="ph-tabbar">${CLOCK_TABS.map(([k, l]) => `<div class="ph-tab${D.clockTab === k ? ' on' : ''}" data-act="tab:${k}" data-label="${l}" data-type="Button">${l}</div>`).join('')}</div></div>`;+ case 'settings': {+ const pg = SETTINGS[D.setPage];+ return `<div class="ph-set">${pg.back ? `<div class="ph-nav"><span class="ph-back" data-act="${pg.back[1]}" data-label="${pg.back[0]}" data-type="Button">‹ ${pg.back[0]}</span></div>` : ''}<div class="ph-title" data-label="${pg.title}" data-type="StaticText">${pg.title}</div>${pg.groups.map(g => `<div class="ph-group">${g.map(([l, v, act]) => `<div class="ph-cell"${act ? ` data-act="${act}"` : ''} data-label="${l}${v ? ' ' + v : ''}" data-type="Cell"><span>${l}</span><span class="ph-cell-v">${v}${act ? ' ›' : ''}</span></div>`).join('')}</div>`).join('')}</div>`;+ }+ case 'messages': return `<div class="ph-msgs"><div class="ph-title" data-label="${tr('信息')}" data-type="StaticText">${tr('信息')}</div><div class="ph-search" data-label="${tr('搜索')}" data-type="SearchField">${tr('搜索')}</div>${Object.entries(D.chats).map(([who, msgs]) => { const last = msgs[msgs.length - 1]; return `<div class="ph-thread" data-act="open-chat:${esc(who)}" data-label="${esc(who)}" data-type="Cell"><div class="ph-avatar">${esc(who[0])}</div><div class="ph-thread-text"><span class="ph-thread-name">${esc(who)}</span><span class="ph-thread-prev">${esc(last.text)}</span></div><span class="ph-thread-time">${esc(last.t)}</span></div>`; }).join('')}</div>`;+ case 'chat': {+ const msgs = D.chats[D.chatWho] || [], has = D.draft.length > 0;+ return `<div class="ph-chat"><div class="ph-chat-head"><span class="ph-back" data-act="chat:back" data-label="${tr('信息')}" data-type="Button">‹ ${tr('信息')}</span><div class="ph-chat-who"><div class="ph-avatar">${esc(D.chatWho[0])}</div><span>${esc(D.chatWho)}</span></div><span></span></div>+ <div class="ph-chat-body">${msgs.map(m => `<div class="ph-bubble ${m.me ? 'out' : 'in'}" data-label="${esc(m.text)}" data-type="StaticText">${esc(m.text)}</div>`).join('')}</div>+ <div class="ph-chat-input"><div class="ph-field${has ? '' : ' empty'}${D.focused ? ' focus' : ''}" data-act="chat:focus" data-label="${tr('信息')}" data-type="TextField">${has ? esc(D.draft) : tr('iMessage 信息')}</div><div class="ph-send${has ? '' : ' off'}" data-act="chat:send" data-label="${tr('发送')}" data-type="Button">${tr('发送')}</div></div>+ ${D.focused ? tr('<div class="ph-kb" data-type="Keyboard">键盘</div>') : ''}</div>`;+ }+ default: return `<div class="ph-generic"><div class="ph-title" data-label="${esc(D.generic)}" data-type="StaticText">${esc(D.generic)}</div><p class="ph-generic-sub">${esc(D.genericSub || tr('演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。'))}</p></div>`;+ }+}+function renderDemo() {+ const tone = ['messages', 'chat', 'generic'].includes(D.screen) ? ' ph--light' : D.screen === 'settings' ? ' ph--gray' : D.screen === 'clock' ? ' ph--black' : '';+ demoEl.className = 'ph' + tone + (demoDev.kind === 'ipad' ? ' ph--ipad' : '');+ demoEl.innerHTML = `<div class="ph-status"><span>${hhmm()}</span><span class="ph-sys"><span>5G</span><span class="ph-batt"></span></span></div><div class="ph-main">${screenHtml()}</div><div class="ph-ind"></div>`;+ if (S.mode === 'demo') {+ if (S.dstatus) { S.dstatus.foreground = foreground(); S.dstatus.locked = D.screen === 'lock'; }+ S.elements = []; S.elState = 'stale'; renderChips(); if (S.devTab === 'status') renderStatusPanel(); if (S.devTab === 'elements') renderElements(); }+}+function demoOpen(screen) { D.screen = screen; if (screen !== 'chat') D.focused = false; renderDemo(); }+function demoLaunch(a) {+ if (a.id === 'clock') { demoOpen('clock'); }+ else if (a.id === 'settings') { D.setPage = 'root'; demoOpen('settings'); }+ else if (a.id === 'messages') { demoOpen('messages'); }+ else { D.generic = a.name; D.genericSub = ''; demoOpen('generic'); }+ return `${tr('打开了「')}${a.name}${tr('」')}`;+}+function demoAct(act) {+ const i = act.indexOf(':'), k = act.slice(0, i), v = act.slice(i + 1);+ switch (k) {+ case 'app': return demoLaunch(appById(v));+ case 'tab': D.clockTab = v; renderDemo(); return `${tr('切到「')}${CLOCK_TABS.find(t => t[0] === v)[1]}${tr('」')}`;+ case 'set': if (v === 'none') return tr('演示模式没有模拟这一页'); D.setPage = v; renderDemo(); return `${tr('进入「')}${SETTINGS[v].title}${tr('」')}`;+ case 'sw':+ if (v === 'toggle') {+ if (D.sw.running) { D.sw.acc = swElapsed(); D.sw.running = false; renderDemo(); return tr('秒表已停止'); }+ D.sw.start = performance.now(); D.sw.running = true; renderDemo(); return tr('秒表开始计时');+ }+ if (v === 'lap') { D.sw.laps.push(swElapsed()); renderDemo(); return `${tr('记了第')} ${D.sw.laps.length} ${tr('次计次')}`; }+ D.sw = { running: false, start: 0, acc: 0, laps: [] }; renderDemo(); return tr('秒表已复位');+ case 'open-chat': D.chatWho = v; D.draft = ''; D.focused = false; demoOpen('chat'); return `${tr('打开了与「')}${v}${tr('」的对话')}`;+ case 'chat':+ if (v === 'back') { demoOpen('messages'); return tr('回到「信息」列表'); }+ if (v === 'focus') { D.focused = true; renderDemo(); return tr('输入框获得焦点,弹出了键盘'); }+ return demoSend();+ case 'timer': return tr('演示模式没有模拟计时器');+ }+ return tr('这里没有可点的东西');+}+function demoSend() {+ if (!D.draft) return tr('输入框是空的,没有发出任何内容');+ (D.chats[D.chatWho] ||= []).push({ me: true, text: D.draft, t: hhmm() });+ const sent = D.draft; D.draft = ''; renderDemo();+ return `${tr('已发送给「')}${D.chatWho}${tr('」:')}${sent}`;+}+function demoType(text, submit) {+ if (!(D.screen === 'chat' && D.focused)) return { ok: false, message: tr('没有弹出键盘:先在画面里点一下输入框。') };+ D.draft += text; renderDemo();+ return submit ? { ok: true, message: demoSend() } : { ok: true, message: `${tr('已输入「')}${text}${tr('」')}` };+}+function demoKey(key) {+ if (key === 'home') { const wasLocked = D.screen === 'lock'; demoOpen('home'); return wasLocked ? tr('已自动解锁,回到主屏幕') : tr('回到主屏幕'); }+ if (key === 'lock') { demoOpen('lock'); return tr('已锁屏'); }+ return key === 'volume_up' ? tr('音量加(演示画面没有变化)') : tr('音量减(演示画面没有变化)');+}+setInterval(() => {+ if (S.mode === 'demo' && D.screen === 'clock' && D.clockTab === 'stopwatch' && D.sw.running) {+ const el = $('.sw-time', demoEl); if (el) el.textContent = fmtSw(swElapsed());+ }+}, 50);+function demoElements() {+ const R = demoEl.getBoundingClientRect(), k = R.width / DW() || 0;+ return $$('[data-label]', demoEl).map(e => {+ const r = e.getBoundingClientRect();+ return { type: e.dataset.type || 'StaticText', label: e.dataset.label, x: k ? round1((r.left - R.left) / k) : 0, y: k ? round1((r.top - R.top) / k) : 0, width: k ? round1(r.width / k) : 0, height: k ? round1(r.height / k) : 0 };+ });+}-// Picture position → points on the phone, in the current orientation-function toPoints(ev) {- if (!size || !img.naturalWidth) return null;- const r = img.getBoundingClientRect();- const scale = Math.min(r.width / img.naturalWidth, r.height / img.naturalHeight);- const w = img.naturalWidth * scale, h = img.naturalHeight * scale;- const fx = (ev.clientX - r.left - (r.width - w) / 2) / w, fy = (ev.clientY - r.top - (r.height - h) / 2) / h;+/* ================================================================+ * 画面几何+ * ================================================================ */+function dims() {+ if (S.mode === 'demo') return { W: DW(), H: DH() };+ if (!S.size) return null;+ const land = live.naturalWidth > live.naturalHeight;+ return land ? { W: S.size.h, H: S.size.w } : { W: S.size.w, H: S.size.h };+}+function setRatio(w, h) {+ stage.style.aspectRatio = `${w} / ${h}`; frame.style.setProperty('--ratio', String(w / h));+ // 短边/长边 > 0.6 是 iPad(约 0.66–0.77),iPhone 约 0.46;横竖屏都适用+ frame.dataset.kind = Math.min(w, h) / Math.max(w, h) > 0.6 ? 'ipad' : 'iphone';+ applyZoom();+}+function applyDemoGeometry() {+ demoEl.style.setProperty('--dw', DW() + 'px'); demoEl.style.setProperty('--dh', DH() + 'px');+ setRatio(DW(), DH()); syncMarksBox();+ requestAnimationFrame(() => demoEl.style.setProperty('--k', String(stage.clientWidth / DW())));+}+function syncMarksBox() { const d = dims(); if (d) marks.setAttribute('viewBox', `0 0 ${d.W} ${d.H}`); }+function toPoints(cx, cy) {+ const d = dims(); if (!d) return null;+ const r = stage.getBoundingClientRect();+ let w = r.width, h = r.height, ox = 0, oy = 0;+ if (S.mode === 'live' && live.naturalWidth) {+ const sc = Math.min(r.width / live.naturalWidth, r.height / live.naturalHeight);+ w = live.naturalWidth * sc; h = live.naturalHeight * sc; ox = (r.width - w) / 2; oy = (r.height - h) / 2;+ }+ const fx = (cx - r.left - ox) / w, fy = (cy - r.top - oy) / h;if (fx < 0 || fx > 1 || fy < 0 || fy > 1) return null;- const land = img.naturalWidth > img.naturalHeight;- const W = land ? size.h : size.w, H = land ? size.w : size.h;- return { x: Math.round(fx * W * 10) / 10, y: Math.round(fy * H * 10) / 10 };+ return { x: round1(fx * d.W), y: round1(fy * d.H) };+}+new ResizeObserver(() => { demoEl.style.setProperty('--k', String(stage.clientWidth / DW())); }).observe(stage);++const SVGNS = 'http://www.w3.org/2000/svg';+function svgEl(tag, attrs) { const el = document.createElementNS(SVGNS, tag); for (const k in attrs) el.setAttribute(k, attrs[k]); return el; }+function shape(who, p, r) {+ return who === 'ai'+ ? svgEl('rect', { x: p.x - r, y: p.y - r, width: r * 2, height: r * 2, transform: `rotate(45 ${p.x} ${p.y})`, class: 'mk-shape' })+ : svgEl('circle', { cx: p.x, cy: p.y, r, class: 'mk-shape' });+}+function drawMark(kind, who, p, p2) {+ // 只标 AI 的操作;自己的操作看画面就够了+ if (!p || who !== 'ai') return;+ const g = svgEl('g', { class: `mk mk-${who}` });+ if (kind === 'swipe' && p2) {+ g.append(svgEl('line', { x1: p.x, y1: p.y, x2: p2.x, y2: p2.y, class: 'mk-line' }), svgEl('circle', { cx: p.x, cy: p.y, r: 7, class: 'mk-dot' }), shape(who, p2, 12));+ } else {+ g.append(shape(who, p, kind === 'long_press' ? 24 : 16));+ if (kind === 'long_press') g.append(svgEl('circle', { cx: p.x, cy: p.y, r: 36, class: 'mk-ring' }));+ }+ if (who === 'ai') { const t = svgEl('text', { x: p.x + 26, y: p.y - 22, class: 'mk-tag' }); t.textContent = 'AI'; g.append(t); }+ marks.append(g);+ setTimeout(() => g.classList.add('out'), 1000);+ setTimeout(() => g.remove(), 1250);+}+let hlRect = null;+function highlight(el) {+ hlRect?.remove(); hlRect = null;+ if (!el || !el.width) return;+ hlRect = svgEl('rect', { x: el.x, y: el.y, width: el.width, height: el.height, rx: 6, class: 'mk-hl' });+ marks.append(hlRect);+}++/* ================================================================+ * 请求+ * ================================================================ */+async function api(path, body) {+ const opt = body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) };+ opt.headers = { ...(opt.headers || {}), 'X-Ictl-Lang': LANG };+ // 操作只发给本页显示的那台;守护进程已换到别的设备时会被拒绝,不会点到用户没在看的手机上+ if (S.udid) opt.headers['X-Ictl-Device'] = S.udid;+ const r = await fetch(path, opt);+ if (!r.ok) {+ let msg = '';+ try { msg = (await r.json()).message || ''; } catch { /* 不是 JSON */ }+ if (r.status === 404 && !msg) msg = `viewer ${tr('没有这个接口(')}${path.split('?')[0]}${tr(')')}`;+ throw new Error(msg || `${tr('请求失败(')}HTTP ${r.status}${tr(')')}`);+ }+ return r.json();+}+async function act(path, body, quiet) {+ const t0 = performance.now();+ try {+ const v = await api(path, body);+ S.rtt = Math.round(performance.now() - t0); renderFeed();+ // 画面上的手势、底栏的按键和输入:成功时不弹提示,画面本身就是结果;失败照样提示+ if (!quiet || !v.ok) show(v.message || (v.ok ? tr('完成') : tr('失败')), v.ok ? null : 'err');+ if (v.ok) refreshStatusSoon();+ // 失败可能是设备已在别处换掉(操作带着旧 UDID 被拒):马上看一眼,换了就跟过去,不用等 10 秒的轮询+ else if (S.mode === 'live') loadInfo();+ return v;+ } catch (e) { show(String(e.message || e), 'err'); return { ok: false, message: String(e.message || e) }; }}+/* ================================================================+ * 手动操作+ * ================================================================ */let down = null;-img.addEventListener('pointerdown', ev => { img.setPointerCapture(ev.pointerId); down = { p: toPoints(ev), t: performance.now(), cx: ev.clientX, cy: ev.clientY }; });-img.addEventListener('pointerup', ev => {+function nudgeGuard() {+ const g = $('#guard');+ g.classList.remove('nudge'); void g.offsetWidth; g.classList.add('nudge');+ const t = activeTask();+ show(t && t.status === 'waiting' ? tr('AI 在等你确认一步操作,确认前画面保持锁定。') : tr('AI 正在操作这台设备。要自己操作,先点「接管」。'), 'warn');+}+/* 画面外的点夹到屏幕边上(拖动时手指不会离开屏幕) */+function clampPoint(cx, cy) {+ const d = dims(); if (!d) return null;+ const r = stage.getBoundingClientRect();+ let w = r.width, h = r.height, ox = 0, oy = 0;+ if (S.mode === 'live' && live.naturalWidth) {+ const sc = Math.min(r.width / live.naturalWidth, r.height / live.naturalHeight);+ w = live.naturalWidth * sc; h = live.naturalHeight * sc; ox = (r.width - w) / 2; oy = (r.height - h) / 2;+ }+ const fx = Math.min(1, Math.max(0, (cx - r.left - ox) / w)), fy = Math.min(1, Math.max(0, (cy - r.top - oy) / h));+ return { x: round1(fx * d.W), y: round1(fy * d.H) };+}+/* 页面上一个 CSS 像素对应设备上多少点 */+function pointsPerPx() {+ const d = dims(), r = stage.getBoundingClientRect();+ if (!d || !r.width) return 1;+ if (S.mode === 'live' && live.naturalWidth) return d.W / (live.naturalWidth * Math.min(r.width / live.naturalWidth, r.height / live.naturalHeight));+ return d.W / r.width;+}++/* ---------- 实时手指(iOS 27 起,经 CoreDevice HID):按下、移动、抬起各发一次,设备跟着鼠标动 ----------+ * 一次只有一个请求在路上:还没发出去的移动只留最新的一个,按下、抬起一定按顺序发。+ * 按住不动时每 100 毫秒再报一次当前位置,长按、拖动中途停顿都和真手指一样。 */+const T = { q: [], busy: false, on: false, last: null, keep: 0, warm: 0, fails: 0, legacy: false };+function touchSend(phase, p) {+ const tail = T.q[T.q.length - 1];+ if (phase === 'move' && tail && tail.phase === 'move') tail.p = p;+ else T.q.push({ phase, p });+ touchPump();+}+async function touchPump() {+ if (T.busy) return;+ T.busy = true;+ while (T.q.length) {+ const e = T.q.shift(), t0 = performance.now();+ let v;+ try { v = await api('/api/touch', { phase: e.phase, x: e.p ? e.p.x : 0, y: e.p ? e.p.y : 0 }); }+ catch (err) { v = { ok: false, message: String(err.message || err) }; }+ if (e.phase === 'down' || e.phase === 'up') { S.rtt = Math.round(performance.now() - t0); renderFeed(); }+ if (v.ok) { if (e.phase !== 'prepare') T.fails = 0; if (e.phase === 'up') refreshStatusSoon(); continue; }+ if (e.phase === 'prepare') continue;+ show(v.message || tr('操作失败'), 'err');+ if (e.phase === 'down') {+ // 这一下没按下去:丢掉它后面的移动和抬起,松开时改用整段手势+ while (T.q.length && T.q[0].phase !== 'down') T.q.shift();+ if (down) down.legacy = true;+ // 连着两次按不下去(HID 不可用),本页之后都用整段手势+ if (++T.fails >= 2) { S.liveTouch = false; renderFeed(); }+ }+ }+ T.busy = false;+}+function touchWarm() {+ if (!S.liveTouch || S.mode !== 'live' || guarded() || Date.now() - T.warm < 20000) return;+ T.warm = Date.now(); touchSend('prepare', null);+}+function fingerDown(p) { T.on = true; T.last = p; touchSend('down', p); clearInterval(T.keep); T.keep = setInterval(() => { if (T.on && T.last) touchSend('move', T.last); }, 100); }+function fingerMove(p) { if (!T.on) return; T.last = p; touchSend('move', p); }+function fingerUp(p) { if (!T.on) return; T.on = false; clearInterval(T.keep); touchSend('up', p || T.last); T.last = null; }+stage.addEventListener('pointerenter', touchWarm);++stage.addEventListener('pointerdown', ev => {+ if (ev.button !== 0 || S.mode === 'detecting' || ev.target.closest('button, a, code')) return;+ if (guarded()) { nudgeGuard(); return; }+ const p = toPoints(ev.clientX, ev.clientY);+ stage.setPointerCapture(ev.pointerId);+ wheelEnd(true);+ const liveFinger = S.mode === 'live' && S.liveTouch && !!p;+ down = { p, t: performance.now(), cx: ev.clientX, cy: ev.clientY, live: liveFinger, legacy: false };+ if (liveFinger) fingerDown(p);+});+/* 鼠标悬停时跟随光标的小圆点,标出将要点到的位置;触屏、画面外、AI 操作时不显示 */+let hoverDot = null;+function moveHoverDot(p, ev) {+ if (!p || ev.pointerType === 'touch' || guarded()) { hideHoverDot(); return; }+ if (!hoverDot) {+ hoverDot = svgEl('g', { class: 'hover-dot' });+ const scale = svgEl('g', { class: 'dot-scale' });+ scale.append(svgEl('circle', { cx: 0, cy: 0, r: 9, class: 'ring' }), svgEl('circle', { cx: 0, cy: 0, r: 2.5, class: 'core' }));+ hoverDot.append(scale);+ }+ if (!hoverDot.isConnected) marks.append(hoverDot);+ hoverDot.removeAttribute('hidden');+ hoverDot.setAttribute('transform', `translate(${p.x} ${p.y})`);+ hoverDot.classList.toggle('pressed', !!down);+}+function hideHoverDot() { hoverDot?.setAttribute('hidden', ''); }+stage.addEventListener('pointerleave', hideHoverDot);+stage.addEventListener('pointermove', ev => {+ const p = toPoints(ev.clientX, ev.clientY);+ moveHoverDot(p, ev);+ if (down && down.live && !down.legacy) fingerMove(p || clampPoint(ev.clientX, ev.clientY));+});+function endPointer(ev, cancelled) {if (!down) return;const start = down; down = null;- const end = toPoints(ev), held = (performance.now() - start.t) / 1000;- if (!start.p) { show(size ? 'Outside the screen' : 'Screen size not known yet', true); return; }- if (Math.hypot(ev.clientX - start.cx, ev.clientY - start.cy) < 8) {- if (held < 0.5) post('tap', start.p); else post('long_press', { ...start.p, seconds: held });- } else if (end) {- post('swipe', { x1: start.p.x, y1: start.p.y, x2: end.x, y2: end.y, seconds: Math.max(held, 0.1) });+ hoverDot?.classList.remove('pressed');+ if (start.live && !start.legacy) { fingerUp(clampPoint(ev.clientX, ev.clientY)); return; }+ if (cancelled) return;+ const end = toPoints(ev.clientX, ev.clientY), held = (performance.now() - start.t) / 1000;+ if (!start.p) { show(dims() ? tr('这个位置在画面外面') : tr('还不知道屏幕尺寸,稍后再试'), 'err'); return; }+ if (Math.hypot(ev.clientX - start.cx, ev.clientY - start.cy) < 8) userGesture(held < 0.5 ? 'tap' : 'long_press', start.p, null, held, start.cx, start.cy);+ else if (end) userGesture('swipe', start.p, end, held);+}+stage.addEventListener('pointerup', ev => endPointer(ev, false));+stage.addEventListener('pointercancel', ev => { endPointer(ev, true); hideHoverDot(); });++/* ---------- 滚轮、触控板:在画面上滚动就滚动设备上的页面,不用按住鼠标 ----------+ * 实时手指:在光标处按下(离屏幕边缘太近就挪进来,免得变成回主屏、下拉通知的手势),按滚动量移动,+ * 停下 160 毫秒后抬起;抬起前已经停住,不会再甩一段。触控板松手后的惯性滚动由浏览器继续发滚轮事件。+ * 手指走到屏幕边上就抬起、回到起点重新按下(按下会停住上一段的惯性)。+ * 没有实时手指时(iOS 27 以下)攒起滚动量,停下后发一次滑动。按住 Ctrl(触控板捏合)时不处理,留给缩放。 */+const W = { on: false, start: null, cur: null, pend: { x: 0, y: 0 }, idle: 0, raf: 0 };+const EDGE = 90;+function wheelSafe(p) { const d = dims(); return { x: Math.min(d.W - 30, Math.max(30, p.x)), y: Math.min(d.H - EDGE, Math.max(EDGE, p.y)) }; }+stage.addEventListener('wheel', ev => {+ if (S.mode !== 'live' || ev.ctrlKey || down) return;+ const p = toPoints(ev.clientX, ev.clientY);+ if (!p) return;+ ev.preventDefault();+ if (guarded()) { nudgeGuard(); return; }+ const d = dims(), k = ev.deltaMode === 1 ? 16 : ev.deltaMode === 2 ? d.H * 0.8 / pointsPerPx() : 1;+ W.pend.x += ev.deltaX * k * pointsPerPx(); W.pend.y += ev.deltaY * k * pointsPerPx();+ if (!W.on) {+ W.on = true; W.start = wheelSafe(p); W.cur = { ...W.start };+ if (S.liveTouch) { fingerDown(W.cur); W.raf = requestAnimationFrame(wheelStep); }+ }+ clearTimeout(W.idle); W.idle = setTimeout(() => wheelEnd(false), 160);+}, { passive: false });+function wheelStep() {+ if (!W.on) return;+ const d = dims();+ // 一格滚轮分几帧走完,像手指拖过去+ const step = a => (Math.abs(a) < 1 ? a : a * 0.45);+ const sx = step(W.pend.x), sy = step(W.pend.y);+ W.pend.x -= sx; W.pend.y -= sy;+ if (sx || sy) {+ const next = { x: round1(W.cur.x - sx), y: round1(W.cur.y - sy) };+ if (next.x < 20 || next.x > d.W - 20 || next.y < 40 || next.y > d.H - 40) {+ fingerUp(W.cur); W.cur = { ...W.start }; fingerDown(W.cur);+ } else { W.cur = next; fingerMove(W.cur); }+ }+ W.raf = requestAnimationFrame(wheelStep);+}+function wheelEnd(now) {+ if (!W.on) return;+ // 边移动边滑动时等手指把剩下的滚动量走完;整段手势(iOS 27 以下)没人消耗它,等下去就永远发不出滑动+ if (!now && S.liveTouch && (Math.abs(W.pend.x) > 1 || Math.abs(W.pend.y) > 1)) { W.idle = setTimeout(() => wheelEnd(false), 60); return; }+ clearTimeout(W.idle); cancelAnimationFrame(W.raf); W.on = false;+ if (S.liveTouch) { fingerUp(W.cur); }+ else {+ // 整段滑动:从光标处往滚动的反方向拖,最长 70% 屏高+ const d = dims(), max = d.H * 0.7;+ const dx = Math.max(-max, Math.min(max, W.pend.x)), dy = Math.max(-max, Math.min(max, W.pend.y));+ if (Math.abs(dx) > 4 || Math.abs(dy) > 4) {+ const a = W.start, b = { x: round1(Math.min(d.W - 10, Math.max(10, a.x - dx))), y: round1(Math.min(d.H - 10, Math.max(10, a.y - dy))) };+ act('/api/swipe', { x1: a.x, y1: a.y, x2: b.x, y2: b.y, seconds: 0.3 }, true);+ }+ }+ W.pend = { x: 0, y: 0 };+}++/* 整段手势(没有实时手指时):松开后一次发出 */+function userGesture(kind, p, p2, held, cx, cy) {+ if (S.mode === 'live') {+ if (kind === 'tap') act('/api/tap', p, true);+ else if (kind === 'long_press') act('/api/long_press', { ...p, seconds: round1(held) }, true);+ else act('/api/swipe', { x1: p.x, y1: p.y, x2: p2.x, y2: p2.y, seconds: Math.max(round1(held), 0.1) }, true);+ return;+ }+ const at = `(${p.x}, ${p.y})`;+ if (kind === 'tap') {+ const hit = document.elementsFromPoint(cx, cy).map(e => e.closest && e.closest('[data-act]')).find(e => e && demoEl.contains(e));+ show(`${tr('轻点')} ${at}${tr(':')}${hit ? demoAct(hit.dataset.act) : tr('这里没有可点的东西')}`);+ } else if (kind === 'long_press') show(`${tr('长按')} ${at} ${held.toFixed(1)} ${tr('秒:演示模式没有模拟长按菜单')}`);+ else {+ const up = p.y - p2.y;+ if ((D.screen === 'lock' && up > 80) || (p.y > DH() - 60 && up > 80)) show(`${tr('从')} ${at} ${tr('上滑:')}${demoKey('home')}`);+ else show(`${tr('滑动')} ${at} → (${p2.x}, ${p2.y})${tr(':演示画面不支持滚动')}`);}+}+$$('[data-key]').forEach(b => b.addEventListener('click', () => {+ if (guarded()) { nudgeGuard(); return; }+ if (S.mode === 'live') act('/api/button', { button: b.dataset.key }, true); else if (S.mode === 'demo') show(demoKey(b.dataset.key));+}));+async function typeText(submit) {+ if (guarded()) { nudgeGuard(); return; }+ const text = typeEl.value;+ if (!text && !submit) { show(tr('先输入要打到设备上的文字'), 'err'); typeEl.focus(); return; }+ if (S.mode === 'live') { if ((await act('/api/type', { text, submit }, true)).ok) typeEl.value = ''; return; }+ const r = demoType(text, submit);+ show(r.message, r.ok ? null : 'err');+ if (r.ok) typeEl.value = '';+}+$('#type-btn').addEventListener('click', () => typeText(false));+$('#type-submit').addEventListener('click', () => typeText(true));+typeEl.addEventListener('keydown', ev => { if (ev.key === 'Enter' && !ev.isComposing && ev.keyCode !== 229) { ev.preventDefault(); typeText(false); } });++/* ================================================================+ * 实时画面+ * ================================================================ */+function applyInfo(v) {+ S.size = v.width && v.height ? { w: v.width, h: v.height } : null;+ if (v.device) S.deviceName = v.device;+ if (v.udid && S.udid && v.udid.toLowerCase() !== S.udid.toLowerCase()) { onDeviceChanged(v); return; }+ if (v.udid) S.udid = v.udid;+ // 一旦改用整段手势(连着按不下去),本页之后不再改回来+ if (S.liveTouch !== false) S.liveTouch = !!v.live_touch;+ if (v.warning) show(v.warning, 'err');+}+/* 守护进程控制的设备变了(本页、别的页面、命令行切换,或拔掉后自动换了一台):画面和各面板都换过去 */+function onDeviceChanged(v) {+ const mine = S.switching;+ S.udid = v.udid;+ // 上一台设备上按着的手指、没走完的滚动,都不能带到新设备上+ W.on && (clearTimeout(W.idle), cancelAnimationFrame(W.raf), W.on = false);+ T.q.length = 0; T.on = false; T.last = null; clearInterval(T.keep); T.warm = 0; T.fails = 0; down = null;+ S.liveTouch = !!v.live_touch;+ S.dstatus = null; S.rtt = null;+ S.apps = []; S.appsState = 'idle'; S.elements = []; S.elState = 'idle'; appNames.map = null;+ highlight(null);+ connect(); loadDeviceState();+ if (S.devTab === 'apps') loadApps(); else if (S.devTab === 'elements') renderElements();+ const name = v.device || tr('另一台设备');+ show(mine ? `${tr('已切换到')} ${name}` : `${tr('设备已在别处切换到')} ${name}${tr(',画面已跟过去')}`);+}+function signButton(label) {+ return `<button type="button" data-action="sign"${S.signing ? ' disabled' : ''} class="btn btn-primary btn-sm">${esc(S.signing ? tr('正在签名安装…') : label)}</button>`;+}+/* 没有画面时,按守护进程的状态说清楚卡在哪、怎么办 */+function stageNote() {+ const d = S.daemon, name = d?.device?.name || S.deviceName || tr('设备');+ switch (d?.state) {+ case 'Absent': return esc(tr('没有连上设备:用数据线连上 iPhone,确认数据线能传数据。'));+ case 'NeedsTrust': case 'DeveloperModeOff':+ return `${esc(name)} ${esc(tr('还没设置好(配对、开发者模式)。在终端运行'))} <code>iphone-control setup --reconfigure</code>${esc(tr(',选「手机」。'))}`;+ case 'NeedsSigning':+ return d.signed_in+ ? `${esc(name)} ${esc(tr('上还没装 WebDriverAgent。'))}<br>${signButton(tr('签名并安装 WDA'))}`+ : `${esc(name)} ${esc(tr('上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行'))} <code>iphone-control setup --reconfigure</code>${esc(tr(',选「Apple ID」。'))}`;+ case 'WdaStarting':+ // 启动失败过就把原因摆出来(守护进程会自动重试),不要一直说「通常 10–60 秒」+ // 启动失败常见的一种是签名证书变了(给另一台设备重签时换了证书),重签这台就好;登录了 Apple ID 就给个按钮+ if (d.last_error) return `${esc(name)}${esc(tr(':WebDriverAgent 启动失败,会自动重试'))}<br><span class="stage-err">${esc(d.last_error)}</span>${d.signed_in ? `<br>${signButton(tr('重新签名并安装 WDA'))}` : ''}`;+ return `${esc(tr('正在'))} ${esc(name)} ${esc(tr('上启动 WebDriverAgent,通常 10–60 秒…'))}`;+ case 'NeedsUnlock': return esc(tr('设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。'));+ case 'NeedsAutomationPin': return esc(tr('设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。'));+ default: return esc(tr('没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…'));+ }+}+function showStageNote() {+ if (S.mode !== 'live' || S.stream !== 'error') return;+ const html = stageNote(); if (stageMsg.dataset.note !== html) { stageMsg.innerHTML = html; stageMsg.dataset.note = html; } // 不变就不重画,免得按钮丢了焦点+ stageMsg.hidden = false;+}+async function loadInfo() { try { applyInfo(await (await fetch('/api/info', { headers: { 'X-Ictl-Lang': LANG } })).json()); } catch { /* 跟着画面一起重试 */ } }+function connect() {+ S.stream = 'connecting'; stageMsg.textContent = tr('正在连接画面…'); delete stageMsg.dataset.note; stageMsg.hidden = false; live.hidden = false;+ live.src = `/stream?${S.udid ? `udid=${encodeURIComponent(S.udid)}&` : ''}t=${Date.now()}`; renderFeed(); renderChips();+}+live.addEventListener('load', () => {+ if (S.mode !== 'live') return;+ S.stream = 'ok'; stageMsg.hidden = true; live.style.visibility = ''; setRatio(live.naturalWidth, live.naturalHeight); syncMarksBox(); renderFeed(); renderChips();+});+live.addEventListener('error', () => {+ if (S.mode !== 'live') return;+ S.stream = 'error'; live.style.visibility = 'hidden'; showStageNote();+ renderFeed(); renderChips(); loadDeviceState();+ // 换了设备时 loadInfo 自己会重连;没换就重试这一台+ setTimeout(async () => { const u = S.udid; await loadInfo(); if (S.udid === u) connect(); }, 3000);});-img.addEventListener('pointercancel', () => { down = null; });+function renderFeed() {+ const dot = $('#feed-dot'), txt = $('#feed-text');+ dot.className = 'feed-dot';+ if (S.mode === 'demo') { txt.textContent = tr('演示画面 · 本地模拟'); return; }+ if (S.mode === 'detecting' || S.stream === 'connecting') { dot.classList.add('wait'); txt.textContent = tr('正在连接画面…'); return; }+ if (S.stream === 'error') { dot.classList.add('off'); txt.textContent = tr('画面断开 · 自动重试中'); return; }+ const route = S.dstatus?.route === 'hid' ? tr('HID 后备') : 'WDA';+ txt.textContent = `${tr('实时画面')} · ${route}${S.rtt != null ? ` · ${tr('操作往返')} ${S.rtt} ms` : ''}`;+}-document.querySelectorAll('[data-button]').forEach(b => b.addEventListener('click', () => post('button', { button: b.dataset.button })));+/* ================================================================+ * 设备:状态、切换+ * ================================================================ */+const CHECKS = [+ { name: tr('USB 连接'), fail: ['Absent'], hint: tr('用 USB 连上设备,确认数据线能传数据。') },+ { name: tr('信任这台电脑'), fail: ['NeedsTrust'], hint: tr('运行 <code>iphone-control setup --reconfigure</code> 选「手机」,在设备上点「信任」。') },+ { name: tr('开发者模式'), fail: ['DeveloperModeOff'], hint: tr('在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。') },+ { name: tr('WDA 已签名安装'), fail: ['NeedsSigning'], hint: tr('运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。'), action: 'sign' },+ { name: tr('WDA 运行中'), fail: ['WdaStarting', 'NeedsUnlock', 'NeedsAutomationPin'], hint: '' }+];+const STARTING_NO_HID = tr('正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。');+const STARTING_HINT = {+ WdaStarting: tr('正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。'),+ NeedsUnlock: tr('设备重启后还没解锁过,需要在设备上手动解锁一次。'),+ NeedsAutomationPin: tr('设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。')+};+let statusTimerId = 0;+function refreshStatusSoon() { clearTimeout(statusTimerId); statusTimerId = setTimeout(loadDeviceState, 600); }+async function loadDeviceState() {+ if (S.mode === 'demo') {+ S.daemon = { state: 'Ready', device: demoDev, auto_unlock: true };+ S.dstatus = { wda_ready: true, locked: D.screen === 'lock', foreground: foreground(), width: DW(), height: DH(), route: 'wda' };+ S.devices = DEMO_DEVICES.map(d => ({ ...d, controlled: d === demoDev })); S.statusErr = ''; S.devicesErr = '';+ } else if (S.mode === 'live') {+ const [d, s, l] = await Promise.allSettled([api('/api/daemon'), api('/api/status'), api('/api/devices')]);+ S.daemon = d.status === 'fulfilled' ? d.value : null;+ S.dstatus = s.status === 'fulfilled' ? s.value : null;+ S.statusErr = d.status === 'rejected' ? String(d.reason.message) : s.status === 'rejected' ? String(s.reason.message) : '';+ if (l.status === 'fulfilled') { S.devices = l.value.devices || []; S.devicesFixed = !!l.value.fixed; S.devicesErr = ''; } else { S.devices = []; S.devicesErr = String(l.reason.message); }+ }+ renderDevices(); renderChips(); renderFeed(); showStageNote(); if (S.devTab === 'status') renderStatusPanel();+}+/* 新设备上还没装 WDA:用已登录的 Apple ID 签名并安装,大约 1–2 分钟 */+async function signWda() {+ if (S.signing) return;+ S.signing = true; showStageNote(); if (S.devTab === 'status') renderStatusPanel();+ show(tr('正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…'));+ try { await act('/api/sign', {}); } finally { S.signing = false; await loadDeviceState(); }+}+function renderDevices() {+ if (S.mode === 'detecting') return;+ if (!S.devices.length) {+ deviceEl.innerHTML = `<option>${esc(S.mode === 'live' ? tr('当前设备') : tr('没有设备'))}</option>`; deviceEl.disabled = true;+ deviceEl.title = S.devicesErr || ''; return;+ }+ const cur = S.devices.find(d => d.controlled);+ deviceEl.innerHTML = S.devices.map(d => `<option value="${esc(d.udid)}"${d.controlled ? ' selected' : ''}>${esc(d.name)}${S.mode === 'demo' ? tr('(演示)') : ''}</option>`).join('')+ + `<option value="auto"${cur ? '' : ' selected'}>${tr('自动选择')}</option>`;+ deviceEl.disabled = guarded() || S.devicesFixed;+ deviceEl.title = S.devicesFixed ? tr('已用 IPHONE_UDID 固定设备,不能切换') : '';+}+deviceEl.addEventListener('change', async () => {+ const v = deviceEl.value;+ if (S.mode === 'demo') {+ const next = v === 'auto' ? demoDev : DEMO_DEVICES.find(d => d.udid === v);+ if (!next || next === demoDev) { show(v === 'auto' ? `${tr('已改为自动选择:继续控制')} ${demoDev.name}` : tr('已经在控制这台设备')); return; }+ demoDev = next; D.screen = 'home'; D.focused = false;+ applyDemoGeometry(); renderDemo(); await loadDeviceState();+ S.appsState = 'idle'; if (S.devTab === 'apps') loadApps();+ show(`${tr('已切换到')} ${next.name}${tr('(演示)')}`);+ return;+ }+ S.switching = true; deviceEl.disabled = true;+ try {+ const r = await act('/api/select', { device: v }, true);+ // /api/info 拿到新设备后 onDeviceChanged 换画面、清面板;选的就是当前这台时什么也不用换+ if (r.ok) { const u = S.udid; await loadInfo(); if (S.udid === u) show(r.message || tr('已经在控制这台设备')); }+ } finally { S.switching = false; await loadDeviceState(); }+});+function renderChips() {+ const c = $('#chips'), d = S.daemon, s = S.dstatus;+ if (S.mode === 'detecting') { c.innerHTML = ''; return; }+ const chips = [];+ const ready = d ? d.state === 'Ready' : S.stream === 'ok';+ chips.push(`<span class="chip"><span class="chip-dot ${ready ? 'ok' : d ? 'warn' : S.stream === 'error' ? 'off' : 'warn'}"></span><span>${ready ? tr('就绪') : d ? tr('未就绪') : S.stream === 'error' ? tr('画面断开') : tr('连接中')}</span></span>`);+ // 不知道锁没锁(WDA 没起来、又没有 HID)时不显示+ if (s && s.locked != null) {+ chips.push(`<span class="chip"><span class="k">${tr('屏幕')}</span><span>${s.locked ? tr('已锁定') : tr('未锁定')}</span></span>`);+ }+ if (S.mode === 'demo') chips.push(tr('<span class="chip"><span class="chip-dot warn"></span><span>演示模式</span></span>'));+ c.innerHTML = chips.join('');+}+function renderStatusPanel() {+ const p = $('#tp-status'), d = S.daemon, s = S.dstatus;+ if (S.mode === 'detecting') { p.innerHTML = tr('<p class="empty-note">正在连接 iphone-control 服务…</p>'); return; }+ const dev = d?.device || {};+ const facts = [+ [tr('前台 App'), s?.foreground || '—'], [tr('屏幕'), s && s.locked != null ? (s.locked ? tr('已锁定') : tr('未锁定')) : '—'],+ [tr('操作通道'), s ? (s.route === 'hid' ? tr('HID 后备') : s.route === 'none' ? tr('不可用') : 'WDA') : '—'], [tr('屏幕尺寸'), s?.width ? `${s.width}×${s.height} pt` : S.size ? `${S.size.w}×${S.size.h} pt` : '—'],+ [tr('自动解锁'), d ? (d.auto_unlock ? tr('已设置密码') : tr('未设置')) : '—'], [tr('系统'), dev.ios ? `${osName(dev)} ${dev.ios}` : '—']+ ];+ let checks = '';+ if (d) {+ const failAt = d.state === 'Ready' ? -1 : CHECKS.findIndex(c => c.fail.includes(d.state));+ checks = CHECKS.map((c, i) => {+ const st = failAt === -1 || i < failAt ? 'ok' : i === failAt ? (d.state === 'WdaStarting' ? 'busy' : 'bad') : 'pending';+ // iOS 27 以下没有 HID 后备,别说「改走 HID」+ const hint = i === failAt ? (c.hint || (d.state === 'WdaStarting' && S.dstatus?.route === 'none' ? STARTING_NO_HID : STARTING_HINT[d.state]) || '') : '';+ const dot = st === 'ok' ? `<span class="check-dot tone-ok">${icon('check')}</span>` : st === 'busy' ? `<span class="check-dot tone-accent">${icon('loader', 'spin')}</span>` : st === 'bad' ? `<span class="check-dot tone-warn">${icon('alert')}</span>` : '<span class="check-dot pending"></span>';+ const label = st === 'ok' ? tr('已完成') : st === 'busy' ? tr('进行中') : st === 'bad' ? tr('需要处理') : tr('等待前一步');+ return `<li class="check${st === 'pending' ? ' pending' : ''}"><div class="check-rail">${dot}<span class="check-line"></span></div>+ <div class="check-body"><span class="check-name">${c.name}<span class="sr-only">${tr(':')}${label}</span></span>${hint ? `<span class="check-hint">${hint}</span>` : ''}${i === failAt && c.action === 'sign' && d.signed_in ? `<span><button type="button" class="btn btn-sm" data-action="sign"${S.signing ? ' disabled' : ''}>${esc(S.signing ? tr('正在签名安装…') : tr('签名并安装 WDA'))}</button></span>` : ''}${i === failAt && d.last_error ? `<span class="check-err">${esc(d.last_error)}</span>` : ''}</div></li>`;+ }).join('');+ }+ p.innerHTML = `+ <div class="device-card"><span class="device-ic">${icon(isPad(dev) || frame.dataset.kind === 'ipad' ? 'tablet' : 'phone')}</span>+ <div class="od-field"><span class="device-name od-truncate">${esc(dev.name || (S.mode === 'live' ? tr('已连接的设备') : '—'))}</span><span class="device-sub od-truncate">${esc([dev.model, dev.ios && `${osName(dev)} ${dev.ios}`].filter(Boolean).join(' · ') || tr('型号未知'))}${S.mode === 'demo' ? tr(' · 演示数据') : ''}</span></div></div>+ <div class="facts">${facts.map(([k, v]) => `<div class="fact"><span class="fact-k">${k}</span><span class="fact-v">${esc(v)}</span></div>`).join('')}+ <div class="fact" style="grid-column:1/-1"><span class="fact-k">UDID</span><span class="fact-v mono">${esc(dev.udid || '—')}</span></div></div>+ <div class="sec"><div class="sec-head"><span class="sec-title">${tr('就绪检查')}</span>${d ? badge(d.state === 'Ready' ? { label: tr('全部就绪'), tone: 'ok', icon: 'check' } : { label: tr('未就绪'), tone: 'warn', icon: 'alert' }) : ''}</div>+ ${d ? `<ol class="checks">${checks}</ol>` : `<p class="empty-note${S.statusErr ? ' err' : ''}">${esc(S.statusErr || tr('还没有拿到守护进程状态。'))}</p>`}</div>`;+}-const text = document.getElementById('text');-async function typeText(submit) {- if (!text.value && !submit) return;- if (await post('type', { text: text.value, submit })) text.value = '';+/* ================================================================+ * 应用+ * ================================================================ */+async function loadApps() {+ S.appsState = 'loading'; renderApps();+ const sys = $('#app-sys').checked;+ try {+ if (S.mode === 'demo') { await sleep(350); S.apps = sys ? ALL_APPS.map(a => ({ name: a.name, bundle_id: a.bundle })) : []; }+ else S.apps = (await api(`/api/apps?system=${sys ? 1 : 0}`)).apps || [];+ S.appsState = 'ok';+ } catch (e) { S.appsState = 'error'; S.appsErr = String(e.message || e); }+ renderApps();+}+function renderApps() {+ const ul = $('#apps'), q = $('#app-q').value.trim().toLowerCase(), lock = guarded();+ const list = S.apps.filter(a => !q || a.name.toLowerCase().includes(q) || a.bundle_id.toLowerCase().includes(q));+ $('#apps-count').textContent = S.appsState === 'ok' ? `${list.length} ${tr('个')}${S.mode === 'demo' ? tr(' · 演示数据') : ''}` : '';+ if (S.appsState === 'loading') { ul.innerHTML = tr('<li class="sr-only">正在读取 App 列表…</li>') + '<li class="skel-row" aria-hidden="true"><span class="skel tile"></span><span class="skel-lines"><span class="skel l1"></span><span class="skel l2"></span></span></li>'.repeat(6); return; }+ if (S.appsState === 'error') { ul.innerHTML = `<li class="empty-note err">${esc(S.appsErr)}</li>`; return; }+ if (S.appsState !== 'ok') { ul.innerHTML = tr('<li class="empty-note">打开这一页时会读取已安装的 App。</li>'); return; }+ if (!list.length) { ul.innerHTML = `<li class="empty-note">${q ? `${tr('没有名称或 bundle id 含「')}${esc(q)}${tr('」的 App。')}` : $('#app-sys').checked ? tr('没有读到 App。') : tr('没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。')}</li>`; return; }+ ul.innerHTML = list.map(a => {+ const meta = appByAny(a.bundle_id);+ const tile = meta ? `style="background:${meta.bg};color:${meta.fg}"` : 'style="background:var(--sunken);color:var(--text-2)"';+ return `<li class="app-row"><span class="app-tile" ${tile} aria-hidden="true">${esc(meta ? meta.glyph : a.name.slice(0, 1))}</span>+ <span class="app-text"><span class="app-name od-truncate">${esc(a.name)}</span><span class="app-id od-truncate">${esc(a.bundle_id)}</span></span>+ <span class="app-actions"><button type="button" class="btn btn-sm" data-action="launch" data-app="${esc(a.bundle_id)}" data-name="${esc(a.name)}" ${lock ? 'disabled' : ''}>${tr('启动')}</button>+ <button type="button" class="btn btn-ghost btn-icon btn-sm" data-action="terminate" data-app="${esc(a.bundle_id)}" data-name="${esc(a.name)}" aria-label="${tr('结束「')}${esc(a.name)}${tr('」')}" title="${tr('结束')}" ${lock ? 'disabled' : ''}>${icon('x')}</button></span></li>`;+ }).join('');+}+$('#app-q').addEventListener('input', renderApps);+$('#app-sys').addEventListener('change', loadApps);+async function launchApp(bundle, name) {+ if (guarded()) { nudgeGuard(); return; }+ if (S.mode === 'live') return act('/api/launch_app', { app: bundle });+ show(demoLaunch(appByAny(bundle) || { id: bundle, name }));+}+async function terminateApp(bundle, name) {+ if (guarded()) { nudgeGuard(); return; }+ if (S.mode === 'live') return act('/api/terminate_app', { app: bundle });+ if (foreground() === name) demoOpen('home');+ show(`${tr('已结束「')}${name}${tr('」')}`);+}+async function openUrl() {+ if (guarded()) { nudgeGuard(); return; }+ const inp = $('#url'), url = inp.value.trim();+ if (!url) { show(tr('先填要打开的链接'), 'err'); inp.focus(); return; }+ if (S.mode === 'live') { if ((await act('/api/open_url', { url })).ok) inp.value = ''; return; }+ if (/^https?:\/\//i.test(url)) { D.generic = 'Safari'; D.genericSub = `${tr('正在打开')} ${url}${tr('(演示画面不加载网页)')}`; demoOpen('generic'); show(`${tr('已用 Safari 打开')} ${url}`); inp.value = ''; }+ else show(tr('演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试'), 'err');+}+$('#url').addEventListener('keydown', ev => { if (ev.key === 'Enter' && !ev.isComposing) { ev.preventDefault(); openUrl(); } });++/* ================================================================+ * 元素+ * ================================================================ */+async function loadElements() {+ S.elState = 'loading'; renderElements();+ try {+ if (S.mode === 'demo') { await sleep(300); S.elements = demoElements(); }+ else S.elements = (await api('/api/elements?filter=')).elements || [];+ S.elState = 'ok';+ } catch (e) { S.elState = 'error'; S.elErr = String(e.message || e); }+ renderElements();+}+function renderElements() {+ const ul = $('#elements'), q = $('#el-q').value.trim().toLowerCase(), lock = guarded();+ const list = S.elements.map((e, i) => ({ ...e, i })).filter(e => !q || e.label.toLowerCase().includes(q) || e.type.toLowerCase().includes(q));+ $('#el-count').textContent = S.elState === 'ok' ? `${list.length} ${tr('个')}${S.mode === 'demo' ? tr(' · 演示数据') : ''}` : '';+ if (S.elState === 'loading') { ul.innerHTML = tr('<li class="sr-only">正在读取元素…</li>') + '<li class="skel-row no-tile" aria-hidden="true"><span class="skel-lines"><span class="skel l1"></span><span class="skel l2"></span></span></li>'.repeat(6); return; }+ if (S.elState === 'error') { ul.innerHTML = `<li class="empty-note err">${esc(S.elErr)}</li>`; return; }+ if (S.elState === 'stale' || S.elState === 'idle') { ul.innerHTML = `<li class="empty-note">${S.elState === 'stale' ? tr('界面变了,') : ''}${tr('点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。')}</li>`; return; }+ if (!list.length) { ul.innerHTML = `<li class="empty-note">${q ? `${tr('没有含「')}${esc(q)}${tr('」的元素。')}` : tr('当前界面没有带文字的元素。')}</li>`; return; }+ ul.innerHTML = list.map(e => `<li class="el-row" data-el="${e.i}">+ <span class="el-text"><span class="el-label od-truncate">${esc(e.label)}</span><span class="el-meta od-truncate">${esc(e.type)} · ${Math.round(e.x + e.width / 2)}, ${Math.round(e.y + e.height / 2)}</span></span>+ <span class="el-actions"><button type="button" class="btn btn-sm" data-action="tap-el" data-el="${e.i}" ${lock ? 'disabled' : ''}>${tr('点它')}</button></span></li>`).join('');+}+$('#el-q').addEventListener('input', renderElements);+const elList = $('#elements');+elList.addEventListener('pointerover', ev => { const row = ev.target.closest('[data-el]'); if (row) highlight(S.elements[+row.dataset.el]); });+elList.addEventListener('pointerleave', () => highlight(null));+elList.addEventListener('focusin', ev => { const row = ev.target.closest('[data-el]'); if (row) highlight(S.elements[+row.dataset.el]); });+elList.addEventListener('focusout', () => highlight(null));+async function tapElement(i) {+ if (guarded()) { nudgeGuard(); return; }+ const e = S.elements[i]; if (!e) return;+ const same = S.elements.slice(0, i).filter(x => x.label === e.label).length;+ const p = { x: round1(e.x + e.width / 2), y: round1(e.y + e.height / 2) };+ highlight(null);+ if (S.mode === 'live') { drawMark('tap', 'user', p); await act('/api/tap_element', { text: e.label, index: same }); }+ else {+ const el = $$('[data-label]', demoEl).filter(x => x.dataset.label === e.label)[same];+ drawMark('tap', 'user', p);+ show(`${tr('按名字点「')}${e.label}${tr('」:')}${el && el.dataset.act ? demoAct(el.dataset.act) : tr('它不是可点的控件,界面没有变化')}`);+ }+ S.elState = 'stale'; renderElements();+}+async function waitFor() {+ const inp = $('#wait-q'), text = inp.value.trim(), out = $('#wait-result'), btn = $('#wait-btn');+ if (!text) { inp.focus(); out.hidden = false; out.className = 'wait-result t-danger'; out.textContent = tr('先填要等的文字。'); return; }+ btn.disabled = true; btn.textContent = tr('等待中…'); out.hidden = false; out.className = 'wait-result t-muted'; out.textContent = `${tr('等「')}${text}${tr('」出现,最多 5 秒')}…`;+ let ok = false, msg = '';+ try {+ if (S.mode === 'live') { const v = await api('/api/wait_for', { text, timeout: 5 }); ok = !!v.ok; msg = v.message || ''; }+ else {+ const t0 = Date.now();+ while (Date.now() - t0 < 5000) { if (demoElements().some(e => e.label.includes(text) && e.type !== 'TextField')) { ok = true; break; } await sleep(200); }+ msg = ok ? `${tr('「')}${text}${tr('」已经出现(')}${((Date.now() - t0) / 1000).toFixed(1)} ${tr('秒)')}` : `5 ${tr('秒内没有出现「')}${text}${tr('」')}`;+ }+ } catch (e) { msg = String(e.message || e); }+ out.className = `wait-result ${ok ? 't-ok' : 't-danger'}`; out.textContent = msg;+ btn.disabled = false; btn.textContent = tr('等待 5 秒');+}+$('#wait-q').addEventListener('keydown', ev => { if (ev.key === 'Enter' && !ev.isComposing) { ev.preventDefault(); waitFor(); } });++function setDevTab(tab) {+ S.devTab = tab;+ ['status', 'apps', 'elements'].forEach(t => {+ $(`#tab-${t}`).setAttribute('aria-selected', String(t === tab));+ $(`#tp-${t}`).hidden = t !== tab;+ });+ if (tab === 'status') renderStatusPanel();+ if (tab === 'apps' && S.appsState === 'idle' && S.mode !== 'detecting') loadApps(); else if (tab === 'apps') renderApps();+ if (tab === 'elements') renderElements();+}++/* ================================================================+ * AI 任务:演示脚本+ * ================================================================ */+const STOP = Symbol('stop');+function snapshot() {+ const c = demoEl.cloneNode(true);+ c.removeAttribute('id'); c.removeAttribute('hidden'); c.setAttribute('aria-hidden', 'true');+ c.style.setProperty('--k', String(64 / DW()));+ return c.outerHTML;+}+function elPoint(sel) {+ const el = demoEl.querySelector(sel); if (!el) return { el: null, p: null };+ const R = demoEl.getBoundingClientRect(); if (!R.width) return { el, p: null };+ const r = el.getBoundingClientRect(), k = R.width / DW();+ return { el, p: { x: round1((r.left - R.left + r.width / 2) / k), y: round1((r.top - R.top + r.height / 2) / k) } };+}+function aiTap(sel, what) {+ const { el, p } = elPoint(sel);+ if (!el) return { error: true, text: `${tr('界面上没找到「')}${what}${tr('」。界面可能已经变了,需要重新截图判断。')}` };+ drawMark('tap', 'ai', p);+ const msg = demoAct(el.dataset.act);+ return { text: p ? `${tr('点了')} (${p.x}, ${p.y})${tr(':')}${msg}` : msg };+}+const shot = () => ({ text: `${tr('当前在「')}${screenName()}${tr('」')}`, thumb: true });+const labelsMatching = f => $$('[data-label]', demoEl).map(e => e.dataset.label).filter(l => l.includes(f));+function classify(prompt) {+ if (/系统版本|iOS 版本|关于本机|version|about/i.test(prompt)) return 'version';+ if (/闹钟|alarm/i.test(prompt)) return 'alarms';+ if (/秒表|计时|stopwatch|timer/i.test(prompt)) return 'stopwatch';+ if (/主屏幕|桌面|home/i.test(prompt)) return 'home';+ if (/发|信息|短信|消息|告诉|message|text|tell|send/i.test(prompt)) return 'message';+ if (/截图|看看|有什么|screen|look/i.test(prompt)) return 'look';+ return 'unknown';+}+function buildScript(task) {+ const look = { thought: tr('先看一下设备现在的界面。'), tool: 'iphone_screenshot', args: {}, exec: shot };+ const launch = (name, fn) => ({ thought: `${tr('打开「')}${name}${tr('」。')}`, tool: 'iphone_launch_app', args: { app: name }, exec: () => { fn(); return { text: `${tr('「')}${name}${tr('」已在前台')}` }; }, think: 900 });+ switch (classify(task.prompt)) {+ case 'version': return { steps: [+ look, launch(tr('设置'), () => { D.setPage = 'root'; demoOpen('settings'); }),+ { thought: tr('系统版本在「通用 › 关于本机」里,先点「通用」。'), tool: 'iphone_tap_element', args: { text: tr('通用') }, exec: () => aiTap('[data-act="set:general"]', tr('通用')) },+ { thought: tr('再点「关于本机」。'), tool: 'iphone_tap_element', args: { text: tr('关于本机') }, exec: () => aiTap('[data-act="set:about"]', tr('关于本机')) },+ { thought: tr('读出「iOS 版本」这一行。'), tool: 'iphone_list_elements', args: { filter: tr('iOS 版本') }, exec: () => { const l = labelsMatching(tr('iOS 版本')); return l.length ? { text: l[0], thumb: true } : { error: true, text: tr('没找到「iOS 版本」') }; } }+ ], summary: () => tr('这台设备的系统版本是 iOS 18.1。') };+ case 'alarms': return { steps: [+ look, launch(tr('时钟'), () => demoOpen('clock')),+ { thought: tr('底部有「闹钟」标签,点它。'), tool: 'iphone_tap_element', args: { text: tr('闹钟') }, exec: () => aiTap('[data-act="tab:alarm"]', tr('闹钟')) },+ { thought: tr('读一下列表里的闹钟。'), tool: 'iphone_list_elements', args: { filter: tr('闹钟') }, exec: () => { const n = labelsMatching(tr('闹钟 ')).length; return n ? { text: `${tr('找到')} ${n} ${tr('个闹钟')}`, thumb: true } : { error: true, text: tr('列表里没有闹钟') }; } }+ ], summary: () => `${tr('一共')} ${ALARMS.length} ${tr('个闹钟:')}${ALARMS.map(a => `${a.time} ${a.note}${tr('(')}${a.on ? tr('开') : tr('关')}${tr(')')}`).join(tr(','))}${tr('。')}` };+ case 'stopwatch': return { steps: [+ look, launch(tr('时钟'), () => demoOpen('clock')),+ { thought: tr('点底部的「秒表」。'), tool: 'iphone_tap_element', args: { text: tr('秒表') }, exec: () => aiTap('[data-act="tab:stopwatch"]', tr('秒表')) },+ { thought: tr('点「启动」。'), tool: 'iphone_tap_element', args: { text: tr('启动') }, exec: () => D.sw.running ? { text: tr('秒表已经在计时') } : aiTap('[data-act="sw:toggle"]', tr('启动')) },+ { thought: tr('确认秒表在走。'), tool: 'iphone_screenshot', args: {}, exec: () => D.sw.running ? { text: `${tr('秒表正在计时:')}${fmtSw(swElapsed())}`, thumb: true } : { error: true, text: tr('秒表没有在计时'), thumb: true }, think: 1200 }+ ], summary: () => tr('秒表已经开始计时。') };+ case 'home': return { steps: [+ { thought: tr('按一下主屏幕键。'), tool: 'iphone_press_button', args: { button: 'home' }, exec: () => ({ text: demoKey('home') }) },+ { thought: tr('确认已经在主屏幕。'), tool: 'iphone_screenshot', args: {}, exec: () => D.screen === 'home' ? shot() : { error: true, text: `${tr('还停在「')}${screenName()}${tr('」')}`, thumb: true } }+ ], summary: () => tr('已回到主屏幕。') };+ case 'message': {+ const who = Object.keys(D.chats).find(n => task.prompt.includes(n)) || tr('妈妈');+ const m = task.prompt.match(/[::](.+)$/) || task.prompt.match(/说(.+)$/) || task.prompt.match(/\bsay(?:ing)?\s+(.+)$/i);+ const text = (m ? m[1] : tr('我晚点到')).trim() || tr('我晚点到');+ return { steps: [+ look, launch(tr('信息'), () => demoOpen('messages')),+ { thought: `${tr('点开和「')}${who}${tr('」的对话。')}`, tool: 'iphone_tap_element', args: { text: who }, exec: () => aiTap(`[data-act="open-chat:${who}"]`, who) },+ { thought: tr('点一下底部的输入框。'), tool: 'iphone_tap', argsFrom: () => elPoint('[data-act="chat:focus"]').p || {}, exec: () => aiTap('[data-act="chat:focus"]', tr('输入框')) },+ { thought: tr('输入要发的内容。'), tool: 'iphone_type_text', args: { text }, exec: () => { const r = demoType(text, false); return r.ok ? { text: r.message } : { error: true, text: r.message }; } },+ { thought: tr('内容填好了。发消息需要你先确认。'), tool: 'iphone_tap_element', args: { text: tr('发送') }, confirm: { action: tr('发送消息'), detail: `${tr('发给「')}${who}${tr('」:')}${text}` }, rejectSummary: tr('你拒绝了发送。消息还留在输入框里,没有发出。'), exec: () => aiTap('[data-act="chat:send"]', tr('发送')) }+ ], summary: () => `${tr('已把「')}${text}${tr('」发给「')}${who}${tr('」。')}` };+ }+ case 'look': return { steps: [+ look,+ { thought: tr('读一下界面上带文字的元素。'), tool: 'iphone_list_elements', args: { limit: 150 }, exec: () => ({ text: `${tr('找到')} ${$$('[data-label]', demoEl).length} ${tr('个带文字的元素')}` }), think: 1100 }+ ], summary: () => { const l = [...new Set($$('[data-label]', demoEl).map(e => e.dataset.label))]; return `${tr('现在在「')}${screenName()}${tr('」,能看到:')}${l.slice(0, 8).join(tr('、'))}${l.length > 8 ? tr(' 等') : ''}${tr('。')}`; } };+ default: return { steps: [+ look,+ { thought: tr('演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。'), tool: null, args: null, exec: () => ({ error: true, text: tr('演示模式没有模拟这个任务') }), think: 900 }+ ], failSummary: tr('演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。') };+ }+}+async function gate(task) {+ while (task.status === 'paused' || task.status === 'takeover') { await sleep(150); if (task.stopped) throw STOP; }+ if (task.stopped) throw STOP;+}+async function runStep(task, spec) {+ await gate(task);+ if (task.recheck) { task.recheck = false; await runStep(task, { thought: tr('你刚才接管过设备,先重新看一下界面再继续。'), tool: 'iphone_screenshot', args: {}, exec: shot }); }+ const step = { n: task.steps.length + 1, thought: spec.thought, tool: spec.tool, args: spec.argsFrom ? spec.argsFrom() : spec.args, status: 'running' };+ task.steps.push(step); renderTurns(true);+ const t0 = performance.now();+ await sleep(spec.think ?? 700);+ await gate(task);+ if (spec.confirm) {+ step.status = 'waiting'; step.confirm = spec.confirm; task.status = 'waiting'; renderAll(); scrollConvo();+ const ok = await new Promise(res => { task.confirmResolve = res; });+ task.confirmResolve = null;+ if (task.stopped) throw STOP;+ if (!ok) { step.status = 'rejected'; step.result = tr('你拒绝了这一步,没有执行。'); finish(task, 'stopped', spec.rejectSummary); throw STOP; }+ step.status = 'running'; task.status = 'running'; renderAll(); await sleep(400);+ }+ const r = spec.exec() || {};+ step.ms = performance.now() - t0; step.status = r.error ? 'error' : 'ok'; step.result = r.text;+ renderTurns(true);+ if (r.error) throw new Error(r.text);+ await sleep(300);+}+async function runDemo(task) {+ const script = buildScript(task);+ try { for (const spec of script.steps) await runStep(task, spec); finish(task, 'success', script.summary()); }+ catch (e) { if (e === STOP) return; finish(task, 'failed', script.failSummary || `${tr('第')} ${task.steps.length} ${tr('步没走通:')}${e.message}${tr('。可以换个说法再试,或者接管后手动完成。')}`); }+}+function finish(task, status, summary) {+ task.status = status; task.endedAt = Date.now(); task.summary = summary; task.es?.close();+ S.expanded.delete(task.id); // 完成后步骤自动收起,用户可以手动展开+ renderAll(); scrollConvo();+ show(status === 'success' ? tr('AI 任务已完成') : status === 'failed' ? tr('AI 任务没有完成') : tr('AI 任务已停止'), status === 'failed' ? 'err' : null);+}++/* ---------- AI 任务:真实接口 ---------- */+function upsertStep(task, d) {+ let s = d.id != null ? task.steps.find(x => x.id === d.id) : null;+ if (!s) { s = { n: task.steps.length + 1, status: 'running' }; task.steps.push(s); }+ Object.assign(s, d);+ return s;+}+async function runLive(task) {+ try {+ const v = await api('/api/agent/tasks', { prompt: task.prompt, agent: task.agent });+ task.remoteId = v.id;+ const es = new EventSource(`/api/agent/tasks/${encodeURIComponent(v.id)}/events`);+ task.es = es;+ es.addEventListener('step', e => { const d = JSON.parse(e.data); upsertStep(task, d); if (d.gesture) { const g = d.gesture; drawMark(g.kind, 'ai', { x: g.x, y: g.y }, g.x2 != null ? { x: g.x2, y: g.y2 } : null); } renderTurns(true); });+ es.addEventListener('confirm', e => { const d = JSON.parse(e.data); upsertStep(task, { id: d.step, status: 'waiting', confirm: d }); task.status = 'waiting'; renderAll(); scrollConvo(); });+ es.addEventListener('state', e => { const d = JSON.parse(e.data); if (ACTIVE.includes(task.status)) { task.status = d.state; renderAll(); } });+ es.addEventListener('done', e => { const d = JSON.parse(e.data); finish(task, d.ok ? 'success' : d.stopped ? 'stopped' : 'failed', d.summary || ''); refreshStatusSoon(); });+ es.onerror = () => { if (ACTIVE.includes(task.status)) show(tr('AI 任务的事件流断开了,正在重连…'), 'warn'); };+ } catch (e) {+ task.steps.push({ n: 1, tool: null, status: 'error', result: String(e.message || e) });+ finish(task, 'failed', tr('任务没能交给 AI。手动操作和设备面板不受影响。'));+ }+}+async function liveControl(task, action, body) {+ if (!task.remoteId) return;+ try { await api(`/api/agent/tasks/${encodeURIComponent(task.remoteId)}/${action}`, body || {}); } catch (e) { show(`${tr('操作没有生效:')}${e.message || e}`, 'err'); }+}++/* ---------- 发送、控制、确认 ---------- */+function clearPromptError() { promptErr.hidden = true; promptErr.textContent = ''; promptEl.removeAttribute('aria-invalid'); $('#composer').classList.remove('invalid'); }+function autosize() { promptEl.style.height = 'auto'; promptEl.style.height = Math.min(promptEl.scrollHeight, 176) + 'px'; }+function sendPrompt() {+ if (activeTask()) return;+ const text = promptEl.value.trim();+ if (!text) {+ promptErr.textContent = tr('先写下要 AI 做的事,例如「打开设置,查看系统版本」。'); promptErr.hidden = false;+ promptEl.setAttribute('aria-invalid', 'true'); $('#composer').classList.add('invalid'); promptEl.focus(); return;+ }+ if (S.mode === 'live' && !S.agent) {+ promptErr.textContent = S.agents.length ? tr('这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。') : tr('还在读取可用的 AI,稍等一下再试。');+ promptErr.hidden = false; return;+ }+ clearPromptError();+ if (startTask(text)) { promptEl.value = ''; autosize(); }+}+function startTask(text) {+ if (activeTask()) return false;+ if (S.mode === 'detecting') { show(tr('还在连接服务,稍等一下再开始'), 'warn'); return false; }+ S.pendingDelete = null;+ const task = { id: 't' + (++S.seq), prompt: text, status: 'running', steps: [], startedAt: Date.now(), source: S.mode, agent: S.agent };+ S.tasks.push(task); S.expanded.add(task.id);+ renderAll(); scrollConvo();+ ($('[data-focus="rc-pause"]') || $('#intro-title')).focus({ preventScroll: true });+ show(tr('任务已交给 AI,画面的手动操作已锁定'));+ (S.mode === 'demo' ? runDemo : runLive)(task);+ return true;+}+function rerunTask(id) {+ const t = S.tasks.find(x => x.id === id);+ if (!t || activeTask()) return;+ if (startTask(t.prompt)) show(`${tr('重新执行:')}${t.prompt}`);+}+let delTimer = 0;+function askDelete(id) {+ S.pendingDelete = id; renderTurns();+ $(`[data-focus="dely-${CSS.escape(id)}"]`)?.focus({ preventScroll: true });+ clearTimeout(delTimer);+ delTimer = setTimeout(() => { if (S.pendingDelete === id) { S.pendingDelete = null; renderTurns(); } }, 5000);+}+function cancelDelete(id) {+ clearTimeout(delTimer); S.pendingDelete = null; renderTurns();+ $(`[data-focus="del-${CSS.escape(id)}"]`)?.focus({ preventScroll: true });+}+function confirmDelete(id) {+ clearTimeout(delTimer);+ const i = S.tasks.findIndex(x => x.id === id);+ if (i < 0 || ACTIVE.includes(S.tasks[i].status)) return;+ S.tasks.splice(i, 1); S.expanded.delete(id); S.pendingDelete = null;+ renderAll();+ show(tr('已删除这条记录'));+ // 焦点落到相邻记录的删除按钮上;没有记录了就回到输入框+ const near = S.tasks[i] || S.tasks[i - 1];+ ((near && $(`[data-focus="del-${CSS.escape(near.id)}"]`)) || (promptEl.disabled ? $('#intro-title') : promptEl)).focus({ preventScroll: true });+}+function control(action) {+ const t = activeTask(); if (!t) return;+ if (t.source === 'live') liveControl(t, action);+ if (action === 'pause') { t.status = 'paused'; show(tr('AI 已暂停')); }+ if (action === 'resume') { t.status = 'running'; show(tr('AI 继续执行')); }+ if (action === 'takeover') { t.status = 'takeover'; show(tr('你已接管:现在可以直接在画面上操作。')); }+ if (action === 'handback') { t.status = 'running'; t.recheck = true; show(tr('已交还 AI,它会先重新看一遍屏幕')); }+ renderAll();+}+function answerConfirm(approve) {+ const t = activeTask(); if (!t || t.status !== 'waiting') return;+ if (t.source === 'live') {+ const s = t.steps.find(x => x.status === 'waiting');+ liveControl(t, 'confirm', { step: s?.id, approve });+ if (s) s.status = approve ? 'running' : 'rejected';+ t.status = 'running'; renderAll();+ } else t.confirmResolve?.(approve);+ show(approve ? tr('已批准,AI 继续执行') : tr('已拒绝这一步'));+}+function stopTask() {+ const t = activeTask(); if (!t) return;+ t.stopped = true;+ t.steps.forEach(s => { if (s.status === 'running' || s.status === 'waiting') s.status = 'stopped'; });+ t.confirmResolve?.(false);+ if (t.source === 'live') liveControl(t, 'stop');+ finish(t, 'stopped', `${tr('在第')} ${t.steps.length} ${tr('步停下了。已经做完的操作不会撤销。')}`);+}+function gotoConfirm() {+ setView('agent');+ const t = activeTask(); if (t) { S.expanded.add(t.id); renderTurns(); }+ const btn = $('[data-action="approve"]');+ if (btn) { btn.closest('.confirm').scrollIntoView({ block: 'center' }); btn.focus({ preventScroll: true }); }+}++/* ================================================================+ * 渲染+ * ================================================================ */+/* 一步的说明:agent 自己说的话;没说时按工具和参数写一句看得懂的话 */+/* bundle id → App 名:没读过就读一次全部 App(含系统的),读完重画执行记录 */+const appNames = { map: null, loading: false };+function appLabel(app) {+ const a = S.apps.find(x => x.bundle_id === app);+ if (a) return a.name;+ if (appNames.map) return appNames.map[app] || app;+ if (!appNames.loading && S.mode === 'live') {+ appNames.loading = true;+ api('/api/apps?system=1').then(v => {+ appNames.map = Object.fromEntries((v.apps || []).map(x => [x.bundle_id, x.name]));+ renderTurns();+ }).catch(() => { appNames.map = {}; });+ }+ return app;+}+function describeStep(s) {+ // 中文「」紧挨着前面的字,英文用 “” 并空一格+ const a = s.args || {}, sp = LANG === 'en' ? ' ' : '', q = v => sp + (LANG === 'en' ? `“${String(v ?? '')}”` : `「${String(v ?? '')}」`);+ switch (s.tool) {+ case 'iphone_screenshot': return tr('看一下屏幕');+ case 'iphone_list_elements': return tr('读取屏幕上的内容');+ case 'iphone_status': return tr('查看手机状态');+ case 'iphone_tap': return tr('点击屏幕');+ case 'iphone_tap_element': return tr('点击') + q(a.text);+ case 'iphone_long_press': return tr('长按屏幕');+ case 'iphone_swipe': return tr('滑动屏幕');+ case 'iphone_type_text': return tr('输入') + q(a.text);+ case 'iphone_press_button': return ({ home: tr('按主屏幕键'), lock: tr('锁屏'), volume_up: tr('音量加'), volume_down: tr('音量减') })[a.button] || tr('按键');+ case 'iphone_launch_app': return tr('打开 App') + q(appLabel(a.app));+ case 'iphone_terminate_app': return tr('关闭') + q(appLabel(a.app));+ case 'iphone_open_url': return tr('打开链接') + ' ' + String(a.url || '');+ case 'iphone_wait_for': return tr('等待') + q(a.text) + sp + tr('出现');+ case 'iphone_list_apps': return tr('查看已安装的 App');+ case 'iphone_list_devices': return tr('查看已连接的设备');+ case 'iphone_batch': return tr('连续执行几步操作');+ case 'iphone_confirm': return tr('请你确认') + q(a.action);+ default: return tr('操作手机');+ }+}+/* 执行记录里每一步只有一句话:做了什么;没成功时注明一句(具体原因是给 agent 看的,它的下一步和总结会说明)。截图、工具名、参数和原始结果都不显示 */+function stepHtml(s) {+ const st = STEP_STATUS[s.status] || STEP_STATUS.running;+ const text = s.thought || describeStep(s);+ const confirm = s.status === 'waiting' && s.confirm ? `<div class="confirm" role="group" aria-labelledby="cf-${s.n}">+ <p class="confirm-title" id="cf-${s.n}">${icon('alert')}<span>${tr('需要你确认:')}${esc(s.confirm.action)}</span></p>+ <p class="confirm-detail">${esc(s.confirm.detail)}</p>+ <div class="od-cluster"><button type="button" class="btn btn-primary" data-action="approve" data-focus="approve">${icon('check')}<span>${tr('批准并执行')}</span></button><button type="button" class="btn" data-action="reject" data-focus="reject">${tr('拒绝')}</button></div></div>` : '';+ return `<li class="step"><div class="step-rail"><span class="step-dot tone-${st.tone}" title="${st.label}">${icon(st.icon, st.icon === 'loader' ? 'spin' : '')}<span class="sr-only">${st.label}</span></span><span class="step-line"></span></div>+ <div class="step-body"><p class="step-thought">${esc(text)}</p>${s.status === 'error' ? `<p class="step-result err">${tr('这一步没成功')}</p>` : ''}${confirm}</div></li>`;+}+function turnHtml(t) {+ const st = TASK_STATUS[t.status], active = ACTIVE.includes(t.status), open = S.expanded.has(t.id) || active;+ const busy = !!activeTask();+ const actions = active ? '' : S.pendingDelete === t.id+ ? `<button type="button" class="mini confirm-del" data-action="del-yes" data-id="${t.id}" data-focus="dely-${t.id}">${icon('trash')}<span>${tr('确认删除')}</span></button><button type="button" class="mini" data-action="del-no" data-id="${t.id}" data-focus="deln-${t.id}">${tr('取消')}</button>`+ : `<button type="button" class="mini" data-action="rerun" data-id="${t.id}" data-focus="rerun-${t.id}" ${busy ? 'disabled' : ''}>${icon('refresh')}<span>${tr('重新执行')}</span></button><button type="button" class="mini danger" data-action="del-ask" data-id="${t.id}" data-focus="del-${t.id}" aria-label="${tr('删除这条记录')}" title="${tr('删除这条记录')}">${icon('trash')}<span>${tr('删除')}</span></button>`;+ const answer = !active && t.summary ? `<div class="answer tone-${st.tone}">${icon(st.icon)}<div class="answer-text"><span class="answer-title">${st.label}</span><span class="answer-body">${esc(t.summary)}</span></div></div>` : '';+ const toggle = !active && t.steps.length ? `<button type="button" class="toggle-steps" data-action="toggle-steps" data-id="${t.id}" data-focus="ts-${t.id}" aria-expanded="${open}" aria-controls="steps-${t.id}"><span>${open ? tr('收起步骤') : `${tr('查看')} ${t.steps.length} ${tr('个步骤')}`}</span>${icon('chevron')}</button>` : '';+ return `<li class="turn">+ <div class="msg-user">+ <button type="button" class="bubble" data-action="rerun" data-id="${t.id}" data-focus="bubble-${t.id}" title="${busy ? tr('当前任务结束后可以重新执行') : tr('点击重新执行这条指令')}" aria-label="${tr('重新执行:')}${esc(t.prompt)}" ${busy ? 'disabled' : ''}>${esc(t.prompt)}</button>+ <div class="msg-meta"><span class="msg-time">${hhmm(new Date(t.startedAt))}</span>${actions}</div>+ </div>+ <div class="msg-agent">+ <div class="agent-line"><span class="avatar">${icon('bot')}</span><span class="agent-name">AI ${tr('助手')}</span><span class="agent-meta" data-elapsed="${t.id}">${t.steps.length} ${tr('步')} · ${mmss((t.endedAt || Date.now()) - t.startedAt)}</span>${badge(st)}</div>+ ${answer}${toggle}+ ${t.steps.length ? `<ol class="steps" id="steps-${t.id}" aria-label="${tr('执行步骤')}"${open ? '' : ' hidden'}>${t.steps.map(stepHtml).join('')}</ol>` : ''}+ </div></li>`;+}+function renderTurns(follow) {+ const sc = $('#agent-scroll'), near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 120;+ keepFocus(() => { turnsEl.innerHTML = S.tasks.map(turnHtml).join(''); });+ saveTasks();+ $('#intro').hidden = S.tasks.length > 0;+ if (follow && near) sc.scrollTop = sc.scrollHeight;+}+function scrollConvo() { const sc = $('#agent-scroll'); sc.scrollTop = sc.scrollHeight; }+function renderRunbar() {+ const t = activeTask(), bar = $('#runbar');+ const btn = (a, l, i, cls = '') => `<button type="button" class="btn btn-sm ${cls}" data-action="${a}" data-focus="rc-${a}">${icon(i)}<span>${l}</span></button>`;+ if (!t) { bar.hidden = true; bar.innerHTML = ''; }+ else {+ const st = TASK_STATUS[t.status], b = [];+ if (t.status === 'running') b.push(btn('pause', tr('暂停'), 'pause'), btn('takeover', tr('接管'), 'cursor'));+ if (t.status === 'paused') b.push(btn('resume', tr('继续'), 'play', 'btn-primary'), btn('takeover', tr('接管'), 'cursor'));+ if (t.status === 'takeover') b.push(btn('handback', tr('交还 AI'), 'play', 'btn-primary'));+ if (t.status === 'waiting') b.push(btn('goto-confirm', tr('去确认'), 'arrow', 'btn-primary'));+ b.push(btn('stop', tr('停止'), 'stop', 'btn-danger'));+ bar.innerHTML = `<span class="runbar-state t-${st.tone}">${icon(st.icon, st.icon === 'loader' ? 'spin' : '')}<span>${st.label}</span><span class="runbar-time" data-runtime="${t.id}">${mmss(Date.now() - t.startedAt)}</span></span>${b.join('')}`;+ bar.hidden = false;+ }+ const busy = !!t;+ promptEl.disabled = busy; $('#send').disabled = busy;+ promptEl.placeholder = busy ? tr('当前任务结束后可以发新任务') : tr('想让设备做什么?');+ const clear = $('#clear-btn');+ clear.hidden = !S.tasks.length || busy;+ $('#agent-badge').innerHTML = badge(t ? TASK_STATUS[t.status] : { label: S.mode === 'demo' ? tr('演示模式') : tr('空闲'), tone: S.mode === 'demo' ? 'warn' : 'muted', icon: S.mode === 'demo' ? 'info' : 'dot' });+}+function renderGuard() {+ const t = activeTask(), g = $('#guard');+ // 提示条和按键工具条占同一个位置、同样高度:AI 操作时换成提示条,设备画面尺寸保持不变+ const dock = $('#dock'), handback = $('#dock-handback');+ handback.hidden = !(t && t.status === 'takeover');+ if (!t || t.status === 'takeover') {+ g.hidden = true; g.innerHTML = ''; dock.classList.remove('is-covered'); dock.inert = false;+ frame.dataset.ctl = t ? 'takeover' : 'user';+ return;+ }+ dock.classList.add('is-covered'); dock.inert = true;+ const cfg = {+ running: { tone: 'accent', ic: 'loader', title: tr('AI 正在操作这台设备'), sub: tr('手动操作已锁定,避免和 AI 同时点击。'), btns: [['takeover', tr('接管'), 'cursor']] },+ paused: { tone: 'warn', ic: 'pause', title: tr('AI 已暂停'), sub: tr('画面仍为 AI 保留,要自己操作先接管。'), btns: [['resume', tr('继续'), 'play'], ['takeover', tr('接管'), 'cursor']] },+ waiting: { tone: 'warn', ic: 'alert', title: tr('AI 在等你确认一步操作'), sub: tr('确认前画面保持锁定。'), btns: [['goto-confirm', tr('去确认'), 'arrow']] },+ takeover: { tone: 'user', ic: 'cursor', title: tr('你在接管'), sub: tr('AI 已暂停。交还后它会先重新看一遍屏幕。'), btns: [['handback', tr('交还 AI'), 'play']] }+ }[t.status];+ g.className = `guard tone-${cfg.tone}`;+ g.innerHTML = `<span class="t-${cfg.tone}">${icon(cfg.ic, cfg.ic === 'loader' ? 'spin' : '')}</span><div class="guard-text"><span class="guard-title od-truncate">${cfg.title}</span><span class="guard-sub od-truncate">${cfg.sub}</span></div>+ <div class="od-row od-fixed">${cfg.btns.map(([a, l, i]) => `<button type="button" class="btn btn-sm" data-action="${a}" data-focus="guard-${a}">${icon(i)}<span>${l}</span></button>`).join('')}</div>`;+ g.hidden = false;+ frame.dataset.ctl = 'ai';+}+function renderManual() {+ const lock = guarded() || S.mode === 'detecting';+ $$('[data-key]').forEach(b => { b.disabled = lock; });+ typeEl.disabled = lock; $('#type-btn').disabled = lock; $('#type-submit').disabled = lock;+ $('#url').disabled = lock; $('#url-btn').disabled = lock;+ deviceEl.disabled = lock || !S.devices.length || !!S.devicesFixed;+ const t = activeTask();+ $('#vt-agent-label').textContent = t ? `AI · ${{ running: tr('执行中'), waiting: tr('待确认'), paused: tr('已暂停'), takeover: tr('接管中') }[t.status]}` : tr('AI 助手');+}+function renderAll() {+ keepFocus(() => { renderRunbar(); renderGuard(); renderManual(); renderTurns(); renderChips(); renderFeed(); renderAgentPick(); });+ if (S.devTab === 'apps') renderApps();+ if (S.devTab === 'elements') renderElements();+}+function fallbackFocus() {+ const rc = $('#runbar button');+ if (rc && !$('#runbar').hidden) return rc;+ return promptEl.disabled ? $('#intro-title') : promptEl;+}+function keepFocus(fn) {+ const a = document.activeElement, key = a && a.dataset ? a.dataset.focus : null;+ fn();+ if (key && !a.isConnected) {+ const n = $(`[data-focus="${CSS.escape(key)}"]`);+ (n && !n.disabled && n.offsetParent !== null ? n : fallbackFocus()).focus({ preventScroll: true });+ }+}+setInterval(() => {+ const t = activeTask(); if (!t) return;+ const el = $(`[data-runtime="${t.id}"]`); if (el) el.textContent = mmss(Date.now() - t.startedAt);+ const m = $(`[data-elapsed="${t.id}"]`); if (m) m.textContent = `${t.steps.length} ${tr('步')} · ${mmss(Date.now() - t.startedAt)}`;+}, 1000);++/* ---------- 视图:≥1280 三栏;1024–1279 右栏抽屉;<1024 三个标签页 ---------- */+const mqDrawer = matchMedia('(min-width: 1024px) and (max-width: 1279.98px)');+const mqTabs = matchMedia('(max-width: 1023.98px)');+function syncInert() {+ $('#pane-dev').inert = (mqDrawer.matches && !S.devOpen) || (mqTabs.matches && S.view !== 'device') || (isThreeCol() && devHidden);+ $('#pane-agent').inert = mqTabs.matches && S.view !== 'agent';+ $('#pane-stage').inert = mqTabs.matches && S.view !== 'screen';+}+function setView(v) {+ S.view = v; shell.dataset.view = v;+ ['agent', 'screen', 'device'].forEach(k => $(`#vt-${k}`).setAttribute('aria-selected', String(k === v)));+ if (v === 'device') setDevTab(S.devTab);+ syncInert();+}+function setDevOpen(open) {+ S.devOpen = open; shell.dataset.devOpen = String(open); $('#dev-toggle').setAttribute('aria-expanded', String(open)); syncInert();+ if (open) { setDevTab(S.devTab); setTimeout(() => $(`#tab-${S.devTab}`).focus(), 320); } else $('#dev-toggle').focus();+}+mqDrawer.addEventListener('change', syncInert);+mqTabs.addEventListener('change', syncInert);++/* ---------- 事件委托 ---------- */+document.addEventListener('click', ev => {+ const b = ev.target.closest('[data-action]');+ if (!b || b.disabled) return;+ const a = b.dataset.action;+ switch (a) {+ case 'send': sendPrompt(); break;+ case 'fill': if (activeTask()) return; promptEl.value = b.dataset.prompt; autosize(); clearPromptError(); promptEl.focus(); promptEl.setSelectionRange(promptEl.value.length, promptEl.value.length); break;+ case 'pause': case 'resume': case 'takeover': case 'handback': control(a); break;+ case 'approve': answerConfirm(true); break;+ case 'reject': answerConfirm(false); break;+ case 'stop': stopDialog.showModal(); requestAnimationFrame(() => $('#stop-cancel').focus()); break;+ case 'clear': if (activeTask() || !S.tasks.length) return; clearDialog.showModal(); requestAnimationFrame(() => $('#clear-cancel').focus()); break;+ case 'goto-confirm': gotoConfirm(); break;+ case 'sign': signWda(); break;+ case 'rerun': rerunTask(b.dataset.id); break;+ case 'del-ask': askDelete(b.dataset.id); break;+ case 'del-no': cancelDelete(b.dataset.id); break;+ case 'del-yes': confirmDelete(b.dataset.id); break;+ case 'zoom-in': zoomStep(1); break;+ case 'zoom-out': zoomStep(-1); break;+ case 'zoom-actual': setZoom(1); break;+ case 'zoom-fit': setZoom('fit'); break;+ case 'toggle-steps': { const id = b.dataset.id; if (S.expanded.has(id)) S.expanded.delete(id); else S.expanded.add(id); renderTurns(); break; }+ case 'view': setView(b.dataset.view); break;+ case 'dev-open': if (isThreeCol()) setDevHidden(false, true); else setDevOpen(true); break;+ case 'dev-close': if (isThreeCol()) setDevHidden(true, true); else setDevOpen(false); break;+ case 'dev-tab': setDevTab(b.dataset.tab); break;+ case 'load-apps': loadApps(); break;+ case 'launch': launchApp(b.dataset.app, b.dataset.name); break;+ case 'terminate': terminateApp(b.dataset.app, b.dataset.name); break;+ case 'open-url': openUrl(); break;+ case 'load-elements': loadElements(); break;+ case 'tap-el': tapElement(+b.dataset.el); break;+ case 'wait-for': waitFor(); break;+ case 'reconnect':+ if (S.mode === 'live') { loadInfo(); connect(); loadDeviceState(); show(tr('正在重新连接画面…')); }+ else if (S.mode === 'demo') { renderDemo(); loadDeviceState(); show(tr('已刷新演示画面')); }+ break;+ }+});+promptEl.addEventListener('keydown', ev => { if (ev.key === 'Enter' && !ev.shiftKey && !ev.isComposing && ev.keyCode !== 229) { ev.preventDefault(); sendPrompt(); } });+promptEl.addEventListener('input', () => { autosize(); if (!promptErr.hidden && promptEl.value.trim()) clearPromptError(); });+document.addEventListener('keydown', ev => { if (ev.key === 'Escape' && mqDrawer.matches && S.devOpen && !stopDialog.open) setDevOpen(false); });+// 设备面板的标签页支持左右方向键切换+$('#pane-dev .seg').addEventListener('keydown', ev => {+ if (ev.key !== 'ArrowLeft' && ev.key !== 'ArrowRight') return;+ const tabs = ['status', 'apps', 'elements'], i = tabs.indexOf(S.devTab), n = tabs[(i + (ev.key === 'ArrowRight' ? 1 : 2)) % 3];+ setDevTab(n); $(`#tab-${n}`).focus();+});++function closeStop(confirmed) {+ stopDialog.close();+ if (confirmed) stopTask();+ const back = $('[data-focus="rc-stop"]');+ (back || fallbackFocus()).focus();+}+$('#stop-cancel').addEventListener('click', () => closeStop(false));+$('#stop-confirm').addEventListener('click', () => closeStop(true));+stopDialog.addEventListener('cancel', ev => { ev.preventDefault(); closeStop(false); });++// 清空操作记录:只清本页记录,任务执行中不可用+const clearDialog = $('#clear-dialog');+function closeClear(confirmed) {+ clearDialog.close();+ if (confirmed && !activeTask()) {+ S.tasks.forEach(t => t.es?.close());+ S.tasks = []; S.expanded.clear();+ renderAll();+ $('#agent-scroll').scrollTop = 0;+ show(tr('已清空操作记录'));+ promptEl.focus();+ return;+ }+ ($('#clear-btn').hidden ? promptEl : $('#clear-btn')).focus();+}+$('#clear-cancel').addEventListener('click', () => closeClear(false));+$('#clear-confirm').addEventListener('click', () => closeClear(true));+clearDialog.addEventListener('cancel', ev => { ev.preventDefault(); closeClear(false); });++/* ---------- 启动 ---------- */+async function detect() {+ try {+ const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), 1500);+ const r = await fetch('/api/info', { signal: ctrl.signal, headers: { 'X-Ictl-Lang': LANG } }); clearTimeout(timer);+ if (!r.ok) throw new Error('no service');+ const v = await r.json();+ if (!v || typeof v !== 'object' || !('width' in v || 'warning' in v)) throw new Error('no service');+ S.mode = 'live'; applyInfo(v); connect(); loadAgents();+ setInterval(() => { loadInfo(); loadDeviceState(); }, 10000);+ } catch {+ S.mode = 'demo'; S.stream = 'ok';+ stageMsg.hidden = true; live.hidden = true; demoEl.hidden = false; $('#demo-note').hidden = false;+ applyDemoGeometry(); renderDemo();+ show(tr('演示模式:没有连上 iphone-control 服务,画面是本地模拟的。'));+ }+ await loadDeviceState();+ renderAll(); setDevTab(S.devTab);+}+/* ---------- 执行任务的 AI:本机装了哪些就列哪些,选择记在浏览器里 ---------- */+const AGENT_KEY = 'ictl.agent';+async function loadAgents() {+ try { S.agents = (await api('/api/agent/backends')).backends || []; } catch { S.agents = []; }+ const ok = S.agents.filter(a => a.available);+ let saved = null;+ try { saved = localStorage.getItem(AGENT_KEY); } catch { /* 预览环境可能禁用存储 */ }+ S.agent = (ok.find(a => a.id === saved) || ok[0] || {}).id || null;+ renderAgentPick();+}+function renderAgentPick() {+ const wrap = $('#agent-pick'), sel = $('#agent');+ wrap.hidden = S.mode !== 'live';+ if (wrap.hidden) return;+ if (!S.agents.some(a => a.available)) {+ sel.innerHTML = tr('<option>没有可用的 AI</option>');+ sel.title = tr('这台机器的 PATH 里没有 claude 或 codex');+ } else {+ sel.innerHTML = S.agents.map(a => `<option value="${esc(a.id)}"${a.id === S.agent ? ' selected' : ''}${a.available ? '' : ' disabled'}>${esc(a.name)}${a.available ? '' : tr('(未安装)')}</option>`).join('');+ sel.title = tr('执行任务的本地 AI');+ }+ sel.disabled = !S.agent || !!activeTask();+}+$('#agent').addEventListener('change', ev => {+ S.agent = ev.target.value;+ try { localStorage.setItem(AGENT_KEY, S.agent); } catch { /* 只在本次会话生效 */ }+});++/* ---------- 右侧设备面板隐藏 / 显示(宽屏三栏时),记在浏览器里 ---------- */+let devHidden = false;+try { devHidden = localStorage.getItem('ictl.devHidden') === '1'; } catch { /* 预览环境可能禁用存储 */ }+shell.dataset.devHidden = String(devHidden);+function setDevHidden(hidden, moveFocus) {+ devHidden = hidden; shell.dataset.devHidden = String(hidden);+ try { localStorage.setItem('ictl.devHidden', hidden ? '1' : '0'); } catch { /* 只在本次会话生效 */ }+ $('#dev-toggle').setAttribute('aria-expanded', String(!hidden));+ syncInert(); fitPanes();+ if (!hidden) setDevTab(S.devTab);+ if (moveFocus) (hidden ? $('#dev-toggle') : $(`#tab-${S.devTab}`)).focus();+ show(hidden ? tr('已隐藏设备面板,点右上角「设备面板」可以再打开') : tr('已显示设备面板'));+}++/* ---------- 两侧栏宽度:拖拽、方向键调整,双击恢复默认,记在浏览器里 ---------- */+const MIN_STAGE = 420; // 中间设备画面至少保留的宽度+const isThreeCol = () => matchMedia('(min-width: 1280px)').matches;+function makeResizer({ handle, pane, cssVar, def, min, key, edge, maxFn }) {+ const r = { w: def };+ try { const v = parseInt(localStorage.getItem(key), 10); if (v) r.w = v; } catch { /* 预览环境可能禁用存储 */ }+ r.set = (w, save) => {+ const max = Math.round(maxFn());+ r.w = Math.round(Math.min(max, Math.max(min, w)));+ shell.style.setProperty(cssVar, r.w + 'px');+ handle.setAttribute('aria-valuemin', min);+ handle.setAttribute('aria-valuemax', max);+ handle.setAttribute('aria-valuenow', r.w);+ handle.setAttribute('aria-valuetext', `${r.w} ${tr('像素')}`);+ if (save) { try { localStorage.setItem(key, String(r.w)); } catch { /* 只在本次会话生效 */ } }+ };+ handle.addEventListener('pointerdown', ev => {+ if (ev.button !== 0) return;+ ev.preventDefault();+ handle.setPointerCapture(ev.pointerId);+ const rect = pane.getBoundingClientRect();+ handle.classList.add('dragging'); document.body.classList.add('resizing');+ // 手柄在右边缘(左栏):往右拖变宽;手柄在左边缘(右栏):往左拖变宽+ const move = e => r.set(edge === 'right' ? e.clientX - rect.left : rect.right - e.clientX, false);+ const up = () => {+ handle.removeEventListener('pointermove', move);+ handle.removeEventListener('pointerup', up);+ handle.removeEventListener('pointercancel', up);+ handle.classList.remove('dragging'); document.body.classList.remove('resizing');+ r.set(r.w, true);+ };+ handle.addEventListener('pointermove', move);+ handle.addEventListener('pointerup', up);+ handle.addEventListener('pointercancel', up);+ });+ handle.addEventListener('dblclick', () => r.set(def, true));+ handle.addEventListener('keydown', ev => {+ const step = (ev.shiftKey ? 64 : 16) * (edge === 'right' ? 1 : -1);+ const next = { ArrowLeft: r.w - step, ArrowRight: r.w + step, Home: min, End: maxFn() }[ev.key];+ if (next === undefined) return;+ ev.preventDefault(); r.set(next, true);+ });+ return r;+}+const agentRS = makeResizer({+ handle: $('#resizer'), pane: $('#pane-agent'), cssVar: '--w-agent', def: 460, min: 360, key: 'ictl.agentWidth', edge: 'right',+ maxFn: () => Math.max(360, Math.min(760, window.innerWidth - (isThreeCol() && !devHidden ? devRS.w : 0) - MIN_STAGE))+});+const devRS = makeResizer({+ handle: $('#resizer-dev'), pane: $('#pane-dev'), cssVar: '--w-dev', def: 344, min: 300, key: 'ictl.devWidth', edge: 'left',+ // 三栏时给左栏和设备画面留够位置;1024–1279px 的抽屉最宽占视口 90%+ maxFn: () => isThreeCol() ? Math.max(300, Math.min(600, window.innerWidth - agentRS.w - MIN_STAGE)) : Math.max(300, Math.min(600, window.innerWidth * 0.9))+});+function fitPanes() { devRS.set(devRS.w, false); agentRS.set(agentRS.w, false); }+window.addEventListener('resize', fitPanes);+fitPanes();++/* ---------- 操作记录保存在浏览器里,刷新后还在 ---------- */+const TASKS_KEY = 'ictl.tasks', MAX_TASKS = 50;+function serializeTasks(withThumbs) {+ return JSON.stringify(S.tasks.slice(-MAX_TASKS).map(t => ({+ id: t.id, prompt: t.prompt, status: t.status, source: t.source, startedAt: t.startedAt, endedAt: t.endedAt, summary: t.summary, remoteId: t.remoteId,+ steps: t.steps.map(st => ({ id: st.id, n: st.n, thought: st.thought, tool: st.tool, args: st.args, status: st.status, ms: st.ms, result: st.result, confirm: st.confirm }))+ })));+}+let saveTimer = 0;+function saveTasks() {+ clearTimeout(saveTimer);+ saveTimer = setTimeout(() => {+ try { localStorage.setItem(TASKS_KEY, serializeTasks(true)); }+ catch {+ // 空间不够时去掉截图缩略图再存一次;存储被禁用时只保留在本次页面里+ try { localStorage.setItem(TASKS_KEY, serializeTasks(false)); } catch { /* 忽略 */ }+ }+ }, 300);+}+function loadTasks() {+ let list;+ try { list = JSON.parse(localStorage.getItem(TASKS_KEY) || '[]'); } catch { return; }+ if (!Array.isArray(list)) return;+ list = list.filter(t => t && t.id && Array.isArray(t.steps));+ list.forEach(t => {+ // 刷新前还在执行的任务:页面已经不再跟踪它,如实标成已停止+ if (ACTIVE.includes(t.status)) {+ t.status = 'stopped'; t.endedAt = t.endedAt || Date.now();+ t.summary = tr('页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。');+ t.steps.forEach(st => { if (st.status === 'running' || st.status === 'waiting') st.status = 'stopped'; });+ }+ });+ S.tasks = list;+ S.seq = list.reduce((m, t) => Math.max(m, parseInt(String(t.id).replace(/\D/g, ''), 10) || 0), 0);+}+loadTasks();++/* ---------- 画面缩放:适应窗口,或按实际尺寸的 50%–200%(100% = 一个点占一个像素),记在浏览器里 ---------- */+const ZOOM = { min: 0.5, max: 2, steps: [0.5, 0.67, 0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2], key: 'ictl.zoom' };+const stageWrap = $('#stage-wrap');+let zoom = 'fit';+try { const v = localStorage.getItem(ZOOM.key); if (v && v !== 'fit' && +v >= ZOOM.min && +v <= ZOOM.max) zoom = +v; } catch { /* 预览环境可能禁用存储 */ }+const devPointsW = () => (dims() || {}).W || 0; // 当前方向下设备的宽度(点)+const fitScale = () => { const w = devPointsW(); return w ? stage.clientWidth / w : 1; };+const currentScale = () => zoom === 'fit' ? fitScale() : zoom;+function applyZoom() {+ const w = devPointsW();+ if (zoom === 'fit' || !w) { delete frame.dataset.zoom; frame.style.removeProperty('--fixed-w'); }+ else {+ const pad = parseFloat(getComputedStyle(frame).getPropertyValue('--pad')) || 11;+ frame.dataset.zoom = 'fixed'; frame.style.setProperty('--fixed-w', `${Math.round(w * zoom + pad * 2)}px`);+ }+ updateZoomUI();+}+function updateZoomUI() {+ const sc = currentScale();+ $('#zoom-val').textContent = `${Math.round(sc * 100)}%`;+ $('#zoom-fit').setAttribute('aria-pressed', String(zoom === 'fit'));+ $('#zoom-out').disabled = sc <= ZOOM.min + 0.001;+ $('#zoom-in').disabled = sc >= ZOOM.max - 0.001;+}+function setZoom(z, anchor) {+ // 缩放前记下视野中心(或滚轮所在点)在内容里的相对位置,缩放后保持在原处+ const r = stageWrap.getBoundingClientRect();+ const ax = anchor ? anchor.x - r.left : stageWrap.clientWidth / 2, ay = anchor ? anchor.y - r.top : stageWrap.clientHeight / 2;+ const fx = (stageWrap.scrollLeft + ax) / stageWrap.scrollWidth, fy = (stageWrap.scrollTop + ay) / stageWrap.scrollHeight;+ zoom = z === 'fit' ? 'fit' : Math.round(Math.min(ZOOM.max, Math.max(ZOOM.min, z)) * 100) / 100;+ try { localStorage.setItem(ZOOM.key, String(zoom)); } catch { /* 只在本次会话生效 */ }+ applyZoom();+ stageWrap.scrollLeft = fx * stageWrap.scrollWidth - ax;+ stageWrap.scrollTop = fy * stageWrap.scrollHeight - ay;+}+function zoomStep(dir) {+ const sc = currentScale();+ const next = dir > 0 ? ZOOM.steps.find(v => v > sc + 0.005) : [...ZOOM.steps].reverse().find(v => v < sc - 0.005);+ setZoom(next ?? (dir > 0 ? ZOOM.max : ZOOM.min));}-document.getElementById('type').addEventListener('submit', ev => { ev.preventDefault(); typeText(false); });-document.getElementById('submit').addEventListener('click', () => typeText(true));+// 按住 Ctrl/⌘ 滚动滚轮缩放;触控板双指捏合在浏览器里也会以这种方式传进来+stageWrap.addEventListener('wheel', ev => {+ if (!ev.ctrlKey && !ev.metaKey) return;+ ev.preventDefault();+ setZoom(currentScale() * Math.exp(-ev.deltaY * 0.01), { x: ev.clientX, y: ev.clientY });+}, { passive: false });+// 适应模式下窗口或栏宽变化时,比例读数跟着更新+new ResizeObserver(updateZoomUI).observe(stage);-loadInfo();-// keep the size and the device check current (WDA may come up later, the daemon may switch devices)-setInterval(loadInfo, 10000);-// the stream may have failed before the handlers above were set-if (img.complete && !img.naturalWidth) img.onerror();+hydrateIcons();+renderAll();+renderStatusPanel();+syncInert();+detect();</script></body></html>diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rsindex 0e1ada6..ea86c69 100644--- a/apps/iphone-control/src/viewer.rs+++ b/apps/iphone-control/src/viewer.rs@@ -1,62 +1,138 @@-//! `iphone-control viewer`: a small page on 127.0.0.1 that shows the phone's screen live and acts on it.+//! `iphone-control viewer`: a page on 127.0.0.1 to watch the phone live, act on it with the mouse, look at its+//! state, apps and elements, and hand tasks to a local AI agent (see [`crate::agent`]).//!-//! - `GET /` the page, `GET /stream` WDA's MJPEG stream (port 9100 on the phone, over usbmuxd, read-only),-//! `GET /api/info` the screen size in points.-//! - `POST /api/{tap,swipe,long_press,type,button}` turn into ordinary daemon requests, so they queue with-//! the agent's calls, get auto-unlock and follow the controlled device, exactly like an MCP tool call.+//! - `GET /` the page, `GET /stream` WDA's MJPEG stream (port 9100 on the phone, over usbmuxd, read-only).+//! - `GET /api/{info,daemon,status,devices,apps,elements}`: the daemon's answers as JSON for the page.+//! - `POST /api/{tap,swipe,long_press,type,button,launch_app,terminate_app,open_url,tap_element,wait_for,select}`+//! turn into ordinary daemon requests, so they queue with an agent's calls, get auto-unlock and follow the+//! controlled device, exactly like an MCP tool call.+//! - `/api/agent/…`: available agents, starting a task, its events (server-sent events), and pause / resume /+//! take over / hand back / stop / confirm.//!//! Protections, same model as `wda-bridge`: it binds to the loopback address only, every request needs a-//! loopback `Host` (against DNS rebinding), and every action also needs an `Origin` of this very page and a-//! JSON content type (against other web pages posting to it). Other local users can still reach the port,-//! which the command says when it starts.+//! loopback `Host` (against DNS rebinding), every action also needs an `Origin` of this very page and a JSON+//! content type (against other web pages posting to it), and a read whose `Sec-Fetch-Site` says another site+//! sent it is refused (reading elements unlocks the phone). Other local users can still reach the port, which the+//! command says when it starts.//!-//! The viewer belongs to one device, the one controlled when it starts: the picture always comes from it, and-//! every action carries its UDID ([`ictl_daemon::protocol::EXPECT_UDID`]), so the daemon refuses an action once-//! it controls another device (after `select`, or an unplug in automatic mode) instead of tapping a phone the-//! user isn't looking at. The device handle is looked up again for each stream, so a replug (new usbmuxd id)-//! doesn't break the picture.+//! The viewer follows one device, the one controlled when it starts or the one picked on the page: the picture+//! always comes from it, and every action carries its UDID ([`ictl_daemon::protocol::EXPECT_UDID`]), so the daemon+//! refuses an action once it controls another device (after `select` elsewhere, or an unplug in automatic mode)+//! instead of tapping a phone the user isn't looking at. The device handle is looked up again for each stream, so a+//! replug (new usbmuxd id) doesn't break the picture.-use std::path::Path;+use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};use std::time::Duration;use anyhow::bail;-use ictl_daemon::protocol::{Request, Response};+use ictl_daemon::machine::DeviceState;+use ictl_daemon::protocol::{self, Request, Response, TouchPhase};use serde_json::{Value, json};use tokio::io::{AsyncReadExt, AsyncWriteExt};use tokio::net::TcpStream;+use crate::agent::{self, Agents};+const PAGE: &str = include_str!("viewer.html");/// WDA's MJPEG server on the phoneconst MJPEG_PORT: u16 = 9100;const MAX_BODY: usize = 16 * 1024;+/// Most elements the Elements tab lists+const ELEMENT_LIMIT: usize = 300;+const SPRINGBOARD: &str = "com.apple.springboard";++/// What every connection shares+struct Ctx {+ /// The data directory: whether an Apple ID is signed in (signing WDA from the page needs one)+ data_dir: PathBuf,+ /// The page, marked with the viewer's language (the page's default; it can switch)+ page: String,+ socket: PathBuf,+ port: u16,+ /// The device the page shows and acts on+ udid: Mutex<String>,+ agents: Arc<Agents>,+ /// Bundle id → display name, for the foreground app+ names: tokio::sync::Mutex<HashMap<String, String>>,+}++impl Ctx {+ fn udid(&self) -> String {+ self.udid.lock().unwrap_or_else(|p| p.into_inner()).clone()+ }+}-pub async fn run(socket: &Path, port: u16) -> anyhow::Result<()> {- let udid = crate::target_device(socket, None).await?.udid;+pub async fn run(socket: &Path, data_dir: &Path, port: u16) -> anyhow::Result<()> {+ // only a first guess: the page follows whichever device the daemon controls (see `info`). Not knowing yet is+ // fine: the daemon may still be starting (started together with this at login), and with several devices+ // connected it is the one that picks+ let udid = match crate::target_device(socket, None).await {+ Ok(d) => d.udid,+ Err(e) => {+ eprintln!(+ "{}",+ ictl_l10n::trf!(+ "还不知道控制哪台设备({e}),等守护进程选好后页面自动跟上",+ "Not sure which device yet ({e}); the page follows once the daemon has picked one"+ )+ );+ String::new()+ }+ };let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?;let port = listener.local_addr()?.port();+ // next to the daemon's socket: a directory only this user can enter+ let gate = socket.parent().unwrap_or(Path::new("/tmp")).join(format!("viewer-{port}.sock"));+ let agents = Agents::new(socket, gate.clone())?;+ agent::GateServer::serve(gate, agents.clone()).await?;println!("{}",ictl_l10n::trf!("实时画面:http://127.0.0.1:{port}/ (手机 {},Ctrl-C 停止)","Live viewer: http://127.0.0.1:{port}/ (phone {}, Ctrl-C to stop)",- udid+ if udid.is_empty() { ictl_l10n::tr!("跟随守护进程", "whichever the daemon controls") } else { &udid }));+ let found: Vec<&str> =+ agent::Backend::ALL.iter().filter(|b| b.find().is_some()).map(|b| b.id()).collect::<Vec<_>>();+ println!(+ "{}",+ if found.is_empty() {+ ictl_l10n::tr!(+ "AI 任务:PATH 里没有 claude 或 codex,网页上只能手动操作",+ "AI tasks: neither claude nor codex is on PATH, so the page can only be used by hand"+ )+ .to_owned()+ } else {+ ictl_l10n::trf!("AI 任务可用:{}", "AI tasks available with: {}", found.join(", "))+ }+ );println!("{}",ictl_l10n::tr!(- "注意:本机所有用户都能经这个端口看到屏幕、操作手机,用完就停掉。",- "Note: every user on this machine can watch and control the phone through this port; stop it when you are done."+ "注意:本机所有用户都能经这个端口看到屏幕、操作手机、让 AI 执行任务,用完就停掉。",+ "Note: every user on this machine can watch and control the phone and start AI tasks through this port; stop it when you are done."));- let slots = std::sync::Arc::new(tokio::sync::Semaphore::new(crate::MAX_CONNECTIONS));+ let ctx = Arc::new(Ctx {+ socket: socket.to_path_buf(),+ data_dir: data_dir.to_path_buf(),+ port,+ udid: Mutex::new(udid),+ agents,+ names: tokio::sync::Mutex::default(),+ page: page_in(ictl_l10n::lang()),+ });+ let slots = Arc::new(tokio::sync::Semaphore::new(crate::MAX_CONNECTIONS));loop {let (client, _) = listener.accept().await?;// too many open connections (for example many tabs): drop the new onelet Ok(slot) = slots.clone().try_acquire_owned() else { continue };- let (udid, socket) = (udid.clone(), socket.to_path_buf());+ let ctx = ctx.clone();tokio::spawn(async move {- if let Err(e) = serve(client, &udid, &socket, port).await {+ if let Err(e) = serve(client, &ctx).await {tracing::debug!("viewer connection: {e}");}drop(slot);@@ -64,20 +140,43 @@ pub async fn run(socket: &Path, port: u16) -> anyhow::Result<()> {}}-/// One request per connection (`Connection: close`), which keeps the parser small-async fn serve(mut client: TcpStream, udid: &str, socket: &Path, port: u16) -> anyhow::Result<()> {- let (head, mut body) = crate::read_head(&mut client).await?;+/// The page with `data-lang` set for English, which the page reads as its default language+fn page_in(lang: ictl_l10n::Lang) -> String {+ match lang {+ ictl_l10n::Lang::En => PAGE.replacen("<html lang=\"zh-CN\">", "<html lang=\"en\" data-lang=\"en\">", 1),+ ictl_l10n::Lang::Zh => PAGE.to_owned(),+ }+}++/// One request per connection (`Connection: close`), which keeps the parser small. It is handled in the page's+/// language (`X-Ictl-Lang`), so the daemon's messages match the page+async fn serve(mut client: TcpStream, ctx: &Ctx) -> anyhow::Result<()> {+ let (head, body) = crate::read_head(&mut client).await?;let Some(req) = Head::parse(&head) else {return reply(&mut client, 400, "text/plain", b"bad request").await;};- if !crate::host_is_loopback(&head) {+ match req.lang {+ Some(l) => ictl_l10n::scope(l, handle(client, ctx, head, req, body)).await,+ None => handle(client, ctx, head, req, body).await,+ }+}++async fn handle(mut client: TcpStream, ctx: &Ctx, head: Vec<u8>, req: Head, mut body: Vec<u8>) -> anyhow::Result<()> {+ if !crate::host_is_loopback(&head) || (req.path != "/" && !fetch_site_ok(&req)) {return reply(&mut client, 403, "text/plain", b"forbidden").await;}- match (req.method.as_str(), req.path.as_str()) {- ("GET", "/") => reply(&mut client, 200, "text/html; charset=utf-8", PAGE.as_bytes()).await,+ let path = req.path.as_str();+ match (req.method.as_str(), path) {+ ("GET", "/") => reply(&mut client, 200, "text/html; charset=utf-8", ctx.page.as_bytes()).await,("GET", "/stream") => {- // looked up again each time: after a replug usbmuxd gives the device a new id- let device = ictl_device::Device::find(Some(udid)).await;+ // the device the page shows (`?udid=`), so a page that hasn't noticed a switch keeps its own picture+ // instead of silently showing another phone. Looked up again each time: after a replug usbmuxd gives the+ // device a new id+ let udid = req.query("udid").filter(|u| !u.is_empty()).unwrap_or_else(|| ctx.udid());+ if udid.is_empty() {+ return reply(&mut client, 503, "text/plain", b"no device yet").await;+ }+ let device = ictl_device::Device::find(Some(&udid)).await;let mut remote = match async { device?.connect_port(MJPEG_PORT).await }.await {Ok(r) => r,Err(e) => return reply(&mut client, 502, "text/plain", e.to_string().as_bytes()).await,@@ -87,12 +186,35 @@ async fn serve(mut client: TcpStream, udid: &str, socket: &Path, port: u16) -> atokio::io::copy_bidirectional(&mut client, &mut remote).await?;Ok(())}- ("GET", "/api/info") => {- let v = info(socket, udid).await;- reply(&mut client, 200, "application/json", v.to_string().as_bytes()).await+ ("GET", p) if p.starts_with("/api/agent/tasks/") && p.ends_with("/events") => {+ let id = &p["/api/agent/tasks/".len()..p.len() - "/events".len()];+ match ctx.agents.task(id) {+ Some(t) => events(&mut client, &t).await,+ None => {+ json_reply(&mut client, 404, &json!({"message": ictl_l10n::tr!("没有这个任务", "No such task")}))+ .await+ }+ }+ }+ ("GET", p) if p.starts_with("/api/") => {+ let v = match &p[5..] {+ // always an answer: the page falls back to its offline demo when this one fails+ "info" => Ok(info(ctx).await.unwrap_or_else(|m| json!({"width": null, "height": null, "warning": m}))),+ "daemon" => daemon(ctx).await,+ "status" => status(ctx).await,+ "devices" => devices(ctx).await,+ "apps" => apps(ctx, req.query("system").is_some_and(|v| v == "1")).await,+ "elements" => elements(ctx, &req.query("filter").unwrap_or_default()).await,+ "agent/backends" => Ok(json!({"backends": agent::backends()})),+ _ => return reply(&mut client, 404, "text/plain", b"not found").await,+ };+ match v {+ Ok(v) => json_reply(&mut client, 200, &v).await,+ Err(m) => json_reply(&mut client, 502, &json!({"message": m})).await,+ }}- ("POST", path) if path.starts_with("/api/") => {- if !action_allowed(&req, port) {+ ("POST", p) if p.starts_with("/api/") => {+ if !action_allowed(&req, ctx.port) {return reply(&mut client, 403, "text/plain", b"forbidden").await;}let len = req.content_length.unwrap_or(0);@@ -108,22 +230,130 @@ async fn serve(mut client: TcpStream, udid: &str, socket: &Path, port: u16) -> abody.extend_from_slice(&buf[..n]);}body.truncate(len);- let v = match serde_json::from_slice::<Value>(&body).ok().and_then(|b| action(&path[5..], &b)) {- Some(r) => run_action(socket, r, udid).await,- None => json!({"ok": false, "message": "bad action"}),+ let Ok(b) = serde_json::from_slice::<Value>(&body) else {+ return json_reply(&mut client, 400, &json!({"ok": false, "message": "bad request"})).await;};- reply(&mut client, 200, "application/json", v.to_string().as_bytes()).await+ let (code, v) = post(ctx, &p[5..], &b, req.device.as_deref()).await;+ json_reply(&mut client, code, &v).await}_ => reply(&mut client, 404, "text/plain", b"not found").await,}}+/// A POST under `/api/`: status code and JSON answer+/// `device`: the one the page shows (`X-Ictl-Device`); actions only go to it+async fn post(ctx: &Ctx, name: &str, b: &Value, device: Option<&str>) -> (u16, Value) {+ let conflict = |m: String| (409, json!({"ok": false, "message": m}));+ if name == "agent/tasks" {+ let prompt = b["prompt"].as_str().unwrap_or_default();+ let backend = b["agent"].as_str().unwrap_or("claude");+ return match ctx.agents.start(prompt, backend) {+ Ok(id) => (200, json!({"ok": true, "id": id})),+ Err(m) => conflict(m),+ };+ }+ if let Some(rest) = name.strip_prefix("agent/tasks/")+ && let Some((id, action)) = rest.split_once('/')+ {+ return match ctx.agents.control(id, action, b) {+ Ok(()) => (200, json!({"ok": true})),+ Err(m) => conflict(m),+ };+ }+ if name == "select" {+ if ctx.agents.busy() {+ return conflict(+ ictl_l10n::tr!("AI 任务执行中,不能切换设备", "An AI task is running, so the device can't be switched")+ .into(),+ );+ }+ let Some(device) = b["device"].as_str() else { return (400, json!({"ok": false, "message": "bad action"})) };+ let v = run_action(&ctx.socket, &Request::SelectDevice { device: device.to_owned() }, None, SHORT).await;+ // the page follows the device it picked+ if v["ok"] == true+ && let Ok(s) = crate::snapshot(&ctx.socket).await+ && let Some(d) = s.device+ {+ *ctx.udid.lock().unwrap_or_else(|p| p.into_inner()) = d.udid;+ }+ return (200, v);+ }+ let udid = device.map(str::to_owned).unwrap_or_else(|| ctx.udid());+ // not known yet (the daemon wasn't up when this started): no device check rather than one that always fails+ let udid = Some(udid.as_str()).filter(|u| !u.is_empty());+ if name == "sign" {+ if !ctx.agents.manual_allowed() {+ return conflict(+ ictl_l10n::tr!("AI 任务执行中,不能签名安装", "An AI task is running; signing has to wait").into(),+ );+ }+ // signing for the page's device: refused if the daemon has moved on to another one+ return (200, run_action(&ctx.socket, &Request::Resign { force: true }, udid, SIGN).await);+ }+ let Some(req) = action(name, b) else { return (400, json!({"ok": false, "message": "bad action"})) };+ // reading is fine during a task, and so is lifting a finger that was down when it started; acting would compete+ // with the agent+ let harmless = matches!(req, Request::WaitFor { .. } | Request::Touch { phase: TouchPhase::Up, .. });+ if !harmless && !ctx.agents.manual_allowed() {+ return conflict(+ ictl_l10n::tr!(+ "AI 正在操作这台设备。要自己操作,先点「接管」。",+ "The AI is operating this device. To act yourself, click “Take over” first."+ )+ .into(),+ );+ }+ (200, run_action(&ctx.socket, &req, udid, SHORT).await)+}++/// The task's events so far, then new ones as they come, as server-sent events, until it is done+async fn events(client: &mut TcpStream, task: &agent::Task) -> anyhow::Result<()> {+ client+ .write_all(+ b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\n\+ X-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n",+ )+ .await?;+ let (log, mut rx, done) = task.subscribe();+ for e in &log {+ client.write_all(sse(e).as_bytes()).await?;+ }+ if done {+ return Ok(());+ }+ loop {+ tokio::select! {+ r = rx.recv() => match r {+ Ok(e) => {+ client.write_all(sse(&e).as_bytes()).await?;+ if e.name == "done" {+ return Ok(());+ }+ }+ // fell behind (many screenshots at once): the page reconnects and gets everything again+ Err(_) => return Ok(()),+ },+ // a comment now and then finds a page that went away+ _ = tokio::time::sleep(Duration::from_secs(15)) => client.write_all(b": ping\n\n").await?,+ }+ }+}++fn sse(e: &agent::Event) -> String {+ format!("event: {}\ndata: {}\n\n", e.name, e.data)+}++async fn json_reply(client: &mut TcpStream, status: u16, v: &Value) -> anyhow::Result<()> {+ reply(client, status, "application/json", v.to_string().as_bytes()).await+}+async fn reply(client: &mut TcpStream, status: u16, kind: &str, body: &[u8]) -> anyhow::Result<()> {let reason = match status {200 => "OK",400 => "Bad Request",403 => "Forbidden",404 => "Not Found",+ 409 => "Conflict",413 => "Payload Too Large",_ => "Bad Gateway",};@@ -140,9 +370,15 @@ async fn reply(client: &mut TcpStream, status: u16, kind: &str, body: &[u8]) ->struct Head {method: String,path: String,+ query: String,origin: Option<String>,content_type: Option<String>,content_length: Option<usize>,+ /// `X-Ictl-Device`: the device the page shows; its actions are refused once the daemon controls another+ device: Option<String>,+ fetch_site: Option<String>,+ /// `X-Ictl-Lang`: the page's language+ lang: Option<ictl_l10n::Lang>,}impl Head {@@ -151,8 +387,20 @@ impl Head {let mut lines = text.split("\r\n");let mut first = lines.next()?.split(' ');let method = first.next()?.to_owned();- let path = first.next()?.split('?').next()?.to_owned();- let mut h = Self { method, path, origin: None, content_type: None, content_length: None };+ let target = first.next()?;+ let (path, query) = target.split_once('?').unwrap_or((target, ""));+ let (path, query) = (path.to_owned(), query.to_owned());+ let mut h = Self {+ method,+ path,+ query,+ origin: None,+ content_type: None,+ content_length: None,+ fetch_site: None,+ lang: None,+ device: None,+ };for l in lines {let Some((k, v)) = l.split_once(':') else { continue };let v = v.trim();@@ -160,11 +408,45 @@ impl Head {"origin" => h.origin = Some(v.to_owned()),"content-type" => h.content_type = Some(v.to_ascii_lowercase()),"content-length" => h.content_length = Some(v.parse().ok()?),+ "sec-fetch-site" => h.fetch_site = Some(v.to_ascii_lowercase()),+ "x-ictl-lang" => h.lang = ictl_l10n::parse(v),+ "x-ictl-device" if !v.is_empty() => h.device = Some(v.to_owned()),_ => {}}}Some(h)}++ /// A query parameter, percent-decoded+ fn query(&self, key: &str) -> Option<String> {+ self.query.split('&').find_map(|kv| {+ let (k, v) = kv.split_once('=').unwrap_or((kv, ""));+ (k == key).then(|| percent_decode(v))+ })+ }+}++fn percent_decode(s: &str) -> String {+ let b = s.as_bytes();+ let mut out = Vec::with_capacity(b.len());+ let mut i = 0;+ while i < b.len() {+ match b[i] {+ b'+' => out.push(b' '),+ b'%' if i + 2 < b.len() => {+ match std::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) {+ Some(v) => {+ out.push(v);+ i += 2;+ }+ None => out.push(b'%'),+ }+ }+ c => out.push(c),+ }+ i += 1;+ }+ String::from_utf8_lossy(&out).into_owned()}/// An action must come from this page: `Origin` is the viewer's own address, and the body is JSON, which a@@ -177,9 +459,16 @@ fn action_allowed(req: &Head, port: u16) -> bool {json && origin}+/// A read from another site (an `<img>` or `<script>` on some page) is refused: browsers say so in+/// `Sec-Fetch-Site`. Requests without it (curl, older browsers) come from this machine anyway+fn fetch_site_ok(req: &Head) -> bool {+ req.fetch_site.as_deref().is_none_or(|s| matches!(s, "same-origin" | "none"))+}+/// Maps a page action to the daemon request it stands forfn action(name: &str, b: &Value) -> Option<Request> {let num = |k: &str| b.get(k).and_then(Value::as_f64).filter(|v| v.is_finite());+ let text = |k: &str| b.get(k).and_then(Value::as_str).map(str::to_owned);Some(match name {"tap" => Request::Tap { x: num("x")?, y: num("y")? },"long_press" => Request::LongPress { x: num("x")?, y: num("y")?, seconds: num("seconds")?.clamp(0.3, 5.0) },@@ -188,45 +477,241 @@ fn action(name: &str, b: &Value) -> Option<Request> {to: (num("x2")?, num("y2")?),seconds: num("seconds")?.clamp(0.05, 3.0),},- "type" => Request::TypeText {- text: b.get("text")?.as_str()?.to_owned(),- submit: b.get("submit").and_then(Value::as_bool).unwrap_or(false),+ "type" => {+ Request::TypeText { text: text("text")?, submit: b.get("submit").and_then(Value::as_bool).unwrap_or(false) }+ }+ "button" => Request::PressButton { button: text("button")? },+ "touch" => Request::Touch {+ phase: match b.get("phase")?.as_str()? {+ "prepare" => TouchPhase::Prepare,+ "down" => TouchPhase::Down,+ "move" => TouchPhase::Move,+ "up" => TouchPhase::Up,+ _ => return None,+ },+ x: num("x").unwrap_or(0.0),+ y: num("y").unwrap_or(0.0),+ },+ "launch_app" => Request::LaunchApp { app: text("app")?.trim().to_owned() },+ "terminate_app" => Request::TerminateApp { app: text("app")?.trim().to_owned() },+ "open_url" => Request::OpenUrl { url: text("url")?.trim().to_owned() },+ "tap_element" => Request::TapElement {+ text: text("text")?,+ index: b.get("index").and_then(Value::as_u64).unwrap_or(0) as usize,+ max_age_ms: 0,+ },+ "wait_for" => Request::WaitFor {+ text: text("text")?,+ timeout_ms: (num("timeout").unwrap_or(5.0).clamp(0.5, 30.0) * 1000.0) as u64,},- "button" => Request::PressButton { button: b.get("button")?.as_str()?.to_owned() },_ => return None,})}-/// Sends one action to the daemon, only for the viewer's device (see the module docs)-async fn run_action(socket: &Path, req: Request, udid: &str) -> Value {- match ictl_daemon::protocol::call_expecting(socket, &req, Some(Duration::from_secs(120)), Some(udid)).await {- Ok(Response::Text { text, .. }) => json!({"ok": true, "message": text}),+/// Sends one action to the daemon; `udid` limits it to the viewer's device (see the module docs)+/// How long a page action may take; signing and installing WDA has its own, longer limit in the daemon+const SHORT: Duration = Duration::from_secs(120);+const SIGN: Duration = Duration::from_secs(16 * 60);++async fn run_action(socket: &Path, req: &Request, udid: Option<&str>, timeout: Duration) -> Value {+ match protocol::call_expecting(socket, req, Some(timeout), udid).await {+ // tapping by text that found nothing is an ordinary answer for the agent, a failure for the page+ Ok(Response::Text { text, outcome }) => {+ let missed = matches!(req, Request::TapElement { .. }) && protocol::tapped_nothing(&text, outcome);+ json!({"ok": !missed, "message": text})+ }Ok(Response::Image { caption, .. }) => json!({"ok": true, "message": caption}),Ok(Response::Error { message }) => json!({"ok": false, "message": message}),Err(e) => json!({"ok": false, "message": e.to_string()}),}}-/// Screen size in points (portrait) for turning a click on the picture into a tap, and whether the daemon-/// still controls the viewer's device-async fn info(socket: &Path, udid: &str) -> Value {- match crate::snapshot(socket).await {- Ok(s) => {- let screen = screen_of(&s.persisted, udid);- let controlled = s.device.as_ref().is_some_and(|d| d.udid.eq_ignore_ascii_case(udid));- json!({- "width": screen.map(|s| s.width),- "height": screen.map(|s| s.height),- "state": s.state,- "device": s.device.map(|d| d.name),- "warning": (!controlled).then(|| ictl_l10n::trf!(- "守护进程现在控制的不是这台({udid}),操作会被拒绝;要看另一台,重新运行 iphone-control viewer",- "The daemon no longer controls this device ({udid}), so actions are refused; to view another device, run iphone-control viewer again"- )),- })+/// One daemon request whose text the page needs as data. `en`: ask in English, whose wording the parsers expect+async fn text_of(socket: &Path, req: Request, en: bool) -> Result<String, String> {+ let call = protocol::call(socket, &req, Some(Duration::from_secs(60)));+ let r = if en { ictl_l10n::scope(ictl_l10n::Lang::En, call).await } else { call.await };+ match r {+ Ok(Response::Text { text, .. }) => Ok(text),+ Ok(Response::Error { message }) => Err(message),+ Ok(Response::Image { caption, .. }) => Ok(caption),+ Err(e) => Err(e.to_string()),+ }+}++/// Screen size in points (portrait) for turning a click on the picture into a tap, and the device the viewer follows.+/// It follows the device the daemon controls: switched on this page, on another page, with `iphone-control select`,+/// or automatically after an unplug. The page notices `udid` changing and moves its picture and panels over; until+/// then its actions carry the old UDID and are refused, never sent to a phone the user isn't looking at+async fn info(ctx: &Ctx) -> Result<Value, String> {+ let s = crate::snapshot(&ctx.socket).await.map_err(|e| e.to_string())?;+ if let Some(d) = &s.device+ && !d.udid.eq_ignore_ascii_case(&ctx.udid())+ {+ *ctx.udid.lock().unwrap_or_else(|p| p.into_inner()) = d.udid.clone();+ }+ let udid = ctx.udid();+ let screen = screen_of(&s.persisted, &udid);+ Ok(json!({+ "width": screen.map(|s| s.width),+ "height": screen.map(|s| s.height),+ "udid": udid,+ // the picture's pointer drives a finger over CoreDevice HID (iOS 27 and later); older phones get whole gestures+ "live_touch": s.device.as_ref().is_some_and(|d| d.major_version() >= 27),+ "device": s.device.map(|d| d.name),+ "state": state_of(&s.state).0,+ }))+}++fn state_of(s: &DeviceState) -> (&'static str, Option<String>) {+ match s {+ DeviceState::Absent => ("Absent", None),+ DeviceState::NeedsTrust => ("NeedsTrust", None),+ DeviceState::DeveloperModeOff => ("DeveloperModeOff", None),+ DeviceState::NeedsUnlock => ("NeedsUnlock", None),+ DeviceState::NeedsSigning => ("NeedsSigning", None),+ DeviceState::WdaStarting { last_error } => ("WdaStarting", last_error.clone()),+ DeviceState::NeedsAutomationPin => ("NeedsAutomationPin", None),+ DeviceState::Ready => ("Ready", None),+ }+}++fn device_json(d: &ictl_device::DeviceInfo) -> Value {+ json!({"udid": d.udid, "name": d.name, "model": d.product_type, "ios": d.product_version})+}++/// `{ state, last_error?, device: { name, model, ios, udid }, auto_unlock }`+async fn daemon(ctx: &Ctx) -> Result<Value, String> {+ let s = crate::snapshot(&ctx.socket).await.map_err(|e| e.to_string())?;+ let (state, last_error) = state_of(&s.state);+ Ok(json!({+ "state": state,+ "state_text": s.state.describe(),+ "last_error": last_error,+ "device": s.device.as_ref().map(device_json),+ "auto_unlock": s.auto_unlock && !s.unlock_disabled,+ // the page offers to sign and install WDA (NeedsSigning) only with an Apple ID to sign with+ "signed_in": crate::account_dir(&ctx.data_dir).selected_email().await.is_ok(),+ }))+}++/// `{ devices: [{ udid, name, model, ios, controlled }], fixed }`+async fn devices(ctx: &Ctx) -> Result<Value, String> {+ let s = crate::snapshot(&ctx.socket).await.map_err(|e| e.to_string())?;+ let cur = s.device.as_ref().map(|d| d.udid.to_ascii_lowercase());+ let list: Vec<Value> = s+ .devices+ .iter()+ .map(|d| {+ let mut v = device_json(d);+ v["controlled"] = (cur.as_deref() == Some(d.udid.to_ascii_lowercase().as_str())).into();+ v+ })+ .collect();+ Ok(json!({"devices": list, "fixed": s.pinned_by_env, "auto": s.pinned.is_none()}))+}++/// `{ wda_ready, locked, foreground, foreground_id, width, height, route }`, from the English status text+async fn status(ctx: &Ctx) -> Result<Value, String> {+ let text = text_of(&ctx.socket, Request::Status, true).await?;+ // the HID fallback needs iOS 27; an older device without WDA can't be operated at all+ let hid = crate::snapshot(&ctx.socket).await.ok().and_then(|s| s.device).is_some_and(|d| d.major_version() >= 27);+ let mut v = parse_status(&text, hid);+ if let Some(id) = v["foreground_id"].as_str().map(str::to_owned) {+ v["foreground"] = app_name(ctx, &id).await.into();+ }+ Ok(v)+}++fn parse_status(text: &str, hid: bool) -> Value {+ let field = |k: &str| text.lines().find_map(|l| l.strip_prefix(k)).map(str::trim);+ let ready = field("WDA ready:") == Some("True");+ let lock = field("Locked:");+ let locked = lock.map(|l| !l.starts_with("unlocked"));+ let fg = field("Foreground app:").filter(|s| !s.is_empty());+ let (w, h) = field("Screen:")+ .and_then(|s| s.split_whitespace().next())+ .and_then(|s| s.split_once('x'))+ .and_then(|(w, h)| Some((w.parse::<f64>().ok()?, h.parse::<f64>().ok()?)))+ .unzip();+ json!({+ "wda_ready": ready,+ "locked": locked,+ "possibly_locked": lock.is_some_and(|l| l.starts_with("possibly")),+ "foreground_id": fg,+ "foreground": fg,+ "width": w,+ "height": h,+ // without WDA, screenshots, taps and keys go over CoreDevice HID (iOS 27 and later); otherwise nothing works+ "route": if ready { "wda" } else if hid { "hid" } else { "none" },+ })+}++/// The display name of an installed app (the home screen for SpringBoard); the bundle id when unknown+async fn app_name(ctx: &Ctx, bundle: &str) -> String {+ if bundle == SPRINGBOARD {+ return ictl_l10n::tr!("主屏幕", "Home Screen").into();+ }+ let mut names = ctx.names.lock().await;+ if !names.contains_key(bundle) {+ for system in [false, true] {+ if let Ok(list) = list_apps(ctx, system).await {+ for (n, b) in list {+ names.insert(b, n);+ }+ }}- Err(e) => json!({"error": e.to_string()}),}+ names.get(bundle).cloned().unwrap_or_else(|| bundle.to_owned())+}++async fn list_apps(ctx: &Ctx, system: bool) -> Result<Vec<(String, String)>, String> {+ let text = text_of(&ctx.socket, Request::ListApps { include_system: system }, false).await?;+ Ok(text+ .lines()+ .filter_map(|l| l.split_once('\t'))+ .map(|(n, b)| (n.trim().to_owned(), b.trim().to_owned()))+ .collect())+}++/// `{ apps: [{ name, bundle_id }] }`: the user's apps, and with `system` the system's too+async fn apps(ctx: &Ctx, system: bool) -> Result<Value, String> {+ let mut all = list_apps(ctx, false).await?;+ if system {+ all.extend(list_apps(ctx, true).await?);+ }+ let mut seen = std::collections::HashSet::new();+ all.retain(|(_, b)| seen.insert(b.clone()));+ Ok(json!({"apps": all.iter().map(|(n, b)| json!({"name": n, "bundle_id": b})).collect::<Vec<_>>()}))+}++/// `{ elements: [{ type, label, x, y, width, height }] }`, `x`/`y` the top-left corner in points+async fn elements(ctx: &Ctx, filter: &str) -> Result<Value, String> {+ let req = Request::ListElements { filter: filter.to_owned(), limit: ELEMENT_LIMIT, max_age_ms: 0 };+ let text = text_of(&ctx.socket, req, true).await?;+ Ok(json!({"elements": text.lines().filter_map(parse_element).collect::<Vec<_>>()}))+}++/// One line of `iphone_list_elements`: `Type "label" [id="…"] [value="…"] @(cx,cy) WxH`. Other lines (a note+/// that more were left out) are skipped+fn parse_element(line: &str) -> Option<Value> {+ let (kind, rest) = line.split_once(" \"")?;+ if kind.is_empty() || kind.contains(' ') {+ return None;+ }+ let at = rest.rfind(" @(")?;+ let (desc, geom) = (&rest[..at], &rest[at + 3..]);+ let label_end =+ [desc.find("\" id=\""), desc.find("\" value=\"")].into_iter().flatten().min().unwrap_or_else(|| {+ // no id or value: the label runs to the last quote+ desc.rfind('"').unwrap_or(desc.len())+ });+ let label = &desc[..label_end];+ let (center, size) = geom.split_once(") ")?;+ let (cx, cy) = center.split_once(',')?;+ let (w, h) = size.trim().split_once('x')?;+ let n = |s: &str| s.trim().parse::<f64>().ok();+ let (cx, cy, w, h) = (n(cx)?, n(cy)?, n(w)?, n(h)?);+ Some(json!({"type": kind, "label": label, "x": cx - w / 2.0, "y": cy - h / 2.0, "width": w, "height": h}))}/// The recorded screen size, only if it belongs to `udid` (a size recorded by an older version, without@@ -257,6 +742,16 @@ mod tests {assert!(!action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200", "Origin: null")), 8200));}+ #[test]+ fn reads_from_other_sites_are_refused() {+ let get = |site: &str| head(&format!("GET /api/elements HTTP/1.1\r\nHost: 127.0.0.1:8200\r\n{site}\r\n"));+ assert!(fetch_site_ok(&get("Sec-Fetch-Site: same-origin\r\n")));+ assert!(fetch_site_ok(&get("Sec-Fetch-Site: none\r\n")), "typed into the address bar");+ assert!(fetch_site_ok(&get("")), "curl");+ assert!(!fetch_site_ok(&get("Sec-Fetch-Site: cross-site\r\n")));+ assert!(!fetch_site_ok(&get("Sec-Fetch-Site: same-site\r\n")), "another port on localhost");+ }+#[test]fn page_actions_map_to_daemon_requests() {assert_eq!(action("tap", &json!({"x": 10.0, "y": 20.5})), Some(Request::Tap { x: 10.0, y: 20.5 }));@@ -269,8 +764,26 @@ mod tests {Some(Request::TypeText { text: "hi".into(), submit: false }));assert_eq!(action("button", &json!({"button": "home"})), Some(Request::PressButton { button: "home".into() }));+ assert_eq!(+ action("tap_element", &json!({"text": "通用", "index": 1})),+ Some(Request::TapElement { text: "通用".into(), index: 1, max_age_ms: 0 })+ );+ assert_eq!(+ action("wait_for", &json!({"text": "x", "timeout": 99})),+ Some(Request::WaitFor { text: "x".into(), timeout_ms: 30_000 })+ );+ assert_eq!(action("launch_app", &json!({"app": " 设置 "})), Some(Request::LaunchApp { app: "设置".into() }));+ assert_eq!(+ action("touch", &json!({"phase": "move", "x": 3, "y": 4.5})),+ Some(Request::Touch { phase: TouchPhase::Move, x: 3.0, y: 4.5 })+ );+ assert_eq!(+ action("touch", &json!({"phase": "prepare"})),+ Some(Request::Touch { phase: TouchPhase::Prepare, x: 0.0, y: 0.0 })+ );+ assert_eq!(action("touch", &json!({"phase": "hover", "x": 1, "y": 1})), None);assert_eq!(action("tap", &json!({"x": 1})), None);- assert_eq!(action("launch", &json!({})), None);+ assert_eq!(action("uninstall_app", &json!({"app": "x"})), None);}#[test]@@ -287,9 +800,67 @@ mod tests {}#[test]- fn parses_request_head() {+ fn parses_request_head_and_query() {let h = head("GET /stream?t=1 HTTP/1.1\r\nHost: localhost:8200\r\n\r\n");assert_eq!((h.method.as_str(), h.path.as_str()), ("GET", "/stream"));+ let h = head("GET /api/elements?filter=%E8%AE%BE+x&system=1 HTTP/1.1\r\nHost: localhost\r\n\r\n");+ assert_eq!(+ (h.path.as_str(), h.query("filter").as_deref(), h.query("system").as_deref()),+ ("/api/elements", Some("设 x"), Some("1"))+ );+ assert_eq!(head("GET /api/apps HTTP/1.1\r\n\r\n").query("system"), None);+ assert_eq!(percent_decode("100%"), "100%");+ let h = head("GET /api/status HTTP/1.1\r\nHost: localhost\r\nX-Ictl-Lang: en\r\n\r\n");+ assert_eq!(h.lang, Some(ictl_l10n::Lang::En));+ // the device the page shows: its actions go only there, its picture comes from there+ let h = head("POST /api/tap HTTP/1.1\r\nX-Ictl-Device: 00008150-001A\r\n\r\n");+ assert_eq!(h.device.as_deref(), Some("00008150-001A"));+ assert_eq!(head("POST /api/tap HTTP/1.1\r\nX-Ictl-Device: \r\n\r\n").device, None, "empty means none");+ let h = head("GET /stream?udid=00008150-001A&t=1 HTTP/1.1\r\n\r\n");+ assert_eq!(h.query("udid").as_deref(), Some("00008150-001A"));assert!(Head::parse(b"POST / HTTP/1.1\r\nContent-Length: x\r\n\r\n").is_none());}++ #[test]+ fn the_page_says_its_default_language() {+ assert!(page_in(ictl_l10n::Lang::En).contains("<html lang=\"en\" data-lang=\"en\">"));+ assert!(page_in(ictl_l10n::Lang::Zh).contains("<html lang=\"zh-CN\">"));+ }++ #[test]+ fn status_text_becomes_fields() {+ let v = parse_status(+ "WDA ready: True\nLocked: locked (actions unlock automatically)\nForeground app: com.apple.Preferences\nScreen: 440x956 points\nDaemon: Ready",+ true,+ );+ assert_eq!(v["wda_ready"], true);+ assert_eq!(v["locked"], true);+ assert_eq!(v["foreground_id"], "com.apple.Preferences");+ assert_eq!((v["width"].as_f64(), v["height"].as_f64()), (Some(440.0), Some(956.0)));+ assert_eq!(v["route"], "wda");+ assert_eq!(parse_status("WDA ready: True\nLocked: unlocked\n", false)["locked"], false);+ let down = "WDA is starting\nreading elements … wait until WDA is back\nDaemon: Starting WDA";+ assert_eq!(parse_status(down, true)["route"], "hid", "iOS 27 and later");+ assert_eq!(parse_status(down, false)["route"], "none", "older: no HID fallback");+ let down = parse_status(down, true);+ assert_eq!(down["wda_ready"], false);+ assert!(down["locked"].is_null());+ }++ #[test]+ fn element_lines_become_boxes() {+ let e = parse_element("Button \"通用\" id=\"com.apple.settings.general\" @(220,776) 400x52").unwrap();+ assert_eq!(+ e,+ json!({"type": "Button", "label": "通用", "x": 20.0, "y": 750.0, "width": 400.0, "height": 52.0})+ );+ let v = parse_element("Button \"秒表\" value=\"1\" @(267,904) 108x54").unwrap();+ assert_eq!((v["label"].as_str(), v["x"].as_f64()), (Some("秒表"), Some(213.0)));+ let plain = parse_element("StaticText \"世界时钟\" @(83,140) 126x41").unwrap();+ assert_eq!(plain["label"], "世界时钟");+ let quoted = parse_element("StaticText \"say \"hi\"\" @(10,10) 4x4").unwrap();+ assert_eq!(quoted["label"], "say \"hi\"");+ assert!(parse_element("……另有 4 个未列出,可用 filter 缩小范围").is_none());+ assert!(parse_element("4 more not listed; narrow it down with filter").is_none());+ }}diff --git a/compose.yaml b/compose.yamldeleted file mode 100644index 71bacca..0000000--- a/compose.yaml+++ /dev/null@@ -1,43 +0,0 @@-services:- iphone:- build:- context: .- dockerfile: docker/Dockerfile- network: host # 让构建能用宿主机 127.0.0.1 上的代理- args:- HTTP_PROXY: ${HTTP_PROXY:-}- HTTPS_PROXY: ${HTTPS_PROXY:-}- image: ${IMAGE:-iphone-control:local}- container_name: ${CONTAINER_NAME:-iphone-control}- # 只开放 USB 设备(字符设备主号 189),不再整个 privileged;隧道走用户态 TCP 栈,不建网卡、不改宿主机网络。- # /dev/bus/usb 用绑定挂载(见 volumes)而不是 devices:拔插后新出现的设备节点在容器里也看得到- device_cgroup_rules:- - "c 189:* rmw"- # 守护进程是 PID 1:加 init 回收子进程(stty 等),并把停止信号转给它- init: true- # 停止时先停 HID 屏幕媒体流、runner、usbmuxd;给够时间,避免被强杀后手机端留下会话- stop_grace_period: 30s- # WDA 经 usbmuxd 直连手机,本机不监听任何端口;host 网络只为了用宿主机上的代理- network_mode: host- restart: unless-stopped- # status 连不上控制接口就算不健康;卡死时守护进程自己退出,由上面的 restart 拉起- healthcheck:- test: ["CMD", "iphone-control", "status"]- interval: 60s- timeout: 15s- retries: 3- start_period: 30s- # stdout/stderr 的上限;logs 目录里的日志由守护进程自己轮转- logging:- driver: json-file- options:- max-size: 10m- max-file: "3"- env_file:- - path: .env- required: false- environment:- NO_PROXY: ${NO_PROXY:-localhost,127.0.0.1,::1}- volumes:- - /dev/bus/usb:/dev/bus/usb- - ${DATA_DIR:-./data}:/var/lib/iphone-controldiff --git a/crates/ictl-daemon/src/config.rs b/crates/ictl-daemon/src/config.rsindex 2737b03..fde906c 100644--- a/crates/ictl-daemon/src/config.rs+++ b/crates/ictl-daemon/src/config.rs@@ -1,4 +1,4 @@-//! 守护进程配置:全部来自环境变量(容器里由 .env 注入;从源码运行时由 systemd 的环境文件或 shell 给),都有默认值。秘密只放文件,不放环境变量以外的地方。+//! 守护进程配置:全部来自环境变量(服务从 ~/.config/iphone-control/env 读入,手动运行时由 shell 给),都有默认值。秘密只放文件,不放环境变量以外的地方。use std::path::{Path, PathBuf};use std::time::Duration;@@ -12,11 +12,7 @@ pub struct Config {/// 固定要控制的手机(`IPHONE_UDID`);None 时可以在运行中选(见 [`crate::core::Persisted::selected_udid`])。/// 都没选是自动选:正在控制的那台一直用到断开,没有正在控制的才取 usbmuxd 列出的第一台pub udid: Option<String>,- /// 由守护进程拉起并看护 usbmuxd。默认以 root 运行(容器)时为 true;普通用户拉起的 usbmuxd 碰不到 USB,- /// 改用系统的 usbmuxd 服务。宿主机以 root 运行、又已有 usbmuxd 服务时设 ICTL_MANAGE_USBMUXD=0- pub manage_usbmuxd: bool,- pub usbmuxd_bin: String,- /// 未签名的 WDA:镜像里自带;从源码运行时是数据目录里的 [`Config::wda_unsigned_cache`],第一次签名前下载+ /// 未签名的 WDA:默认是数据目录里的 [`Config::wda_unsigned_cache`],第一次签名前下载pub wda_unsigned: PathBuf,pub ddi_url: String,/// 自己从 Xcode 提取的 DDI Restore 目录;设了就不下载,也从不删除里面的文件@@ -46,7 +42,7 @@ impl NotifyConfig {}}-/// 读环境变量,去掉首尾空白,空值当作没设(.env 里常留着 `KEY=`)+/// 读环境变量,去掉首尾空白,空值当作没设(配置文件里常留着 `KEY=`)pub fn env(k: &str) -> Option<String> {std::env::var(k).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty())}@@ -71,13 +67,7 @@ impl Config {// 实际值由命令行给(--socket / ICTL_SOCKET,见 apps/iphone-control)socket: crate::protocol::default_socket(),udid: env("IPHONE_UDID"),- manage_usbmuxd: env("ICTL_MANAGE_USBMUXD")- .map_or_else(crate::protocol::running_as_root, |v| v != "0" && v != "false"),- usbmuxd_bin: env("ICTL_USBMUXD_BIN").unwrap_or_else(|| "usbmuxd".into()),- wda_unsigned: env("ICTL_WDA_UNSIGNED").map(PathBuf::from).unwrap_or_else(|| {- let image = Path::new(crate::wda_pkg::IMAGE_PATH);- if image.is_file() { image.to_owned() } else { wda_unsigned_cache(data_dir) }- }),+ wda_unsigned: env("ICTL_WDA_UNSIGNED").map(PathBuf::from).unwrap_or_else(|| wda_unsigned_cache(data_dir)),ddi_url: env("ICTL_DDI_URL").unwrap_or_else(|| ictl_device::ddi::DEFAULT_BASE_URL.into()),ddi_dir: env("ICTL_DDI_DIR").map(PathBuf::from),anisette_url: env("ICTL_ANISETTE_URL"),@@ -143,13 +133,13 @@ impl Config {self.data_dir.join("state.json")}- /// 建好数据目录并收紧权限:配对记录、账号私钥、锁屏密码都在里面+ /// 建好数据目录并收紧权限:账号私钥、锁屏密码都在里面(配对记录归系统的 usbmuxd 管)pub fn prepare_dirs(&self) -> std::io::Result<()> {use std::os::unix::fs::PermissionsExt;- for d in ["lockdown", "account", "wda", "ddi", "secrets", "logs"] {+ for d in ["account", "wda", "ddi", "secrets", "logs"] {std::fs::create_dir_all(self.data_dir.join(d))?;}- for d in ["", "lockdown", "account", "secrets"] {+ for d in ["", "account", "secrets"] {std::fs::set_permissions(self.data_dir.join(d), std::fs::Permissions::from_mode(0o700))?;}Ok(())diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex d143895..0aa24c0 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -22,7 +22,7 @@ use tokio::task::JoinHandle;use crate::config::Config;use crate::eventlog::EventLog;-use crate::machine::{Backoff, DeviceState, Misses, MuxWatch};+use crate::machine::{Backoff, DeviceState, Misses};use crate::notify::{self, Dedup, Event};use crate::protocol::{Request, Response};use crate::supervise::StartOutcome;@@ -161,7 +161,7 @@ impl DeviceProfile {/// 从手机上的描述文件(原始内容)里挑 WDA 的:app-id 是「团队 ID.WDA Bundle ID」(不知道团队 ID 时只看 Bundle ID)、/// 设备列表里有这台手机,取最晚到期的那份。装过几次会留下几份,旧的过期了也还在-pub fn wda_profile_expiry(profiles: &[Vec<u8>], team: Option<&str>, bundle: &str, udid: &str) -> Option<SystemTime> {+pub fn wda_profile(profiles: &[Vec<u8>], team: Option<&str>, bundle: &str, udid: &str) -> Option<ictl_sign::Profile> {profiles.iter().filter_map(|p| ictl_sign::Profile::parse(p))@@ -171,8 +171,11 @@ pub fn wda_profile_expiry(profiles: &[Vec<u8>], team: Option<&str>, bundle: &str.is_some_and(|(t, b)| b == bundle && team.is_none_or(|team| t == team))&& p.devices.iter().any(|d| d.eq_ignore_ascii_case(udid))})- .map(|p| p.expires)- .max()+ .max_by_key(|p| p.expires)+}++pub fn wda_profile_expiry(profiles: &[Vec<u8>], team: Option<&str>, bundle: &str, udid: &str) -> Option<SystemTime> {+ wda_profile(profiles, team, bundle, udid).map(|p| p.expires)}/// 一次请求的附带条件(来自请求里的 [`ictl_protocol::CANCEL_ON_CLOSE`]、[`ictl_protocol::EXPECT_UDID`])@@ -214,6 +217,10 @@ pub struct Snapshot {pub(crate) struct PerDevice {/// 这台手机上的 WDA 描述文件pub device_profile: DeviceProfile,+ /// 那份描述文件里没有本机签名私钥的证书(Some(true)):WDA 是别的机器、旧的数据目录签的,或本机的证书是后来才+ /// 新建的。这时 WDA 起不来多半是签它的证书被吊销了,用本机的证书重签就好([`Daemon::heal_certificate`])。+ /// None:不知道(没读到描述文件、本机还没签过名)+ pub foreign_wda: Option<bool>,/// WDA 最近一次报的界面旋转及读取时间。只在短暂掉线时给 HID 使用,不持久化pub wda_rotation: Option<(Instant, Rotation)>,/// 开发者镜像连续挂载失败次数,到 3 次清缓存重新下载@@ -223,6 +230,8 @@ pub(crate) struct PerDevice {/// 这台手机上 Home 先用 XCTest 的:上一次 IOHID 的没回到主屏、XCTest 的回到了(iPhone 18 Pro Max //// iOS 27.2.1 上 IOHID 的 Home 基本不起作用)。iPhone 12 mini 正相反,所以按设备记,见 `tools::press_home`pub home_via_xctest: bool,+ /// The orientation of the finger the web viewer is moving (`Request::Touch`), worked out when it touched down+ pub touch_rotation: Option<Rotation>,pub apps: HashMap<bool, Vec<AppInfo>>,/// Log capture for `AppLogs` (developer tools), started by the first requestpub log_capture: Option<crate::devtools::Capture>,@@ -247,12 +256,6 @@ pub(crate) struct Inner {pub resigning: bool,pub wda_misses: Misses,pub backoff: Backoff,- pub mux: MuxWatch,- pub usbmuxd: Option<tokio::process::Child>,- pub usbmuxd_started: Option<Instant>,- /// usbmuxd 起来就退出时,下次重启不早于这个时间(退避)- pub usbmuxd_retry_at: Option<Instant>,- pub usbmuxd_delay: Duration,/// 连续列不出设备的次数(usbmuxd 抖一下不立刻当成离线)pub list_errors: u32,pub offline_since: Option<Instant>,@@ -263,6 +266,11 @@ pub(crate) struct Inner {/// 滑动等列表停下时最后读到的树([`crate::tools`] 的 `settle` 拿来当比较的起点)pub swiped_tree: Option<(Instant, ictl_wda::elements::Tree)>,pub dedup: Dedup,+ /// 各设备最近一次因为证书自动重签的时间(按 UDID,换设备、重插也记着):[`crate::supervise::CERT_HEAL_EVERY`] 内+ /// 不再自动重签同一台,免得重签也治不好时反复签+ pub cert_heals: HashMap<String, Instant>,+ /// 本机的签名证书还在不在团队里,和查的时间(会话检查、自动重签前联网查;doctor 显示它,不在持锁时联网)+ pub own_cert: Option<(Instant, bool)>,pub next_resign: Instant,pub next_session_check: Instant,}@@ -358,17 +366,14 @@ impl Daemon {resigning: false,wda_misses: Misses::default(),backoff: Backoff::default(),- mux: MuxWatch::default(),- usbmuxd: None,- usbmuxd_started: None,- usbmuxd_retry_at: None,- usbmuxd_delay: Duration::ZERO,list_errors: 0,offline_since: Some(now),hid_used: None,elements_cache: None,swiped_tree: None,dedup: Dedup::default(),+ cert_heals: HashMap::new(),+ own_cert: None,// 启动一分钟后再做第一次重签检查和会话验证,先让设备就绪next_resign: now + Duration::from_secs(60),next_session_check: now + Duration::from_secs(90),@@ -468,9 +473,14 @@ impl Daemon {g.dev.device_profile = DeviceProfile::Missing;return;};+ g.dev.foreign_wda = None;g.dev.device_profile = match d.installed_profiles().await {- Ok(ps) => match wda_profile_expiry(&ps, g.persisted.team_id.as_deref(), &bundle, &d.udid) {- Some(t) => DeviceProfile::Expires(t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()),+ Ok(ps) => match wda_profile(&ps, g.persisted.team_id.as_deref(), &bundle, &d.udid) {+ Some(p) => {+ let keys = self.account().local_public_keys();+ g.dev.foreign_wda = (!keys.is_empty()).then(|| !p.signed_with_any(&keys));+ DeviceProfile::Expires(p.expires.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs())+ }None => DeviceProfile::Missing,},Err(e) => {@@ -655,6 +665,7 @@ impl Daemon {Request::Swipe { from, to, seconds } => self.swipe(g, from, to, seconds).await,Request::TypeText { text, submit } => self.type_text(g, &text, submit).await,Request::PressButton { button } => self.press_button(g, &button).await,+ Request::Touch { phase, x, y } => self.touch(g, phase, x, y).await,Request::ListApps { include_system } => self.list_apps(g, include_system).await@@ -700,21 +711,11 @@ impl Daemon {pub async fn shutdown(&self) {let mut g = self.inner.lock().await;self.log.log(ictl_l10n::log_tr!("收到停止信号,退出", "Received stop signal, exiting"));- // 先停 HID 媒体流、runner(经 usbmuxd),再停 usbmuxd+ // 停 HID 媒体流、runner(经系统的 usbmuxd)self.drop_session(&mut g).await;- if let Some(mut c) = g.usbmuxd.take() {- stop_child(&mut c).await;- }}}-/// Kills a child and waits for it, but not forever: a process stuck in the kernel (a USB call that never returns)-/// doesn't exit on SIGKILL, and whoever is stopping it holds the device lock-pub(crate) async fn stop_child(child: &mut tokio::process::Child) {- let _ = child.start_kill();- let _ = tokio::time::timeout(Duration::from_secs(5), child.wait()).await;-}-/// 参数检查(与设备无关,不必拿锁)/// Which path a request takes through [`Daemon::handle`]. Every variant is listed (no `_`), so a new request type/// doesn't compile until it is given a lane; a lane decides the lock, and every lane but the snapshot and re-signing@@ -747,6 +748,7 @@ fn lane(req: &Request) -> Lane {| Request::Swipe { .. }| Request::TypeText { .. }| Request::PressButton { .. }+ | Request::Touch { .. }| Request::ListApps { .. }| Request::LaunchApp { .. }| Request::TerminateApp { .. }@@ -832,6 +834,9 @@ fn check_request(req: &Request) -> Result<(), String> {MAX_WAIT_MS / 1000));}+ Request::Touch { x, y, .. } if !x.is_finite() || !y.is_finite() => {+ return Err(ictl_l10n::tr!("x、y 要是有效的数", "x and y must be valid numbers").into());+ }Request::WaitFor { text, .. } if text.is_empty() => {return Err(ictl_l10n::tr!("text 不能为空", "text can't be empty").into());}diff --git a/crates/ictl-daemon/src/devices.rs b/crates/ictl-daemon/src/devices.rsindex 8ca5a61..0cd9266 100644--- a/crates/ictl-daemon/src/devices.rs+++ b/crates/ictl-daemon/src/devices.rs@@ -89,8 +89,8 @@ impl Daemon {if self.cfg.udid.is_none() && infos.len() > 1 {lines.push(ictl_l10n::tr!(- "切换:iphone_select_device(UDID 或设备名),auto 改回自动选",- "Switch: iphone_select_device (UDID or device name), auto to go back to automatic"+ "切换:iphone-control select 或 iphone_select_device 工具(UDID 或设备名),auto 改回自动选",+ "Switch: iphone-control select or the iphone_select_device tool (UDID or device name), auto to go back to automatic").into(),);@@ -107,8 +107,8 @@ impl Daemon {if q.eq_ignore_ascii_case("auto") || q == ictl_l10n::tr!("自动", "automatic") {if let Some(u) = &self.cfg.udid {return Err(ictl_l10n::trf!(- "IPHONE_UDID 固定为 {u};要改回自动选,先在 .env 里清掉它再重建容器(或重启守护进程)",- "IPHONE_UDID pins {u}; to go back to automatic, remove it from .env and recreate the container (or restart the daemon)"+ "IPHONE_UDID 固定为 {u};要改回自动选,先从 ~/.config/iphone-control/env 里删掉它,再重启守护进程",+ "IPHONE_UDID pins {u}; to go back to automatic, remove it from ~/.config/iphone-control/env and restart the daemon"));}g.persisted.selected_udid = None;@@ -116,7 +116,7 @@ impl Daemon {return Ok(match g.info.as_ref().filter(|_| g.device.is_some()) {Some(i) => ictl_l10n::trf!("已改回自动选;正在控制 {},它断开时换成别的接着的设备", "Back to automatic; controlling {}, switches to another connected device when it disconnects", device_label(i)),None if g.connected.is_empty() => ictl_l10n::tr!("已改回自动选;现在没接设备,接上后自动控制它", "Back to automatic; no device connected now, it takes over the next one plugged in").into(),- None => ictl_l10n::tr!("已改回自动选;10 秒内接管接着的设备,先用 iphone_status 确认就绪", "Back to automatic; it takes over a connected device within 10 seconds, check readiness with iphone_status first").into(),+ None => ictl_l10n::tr!("已改回自动选;10 秒内接管接着的设备,先用 iphone-control status 或 iphone_status 确认就绪", "Back to automatic; it takes over a connected device within 10 seconds, check readiness with iphone-control status or iphone_status first").into(),});}let infos = self.connected_infos(g);@@ -125,8 +125,8 @@ impl Daemon {&& !u.eq_ignore_ascii_case(&target.udid){return Err(ictl_l10n::trf!(- "IPHONE_UDID 固定为 {u};要换设备,先改 .env 里的 IPHONE_UDID 再重建容器(或重启守护进程)",- "IPHONE_UDID pins {u}; to switch devices, change IPHONE_UDID in .env and recreate the container (or restart the daemon)"+ "IPHONE_UDID 固定为 {u};要换设备,先改 ~/.config/iphone-control/env 里的 IPHONE_UDID,再重启守护进程",+ "IPHONE_UDID pins {u}; to switch devices, change IPHONE_UDID in ~/.config/iphone-control/env and restart the daemon"));}if self.cfg.udid.is_none() {@@ -156,8 +156,8 @@ impl Daemon {)};Ok(ictl_l10n::trf!(- "已切换到 {label},之后固定控制这台。状态:{};WDA 起来要 10~60 秒,先用 iphone_status 确认就绪{pin}",- "Switched to {label}; it stays selected from now on. State: {}; WDA takes 10-60 seconds to start, check readiness with iphone_status first{pin}",+ "已切换到 {label},之后固定控制这台。状态:{};WDA 起来要 10~60 秒,先用 iphone-control status 或 iphone_status 确认就绪{pin}",+ "Switched to {label}; it stays selected from now on. State: {}; WDA takes 10-60 seconds to start, check readiness with iphone-control status or iphone_status first{pin}",g.state.describe()))}diff --git a/crates/ictl-daemon/src/devtools.rs b/crates/ictl-daemon/src/devtools.rsindex c8a0b2c..1d95416 100644--- a/crates/ictl-daemon/src/devtools.rs+++ b/crates/ictl-daemon/src/devtools.rs@@ -201,8 +201,8 @@ impl Daemon {let p = std::path::Path::new(path);if !p.exists() {return Err(ictl_l10n::trf!(- "找不到 {path}(路径要在运行守护进程的机器上,容器部署时是容器里的路径)",- "{path} not found (the path is on the machine that runs the daemon; inside the container for a container deployment)"+ "找不到 {path}(路径要在运行守护进程的机器上)",+ "{path} not found (the path is on the machine that runs the daemon)"));}device.install(p).await.map_err(|e| e.to_string())?;diff --git a/crates/ictl-daemon/src/doctor.rs b/crates/ictl-daemon/src/doctor.rsindex 2aea478..d35d254 100644--- a/crates/ictl-daemon/src/doctor.rs+++ b/crates/ictl-daemon/src/doctor.rs@@ -3,6 +3,7 @@use std::time::Duration;use crate::core::{Daemon, DeviceProfile, Inner};+use crate::machine::DeviceState;impl Daemon {pub(crate) async fn doctor(&self, g: &mut Inner) -> String {@@ -14,9 +15,7 @@ impl Daemon {Ok(_) => out.push(ictl_l10n::tr!("✅ usbmuxd 在运行", "✅ usbmuxd is running").into()),Err(e) => {out.push(ictl_l10n::trf!("❌ 连不上 usbmuxd:{e}\n → {}", "❌ Can't reach usbmuxd: {e}\n → {}",- if self.cfg.manage_usbmuxd {- ictl_l10n::tr!("由守护进程自动拉起,看数据目录 logs/usbmuxd.log;宿主机已有 usbmuxd 服务时设 ICTL_MANAGE_USBMUXD=0", "the daemon starts it itself, see logs/usbmuxd.log in the data directory; if the host already runs a usbmuxd service, set ICTL_MANAGE_USBMUXD=0")- } else if cfg!(target_os = "macos") {+ if cfg!(target_os = "macos") {ictl_l10n::tr!("macOS 自带 usbmuxd,应一直在运行:sudo launchctl kickstart -k system/com.apple.usbmuxd", "macOS ships usbmuxd and it should always be running: sudo launchctl kickstart -k system/com.apple.usbmuxd")} else {ictl_l10n::tr!("用的是系统的 usbmuxd 服务(插上手机时由 udev 拉起):确认已安装 usbmuxd、手机已插好", "using the system usbmuxd service (udev starts it when the phone is plugged in): make sure usbmuxd is installed and the phone is plugged in")@@ -67,7 +66,10 @@ impl Daemon {(None, _) if self.pinned(g).is_some() && !g.connected.is_empty() => {let p = self.pinned(g).unwrap_or_default();let how = if self.cfg.udid.is_some() {- ictl_l10n::tr!("或改 .env 里的 IPHONE_UDID", "or change IPHONE_UDID in .env")+ ictl_l10n::tr!(+ "或改 ~/.config/iphone-control/env 里的 IPHONE_UDID",+ "or change IPHONE_UDID in ~/.config/iphone-control/env"+ )} else {ictl_l10n::tr!("或 iphone-control select 换成接着的另一台(auto 改回自动选)",@@ -82,9 +84,7 @@ impl Daemon {}(None, _) => {out.push(- if self.cfg.manage_usbmuxd {- ictl_l10n::tr!("❌ 守护进程看不到手机\n → 等 30 秒,会自动重启 usbmuxd;仍不行就重启容器(或守护进程)", "❌ The daemon can't see the phone\n → wait 30 seconds, usbmuxd restarts automatically; if that doesn't help, restart the container (or the daemon)")- } else if cfg!(target_os = "macos") {+ if cfg!(target_os = "macos") {ictl_l10n::tr!("❌ 守护进程看不到手机\n → 重新插拔数据线;仍不行就 sudo launchctl kickstart -k system/com.apple.usbmuxd", "❌ The daemon can't see the phone\n → replug the cable; if that doesn't help, sudo launchctl kickstart -k system/com.apple.usbmuxd")} else {ictl_l10n::tr!("❌ 守护进程看不到手机\n → 重新插拔数据线;仍不行就 sudo systemctl restart usbmuxd", "❌ The daemon can't see the phone\n → replug the cable; if that doesn't help, sudo systemctl restart usbmuxd")@@ -165,6 +165,46 @@ impl Daemon {.into(),),}+ // 描述文件有效不代表能启动:签 WDA 的证书一被吊销(同一个 Apple ID 在别处新建证书、满了吊销旧的),+ // 每台设备上用它签的 WDA 都起不来+ match (g.device.is_some(), g.dev.foreign_wda) {+ (true, Some(true)) if g.state == DeviceState::Ready => out.push(ictl_l10n::tr!(+ "⚠️ 这台设备上的 WDA 不是本机的签名证书签的(别的机器或旧的数据目录签的) 现在能用;签它的证书一被吊销就起不来,那时守护进程会自动重签",+ "⚠️ The WDA on this device wasn't signed with this machine's certificate (another machine or an old data directory signed it) works now; once that certificate is revoked it won't start, and the daemon re-signs it then"+ ).into()),+ (true, Some(true)) => {+ out.push(ictl_l10n::tr!(+ "❌ 这台设备上的 WDA 不是本机的签名证书签的(别的机器或旧的数据目录签的,签它的证书多半已被吊销)\n → iphone-control sign",+ "❌ The WDA on this device wasn't signed with this machine's certificate (another machine or an old data directory signed it, and that certificate was most likely revoked)\n → iphone-control sign"+ ).into());+ fails += 1;+ }+ (true, Some(false)) => out.push(+ ictl_l10n::tr!(+ "✅ 这台设备上的 WDA 是本机的签名证书签的",+ "✅ The WDA on this device was signed with this machine's certificate"+ )+ .into(),+ ),+ _ => {}+ }+ match g.own_cert {+ Some((at, true)) => out.push(ictl_l10n::trf!(+ "✅ 本机的签名证书还在 Apple ID 的团队里 {}前查过",+ "✅ This machine's signing certificate is still in the Apple ID's team checked {} ago",+ ago(at.elapsed())+ )),+ Some((at, false)) => {+ out.push(ictl_l10n::trf!(+ "❌ 本机的签名证书已不在 Apple ID 的团队里({}前查的):别处新建证书时把它吊销了,用它签的 WDA 都起不来\n → iphone-control sign(新建证书并重签这台;其他设备切过去时会自动重签)",+ "❌ This machine's signing certificate is no longer in the Apple ID's team (checked {} ago): it was revoked when a certificate was created elsewhere, so WDA signed with it won't start\n → iphone-control sign (creates a new certificate and re-signs this device; other devices are re-signed automatically when you switch to them)",+ ago(at.elapsed())+ ));+ fails += 1;+ }+ // 守护进程启动约 90 秒后的会话检查才第一次查+ None => {}+ }}None => {out.push(@@ -234,3 +274,23 @@ impl Daemon {out.join("\n")}}++/// 多久以前,粗到分钟、小时+fn ago(d: Duration) -> String {+ let m = d.as_secs() / 60;+ if m < 60 { ictl_l10n::trf!("{} 分钟", "{} min", m.max(1)) } else { ictl_l10n::trf!("{} 小时", "{} h", m / 60) }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ago_rounds_to_minutes_and_hours() {+ ictl_l10n::with_lang(ictl_l10n::Lang::Zh, || {+ assert_eq!(ago(Duration::from_secs(5)), "1 分钟");+ assert_eq!(ago(Duration::from_secs(59 * 60)), "59 分钟");+ assert_eq!(ago(Duration::from_secs(25 * 3600)), "25 小时");+ });+ }+}diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rsindex 1299efa..b912ac2 100644--- a/crates/ictl-daemon/src/lib.rs+++ b/crates/ictl-daemon/src/lib.rs@@ -1,7 +1,7 @@//! 守护进程:唯一持有设备的进程。替代 toolkit 的 supervisor.sh + 重签定时器 + notify.sh。//!//! - 状态机([`machine::DeviceState`],docs/architecture.md §3)每 10 秒推进一次([`supervise`])-//! - usbmuxd 作为子进程看护;容器无 udev,靠 sysfs 发现漏掉的设备并重启它+//! - usbmuxd 用系统的(macOS 自带,Linux 是 usbmuxd 包,插上手机时由 udev 拉起)//! - 控制接口:Unix socket,每行一个 JSON([`protocol`]),MCP 和 CLI 都通过它访问设备//! - 并发模型见 [`core`]diff --git a/crates/ictl-daemon/src/machine.rs b/crates/ictl-daemon/src/machine.rsindex 4bbe443..8f11aaa 100644--- a/crates/ictl-daemon/src/machine.rs+++ b/crates/ictl-daemon/src/machine.rs@@ -89,14 +89,6 @@ impl Backoff {}}-/// 容器里没有 udev,usbmuxd 收不到热插拔:sysfs 上有 Apple 设备但 usbmuxd 看不到,连续 3 次就该重启它-#[derive(Debug, Default)]-pub struct MuxWatch {- misses: u32,-}--pub const USBMUXD_MISS_LIMIT: u32 = 3;-/// 接着几台设备时控制哪一台,返回在 `udids` 里的下标:/// - 选定了(`IPHONE_UDID` 或运行中选的):只认那一台,没接就是没有(不换成别的,免得操作、自动解锁落到另一台上)/// - 没选定:正在控制的那台还接着就继续用它,不因 usbmuxd 列表顺序变化换台;没有正在控制的才取第一台@@ -108,24 +100,6 @@ pub fn pick_device(udids: &[&str], pinned: Option<&str>, current: Option<&str>)}}-impl MuxWatch {- /// 返回 true 表示该重启 usbmuxd 了。`on_usb`:sysfs 里的 iPhone/iPad 台数;`seen`:usbmuxd 认到的台数。- /// 比台数而不是「要控制的那台在不在」:那台没接、另一台接着时不该重启;- /// 也不是「看没看到任何一台」:已经接着一台时再插一台,没有 udev 的 usbmuxd 认不到它- pub fn observe(&mut self, on_usb: usize, seen: usize) -> bool {- if seen >= on_usb {- self.misses = 0;- return false;- }- self.misses += 1;- if self.misses >= USBMUXD_MISS_LIMIT {- self.misses = 0;- return true;- }- false- }-}-/// WDA 连续几次探测不通才算挂(避免一次慢请求就重启它)#[derive(Debug, Default)]pub struct Misses(u32);@@ -204,30 +178,6 @@ mod tests {assert_eq!(pick_device(&[], None, None), None);}- /// 回归用例 #7:sysfs 有设备但 usbmuxd 看不到,连续 3 次才重启- #[test]- fn usbmuxd_restart_after_three_misses() {- let mut w = MuxWatch::default();- assert!(!w.observe(1, 0));- assert!(!w.observe(1, 0));- assert!(w.observe(1, 0));- assert!(!w.observe(1, 0), "重启后重新计数");- assert!(!w.observe(0, 0), "USB 上没有设备不算漏");- assert!(!w.observe(1, 1));- }-- /// 接着 iPad 时再插 iPhone:usbmuxd 只认到 1 台,也要重启- #[test]- fn usbmuxd_restart_when_a_second_device_is_missed() {- let mut w = MuxWatch::default();- assert!(!w.observe(2, 1));- assert!(!w.observe(2, 1));- assert!(w.observe(2, 1));- assert!(!w.observe(2, 2));- // 拔掉一台、usbmuxd 还没更新列表:不算漏- assert!(!w.observe(1, 2));- }-#[test]fn misses_need_three_in_a_row() {let mut m = Misses::default();diff --git a/crates/ictl-daemon/src/notify.rs b/crates/ictl-daemon/src/notify.rsindex 31b7740..90a8c4c 100644--- a/crates/ictl-daemon/src/notify.rs+++ b/crates/ictl-daemon/src/notify.rs@@ -12,8 +12,16 @@ pub enum Event {NeedsAutomationPin,WdaRecovered,UnlockDisabled,- DeviceOffline { minutes: u64 },- DeviceOnline { minutes: u64 },+ DeviceOffline {+ minutes: u64,+ },+ DeviceOnline {+ minutes: u64,+ },+ /// 签名时新建了证书;`revoked`:团队里证书满了,还吊销了一张旧的+ CertificateChanged {+ revoked: bool,+ },}impl Event {@@ -27,6 +35,7 @@ impl Event {Self::UnlockDisabled => "unlock",Self::DeviceOffline { .. } => "offline",Self::DeviceOnline { .. } => "online",+ Self::CertificateChanged { .. } => "cert",}}@@ -42,6 +51,7 @@ impl Event {Self::UnlockDisabled,Self::DeviceOffline { minutes: 10 },Self::DeviceOnline { minutes: 12 },+ Self::CertificateChanged { revoked: true },]}@@ -74,6 +84,14 @@ impl Event {ictl_l10n::tr!("连不上手机:检查 USB 线、手机是否没电关机。重新连上后会自动恢复。", "Can't reach the phone: check the USB cable and whether the phone ran out of battery. It recovers automatically once reconnected.").into(),),Self::DeviceOnline { minutes } => (ictl_l10n::tr!("iPhone 已重新连上", "iPhone reconnected").into(), ictl_l10n::trf!("离线约 {minutes} 分钟,正在自动恢复。", "Offline for about {minutes} minutes, recovering automatically.")),+ Self::CertificateChanged { revoked: true } => (+ ictl_l10n::tr!("签名证书换了,旧证书已被吊销", "Signing certificate replaced, an old one was revoked").into(),+ ictl_l10n::tr!("这次签名新建了证书;免费 Apple ID 最多两张,满了就吊销了一张旧的。用旧证书签的 WDA(可能在别的设备,或用同一个 Apple ID 的其他机器、其他侧载工具上)起不来了:这里控制的设备切过去时会自动重签,也可以运行 iphone-control sign。", "This signing created a new certificate; a free Apple ID holds at most two, so an old one was revoked. WDA signed with it (maybe on other devices, or on other machines or sideloading tools using the same Apple ID) won't start any more: devices controlled here are re-signed automatically when you switch to them, or run iphone-control sign.").into(),+ ),+ Self::CertificateChanged { revoked: false } => (+ ictl_l10n::tr!("签名证书换了", "Signing certificate replaced").into(),+ ictl_l10n::tr!("这次签名新建了证书(第一次在这台机器上签名,或原来的证书已被别处吊销)。之前用别的证书签的设备,WDA 起不来时会自动重签,也可以运行 iphone-control sign。", "This signing created a new certificate (the first signing on this machine, or the previous one was revoked elsewhere). Devices signed with another certificate are re-signed automatically when their WDA won't start, or run iphone-control sign.").into(),+ ),}}}@@ -88,7 +106,8 @@ pub struct Dedup {fn cooldown(e: &Event) -> Option<Duration> {match e {Event::ResignFailed(_) | Event::SessionExpired(_) => Some(Duration::from_secs(20 * 3600)),- Event::WdaRecovered | Event::DeviceOnline { .. } => Some(Duration::ZERO),+ // 证书每换一次都要知道+ Event::WdaRecovered | Event::DeviceOnline { .. } | Event::CertificateChanged { .. } => Some(Duration::ZERO),_ => None,}}@@ -176,7 +195,7 @@ mod tests {uniq.dedup();assert_eq!(uniq.len(), names.len());// 新增事件时这里的数字要跟着改,提醒同时补样例- assert_eq!(names.len(), 7);+ assert_eq!(names.len(), 8);}#[test]diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rsindex 7e38859..7024760 100644--- a/crates/ictl-daemon/src/supervise.rs+++ b/crates/ictl-daemon/src/supervise.rs@@ -1,10 +1,9 @@-//! 巡检和后台任务:usbmuxd 看护、每 10 秒推进状态机、后台启动 WDA、重签、Apple ID 会话检查。+//! 巡检和后台任务:每 10 秒推进状态机、后台启动 WDA、重签(含证书出问题时自动重签)、Apple ID 会话检查。-use std::path::Path;use std::sync::Arc;use std::time::{Duration, Instant, UNIX_EPOCH};-use ictl_device::{Device, DeviceError, SYSFS_USB, Tunnel, UsbDevice};+use ictl_device::{Device, DeviceError, Tunnel, UsbDevice};use ictl_wda::{WdaClient, WdaError, WdaRunner, http::DeviceTransport};use crate::core::{Daemon, DeviceProfile, Inner, close_hid};@@ -17,9 +16,6 @@ const WDA_START_TIMEOUT: Duration = Duration::from_secs(120);/// HID 会话空闲这么久就关掉。它持有屏幕媒体流,开着时 iOS 当作屏幕被远程查看:不会自动锁屏,/// 还会弹「viewed remotely」通知。重开约 0.5 秒pub(crate) const HID_IDLE: Duration = Duration::from_secs(30);-/// usbmuxd 起来后这么久内就退出,算「起不来」,按退避重试-const USBMUXD_QUICK_EXIT: Duration = Duration::from_secs(30);-const USBMUXD_MAX_DELAY: Duration = Duration::from_secs(300);/// 连续这么多轮列不出设备才当作离线const LIST_ERRORS_OFFLINE: u32 = 3;/// 开发者镜像连续挂载失败这么多次就清缓存重新下载@@ -30,6 +26,8 @@ const RESIGN_TIMEOUT: Duration = Duration::from_secs(15 * 60);const SESSION_CHECK_TIMEOUT: Duration = Duration::from_secs(3 * 60);/// 换了设备或重新接上后,这么久内就检查一次要不要重签(离线期间可能过期了,不能等满 RESIGN_CHECK_HOURS)const RESIGN_CHECK_AFTER_CONNECT: Duration = Duration::from_secs(60);+/// 因为证书自动重签同一台设备的最短间隔:重签也治不好时(例如其实是没信任开发者)不反复签+pub(crate) const CERT_HEAL_EVERY: Duration = Duration::from_secs(6 * 3600);/// 后台启动 WDA 的结果pub(crate) enum StartOutcome {@@ -49,73 +47,12 @@ pub(crate) enum StartOutcome {}impl Daemon {- // ------------------------------------------------------------------ usbmuxd-- pub(crate) async fn ensure_usbmuxd(&self, g: &mut Inner, restart: bool) {- if !self.cfg.manage_usbmuxd {- return;- }- let exited = match g.usbmuxd.as_mut().map(|c| c.try_wait()) {- Some(Ok(None)) => None,- Some(Ok(Some(st))) => Some(st.to_string()),- Some(Err(e)) => Some(e.to_string()),- None => Some(String::new()),- };- if exited.is_none() && !restart {- return;- }- if !restart {- // 起来就退出(例如宿主机上已有 usbmuxd 占着 socket):退避重试,不要每 10 秒拆一次会话、写一行日志- if let Some(why) = exited.filter(|w| !w.is_empty())- && g.usbmuxd_started.is_some_and(|t| t.elapsed() < USBMUXD_QUICK_EXIT)- {- g.usbmuxd_delay = (g.usbmuxd_delay * 2).clamp(Duration::from_secs(10), USBMUXD_MAX_DELAY);- g.usbmuxd_retry_at = Some(Instant::now() + g.usbmuxd_delay);- g.usbmuxd_started = None;- self.log.log(&ictl_l10n::log_trf!("usbmuxd 启动后很快就退出了({why}),{} 秒后再试;宿主机已在运行 usbmuxd 时设 ICTL_MANAGE_USBMUXD=0", "usbmuxd exited right after starting ({why}), retrying in {} seconds; if the host already runs usbmuxd, set ICTL_MANAGE_USBMUXD=0",- g.usbmuxd_delay.as_secs()- ));- }- if g.usbmuxd_retry_at.is_some_and(|t| Instant::now() < t) {- return;- }- }- // 经旧 usbmuxd 建立的连接(隧道、runner、WDA)都要失效:先停 HID 媒体流(还要经它),再停它- self.drop_session(g).await;- if let Some(mut c) = g.usbmuxd.take() {- crate::core::stop_child(&mut c).await;- }- let log_path = self.cfg.logs().join("usbmuxd.log");- rotate_before_append(&log_path, crate::eventlog::MAX_BYTES);- let log = std::fs::OpenOptions::new().create(true).append(true).open(log_path);- let mut cmd = tokio::process::Command::new(&self.cfg.usbmuxd_bin);- cmd.args(["-U", "root", "-f"]).kill_on_drop(true);- if let Ok(f) = log- && let Ok(f2) = f.try_clone()- {- cmd.stdout(f).stderr(f2);- }- match cmd.spawn() {- Ok(c) => {- g.usbmuxd = Some(c);- g.usbmuxd_started = Some(Instant::now());- if g.usbmuxd_retry_at.take().is_none() {- g.usbmuxd_delay = Duration::ZERO;- }- self.log.log(ictl_l10n::log_tr!("usbmuxd 已(重新)启动", "usbmuxd (re)started"));- tokio::time::sleep(Duration::from_secs(1)).await;- }- Err(e) => self.log.log(&ictl_l10n::log_trf!("启动 usbmuxd 失败:{e}", "Starting usbmuxd failed: {e}")),- }- }-// ------------------------------------------------------------------ 状态机/// 每 10 秒一次。有请求在用设备就跳过这一轮(巡检不排队,下一轮再来)pub async fn tick(self: Arc<Self>) {let Ok(mut g) = self.inner.try_lock() else { return };let g = &mut *g;- self.ensure_usbmuxd(g, false).await;if g.tunnel.as_ref().is_some_and(Tunnel::hid_open) && g.hid_used.is_none_or(|t| t.elapsed() >= HID_IDLE) {close_hid(g).await;@@ -155,18 +92,10 @@ impl Daemon {self.note_connected(g, devices).await;let pinned = self.pinned(g);let udids: Vec<&str> = g.connected.iter().map(|d| d.udid.as_str()).collect();- let current = g.device.as_ref().map(|d| d.udid.as_str());+ // just started, nothing controlled yet: in automatic mode go on with the last device that was ready (kept in+ // state.json), not whichever usbmuxd happens to list first+ let current = g.device.as_ref().map(|d| d.udid.as_str()).or(g.persisted.screen_udid.as_deref());let target = crate::machine::pick_device(&udids, pinned.as_deref(), current).map(|i| g.connected[i].clone());- // 只在容器里(自己看护 usbmuxd、没有 udev)需要;用系统的 usbmuxd 服务时插拔由 udev 处理,也重启不了它- let on_usb = ictl_device::ios_usb_count(Path::new(SYSFS_USB));- if self.cfg.manage_usbmuxd && g.mux.observe(on_usb, g.connected.len()) {- self.log.log(&ictl_l10n::log_trf!(- "USB 上有 {on_usb} 台 iPhone/iPad,usbmuxd 只认到 {} 台,重启 usbmuxd",- "{on_usb} iPhone/iPad on USB but usbmuxd only sees {}, restarting usbmuxd",- g.connected.len()- ));- self.ensure_usbmuxd(g, true).await;- }match target {None => self.offline(g).await,@@ -363,7 +292,7 @@ impl Daemon {}/// 后台启动做完了就收结果- async fn poll_start(&self, g: &mut Inner) {+ async fn poll_start(self: &Arc<Self>, g: &mut Inner) {if !g.starting.as_ref().is_some_and(|h| h.is_finished()) {return;}@@ -382,6 +311,8 @@ impl Daemon {if g.info.as_ref().is_some_and(|i| i.product_type.starts_with("iPhone")) {client.keep_stream_upright();}+ // the live viewer's picture at 60 fps, so it follows the pointer (see `WdaClient::fast_stream`)+ client.fast_stream();g.wda = Some(client);// 状态在下面 online() 的健康检查里变成 Ready}@@ -415,21 +346,142 @@ impl Daemon {}StartOutcome::Wda(e) => {g.backoff.failed(Instant::now());+ // StartFailed 自己就以「WDA 启动失败:」开头,日志和状态里再加一遍就重复了+ let e = match e {+ WdaError::StartFailed(m) => m,+ e => e.to_string(),+ };self.log.log(&ictl_l10n::log_trf!("WDA 启动失败:{e}", "WDA failed to start: {e}"));- self.set_state(g, DeviceState::WdaStarting { last_error: Some(e.to_string()) });+ let refused = ictl_wda::runner::launch_refused(&e);+ self.set_state(g, DeviceState::WdaStarting { last_error: Some(e) });+ if refused {+ self.maybe_heal_certificate(g);+ }}}}+ /// 设备拒绝启动 WDA(只报 unexpected response)时,看是不是证书的问题,是就自动重签这台(见 `ictl_sign` 的模块说明):+ /// 设备上的 WDA 不是本机的证书签的(别的机器、旧的数据目录签的,签它的证书多半被吊销了),或本机的证书已不在团队里+ /// (别处新建证书时把它吊销了)。都不是就多半是还没信任开发者,留给用户(状态里有提示)。+ /// 同一台 [`CERT_HEAL_EVERY`] 内只自动重签一次+ fn maybe_heal_certificate(self: &Arc<Self>, g: &mut Inner) {+ let Some(udid) = g.device.as_ref().map(|d| d.udid.clone()) else { return };+ if g.resigning || g.persisted.wda_bundle.is_none() {+ return;+ }+ if g.cert_heals.get(&udid).is_some_and(|t| t.elapsed() < CERT_HEAL_EVERY) {+ return;+ }+ g.cert_heals.insert(udid.clone(), Instant::now());+ tokio::task::spawn_local(self.clone().heal_certificate(udid, g.dev.foreign_wda));+ }++ async fn heal_certificate(self: Arc<Self>, udid: String, foreign: Option<bool>) {+ if self.account().selected_email().await.is_err() {+ return;+ }+ let why = if foreign == Some(true) {+ ictl_l10n::tr!(+ "这台设备上的 WDA 不是本机的签名证书签的(别的机器或旧的数据目录签的,签它的证书多半已被吊销)",+ "the WDA on this device wasn't signed with this machine's certificate (another machine or an old data directory signed it, and that certificate was most likely revoked)"+ )+ } else {+ match self.check_own_certificate().await {+ Some(false) => ictl_l10n::tr!(+ "本机的签名证书已不在 Apple ID 的团队里(别处新建证书时把它吊销了)",+ "this machine's signing certificate is no longer in the Apple ID's team (it was revoked when a certificate was created elsewhere)"+ ),+ // 证书没问题(或查不了):多半是还没信任开发者+ _ => return,+ }+ };+ {+ let mut g = self.inner.lock().await;+ // 查证书期间切到了别的设备,或用户已经在重签了+ if g.device.as_ref().map(|d| d.udid.as_str()) != Some(udid.as_str()) || g.resigning {+ return;+ }+ self.log.log(&ictl_l10n::log_trf!(+ "WDA 起不来:{why},自动重签这台设备",+ "WDA won't start: {why}; re-signing this device automatically"+ ));+ self.set_state(+ &mut g,+ DeviceState::WdaStarting {+ last_error: Some(ictl_l10n::trf!(+ "{why}。正在自动重签这台设备,约 1–2 分钟,保持设备解锁",+ "{why}. Re-signing this device automatically, about 1–2 minutes; keep it unlocked"+ )),+ },+ );+ self.publish(&g);+ }+ if let Err(e) = self.resign_now(true).await {+ let mut g = self.inner.lock().await;+ self.notify(&mut g, Event::ResignFailed(e));+ }+ }++ /// 联网查本机的签名证书还在不在团队里,记进 `own_cert`(doctor 显示)。登录不了、查不了返回 None+ async fn check_own_certificate(&self) -> Option<bool> {+ let account = self.account();+ // plume_core 的 future 不是 Send,放到阻塞线程里 block_on(同重签);也不持锁+ let r = tokio::task::spawn_blocking(move || {+ tokio::runtime::Handle::current().block_on(async move {+ tokio::time::timeout(SESSION_CHECK_TIMEOUT, async {+ account.session().await?.own_certificate_listed().await+ })+ .await+ })+ })+ .await;+ match r {+ Ok(Ok(Ok(Some(listed)))) => {+ self.inner.lock().await.own_cert = Some((Instant::now(), listed));+ Some(listed)+ }+ Ok(Ok(Err(e))) => {+ tracing::warn!(+ "{}",+ ictl_l10n::log_trf!(+ "查本机的签名证书失败:{e}",+ "Checking this machine's signing certificate failed: {e}"+ )+ );+ None+ }+ _ => None,+ }+ }+// ------------------------------------------------------------------ 重签与会话async fn check_session(self: Arc<Self>) {let account = self.account();// plume_core 的 future 不是 Send,放到阻塞线程里 block_on(同重签);也不持锁- let r: Result<(), Option<String>> = tokio::task::spawn_blocking(move || {+ // 会话好的话顺便查本机的签名证书还在不在团队里(同一次登录)+ let r: Result<Option<bool>, Option<String>> = tokio::task::spawn_blocking(move || {tokio::runtime::Handle::current().block_on(async move {- match tokio::time::timeout(SESSION_CHECK_TIMEOUT, account.session()).await {- Ok(Ok(_)) => Ok(()),+ let check = async {+ let s = account.session().await?;+ Ok::<_, ictl_sign::SignError>(match s.own_certificate_listed().await {+ Ok(listed) => listed,+ // 会话是好的,只是这一步没查成:不算会话失效,记一笔+ Err(e) => {+ tracing::warn!(+ "{}",+ ictl_l10n::log_trf!(+ "查本机的签名证书失败:{e}",+ "Checking this machine's signing certificate failed: {e}"+ )+ );+ None+ }+ })+ };+ match tokio::time::timeout(SESSION_CHECK_TIMEOUT, check).await {+ Ok(Ok(listed)) => Ok(listed),Ok(Err(ictl_sign::SignError::NotLoggedIn)) => Err(None),Ok(Err(e)) => Err(Some(e.to_string())),Err(_) => Err(Some(ictl_l10n::trf!(@@ -444,7 +496,18 @@ impl Daemon {.unwrap_or_else(|e| Err(Some(ictl_l10n::trf!("会话检查任务异常:{e}", "Session check task failed: {e}"))));let mut g = self.inner.lock().await;match r {- Ok(()) => g.dedup.clear("session"),+ Ok(listed) => {+ g.dedup.clear("session");+ if let Some(l) = listed {+ g.own_cert = Some((Instant::now(), l));+ if !l {+ self.log.log(ictl_l10n::log_tr!(+ "本机的签名证书已不在 Apple ID 的团队里(别处新建证书时把它吊销了):用它签的 WDA 起不来,会自动重签",+ "This machine's signing certificate is no longer in the Apple ID's team (revoked when a certificate was created elsewhere): WDA signed with it won't start and gets re-signed automatically"+ ));+ }+ }+ }Err(None) => {}Err(Some(e)) => {self.log@@ -503,8 +566,8 @@ impl Daemon {let fetch = self.cfg.wda_unsigned_is_cache() && !unsigned.is_file();if fetch {self.log.log(&ictl_l10n::log_trf!(- "没有未签名的 WDA 包(不在镜像里运行),先下载 {}",- "No unsigned WDA package (not running in the image), downloading {} first",+ "还没有未签名的 WDA 包,先下载 {}",+ "No unsigned WDA package yet, downloading {} first",crate::wda_pkg::WDA_VERSION));}@@ -545,6 +608,22 @@ impl Daemon {g.resigning = false;let r = match r {Ok(s) => {+ if s.new_certificate {+ self.log.log(if s.revoked_certificate {+ ictl_l10n::log_tr!(+ "签名新建了证书,团队里的证书满了,吊销了一张旧的:用它签的 WDA 在所有设备上都起不来了",+ "Signing created a new certificate and revoked an old one (the team was full): WDA signed with it won't start on any device"+ )+ } else {+ ictl_l10n::log_tr!(+ "签名新建了证书(本机没有私钥,或原来的证书已不在团队里)",+ "Signing created a new certificate (no local key, or the previous one is no longer in the team)"+ )+ });+ self.notify(g, Event::CertificateChanged { revoked: s.revoked_certificate });+ }+ // 刚用它签成功,本机的证书肯定在团队里+ g.own_cert = Some((Instant::now(), true));let exp = s.profile.expires.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();g.persisted.team_id = Some(s.team_id);g.persisted.wda_bundle = Some(s.bundle_id);@@ -581,13 +660,6 @@ impl Daemon {}}-/// Keeps a log that a child appends to from growing without end. Only safe while nothing has it open-fn rotate_before_append(path: &Path, max: u64) {- if std::fs::metadata(path).is_ok_and(|m| m.len() >= max) {- let _ = std::fs::rename(path, path.with_extension("log.1"));- }-}-fn now_secs() -> u64 {std::time::SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()}diff --git a/crates/ictl-daemon/src/tools.rs b/crates/ictl-daemon/src/tools.rsindex c5d5209..b89b41f 100644--- a/crates/ictl-daemon/src/tools.rs+++ b/crates/ictl-daemon/src/tools.rs@@ -13,7 +13,7 @@ use ictl_wda::{Launch, WdaClient, WdaError};use crate::core::{Daemon, Inner, drop_tunnel, hid_supported, wda_down};use crate::imaging::{self, fmt_g};use crate::notify::Event;-use crate::protocol::{ALERT_BLOCKING, Response, TAP_MISSED};+use crate::protocol::{ALERT_BLOCKING, Response, TAP_MISSED, TouchPhase};/// 锁屏后至少等这么久再自动解锁:锁屏过渡没走完就唤醒,WDA 第一下上滑卡约 16 秒后报 `point.x != INFINITY`pub(crate) const LOCK_SETTLE: Duration = Duration::from_secs(3);@@ -78,7 +78,7 @@ impl Daemon {.screen.filter(|_| same).or(self.cfg.screen_fallback)- .ok_or_else(|| ictl_l10n::tr!("WDA 不可用,也不知道屏幕尺寸;等 WDA 起来一次,或在 .env 里设 SCREEN_W/SCREEN_H", "WDA is unavailable and the screen size is unknown; wait for WDA to start once, or set SCREEN_W/SCREEN_H in .env").into())+ .ok_or_else(|| ictl_l10n::tr!("WDA 不可用,也不知道屏幕尺寸;等 WDA 起来一次,或在 ~/.config/iphone-control/env 里设 SCREEN_W/SCREEN_H", "WDA is unavailable and the screen size is unknown; wait for WDA to start once, or set SCREEN_W/SCREEN_H in ~/.config/iphone-control/env").into())}/// 记下 WDA 报的界面旋转角:WDA 挂了以后 HID 点击要靠它换算横屏坐标(约 20 毫秒)@@ -173,11 +173,14 @@ impl Daemon {.collect();let how = if self.cfg.udid.is_some() {ictl_l10n::tr!(- "(IPHONE_UDID 固定了设备,要换先改 .env)",- " (IPHONE_UDID pins the device; change .env to switch)"+ "(IPHONE_UDID 固定了设备,要换先改 ~/.config/iphone-control/env)",+ " (IPHONE_UDID pins the device; change ~/.config/iphone-control/env to switch)")} else {- ictl_l10n::tr!(";用 iphone_select_device 切换", "; switch with iphone_select_device")+ ictl_l10n::tr!(+ ";用 iphone-control select 或 iphone_select_device 工具切换",+ "; switch with iphone-control select or the iphone_select_device tool"+ )};match (current, &pinned) {(None, Some(p)) => Some(ictl_l10n::trf!(@@ -483,6 +486,71 @@ impl Daemon {Ok(ictl_l10n::trf!("已点击 {pos}(经 HID)", "Tapped {pos} (via HID)"))}+ /// A finger following the web viewer's pointer, one HID report per call (see `Request::Touch`). The checks a+ /// gesture needs (unlocking, the orientation) are done once, when it touches down; moves and the lift only send+ /// their report on the open HID session, so the screen keeps up with the pointer+ pub(crate) async fn touch(&self, g: &mut Inner, phase: TouchPhase, x: f64, y: f64) -> Result<String, String> {+ let contact = match phase {+ TouchPhase::Prepare => {+ self.hid(g).await?;+ g.hid_used = Some(Instant::now());+ return Ok(String::new());+ }+ TouchPhase::Down => {+ self.ensure_unlocked(g).await?;+ // WDA knows which way the interface is turned (about 20 ms); without it, check with a screenshot+ let rot = match self.wda(g) {+ Some(w) => w.rotation().await.ok(),+ None => None,+ };+ let rot = match rot {+ Some(r) => {+ g.dev.wda_rotation = Some((Instant::now(), r));+ r+ }+ None => self.hid_touch_rotation(g).await?,+ };+ g.dev.touch_rotation = Some(rot);+ true+ }+ TouchPhase::Move => true,+ TouchPhase::Up => false,+ };+ let Some(rot) = g.dev.touch_rotation else {+ return Err(ictl_l10n::tr!("没有按下的手指,先发 down", "No finger is down; send down first").into());+ };+ if !contact {+ g.dev.touch_rotation = None;+ }+ // the open session straight away: looking up the screen size for every move would cost a WDA request each+ let open = g.tunnel.as_mut().and_then(|t| t.open_hid()).is_some();+ let r = if open {+ let h = g.tunnel.as_mut().and_then(|t| t.open_hid()).expect("checked above");+ h.rotation = rot;+ let r = h.touch(contact, x, y).await;+ g.hid_used = Some(Instant::now());+ match r {+ Ok(()) => Ok(()),+ Err(e) => {+ drop_tunnel(g).await;+ Err(ictl_l10n::trf!("HID 命令失败: {e}", "HID command failed: {e}"))+ }+ }+ } else {+ self.hid_do(g, move |h| {+ Box::pin(async move {+ h.rotation = rot;+ h.touch(contact, x, y).await+ })+ })+ .await+ };+ if r.is_err() {+ g.dev.touch_rotation = None;+ }+ r.map(|()| String::new())+ }+pub(crate) async fn tap_element(&self,g: &mut Inner,@@ -841,15 +909,17 @@ pub(crate) fn hid_rotation(w: u32, h: u32, known: Option<(Duration, Rotation)>)/// 两种按法各有设备不认:XCTest 的 home 在 iPhone 12 mini / iOS 26.4.1 上不起作用却报成功;IOHID 的 AC Home/// 在 iPhone 18 Pro Max / iOS 27.2.1 上基本不起作用(按住 0.05~0.5 秒都一样)。所以默认先 IOHID,/// `xctest_first` 时先 XCTest;[`HOME_SETTLE`] 内没回到主屏(或这一下报错)再换另一种补一次。-/// 同时返回回到主屏的是不是 XCTest 那一下(都没回到为 `None`),调用方记下来,这台设备下次先用它+/// 同时返回回到主屏的是不是 XCTest 那一下(都没回到为 `None`),调用方记下来,这台设备下次先用它。+/// 两种都没回到主屏时,再用第一种补按一次:App 刚到前台、转场动画没走完时 iPadOS 会把两下都忽略+/// (iPad mini 5 / iPadOS 26.6.1:启动 App 后马上按 Home,约三次有一次这样),转场完了再按就行async fn press_home(w: &mut WdaClient<DeviceTransport>,xctest_first: bool,) -> Result<(String, Option<bool>), WdaError> {let mut app = String::new();- let order = if xctest_first { [false, true] } else { [true, false] };+ let order = if xctest_first { [false, true, false] } else { [true, false, true] };for (i, via_hid) in order.into_iter().enumerate() {- let last = i == 1;+ let last = i == order.len() - 1;let sent = if via_hid { w.press_home_hid().await } else { w.press_button("home").await };let (way, other) = if via_hid { ("IOHID", "XCTest") } else { ("XCTest", "IOHID") };match sent {diff --git a/crates/ictl-daemon/src/watchdog.rs b/crates/ictl-daemon/src/watchdog.rsindex 7e6ece2..f9cb766 100644--- a/crates/ictl-daemon/src/watchdog.rs+++ b/crates/ictl-daemon/src/watchdog.rs@@ -5,7 +5,7 @@//! Everything that finishes work under the device lock (a request, a full supervision round) goes through//! [`crate::Daemon`]'s `publish`, which beats the heartbeat. A round that finds the lock busy skips without beating,//! so a stuck lock holder shows up as silence. The check runs on its own thread, so a blocked runtime is caught too.-//! The service manager (systemd `Restart=on-failure`, Docker `restart: unless-stopped`) starts a fresh daemon.+//! The service manager (systemd `Restart=on-failure`, launchd `KeepAlive`) starts a fresh daemon.use std::sync::Arc;use std::sync::atomic::{AtomicU64, Ordering};diff --git a/crates/ictl-daemon/src/wda_pkg.rs b/crates/ictl-daemon/src/wda_pkg.rsindex 32bdb9e..0c6c711 100644--- a/crates/ictl-daemon/src/wda_pkg.rs+++ b/crates/ictl-daemon/src/wda_pkg.rs@@ -1,6 +1,4 @@-//! 未签名的 WDA 包。镜像里自带(docker/Dockerfile 的 wda 阶段);从源码运行时没有它,-//! 第一次签名前按同一版本下载 Appium 官方构建的真机包、核对 sha256,重新打成 ipa 放进数据目录。-//! 版本和校验和必须与 Dockerfile 一致(单测核对)。+//! 未签名的 WDA 包:第一次签名前按固定版本下载 Appium 官方构建的真机包、核对 sha256,重新打成 ipa 放进数据目录。use std::path::Path;use std::time::Duration;@@ -9,8 +7,6 @@ use sha2::{Digest, Sha256};pub const WDA_VERSION: &str = "v16.15.3";pub const WDA_SHA256: &str = "2176793538d902f6b1e61291e9997f68d306541f222ea715d256a7c6ce9d4fc5";-/// 镜像里自带的那份-pub const IMAGE_PATH: &str = "/usr/share/iphone-control/WDA-unsigned.ipa";fn url() -> String {format!("https://github.com/appium/WebDriverAgent/releases/download/{WDA_VERSION}/WebDriverAgentRunner-Runner.zip")@@ -59,16 +55,3 @@ pub async fn ensure(dest: &Path) -> Result<(), String> {}Ok(())}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn matches_dockerfile() {- let dockerfile = include_str!("../../../docker/Dockerfile");- assert!(dockerfile.contains(&format!("ARG WDA_VERSION={WDA_VERSION}\n")), "WDA_VERSION 和 Dockerfile 不一致");- assert!(dockerfile.contains(&format!("ARG WDA_SHA256={WDA_SHA256}\n")), "WDA_SHA256 和 Dockerfile 不一致");- assert!(dockerfile.contains(&format!("COPY --from=wda /out/WDA-unsigned.ipa {IMAGE_PATH}\n")));- }-}diff --git a/crates/ictl-device/src/hid.rs b/crates/ictl-device/src/hid.rsindex bb5b300..793fa11 100644--- a/crates/ictl-device/src/hid.rs+++ b/crates/ictl-device/src/hid.rs@@ -8,7 +8,9 @@ use std::time::Duration;use idevice::{ReadWrite, RsdService,- core_device::hid::{ButtonState, IndigoHidClient, UniversalHidServiceClient},+ core_device::hid::{+ ButtonState, IndigoHidClient, TOUCHSCREEN_STATE_CONTACT, TOUCHSCREEN_STATE_RELEASE, UniversalHidServiceClient,+ },rsd::RsdHandshake,tcp::handle::AdapterHandle,};@@ -171,6 +173,18 @@ impl HidSession {.await}+ /// One sample of a finger that follows the user's pointer (the web viewer): `contact` true puts the finger at the+ /// point (the first one touches down, later ones move it), false lifts it there. iOS works out taps, long presses+ /// and the speed of a swipe from these samples and their timing, the same way as from a real finger+ pub async fn touch(&mut self, contact: bool, x: f64, y: f64) -> Result<()> {+ let (hx, hy) = self.hid_point((x, y));+ let state = if contact { TOUCHSCREEN_STATE_CONTACT } else { TOUCHSCREEN_STATE_RELEASE };+ limit(ictl_l10n::tr!("HID 触摸", "HID touch"), Duration::from_secs(5), async {+ Ok(self.touch.send_touchscreen(state, hx, hy, None).await?)+ })+ .await+ }+pub async fn press(&mut self, button: Button) -> Result<()> {let (page, code, hold) = button.usage();limit(ictl_l10n::tr!("HID 按键", "HID key press"), Duration::from_secs(10), async {diff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rsindex 16cd1eb..b4f9ef4 100644--- a/crates/ictl-device/src/lib.rs+++ b/crates/ictl-device/src/lib.rs@@ -1,6 +1,6 @@//! 设备层:一台 iPhone 的全部底层能力,基于 `idevice`。//!-//! - 发现:usbmuxd `get_devices`;容器里没有 udev,另用 sysfs 数 USB 上有几台 iPhone/iPad([`ios_usb_count`])+//! - 发现:usbmuxd `get_devices`;`doctor` 另用 sysfs(Linux)或 IORegistry(macOS)看 USB 上有没有 iPhone/iPad//! - 配对、设备信息、开发者模式:lockdown / amfi//! - 隧道:CoreDeviceProxy + jktcp 用户态 TCP 栈(免 root、不建网卡),RSD 握手([`Tunnel`])//! - 开发者镜像:`cryptexd::installed_ddi` / `install_ddi`(个性化 + TSS);DDI 下载见 [`ddi`]@@ -351,7 +351,7 @@ impl Device {}/// 发起配对:手机上弹「信任此电脑」。用户还没点时返回 [`DeviceError::PairingPending`],调用方应轮询重试。- /// 成功后配对记录交给 usbmuxd 保存(容器里即 `/var/lib/lockdown`)。+ /// 成功后配对记录交给 usbmuxd 保存(Linux 上是 `/var/lib/lockdown`,macOS 上是 `/var/db/lockdown`)。pub async fn pair(&self, host_name: &str) -> Result<()> {limit(ictl_l10n::tr!("配对", "pair"), Duration::from_secs(30), async {let mut mux = self.provider.addr.connect(0).await?;@@ -580,6 +580,11 @@ impl Tunnel {self.hid.is_some()}+ /// The HID session if it is already open (no request to the phone)+ pub fn open_hid(&mut self) -> Option<&mut HidSession> {+ self.hid.as_mut()+ }+/// 停掉 HID 会话(含屏幕媒体流),隧道保留pub async fn close_hid(&mut self) {if let Some(h) = self.hid.take() {diff --git a/crates/ictl-mcp/src/gate.rs b/crates/ictl-mcp/src/gate.rsnew file mode 100644index 0000000..2ae6fff--- /dev/null+++ b/crates/ictl-mcp/src/gate.rs@@ -0,0 +1,170 @@+//! The task gate: how a task started from the web viewer (`iphone-control viewer`) follows and steers the agent.+//!+//! The viewer runs an agent (Claude Code or Codex) with this MCP server and two environment variables:+//! [`GATE_ENV`], the path of a Unix socket the viewer listens on, and [`TOKEN_ENV`], the task's secret. With them+//! set, every tool call asks the viewer first (`before`): the viewer records it as a step of the task, holds it while+//! the task is paused or the user has taken over, and can refuse it. After the call the result goes back (`after`)+//! so the page shows it, screenshot included. [`CONFIRM_TOOL`] is listed too: the agent calls it before payments,+//! deletions, sending messages and the like, and it waits until the user approves or rejects on the page.+//!+//! The steps come from here rather than from the agent's own output, so they look the same whichever agent runs.+//! Without the variables nothing changes: the tool list and every call are as before.+//!+//! One JSON line each way per connection. Calls can wait as long as the user takes (a pause, a confirmation), so+//! there is no timeout; when the viewer is gone the call is refused instead of acting unsupervised.++use std::path::PathBuf;++use serde_json::{Map, Value, json};+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};++pub const GATE_ENV: &str = "ICTL_AGENT_GATE";+pub const TOKEN_ENV: &str = "ICTL_AGENT_TOKEN";+/// Listed only under a gate: asks the user on the page before a sensitive action+pub const CONFIRM_TOOL: &str = "iphone_confirm";+/// Text results longer than this are cut before they go to the page (the agent still gets all of it)+const MAX_TEXT: usize = 4000;++#[derive(Debug, Clone)]+pub struct Gate {+ path: PathBuf,+ token: String,+}++/// What the viewer says before a tool call+#[derive(Debug, PartialEq)]+pub enum Before {+ /// Go ahead; the call is step `step` of the task+ Go(u64),+ /// Don't run it; tell the agent why+ Refuse(String),+}++impl Gate {+ pub fn from_env() -> Option<Self> {+ let path = std::env::var_os(GATE_ENV).filter(|p| !p.is_empty())?;+ let token = std::env::var(TOKEN_ENV).ok().filter(|t| !t.is_empty())?;+ Some(Self { path: path.into(), token })+ }++ async fn ask(&self, mut msg: Value) -> std::io::Result<Value> {+ if let Some(o) = msg.as_object_mut() {+ o.insert("token".into(), self.token.clone().into());+ }+ let stream = tokio::net::UnixStream::connect(&self.path).await?;+ let (r, mut w) = stream.into_split();+ let mut line = msg.to_string();+ line.push('\n');+ w.write_all(line.as_bytes()).await?;+ let mut resp = String::new();+ BufReader::new(r).read_line(&mut resp).await?;+ serde_json::from_str(&resp).map_err(std::io::Error::other)+ }++ pub async fn before(&self, tool: &str, args: &Map<String, Value>) -> Before {+ match self.ask(json!({"op": "before", "tool": tool, "args": args})).await {+ Ok(v) if v["go"].as_bool() == Some(true) => Before::Go(v["step"].as_u64().unwrap_or(0)),+ Ok(v) => Before::Refuse(v["message"].as_str().unwrap_or_default().to_owned()),+ Err(e) => Before::Refuse(gone(&e)),+ }+ }++ /// Reports a finished call. `result` is the serialized tool result (`content`, `isError`)+ pub async fn after(&self, step: u64, result: &Value, ms: u64) {+ let text = summarize(result);+ let ok = result["isError"].as_bool() != Some(true);+ let msg = json!({"op": "after", "step": step, "ok": ok, "ms": ms, "text": text});+ if let Err(e) = self.ask(msg).await {+ // stdout is the MCP protocol: stderr only+ eprintln!("task gate: {e}");+ }+ }++ /// Waits for the user's answer. `Ok(message)` when approved, `Err(message)` when rejected or the task ended+ pub async fn confirm(&self, args: &Map<String, Value>) -> Result<String, String> {+ let s = |k: &str| args.get(k).and_then(Value::as_str).unwrap_or_default().trim().to_owned();+ let (action, detail) = (s("action"), s("detail"));+ if action.is_empty() {+ return Err(ictl_l10n::tr!("action 不能为空", "action can't be empty").into());+ }+ match self.ask(json!({"op": "confirm", "action": action, "detail": detail})).await {+ Ok(v) if v["approve"].as_bool() == Some(true) => Ok(v["message"].as_str().unwrap_or_default().to_owned()),+ Ok(v) => Err(v["message"].as_str().unwrap_or_default().to_owned()),+ Err(e) => Err(gone(&e)),+ }+ }+}++fn gone(e: &std::io::Error) -> String {+ ictl_l10n::trf!(+ "网页上的任务已经结束或页面服务已停止({e}),没有执行;停下来,不要再操作手机",+ "The task on the web page has ended or its server stopped ({e}); nothing was done. Stop and don't act on the phone any more"+ )+}++/// The text blocks joined, cut to [`MAX_TEXT`]. Screenshots stay with the agent: the page shows a sentence per step+pub fn summarize(result: &Value) -> String {+ let mut text = String::new();+ for c in result["content"].as_array().into_iter().flatten() {+ if c["type"].as_str() == Some("text") {+ if !text.is_empty() {+ text.push('\n');+ }+ text += c["text"].as_str().unwrap_or_default();+ }+ }+ if let Some((i, _)) = text.char_indices().nth(MAX_TEXT) {+ text.truncate(i);+ text.push('…');+ }+ text+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn summary_joins_text_and_leaves_images_out() {+ let r = json!({"content": [+ {"type": "text", "text": "已点击"},+ {"type": "image", "data": "AAA", "mimeType": "image/jpeg"},+ {"type": "text", "text": "440x956"},+ {"type": "image", "data": "BBB", "mimeType": "image/jpeg"}+ ]});+ assert_eq!(summarize(&r), "已点击\n440x956");+ let long = json!({"content": [{"type": "text", "text": "字".repeat(MAX_TEXT + 10)}]});+ assert_eq!(summarize(&long).chars().count(), MAX_TEXT + 1);+ }++ #[tokio::test]+ async fn a_gate_nobody_listens_on_refuses() {+ let g = Gate { path: "/nonexistent/ictl-gate.sock".into(), token: "t".into() };+ assert!(matches!(g.before("iphone_tap", &Map::new()).await, Before::Refuse(_)));+ let args = json!({"action": "发送消息"}).as_object().cloned().unwrap();+ assert!(g.confirm(&args).await.is_err());+ }++ #[tokio::test]+ async fn talks_one_json_line_with_the_token() {+ let dir = std::env::temp_dir().join(format!("ictl-gate-test-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("g.sock");+ let _ = std::fs::remove_file(&path);+ let listener = tokio::net::UnixListener::bind(&path).unwrap();+ let server = tokio::spawn(async move {+ let (s, _) = listener.accept().await.unwrap();+ let (r, mut w) = s.into_split();+ let mut line = String::new();+ BufReader::new(r).read_line(&mut line).await.unwrap();+ let v: Value = serde_json::from_str(&line).unwrap();+ w.write_all(b"{\"go\":true,\"step\":7}\n").await.unwrap();+ v+ });+ let g = Gate { path: path.clone(), token: "secret".into() };+ assert_eq!(g.before("iphone_tap", &Map::new()).await, Before::Go(7));+ let seen = server.await.unwrap();+ assert_eq!((seen["op"].as_str(), seen["token"].as_str()), (Some("before"), Some("secret")));+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rsindex 24bf5bf..9f98e7a 100644--- a/crates/ictl-mcp/src/lib.rs+++ b/crates/ictl-mcp/src/lib.rs@@ -18,6 +18,8 @@ use rmcp::{};use serde_json::{Map, Value, json};+pub mod gate;+/// 服务说明(发给客户端的 instructions):toolkit 的那段,加上自动解锁范围、多设备的说明pub fn instructions() -> &'static str {ictl_l10n::tr!(@@ -148,6 +150,28 @@ pub fn tools_with(dev: bool) -> Vec<Tool> {v}+/// [`gate::CONFIRM_TOOL`], listed only for a task started from the web viewer+pub fn confirm_tool() -> Tool {+ Tool::new(+ gate::CONFIRM_TOOL,+ ictl_l10n::tr!(+ "请用户在网页上确认一步操作,一直等到用户回答。\n\n何时用:付款、购买、下单、转账;删除或清空数据;发送消息、邮件、评论、帖子;\+修改账号、密码、隐私或安全设置;其他不可撤销的操作。在真正点下那一步之前调用。\n\n\+返回:用户同意时是普通结果,接着执行;用户拒绝时是错误结果,这时不要执行这一步,也不要换个方式绕过,停下来说明情况。",+ "Ask the user on the web page to confirm one action, and wait for the answer.\n\nWhen to use: payments, purchases, orders, transfers; deleting or clearing data; sending messages, emails, comments, posts; changing account, password, privacy or security settings; anything else that can't be undone. Call it right before the step that does it.\n\nReturns: a normal result when the user approves, then go ahead; an error when the user rejects, then don't do that step or work around it: stop and explain."+ )+ .to_owned(),+ schema(+ json!({+ "action": {"type": "string", "description": ictl_l10n::tr!("要做的事,一句话,例如「发送消息」「删除照片」", "what is about to happen, in a few words, e.g. “Send message”, “Delete photo”")},+ "detail": {"type": "string", "description": ictl_l10n::tr!("具体内容:发给谁、发什么、删哪几项、付多少钱", "the specifics: to whom, what, which items, how much")}+ }),+ &["action", "detail"],+ ),+ )+ .with_annotations(ToolAnnotations::with_title(ictl_l10n::tr!("请用户确认", "Ask the user")).read_only(true).open_world(false))+}+fn dev_tools() -> Vec<Tool> {let t = |name: &'static str, desc: &str, s: Map<String, Value>, a: ToolAnnotations| {Tool::new(name, desc.to_owned(), s).with_annotations(a)@@ -192,9 +216,9 @@ fn dev_tools() -> Vec<Tool> {t("iphone_install_app",ictl_l10n::tr!(- "安装签好名的 .ipa 或 .app(覆盖已装的同一 App)。path 是运行守护进程的机器上的路径,容器部署时是容器里的路径。\+ "安装签好名的 .ipa 或 .app(覆盖已装的同一 App)。path 是运行守护进程的机器上的路径。\大的包要一两分钟。",- "Install a signed .ipa or .app (replacing the same app if installed). path is on the machine that runs the daemon; inside the container for a container deployment. Large packages take a minute or two."+ "Install a signed .ipa or .app (replacing the same app if installed). path is on the machine that runs the daemon. Large packages take a minute or two."),schema(json!({"path": {"type": "string", "description": ictl_l10n::tr!(".ipa 文件或 .app 目录的路径", "path of the .ipa file or .app directory")}}),@@ -800,7 +824,9 @@ pub fn wants_alert_check(req: &Request) -> bool {| Request::OpenUrl { .. } => true,// 按键见 PressButton 自己的弹窗处理;切换设备后新设备的 WDA 还没起来,查不了弹窗;// 安装、卸载、Web Inspector 不碰屏幕(Web Inspector 也不该为它排队等设备锁)+ // the web viewer's finger isn't an MCP tool; the person watching sees any alertRequest::PressButton { .. }+ | Request::Touch { .. }| Request::TerminateApp { .. }| Request::SelectDevice { .. }| Request::InstallApp { .. }@@ -838,6 +864,8 @@ pub fn to_result(r: Response) -> CallToolResult {#[derive(Debug, Clone)]pub struct McpServer {pub socket: PathBuf,+ /// Set for a task started from the web viewer (see [`gate`])+ pub gate: Option<gate::Gate>,}impl ServerHandler for McpServer {@@ -850,13 +878,54 @@ impl ServerHandler for McpServer {_request: Option<PaginatedRequestParams>,_context: RequestContext<RoleServer>,) -> Result<ListToolsResult, ErrorData> {- Ok(ListToolsResult::with_all_items(tools()))+ let mut t = tools();+ if self.gate.is_some() {+ t.push(confirm_tool());+ }+ Ok(ListToolsResult::with_all_items(t))}async fn call_tool(&self,request: CallToolRequestParams,context: RequestContext<RoleServer>,+ ) -> Result<CallToolResponse, ErrorData> {+ let Some(gate) = &self.gate else { return self.call_tool_cancellable(request, &context).await };+ // a task from the web viewer: the viewer sees every call and can hold or refuse it (see `gate`)+ let args = request.arguments.clone().unwrap_or_default();+ let work = async {+ if request.name == gate::CONFIRM_TOOL {+ let r = match gate.confirm(&args).await {+ Ok(m) => CallToolResult::success(vec![ContentBlock::text(m)]),+ Err(m) => CallToolResult::error(vec![ContentBlock::text(m)]),+ };+ return Ok(r.into());+ }+ match gate.before(&request.name, &args).await {+ gate::Before::Go(step) => {+ let t0 = std::time::Instant::now();+ let r = self.call_tool_inner(request).await;+ if let Ok(CallToolResponse::Complete(c)) = &r {+ let v = serde_json::to_value(c).unwrap_or_default();+ gate.after(step, &v, t0.elapsed().as_millis() as u64).await;+ }+ r+ }+ gate::Before::Refuse(m) => Ok(CallToolResult::error(vec![ContentBlock::text(m)]).into()),+ }+ };+ tokio::select! {+ r = work => r,+ _ = context.ct.cancelled() => Ok(to_result(Response::error(ictl_l10n::tr!("调用已取消", "Call cancelled"))).into()),+ }+ }+}++impl McpServer {+ async fn call_tool_cancellable(+ &self,+ request: CallToolRequestParams,+ context: &RequestContext<RoleServer>,) -> Result<CallToolResponse, ErrorData> {// rmcp 收到取消通知只是置这个令牌,不会中止处理:自己停下。丢掉进行中的调用会断开到守护进程的连接,// 守护进程那边还在排队的请求随之放弃(protocol::call),iphone_batch 剩下的步骤也不再执行@@ -865,9 +934,7 @@ impl ServerHandler for McpServer {_ = context.ct.cancelled() => Ok(to_result(Response::error(ictl_l10n::tr!("调用已取消", "Call cancelled"))).into()),}}-}-impl McpServer {async fn call_tool_inner(&self, request: CallToolRequestParams) -> Result<CallToolResponse, ErrorData> {let args = request.arguments.unwrap_or_default();let then = match parse_then(&args) {@@ -913,7 +980,9 @@ impl McpServer {let wait = if matches!(req, Request::InstallApp { .. }) { 660 } else { 150 };protocol::call_expecting(&self.socket, req, Some(Duration::from_secs(wait)), expect_udid).await.unwrap_or_else(|e| {- Response::error(ictl_l10n::trf!("连不上守护进程({}):{e};确认守护进程在运行(容器部署看 iphone-control 容器)", "Can't reach the daemon ({}): {e}; make sure the daemon is running (for a container deployment, check the iphone-control container)",+ Response::error(ictl_l10n::trf!(+ "连不上守护进程({}):{e};确认守护进程在运行(iphone-control status)",+ "Can't reach the daemon ({}): {e}; make sure the daemon is running (iphone-control status)",self.socket.display()))},@@ -1039,7 +1108,7 @@ impl McpServer {/// 在 stdin/stdout 上运行 MCP 服务直到客户端断开pub async fn serve_stdio(socket: PathBuf) -> anyhow::Result<()> {- let running = McpServer { socket }.serve(rmcp::transport::stdio()).await?;+ let running = McpServer { socket, gate: gate::Gate::from_env() }.serve(rmcp::transport::stdio()).await?;running.waiting().await?;Ok(())}diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rsindex 93fc3eb..acea668 100644--- a/crates/ictl-protocol/src/lib.rs+++ b/crates/ictl-protocol/src/lib.rs@@ -5,7 +5,7 @@ use std::path::PathBuf;use serde::{Deserialize, Serialize};-/// 以 root 运行(容器、系统服务)时的控制接口和数据目录+/// 以 root 运行(系统服务)时的控制接口和数据目录pub const SYSTEM_SOCKET: &str = "/run/iphone-control/ctl.sock";pub const SYSTEM_DATA_DIR: &str = "/var/lib/iphone-control";@@ -41,6 +41,15 @@ pub fn default_socket() -> PathBuf {}}+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum TouchPhase {+ Prepare,+ Down,+ Move,+ Up,+}+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(tag = "op", rename_all = "snake_case")]pub enum Request {@@ -86,6 +95,16 @@ pub enum Request {PressButton {button: String,},+ /// A finger that follows the pointer in the web viewer: `down` touches at the point, `move` drags it there, `up`+ /// lifts it there; `prepare` only opens the HID session, so the first touch doesn't wait for it. Over CoreDevice+ /// HID (iOS 27 and later), one report each, so the screen moves while the pointer does+ Touch {+ phase: TouchPhase,+ #[serde(default)]+ x: f64,+ #[serde(default)]+ y: f64,+ },ListApps {include_system: bool,},@@ -216,6 +235,7 @@ impl Request {| Self::Swipe { .. }| Self::TypeText { .. }| Self::PressButton { .. }+ | Self::Touch { .. }| Self::LaunchApp { .. }| Self::TerminateApp { .. }| Self::OpenUrl { .. }diff --git a/crates/ictl-sign/Cargo.toml b/crates/ictl-sign/Cargo.tomlindex 3ef5765..1bb8be8 100644--- a/crates/ictl-sign/Cargo.toml+++ b/crates/ictl-sign/Cargo.toml@@ -16,5 +16,7 @@ plume_store.workspace = truethiserror.workspace = truetracing.workspace = trueplist.workspace = true+rsa.workspace = true+x509-certificate.workspace = trueuuid.workspace = truezip.workspace = truediff --git a/crates/ictl-sign/src/lib.rs b/crates/ictl-sign/src/lib.rsindex 10900be..745cb05 100644--- a/crates/ictl-sign/src/lib.rs+++ b/crates/ictl-sign/src/lib.rs@@ -6,6 +6,11 @@//!//! 账号目录(数据目录下 `account/`,0700):`accounts.json`(会话令牌)、`keys/<团队>/key.pem`(开发私钥)、anisette 状态。//! 免费账号:描述文件 7 天过期、开发证书 1 年。+//!+//! 证书:每个账号目录有自己的私钥,对应团队里的一张开发证书;同一个团队同时最多两张(免费账号)。没有私钥(新的+//! 数据目录、换了机器)或私钥的证书已不在团队里时,签名会新建一张,满了就先吊销一张旧的,不挑是谁的。证书一被吊销,+//! 用它签的 App 在每台设备上都起不来,而描述文件看上去还有效。所以要能判断设备上的 WDA 是不是本机这把私钥签的+//! ([`AccountDir::local_public_keys`]、[`Profile::signed_with_any`]),本机的证书还在不在([`Session::own_certificate_listed`])。pub mod bundle;pub mod ipa;@@ -21,6 +26,13 @@ use plume_store::AccountStore;pub use plume_core::auth::{TwoFactorAction, TwoFactorMethod, TwoFactorRequest};pub use profile::Profile;+use rsa::pkcs1::EncodeRsaPublicKey;+use rsa::pkcs8::DecodePrivateKey;++/// 证书(DER)里的公钥(SubjectPublicKeyInfo 的位串,RSA 时是 PKCS#1)。和 plume 认自己证书的比法一样+pub fn certificate_public_key(der: &[u8]) -> Option<Vec<u8>> {+ x509_certificate::X509Certificate::from_der(der).ok().map(|c| c.public_key_data().to_vec())+}#[derive(Debug, thiserror::Error)]pub enum SignError {@@ -95,6 +107,18 @@ impl AccountDir {Ok(email.to_owned())}+ /// 本机签名私钥(`keys/<团队>/key.pem`)的公钥,PKCS#1 DER,可以和 [`certificate_public_key`] 比。还没签过名时为空+ pub fn local_public_keys(&self) -> Vec<Vec<u8>> {+ let Ok(dirs) = std::fs::read_dir(self.dir.join("keys")) else { return Vec::new() };+ dirs.flatten()+ .filter_map(|e| {+ let pem = std::fs::read_to_string(e.path().join("key.pem")).ok()?;+ let key = rsa::RsaPrivateKey::from_pkcs8_pem(&pem).ok()?;+ Some(key.to_public_key().to_pkcs1_der().ok()?.as_bytes().to_vec())+ })+ .collect()+ }+/// 当前选中账号的邮箱pub async fn selected_email(&self) -> Result<String> {let store =@@ -131,9 +155,29 @@ pub struct Signed {pub team_id: String,pub bundle_id: String,pub profile: Profile,+ /// 这次新建了签名证书(本机没有私钥,或私钥的证书已不在团队里):别处用旧证书签的 App 不受影响,除非也吊销了+ pub new_certificate: bool,+ /// 新建时团队里的证书满了,吊销了一张旧的:用它签的 App 在所有设备上都起不来了,要重签+ pub revoked_certificate: bool,}impl Session {+ /// 本机的签名证书还在不在团队里(吊销了的不再列出)。本机还没有私钥时为 None+ pub async fn own_certificate_listed(&self) -> Result<Option<bool>> {+ let keys = self.dir.local_public_keys();+ if keys.is_empty() {+ return Ok(None);+ }+ let certs = self.inner.qh_list_certs(&self.team_id).await?.certificates;+ Ok(Some(+ certs+ .iter()+ .filter_map(|c| c.cert_content.as_ref())+ .filter_map(|d| certificate_public_key(d.as_ref()))+ .any(|k| keys.contains(&k)),+ ))+ }+/// 把设备注册到团队(已注册则跳过)pub async fn ensure_device(&self, udid: &str, name: &str) -> Result<()> {self.inner.qh_ensure_device(&self.team_id, &name.to_owned(), &udid.to_owned()).await?;@@ -165,9 +209,32 @@ impl Session {let new_id = if orig.ends_with(&format!(".{team}")) { orig.clone() } else { format!("{orig}.{team}") };// 证书必须在申请描述文件之前定下来:本地没有私钥时这里会吊销旧证书、新建一张,- // 而描述文件只包含生成那一刻团队里有效的证书,先拿描述文件会装不上(0xe8008015)- let cert =- CertificateIdentity::new_with_session(&self.inner, self.dir.dir.clone(), None, team, false, None).await?;+ // 而描述文件只包含生成那一刻团队里有效的证书,先拿描述文件会装不上(0xe8008015)。+ // 证书满了要吊销旧的之前 plume 调这个回调(返回 true 继续),记下来告诉调用方+ let mut revoked_certificate = false;+ let mut on_reset = || {+ revoked_certificate = true;+ true+ };+ let cert = CertificateIdentity::new_with_session(+ &self.inner,+ self.dir.dir.clone(),+ None,+ team,+ false,+ Some(&mut on_reset),+ )+ .await?;+ let new_certificate = cert.new;+ if new_certificate {+ tracing::warn!(+ "{}",+ ictl_l10n::log_tr!(+ "新建了签名证书(本机没有私钥,或它的证书已不在团队里)",+ "Created a new signing certificate (no local key, or its certificate is no longer in the team)"+ )+ );+ }// 只有带 entitlements 的 bundle(App/扩展)需要换 ID 并申请描述文件;WDA 里只有主程序一个let mut profiles = Vec::new();@@ -221,7 +288,7 @@ impl Session {let profile = verify_signed(&app, udid, cert.cert.as_ref().map(|c| c.constructed_data()))?;ipa::pack(work, output)?;- Ok(Signed { team_id: team.clone(), bundle_id: new_id, profile })+ Ok(Signed { team_id: team.clone(), bundle_id: new_id, profile, new_certificate, revoked_certificate })}}@@ -356,4 +423,45 @@ mod tests {assert!(verify_signed(&app, "UDID-1", Some(b"CERT-B")).unwrap_err().to_string().contains("签名用的证书"));std::fs::remove_dir_all(root).unwrap();}++ /// 现场生成一把 RSA 私钥(PKCS#8 PEM)和用它自签的证书(DER)。dev 构建里大数运算开了优化(工作区 Cargo.toml),+ /// 生成 2048 位密钥不到一秒;仓库里不放私钥文件+ fn key_and_cert() -> (String, Vec<u8>) {+ use rsa::pkcs8::EncodePrivateKey;+ let key = rsa::RsaPrivateKey::new(&mut rsa::rand_core::OsRng, 2048).unwrap();+ let pair =+ x509_certificate::InMemorySigningKeyPair::from_pkcs8_der(key.to_pkcs8_der().unwrap().as_bytes()).unwrap();+ let mut b = x509_certificate::X509CertificateBuilder::default();+ b.subject().append_common_name_utf8_string("ictl-sign test").unwrap();+ let cert = b.create_with_key_pair(&pair).unwrap().encode_der().unwrap();+ (key.to_pkcs8_pem(Default::default()).unwrap().to_string(), cert)+ }++ /// 设备上 WDA 的描述文件里有没有本机私钥的证书:iPad 上那份是别处签的(本机的证书是后来才建的),里面没有+ #[test]+ fn tells_whether_a_profile_has_this_machines_certificate() {+ let (pem, mine) = key_and_cert();+ let (_, other) = key_and_cert();+ let root = std::env::temp_dir().join(format!("ictl-keys-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(root.join("keys/TEAM1")).unwrap();+ std::fs::write(root.join("keys/TEAM1/key.pem"), pem).unwrap();+ let acct = AccountDir { dir: root.clone(), anisette_url: None };+ let keys = acct.local_public_keys();+ assert_eq!(keys.len(), 1);+ assert_eq!(certificate_public_key(&mine).as_ref(), Some(&keys[0]), "the same comparison plume uses");+ assert_ne!(certificate_public_key(&other).as_ref(), Some(&keys[0]));+ let profile = |certs: Vec<Vec<u8>>| Profile {+ expires: SystemTime::now(),+ devices: vec![],+ get_task_allow: true,+ application_identifier: String::new(),+ certificates: certs,+ };+ assert!(!profile(vec![other.clone()]).signed_with_any(&keys), "signed elsewhere");+ assert!(profile(vec![other, mine]).signed_with_any(&keys), "lists every certificate valid at the time");+ assert!(!profile(vec![b"not a certificate".to_vec()]).signed_with_any(&keys));+ let none = AccountDir { dir: root.join("nothing"), anisette_url: None };+ assert!(none.local_public_keys().is_empty(), "never signed here");+ std::fs::remove_dir_all(root).unwrap();+ }}diff --git a/crates/ictl-sign/src/profile.rs b/crates/ictl-sign/src/profile.rsindex 4279c0c..86c98c1 100644--- a/crates/ictl-sign/src/profile.rs+++ b/crates/ictl-sign/src/profile.rs@@ -46,6 +46,13 @@ impl Profile {pub fn load(path: &std::path::Path) -> Option<Self> {Self::parse(&std::fs::read(path).ok()?)}++ /// 描述文件里有没有这些公钥([`crate::AccountDir::local_public_keys`])之一的证书。描述文件列的是生成那一刻+ /// 团队里所有有效的证书,所以「有」不等于是用它签的;「没有」则一定不是本机签的(别的机器、旧的数据目录签的,+ /// 或本机的证书是后来才新建的)+ pub fn signed_with_any(&self, keys: &[Vec<u8>]) -> bool {+ self.certificates.iter().filter_map(|c| crate::certificate_public_key(c)).any(|k| keys.contains(&k))+ }}fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rsindex 4d44757..352d3a7 100644--- a/crates/ictl-wda/src/client.rs+++ b/crates/ictl-wda/src/client.rs@@ -70,6 +70,10 @@ impl IdleSettings {pub const NO_COOL_OFF: Self = Self { wait_for_idle_timeout: 1.0, animation_cool_off_timeout: 0.0 };}+/// Frames a second and size (percent) of WDA's MJPEG stream with [`WdaClient::fast_stream`]+const MJPEG_FPS: u32 = 60;+const MJPEG_SCALE: u32 = 75;+/// 主屏、锁屏、系统弹窗所属的进程pub const SPRINGBOARD: &str = "com.apple.springboard";/// IOHID 消费者页(Consumer)@@ -115,6 +119,8 @@ pub struct WdaClient<T> {/// What WDA has now, as far as we know: sending the same again is a wasted round tripidle_current: Option<IdleSettings>,upright_stream: bool,+ /// See [`Self::fast_stream`]+ fast_stream: bool,}impl<T: Transport> WdaClient<T> {@@ -127,6 +133,7 @@ impl<T: Transport> WdaClient<T> {idle_baseline: None,idle_current: None,upright_stream: false,+ fast_stream: false,}}@@ -178,11 +185,18 @@ impl<T: Transport> WdaClient<T> {.to_owned();self.session = Some(id.clone());self.idle_current = None;- if self.upright_stream {- let body = json!({"settings": {"mjpegFixOrientation": true}});+ if self.upright_stream || self.fast_stream {+ let mut settings = serde_json::Map::new();+ if self.fast_stream {+ settings.insert("mjpegServerFramerate".into(), MJPEG_FPS.into());+ settings.insert("mjpegScalingFactor".into(), MJPEG_SCALE.into());+ }+ if self.upright_stream {+ settings.insert("mjpegFixOrientation".into(), true.into());+ }let path = format!("/session/{id}/appium/settings");- if let Err(e) = self.call("POST", &path, Some(body), DEFAULT_TIMEOUT).await {- tracing::debug!("mjpegFixOrientation: {e}");+ if let Err(e) = self.call("POST", &path, Some(json!({"settings": settings})), DEFAULT_TIMEOUT).await {+ tracing::debug!("MJPEG settings: {e}");}}Ok(id)@@ -429,6 +443,14 @@ impl<T: Transport> WdaClient<T> {self.upright_stream = true;}+ /// The MJPEG stream (the live viewer) at [`MJPEG_FPS`] frames a second and [`MJPEG_SCALE`]% of the screen's+ /// pixels instead of WDA's 10 at full size, set with each new session: the picture follows a drag closely.+ /// Measured on an iPhone 18 Pro Max (iOS 27.2.1): about 50 fps at 34 KB a frame, and element-tree reads no slower+ /// while it streams. WDA only captures while a client is connected+ pub fn fast_stream(&mut self) {+ self.fast_stream = true;+ }+/// Swipes and stays in polling mode for the caller, who ends it with [`Self::end_polling`]: restoring the settings/// only to change them again right after would cost two round tripspub async fn swipe_into_polling(&mut self, from: (f64, f64), to: (f64, f64), ms: u64) -> Result<()> {diff --git a/crates/ictl-wda/src/runner.rs b/crates/ictl-wda/src/runner.rsindex 87298ce..0896bf8 100644--- a/crates/ictl-wda/src/runner.rs+++ b/crates/ictl-wda/src/runner.rs@@ -54,14 +54,20 @@ fn automation_signal(msg: &str) -> Option<AutomationSignal> {}}+/// 设备拒绝启动 runner(见 [`launch_hint`]):还没信任开发者,或签 WDA 的证书已被吊销。守护进程据此判断要不要重签+pub fn launch_refused(msg: &str) -> bool {+ msg.contains("unexpected response")+}+/// 手机拒绝启动 runner 时回的是 NSError,但 idevice 收到的是没解开的归档(字段都是 `Uid(n)` 引用),读不出文字,/// 只报 `unexpected response`。首次安装后最常见的原因是还没信任开发者(iPad mini 5 / iPadOS 26.6.1 真机:-/// 点「信任」之前这样报,之后下一次就能启动),在报错里提示一句+/// 点「信任」之前这样报,之后下一次就能启动);用过的设备则可能是签 WDA 的证书变了(给另一台设备重签时换了证书,+/// 同一台 iPad 上点 runner 图标提示「无法验证 App」,重签这台后就能启动),两种都在报错里提示一句fn launch_hint(msg: String) -> String {- if msg.contains("unexpected response") {+ if launch_refused(&msg) {ictl_l10n::trf!(- "{msg}(如果是第一次在这台手机上装 WDA:到 设置 → 通用 → VPN 与设备管理 里信任你的 Apple ID 开发者,需要联网)",- "{msg} (if this is the first WDA install on this phone: trust your Apple ID developer under Settings → General → VPN & Device Management, which needs internet)"+ "{msg}(第一次在这台设备上装 WDA 的:到 设置 → 通用 → VPN 与设备管理 里信任你的 Apple ID 开发者,需要联网;已经信任过的,可能是签名证书变了:运行 iphone-control sign 重签这台)",+ "{msg} (first WDA install on this device: trust your Apple ID developer under Settings → General → VPN & Device Management, which needs internet; already trusted: the signing certificate may have changed, run iphone-control sign to re-sign this device)")} else {msg@@ -265,8 +271,12 @@ mod tests {#[test]fn untrusted_developer_hint_only_for_unexpected_response() {let m = launch_hint("unexpected response from device: unexpected response".into());- assert!(m.contains("VPN 与设备管理"), "{m}");+ assert!(m.contains("VPN 与设备管理") && m.contains("iphone-control sign"), "{m}");assert_eq!(launch_hint("WDA 在限定时间内没有就绪".into()), "WDA 在限定时间内没有就绪");+ // 守护进程据此决定要不要查证书、自动重签:带不带提示都认+ assert!(launch_refused("unexpected response from device: unexpected response"));+ assert!(launch_refused(&m));+ assert!(!launch_refused("WDA 在限定时间内没有就绪"));}#[test]diff --git a/deploy/deb/iphone-control.service b/deploy/deb/iphone-control.servicenew file mode 100644index 0000000..cc74205--- /dev/null+++ b/deploy/deb/iphone-control.service@@ -0,0 +1,22 @@+# systemd user service installed by the iphone-control .deb package (/usr/lib/systemd/user/).+# Each user turns it on for themselves:+# systemctl --user enable --now iphone-control+# sudo loginctl enable-linger "$USER" # also start at boot without logging in+# Settings: ~/.config/iphone-control/env (same format as /usr/share/doc/iphone-control/env.example).++[Unit]+Description=iphone-control daemon (iPhone over USB, MCP)+After=network-online.target++[Service]+ExecStart=/usr/bin/iphone-control daemon+EnvironmentFile=-%h/.config/iphone-control/env+# memory freed after screenshots goes back to the system+Environment=MALLOC_ARENA_MAX=2+Restart=on-failure+RestartSec=10+# on stop it ends the phone's HID session and WDA first+TimeoutStopSec=30++[Install]+WantedBy=default.targetdiff --git a/deploy/deb/postinst b/deploy/deb/postinstnew file mode 100755index 0000000..0aa52de--- /dev/null+++ b/deploy/deb/postinst@@ -0,0 +1,14 @@+#!/bin/sh+# What to do next. A user service is each user's own to turn on, so the package doesn't start it+set -e+if [ "$1" = configure ]; then+ cat <<'MSG'++iphone-control is installed. As your regular user (not root), connect the iPhone and run+ iphone-control+It starts the daemon as a user service and walks you through setup.+安装完成。以普通用户(不是 root)接好 iPhone 后运行 iphone-control,它会启动后台服务并一步步带你完成设置。++MSG+fi+exit 0diff --git a/deploy/iphone-control.service b/deploy/iphone-control.servicedeleted file mode 100644index 678e9f0..0000000--- a/deploy/iphone-control.service+++ /dev/null@@ -1,24 +0,0 @@-# 从源码运行时的 systemd 用户服务(不用 Docker)。安装见 https://derrors.github.io/iphone-control/deploy/source-# cp deploy/iphone-control.service ~/.config/systemd/user/-# systemctl --user daemon-reload && systemctl --user enable --now iphone-control-# loginctl enable-linger "$USER" # 不登录也随开机启动-# 数据目录默认 ~/.local/share/iphone-control,控制接口 $XDG_RUNTIME_DIR/iphone-control/ctl.sock;-# usbmuxd 用系统的服务(以普通用户运行时守护进程不自己拉起)。--[Unit]-Description=iphone-control daemon (iPhone over USB, MCP)-After=network-online.target--[Service]-ExecStart=%h/.cargo/bin/iphone-control daemon-# 代理、通知、IPHONE_UDID 等,格式同 .env.example;没有这个文件也能启动-EnvironmentFile=-%h/.config/iphone-control/env-# 见 docker/Dockerfile:截图时的临时内存释放后能还给系统-Environment=MALLOC_ARENA_MAX=2-Restart=on-failure-RestartSec=10-# 停止时先停 HID 屏幕媒体流和 runner,给够时间,避免手机端留下会话-TimeoutStopSec=30--[Install]-WantedBy=default.targetdiff --git a/docker/Dockerfile b/docker/Dockerfiledeleted file mode 100644index 28758f7..0000000--- a/docker/Dockerfile+++ /dev/null@@ -1,74 +0,0 @@-# syntax=docker/dockerfile:1-# iphone-control 镜像:一个 Rust 二进制 + Debian 的 usbmuxd。-# 所有版本锁在 ARG 里;Rust 依赖由 Cargo.lock 锁定(--locked)。--ARG DEBIAN_IMAGE=debian:trixie-slim@sha256:f6b08b09a05725f9431502d3b5714f5c4576e82c1a84fa1debe0c24a7e0c3ec4-ARG RUST_IMAGE=rust:1-trixie@sha256:09027f873d45b8ecd1dc86f1fa13b7a62b875c961f017a0e331267b350430137--# ---- 编译 -----# 依赖下载和编译产物放在构建缓存里:改 README、compose 等不再从头编译约 570 个 crate-# registry、git 缓存用 sharing=locked:build 和 notices 两个阶段会并行,缓存是空的时候(CI 上每次都是)-# 两边同时检出 git 依赖(idevice)会互相踩坏文件-FROM ${RUST_IMAGE} AS build-WORKDIR /src-COPY . .-RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \- --mount=type=cache,target=/usr/local/cargo/git,sharing=locked \- --mount=type=cache,target=/src/target \- cargo build --release --locked -p iphone-control \- && cp target/release/iphone-control /iphone-control--# ---- 第三方许可证清单(cargo-about,按 Cargo.lock 生成,含 MIT/Apache 等要求随附的许可证全文)-----FROM ${RUST_IMAGE} AS notices-ARG CARGO_ABOUT_VERSION=0.9.3-RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \- cargo install --locked --features cli "cargo-about@${CARGO_ABOUT_VERSION}"-WORKDIR /src-COPY . .-RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \- --mount=type=cache,target=/usr/local/cargo/git,sharing=locked \- cargo about generate --locked -m apps/iphone-control/Cargo.toml -c docker/about.toml docker/about.hbs \- -o /THIRD_PARTY_LICENSES.html--# ---- WebDriverAgent:Appium 官方构建的未签名真机包,重新打成 IPA -----# 计划改为本项目在 macOS CI 上自己编译(docs/dev/archive/roadmap.md 阶段 7)-FROM ${DEBIAN_IMAGE} AS wda-ARG WDA_VERSION=v16.15.3-ARG WDA_SHA256=2176793538d902f6b1e61291e9997f68d306541f222ea715d256a7c6ce9d4fc5-RUN apt-get update \- && apt-get install -y --no-install-recommends ca-certificates curl unzip zip \- && rm -rf /var/lib/apt/lists/*-RUN curl -fsSL -o /tmp/wda.zip \- "https://github.com/appium/WebDriverAgent/releases/download/${WDA_VERSION}/WebDriverAgentRunner-Runner.zip" \- && echo "${WDA_SHA256} /tmp/wda.zip" | sha256sum -c - \- && mkdir -p /w/Payload /out/licenses/WebDriverAgent && cd /w/Payload && unzip -q /tmp/wda.zip \- && cd /w && zip -qry /out/WDA-unsigned.ipa Payload \- && curl -fsSL -o /out/licenses/WebDriverAgent/LICENSE \- "https://raw.githubusercontent.com/appium/WebDriverAgent/${WDA_VERSION}/LICENSE"--# ---- 运行镜像 -----FROM ${DEBIAN_IMAGE}-# usbmuxd 用 Debian 的包(GPL-3.0,独立进程运行;源码可从 Debian 获取)-RUN apt-get update \- && apt-get install -y --no-install-recommends usbmuxd ca-certificates \- && rm -rf /var/lib/apt/lists/*-COPY --from=build /iphone-control /usr/local/bin/iphone-control-COPY --from=wda /out/WDA-unsigned.ipa /usr/share/iphone-control/WDA-unsigned.ipa-COPY --from=wda /out/licenses/ /usr/share/licenses/-COPY LICENSE THIRD_PARTY.md /usr/share/doc/iphone-control/-COPY --from=notices /THIRD_PARTY_LICENSES.html /usr/share/doc/iphone-control/THIRD_PARTY_LICENSES.html-COPY vendor/plume_core/LICENSE /usr/share/licenses/plume_core/LICENSE-COPY vendor/plume_store/LICENSE-MIT-Impactor /usr/share/licenses/plume_store/LICENSE-COPY vendor/omnisette/LICENSE /usr/share/licenses/omnisette/LICENSE-COPY vendor/apple-codesign/LICENSE /usr/share/licenses/apple-codesign/LICENSE-# usbmuxd 把配对记录写在 /var/lib/lockdown,指到数据目录里,删掉重建容器也不丢-RUN rm -rf /var/lib/lockdown && ln -s /var/lib/iphone-control/lockdown /var/lib/lockdown-ENV ICTL_DATA_DIR=/var/lib/iphone-control-# 截图处理时临时分配几十 MB;glibc 默认按线程开很多 arena,释放后也不还给系统,看起来像内存涨了不回落-ENV MALLOC_ARENA_MAX=2-LABEL org.opencontainers.image.title="iphone-control" \- org.opencontainers.image.description="Drive a real iPhone from Linux: WebDriverAgent + CoreDevice HID + MCP, single Rust binary" \- org.opencontainers.image.licenses="MIT AND MPL-2.0" \- org.opencontainers.image.source="https://github.com/Derrors/iphone-control"-ENTRYPOINT ["iphone-control"]-CMD ["daemon"]diff --git a/docker/about.toml b/docker/about.tomldeleted file mode 100644index 8b0a83c..0000000--- a/docker/about.toml+++ /dev/null@@ -1,9 +0,0 @@-# cargo-about:生成镜像里的第三方 Rust 组件许可证清单(/usr/share/doc/iphone-control/THIRD_PARTY_LICENSES.html)。-# 依赖里出现不在这个列表里的许可证时构建失败,需要人看一眼再决定(例如 AGPL、没有许可证声明的 crate)-accepted = [- "MIT", "Apache-2.0", "Apache-2.0 WITH LLVM-exception", "BSD-2-Clause", "BSD-3-Clause", "ISC", "MPL-2.0",- "Unicode-3.0", "Zlib", "CC0-1.0", "0BSD", "BSL-1.0", "Unlicense", "CDLA-Permissive-2.0", "BlueOak-1.0.0",-]-targets = ["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu"]-ignore-build-dependencies = true-ignore-dev-dependencies = truediff --git a/docs/architecture.md b/docs/architecture.mdindex 006994b..fc06fc1 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -3,14 +3,14 @@## 1. 总览```-┌──────────────────── Linux / macOS 主机或容器 ─────────────────────────────────┐+┌──────────────────── Linux / macOS 主机(以普通用户运行)────────────────────────┐│ ││ Claude Code ──stdio──▶ iphone-control mcp ──unix socket──┐ ││ (每个会话一个,短命) (ictl-mcp,经 ictl-protocol) │ ││ ▼ ││ iphone-control daemon(ictl-daemon,常驻,唯一持有设备) ││ ┌───────────────────────────────────────────────────┐ │-│ usbmuxd(系统包)◀─看护─┤ 设备状态机 usbmux 监听 重签调度 通知 │ │+│ usbmuxd(系统的)◀──────┤ 设备状态机 usbmux 监听 重签调度 通知 │ ││ │ │ │ │ ││ │ │ ictl-device: lockdown · CoreDeviceProxy 隧道 │ ││ │ │ (jktcp 用户态 TCP) · RSD · cryptexd │ │@@ -35,16 +35,18 @@| 进程 | 生命周期 | 职责 ||---|---|---|-| `iphone-control daemon` | 常驻,容器入口(Linux 上从源码运行时由 systemd 用户服务启动;macOS 上在终端里前台运行) | 唯一和设备通信的进程。维护设备状态机,对外提供本地控制接口 |+| `iphone-control daemon` | 常驻,作为用户服务运行(macOS 是 launchd,Linux 是 systemd 用户服务;由 `install.sh`、`iphone-control service install`、`brew services` 或 .deb 的 unit 装好),也可以在终端里前台运行 | 唯一和设备通信的进程。维护设备状态机,对外提供本地控制接口 || `iphone-control mcp` | 每个 agent 会话一个 | MCP stdio 服务,把工具调用翻译成对守护进程的请求 |-| `usbmuxd` | 容器里是守护进程的子进程;Linux 上以普通用户运行时用系统的 usbmuxd 服务;macOS 用系统自带的 | Linux 上是系统包,GPL-3.0,独立进程运行,不链接 |-| `iphone-control doctor/setup/sign/...` | 一次性 | 运维命令,也通过控制接口或直接调用库 |+| `usbmuxd` | 系统的服务:Linux 上是发行版的包(.deb 依赖它,udev 在插上手机时启动),macOS 自带;守护进程不启动也不重启它 | Linux 上是系统包,GPL-3.0,独立进程运行,不链接 |+| `iphone-control`(不带命令)、`setup`、`service`、`doctor`、`sign` 等 | 一次性 | 首次运行引导(`guide.rs`)、后台服务管理(`service.rs`)和运维命令,通过控制接口或直接调用库。启动时先把 `~/.config/iphone-control/env` 读进环境(`envfile.rs`,已有的环境变量优先) |**控制接口**:Unix socket(root 默认 `/run/iphone-control/ctl.sock`,普通用户默认 `$XDG_RUNTIME_DIR/iphone-control/ctl.sock`,没有这个变量时(macOS)在数据目录下,权限 0600),JSON 行协议。请求/响应类型和客户端 `call(socket, req, timeout)` 在 `ictl-protocol`,MCP 和 CLI 共用。理由:-- MCP 进程由 `docker exec -i`(从源码运行时直接调用二进制)拉起,短命且可能同时有多个;设备连接(尤其是 HID 需要的显示媒体流、WDA 的 XCTest 会话)只能有一个持有者。-- 不开 TCP 端口,避免重蹈 `ios forward` 监听所有网卡的覆辙。WDA 本身也通过 idevice 的 provider 直连设备端口,**本机不再监听 8100**。如需给外部工具用,`iphone-control wda-bridge` 显式开启,只绑 127.0.0.1,且只转发 Host 头是 `localhost`/`127.0.0.1`/`[::1]` 的请求(挡住 DNS rebinding)。注意容器用 host 网络,**本机的任何用户都能连上 bridge**,而 WDA 没有认证,用完就停。-- `iphone-control viewer` 同样显式开启、只绑 127.0.0.1、检查 Host 头:页面看 WDA 的 MJPEG 流(手机上的 9100 端口,经 usbmuxd,只读);点击、滑动、输入、按键是 POST,还要检查 `Origin` 是页面本身、内容类型是 JSON,然后作为普通请求发给守护进程,和 agent 的调用排队、自动解锁。它绑定启动时正在控制的设备:每个操作带上这台的 UDID,守护进程控制的不是这台就拒绝。+- MCP 进程由 AI 客户端直接调用二进制拉起,短命且可能同时有多个;设备连接(尤其是 HID 需要的显示媒体流、WDA 的 XCTest 会话)只能有一个持有者。+- 不开 TCP 端口,避免重蹈 `ios forward` 监听所有网卡的覆辙。WDA 本身也通过 idevice 的 provider 直连设备端口,**本机不再监听 8100**。如需给外部工具用,`iphone-control wda-bridge` 显式开启,只绑 127.0.0.1,且只转发 Host 头是 `localhost`/`127.0.0.1`/`[::1]` 的请求(挡住 DNS rebinding)。注意**本机的任何用户都能连上 bridge**,而 WDA 没有认证,用完就停。+- `iphone-control viewer` 同样显式开启、只绑 127.0.0.1、检查 Host 头:页面看 WDA 的 MJPEG 流(手机上的 9100 端口,经 usbmuxd,只读);点击、滑动、输入、按键是 POST,还要检查 `Origin` 是页面本身、内容类型是 JSON,然后作为普通请求发给守护进程,和 agent 的调用排队、自动解锁。它跟着守护进程控制的设备:在本页、别的页面、`iphone-control select`、MCP 工具里切换,或拔掉后自动换了一台,`/api/info` 的 `udid` 都会变,页面最迟在下一次 10 秒轮询时发现,把画面(`/stream?udid=`)和各面板换过去。每个操作带上页面显示的那台的 UDID(`X-Ictl-Device`),守护进程控制的不是这台就拒绝,不会发到用户没在看的手机上。还没装 WDA 的设备,登录了 Apple ID 时页面上可以直接签名安装(`/api/sign`,即 `Request::Resign { force: true }`,时限 16 分钟)。AI 任务执行中不能切换设备,设了 `IPHONE_UDID` 时也不能。+- viewer 的画面像触摸屏:iOS 27 起按下、移动、松开各发一个 `Request::Touch`(`prepare`/`down`/`move`/`up`),守护进程在已开的 HID 会话上发一个 touchscreen 报告(约 2 毫秒);解锁、核对方向只在 `down` 时做一次。页面一次只发一个请求,没发出去的移动只留最新的一个,按住不动时每 100 毫秒再报一次位置。滚轮、触控板换成同样的手指拖动。iOS 27 以下松开后发整段手势(WDA)。画面的 MJPEG 流在 `WdaClient::fast_stream` 下是每秒 60 帧、75% 尺寸。页面的文字中英两套,请求带 `X-Ictl-Lang`,viewer 在这种语言下处理,AI 任务记下开始时的语言。+- viewer 的 AI 任务(`agent.rs`):页面上写的任务交给本机的 Claude Code(`claude -p --output-format stream-json`,`--tools ""`、`--strict-mcp-config`,只有 iphone 的 MCP 工具)或 Codex(`codex exec --json`,只读沙箱,`-c` 挂上 iphone 的 MCP 服务),作为子进程(单独的进程组,停止时整组结束)。它的 MCP 服务带上环境变量 `ICTL_AGENT_GATE`(viewer 在控制接口旁边监听的 Unix socket `viewer-<端口>.sock`,0600)和 `ICTL_AGENT_TOKEN`(这个任务的口令),于是每次工具调用前先问 viewer(`ictl_mcp::gate`):记成任务的一步、暂停或用户接管时挂住、任务停了就拒绝;调用后把结果和截图报回去;另外多列一个 `iphone_confirm`,等用户在页面上同意或拒绝。所以步骤、暂停、接管、确认都在 iphone-control 这一层,和用哪种 agent 无关;agent 自己的输出只取它说的话(挂到下一步上)和最后的总结。Codex 对标了 destructive 的 MCP 工具默认要审批,非交互运行时会全部拒绝,所以给这个服务设 `default_tools_approval_mode="approve"`,由 `iphone_confirm` 把关。页面按 SSE 收任务事件(`step`/`confirm`/`state`/`done`),重连时先重放;同一时间只有一个任务,任务执行中(没有接管时)viewer 拒绝页面的手动操作。### 并发模型@@ -61,8 +63,8 @@- 安装(`iphone_install_app`)同样不持设备锁;安装之间互斥(`iphone_install_app`、重签、`sign`,锁在 `Device::install`),因为 idevice 把每个 .ipa 都上传到手机上同一个文件。- Web 请求(`iphone_web_targets`、`iphone_web_eval`)用独立的锁,不占设备锁,慢页面不挡点击和截图。- 改变手机状态的请求(含 `iphone_web_eval`、`iphone_install_app`)排队超过 30 秒就放弃,免得点击落到已经变了的屏幕上;调用方取消后还在排队的请求也不执行。-- 停止信号优先处理(`biased` select):取消排队和执行中的请求、巡检,再停 HID 媒体流、runner、usbmuxd。-- **卡死兜底**:约 10 分钟没有完成任何巡检或请求(设备锁被占死、运行时卡住)时,守护进程自己退出,交给 systemd 或 Docker 重启,免得一直占着设备又不干活。容器另有 healthcheck 和日志大小限制(`compose.yaml`)。+- 停止信号优先处理(`biased` select):取消排队和执行中的请求、巡检,再停 HID 媒体流、runner。+- **卡死兜底**:约 10 分钟没有完成任何巡检或请求(设备锁被占死、运行时卡住)时,守护进程自己退出,交给服务管理器(launchd 或 systemd)重启,免得一直占着设备又不干活。## 3. 守护进程状态机@@ -92,7 +94,7 @@要点(每一条都来自 toolkit 实际踩过的坑):-- **热插拔**:容器里没有 udev,usbmuxd 收不到热插拔事件。守护进程每 10 秒向 usbmuxd 列一次设备,并数 sysfs `/sys/bus/usb/devices/` 里的 iPhone/iPad/iPod(厂商号 `05ac` 且产品名匹配,键盘等配件不算)。只在自管 usbmuxd 时:sysfs 里的台数连续 3 次多于 usbmuxd 认到的台数就重启 usbmuxd 子进程。列设备连续 3 轮出错才当作离线,usbmuxd 抖一下不拆会话。+- **热插拔**:交给系统的 usbmuxd(Linux 上由 udev 通知)。守护进程每 10 秒向 usbmuxd 列一次设备;列设备连续 3 轮出错才当作离线,usbmuxd 抖一下不拆会话。`doctor` 另数 sysfs `/sys/bus/usb/devices/`(Linux)或 IORegistry(macOS)里的 iPhone/iPad/iPod(厂商号 `05ac` 且产品名匹配,键盘等配件不算),区分「USB 上没有手机」和「usbmuxd 看不到」。(以前的 Docker 镜像里没有 udev,守护进程自己看护 usbmuxd,台数对不上就重启它;去掉 Docker 后这部分删了,见 D5、D14。)- **隧道**:CoreDeviceProxy + jktcp 用户态 TCP 栈(idevice `tunnel_tcp_stack`),不需要 root,不创建 TUN 网卡。锁屏且从未解锁过(BFU)时报 `PasswordProtected`,进入 `NeedsUnlock`,只能人工解锁。HID 和截图用的隧道按需建立、常驻复用;WDA 掉线或 usbmuxd 重启时连隧道一起丢。- **HID 会话**:归 `Tunnel` 所有(`Tunnel::hid` / `close_hid` / `close`),持有屏幕媒体流。关闭时必须先停媒体流再断隧道,否则手机一直挂着「配对的电脑」会话(灵动岛图标常驻、不自动锁屏)。空闲 30 秒关闭,重开约 0.5 秒。- **开发者镜像**:每次启动 WDA 前都先 `installed_ddi()` 查询(toolkit 实测已挂载时约 1 秒),未挂载才走 `install_ddi()`(个性化 + TSS)。手机重启后镜像可能会掉,所以这一步不能省。默认缓存(`ddi/`)连续 3 次**挂载**失败才清掉重新下载,隧道建不起来不计入。设了 `ICTL_DDI_DIR` 时不下载、也不删里面的文件,缺文件时报错说明缺哪个。@@ -111,38 +113,39 @@| `ictl-protocol` | 控制接口的 `Request`/`Response` 类型和客户端 `call(socket, req, timeout)` | `serde`、`tokio` || `ictl-sign` | Apple ID 登录(含双重认证交互)、会话持久化、注册设备、App ID、描述文件、签名 `.app`/`.ipa`(**包括 `.xctest`**;bundle 逻辑改写自 plume_utils)、签后自检 | vendored 的 `plume_core`/`plume_store`(MPL-2.0/MIT;经 plume_core 用 vendored 的 `omnisette` 和打过补丁的 `apple-codesign`) || `ictl-unlock` | 锁屏密码键盘定位、逐位输入并核对密码栏、从第 2 位起先写停用标记 | `ictl-wda` |-| `ictl-daemon` | `core`(共享状态、请求分发、快照)、`supervise`(巡检、usbmuxd 看护、后台启动 WDA、重签、会话检查)、`tools`(工具的实现、HID 后备)、`devtools`(日志采集、崩溃报告、安装、卸载)、`web`(Web Inspector 工具,保留一条连接复用)、`devices`(列出、选择设备)、`doctor`;通知(Bark/Telegram)、截图缩放/裁剪、控制接口服务端 | 以上全部、`tokio`、`reqwest`、`image` |+| `ictl-daemon` | `core`(共享状态、请求分发、快照)、`supervise`(巡检、后台启动 WDA、重签、会话检查)、`tools`(工具的实现、HID 后备)、`devtools`(日志采集、崩溃报告、安装、卸载)、`web`(Web Inspector 工具,保留一条连接复用)、`devices`(列出、选择设备)、`doctor`;通知(Bark/Telegram)、截图缩放/裁剪、控制接口服务端 | 以上全部、`tokio`、`reqwest`、`image` || `ictl-mcp` | MCP stdio 服务,`iphone_*` 工具 17 个,开启开发者工具后 23 个:toolkit 的 13 个 + `iphone_wait_for`、`iphone_batch`、`iphone_list_devices`、`iphone_select_device`,以及 6 个可选的开发者工具(D13);操作类工具可带 `then` 顺带返回操作后的界面;经控制接口调用守护进程 | `ictl-protocol`、`ictl-l10n`、`rmcp`(`server`、`transport-io`) |-| `apps/iphone-control` | CLI 入口:`daemon`、`mcp`、`mcp-config`、`status`、`doctor`、`setup`、`login`、`sign`、`resign`、`passcode`、`unlock-reset`、`devices`、`select`、`wda-bridge`、`viewer`(`viewer.rs`:本机网页看实时画面并操作)、`notify-test`;隐藏的 `debug <ddi\|hid\|screenshot\|soak\|wda\|e2e>` 真机诊断(原第 0 步 spike,不经守护进程;feature `debug-cmds`,默认不编译) | `clap` |+| `apps/iphone-control` | CLI 入口:不带命令时是首次运行引导或状态(`guide.rs`)、`daemon`、`mcp`、`mcp-config`、`status`、`doctor`、`setup [--reconfigure]`、`service`(`service.rs`:launchd / systemd 用户服务)、`login`、`sign`、`resign`、`passcode`、`unlock-reset`、`devices`、`select`、`wda-bridge`、`viewer`(`viewer.rs`:本机控制台网页,实时画面、设备面板;`agent.rs`:页面上的 AI 任务,`viewer.html` 是页面)、`notify-test`;隐藏的 `debug <ddi\|hid\|screenshot\|soak\|wda\|e2e>` 真机诊断(原第 0 步 spike,不经守护进程;feature `debug-cmds`,默认不编译) | `clap` |依赖方向:`apps` → `ictl-daemon` / `ictl-mcp`,还直接依赖 `ictl-device`、`ictl-sign`;`ictl-daemon` → `ictl-unlock` → `ictl-wda` → `ictl-device`;`ictl-daemon` 还直接依赖 `ictl-webinspector`、`ictl-sign` 和 `ictl-protocol`。`ictl-device` 也依赖 `ictl-webinspector`(打开连接)。`ictl-mcp` 只依赖 `ictl-protocol` 和 `ictl-l10n`,不依赖守护进程和设备层。`ictl-l10n` 不依赖其他 crate,除 `ictl-webinspector` 外都用它。`apps` 的 `debug`(feature `debug-cmds`)直接调用 `ictl-device`、`ictl-wda`。## 5. 截图与坐标-- 坐标单位统一用**点(pt)**,与 WDA 一致,随界面方向变化;屏幕点尺寸从 WDA `/wda/screen` 读取。WDA 就绪时把竖放尺寸和设备 UDID 记到 `state.json`(只记最近一台)。WDA 不可用时:记录是这台的就用记录,否则用 `.env` 的 `SCREEN_W`/`SCREEN_H`(不分设备),都没有就报错(不写死 430×932)。+- 坐标单位统一用**点(pt)**,与 WDA 一致,随界面方向变化;屏幕点尺寸从 WDA `/wda/screen` 读取。WDA 就绪时把竖放尺寸和设备 UDID 记到 `state.json`(只记最近一台)。WDA 不可用时:记录是这台的就用记录,否则用设置里的 `SCREEN_W`/`SCREEN_H`(不分设备),都没有就报错(不写死 430×932)。- HID 坐标是 0~65535 归一化:先按界面方向转回竖放(`Rotation::to_portrait`),再换算 `x / w * 65535`。每次 HID 触摸前重新截图核对横竖;横屏要有 30 秒内且匹配的 WDA 旋转角,否则拒绝触摸。- 截图优先走 WDA(toolkit 实测约 0.4 秒);WDA 不可用时走 CoreDevice `screencaptureservice`(不需要签名)。- 区域放大:从原始像素截图裁剪,长边 < 600 放大到 600,> 1200 缩到 1200,返回倍数和坐标换算式(三位有效数字)。## 6. 数据与秘密目录-全部在一个数据根目录下(root 默认 `/var/lib/iphone-control`,容器里挂卷;普通用户默认 `$XDG_DATA_HOME/iphone-control`,没设时 `~/.local/share/iphone-control`,macOS 相同)。数据根目录是 0700;下表权限写「默认」的没有单独设,靠它保护:+全部在一个数据根目录下(普通用户默认 `$XDG_DATA_HOME/iphone-control`,没设时 `~/.local/share/iphone-control`,macOS 相同;以 root 运行时是 `/var/lib/iphone-control`,安装方式都不这样用)。数据根目录是 0700;下表权限写「默认」的没有单独设,靠它保护:-| 路径 | 内容 | 权限 | 进 git / 进镜像 |+| 路径 | 内容 | 权限 | 进 git / 进发布包 ||---|---|---|---|-| `lockdown/` | 配对记录(容器里的 usbmuxd 读写,即 `/var/lib/lockdown`;用系统的 usbmuxd 服务时不用这里,记录在系统的 `/var/lib/lockdown`;macOS 在 `/var/db/lockdown`,和 Finder 共用) | 0700 | 否 |+| `lockdown/` | 不再使用(以前容器里的 usbmuxd 把配对记录放这里)。配对记录由系统的 usbmuxd 保存:Linux 在 `/var/lib/lockdown`,macOS 在 `/var/db/lockdown`,和 Finder 共用 | 0700 | 否 || `account/` | Apple ID 会话、开发私钥、证书 | 0700 | 否 || `ddi/` | 开发者镜像缓存(运行时下载的苹果文件);设了 `ICTL_DDI_DIR` 时用那个目录,不用这里 | 默认 | **否,不得分发** |-| `wda/` | 当前签好的包 `WDA-signed.ipa`。未签名包在镜像的 `/usr/share/iphone-control/WDA-unsigned.ipa`:构建时下载 Appium 官方的未签名真机包(`WebDriverAgentRunner-Runner.zip` v16.15.3,校验 sha256)重新打包。从源码运行时没有镜像,第一次签名前按同一版本下载、校验,转成 `wda/WDA-unsigned.ipa`(`crates/ictl-daemon/src/wda_pkg.rs`,版本与 Dockerfile 由单测核对);计划改为本项目 macOS CI 编译。描述文件只嵌在签好的包里,到期时间记在 `state.json` | 默认 | 未签名包进镜像(从源码运行时在本机下载) |+| `wda/` | 当前签好的包 `WDA-signed.ipa`,和未签名包 `WDA-unsigned.ipa`:第一次签名前下载 Appium 官方的未签名真机包(`WebDriverAgentRunner-Runner.zip` v16.15.3,校验 sha256)重新打包(`crates/ictl-daemon/src/wda_pkg.rs`);计划改为本项目 macOS CI 编译。描述文件只嵌在签好的包里,到期时间记在 `state.json` | 默认 | 否(在本机下载) || `secrets/passcodes/<UDID>` | 各设备的锁屏密码(仅启用自动解锁时);旧版本的 `secrets/passcode` 在只接着一台时归到那台名下 | 0600 | 否 |-| `logs/` | 事件日志 `daemon.log`(超过 5 MB 轮转成 `.1`);`usbmuxd.log`(自管 usbmuxd 时的输出,超过一定大小时在启动 usbmuxd 前轮转);自动解锁停用标记 `UNLOCK-DISABLED`(与 toolkit 一致,便于人工发现;全局,不分设备) | 默认 | 否 |+| `logs/` | 事件日志 `daemon.log`(超过 5 MB 轮转成 `.1`);自动解锁停用标记 `UNLOCK-DISABLED`(与 toolkit 一致,便于人工发现;全局,不分设备) | 默认 | 否 || `state.json` | 最近一次签名的 Team ID、WDA Bundle ID、描述文件到期时间;选定的设备;最近一台就绪设备的竖放屏幕尺寸和 UDID;上次重签结果 | 默认 | 否 |-没有配置文件,通知渠道也一样:配置全部来自环境变量(容器里由 `.env` 注入,从源码运行时由 shell 或 systemd 的 `EnvironmentFile` 给,见 `.env.example`、`crates/ictl-daemon/src/config.rs`),都有默认值;秘密只放文件。+守护进程的配置全部来自环境变量(`crates/ictl-daemon/src/config.rs`),都有默认值。设置文件 `~/.config/iphone-control/env`(`KEY=value`,0600,模板 `packaging/env.example`)由首次运行引导和 `setup --reconfigure` 写(`envfile.rs`:改一项就地替换,注释和其他项保留);后台服务(launchd、systemd、`brew services`)把它读进守护进程的环境,其他命令启动时也读一遍,已有的环境变量优先。通知渠道的密钥也在这个文件里;其余秘密只放数据目录里的文件。## 7. 重签与通知- 守护进程每 `RESIGN_CHECK_HOURS`(默认 6 小时)检查一次:描述文件剩余 < `RESIGN_MIN_DAYS`(默认 2 天)才重签;另外**每天验证一次 Apple ID 会话**(toolkit 的教训:只在要重签时才发现登录过期,只剩 2 天处理)。两者都在后台跑,不持设备锁。只检查正在控制的那台;手机重新连上或切换设备后 1 分钟内也查一次。- 重签流程:`plume_core` 取新描述文件 → `ictl-sign` 签名(含 `.xctest`)→ `installation_proxy` 安装 → 下一轮巡检重启 WDA。安装成功后才替换旧文件。整个重签有总时限,超时按失败处理并推送通知。没装过当前 Apple ID 签的 WDA 的设备不自动重签(注册设备占 Apple ID 的名额,交给用户决定)。-- 通知事件:重签失败、Apple ID 会话失效、需要输入自动化密码、WDA 恢复、自动解锁失败已停用、手机离线超过 10 分钟、恢复在线。通知文字不带设备名。去重:重签失败、会话失效 20 小时内不重复;等密码、离线、自动解锁停用推一次,直到恢复或 `unlock-reset`;只有等密码和离线有恢复推送。去重记录只在内存里,守护进程重启后清空。-- 容器整个挂掉时守护进程发不了通知,这部分仍需宿主机侧的监控,本项目还没有提供。从源码运行时 `deploy/iphone-control.service` 只负责崩溃后重启,同样不报警。+- **签名证书**:每个账号目录有自己的私钥(`account/keys/<团队>/key.pem`)和对应的开发证书;免费团队同时最多两张,新建时满了 plume 会吊销一张,不挑是谁的,用它签的 App 在所有设备上都起不来,描述文件却仍有效。所以:读设备上的 WDA 描述文件时顺带离线判断里面有没有本机公钥的证书(`foreign_wda`);每天的会话检查顺带联网查本机证书还在不在团队里(`own_cert`)。设备拒绝启动 WDA(只报 `unexpected response`)时,两者任一有问题就自动重签这台,同一台 6 小时内最多一次;都没问题就多半是还没信任开发者,留给用户。签名新建或吊销证书时写日志、推送。`doctor` 显示这两项。+- 通知事件:重签失败、Apple ID 会话失效、需要输入自动化密码、WDA 恢复、自动解锁失败已停用、手机离线超过 10 分钟、恢复在线、签名证书换了。通知文字不带设备名。去重:重签失败、会话失效 20 小时内不重复;等密码、离线、自动解锁停用推一次,直到恢复或 `unlock-reset`;只有等密码和离线有恢复推送;签名证书换了每次都推。去重记录只在内存里,守护进程重启后清空。+- 守护进程整个挂掉时发不了通知,这部分仍需宿主机侧的监控,本项目还没有提供。后台服务(`iphone-control service install` 装的 launchd 或 systemd 服务)只负责崩溃后重启,同样不报警。diff --git a/docs/decisions.md b/docs/decisions.mdindex ae0563f..a1a315b 100644--- a/docs/decisions.md+++ b/docs/decisions.md@@ -19,20 +19,21 @@- **决定**:用 idevice 的 provider 直连设备端口访问 WDA;外部工具需要时显式开 bridge,只绑 127.0.0.1。- **理由**:WDA 没有认证;toolkit 早期用 `ios forward` 监听了所有网卡,局域网内任何人都能控制手机。-- **补充**:`iphone-control viewer` 用同样的保护模型(显式开启、只绑 127.0.0.1、检查 `Host`),另加操作的 `Origin` 和 JSON 内容类型检查,并绑定启动时正在控制的设备。+- **补充**:`iphone-control viewer` 用同样的保护模型(显式开启、只绑 127.0.0.1、检查 `Host`),另加操作的 `Origin` 和 JSON 内容类型检查、读接口的 `Sec-Fetch-Site` 检查,并只作用于页面跟着的那台设备。它的 AI 任务不开新端口:agent 的 MCP 服务经控制接口旁边的 Unix socket(0600,每个任务一个口令)回报 viewer。## D4:WDA 仍然是 Objective-C,在 macOS CI 上编译- **决定**:不重写 WDA;fork appium/WebDriverAgent,在 GitHub Actions macOS runner 上不签名编译,发布未签名 IPA + sha256。- **理由**:WDA 是 XCTest bundle,只能用 Xcode 编译,依赖苹果私有/测试框架;Rust 无法替代。- **代价**:发布流程依赖 macOS runner。-- **现状**:自己编译还没做;镜像构建时暂时下载 Appium 官方 Release 的未签名真机包(v16.15.3,校验 sha256)。+- **现状**:自己编译还没做;暂时在第一次签名前于本机下载 Appium 官方 Release 的未签名真机包(v16.15.3,校验 sha256)。-## D5:保留系统 usbmuxd,作为子进程看护+## D5:使用系统的 usbmuxd-- **决定**:不内置 USB 协议栈。Linux 上使用 Debian 的 `usbmuxd`:容器里作为子进程看护,以普通用户运行时用系统服务。macOS 用系统自带的 usbmuxd,守护进程不启动也不重启它。+- **决定**:不内置 USB 协议栈。Linux 上用发行版的 `usbmuxd` 包(.deb 依赖它),macOS 用系统自带的;守护进程不启动也不重启它。- **理由**:idevice 只有 usbmuxd 客户端;自己实现 USB 多路复用收益很小;usbmuxd 是 GPL-3.0,作为独立进程运行不影响本项目许可证。-- **代价**:仍需处理容器无 udev 的热插拔问题(sysfs 兜底 + 重启)。+- **代价**:Linux 上要用户自己装 usbmuxd(install.sh 会提示,.deb 自动装上)。+- **变更(2026-11-10)**:以前在容器里把 usbmuxd 作为子进程看护(`ICTL_MANAGE_USBMUXD`、`ICTL_USBMUXD_BIN`),还要处理容器没有 udev 的热插拔(数 sysfs,台数对不上就重启它)。去掉 Docker 后这部分删了,见 D14。## D6:签名组件 vendor 而不是 git 依赖@@ -53,7 +54,7 @@## D9:所有依赖锁定精确版本-- **决定**:`Cargo.toml` 用 `=x.y.z`,`Cargo.lock` 入库,Docker 基础镜像锁 digest。+- **决定**:`Cargo.toml` 用 `=x.y.z`,`Cargo.lock` 入库,CI 和发布用的 Rust 工具链、cargo-about 也锁版本。- **理由**:toolkit 两次被版本漂移坑过(mcp 2.x 改名;go-ios main 分支命令变化)。idevice 官方也要求锁定。## D10:与 toolkit 工具接口一致@@ -75,7 +76,7 @@## D12:界面文字可选英文,默认仍是中文- **决定**:`IPHONE_CONTROL_LANG=en|zh` 选择人和 agent 看到的文字的语言(工具说明、工具结果、命令行输出、日志、通知);不设或认不出时是简体中文。每条文字在代码里原地写成中英一对(`ictl-l10n` 的 `tr!` / `trf!`),不另建翻译目录。从手机界面读到的文字(例如「滚动条」)不翻译。-- **结果的语言由客户端决定**:MCP 和命令行在每个请求里带上自己的语言(`lang` 键),守护进程按它回答;不带 `lang` 的请求(旧版本客户端)照旧得到中文,因为它们按中文的固定开头认结果。守护进程自己的设置管它主动写的文字(事件日志、日志行、通知),处理请求时写的也一样(`ictl-l10n` 的 `log_tr!` / `log_trf!`),所以日志和通知始终是同一种语言。上次重签的结果存成时间和成败,显示时再按看的人的语言拼句子。容器部署里 MCP 和守护进程读同一个 `.env`,自然一致。+- **结果的语言由客户端决定**:MCP 和命令行在每个请求里带上自己的语言(`lang` 键),守护进程按它回答;不带 `lang` 的请求(旧版本客户端)照旧得到中文,因为它们按中文的固定开头认结果。守护进程自己的设置管它主动写的文字(事件日志、日志行、通知),处理请求时写的也一样(`ictl-l10n` 的 `log_tr!` / `log_trf!`),所以日志和通知始终是同一种语言。上次重签的结果存成时间和成败,显示时再按看的人的语言拼句子。MCP 和守护进程启动时都读设置文件 `~/.config/iphone-control/env`,自然一致(注册 MCP 时用 `-e` 设的值优先)。- **客户端要据以行动的结果用字段表示**:文字结果带 `outcome`(`tapped_nothing`:按名字没点到;`alert_reported`:结果里已经报过系统弹窗),新版本 MCP 只看字段,不再从文字里认;没有 `outcome` 的响应来自旧版本守护进程,那时文字一定是中文,才按 `TAP_MISSED`、`ALERT_BLOCKING` 认。旧版本客户端不认识这个字段,会忽略它。- **理由**:D10 承诺已有工具的默认返回不变,所以英文只能是可选项,不设就和以前完全一样。两种语言并排写在原处,改文字时另一种就在旁边,审查时也能逐条对照。- **代价**:每条新文字都要写两种语言;取语言是一次原子读,开销可以忽略。@@ -89,5 +90,16 @@- 日志:idevice 默认的 `StreamFlags` 带 Debug,手机上每个进程都开始产生 Debug 消息。真机上约 650 行/秒,不开时约 80 行/秒;开着时手势变慢、失败(`crates/ictl-device/src/oslog.rs`)。- Web Inspector:刚关闭后新开一条连接约 8 秒,几轮连接、断开后手机不再向新连接报告 Safari,要重启 Safari;保留的连接上列表和执行只要几毫秒(iPhone 15 Pro Max,iOS 27.0.1,`crates/ictl-daemon/src/web.rs`)。- 卸载连同数据一起删掉,猜错名字的代价比启动错 App 大得多。-- **代价**:开关挡不住能连上控制接口的本机进程,真正的边界是 socket 权限;从源码运行时开关要设在 MCP 的环境里,守护进程的 env 文件不生效;看不到 Debug、Info 级别的日志;保留的连接要 5 分钟没有请求才关。+- **代价**:开关挡不住能连上控制接口的本机进程,真正的边界是 socket 权限;开关要对 MCP 进程生效:写在设置文件里,或注册 MCP 时用 `-e` 设(首次运行引导和 `mcp-config` 会带上);看不到 Debug、Info 级别的日志;保留的连接要 5 分钟没有请求才关。- **重新评估**:出现需要在守护进程上按调用方限权的场景时;iOS 能在手机端按进程过滤日志时。++## D14:去掉 Docker,只做原生安装(2026-11-10)++- **背景**:以前 Linux 上推荐用 Docker(`compose.yaml`、ghcr 上的镜像),macOS 和从源码运行是另一套步骤。控制台(`iphone-control viewer`)加了 AI 任务以后,任务要交给本机的 Claude Code 或 Codex 执行。+- **决定**:从下一个版本起不再发布 Docker 镜像,删掉 `compose.yaml`、`docker/Dockerfile`、`.dockerignore` 和 `deploy/iphone-control.service`。安装只有原生方式:一行命令的 `install.sh`(macOS Apple Silicon、Linux x86_64/aarch64)、Homebrew(`derrors/tap`)、Debian/Ubuntu 的 `.deb`,以及从源码编译(Intel Mac、开发)。守护进程以普通用户运行,装成用户服务(macOS 是 launchd,Linux 是 systemd 用户服务),由 `install.sh`、`iphone-control service install`、`brew services` 或 .deb 的 unit 管理。usbmuxd 用系统的(D5)。装好后运行 `iphone-control`,首次运行引导一步步完成设置,写 `~/.config/iphone-control/env`。+- **理由**:+ - 容器里的守护进程够不到宿主机上的 Claude Code / Codex(它们的登录、配置都在用户的家目录里),控制台的 AI 任务用不了。+ - 原生安装更简单:不用 root、不用 Docker、不用 USB 直通,macOS 和 Linux 是同一套步骤;Mac 上本来就不能用 Docker(Docker Desktop 不支持 USB 直通)。+ - 少一套要维护的东西:自管 usbmuxd、容器没有 udev 的热插拔兜底、镜像构建和 SBOM、`docker exec` 形式的注册命令都不要了。+- **代价**:Docker 用户要迁移(数据目录拷到 `~/.local/share/iphone-control`,`.env` 改成 `~/.config/iphone-control/env`,手机可能要重新信任,见更新日志的升级注意事项);Linux 上要自己装 usbmuxd;不能再用容器把它和宿主机隔离开,守护进程的权限就是登录用户的权限;Intel Mac 没有预编译版本,要从源码编译。+- **重新评估**:有人需要在无人值守的服务器上隔离运行、又不用控制台的 AI 任务时。diff --git a/docs/dev/macos-verification.md b/docs/dev/macos-verification.mdindex ca6f710..3865b14 100644--- a/docs/dev/macos-verification.md+++ b/docs/dev/macos-verification.md@@ -59,10 +59,7 @@ iphone-control --version### 注意事项-- **全程用普通用户运行,不要 sudo。** 以 root 运行时,守护进程会自己启动一个 usbmuxd,和系统的冲突。保险起见,每个终端先执行:- ```bash- export ICTL_MANAGE_USBMUXD=0- ```+- **全程用普通用户运行,不要 sudo。** 以 root 运行时,守护进程改用 Linux 的系统路径(`/var/lib/iphone-control`、`/run/iphone-control`)。- 数据目录是 `~/.local/share/iphone-control`,控制接口在 `~/.local/share/iphone-control/ctl.sock`(macOS 没有 `XDG_RUNTIME_DIR`)。- 同一时间只能有一个程序控制手机:守护进程、`iphone-control debug …`、Xcode 的 UI 测试不要同时跑。@@ -200,8 +197,7 @@ done## 已知差异(不算失败)- 数据目录在 `~/.local/share` 下,不是 Mac 习惯的 `~/Library/Application Support`。-- 还没有 launchd 配置,只能前台运行。-- 不能用 Docker:Docker Desktop 在 Mac 上不支持 USB 直通。+- 这份步骤让守护进程在终端里前台运行,方便看输出;日常使用时装成 launchd 服务(`iphone-control service install`),launchd 方式本身还没按这份清单验证过。## 清理diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.mdindex db5f1e0..6aecbca 100644--- a/docs/dev/regression-cases.md+++ b/docs/dev/regression-cases.md@@ -1,6 +1,6 @@# 必须覆盖的回归用例-#1~#34 来自 toolkit 和本项目早期实际踩过的坑,#35~#45 是多设备和 HID 横屏,#46~#58 是实时画面、开发者工具和英文界面,#59 起是 iPhone 18 Pro Max(iOS 27.2.1)真机全量测试发现的问题。能单测的写单测,不能单测的进真机回归清单:改了设备、时序、WDA 相关的代码,要在真机上重跑相关的用例,并在 PR 里写明跑了哪些、用什么设备和 iOS 版本。+#1~#34 来自 toolkit 和本项目早期实际踩过的坑,#35~#45 是多设备和 HID 横屏,#46~#58 是实时画面、开发者工具和英文界面,#59~#63 是 iPhone 18 Pro Max(iOS 27.2.1)真机全量测试发现的问题,#64 起是 viewer 的 AI 任务和新页面。能单测的写单测,不能单测的进真机回归清单:改了设备、时序、WDA 相关的代码,要在真机上重跑相关的用例,并在 PR 里写明跑了哪些、用什么设备和 iOS 版本。| # | 坑 | 正确行为 | 测试方式 ||---|---|---|---|@@ -10,7 +10,7 @@| 4 | 多位密码合成一个 W3C 手势会漏键 | 每位单独一个手势并逐位核对 | 真机 || 5 | 锁屏上 `/wda/tap` 每次约 2.9 秒 | 解锁用 W3C 单手势(约 0.7 秒) | 真机计时 || 6 | 同名「设置」有 5 个 `SBAppTags` 含 `hidden` 的后台服务 | 按名字解析 App 时跳过 hidden | 单测 |-| 7 | 容器无 udev,手机重启/重插后 usbmuxd 看不到设备 | sysfs 里 iPhone/iPad/iPod 的台数连续 3 次多于 usbmuxd 认到的台数 → 重启 usbmuxd(只在自管 usbmuxd 时) | 单测(`usbmuxd_restart_after_three_misses`)+ 真机(杀 usbmuxd 模拟) |+| 7 | 容器无 udev,手机重启/重插后 usbmuxd 看不到设备 | 不再适用:2026-11-10 起不发布 Docker,守护进程不再自管 usbmuxd,热插拔由系统的 usbmuxd 和 udev 处理(D5、D14) | — || 8 | 手机重启后 XCTest 弹「Enable UI Automation」密码框 | 识别错误、只推送一次、60 秒重试、恢复后再推送 | 单测(错误识别)+ 真机 || 9 | plumesign 不签 `.xctest`,WDA 报 XCTest 103 | `.xctest` 签名、无 entitlements | 单测(签完检查 `_CodeSignature`)+ 真机 || 10 | `ios forward` 监听所有网卡,WDA 无认证,局域网可直接控制手机 | 默认不监听任何端口;bridge 只绑 127.0.0.1 | 集成测试(检查监听地址) |@@ -33,7 +33,7 @@| 27 | HID 会话在屏幕媒体流起来之后才失败,媒体流没停(症状同 #24) | `HidSession::open`、`media::start` 出错时先停流;HID 会话归 `Tunnel` 所有,关隧道必先停流 | 真机 || 28 | 一个长操作(启动 WDA 等自动化密码最长 120 秒)挡住所有工具、`status` 和 SIGTERM,排队的点击几分钟后才执行 | 启动 WDA、重签、会话检查不持设备锁;`status` 读快照;改变手机状态的请求排队超过 30 秒就放弃;停止信号优先处理(architecture §2 并发模型) | 真机 || 29 | WDA 请求超时或中途断开后退到 HID,同一个动作做了两遍 | 传输层区分连不上(`WdaError::Unavailable`,可以退到 HID)和请求已发出之后的超时、断开、响应不完整(不退,报错让 agent 先截图确认) | 单测 + 代码审查 |-| 30 | `.env` 里留空的 `ICTL_LOG=` 生成一个什么都不放行的过滤器,日志全没了 | 空值当作没设 | 真机(`docker logs`) |+| 30 | 设置文件里留空的 `ICTL_LOG=` 生成一个什么都不放行的过滤器,日志全没了 | 空值当作没设 | 真机(看守护进程的输出) || 31 | `/wda/tap` 每次先等界面空闲:主屏点图标约 1.7 秒(调小等待设置也没用);W3C actions 手势做完又要等动画冷却(默认 2 秒),App 里切标签约 1.9 秒 | 点击用单个 actions 手势,期间临时把 waitForIdleTimeout/animationCoolOffTimeout 调成 1/0.2,做完恢复(原值只读一次)。真机:主屏点图标 1.70→0.91 秒(到前台 1.80→1.01 秒),App 里 0.62→0.72 秒 | 单测(请求顺序、恢复原值)+ 真机计时 || 32 | `/wda/keys` 没有输入框获得焦点时也返回成功,什么都没输(真机:Safari 地址栏没点中、主屏上直接输入) | 输入前查屏幕上有没有软键盘(`XCUIElementTypeKeyboard`,约 0.2 秒),没有就报错让先点输入框 | 真机 || 33 | 系统弹窗(定位、通知权限)挡着时 Home 不生效、App 到不了前台,WDA 照样报成功;弹窗属于 SpringBoard,看前台 App 发现不了 | 按 Home 前查 `/alert/text`(App 静止时约 0.4 秒;按下后动画中查要好几秒);有弹窗就说明并不按。launch_app 没到前台时同样带上弹窗文字。按 Home 后等主屏到前台再返回 | 真机计时;弹窗路径待弹窗再出现时复测 |@@ -44,9 +44,9 @@| 38 | 选定的设备重启守护进程后丢了;设了 `IPHONE_UDID` 还能切走 | 选定的写进 state.json;`IPHONE_UDID` 优先,设了就拒绝切到别的设备 | 真机(`select` 后重启;设 `IPHONE_UDID` 后 `select` 另一台) || 39 | 切换后操作还落在上一台,或用了上一台的 App 列表、方向、屏幕尺寸 | 切换时拆掉上一台的会话,清掉 App 列表和方向;屏幕尺寸记录是别的设备的就不用。切换后等 `iphone_status` 就绪,截图、`iphone_list_apps`、点击都要作用在新设备上 | 真机(iPhone + iPad,各做一遍 `iphone_select_device` → 截图 → 点击) || 40 | 一台的密码输进另一台 | 密码按设备存(`secrets/passcodes/<UDID>`);旧的 `secrets/passcode` 只在 USB 上只接着一台时归到那台,接着多台时不用 | 单测(`passcode_file_is_per_device_and_stays_in_its_dir`)+ 真机 |-| 41 | 已接着一台时再插一台,没有 udev 的 usbmuxd 认不到第二台 | 比台数,不只看「有没有设备」 | 单测(`usbmuxd_restart_when_a_second_device_is_missed`)+ 真机 |+| 41 | 已接着一台时再插一台,没有 udev 的 usbmuxd 认不到第二台 | 不再适用:同 #7,守护进程不再自管 usbmuxd | — || 42 | 自动选设备时 `iphone_batch` 执行到一半换了设备(拔线后换到另一台),剩下的步骤落到另一台上 | 控制的设备变了就停下报错 | 真机(batch 里放 `wait`,中途拔线) |-| 43 | Apple 键盘等配件被当成手机:`doctor` 误报 USB 上有设备,usbmuxd 被反复重启 | 只算 iPhone/iPad/iPod(厂商号 05ac 且产品名匹配) | 单测 + 真机 |+| 43 | Apple 键盘等配件被当成手机:`doctor` 误报 USB 上有设备(以前自管 usbmuxd 时还会被反复重启) | 只算 iPhone/iPad/iPod(厂商号 05ac 且产品名匹配) | 单测 + 真机 || 44 | 横屏时 WDA 掉线,HID 触摸按竖屏坐标换算,点错位置 | 每次 HID 触摸前重新截图核对横竖;横屏要有 30 秒内且匹配的 WDA 旋转角才发送,否则拒绝,不猜方向;截图和按键不受影响 | 单测(`hid_rotation_requires_fresh_matching_landscape`)+ 真机(iOS 27 横屏下让 WDA 掉线,点击落点正确;守护进程重启后横屏触摸被拒绝) || 45 | WDA 在横屏时就绪,记下的是横屏尺寸,之后 HID 换算错 | state.json 只存竖放尺寸和对应的 UDID,换算时再按当前方向转 | 真机(iOS 27,横屏下启动 WDA,再让它掉线后点击) || 46 | 浏览器里的其他网页向 `viewer` 发请求,借它操作手机 | 操作要求 `Origin` 是页面本身、内容类型是 JSON;`Host` 必须是回环地址 | 单测(`actions_need_own_origin_and_json`) |@@ -67,3 +67,16 @@| 61 | 点击、长按用 0.2 秒的动画冷却:界面上一直有动画时(键盘弹着)WDA 要约 26 秒才返回(同 `NO_COOL_OFF` 注释里滑动的情况) | 点击、长按和滑动一样用冷却 0(`IdleSettings::NO_COOL_OFF`);解锁仍用 `QUICK` | 单测(`tap_is_one_gesture_with_quick_waits_then_restores_baseline`)+ 真机计时(设置里搜索后点结果:26 秒 → 1.4 秒;主屏点图标、App 里切标签不变慢) || 62 | 网页检查器没开时手机直接断开 Web Inspector 连接,工具只报一句 TLS 错误 | 连接被手机断开时提示打开 设置 → Safari → 高级 → 网页检查器 | 单测(`a_closed_connection_points_at_the_web_inspector_setting`)+ 真机(开关关着时调 `iphone_web_targets`) || 63 | 不带调试消息的日志流里仍有 Info 级别的条目,和 `iphone_app_logs` 的说明不符 | 采集时丢掉 Info、Debug | 单测(`info_and_debug_entries_are_not_kept`)+ 真机 |+| 64 | Codex 对标了 destructiveHint 的 MCP 工具默认要审批,`codex exec` 非交互运行时直接拒绝(「requires approval, but approval policy is never」),点击、滑动全都做不了 | 给 iphone 这个 MCP 服务设 `default_tools_approval_mode="approve"`,由 `iphone_confirm` 把关 | 真机(Codex 任务里点击、按名字点都执行了) |+| 65 | viewer 已经停了、任务已经停了,agent 的 MCP 服务还在继续操作手机 | 闸门连不上或任务已结束一律拒绝,并告诉 agent 停下 | 单测(`a_gate_nobody_listens_on_refuses`、`a_stopped_task_refuses_everything`)+ 真机(任务中途停止,之后没有新步骤,agent 进程组已结束) |+| 66 | 暂停只挡住了界面上的按钮,agent 照样继续点 | 暂停、接管、等确认时,下一个工具调用在闸门处挂住,恢复后才放行 | 单测(`a_paused_task_holds_the_call_until_resumed`)+ 真机(暂停 8 秒没有新步骤) |+| 67 | 用户接管时动过手机,交还后 agent 按旧的界面接着点 | 交还后第一个不是看屏幕的调用被拒,让它先截图 | 单测(`after_a_takeover_the_agent_looks_again_before_acting`)+ 真机(交还后先截图) |+| 68 | 用户拒绝确认后 agent 正常结束,页面显示「已完成」 | 有被拒绝的一步就按「已停止」结束 | 单测(`a_rejected_confirmation_tells_the_agent_not_to_do_it`)+ 真机(拒绝删除世界时钟城市,没有删) |+| 69 | 按结果文字里的 `@(x,y)` 给所有步骤画点击标记,读元素的一步也被标成点击 | 只给 `iphone_tap_element` 的结果解析点击位置 | 单测(`only_a_tap_by_text_gets_a_mark_from_its_result`) |+| 70 | 其他网站用 `<img src="http://127.0.0.1:8200/api/elements">` 触发读元素,顺带自动解锁手机 | 浏览器标明 `Sec-Fetch-Site` 不是 same-origin / none 的读请求一律 403 | 单测(`reads_from_other_sites_are_refused`)+ curl |+| 71 | AI 任务执行中,用户在页面上点击和 agent 同时操作 | 没有接管时 viewer 拒绝手动操作(409 并说明),页面也锁住 | 真机(任务中 `/api/tap` 被拒,接管后按 Home 生效) |+| 72 | 设计稿在 1024×768 下横向溢出 26px:中间栏各行按内容最小宽度把栏撑出窗口 | 中间栏各行 `min-width: 0`;两栏区间「设备面板」只留图标;状态标签先让出空间 | Playwright:360×800 到 1920×1080 共 11 个视口横向溢出都是 0 |+| 73 | viewer 的手动操作走 WDA:点击约 530 毫秒,滑动要等列表停下(1.8~3 秒),松开鼠标后才滑,画面不跟手 | iOS 27 起经 HID 实时发按下、移动、松开(`Request::Touch`),移动只发最新位置;滚轮换成手指拖动 | 单测(`page_actions_map_to_daemon_requests`)+ 真机(iPhone 18 Pro Max / iOS 27.2.1:移动约 2 毫秒,点击约 20 毫秒;拖动、滚轮滚动设置列表,点击进入「通用」,按住 1 秒出主屏菜单) |+| 74 | 每次 HID 触摸前截图核对方向(几百毫秒),实时移动跟不上 | 只在 `down` 时核对一次(有 WDA 时读它的旋转角),移动、抬起直接用已开的会话 | 真机计时 |+| 75 | WDA 的 MJPEG 默认每秒 10 帧,画面比操作慢 | 每秒 60 帧、75% 尺寸(`fast_stream`);只在有客户端时采集 | 真机:约 48 fps、34 KB/帧,读元素树不变慢 |+| 76 | viewer 页面只有中文 | 页面文字中英两套(`tr()`),默认跟着 `IPHONE_CONTROL_LANG`,可切换;请求带 `X-Ictl-Lang`,守护进程的提示和 AI 任务用同一种语言 | 单测(`the_page_says_its_default_language`)+ Playwright(英文页面除切换按钮和手机上的数据外没有中文;360×800 到 1920×1080 中英文都没有横向溢出)+ 真机(英文 AI 任务) |diff --git a/docs/licensing.md b/docs/licensing.mdindex eb37b08..e2b7e68 100644--- a/docs/licensing.md+++ b/docs/licensing.md@@ -18,9 +18,9 @@| plume_utils(Impactor) | Bundle、Signer | MIT(Impactor 根 LICENSE) | **未 vendor**:`ictl-sign/src/bundle.rs` 改写自它的 `bundle.rs`,签名流程在 `ictl-sign/src/lib.rs` 重写 | 文件头注明来源和版权 || apple-codesign 0.29.0 | 代码签名 | **MPL-2.0** | vendor 到 `vendor/apple-codesign`(Impactor 打过 0o755 权限补丁的副本;去掉了上游的 tests/、docs/、src/testdata/),经 `[patch.crates-io]` 替换 | 以 MPL-2.0 随仓库提供源码 || rmcp 3.8.0 | MCP SDK | Apache-2.0(部分历史代码 MIT) | crates.io 依赖 | 保留 NOTICE/版权声明 |-| tokio、reqwest、quick-xml、image、clap、serde 等 | 通用 | MIT / Apache-2.0 | crates.io 依赖 | 保留声明:镜像里的 `/usr/share/doc/iphone-control/THIRD_PARTY_LICENSES.html` 由 cargo-about 按 Cargo.lock 生成,含许可证全文。这份清单只随镜像分发,预编译二进制的压缩包只带 `LICENSE` 和 `THIRD_PARTY.md` |-| WebDriverAgent(Appium) | 手机端代理 | BSD-3-Clause(Facebook 原始) | 镜像构建时下载 Appium 官方的未签名真机包(v16.15.3,校验 sha256)打成 IPA;计划改为本项目 macOS CI 编译 | 保留 BSD 声明(镜像里 `/usr/share/licenses/WebDriverAgent/LICENSE`) |-| usbmuxd | USB 守护进程 | **GPL-3.0**(以其 README 为准;GitHub 显示 GPL-2.0 有误) | 系统包,独立进程,不链接 | 仅"放在一起分发"。发布镜像时要提供对应源码(Debian 源码包)和许可证文本 |+| tokio、reqwest、quick-xml、image、clap、serde 等 | 通用 | MIT / Apache-2.0 | crates.io 依赖 | 保留声明:`THIRD_PARTY_LICENSES.html` 由 cargo-about 按 Cargo.lock 生成,含许可证全文,放在每个发布的压缩包里(.deb 里在 `/usr/share/doc/iphone-control/`),和 `LICENSE`、`THIRD_PARTY.md` 一起 |+| WebDriverAgent(Appium) | 手机端代理 | BSD-3-Clause(Facebook 原始) | 第一次签名前在用户的机器上下载 Appium 官方的未签名真机包(v16.15.3,校验 sha256)打成 IPA,项目本身不分发;计划改为本项目 macOS CI 编译 | 不分发时没有义务;改为自己编译并分发时要保留 BSD 声明 |+| usbmuxd | USB 守护进程 | **GPL-3.0**(以其 README 为准;GitHub 显示 GPL-2.0 有误) | 系统包(Linux 上用发行版的包,.deb 只声明依赖;macOS 自带),独立进程,不链接 | 不随项目分发,没有额外义务(以前的 Docker 镜像里带着它,要提供对应源码) |## MPL-2.0 怎么处理@@ -32,13 +32,13 @@ MPL-2.0 是按文件计算的弱 copyleft:## 依赖许可证检查-`docker/about.toml` 列出允许的许可证(MIT、Apache-2.0、BSD、ISC、MPL-2.0 等)。依赖里出现列表以外的许可证(例如 AGPL、没有许可证声明的 crate)时 cargo-about 报错,镜像构建失败,要人看过再决定。+`packaging/licenses/about.toml` 列出允许的许可证(MIT、Apache-2.0、BSD、ISC、MPL-2.0 等)。依赖里出现列表以外的许可证(例如 AGPL、没有许可证声明的 crate)时 cargo-about 报错,CI 和发布都会失败,要人看过再决定。## 不能分发的东西| 东西 | 原因 | 处理 ||---|---|---|-| 开发者镜像(DDI、Cryptex 组件、BuildManifest) | 苹果的文件 | 运行时下载到 `ddi/` 缓存;镜像和仓库都不包含。下载来源默认与 pymobiledevice3 一致(社区维护的镜像仓库),也允许用户指向从 Xcode 提取的目录 |+| 开发者镜像(DDI、Cryptex 组件、BuildManifest) | 苹果的文件 | 运行时下载到 `ddi/` 缓存;发布包和仓库都不包含。下载来源默认与 pymobiledevice3 一致(社区维护的镜像仓库),也允许用户指向从 Xcode 提取的目录 || XCTest.framework 等苹果框架 | 苹果的文件 | 编译 WDA 时不嵌入(Appium 官方包也不带),由手机上的开发者镜像提供 || 证书、描述文件、配对记录、Apple ID 会话 | 用户秘密 | 只在用户的数据目录里,`.gitignore` 排除 |diff --git a/docs/tools.md b/docs/tools.mdindex 1b51ae2..8839a8a 100644--- a/docs/tools.md+++ b/docs/tools.md@@ -45,7 +45,7 @@ With `IPHONE_CONTROL_DEV_TOOLS=1` in the MCP server's environment, six more tool|---|---|---|| `iphone_app_logs` | `process`, `grep`, `since` (seconds, default 60, at most 3600), `limit` (default 100, 1 to 1000), `errors_only` | The phone's unified log (os_log) at the default, Error and Fault levels, one line per entry: seconds ago, `process[pid]`, level, subsystem, message. `process` is an app (name or bundle ID) or a process name. Read-only. See the recording notes below the table || `iphone_crash_reports` | `filter`, `name` | Lists crash reports, newest first (at most 50); with `name`, returns that report (`.ips`, cut at 40,000 characters). Read-only |-| `iphone_install_app` | `path` | Installs a signed `.ipa` or `.app` from a path on the machine that runs the daemon (inside the container for a container deployment). Destructive: it replaces an installed copy of the same app |+| `iphone_install_app` | `path` | Installs a signed `.ipa` or `.app` from a path on the machine that runs the daemon. Destructive: it replaces an installed copy of the same app || `iphone_uninstall_app` | `app` | Removes an app and its data. `app` must be a bundle ID or the full display name (case-insensitive); an empty, partial or ambiguous name is refused and the candidates are listed. Refuses to remove the WebDriverAgent runner. Destructive || `iphone_web_targets` | — | Inspectable web pages and WebViews over the Web Inspector service: Safari tabs and inspectable WebViews in apps (debug builds of Capacitor, Cordova, React Native…). One line each: id, type, app, title, URL. Only apps in the foreground answer; needs Settings → Safari → Advanced → Web Inspector. Read-only || `iphone_web_eval` | `expression`, `target`, `timeout` (10 s, at most 60) | Runs JavaScript in a page and returns the result as JSON; a promise is awaited, a DOM node comes back as its description (`"<body>"`). `target` is an id from `iphone_web_targets`, or text in the URL or title; it can be left out when there is one page. Destructive: a script can change the page, submit forms and send requests |@@ -59,6 +59,16 @@ How `iphone_app_logs` records:See [SECURITY.md](../SECURITY.md#developer-tools) before turning these tools on.+## Tasks from the web viewer++When `iphone-control viewer` runs an AI task, it starts the agent with this MCP server and two environment variables, `ICTL_AGENT_GATE` and `ICTL_AGENT_TOKEN`. With them set, every tool call is first reported to the viewer, which shows it as a step, holds it while the task is paused or the user has taken over, and refuses it once the task is stopped; the result (and the screenshot, if any) is reported back afterwards. One more tool is listed:++| Tool | Parameters | Notes |+|---|---|---|+| `iphone_confirm` | `action`, `detail` | Asks the user on the page to confirm one step (paying, deleting, sending a message, changing account settings…) and waits for the answer. A normal result means approved; an error means rejected or the task ended, and the agent must not do the step |++Without the variables, the tool list and every call are unchanged.+## Auto-unlock and "read-only" toolsWhen auto-unlock is configured for the controlled device, a locked phone is unlocked first by the action tools and by `iphone_screenshot`, `iphone_list_elements` and `iphone_wait_for`. `iphone_status`, `iphone_list_apps`, `iphone_list_devices`, `iphone_select_device`, the developer tools and `iphone_press_button` with `lock` never unlock it. While WDA is unavailable nothing is unlocked.diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex b848f31..703ce80 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -1,6 +1,6 @@# Troubleshooting-Start with these two commands (prefix them with `docker exec -it iphone-control` for the container):+Start with these two commands:```bashiphone-control status # current state, signing info, last log lines@@ -15,8 +15,7 @@ Messages are in Simplified Chinese by default, and in English with `IPHONE_CONTR## Phone not detected-- **Container, after unplugging:** the container has no udev, so the daemon notices the phone through sysfs and restarts its own usbmuxd; recovery takes up to about a minute.-- **Two usbmuxd instances:** a host `usbmuxd` (installed by many distributions, started by udev on plug-in) takes the phone away from the container. Mask it with `sudo systemctl mask usbmuxd`, or, for a source install, use the system one and don't run the container.+- **usbmuxd missing (Linux):** the daemon talks to the phone through the system usbmuxd and doesn't start one itself. Install it with `sudo apt install usbmuxd` (the .deb depends on it); udev starts it when the phone is plugged in. Don't mask it.- **Another tool holds the phone:** Xcode-less tools such as go-ios or pymobiledevice3 running at the same time can conflict. Stop them.- **Cable:** some cables only charge. If `lsusb` doesn't show an Apple device (vendor `05ac`), try another cable or port.- **Drops every minute or so while charging:** with *Settings → Battery → Charging → 80% Limit* on, the phone keeps starting and stopping charging near 80%, and each switch renegotiates USB-C power, which briefly disconnects USB (3–5 s). The daemon reconnects by itself, but in-flight actions fail. Set the limit to 100% while the phone is used for automation.@@ -24,19 +23,20 @@ Messages are in Simplified Chinese by default, and in English with `IPHONE_CONTR## WebDriverAgent won't start- **"Untrusted developer":** after the first install, trust your Apple ID under *Settings → General → VPN & Device Management* (needs internet on the phone).+- **Revoked signing certificate:** the launch fails with only `unexpected response` while the profile still looks valid. Each account directory has its own private key (`account/keys/<team>/key.pem`) and certificate; a free team holds two, and plume revokes the first one it can when a new one is needed, whoever it belongs to. Every app signed with the revoked certificate stops launching on every device. The daemon checks two things when the launch is refused: whether the device's WDA profile lists a certificate with this machine's public key (offline, `foreign_wda`), and whether this machine's certificate is still in the team (online, cached as `own_cert` by the daily session check and before an automatic re-sign). Either failing triggers an automatic re-sign of that device, at most once per device every `CERT_HEAL_EVERY` (6 h). Signing that creates or revokes a certificate is logged and notified (`cert`). `doctor` shows both checks.- **Expired signature:** free provisioning profiles last 7 days. The daemon re-signs when fewer than `RESIGN_MIN_DAYS` (default 2) remain. `status` shows the remaining time; `resign --force` re-signs now. Automatic re-signing only covers the controlled device, and is checked within a minute after it reconnects or you switch to it. A re-sign that takes too long counts as failed and you get a notification.- **Apple ID session expired:** you get a notification, and `resign` fails with a login error. Run `login` again.- **Developer Disk Image:** a failure shows on the first line of `status` as `WDA 启动失败,稍后重试:开发者镜像:…`; `doctor` has no separate check for it, and the details are in `logs/daemon.log`. Downloading needs access to GitHub; behind a firewall set `HTTP_PROXY`/`HTTPS_PROXY`, or point `ICTL_DDI_DIR` at an image extracted from Xcode. With `ICTL_DDI_DIR` the daemon neither downloads nor deletes anything, and the error names any missing file. The default cache (`ddi/` in the data directory) is deleted and downloaded again after 3 failed mounts in a row.## Login and signing-- **Two-factor code:** `login` and `setup` ask for it in the terminal. Run them with `-it` (`docker exec -it …`), otherwise there is no terminal to type into.+- **Two-factor code:** `login`, `setup` and the first run of `iphone-control` ask for it in the terminal, so run them in an interactive terminal (not from a script or a pipe).- **Anisette errors:** the default public anisette server may be slow or down. Retry later, or run your own and set `ICTL_ANISETTE_URL` (see [SECURITY.md](../SECURITY.md)).- **Account limits:** free accounts can only have a limited number of app IDs and devices. Use a dedicated Apple ID if your main one is already used with other sideloading tools.## MCP-- **The client can't connect** ("connection closed", "failed to reconnect"): restarting the container ends the MCP process; reconnect from the client (in Claude Code, run `/mcp`). Check the registered command with `iphone-control mcp-config`.+- **The client can't connect** ("connection closed", "failed to reconnect"): restarting the daemon (`iphone-control service restart`) ends the MCP process; reconnect from the client (in Claude Code, run `/mcp`). Check the registered command with `iphone-control mcp-config`.- **"守护进程正忙…已放弃执行":** an action waited more than 30 seconds for the device, so it was dropped instead of tapping a screen that has changed. Take a screenshot and try again.- **An action reports that the WDA connection dropped:** the request was already sent, so it may have happened. It is not redone over HID, to avoid tapping or typing twice. Take a screenshot before trying again.- **Taps do nothing:** a system alert may be covering the screen; the tool result says so (「屏幕上有系统弹窗…」). Dismiss it with `iphone_tap_element`. Taps right after launching an app are delayed until the launch animation is over.@@ -48,17 +48,20 @@ The HID fallback keeps a screen-mirroring session open while it is in use (the D## macOS-- **No Docker:** Docker Desktop has no USB passthrough; run the binary directly as your regular user ([macOS guide](https://derrors.github.io/iphone-control/en/deploy/macos)). Don't run it with `sudo`: as root it starts a second usbmuxd and uses Linux system paths.+- **Run it as your regular user** ([macOS guide](https://derrors.github.io/iphone-control/en/deploy/macos)), never with `sudo`: as root it uses Linux system paths.- **usbmuxd:** it is part of macOS and always running. If `doctor` can't reach it: `sudo launchctl kickstart -k system/com.apple.usbmuxd`.- **Finder** can stay open on the phone; macOS's `remoted` doesn't take the connection away. Xcode's *Devices and Simulators* window is untested.## Logs-- Container: `docker logs iphone-control`, and the event log at `/var/lib/iphone-control/logs/daemon.log` inside the container (`./data/logs/` on the host).-- Source install: `journalctl --user -u iphone-control` and `~/.local/share/iphone-control/logs/`.-- macOS: the terminal running `iphone-control daemon`, and `~/.local/share/iphone-control/logs/`. For system logs use `/usr/bin/log` (zsh has a built-in `log`).-- More detail: set `ICTL_LOG=info,ictl_wda::http=debug` to log every WebDriverAgent request with its duration. Remove it afterwards; it is verbose.+- Event log, every system: `~/.local/share/iphone-control/logs/daemon.log`.+- Linux service: `journalctl --user -u iphone-control` (Homebrew's unit: `-u homebrew.iphone-control`).+- macOS service: `~/Library/Logs/iphone-control/daemon.log` (installed by `install.sh` or `iphone-control service install`) or `$(brew --prefix)/var/log/iphone-control.log` (`brew services`).+- A daemon started by hand logs to its terminal.+- macOS system logs: use `/usr/bin/log` (zsh has a built-in `log`).+- `iphone-control service status` shows which service is set up and whether the daemon runs.+- More detail: set `ICTL_LOG=info,ictl_wda::http=debug` in `~/.config/iphone-control/env` and run `iphone-control service restart` to log every WebDriverAgent request with its duration. Remove it afterwards; it is verbose.## Reporting a bug-Please include the iPhone or iPad model, iOS version, how you run it (Docker, prebuilt binary or source; Linux or macOS), and the output of `iphone-control doctor`. Remove anything private (UDID, Apple ID, notification keys) first.+Please include the iPhone or iPad model, iOS version, how you installed it (install.sh, Homebrew, .deb or source; Linux or macOS), and the output of `iphone-control doctor`. Remove anything private (UDID, Apple ID, notification keys) first.diff --git a/install.sh b/install.shnew file mode 100755index 0000000..ba68cd7--- /dev/null+++ b/install.sh@@ -0,0 +1,229 @@+#!/bin/sh+# iphone-control installer for macOS (Apple Silicon) and Linux (x86_64, aarch64).+#+# curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh+# curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh -s -- --version v0.2.0+#+# Downloads the release archive for this machine, checks its sha256, installs the binary into ~/.local/bin and+# sets up the daemon as a per-user service (launchd on macOS, systemd --user on Linux) that starts at login and+# restarts after a crash. Running it again upgrades. Nothing runs as root; your data stays in+# ~/.local/share/iphone-control.+#+# Options (or the environment variable in brackets):+# --version vX.Y.Z install this release instead of the latest [IPHONE_CONTROL_VERSION]+# --prefix DIR install into DIR/bin (default ~/.local) [IPHONE_CONTROL_PREFIX]+# --no-service only install the binary; start the daemon yourself [IPHONE_CONTROL_NO_SERVICE=1]+# --uninstall stop and remove the service and the binary (keeps your data)+set -eu++REPO="Derrors/iphone-control"+LABEL="io.github.derrors.iphone-control"+VERSION="${IPHONE_CONTROL_VERSION:-}"+PREFIX="${IPHONE_CONTROL_PREFIX:-$HOME/.local}"+SERVICE=1+[ "${IPHONE_CONTROL_NO_SERVICE:-}" = 1 ] && SERVICE=0+UNINSTALL=0++# Messages in Chinese when IPHONE_CONTROL_LANG or the locale says so, English otherwise+case "${IPHONE_CONTROL_LANG:-${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}}" in+ zh*) ZH=1 ;;+ *) ZH=0 ;;+esac+say() { if [ "$ZH" = 1 ]; then printf '%s\n' "$1"; else printf '%s\n' "$2"; fi; }+die() { say "错误:$1" "Error: $2" >&2; exit 1; }++while [ $# -gt 0 ]; do+ case "$1" in+ --version) VERSION="${2:-}"; shift 2 ;;+ --prefix) PREFIX="${2:-}"; shift 2 ;;+ --no-service) SERVICE=0; shift ;;+ --uninstall) UNINSTALL=1; shift ;;+ -h|--help) sed -n '2,19p' "$0" 2>/dev/null || true; exit 0 ;;+ *) die "不认识的参数 $1" "unknown option $1" ;;+ esac+done++# As root, the daemon would use system paths and, on macOS, fight the system usbmuxd+[ "$(id -u)" -ne 0 ] || die "不要用 root 或 sudo 运行,以普通用户安装即可" "don't run this as root or with sudo; install as your regular user"++OS="$(uname -s)"+ARCH="$(uname -m)"+case "$OS" in+ Darwin)+ # a shell running under Rosetta reports x86_64 on Apple Silicon+ if [ "$ARCH" = x86_64 ] && [ "$(sysctl -n hw.optional.arm64 2>/dev/null || echo 0)" = 1 ]; then ARCH=arm64; fi+ [ "$ARCH" = arm64 ] || die "只有 Apple 芯片的 Mac 有预编译版本;Intel Mac 请从源码编译(见 macOS 指南)" \+ "prebuilt binaries are for Apple Silicon Macs only; on an Intel Mac build from source (see the macOS guide)"+ TARGET="macos-arm64"+ ;;+ Linux)+ case "$ARCH" in+ x86_64|amd64) TARGET="linux-x86_64" ;;+ aarch64|arm64) TARGET="linux-aarch64" ;;+ *) die "不支持的架构 $ARCH" "unsupported architecture $ARCH" ;;+ esac+ ;;+ *) die "只支持 macOS 和 Linux" "only macOS and Linux are supported" ;;+esac++BIN_DIR="$PREFIX/bin"+BIN="$BIN_DIR/iphone-control"+PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"+UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"+UNIT="$UNIT_DIR/iphone-control.service"+CONF_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/iphone-control"++has_systemd_user() { command -v systemctl >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1; }++stop_service() {+ if [ "$OS" = Darwin ]; then+ launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true+ elif has_systemd_user && [ -f "$UNIT" ]; then+ systemctl --user stop iphone-control 2>/dev/null || true+ fi+ # the daemon can take up to half a minute to stop (it ends the phone's HID session and WDA first); both service+ # managers end it by force after 30 s, so wait a little longer than that+ n=0+ while pgrep -f "$BIN daemon" >/dev/null 2>&1 && [ "$n" -lt 45 ]; do sleep 1; n=$((n + 1)); done+}++if [ "$UNINSTALL" = 1 ]; then+ stop_service+ if [ "$OS" = Darwin ]; then+ rm -f "$PLIST"+ elif [ -f "$UNIT" ]; then+ if has_systemd_user; then systemctl --user disable iphone-control 2>/dev/null || true; fi+ rm -f "$UNIT"+ if has_systemd_user; then systemctl --user daemon-reload || true; fi+ fi+ rm -f "$BIN"+ say "已卸载 iphone-control。数据还在 ~/.local/share/iphone-control(Apple ID 会话、签名、自动解锁密码),不需要的话自己删除;手机上的 WebDriverAgent 在手机上删除。" \+ "iphone-control is uninstalled. Your data is still in ~/.local/share/iphone-control (Apple ID session, signing, auto-unlock passcodes); delete it if you no longer need it, and remove WebDriverAgent on the phone."+ exit 0+fi++command -v curl >/dev/null 2>&1 || die "需要 curl" "curl is required"+command -v tar >/dev/null 2>&1 || die "需要 tar" "tar is required"++if [ -z "$VERSION" ]; then+ # the latest release's tag, from where /releases/latest redirects (no API rate limit)+ url="$(curl -fsSLo /dev/null -w '%{url_effective}' "https://github.com/$REPO/releases/latest")" ||+ die "查不到最新版本,检查网络,或用 --version 指定" "couldn't find the latest release; check the network or pass --version"+ VERSION="${url##*/}"+fi+case "$VERSION" in v*) ;; *) VERSION="v$VERSION" ;; esac++NAME="iphone-control-$VERSION-$TARGET"+BASE="https://github.com/$REPO/releases/download/$VERSION"+TMP="$(mktemp -d)"+trap 'rm -rf "$TMP"' EXIT INT TERM++say "下载 iphone-control ${VERSION}(${TARGET})…" "Downloading iphone-control $VERSION ($TARGET)…"+# a progress bar only in a terminal+if [ -t 2 ]; then progress=--progress-bar; else progress=-s; fi+curl -fSL "$progress" -o "$TMP/$NAME.tar.gz" "$BASE/$NAME.tar.gz" ||+ die "下载失败:$BASE/$NAME.tar.gz" "download failed: $BASE/$NAME.tar.gz"+curl -fsSL -o "$TMP/$NAME.tar.gz.sha256" "$BASE/$NAME.tar.gz.sha256" || die "下载校验和失败" "couldn't download the checksum"+if command -v sha256sum >/dev/null 2>&1; then+ (cd "$TMP" && sha256sum -c "$NAME.tar.gz.sha256" >/dev/null) || die "sha256 校验不通过" "sha256 check failed"+else+ (cd "$TMP" && shasum -a 256 -c "$NAME.tar.gz.sha256" >/dev/null) || die "sha256 校验不通过" "sha256 check failed"+fi+tar -xzf "$TMP/$NAME.tar.gz" -C "$TMP"++# replacing the binary under a running daemon: stop it first, start it again below+stop_service+mkdir -p "$BIN_DIR" "$CONF_DIR"+install -m 755 "$TMP/$NAME/iphone-control" "$BIN"+[ -f "$TMP/$NAME/env.example" ] && cp "$TMP/$NAME/env.example" "$CONF_DIR/env.example"+say "已安装 ${BIN}($("$BIN" --version))" "Installed $BIN ($("$BIN" --version))"++if [ "$OS" = Linux ] && ! command -v usbmuxd >/dev/null 2>&1 && [ ! -x /usr/sbin/usbmuxd ]; then+ say "还缺 usbmuxd(和 iPhone 通过 USB 通信要用):sudo apt install usbmuxd(其他发行版用对应的包管理器)" \+ "usbmuxd is missing (needed to talk to the iPhone over USB): sudo apt install usbmuxd (or your distribution's package manager)"+fi++started=0+if [ "$SERVICE" = 1 ]; then+ if pgrep -f "iphone-control daemon" >/dev/null 2>&1; then+ # a daemon started by hand: a second one would fight it for the phone+ say "已有一个手动启动的守护进程在运行,没有启动服务。先停掉它(pkill -f 'iphone-control daemon'),再重新运行这个脚本。" \+ "A daemon you started by hand is running, so the service wasn't started. Stop it (pkill -f 'iphone-control daemon') and run this script again."+ elif [ "$OS" = Darwin ]; then+ mkdir -p "$HOME/Library/LaunchAgents" "$HOME/Library/Logs/iphone-control"+ # settings from ~/.config/iphone-control/env, like the systemd service on Linux+ cat > "$PLIST" <<EOF+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key><string>$LABEL</string>+ <key>ProgramArguments</key>+ <array>+ <string>/bin/sh</string>+ <string>-c</string>+ <string>set -a; f="\$HOME/.config/iphone-control/env"; [ -f "\$f" ] && . "\$f"; set +a; exec "$BIN" daemon</string>+ </array>+ <key>RunAtLoad</key><true/>+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>+ <key>ThrottleInterval</key><integer>10</integer>+ <key>ExitTimeOut</key><integer>30</integer>+ <key>StandardOutPath</key><string>$HOME/Library/Logs/iphone-control/daemon.log</string>+ <key>StandardErrorPath</key><string>$HOME/Library/Logs/iphone-control/daemon.log</string>+</dict>+</plist>+EOF+ launchctl bootstrap "gui/$(id -u)" "$PLIST" && started=1+ elif has_systemd_user; then+ mkdir -p "$UNIT_DIR"+ cat > "$UNIT" <<EOF+# Installed by install.sh. Settings: ~/.config/iphone-control/env (see env.example next to it)+[Unit]+Description=iphone-control daemon (iPhone over USB, MCP)+After=network-online.target++[Service]+ExecStart=$BIN daemon+EnvironmentFile=-%h/.config/iphone-control/env+Environment=MALLOC_ARENA_MAX=2+Restart=on-failure+RestartSec=10+TimeoutStopSec=30++[Install]+WantedBy=default.target+EOF+ systemctl --user daemon-reload+ systemctl --user enable --now iphone-control && started=1+ if command -v loginctl >/dev/null 2>&1 && [ "$(loginctl show-user "$(id -un)" -p Linger --value 2>/dev/null)" != yes ]; then+ say "要不登录也随开机启动,运行:sudo loginctl enable-linger $(id -un)" \+ "To start it at boot without logging in, run: sudo loginctl enable-linger $(id -un)"+ fi+ else+ say "没有可用的 systemd 用户会话,没有安装服务。手动启动:$BIN daemon" \+ "No systemd user session, so no service was installed. Start it yourself: $BIN daemon"+ fi+fi++case ":$PATH:" in+ *":$BIN_DIR:"*) ;;+ *) say "$BIN_DIR 不在 PATH 里。把这行加到 shell 的配置文件(~/.zshrc 或 ~/.bashrc):export PATH=\"$BIN_DIR:\$PATH\"" \+ "$BIN_DIR isn't on your PATH. Add this line to your shell profile (~/.zshrc or ~/.bashrc): export PATH=\"$BIN_DIR:\$PATH\"" ;;+esac++echo+if [ "$started" = 1 ]; then+ say "守护进程已作为服务运行,登录后自动启动。" "The daemon runs as a service and starts when you log in."+elif [ "$SERVICE" = 0 ]; then+ say "没有安装服务。启动守护进程:$BIN daemon" "No service installed. Start the daemon: $BIN daemon"+fi+say "接下来:用数据线连上 iPhone,然后运行++ iphone-control++它会一步步带你完成设置(配对、开发者模式、Apple ID、安装 WDA、注册到 Claude Code / Codex),设置好以后再运行只显示状态。" \+"Next: connect the iPhone with a cable, then run++ iphone-control++It walks you through setup step by step (pairing, Developer Mode, Apple ID, WDA, registering with Claude Code / Codex); once set up, running it again just shows the status."diff --git a/.env.example b/packaging/env.examplesimilarity index 59%rename from .env.examplerename to packaging/env.exampleindex 628ab34..c319ac3 100644--- a/.env.example+++ b/packaging/env.example@@ -1,22 +1,20 @@-# 复制为 .env 后按需修改。所有项都可以留空,用默认值。.env 里有通知密钥,不要提交到 git。--# 容器名。改了的话,`iphone-control mcp-config --container <新名字>` 打印的注册命令和 README 里的 docker exec 都要跟着换-CONTAINER_NAME=iphone-control-# 镜像名(compose 构建出的本地镜像,或要拉取的发布镜像)-IMAGE=iphone-control:local-# 数据目录:配对记录、Apple ID 会话和开发私钥、签好的 WDA、开发者镜像缓存、日志、锁屏密码。务必备份,不要提交-DATA_DIR=./data+# iphone-control 的设置,放在 ~/.config/iphone-control/env(首次运行 iphone-control 的引导、+# iphone-control setup --reconfigure 会替你写好;也可以照这个文件手改)。所有项都可以留空,用默认值。+# 改完运行 iphone-control service restart 让守护进程重新读取。这个文件里有通知密钥,不要提交、不要分享。+#+# Settings for iphone-control, in ~/.config/iphone-control/env (the first-run guide of `iphone-control` and+# `iphone-control setup --reconfigure` write it for you; you can also edit it by hand). Every entry may stay empty.+# After a change run iphone-control service restart. The file holds notification secrets: don't commit or share it.# 界面语言:工具说明和结果、命令行输出、日志、通知。zh(默认)或 en。# Language of tool texts, CLI output, logs and notifications: zh (default) or en.# MCP 和命令行各自按自己的设置发请求,守护进程按请求的语言回答;这里的设置管守护进程自己写的日志和通知,-# 容器部署时也管 docker exec 起的 MCP 和命令行。IPHONE_CONTROL_LANG=# 开发者工具:设为 1 时 MCP 服务多出日志、崩溃报告、安装和卸载 App、网页检查(Web Inspector)六个工具(默认关闭,免得 agent 多读工具说明)# Developer tools: 1 adds six MCP tools for logs, crash reports, installing and removing apps, and web pages (Web Inspector) (off by default).-# 从源码运行和在 macOS 上这个文件只有守护进程读,语言和开发者工具要写进 MCP 的配置,见文档的「配置」一页。-# For a source install and on macOS only the daemon reads this file; set the language and developer tools in the MCP configuration too (see the Configuration page).+# 守护进程和每个 iphone-control 命令(包括 MCP 服务)启动时都读这个文件;已经在环境里设了的变量优先,见文档的「配置」一页。+# The daemon and every iphone-control command (the MCP server too) read this file at start-up; a variable already set in the environment wins.IPHONE_CONTROL_DEV_TOOLS=# 固定控制哪台设备,设了就不能切换。留空为自动选:正在控制的那台一直用到它断开;@@ -27,7 +25,7 @@ IPHONE_UDID=SCREEN_W=SCREEN_H=-# 代理:下载开发者镜像、Apple ID 登录、构建镜像、发 Telegram 都会用;留空表示直连+# 代理:下载开发者镜像、Apple ID 登录、下载 WDA、发 Telegram 都会用;留空表示直连HTTP_PROXY=HTTPS_PROXY=NO_PROXY=localhost,127.0.0.1,::1@@ -51,14 +49,9 @@ ICTL_ANISETTE_URL=ICTL_DDI_URL=# 自己从 Xcode 提取的开发者镜像目录。设了就不下载,也不会删里面的文件;缺文件时报错说明缺哪个ICTL_DDI_DIR=-# 守护进程是否自己拉起 usbmuxd。默认:以 root 运行(容器)时拉起,以普通用户运行时用系统的 usbmuxd 服务。-# 以 root 从源码运行、宿主机又已有 usbmuxd 服务时设为 0-# ICTL_MANAGE_USBMUXD=0-# 守护进程自己拉起 usbmuxd 时用的可执行文件,默认 usbmuxd-# ICTL_USBMUXD_BIN=/usr/sbin/usbmuxd-# 未签名 WDA 的路径。默认:容器里是 /usr/share/iphone-control/WDA-unsigned.ipa;从源码运行是数据目录的 wda/WDA-unsigned.ipa,首次签名前下载+# 未签名 WDA 的路径。默认是数据目录的 wda/WDA-unsigned.ipa,首次签名前下载# ICTL_WDA_UNSIGNED=/path/to/WDA-unsigned.ipa-# 数据目录和控制接口(同 --data-dir、--socket)。容器里不要改。要改时不能留空,守护进程、命令行和 MCP 要用同样的值。+# 数据目录和控制接口(同 --data-dir、--socket)。要改时不能留空,守护进程、命令行和 MCP 要用同样的值。# 默认:root 是 /var/lib/iphone-control 和 /run/iphone-control/ctl.sock;# 普通用户是 $XDG_DATA_HOME/iphone-control(没设时 ~/.local/share/iphone-control)和 $XDG_RUNTIME_DIR/iphone-control/ctl.sock(没有 XDG_RUNTIME_DIR 时放在数据目录里)# ICTL_DATA_DIR=/path/to/datadiff --git a/packaging/homebrew/formula.sh b/packaging/homebrew/formula.shnew file mode 100755index 0000000..1006f99--- /dev/null+++ b/packaging/homebrew/formula.sh@@ -0,0 +1,67 @@+#!/bin/sh+# Prints the Homebrew formula for one release (the release workflow pushes it to Derrors/homebrew-tap):+# packaging/homebrew/formula.sh v0.2.0 <sha256 macos-arm64> <sha256 linux-x86_64> <sha256 linux-aarch64>+# The formula installs the prebuilt binary from the GitHub release; `brew services start iphone-control` runs the+# daemon (launchd on macOS, systemd on Linux) with the settings in ~/.config/iphone-control/env.+set -eu+[ $# -eq 4 ] || { echo "usage: $0 vX.Y.Z SHA_MACOS_ARM64 SHA_LINUX_X86_64 SHA_LINUX_AARCH64" >&2; exit 2; }+tag="$1"+base="https://github.com/Derrors/iphone-control/releases/download/$tag/iphone-control-$tag"+cat <<EOF+# Generated by packaging/homebrew/formula.sh in Derrors/iphone-control for $tag; don't edit by hand.+class IphoneControl < Formula+ desc "Let AI agents operate a real iPhone or iPad over USB (MCP server and daemon)"+ homepage "https://github.com/Derrors/iphone-control"+ license "MIT"++ on_macos do+ depends_on arch: :arm64+ on_arm do+ url "$base-macos-arm64.tar.gz"+ sha256 "$2"+ end+ end++ on_linux do+ on_intel do+ url "$base-linux-x86_64.tar.gz"+ sha256 "$3"+ end+ on_arm do+ url "$base-linux-aarch64.tar.gz"+ sha256 "$4"+ end+ end++ def install+ bin.install "iphone-control"+ pkgshare.install "env.example"+ end++ # Settings come from ~/.config/iphone-control/env, as for the systemd service and install.sh+ service do+ run ["/bin/sh", "-c",+ "set -a; f=\"\$HOME/.config/iphone-control/env\"; [ -f \"\$f\" ] && . \"\$f\"; set +a; " \\+ "exec \"#{opt_bin}/iphone-control\" daemon"]+ keep_alive successful_exit: false+ log_path var/"log/iphone-control.log"+ error_log_path var/"log/iphone-control.log"+ end++ def caveats+ <<~EOS+ Run the daemon in the background (it also starts when you log in):+ brew services start iphone-control+ Then connect the iPhone with a cable and run+ iphone-control+ It walks you through setup (pairing, Developer Mode, Apple ID, WebDriverAgent, MCP registration).+ Settings: ~/.config/iphone-control/env (example: #{opt_pkgshare}/env.example).+ On Linux, the daemon also needs the system's usbmuxd (sudo apt install usbmuxd).+ EOS+ end++ test do+ assert_match version.to_s, shell_output("#{bin}/iphone-control --version")+ end+end+EOFdiff --git a/docker/about.hbs b/packaging/licenses/about.hbssimilarity index 100%rename from docker/about.hbsrename to packaging/licenses/about.hbsdiff --git a/packaging/licenses/about.toml b/packaging/licenses/about.tomlnew file mode 100644index 0000000..96fa110--- /dev/null+++ b/packaging/licenses/about.toml@@ -0,0 +1,9 @@+# cargo-about:生成随发布包附带的第三方 Rust 组件许可证清单 THIRD_PARTY_LICENSES.html(压缩包里,deb 是+# /usr/share/doc/iphone-control/THIRD_PARTY_LICENSES.html)。依赖里出现不在这个列表里的许可证时 CI 和发布失败,需要人看一眼再决定(例如 AGPL、没有许可证声明的 crate)+accepted = [+ "MIT", "Apache-2.0", "Apache-2.0 WITH LLVM-exception", "BSD-2-Clause", "BSD-3-Clause", "ISC", "MPL-2.0",+ "Unicode-3.0", "Zlib", "CC0-1.0", "0BSD", "BSL-1.0", "Unlicense", "CDLA-Permissive-2.0", "BlueOak-1.0.0",+]+targets = ["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", "aarch64-apple-darwin"]+ignore-build-dependencies = true+ignore-dev-dependencies = truediff --git a/tests/device/run.py b/tests/device/run.pyindex 30274b3..3ed2b8e 100644--- a/tests/device/run.py+++ b/tests/device/run.py@@ -5,7 +5,7 @@ result with its wall time, and save screenshots.python tests/device/run.py # default steps (harmless: Home, Clock tabs, Spotlight search)python tests/device/run.py '[["iphone_status", {}], ["sleep", 1], ["iphone_screenshot", {}]]'-The MCP server command comes from MCP_CMD (default: `docker exec -i iphone-control iphone-control mcp`;+The MCP server command comes from MCP_CMD (default: `iphone-control mcp`;for a source install use e.g. `iphone-control mcp`). Screenshots go to SHOTS_DIR (default: ./shots).A step `["sleep", seconds]` waits without calling a tool. Exit code is 1 if any tool returned an error."""@@ -42,7 +42,7 @@ DEFAULT_STEPS = [async def main() -> int:steps = json.loads(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_STEPS- cmd = shlex.split(os.environ.get("MCP_CMD", "docker exec -i iphone-control iphone-control mcp"))+ cmd = shlex.split(os.environ.get("MCP_CMD", "iphone-control mcp"))shots = os.environ.get("SHOTS_DIR", "shots")os.makedirs(shots, exist_ok=True)failed = 0diff --git a/website/.vitepress/config.mts b/website/.vitepress/config.mtsindex 48d9dbb..08a20d6 100644--- a/website/.vitepress/config.mts+++ b/website/.vitepress/config.mts@@ -46,8 +46,7 @@ export default defineConfig({{text: '安装部署',items: [- { text: 'Docker', link: '/deploy/docker' },- { text: '从源码 / 二进制', link: '/deploy/source' },+ { text: '从源码编译', link: '/deploy/source' },{ text: 'macOS', link: '/deploy/macos' },{ text: '数据与备份', link: '/deploy/backup' },],@@ -111,8 +110,7 @@ export default defineConfig({{text: 'Deployment',items: [- { text: 'Docker', link: '/en/deploy/docker' },- { text: 'Source / Binary', link: '/en/deploy/source' },+ { text: 'Build from Source', link: '/en/deploy/source' },{ text: 'macOS', link: '/en/deploy/macos' },{ text: 'Data and Backups', link: '/en/deploy/backup' },],diff --git a/website/deploy/backup.md b/website/deploy/backup.mdindex 6580838..ad94346 100644--- a/website/deploy/backup.md+++ b/website/deploy/backup.md@@ -5,14 +5,13 @@| 路径 | 内容 | 丢了会怎样 ||---|---|---|| `account/` | Apple ID 会话、开发签名私钥和证书 | 要重新登录;会生成新证书 |-| `lockdown/` | 配对记录(Docker 部署) | 要在手机上重新点「信任」 || `wda/` | 签好的 WebDriverAgent | 自动重签 || `ddi/` | 开发者镜像缓存 | 自动重新下载 || `secrets/passcodes/` | 各设备的锁屏密码(仅开启自动解锁时) | 要重新 `passcode set` || `state.json` | 签好的 WDA 包信息(Team ID、Bundle ID、描述文件到期时间)、选定的设备、最近一台设备的屏幕尺寸、上次重签结果 | 守护进程按「WDA 还没签名」启动:要重新 `sign` 或 `setup`,选过设备的要重新 `select` || `logs/` | 日志、自动解锁的停用标记 `UNLOCK-DISABLED` | 日志没了不要紧。但停用标记没了就撤销了这层保护:之前输错过的话,可能再用同一个错误密码输一遍 |-位置:Docker 部署是仓库目录下的 `./data`(root 所有,权限 0700);从源码运行是 `~/.local/share/iphone-control`,配对记录在系统的 `/var/lib/lockdown`;macOS 上数据目录也是 `~/.local/share/iphone-control`,配对记录由系统保存在 `/var/db/lockdown`(和 Finder 共用)。+位置:`~/.local/share/iphone-control`(权限 0700),Linux 和 macOS 一样,不管是一行命令、Homebrew、deb 还是从源码装的。配对记录不在这里,由系统的 usbmuxd 保存:Linux 上在 `/var/lib/lockdown`,macOS 上在 `/var/db/lockdown`(和 Finder 共用)。设置在 `~/.config/iphone-control/env`,里面有通知密钥,同样别外传。::: danger 这些是秘密数据目录能用来登录你的 Apple ID 开发者账号、免确认地连接手机,开启自动解锁时还有明文锁屏密码。不要提交到 git,不要发给别人,备份也要加密保存。@@ -21,22 +20,32 @@## 备份```bash-docker compose stop-sudo tar czf iphone-control-data.tar.gz data # 目录是 root 所有,需要 sudo-docker compose start+iphone-control service stop+tar czf iphone-control-data.tar.gz -C ~/.local/share iphone-control+cp ~/.config/iphone-control/env iphone-control-env # 设置+sudo tar czf lockdown.tar.gz /var/lib/lockdown # 配对记录,只在 Linux 上+iphone-control service start```-从源码运行:+守护进程是前台运行的,就先在它的终端按 Ctrl-C 停掉。macOS 上配对记录归系统管理,不用备份,换了 Mac 在手机上重新点一次「信任」即可。++## 迁移到新主机++先在新主机上安装(见[快速开始](../guide/getting-started#install)),不要急着运行 `iphone-control`。把数据目录、设置文件(Linux 上还有 `/var/lib/lockdown`)原样恢复到同一位置,再运行 `iphone-control`,不需要重新登录;恢复了配对记录的也不用重新配对。++## 从 Docker 部署迁过来++从下一个版本起不再提供 Docker 镜像。原来的数据在 compose 文件旁边的 `./data`(或 `DATA_DIR` 指的目录),属于 root。装好新版本后、第一次运行 `iphone-control` 之前:```bash-systemctl --user stop iphone-control-tar czf iphone-control-data.tar.gz -C ~/.local/share iphone-control-sudo tar czf lockdown.tar.gz /var/lib/lockdown # 配对记录-systemctl --user start iphone-control+docker compose down # 在原来的 compose.yaml 所在目录+mkdir -p ~/.local/share+sudo cp -a ./data ~/.local/share/iphone-control+sudo chown -R "$(id -un)": ~/.local/share/iphone-control```-macOS:先在守护进程的终端按 Ctrl-C 停掉,再执行上面的第二条 `tar`。配对记录归系统管理,不用备份,换了 Mac 在手机上重新点一次「信任」即可。--## 迁移到新主机+`~/.local/share/iphone-control` 已经存在时(比如已经运行过 `iphone-control`),先 `iphone-control service stop`,把它改名留着,再复制。-把数据目录(从源码运行时还有 `/var/lib/lockdown`)原样恢复到新主机的同一位置,再启动即可,不需要重新配对、登录。+- 原来 `.env` 里的设置搬到 `~/.config/iphone-control/env`(格式一样,`KEY=value`),权限设成 0600,见[配置](../guide/configuration#settings-file)。也可以直接运行 `iphone-control`,让引导重新问一遍。+- 容器里的配对记录在 `./data/lockdown/`,系统的 usbmuxd 不读这里。第一次运行时手机会再问一次「要信任此电脑吗?」,引导会带你点「信任」。+- `ICTL_MANAGE_USBMUXD`、`ICTL_USBMUXD_BIN` 已经去掉。Linux 上装系统的 usbmuxd(`sudo apt install usbmuxd`;deb 包会自动装),以前为 Docker 做过 `sudo systemctl mask usbmuxd` 的,先 `sudo systemctl unmask usbmuxd`。diff --git a/website/deploy/docker.md b/website/deploy/docker.mddeleted file mode 100644index 32f1a00..0000000--- a/website/deploy/docker.md+++ /dev/null@@ -1,106 +0,0 @@-# Docker 部署--推荐的部署方式。镜像里是一个 Rust 二进制加 Debian 的 usbmuxd,容器不用 `privileged`。--## 安装--三种方式任选其一,跑起来的容器完全一样。--### 只写一个 compose 文件--不用克隆仓库,最省事。新建一个目录(例如 `~/iphone-control`),在里面写 `compose.yaml`:--```yaml-services:- iphone:- image: ghcr.io/derrors/iphone-control:latest # 或固定版本,例如 :0.1.5- container_name: iphone-control- # 只开放 USB 字符设备,不需要 privileged- device_cgroup_rules:- - "c 189:* rmw"- init: true- stop_grace_period: 30s- network_mode: host- restart: unless-stopped- environment:- # 以下都可选,按需取消注释,完整列表见「配置」- # HTTP_PROXY: http://127.0.0.1:7890- # HTTPS_PROXY: http://127.0.0.1:7890- NO_PROXY: localhost,127.0.0.1,::1- # BARK_SERVER: https://api.day.app- # BARK_KEY: 你的key- # TG_BOT_TOKEN: "123456:ABC..."- # TG_CHAT_ID: "你的chat id"- volumes:- - /dev/bus/usb:/dev/bus/usb- - ./data:/var/lib/iphone-control-```--然后在这个目录里:--```bash-docker compose up -d-```--`./data` 是相对 `compose.yaml` 所在目录的,里面有配对记录和 Apple ID 会话,**要备份**。环境变量也可以不写在 `environment:` 里,改成放进同目录的 `.env`、再加一段 `env_file: .env`;`.env` 里有通知密钥时,别提交到 git。各变量的含义见[配置](../guide/configuration)。--### 自己构建--```bash-git clone https://github.com/Derrors/iphone-control && cd iphone-control-cp .env.example .env-docker compose up -d --build-```--### 用预构建镜像--镜像在 `ghcr.io/derrors/iphone-control`(amd64、arm64)。在 `.env` 里设:--```ini-IMAGE=ghcr.io/derrors/iphone-control:latest # 或固定版本,例如 :0.1.5-```--然后:--```bash-docker compose pull && docker compose up -d --no-build-```--装好后运行一次[安装向导](../guide/getting-started)。--## compose 做了什么--- 只开放 USB 字符设备(`device_cgroup_rules: "c 189:* rmw"`),`/dev/bus/usb` 绑定挂载,拔插后新的设备节点在容器里也看得到。-- `network_mode: host`:只为了能用宿主机上的代理;本身不监听任何端口。-- `./data` 挂到容器的 `/var/lib/iphone-control`,删掉重建容器也不丢配对和登录。-- `init: true`、`stop_grace_period: 30s`:停止时先关掉手机上的会话,避免留下「配对的电脑」图标。--## 升级--升级前先看[更新日志](https://github.com/Derrors/iphone-control/blob/main/CHANGELOG.zh-CN.md)里的升级注意事项。--```bash-docker compose pull && docker compose up -d # 只写 compose 文件-# 或-git pull-docker compose up -d --build # 自己构建-# 或-docker compose pull && docker compose up -d --no-build # 预构建镜像-```--镜像标签写的是固定版本时,先把 `compose.yaml` 里的版本号改成新版本再 `pull`。--数据在 `./data`,升级不受影响。容器重启后,AI 客户端里的 MCP 连接会断开,重新连接即可(Claude Code 里运行 `/mcp`)。--::: tip 重启后先等就绪-重启后约 10 秒 WDA 就绪。短时间内连续重启多次,手机可能再次弹出「为 XCTest 输入 iPhone 密码」,输入锁屏密码即可。-:::--## 常用命令--```bash-docker exec iphone-control iphone-control status # 状态-docker exec iphone-control iphone-control doctor # 诊断-docker logs iphone-control # 日志-docker compose down # 停止(数据保留)-```diff --git a/website/deploy/macos.md b/website/deploy/macos.mdindex 03d0d9c..409589b 100644--- a/website/deploy/macos.md+++ b/website/deploy/macos.md@@ -1,6 +1,6 @@# macOS-iphone-control 也能直接跑在 Mac 上:用 macOS 自带的 usbmuxd,不需要 Xcode,也不需要付费开发者账号。和 Linux 上从源码运行基本一样,区别见文末的[已知差异](#已知差异)。+iphone-control 也能直接跑在 Mac 上:用 macOS 自带的 usbmuxd,不需要 Xcode,也不需要付费开发者账号。和 Linux 上基本一样,区别见文末的[已知差异](#已知差异)。::: info 验证情况已在 MacBook Pro(Apple M3 Pro)/ macOS 26.6.2 + iPhone 15 Pro Max / iOS 27.0.1 上验证:安装向导、当时的全部 MCP 工具、开着 Finder 连续操作、同一条隧道连续 30 分钟、拔插和手机重启后自动恢复。这次验证早于 0.1.3,多设备工具(`iphone_list_devices`、`iphone_select_device`)没有在 macOS 上验证过。Intel Mac 还没测过。验证步骤和结果见 [macOS 真机验证](https://github.com/Derrors/iphone-control/blob/main/docs/dev/macos-verification.md)。@@ -8,43 +8,30 @@ iphone-control 也能直接跑在 Mac 上:用 macOS 自带的 usbmuxd,不需## 需要-- Apple Silicon 的 Mac-- 用预编译二进制什么都不用装;从源码编译要 Xcode 命令行工具和 Rust 1.88 以上。都**不需要**完整的 Xcode+- Apple Silicon 的 Mac:一行命令和 Homebrew 装的是编好的程序,什么都不用另外装。Intel Mac 没有预编译包,要从源码编译(Xcode 命令行工具和 Rust 1.88 以上)。都**不需要**完整的 Xcode- 一部 iOS 17 以上的 iPhone 或 iPad,用能**传数据**的线连接- 一个免费 Apple ID(建议专门注册一个)-::: warning 不能用 Docker-Docker Desktop 在 Mac 上把容器跑在 Linux 虚拟机里,不支持 USB 直通,容器看不到手机。在 Mac 上只能直接运行程序。-:::-## 安装-### 预编译二进制--从 0.1.2 起,[Releases](https://github.com/Derrors/iphone-control/releases) 里有 macOS(Apple Silicon,macOS 11 以上)的压缩包 `iphone-control-<版本>-macos-arm64.tar.gz`。在终端里下载安装(把 `V` 换成最新版本号):+### 一行命令(推荐)```bash-V=v0.1.5-curl -fsSLO https://github.com/Derrors/iphone-control/releases/download/$V/iphone-control-$V-macos-arm64.tar.gz-curl -fsSLO https://github.com/Derrors/iphone-control/releases/download/$V/iphone-control-$V-macos-arm64.tar.gz.sha256-shasum -a 256 -c iphone-control-$V-macos-arm64.tar.gz.sha256 # 应显示 OK-tar xzf iphone-control-$V-macos-arm64.tar.gz-mkdir -p ~/.local/bin && install -m 755 iphone-control-$V-macos-arm64/iphone-control ~/.local/bin/-echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zprofile && source ~/.zprofile # 只需做一次-iphone-control --version+curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh```-::: tip 被系统拦下「无法验证开发者」-二进制没有经过苹果公证(那要付费开发者账号)。像上面这样用 `curl` 下载的不会被拦;用浏览器下载的会带上隔离标记,第一次运行时被 Gatekeeper 拦下。去掉标记即可:+它会下载最新版本、校验 sha256,装到 `~/.local/bin/iphone-control`,再装一个 launchd 用户服务(`~/Library/LaunchAgents/io.github.derrors.iphone-control.plist`):登录后自动启动守护进程,崩溃后自动重启,读取 `~/.config/iphone-control/env`,日志在 `~/Library/Logs/iphone-control/daemon.log`。可选参数写在 `sh -s --` 后面:`--version v0.2.0`(指定版本)、`--prefix 目录`(装到 `目录/bin`)、`--no-service`(只装程序,不装服务)。++### Homebrew```bash-xattr -d com.apple.quarantine ~/.local/bin/iphone-control+brew install derrors/tap/iphone-control+brew services start iphone-control # 守护进程常驻,登录后自动启动```-也可以在「系统设置 → 隐私与安全性」里点「仍要打开」。-:::+服务同样读取 `~/.config/iphone-control/env`,日志在 `$(brew --prefix)/var/log/iphone-control.log`。设置模板在 `$(brew --prefix)/opt/iphone-control/share/iphone-control/env.example`。-### 从源码编译+### 从源码编译(Intel Mac)需要 Xcode 命令行工具和 Rust 1.88 以上,M3 Pro 上约 2 分半:@@ -56,53 +43,47 @@ cargo install --path apps/iphone-control --locked # 装到 ~/.cargoiphone-control --version```+后台服务由下面的设置引导装好。+## 运行-**全程用普通用户运行,不要加 sudo。** macOS 自带的 usbmuxd 一直在运行,守护进程直接用它;以 root 运行时守护进程会自己再启动一个 usbmuxd 和系统的抢设备,数据目录和控制接口也会换成按 Linux 设的系统路径(`/var/lib`、`/run`)。+**全程用普通用户运行,不要加 sudo。** macOS 自带的 usbmuxd 一直在运行,守护进程直接用它。以 root 运行时数据目录和控制接口会换成按 Linux 设的系统路径(`/var/lib`、`/run`),一行命令的脚本也会拒绝以 root 运行。-在一个终端里运行守护进程,日志直接打印在这里:+用数据线接上手机,然后:```bash-iphone-control daemon+iphone-control```-另开一个终端运行安装向导:--```bash-iphone-control setup-```+第一次运行会一步步带你完成设置:语言、代理、后台服务、配对、开发者模式、Apple ID、签名安装 WDA、自动解锁和通知(可选)、注册到 Claude Code 和 Codex。手机上要做的事见[快速开始](../guide/getting-started#first-run)。如果这部手机已经在 Finder 里信任过这台 Mac,配对这一步会直接显示「已配对」。设置好以后再运行 `iphone-control` 只显示状态。-向导的六步和 Linux 上一样,手机上要做的事见[快速开始](../guide/getting-started#_2-运行安装向导)。如果这部手机已经在 Finder 里信任过这台 Mac,配对这一步会直接显示「已配对」。+### 手动做-向导显示「WDA 就绪」后,接入 AI 客户端:+引导做的事都能单独做:```bash-iphone-control mcp-config # 打印注册命令,复制运行即可+iphone-control daemon # 在一个终端里前台运行守护进程(不装后台服务时)+iphone-control setup # 另开一个终端,重走引导,做过的步骤跳过+iphone-control mcp-config # 打印注册 MCP 的命令,复制运行即可```-它打印的命令形如 `claude mcp add iphone -s user -- /Users/you/.cargo/bin/iphone-control --socket /Users/you/.local/share/iphone-control/ctl.sock mcp`。其他客户端见[接入 AI 客户端](../guide/mcp-clients)。+`mcp-config` 打印的命令形如 `claude mcp add iphone -s user -- /Users/you/.local/bin/iphone-control --socket /Users/you/.local/share/iphone-control/ctl.sock mcp`。Homebrew 装的,程序路径是 `/opt/homebrew/opt/iphone-control/bin/iphone-control`,升级后不变。其他客户端见[接入 AI 客户端](../guide/mcp-clients)。### 配置-配置写在 `~/.config/iphone-control/env`(格式同仓库里的 `.env.example`),启动守护进程前先加载:--```bash-mkdir -p ~/.config/iphone-control-cp .env.example ~/.config/iphone-control/env # 按需填代理、通知(预编译包里叫 env.example)-set -a; . ~/.config/iphone-control/env; set +a-iphone-control daemon-```--改了配置要重启守护进程(Ctrl-C 后重新运行)。变量说明见[配置](../guide/configuration)。+设置在 `~/.config/iphone-control/env`,引导和 `iphone-control setup --reconfigure` 会写好它。手改之后运行 `iphone-control service restart`。变量说明见[配置](../guide/configuration#settings-file)。### 保持运行-还没有 launchd 配置,守护进程要留在一个终端(或 tmux)里。Mac 睡眠时它也会暂停,长时间无人值守时用 `caffeinate` 防止睡眠:+一行命令、Homebrew 或引导装的后台服务,登录后自动启动守护进程,不用再管:```bash-caffeinate -i iphone-control daemon+iphone-control service status # 服务和守护进程是否在运行+iphone-control service restart # 重启,比如改了设置之后```+Mac 睡眠时守护进程会暂停。长时间无人值守时,在一个终端里运行 `caffeinate -i` 并让它一直开着,防止睡眠。+## 让 USB 连接稳定- **把手机的充电上限改成 100%**:设置 → 电池 → 充电。开着「80% 上限」时,手机在 80% 附近反复开始、停止充电,每次 USB-C 都会重新协商供电,USB 断开 3~5 秒,大约每分钟一次。守护进程能自己重连,但正在执行的操作会失败。@@ -111,8 +92,6 @@ caffeinate -i iphone-control daemon## 日常命令-和 Linux 一样,直接运行,不用加 `docker exec`:-```bashiphone-control status # 状态、描述文件还剩多久、最近日志iphone-control doctor # 逐层诊断@@ -130,21 +109,21 @@ sudo launchctl kickstart -k system/com.apple.usbmuxd升级前先看[更新日志](https://github.com/Derrors/iphone-control/blob/main/CHANGELOG.zh-CN.md)里的升级注意事项。-预编译二进制:按「安装」一节下载新版本,覆盖 `~/.local/bin/iphone-control`。从源码编译:+一行命令安装的:重新运行同一条命令,它会先停服务、换程序、再启动。Homebrew:`brew upgrade iphone-control && brew services restart iphone-control`。从源码编译:```bashcd iphone-control && git pullcargo install --path apps/iphone-control --locked+iphone-control service restart```-然后重启守护进程。-## 卸载-先在守护进程的终端按 Ctrl-C 停掉,然后:+一行命令安装的:`curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh -s -- --uninstall`。Homebrew:`brew services stop iphone-control && brew uninstall iphone-control`。从源码编译的:`iphone-control service uninstall && cargo uninstall iphone-control`。++都会保留数据目录和设置。要彻底删除:```bash-rm -f ~/.local/bin/iphone-control # 预编译二进制;从源码编译的用 cargo uninstall iphone-controlrm -rf ~/.local/share/iphone-control ~/.config/iphone-control # 会删掉 Apple ID 会话和签好的 WDA```@@ -152,14 +131,13 @@ rm -rf ~/.local/share/iphone-control ~/.config/iphone-control # 会删掉 Appl## 已知差异-| | Linux(从源码运行) | macOS |+| | Linux | macOS ||---|---|---|-| 安装 | 预编译二进制或从源码编译 | 同左(只有 Apple Silicon 的包) |-| 常驻 | systemd 用户服务 | 还没有 launchd 配置,在终端里前台运行 |+| 安装 | 一行命令、Homebrew、deb 或从源码编译 | 一行命令、Homebrew 或从源码编译(只有 Apple Silicon 的包) |+| 常驻 | systemd 用户服务 | launchd 用户服务 || usbmuxd | 系统包,插上手机时由 udev 拉起 | macOS 自带,一直在运行 || 数据目录 | `~/.local/share/iphone-control` | 同左(不是 Mac 习惯的 `~/Library/Application Support`) || 控制接口 | `$XDG_RUNTIME_DIR/iphone-control/ctl.sock` | `~/.local/share/iphone-control/ctl.sock` || 配对记录 | `/var/lib/lockdown` | `/var/db/lockdown`(和 Finder 共用) |-| Docker | 支持 | 不支持 |还没在 Mac 上验证过的:Xcode 的「设备与模拟器」窗口开着时会不会抢连接、手机第一次在这台 Mac 上配对的流程、iPad、接多台设备、Intel Mac。遇到问题欢迎[反馈](https://github.com/Derrors/iphone-control/issues)。diff --git a/website/deploy/source.md b/website/deploy/source.mdindex 4d9cf1c..b89ee5f 100644--- a/website/deploy/source.md+++ b/website/deploy/source.md@@ -1,67 +1,46 @@-# 从源码 / 二进制运行+# 从源码编译-在 Linux 上不用 Docker,以普通用户直接运行。需要系统的 usbmuxd(它由 udev 在插上手机时拉起)。在 Mac 上见 [macOS](./macos)。+一般用不着:一行命令、Homebrew 和 deb 包装的都是 Release 里编好的程序,见[快速开始](../guide/getting-started#install)。没有预编译包的机器(Intel Mac)和参与开发时才从源码编译。在 Mac 上见 [macOS](./macos)。-## 安装+## 准备-### 预编译二进制+- Rust 1.88 以上([rustup](https://rustup.rs))和 C 编译器+- Linux 上要系统的 usbmuxd(它由 udev 在插上手机时拉起)。守护进程不会自己启动 usbmuxd-[Releases](https://github.com/Derrors/iphone-control/releases) 里有 Linux x86_64 和 aarch64 的压缩包(需要 glibc 2.34 以上:Debian 12、Ubuntu 22.04 及更新的发行版):+## 编译安装```bash-sudo apt install usbmuxd-tar xzf iphone-control-v*-x86_64*.tar.gz # ARM 主机把 x86_64 换成 aarch64(看 uname -m)-install -Dm755 iphone-control-*/iphone-control ~/.cargo/bin/iphone-control-```--放在 `~/.cargo/bin` 是为了和下面的 systemd 服务文件一致;放别处的话同时改服务文件里的 `ExecStart`。--### 从源码编译--需要 Rust 1.88 以上([rustup](https://rustup.rs))和 C 编译器:--```bash-sudo apt install build-essential git usbmuxd+sudo apt install build-essential git usbmuxd # 其他发行版用对应的包管理器git clone https://github.com/Derrors/iphone-control && cd iphone-controlcargo install --path apps/iphone-control --locked # 装到 ~/.cargo/bin/iphone-control```## 运行+以普通用户运行,不要加 sudo。用数据线接上手机,然后:+```bash-iphone-control daemon # 前台运行-iphone-control setup # 另开一个终端运行安装向导-iphone-control mcp-config # 打印注册 MCP 的命令+iphone-control```-只有下面的 systemd 服务会读 `~/.config/iphone-control/env`。前台运行时先加载它:`set -a; . ~/.config/iphone-control/env; set +a`。+第一次运行是设置引导,和安装包装的一样,见[快速开始](../guide/getting-started#first-run)。其中「后台服务」一步会装好 systemd 用户服务(`~/.config/systemd/user/iphone-control.service`,读取 `~/.config/iphone-control/env`),之后登录就自动启动守护进程。以后也可以单独装:-### 常驻:systemd 用户服务+```bash+iphone-control service install+sudo loginctl enable-linger "$USER" # 不登录也随开机启动+```-服务文件在仓库的 `deploy/iphone-control.service`(二进制压缩包里也有):+开发时也可以不装服务,在一个终端里前台运行守护进程,日志直接打印在这里:```bash-mkdir -p ~/.config/systemd/user ~/.config/iphone-control-cp deploy/iphone-control.service ~/.config/systemd/user/-cp .env.example ~/.config/iphone-control/env # 按需改代理、通知(二进制压缩包里叫 env.example)-systemctl --user daemon-reload && systemctl --user enable --now iphone-control-loginctl enable-linger "$USER" # 不登录也随开机启动+iphone-control daemon```-## 和 Docker 部署的区别--| | Docker | 从源码(普通用户) |-|---|---|---|-| 数据目录 | `./data` | `~/.local/share/iphone-control` |-| 控制接口 | 容器内 `/run/iphone-control/ctl.sock` | `$XDG_RUNTIME_DIR/iphone-control/ctl.sock` |-| usbmuxd | 守护进程自己拉起 | 系统服务 |-| 配对记录 | 数据目录的 `lockdown/` | 系统的 `/var/lib/lockdown` |-| 未签名的 WDA | 镜像自带 | 第一次签名前下载(核对 sha256) |-| 配置 | `.env` | `~/.config/iphone-control/env` |+每个命令启动时都会读 `~/.config/iphone-control/env`,环境里已经有的变量优先,见[配置](../guide/configuration#settings-file)。::: warning- 守护进程、命令行和 MCP 要用同一个用户运行。-- 不要和 Docker 版同时连同一部手机。装了系统 usbmuxd 又要用回 Docker 版时,先 `sudo systemctl mask usbmuxd`。+- 一部手机只接一份:不要同时运行两份 iphone-control(比如装了服务又前台运行一个),或其他基于 usbmuxd 的工具(go-ios、pymobiledevice3 等)。:::## 升级@@ -69,6 +48,15 @@ loginctl enable-linger "$USER" # 不登录也随开机启动升级前先看[更新日志](https://github.com/Derrors/iphone-control/blob/main/CHANGELOG.zh-CN.md)里的升级注意事项。```bash-git pull && cargo install --path apps/iphone-control --locked # 或换上新版本的二进制-systemctl --user restart iphone-control+git pull && cargo install --path apps/iphone-control --locked+iphone-control service restart```++## 卸载++```bash+iphone-control service uninstall # 停止并移除后台服务+cargo uninstall iphone-control+```++数据目录 `~/.local/share/iphone-control` 和设置 `~/.config/iphone-control` 会保留,见[数据与备份](./backup)。diff --git a/website/en/deploy/backup.md b/website/en/deploy/backup.mdindex b93ebf3..c6a0ea1 100644--- a/website/en/deploy/backup.md+++ b/website/en/deploy/backup.md@@ -5,14 +5,13 @@| Path | Contents | If lost ||---|---|---|| `account/` | Apple ID session, signing key and certificate | Log in again; a new certificate is created |-| `lockdown/` | Pairing records (Docker) | Tap *Trust* on the phone again || `wda/` | Signed WebDriverAgent | Re-signed automatically || `ddi/` | Developer Disk Image cache | Downloaded again || `secrets/passcodes/` | Per-device passcodes (only with auto-unlock) | Run `passcode set` again || `state.json` | Signed WDA details (Team ID, bundle id, profile expiry), selected device, screen size of the most recent device, last signing result | The daemon starts as if WDA isn't signed: run `sign` or `setup` again, and `select` again if you had selected a device || `logs/` | Logs, auto-unlock's stop marker `UNLOCK-DISABLED` | The logs don't matter. Losing the marker removes a safeguard: after a wrong passcode, the same one could be entered again |-Location: `./data` in the repository directory for Docker (owned by root, mode 0700); `~/.local/share/iphone-control` for a source install, with pairing records in the system's `/var/lib/lockdown`. On macOS the data directory is also `~/.local/share/iphone-control`, and the system keeps pairing records in `/var/db/lockdown` (shared with Finder).+Location: `~/.local/share/iphone-control` (mode 0700), on Linux and macOS alike, whether installed with the one command, Homebrew, the .deb or from source. Pairing records aren't in it; the system usbmuxd keeps them, in `/var/lib/lockdown` on Linux and `/var/db/lockdown` on macOS (shared with Finder). Settings are in `~/.config/iphone-control/env`, which holds notification secrets: don't share it either.::: danger These are secretsThe data directory can log in to your Apple ID developer account, connect to the phone without confirmation, and — with auto-unlock — contains the passcode in plain text. Never commit or share it, and keep backups encrypted.@@ -21,22 +20,32 @@ The data directory can log in to your Apple ID developer account, connect to the## Back up```bash-docker compose stop-sudo tar czf iphone-control-data.tar.gz data # owned by root, hence sudo-docker compose start+iphone-control service stop+tar czf iphone-control-data.tar.gz -C ~/.local/share iphone-control+cp ~/.config/iphone-control/env iphone-control-env # settings+sudo tar czf lockdown.tar.gz /var/lib/lockdown # pairing records, Linux only+iphone-control service start```-Source install:+If the daemon runs in the foreground, stop it with Ctrl-C in its terminal first. On macOS, pairing records belong to the system and don't need a backup; on a new Mac, tap *Trust* on the phone once more.++## Move to a new host++Install on the new host first (see [Getting Started](../guide/getting-started#install)), but don't run `iphone-control` yet. Restore the data directory and the settings file (and `/var/lib/lockdown` on Linux) to the same locations, then run `iphone-control`. No new login is needed, and no new pairing if you restored the pairing records.++## Moving from the Docker deployment++From the next release on there is no Docker image. Your data is in `./data` next to the compose file (or wherever `DATA_DIR` pointed), owned by root. After installing the new version, and before running `iphone-control` for the first time:```bash-systemctl --user stop iphone-control-tar czf iphone-control-data.tar.gz -C ~/.local/share iphone-control-sudo tar czf lockdown.tar.gz /var/lib/lockdown # pairing records-systemctl --user start iphone-control+docker compose down # in the directory of your old compose.yaml+mkdir -p ~/.local/share+sudo cp -a ./data ~/.local/share/iphone-control+sudo chown -R "$(id -un)": ~/.local/share/iphone-control```-macOS: stop the daemon with Ctrl-C in its terminal, then run the second `tar` above. Pairing records belong to the system and don't need a backup; on a new Mac, tap *Trust* on the phone once more.--## Move to a new host+If `~/.local/share/iphone-control` already exists (for example because you already ran `iphone-control`), run `iphone-control service stop`, rename it to keep it, then copy.-Restore the data directory (and `/var/lib/lockdown` for a source install) to the same location on the new host and start it; no new pairing or login is needed.+- Move the settings from `.env` to `~/.config/iphone-control/env` (same `KEY=value` format) with mode 0600; see [Configuration](../guide/configuration#settings-file). Or just run `iphone-control` and let the guide ask again.+- The container's pairing records are in `./data/lockdown/`, which the system usbmuxd doesn't read. On the first run the phone asks "Trust This Computer?" once more, and the guide walks you through it.+- `ICTL_MANAGE_USBMUXD` and `ICTL_USBMUXD_BIN` are gone. On Linux, install the system usbmuxd (`sudo apt install usbmuxd`; the .deb pulls it in). If you ran `sudo systemctl mask usbmuxd` for Docker, run `sudo systemctl unmask usbmuxd` first.diff --git a/website/en/deploy/docker.md b/website/en/deploy/docker.mddeleted file mode 100644index 087cf74..0000000--- a/website/en/deploy/docker.md+++ /dev/null@@ -1,106 +0,0 @@-# Docker--The recommended way to run it. The image holds one Rust binary plus Debian's usbmuxd, and the container is not `privileged`.--## Install--Pick any one of the three; they all end up with the same container.--### Just a compose file--No need to clone the repository — the least effort. Create a directory (e.g. `~/iphone-control`) and put a `compose.yaml` in it:--```yaml-services:- iphone:- image: ghcr.io/derrors/iphone-control:latest # or pin a version, e.g. :0.1.5- container_name: iphone-control- # USB character devices only; no privileged needed- device_cgroup_rules:- - "c 189:* rmw"- init: true- stop_grace_period: 30s- network_mode: host- restart: unless-stopped- environment:- # All optional — uncomment what you need; see "Configuration" for the full list- # HTTP_PROXY: http://127.0.0.1:7890- # HTTPS_PROXY: http://127.0.0.1:7890- NO_PROXY: localhost,127.0.0.1,::1- # BARK_SERVER: https://api.day.app- # BARK_KEY: your-key- # TG_BOT_TOKEN: "123456:ABC..."- # TG_CHAT_ID: "your chat id"- volumes:- - /dev/bus/usb:/dev/bus/usb- - ./data:/var/lib/iphone-control-```--Then, in that directory:--```bash-docker compose up -d-```--`./data` is relative to the directory holding `compose.yaml`; it contains the pairing records and the Apple ID session, so **back it up**. Instead of `environment:` you can put the variables in a `.env` next to it and add `env_file: .env`; if it holds notification keys, keep it out of git. See [Configuration](../guide/configuration) for what each variable does.--### Build it yourself--```bash-git clone https://github.com/Derrors/iphone-control && cd iphone-control-cp .env.example .env-docker compose up -d --build-```--### Use the prebuilt image--Images are published at `ghcr.io/derrors/iphone-control` (amd64, arm64). In `.env`:--```ini-IMAGE=ghcr.io/derrors/iphone-control:latest # or pin a version, e.g. :0.1.5-```--Then:--```bash-docker compose pull && docker compose up -d --no-build-```--Afterwards, run the [setup wizard](../guide/getting-started) once.--## What the compose file does--- Allows only USB character devices (`device_cgroup_rules: "c 189:* rmw"`) and bind-mounts `/dev/bus/usb`, so device nodes created after re-plugging show up in the container.-- `network_mode: host` — only so the host's proxy is reachable; nothing listens on a port.-- Mounts `./data` at `/var/lib/iphone-control`, so pairing and login survive re-creating the container.-- `init: true` and `stop_grace_period: 30s` — on stop it closes the sessions on the phone first, so no "paired computer" icon is left behind.--## Upgrade--Read the upgrade notes in the [changelog](https://github.com/Derrors/iphone-control/blob/main/CHANGELOG.md) first.--```bash-docker compose pull && docker compose up -d # just a compose file-# or-git pull-docker compose up -d --build # self-built-# or-docker compose pull && docker compose up -d --no-build # prebuilt image-```--If the image tag pins a version, change it in `compose.yaml` to the new one before pulling.--Data lives in `./data` and is untouched. Restarting the container drops the MCP connection in your AI client; reconnect it (`/mcp` in Claude Code).--::: tip Wait until it's ready-WDA is ready about 10 seconds after a restart. Several restarts in a row can make the phone ask for the passcode for "XCTest" again — just enter it.-:::--## Everyday commands--```bash-docker exec iphone-control iphone-control status # state-docker exec iphone-control iphone-control doctor # diagnosis-docker logs iphone-control # logs-docker compose down # stop (data is kept)-```diff --git a/website/en/deploy/macos.md b/website/en/deploy/macos.mdindex df85790..d04eaac 100644--- a/website/en/deploy/macos.md+++ b/website/en/deploy/macos.md@@ -1,6 +1,6 @@# macOS-iphone-control also runs directly on a Mac, using the usbmuxd that ships with macOS. No Xcode and no paid developer account. It works like a source install on Linux; the differences are listed under [Known differences](#known-differences).+iphone-control also runs directly on a Mac, using the usbmuxd that ships with macOS. No Xcode and no paid developer account. It works much like on Linux; the differences are listed under [Known differences](#known-differences).::: info VerifiedVerified on a MacBook Pro (Apple M3 Pro) / macOS 26.6.2 with an iPhone 15 Pro Max / iOS 27.0.1: the setup wizard, every MCP tool at that time, continuous use with Finder open, one tunnel kept busy for 30 minutes, and recovery after unplugging and phone reboots. This predates 0.1.3: the multi-device tools (`iphone_list_devices`, `iphone_select_device`) haven't been verified on macOS. Intel Macs are untested. Steps and results: [macOS verification](https://github.com/Derrors/iphone-control/blob/main/docs/dev/macos-verification.md) (in Chinese).@@ -8,43 +8,30 @@ Verified on a MacBook Pro (Apple M3 Pro) / macOS 26.6.2 with an iPhone 15 Pro Ma## You need-- An Apple Silicon Mac-- Nothing else for the prebuilt binary; to build from source, the Xcode Command Line Tools and Rust 1.88+. Full Xcode is **not** needed+- An Apple Silicon Mac: the one command and Homebrew install the built program, nothing else needed. Intel Macs have no prebuilt package and build from source (Xcode Command Line Tools and Rust 1.88+). Full Xcode is **not** needed- An iPhone or iPad on iOS 17+, connected with a cable that carries **data**- A free Apple ID (a dedicated one is recommended)-::: warning No Docker-Docker Desktop on a Mac runs containers in a Linux VM without USB passthrough, so a container can't see the phone. Run the program directly.-:::-## Install-### Prebuilt binary--Since 0.1.2, [Releases](https://github.com/Derrors/iphone-control/releases) has a macOS archive (Apple Silicon, macOS 11+): `iphone-control-<version>-macos-arm64.tar.gz`. Download and install it from a terminal (set `V` to the latest version):+### One command (recommended)```bash-V=v0.1.5-curl -fsSLO https://github.com/Derrors/iphone-control/releases/download/$V/iphone-control-$V-macos-arm64.tar.gz-curl -fsSLO https://github.com/Derrors/iphone-control/releases/download/$V/iphone-control-$V-macos-arm64.tar.gz.sha256-shasum -a 256 -c iphone-control-$V-macos-arm64.tar.gz.sha256 # should print OK-tar xzf iphone-control-$V-macos-arm64.tar.gz-mkdir -p ~/.local/bin && install -m 755 iphone-control-$V-macos-arm64/iphone-control ~/.local/bin/-echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zprofile && source ~/.zprofile # once-iphone-control --version+curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh```-::: tip "Developer cannot be verified"-The binary isn't notarized by Apple (that needs a paid developer account). Downloaded with `curl` as above it runs as is; downloaded with a browser it carries a quarantine flag and Gatekeeper blocks the first run. Remove the flag:+It downloads the latest release, checks its sha256, installs `~/.local/bin/iphone-control` and a launchd user service (`~/Library/LaunchAgents/io.github.derrors.iphone-control.plist`) that starts the daemon at login, restarts it after a crash, reads `~/.config/iphone-control/env` and logs to `~/Library/Logs/iphone-control/daemon.log`. Options go after `sh -s --`: `--version v0.2.0`, `--prefix DIR` (installs into `DIR/bin`), `--no-service` (only the binary, no service).++### Homebrew```bash-xattr -d com.apple.quarantine ~/.local/bin/iphone-control+brew install derrors/tap/iphone-control+brew services start iphone-control # the daemon runs now and after each login```-or click *Open Anyway* under *System Settings → Privacy & Security*.-:::+This service also reads `~/.config/iphone-control/env` and logs to `$(brew --prefix)/var/log/iphone-control.log`. The settings template is `$(brew --prefix)/opt/iphone-control/share/iphone-control/env.example`.-### Build from source+### Build from source (Intel Macs)You need the Xcode Command Line Tools and Rust 1.88+; about 2½ minutes on an M3 Pro:@@ -56,53 +43,47 @@ cargo install --path apps/iphone-control --locked # installs ~/.cariphone-control --version```+The setup guide below sets up the background service.+## Run-**Run everything as your regular user, never with sudo.** macOS's own usbmuxd is always running and the daemon uses it. As root, the daemon would start a second usbmuxd that fights the system one, and would switch to Linux system paths (`/var/lib`, `/run`) for its data and control socket.+**Run everything as your regular user, never with sudo.** macOS's own usbmuxd is always running and the daemon uses it. As root, the daemon would switch to Linux system paths (`/var/lib`, `/run`) for its data and control socket, and the install script refuses to run as root.-In one terminal, start the daemon; its log prints there:+Connect the phone with a cable, then:```bash-iphone-control daemon+iphone-control```-In a second terminal, run the setup wizard:--```bash-iphone-control setup-```+The first run walks you through setup step by step: language, proxy, background service, pairing, Developer Mode, Apple ID, signing and installing WDA, auto-unlock and notifications (optional), and registering with Claude Code and Codex. What to do on the phone is in [Getting Started](../guide/getting-started#first-run). If the phone already trusts this Mac (from Finder), the pairing step just says it is paired. Once set up, running `iphone-control` again only shows the status.-The six steps are the same as on Linux; what to do on the phone is in [Getting Started](../guide/getting-started#_2-run-the-setup-wizard). If the phone already trusts this Mac (from Finder), the pairing step just says it is paired.+### Doing it by hand-When the wizard says WDA is ready (WDA 就绪), connect your AI client:+Each thing the guide does can be done on its own:```bash-iphone-control mcp-config # prints the registration command; run it+iphone-control daemon # the daemon in the foreground, in one terminal (without the service)+iphone-control setup # in a second terminal: the guide again, done steps skipped+iphone-control mcp-config # prints the MCP registration command; run it```-It prints something like `claude mcp add iphone -s user -- /Users/you/.cargo/bin/iphone-control --socket /Users/you/.local/share/iphone-control/ctl.sock mcp`. Other clients: [Connect an AI Client](../guide/mcp-clients).+`mcp-config` prints something like `claude mcp add iphone -s user -- /Users/you/.local/bin/iphone-control --socket /Users/you/.local/share/iphone-control/ctl.sock mcp`. With Homebrew the program path is `/opt/homebrew/opt/iphone-control/bin/iphone-control`, which stays the same across upgrades. Other clients: [Connect an AI Client](../guide/mcp-clients).### Configuration-Settings go in `~/.config/iphone-control/env` (same format as `.env.example` in the repository). Load it before starting the daemon:--```bash-mkdir -p ~/.config/iphone-control-cp .env.example ~/.config/iphone-control/env # proxy, notifications, … (env.example in the prebuilt archive)-set -a; . ~/.config/iphone-control/env; set +a-iphone-control daemon-```--Restart the daemon (Ctrl-C, then run it again) after changing settings. The variables are listed in [Configuration](../guide/configuration).+Settings are in `~/.config/iphone-control/env`; the guide and `iphone-control setup --reconfigure` write it. After editing it by hand, run `iphone-control service restart`. The variables are listed in [Configuration](../guide/configuration#settings-file).### Keep it running-There is no launchd configuration yet, so keep the daemon in a terminal (or tmux). It pauses while the Mac sleeps; for long unattended runs, keep the Mac awake with `caffeinate`:+The background service set up by the one command, Homebrew or the guide starts the daemon when you log in; nothing else to do:```bash-caffeinate -i iphone-control daemon+iphone-control service status # whether the service and the daemon run+iphone-control service restart # restart, e.g. after changing settings```+The daemon pauses while the Mac sleeps. For long unattended runs, run `caffeinate -i` in a terminal and leave it open to keep the Mac awake.+## Keep the USB connection stable- **Set the phone's charging limit to 100%** under *Settings → Battery → Charging*. With the 80% limit on, the phone keeps starting and stopping charging near 80%, and each switch renegotiates USB-C power, which drops USB for 3–5 seconds about once a minute. The daemon reconnects by itself, but actions in progress fail.@@ -111,8 +92,6 @@ caffeinate -i iphone-control daemon## Everyday commands-Same as on Linux, run directly without `docker exec`:-```bashiphone-control status # state, signing time left, recent logiphone-control doctor # layer-by-layer checks@@ -130,21 +109,21 @@ sudo launchctl kickstart -k system/com.apple.usbmuxdRead the upgrade notes in the [changelog](https://github.com/Derrors/iphone-control/blob/main/CHANGELOG.md) first.-Prebuilt binary: download the new version as under *Install* and replace `~/.local/bin/iphone-control`. From source:+Installed with the one command: run it again; it stops the service, replaces the binary and starts it again. Homebrew: `brew upgrade iphone-control && brew services restart iphone-control`. From source:```bashcd iphone-control && git pullcargo install --path apps/iphone-control --locked+iphone-control service restart```-Then restart the daemon.-## Uninstall-Stop the daemon with Ctrl-C in its terminal, then:+Installed with the one command: `curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh -s -- --uninstall`. Homebrew: `brew services stop iphone-control && brew uninstall iphone-control`. From source: `iphone-control service uninstall && cargo uninstall iphone-control`.++All of them keep your data and settings. To remove them too:```bash-rm -f ~/.local/bin/iphone-control # prebuilt binary; for a source build: cargo uninstall iphone-controlrm -rf ~/.local/share/iphone-control ~/.config/iphone-control # deletes the Apple ID session and signed WDA```@@ -152,14 +131,13 @@ On the phone, delete the WebDriverAgent app; its profile under *VPN & Device Man## Known differences-| | Linux (source install) | macOS |+| | Linux | macOS ||---|---|---|-| Install | Prebuilt binary or build from source | Same (Apple Silicon archive only) |-| Keep running | systemd user service | No launchd configuration yet; run in a terminal |+| Install | One command, Homebrew, .deb or build from source | One command, Homebrew or build from source (packages for Apple Silicon only) |+| Keep running | systemd user service | launchd user service || usbmuxd | System package, started by udev on plug-in | Built into macOS, always running || Data directory | `~/.local/share/iphone-control` | Same (not the usual `~/Library/Application Support`) || Control socket | `$XDG_RUNTIME_DIR/iphone-control/ctl.sock` | `~/.local/share/iphone-control/ctl.sock` || Pairing records | `/var/lib/lockdown` | `/var/db/lockdown` (shared with Finder) |-| Docker | Supported | Not supported |Not yet verified on a Mac: whether Xcode's *Devices and Simulators* window competes for the connection, pairing a phone with the Mac for the first time, iPads, several devices, and Intel Macs. [Reports](https://github.com/Derrors/iphone-control/issues) are welcome.diff --git a/website/en/deploy/source.md b/website/en/deploy/source.mdindex 740acac..7d38742 100644--- a/website/en/deploy/source.md+++ b/website/en/deploy/source.md@@ -1,67 +1,46 @@-# Source / Binary+# Build from Source-Run it directly as a regular user on Linux, without Docker. You need the system usbmuxd (udev starts it when the phone is plugged in). On a Mac, see [macOS](./macos).+Usually you don't need this: the one-line installer, Homebrew and the .deb all install the program built for the release; see [Getting Started](../guide/getting-started#install). Build from source on machines without a prebuilt package (Intel Macs) and for development. On a Mac, see [macOS](./macos).-## Install+## Requirements-### Prebuilt binary+- Rust 1.88+ ([rustup](https://rustup.rs)) and a C compiler+- On Linux, the system usbmuxd (udev starts it when the phone is plugged in). The daemon doesn't start usbmuxd itself-[Releases](https://github.com/Derrors/iphone-control/releases) has Linux x86_64 and aarch64 archives (glibc 2.34 or later: Debian 12, Ubuntu 22.04 and newer):+## Build and install```bash-sudo apt install usbmuxd-tar xzf iphone-control-v*-x86_64*.tar.gz # on ARM, aarch64 instead of x86_64 (see uname -m)-install -Dm755 iphone-control-*/iphone-control ~/.cargo/bin/iphone-control-```--`~/.cargo/bin` matches the systemd unit below; if you put it elsewhere, change `ExecStart` in the unit too.--### Build from source--You need Rust 1.88+ ([rustup](https://rustup.rs)) and a C compiler:--```bash-sudo apt install build-essential git usbmuxd+sudo apt install build-essential git usbmuxd # or your distribution's package managergit clone https://github.com/Derrors/iphone-control && cd iphone-controlcargo install --path apps/iphone-control --locked # installs ~/.cargo/bin/iphone-control```## Run+Run it as your regular user, not with sudo. Connect the phone with a cable, then:+```bash-iphone-control daemon # in the foreground-iphone-control setup # setup wizard, in a second terminal-iphone-control mcp-config # prints the MCP registration command+iphone-control```-Only the systemd service below reads `~/.config/iphone-control/env`. In the foreground, load it first: `set -a; . ~/.config/iphone-control/env; set +a`.+The first run is the setup guide, the same as for a packaged install; see [Getting Started](../guide/getting-started#first-run). Its "Background service" step sets up a systemd user service (`~/.config/systemd/user/iphone-control.service`, reading `~/.config/iphone-control/env`), so the daemon starts when you log in. You can also set it up on its own:-### Keep it running: systemd user service+```bash+iphone-control service install+sudo loginctl enable-linger "$USER" # start at boot without logging in+```-The unit is `deploy/iphone-control.service` in the repository (also included in the binary archives):+For development you can skip the service and run the daemon in the foreground in a terminal, with its log printed there:```bash-mkdir -p ~/.config/systemd/user ~/.config/iphone-control-cp deploy/iphone-control.service ~/.config/systemd/user/-cp .env.example ~/.config/iphone-control/env # proxy, notifications, … (env.example in the binary archive)-systemctl --user daemon-reload && systemctl --user enable --now iphone-control-loginctl enable-linger "$USER" # start at boot without logging in+iphone-control daemon```-## Differences from Docker--| | Docker | Source (regular user) |-|---|---|---|-| Data directory | `./data` | `~/.local/share/iphone-control` |-| Control socket | `/run/iphone-control/ctl.sock` in the container | `$XDG_RUNTIME_DIR/iphone-control/ctl.sock` |-| usbmuxd | started by the daemon | the system service |-| Pairing records | `lockdown/` in the data directory | the system's `/var/lib/lockdown` |-| Unsigned WDA | shipped in the image | downloaded before the first signing (sha256-checked) |-| Configuration | `.env` | `~/.config/iphone-control/env` |+Every command reads `~/.config/iphone-control/env` when it starts; a variable already in the environment wins. See [Configuration](../guide/configuration#settings-file).::: warning- Run the daemon, the CLI and the MCP server as the same user.-- Don't run it alongside the Docker version against the same phone. With a system usbmuxd installed, `sudo systemctl mask usbmuxd` before going back to Docker.+- One copy per phone: don't run two copies of iphone-control (for example the service plus one in the foreground), or other usbmuxd-based tools (go-ios, pymobiledevice3, …).:::## Upgrade@@ -69,6 +48,15 @@ loginctl enable-linger "$USER" # start at boot without loggingRead the upgrade notes in the [changelog](https://github.com/Derrors/iphone-control/blob/main/CHANGELOG.md) first.```bash-git pull && cargo install --path apps/iphone-control --locked # or drop in the new binary-systemctl --user restart iphone-control+git pull && cargo install --path apps/iphone-control --locked+iphone-control service restart```++## Uninstall++```bash+iphone-control service uninstall # stop and remove the background service+cargo uninstall iphone-control+```++The data directory `~/.local/share/iphone-control` and the settings in `~/.config/iphone-control` are kept; see [Data and Backups](./backup).diff --git a/website/en/guide/auto-unlock.md b/website/en/guide/auto-unlock.mdindex 29ba52a..aa6791f 100644--- a/website/en/guide/auto-unlock.md+++ b/website/en/guide/auto-unlock.md@@ -8,15 +8,17 @@ The passcode is stored **in plain text** in the data directory. Anyone who can l## Enable+The first-run guide of `iphone-control` offers it as an optional step; later, run `iphone-control setup --reconfigure` and pick Auto-unlock passcode. Or use the command directly:+```bash-docker exec -it iphone-control iphone-control passcode set+iphone-control passcode set```The passcode is saved for the device the daemon is controlling; for another one add `--device <UDID or name>`. Numeric passcodes of 4 or more digits only. To disable:```bash-docker exec -it iphone-control iphone-control passcode clear # the controlled device; --device for another-docker exec -it iphone-control iphone-control passcode clear --all # all devices+iphone-control passcode clear # the controlled device; --device for another+iphone-control passcode clear --all # all devices```## Several devices@@ -39,8 +41,8 @@ Older versions kept a single passcode (`secrets/passcode`) without knowing whichUnlock the phone by hand first. If the passcode was wrong (for example, you changed it), save the new one and reset:```bash-docker exec -it iphone-control iphone-control passcode set-docker exec -it iphone-control iphone-control unlock-reset+iphone-control passcode set+iphone-control unlock-reset```If it stopped because of an error during entry or a killed process, the passcode may be fine; once you've checked, `unlock-reset` alone is enough. `unlock-reset` doesn't check the passcode, and `passcode set` and `passcode clear` don't lift the stop. Don't delete `logs/` to get going again: that removes this safeguard.diff --git a/website/en/guide/cli.md b/website/en/guide/cli.mdindex a6031c9..9c7ec10 100644--- a/website/en/guide/cli.md+++ b/website/en/guide/cli.md@@ -1,6 +1,8 @@# CLI-Every command is `iphone-control <command>`. With Docker, prefix it with `docker exec -it iphone-control`; for a source install and on macOS, run it directly. `--help` shows help, `--version` the version. Output is in Simplified Chinese by default; set `IPHONE_CONTROL_LANG=en` for English.+Every command is `iphone-control <command>`. `--help` shows help, `--version` the version. Output is in Simplified Chinese by default; set `IPHONE_CONTROL_LANG=en` for English (the first-run guide asks).++`iphone-control` with no command runs the [first-run guide](./getting-started#first-run) the first time; once set up, it shows the status (and starts the daemon first if it isn't running).## Global options@@ -15,15 +17,30 @@ These go before the command, for example `iphone-control --socket /path/ctl.sock| Command | What it does ||---|---|-| `daemon` | The long-running daemon. The container's entry point; for a source install it's started by systemd or by hand, and on macOS you run it in a terminal |+| `daemon` | The long-running daemon. Usually started by the background service; you can also run it in a terminal || `mcp` | MCP stdio server, started by the AI client |-| `mcp-config [--container <name>]` | Prints the command that registers the MCP server with Claude Code. Inside a container or with `--container` it uses `docker exec`; otherwise it calls this binary directly |+| `mcp-config` | Prints the command that registers the MCP server with Claude Code, with a program path that stays the same across upgrades (Homebrew's `opt` link) |++## Background service++The daemon runs as a per-user service: launchd on macOS, a systemd user service on Linux. It starts when you log in and restarts after a crash. No root needed.++| Command | What it does |+|---|---|+| `service install` | Set up the service and start it; if one exists, just start it |+| `service uninstall` | Stop and remove the service this program set up; data is kept. A service that came with Homebrew or the .deb isn't removed: it is disabled, or you're told how to stop it |+| `service start` / `stop` | Start or stop it |+| `service restart` | Restart it, after editing `~/.config/iphone-control/env` |+| `service status` | Which service is set up, and whether the daemon is running |++These commands find the service set up by the one-command install, `iphone-control service install`, `brew services` or the .deb, and act on whichever is there.-## Setup and signing+## Setup and signing {#setup}| Command | What it does ||---|---|-| `setup` | Setup wizard: pairing, Developer Mode, Apple ID sign-in, signing and installing WDA. Safe to re-run; only acts on the controlled device |+| `setup` | Runs the whole guide again: language, proxy, background service, pairing, Developer Mode, Apple ID, signing and installing WDA, auto-unlock, notifications, MCP registration. Done steps are skipped. The phone part only acts on the controlled device |+| `setup --reconfigure` | Set up one part again, picked from a menu: all of it, language, proxy, background service, Apple ID (sign in again and re-sign WDA), phone (pairing, Developer Mode, WDA), auto-unlock passcode, notifications, MCP registration (Claude Code, Codex) || `login [email]` | Sign in to the Apple ID. The password and code are only typed here; without an email it asks for one || `sign` | Sign and install WDA now, same as `resign --force`. Registers the device with the Apple ID || `resign [--force]` | Re-sign only when fewer than `RESIGN_MIN_DAYS` days remain; `--force` re-signs now. Without `--force` it doesn't register a device that has never had WDA |@@ -61,12 +78,12 @@ See [Auto-unlock](./auto-unlock). `--device` takes a UDID or name, and the devic|---|---|| `notify-test [event]` | Send test notifications: one per event type, or one type (`resign`, `session`, `pin`, `pin-recovered`, `unlock`, `offline`, `online`) || `wda-bridge [--port <port>]` | Expose WDA on `127.0.0.1` (default port 8100) for other tools. WDA has no authentication and every local user can reach it, so stop it when done |-| `viewer [--port <port>]` | Live screen in the browser at `http://127.0.0.1:8200/` (default port): click to tap, drag to swipe, hold to long-press, plus a text field and the hardware buttons. Taps and typing go through the daemon like an MCP call, so they queue with the agent and unlock the phone first. It belongs to the device controlled when it starts: after switching to another device its actions are refused and you need to run it again. The picture is WDA's MJPEG stream, so there is none until WDA is ready. Every local user can reach the port, so stop it when done |+| `viewer [--port <port>]` | Control page in the browser at `http://127.0.0.1:8200/` (default port), in English or Chinese (follows `IPHONE_CONTROL_LANG`, switchable on the page). **Screen:** the live picture works like a touchscreen: click to tap, drag to swipe, hold to long-press, scroll with the mouse wheel or trackpad, plus a text field and the hardware buttons. On iOS 27 and later the finger follows the pointer as it moves (over CoreDevice HID, which keeps the phone awake until 30 seconds after the last touch); older versions get the whole gesture on release. Everything goes through the daemon like an MCP call, so it queues with the agent and unlocks the phone first. The picture is WDA's MJPEG stream, so there is none until WDA is ready. **Device panel:** state and readiness checks, installed apps, on-screen elements. The page follows the device the daemon controls: switch on the page or anywhere else, and the picture and panels move over; see [Several Devices](./multi-device#control-page). **AI tasks:** type a task and a local agent carries it out (Claude Code or Codex, whichever is on `PATH`; picked on the page). You can pause, take over and hand back, or stop it, and it asks on the page before paying, deleting or sending messages. Every local user can reach the port, so stop it when done |The `debug` subcommand for diagnostics isn't compiled by default; see the [contributing guide](https://github.com/Derrors/iphone-control/blob/main/CONTRIBUTING.md#testing-on-a-real-phone).## Notes-- **Need the daemon running:** `setup`, `status`, `doctor`, `sign`, `resign`, `devices`, `select`, `unlock-reset`, `wda-bridge`, `viewer`, and MCP tool calls.-- **Need an interactive terminal:** `setup`, `login`, `passcode set`; use `-it` with Docker.-- **Environment variables:** the CLI reads the environment of the current shell. For a source install and on macOS, only the daemon loads `~/.config/iphone-control/env`; before `login`, `setup` (if you set `ICTL_ANISETTE_URL`), `notify-test` or `mcp-config`, run `set -a; . ~/.config/iphone-control/env; set +a`.+- **Need the daemon running:** the phone part of `setup`, `status`, `doctor`, `sign`, `resign`, `devices`, `select`, `unlock-reset`, `wda-bridge`, `viewer`, and MCP tool calls.+- **Need an interactive terminal:** `iphone-control` with no command (the first time), `setup`, `login`, `passcode set`.+- **Settings:** every command reads `~/.config/iphone-control/env` when it starts; a variable already in the environment wins. See [Configuration](./configuration#settings-file).diff --git a/website/en/guide/configuration.md b/website/en/guide/configuration.mdindex 8a320b7..bd519fc 100644--- a/website/en/guide/configuration.md+++ b/website/en/guide/configuration.md@@ -1,30 +1,36 @@# Configuration-Everything is configured with environment variables, and all of them are optional:+Everything is configured with environment variables, and all of them are optional.-- **Docker:** in `.env` in the repository directory (copied from `.env.example`); apply with `docker compose up -d`.-- **Just a compose file:** under `environment:` in your `compose.yaml` (or a `.env` next to it plus `env_file`); apply with `docker compose up -d` as well.-- **Source install:** in `~/.config/iphone-control/env` (read by the systemd user service); apply with `systemctl --user restart iphone-control`.-- **macOS:** also in `~/.config/iphone-control/env`, loaded before starting the daemon; restart the daemon to apply. See [macOS](../deploy/macos#configuration).+## Settings file {#settings-file}++Settings go in `~/.config/iphone-control/env`, one `KEY=value` per line, mode 0600 (it holds notification secrets: don't commit or share it). The first-run guide of `iphone-control` and `iphone-control setup --reconfigure` write it for you; you can also edit it by hand, following the template. The template is `packaging/env.example` in the repository, and a copy is installed:++- One-command install: `~/.config/iphone-control/env.example`+- Homebrew: `$(brew --prefix)/opt/iphone-control/share/iphone-control/env.example`+- .deb: `/usr/share/doc/iphone-control/env.example`++The daemon reads the file when it starts, and so does every other command (`login`, `notify-test`, `mcp-config`, and the `mcp` server the AI client starts), so there is no need to load it into your shell first. A variable that is already in the environment wins, so a value you set on the command line overrides the file.++After editing it by hand, restart the daemon:++```bash+iphone-control service restart+```## Common| Variable | Default | Meaning ||---|---|---|| `HTTP_PROXY` / `HTTPS_PROXY` | direct | Proxy for Apple, anisette, Developer Disk Image and notification traffic |-| `IPHONE_CONTROL_LANG` | `zh` | Language: `zh` or `en`. Applies to tool descriptions and results, CLI output, logs and notifications. The MCP server and the CLI each send their own setting and the daemon answers in it; logs and notifications follow the daemon's own setting. For a source install, see the note below the table |-| `IPHONE_CONTROL_DEV_TOOLS` | off | `1` adds the [developer tools](./tools#developer-tools-opt-in) to the MCP server: logs, crash reports, installing and removing apps, and Web Inspector (JavaScript in web pages and WebViews). See [Security](./security) for the risks. For a source install, see the note below the table |+| `IPHONE_CONTROL_LANG` | `zh` | Language: `zh` or `en`. Applies to tool descriptions and results, CLI output, logs and notifications. The MCP server and the CLI each send their own setting and the daemon answers in it; logs and notifications follow the daemon's own setting. See the note below the table |+| `IPHONE_CONTROL_DEV_TOOLS` | off | `1` adds the [developer tools](./tools#developer-tools-opt-in) to the MCP server: logs, crash reports, installing and removing apps, and Web Inspector (JavaScript in web pages and WebViews). See [Security](./security) for the risks. See the note below the table || `IPHONE_UDID` | automatic | Pin the device to control. Unset: the controlled device is kept until it disconnects, and you can switch with the `select` command or the `iphone_select_device` tool. When set, switching is refused || `RESIGN_MIN_DAYS` | `2` | Re-sign when fewer days than this remain || `RESIGN_CHECK_HOURS` | `6` | How often to check; it is also checked within a minute after the phone reconnects or you switch devices || `OFFLINE_ALERT_MIN` | `10` | Notify after the phone has been offline this many minutes; `0` disables |-For a source install and on macOS, only the daemon loads `~/.config/iphone-control/env`. The AI client starts the MCP server, which never reads that file, so `IPHONE_CONTROL_LANG` and `IPHONE_CONTROL_DEV_TOOLS` have to go into the MCP configuration. `iphone-control mcp-config` reads the environment of the current shell, so load the file first and the registration command it prints will include them:--```bash-set -a; . ~/.config/iphone-control/env; set +a-iphone-control mcp-config-```+The AI client starts the MCP server, and variables set in its registration win over the settings file. The guide and `iphone-control mcp-config` put `IPHONE_CONTROL_LANG=en` and `IPHONE_CONTROL_DEV_TOOLS=1` into the registration command when they are set, so after changing either one, register again: run `iphone-control setup --reconfigure`, pick MCP registration, and open a new session.For clients configured with JSON, see [Connect an AI Client](./mcp-clients#claude-desktop-cursor-and-others).@@ -37,28 +43,16 @@ Notification variables: see [Notifications](./notifications).| `ICTL_ANISETTE_URL` | Your own anisette server (the default is a public third-party one; see [Security](./security)) || `ICTL_DDI_URL` | Developer Disk Image download URL; the default is a community-maintained mirror || `ICTL_DDI_DIR` | A Developer Disk Image directory you extracted from Xcode. The daemon doesn't download anything or delete its files, and the error names any missing file. When unset, the `ddi/` cache in the data directory is used, and it is deleted and downloaded again after 3 failed mounts in a row |-| `ICTL_MANAGE_USBMUXD` | Whether the daemon starts its own usbmuxd. Default: yes as root (container), no as a regular user, which uses the system one. `0` or `false` turns it off, for example as root on a host that already runs a usbmuxd service |-| `ICTL_USBMUXD_BIN` | The executable the daemon runs when it starts usbmuxd itself; default `usbmuxd` |-| `ICTL_WDA_UNSIGNED` | Path of the unsigned WDA. Default: `/usr/share/iphone-control/WDA-unsigned.ipa` in the image; without an image (source install), `wda/WDA-unsigned.ipa` in the data directory, downloaded before the first signing. A path you set yourself is not downloaded |+| `ICTL_WDA_UNSIGNED` | Path of the unsigned WDA. Default: `wda/WDA-unsigned.ipa` in the data directory, downloaded before the first signing. A path you set yourself is not downloaded || `SCREEN_W` / `SCREEN_H` | Screen size in points for the HID fallback, used only while WDA is down and there is no record of this device's size: WDA has never connected, or you switched to a device without one. It applies to every device, so take care with several || `ICTL_LOG` | Log filter, e.g. `info,ictl_wda::http=debug` logs every WDA request with its duration |## Directories and control socket-You normally leave these alone, and shouldn't change them with Docker (the container fixes `ICTL_DATA_DIR`, where the data volume is mounted). If you do set them, don't leave them empty, and give the daemon, the CLI and the MCP server the same values: outside a container only the daemon reads the settings file; see [Source / Binary](../deploy/source#run).+You normally leave these alone. If you do change them, put them in the [settings file](#settings-file) and don't leave them empty: the daemon, the CLI and the MCP server need the same values. The MCP registration carries `--socket`, so after changing `ICTL_SOCKET`, register again (`setup --reconfigure`, MCP registration).| Variable | Default | Meaning ||---|---|---|| `ICTL_DATA_DIR` | root: `/var/lib/iphone-control`<br>regular user: `$XDG_DATA_HOME/iphone-control`, or `~/.local/share/iphone-control` if unset | Data directory; same as the CLI's `--data-dir` || `ICTL_SOCKET` | root: `/run/iphone-control/ctl.sock`<br>regular user: `$XDG_RUNTIME_DIR/iphone-control/ctl.sock`, or in the data directory without that variable (macOS) | The daemon's control socket; same as the CLI's `--socket` || `XDG_DATA_HOME` / `XDG_RUNTIME_DIR` | set by the system | Not this project's variables; they only change the two defaults above for a regular user |--## Docker Compose only--These apply to the repository's own `compose.yaml`; in a compose file you wrote yourself, edit `container_name`, `image` and `volumes` directly.--| Variable | Default | Meaning |-|---|---|---|-| `CONTAINER_NAME` | `iphone-control` | Container name |-| `IMAGE` | `iphone-control:local` | Image; set `ghcr.io/derrors/iphone-control:<version>` for the prebuilt one |-| `DATA_DIR` | `./data` | Data directory; see [Data and Backups](../deploy/backup) |diff --git a/website/en/guide/getting-started.md b/website/en/guide/getting-started.mdindex 96c4221..f13743d 100644--- a/website/en/guide/getting-started.md+++ b/website/en/guide/getting-started.md@@ -1,80 +1,114 @@# Getting Started-Deploying with Docker on Linux takes about 15 minutes. Without Docker, see [Source / Binary](../deploy/source); on a Mac, see [macOS](../deploy/macos) — the setup wizard and client steps are the same as here.+Install the program, plug in the phone, run `iphone-control` and follow the guide. It takes about 15 minutes. The steps are the same on Linux and a Mac; Mac details are in [macOS](../deploy/macos).## You need-- A Linux host with Docker (including Compose v2)+- A host: a Mac with Apple silicon, or Linux (x86_64, aarch64)- An iPhone or iPad (iOS 17+) and a cable that carries data- A free Apple ID (a dedicated one is recommended)-- Internet access to Apple and GitHub from the host (set a proxy if needed)+- Internet access to Apple and GitHub from the host (the guide asks for a proxy if you need one)::: warning One phone, one owner-Don't run two copies of iphone-control, or other usbmuxd-based tools (go-ios, pymobiledevice3, …), against the same phone. If a Linux host has usbmuxd installed, run `sudo systemctl mask usbmuxd` first.+Don't run two copies of iphone-control, or other usbmuxd-based tools (go-ios, pymobiledevice3, …), against the same phone.:::-## 1. Start+## 1. Install {#install}++Pick one of the three. Install as your regular user; don't run `iphone-control` as root or with sudo.++**One command** (macOS, Linux):```bash-git clone https://github.com/Derrors/iphone-control && cd iphone-control-cp .env.example .env # set HTTP_PROXY / HTTPS_PROXY here if you need a proxy-docker compose up -d --build+curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh```-The first build compiles Rust and takes a few minutes. You can also use the prebuilt image instead; see [Docker](../deploy/docker).+It installs the program into `~/.local/bin` and the daemon as a per-user service (launchd on macOS, a systemd user service on Linux) that starts when you log in. Running it again upgrades. Options go after `sh -s --`: `--version vX.Y.Z` installs that release, `--prefix DIR` installs into `DIR/bin`, `--no-service` installs only the program.-## 2. Run the setup wizard--Plug in the phone, unlock it, then:+**Homebrew** (macOS, Linux):```bash-docker exec -it iphone-control iphone-control setup+brew install derrors/tap/iphone-control+brew services start iphone-control```-The wizard has six steps. What you do on the phone:+**Debian / Ubuntu package:** download `iphone-control_<version>_amd64.deb` (`_arm64.deb` on ARM) from the [GitHub Release](https://github.com/Derrors/iphone-control/releases), then:-| Step | On the phone |-|---|---|-| 1. Connect | Unlock it |-| 2. Pair | Tap *Trust* when asked "Trust This Computer?", enter the passcode |-| 3. Developer Mode | *Settings → Privacy & Security → Developer Mode → On*, restart, then tap *Turn On* after unlocking |-| 4. Apple ID | (in the terminal) enter the Apple ID, password and two-factor code |-| 5. Sign and install WDA | Keep the phone unlocked |-| 6. Start WDA | *Settings → General → VPN & Device Management* → trust your Apple ID; if asked to *enter the iPhone passcode for "XCTest"*, enter it |+```bash+sudo apt install ./iphone-control_<version>_amd64.deb+systemctl --user enable --now iphone-control # as your regular user; each user turns it on for themselves+```-You can run the wizard again at any time: pairing, Developer Mode and login are skipped when already done; signing is redone. You're finished when it says WDA is ready (WDA 就绪).+You can skip the second line: the guide below starts it for you.-::: tip Your password stays in the terminal-The Apple ID password and code are only typed here and never written to disk; only the resulting session is stored.+::: tip Linux needs the system usbmuxd+Talking to the phone over USB goes through the system's usbmuxd: `sudo apt install usbmuxd` (or your distribution's package manager). The .deb pulls it in.:::-## 3. Connect your AI client+Intel Macs have no prebuilt binary and need a build from source, as does development. See [Build from Source](../deploy/source).-```bash-docker exec -it iphone-control iphone-control mcp-config-```+## 2. Plug in the phone and run iphone-control {#first-run}-It prints the registration command. For Claude Code:+Plug in the phone with a cable, unlock it, then run in a terminal:```bash-claude mcp add iphone -s user -- docker exec -i iphone-control iphone-control mcp+iphone-control```-Other clients: [Connect an AI Client](./mcp-clients).+The first time, it walks you through setup step by step. Steps that are already done are skipped; if you stop halfway, running `iphone-control` again picks up where you left. It needs an interactive terminal.-## 4. Try it+| Step | What you do |+|---|---|+| Language | Pick 中文 or English |+| Proxy | Enter a proxy URL if you need one, e.g. `http://127.0.0.1:7890` |+| Background service | If no service is set up yet, press Enter to set it up and start it |+| Waiting for the phone | Unlock it |+| Pairing | On the phone, tap *Trust* when asked "Trust This Computer?", enter the passcode |+| Developer Mode | On the phone: *Settings → Privacy & Security → Developer Mode → On*, restart, then tap *Turn On* after unlocking |+| Apple ID | In the terminal, enter the Apple ID, password and two-factor code |+| Sign and install WDA | Keep the phone unlocked |+| Waiting for WDA | On the phone: *Settings → General → VPN & Device Management* → trust your Apple ID (needs internet); if asked to *enter the iPhone passcode for "XCTest"*, enter it |+| Auto-unlock (optional) | Enter the passcode if you want it; see [Auto-unlock](./auto-unlock) |+| Notifications (optional) | Pick Bark or Telegram and enter the key or token; a test message is sent. See [Notifications](./notifications) |+| MCP registration | If Claude Code or Codex is found, press Enter to register with it |++You're finished when it says *All set*. Settings are saved in `~/.config/iphone-control/env`; see [Configuration](./configuration#settings-file).-In Claude Code, say:+::: tip Your password stays in the terminal+The Apple ID password and code are only typed here and never written to disk; only the resulting session is stored.+:::++From then on, `iphone-control` just shows the status, and starts the daemon first if it isn't running. To change a setting, run `iphone-control setup --reconfigure` and pick the part to set up again; see [CLI](./cli#setup).++## 3. Try it++Open a new Claude Code or Codex session and say:> Open Settings on the iPhone and tell me which iOS version it runs.-The agent will use `iphone_launch_app`, `iphone_tap_element`, `iphone_screenshot` and friends.+The agent will use `iphone_launch_app`, `iphone_tap_element`, `iphone_screenshot` and friends. Other clients: [Connect an AI Client](./mcp-clients).++You can also watch and control the phone in a browser, or hand tasks to a local Claude Code or Codex there:++```bash+iphone-control viewer # then open http://127.0.0.1:8200+```## Checking on it```bash-docker exec iphone-control iphone-control status # state, signing time left, recent log-docker exec iphone-control iphone-control doctor # layer-by-layer checks with a fix for each failure+iphone-control status # state, signing time left, recent log+iphone-control doctor # layer-by-layer checks with a fix for each failure```Something wrong? See the [FAQ](../troubleshoot/faq).++## Uninstall++| Installed with | Uninstall |+|---|---|+| One command | `curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh \| sh -s -- --uninstall` |+| Homebrew | `brew services stop iphone-control`, then `brew uninstall iphone-control` |+| .deb | `systemctl --user disable --now iphone-control`, then `sudo apt remove iphone-control` |++The data directory `~/.local/share/iphone-control` (Apple ID session, signing, auto-unlock passcodes) stays; delete it if you no longer need it, and remove WebDriverAgent on the phone.diff --git a/website/en/guide/mcp-clients.md b/website/en/guide/mcp-clients.mdindex 9fba7a9..38ec1ac 100644--- a/website/en/guide/mcp-clients.md+++ b/website/en/guide/mcp-clients.md@@ -1,49 +1,43 @@# Connect an AI Client-The client starts the MCP server on demand: `docker exec -i iphone-control iphone-control mcp` for Docker, `iphone-control --socket <path> mcp` for a source install. When in doubt, run `iphone-control mcp-config` — it prints the right command for your setup.+The client starts the MCP server on demand with `iphone-control --socket <path> mcp`. The last step of the first-run guide registers it with Claude Code and Codex for you; configure other clients by hand as below. When in doubt, run `iphone-control mcp-config` — it prints the right command for this machine.-## Claude Code+## Claude Code and Codex++When the guide finds `claude` or `codex` on `PATH`, it asks whether to register with it. That amounts to:```bash-claude mcp add iphone -s user -- docker exec -i iphone-control iphone-control mcp+claude mcp add iphone -s user -- /path/to/iphone-control --socket <path> mcp+codex mcp add iphone -- /path/to/iphone-control --socket <path> mcp```-`-s user` makes it available in every project. Restarting the container drops the MCP connection; run `/mcp` in Claude Code to reconnect.+Open a new session afterwards and the tools are there. `-s user` makes it available in every Claude Code project. The program path is one that stays the same across upgrades: for Homebrew, the `opt` link, so there is no need to register again after `brew upgrade`.-## Claude Desktop, Cursor and others+If you install Claude Code or Codex later, or want to register again, run `iphone-control setup --reconfigure` and pick MCP registration. You can also run the command that `iphone-control mcp-config` prints.-Add this to the client's MCP configuration:+Restarting the daemon drops the MCP connection; run `/mcp` in Claude Code to reconnect.-```json-{- "mcpServers": {- "iphone": {- "command": "docker",- "args": ["exec", "-i", "iphone-control", "iphone-control", "mcp"]- }- }-}-```+## Claude Desktop, Cursor and others-For a source install, use the command that `mcp-config` prints, for example:+Add this to the client's MCP configuration, with the program path and arguments that `mcp-config` prints, for example:```json{"mcpServers": {"iphone": {- "command": "/home/you/.cargo/bin/iphone-control",+ "command": "/home/you/.local/bin/iphone-control","args": ["--socket", "/run/user/1000/iphone-control/ctl.sock", "mcp"]}}}```-To turn on the [developer tools](./tools#developer-tools-opt-in) or English: when running the binary directly, add `"env": {"IPHONE_CONTROL_DEV_TOOLS": "1", "IPHONE_CONTROL_LANG": "en"}` to the `iphone` entry; with Docker, add `"-e", "IPHONE_CONTROL_DEV_TOOLS=1"` after `"-i"` in `args` (and `"-e", "IPHONE_CONTROL_LANG=en"` for the language).+To turn on the [developer tools](./tools#developer-tools-opt-in) or English, add `"env": {"IPHONE_CONTROL_DEV_TOOLS": "1", "IPHONE_CONTROL_LANG": "en"}` to the `iphone` entry.macOS has no `XDG_RUNTIME_DIR`, so the socket is `~/.local/share/iphone-control/ctl.sock`; again, use what `mcp-config` prints. Claude Desktop's configuration file is `~/Library/Application Support/Claude/claude_desktop_config.json`.::: warning Client and daemon on the same machine-The MCP server reaches the daemon through a local Unix socket. If the client runs on another computer, start it over SSH, e.g. `"command": "ssh", "args": ["host", "docker", "exec", "-i", "iphone-control", "iphone-control", "mcp"]`.+The MCP server reaches the daemon through a local Unix socket. If the client runs on another computer, start it over SSH, followed by the program path and arguments `mcp-config` prints on that host, e.g. `"command": "ssh", "args": ["host", "/home/you/.local/bin/iphone-control", "--socket", "/run/user/1000/iphone-control/ctl.sock", "mcp"]`.:::## Tips for the agentdiff --git a/website/en/guide/multi-device.md b/website/en/guide/multi-device.mdindex 23915e6..c8b2250 100644--- a/website/en/guide/multi-device.md+++ b/website/en/guide/multi-device.md@@ -2,7 +2,7 @@A host can have several iPhones and iPads connected, but it controls one at a time: every tool and command acts on that one. With a single device you can skip this page.-With Docker, prefix the commands below with `docker exec -it iphone-control`. Don't run two copies of iphone-control, or other usbmuxd-based tools, against the same device.+Don't run two copies of iphone-control, or other usbmuxd-based tools, against the same device.## List and switch@@ -16,7 +16,22 @@ Agents use `iphone_list_devices` and `iphone_select_device`, which do the same.- Only devices connected over USB can be selected. It tries the UDID, then the device name, then a part of the name that matches exactly one device. If it matches several, you get an error and need the UDID.- WDA takes 10–60 seconds to start after switching; check with `status` (or `iphone_status`) that it's ready. A device that has never had WDA needs [installing](#install-on-a-new-device) first.-- `iphone-control viewer` belongs to the device controlled when it starts: after switching to another device its actions are refused, so run it again to watch and control the new one.+- The control page, `iphone-control viewer`, can switch too; see [Switching on the control page](#control-page).++## Switching on the control page {#control-page}++The device picker at the top of the `iphone-control viewer` page switches the controlled device.++- **The page follows the daemon.** When the device is switched elsewhere (another tab, `iphone-control select`, the `iphone_select_device` tool, or automatically after an unplug), the page notices within about 10 seconds, says so, and moves its live picture and panels (apps, elements) to the new device.+- **Actions only go to the device the page shows.** Every action the page sends carries that device; if the daemon no longer controls it, the action is refused, never sent to another phone.+- **When the new device isn't ready**, the picture area says why:+ - Not connected: plug it in with a cable that carries data.+ - Not paired or Developer Mode off: run `iphone-control setup --reconfigure` in a terminal and pick Phone.+ - WDA starting: usually 10–60 seconds.+ - Not unlocked since a restart: unlock it by hand once; the first time UI automation is enabled after a restart, enter the passcode on the device.+- **A device without WDA:** with an Apple ID signed in, the picture area has a *Sign and install WDA* button. It takes about 1–2 minutes; keep the phone unlocked. Without an Apple ID, it tells you to run `iphone-control setup --reconfigure` and pick Apple ID.+- Only one device is controlled at a time; you can't watch two phones side by side.+- Switching is refused while an AI task runs, and when `IPHONE_UDID` pins a device.## Which device is controlled@@ -34,15 +49,17 @@ Agents use `iphone_list_devices` and `iphone_select_device`, which do the same.```bashiphone-control select <new device>-iphone-control setup+iphone-control setup --reconfigure # pick Phone: pairing, Developer Mode, signing and installing WDA```-`setup` only acts on the controlled device, so `select` first. It registers the device with your Apple ID, which uses up one of the account's device slots. Automatic re-signing doesn't register a device that has never had WDA; `doctor` tells you to run `setup` in that case.+Setup only acts on the controlled device, so `select` first. Signing registers the device with your Apple ID, which uses up one of the account's device slots. Automatic re-signing doesn't register a device that has never had WDA; `doctor` tells you to run `setup` in that case. You can also switch to the new device on the control page and click *Sign and install WDA* (the device must already be paired, with Developer Mode on).## Re-signingAutomatic re-signing only covers the controlled device. An idle device's profile expires after 7 days. Within a minute of switching back, it is checked and re-signed if it has expired or is about to; you can also run `resign --force`.+Every device is re-signed with the same certificate, so re-signing one doesn't break another. But if an idle device's WDA was signed on another machine (or from an old data directory), that certificate may have been revoked: when WDA won't start after you switch to it, the daemon re-signs it automatically, see the [FAQ](../troubleshoot/faq#cert).+## Auto-unlockPasscodes are kept per device:@@ -64,4 +81,4 @@ Notifications don't name the device. Use `status` or `devices` to see which one- **No HID fallback on iOS 26:** actions fail while WDA restarts, the same as on an iPhone.- **The screen isn't 430×932:** an iPad mini 5 is 768×1024 in portrait. Go by the screenshot and `iphone_status`.-Verified on: iPad mini 5, iOS 26.6.1 (Linux, Docker).+Verified on: iPad mini 5, iOS 26.6.1 (Linux).diff --git a/website/en/guide/notifications.md b/website/en/guide/notifications.mdindex 8ab4047..90f450d 100644--- a/website/en/guide/notifications.md+++ b/website/en/guide/notifications.md@@ -12,16 +12,24 @@ The daemon notifies you when the phone needs attention, through whichever channe| WDA recovered | — || Auto-unlock failed and was disabled | See [Auto-unlock](./auto-unlock) || Phone offline / back online | Check the cable and the host |+| Signing certificate replaced (signing created a new certificate, maybe revoking an old one) | Usually nothing: devices signed with the old certificate are re-signed automatically when their WDA won't start; other machines or sideloading tools using the same Apple ID have to re-sign there, see the [FAQ](../troubleshoot/faq#cert) |How repeats are limited:- Re-signing failed, Apple ID session expired: not repeated for 20 hours; sent again after that if the problem is still there.- Passcode needed, phone offline: sent once until it recovers. Only these two have a recovery notification ("WDA recovered", "back online").- Auto-unlock disabled: sent once; it can only be sent again after `unlock-reset`.+- Signing certificate replaced: sent every time.- This record is kept in memory only. Restarting the daemon clears it, so a problem that isn't solved yet is sent again.Notifications don't name the device; with several connected, use `status` to see which one. See [Several devices](./multi-device).+## Setting up++The easiest way is the guide: the first run of `iphone-control` asks, and later `iphone-control setup --reconfigure` with Notifications. Pick Bark or Telegram and enter the key or token; it sends a test message and restarts the daemon so the settings apply.++You can also put them in the [settings file](./configuration#settings-file), `~/.config/iphone-control/env`, and run `iphone-control service restart`.+## Bark```ini@@ -39,10 +47,10 @@ TG_CHAT_ID=your-chat-id## Test```bash-docker exec iphone-control iphone-control notify-test # one per event type, titled "[测试]"-docker exec iphone-control iphone-control notify-test offline # one type: resign / session / pin / pin-recovered / unlock / offline / online+iphone-control notify-test # one per event type, titled "[test]" (or "[测试]" in Chinese)+iphone-control notify-test offline # one type: resign / session / pin / pin-recovered / unlock / offline / online / cert```-::: info No notification if the container itself dies-Notifications come from the daemon. Watching the container or host needs separate monitoring, which this project doesn't provide.+::: info No notification if the daemon itself dies+Notifications come from the daemon. The background service restarts it after a crash; watching the host itself needs separate monitoring, which this project doesn't provide.:::diff --git a/website/en/guide/security.md b/website/en/guide/security.mdindex 909e080..e25a3b1 100644--- a/website/en/guide/security.md+++ b/website/en/guide/security.md@@ -7,20 +7,19 @@ This page has the essentials. What is stored, who can reach it and the details o## What is stored- **The data directory** holds the Apple ID session, the signing key, pairing records and, with auto-unlock on, the passcode in **plain text**. Keep it and its backups as safe as a password. The Apple ID password is never stored.-- **The control socket** is a Unix socket with mode 0600, and whoever can connect to it controls the phone: root on the host, anyone who can `docker exec` into the container, the same user for a source install.-- **Notification keys** are in `.env` or `~/.config/iphone-control/env`.+- **The control socket** is a Unix socket with mode 0600, and whoever can connect to it controls the phone: root on the host and the user the daemon runs as.+- **Notification keys** are in the settings file `~/.config/iphone-control/env`, mode 0600.## Built-in protections-- **No network ports.** WDA is reached through usbmuxd. `wda-bridge` and the live `viewer` are explicit opt-ins that bind 127.0.0.1 only, and other web pages in your browser can't act through them. They have no login, though: every local user can use them, so stop them when done.-- **Not privileged**: the container only gets USB character devices.+- **No network ports.** WDA is reached through usbmuxd. `wda-bridge` and the live `viewer` are explicit opt-ins that bind 127.0.0.1 only, and other web pages in your browser can't act through them. They have no login, though: every local user can use them, including starting AI tasks from the viewer, so stop them when done.+- **No root.** The daemon runs as your regular user, as a per-user service; the install script refuses to run as root.- **Auto-unlock is off by default** and disables itself after one wrong attempt.- **Developer tools are off by default.**-- Exact dependency versions, base images pinned by digest, and the WebDriverAgent download is sha256-checked.+- Exact dependency versions; the WebDriverAgent download and the install script's download are sha256-checked.## Risks to know about-- **The container runs as root.** It needs the USB device nodes and must restart usbmuxd after re-plugging (there is no udev in the container).- **The anisette server.** Apple ID logins use a public third-party server by default (`mac-ani.jkcoxson.com`). It never gets your password, but it can see when you log in. To avoid it, run your own [anisette-v3-server](https://github.com/Dadoum/anisette-v3-server) and set `ICTL_ANISETTE_URL`.- **Use a dedicated Apple ID.** A separate account contains the damage if the host is compromised.- **The agent acts with your hands.** It can send messages, buy things and change settings. The server tells agents to ask first for these, but that is an instruction, not enforcement.diff --git a/website/en/guide/what-is-iphone-control.md b/website/en/guide/what-is-iphone-control.mdindex e538932..1b55508 100644--- a/website/en/guide/what-is-iphone-control.md+++ b/website/en/guide/what-is-iphone-control.md@@ -24,9 +24,9 @@ It works as a set of [MCP](https://modelcontextprotocol.io) (Model Context Proto| | ||---|---|-| Host | Linux, x86_64 or arm64: Docker (Compose v2), or Rust 1.88+ to build from source<br>macOS, Apple Silicon: prebuilt binary, or Rust 1.88+ to build from source, see [macOS](../deploy/macos) |+| Host | Linux, x86_64 or arm64: one-command install, Homebrew or a .deb (Debian 12+, Ubuntu 22.04+), with the system usbmuxd; or build from source with Rust 1.88+<br>macOS, Apple Silicon: one-command install or Homebrew, or build from source, see [macOS](../deploy/macos)<br>No Windows || Phone | iPhone or iPad, iOS 17 or later; the HID fallback needs iOS 27 or later |-| Verified on | iPhone 15 Pro Max, iOS 27.0.1 (Linux, macOS)<br>iPhone 12 mini, iOS 26.4.1 (Linux)<br>iPad mini 5, iOS 26.6.1 (Linux, Docker) |+| Verified on | iPhone 15 Pro Max, iOS 27.0.1 (Linux, macOS)<br>iPhone 12 mini, iOS 26.4.1 (Linux)<br>iPad mini 5, iOS 26.6.1 (Linux) || Account | A free Apple ID; a dedicated one is recommended |Other models and iOS versions should work but are untested — [reports](https://github.com/Derrors/iphone-control/issues) are welcome.@@ -49,13 +49,11 @@ The CLI, `doctor` output and MCP tool results are in Simplified Chinese by defau- The HID fallback needs iOS 27 or later. On older iOS everything goes through WebDriverAgent, and actions fail while it restarts.- Free Apple ID profiles last 7 days. Re-signing is automatic, but an expired Apple ID session needs `login`.- Apple ID logins use a public third-party anisette server by default; set `ICTL_ANISETTE_URL` to use your own, see [Configuration](./configuration).-- The Docker container runs as root: it needs the USB device nodes and restarts its own usbmuxd after replugging.**macOS**-- Apple Silicon only; Intel Macs are untested.+- Prebuilt binaries are for Apple Silicon only; an Intel Mac needs a build from source and is untested.- The prebuilt binary isn't notarized; a copy downloaded with a browser needs its quarantine flag removed first.-- The daemon runs in a terminal (no launchd configuration yet); no Docker (no USB passthrough).- Set the phone's charging limit to 100%: with the 80% limit, USB drops about once a minute.Other differences from Linux: [macOS known differences](../deploy/macos#known-differences).diff --git a/website/en/index.md b/website/en/index.mdindex add7e2e..6b5d67f 100644--- a/website/en/index.md+++ b/website/en/index.md@@ -40,7 +40,7 @@ features:details: WDA is reached through usbmuxd; nothing listens on the network. Auto-unlock is off by default- icon: 📦title: One binary- details: Written in Rust. One Docker command to deploy on Linux, or run it from source or a prebuilt binary; on a Mac, run the prebuilt binary+ details: Written in Rust. Install with one command, Homebrew or a .deb, then run iphone-control and it walks you through setup; or build from source- icon: 🧭title: Fewer round tripsdetails: Actions can return the resulting screen after waiting for it to settle, and flag loading pages and blocking alertsdiff --git a/website/en/troubleshoot/faq.md b/website/en/troubleshoot/faq.mdindex 2be974e..04e16ed 100644--- a/website/en/troubleshoot/faq.md+++ b/website/en/troubleshoot/faq.md@@ -3,7 +3,7 @@Start with these two commands; they explain most problems:```bash-iphone-control status # with Docker, prefix: docker exec -it iphone-control+iphone-control status # daemon and device state, recent logiphone-control doctor # checks each layer and prints a fix for every failure```@@ -13,9 +13,9 @@ Messages are in Simplified Chinese by default, and in English with `IPHONE_CONTR| `status` shows | Meaning | What to do ||---|---|---|-| 手机未连接<br>Phone not connected | usbmuxd sees no phone | Check the cable and unlock the phone; with a usbmuxd on a Linux host, `sudo systemctl mask usbmuxd`. With several devices, a selected device that isn't connected also shows this: check the `选设备` (`Device`) line of `status`, or run `select auto`; see [Several devices](../guide/multi-device) |-| 未配对<br>Not paired | No pairing record | Run `setup` and tap *Trust* on the phone |-| 开发者模式未打开<br>Developer Mode is off | Developer Mode is off | *Settings → Privacy & Security → Developer Mode*. The toggle only appears after the phone has been seen by a developer tool; running `setup` takes care of that |+| 手机未连接<br>Phone not connected | usbmuxd sees no phone | Check the cable and unlock the phone; on Linux, make sure the system usbmuxd is installed (`sudo apt install usbmuxd`). With several devices, a selected device that isn't connected also shows this: check the `选设备` (`Device`) line of `status`, or run `select auto`; see [Several devices](../guide/multi-device) |+| 未配对<br>Not paired | No pairing record | Run `setup --reconfigure`, pick *Phone*, and tap *Trust* on the phone |+| 开发者模式未打开<br>Developer Mode is off | Developer Mode is off | *Settings → Privacy & Security → Developer Mode*. The toggle only appears after the phone has been seen by a developer tool; running `setup --reconfigure` and picking *Phone* takes care of that || 手机锁屏,隧道建不起来<br>The phone is locked, the tunnel can't be opened | Not unlocked since the last reboot | Unlock it once by hand; the state stays until then and the daemon keeps retrying || WDA 还没签名安装<br>WDA not signed and installed yet | WDA not installed | Run `sign` or `setup` || 正在启动 WDA<br>Starting WDA | Starting WDA (up to about 2 minutes) | Wait. On iOS 27 and later, taps, swipes and screenshots already work through the HID fallback, but a landscape touch needs an orientation from WDA in the last 30 seconds or it is refused, and an unknown screen size returns an error; see [Tools](../guide/tools#when-wda-is-down-the-hid-fallback). On older iOS, wait for WDA |@@ -25,37 +25,47 @@ Messages are in Simplified Chinese by default, and in English with `IPHONE_CONTR## The phone isn't detected-- **Two usbmuxd fighting:** many distributions install usbmuxd and udev starts it on plug-in, taking the phone away from Docker. `sudo systemctl mask usbmuxd`.+- **No usbmuxd on Linux:** the daemon uses the system usbmuxd and doesn't start one itself. `sudo apt install usbmuxd` (the .deb pulls it in). If you ran `sudo systemctl mask usbmuxd` for the Docker deployment, run `sudo systemctl unmask usbmuxd` first.+- **The daemon isn't running:** check with `iphone-control service status` and start it with `iphone-control service start`. Running `iphone-control` also starts the service when it isn't running.- **Another tool holds the phone:** go-ios, pymobiledevice3 and similar tools conflict.- **Cable:** some cables only charge. If `lsusb` shows no Apple device (`05ac`), try another cable or port.-- **After re-plugging:** Docker recovers within about a minute.+- **After re-plugging:** it recovers within about a minute.- **Drops about once a minute while charging:** with *Settings → Battery → Charging → 80% Limit* on, the phone keeps starting and stopping charging near 80%, and each switch renegotiates USB-C power, which drops USB for 3–5 seconds. Set the limit to 100% on a phone used for automation.-- **On a Mac:** Docker can't be used (no USB passthrough); see [macOS](../deploy/macos). usbmuxd is part of macOS; if `doctor` can't reach it, run `sudo launchctl kickstart -k system/com.apple.usbmuxd`.+- **On a Mac:** usbmuxd is part of macOS; if `doctor` can't reach it, run `sudo launchctl kickstart -k system/com.apple.usbmuxd`. See [macOS](../deploy/macos).## WDA won't start- **"Untrusted developer":** after the first install, trust your Apple ID under *Settings → General → VPN & Device Management* (the phone needs internet).+- <a id="cert"></a>**Signing certificate revoked:** `status` says `unexpected response` although the profile is still valid; tapping the WebDriverAgentRunner icon on the device says the app can't be verified.+ - Why: every install (each machine, each data directory) has its own signing key and certificate, and a free Apple ID holds at most two certificates at a time. Signing somewhere new for the first time (another machine, moving from Docker to a native install, a deleted data directory) or with the same Apple ID in a sideloading tool such as AltStore or SideStore creates a certificate; when the team is full an old one is revoked, and apps signed with it won't start on any device.+ - The daemon handles it: when a device refuses to start WDA and its WDA wasn't signed with this machine's certificate, or this machine's certificate is no longer in the Apple ID's team, it re-signs that device automatically (at most once per device every 6 hours) and sends a notification. `doctor` shows both checks.+ - By hand: `iphone-control sign` re-signs the controlled device; the control page also offers "Re-sign and install WDA" when WDA fails to start.+ - Don't sign with the same Apple ID in two places at once: stop old deployments you no longer use, or give them different Apple IDs.- **Expired signature:** free signatures last 7 days and are renewed automatically. `status` shows the time left; `resign --force` re-signs now.-- **Apple ID session expired:** you get a notification; run `login` again.-- **Developer Disk Image fails:** the first line of `status` says `WDA 启动失败,稍后重试:开发者镜像:…`, with details in `logs/daemon.log`; `doctor` has no separate check for it. Downloading needs GitHub; set `HTTP_PROXY` / `HTTPS_PROXY`, or point `ICTL_DDI_DIR` at a directory extracted from Xcode; see [Configuration](../guide/configuration#advanced).+- **Apple ID session expired:** you get a notification. Run `iphone-control setup --reconfigure` and pick *Apple ID* to sign in again and re-sign WDA.+- **Developer Disk Image fails:** the first line of `status` says `WDA 启动失败,稍后重试:开发者镜像:…`, with details in `logs/daemon.log`; `doctor` has no separate check for it. Downloading needs GitHub; set a proxy (`iphone-control setup --reconfigure`, pick *Proxy*), or point `ICTL_DDI_DIR` at a directory extracted from Xcode; see [Configuration](../guide/configuration#advanced).## Login-- **Can't type the code:** `login` and `setup` are interactive; use `-it` with Docker.+- **Can't type the code:** `login`, `setup` and the first run of `iphone-control` are interactive; run them in a terminal, not from a script or a pipe.- **Anisette errors:** the default public anisette server may be down; retry later or run your own and set `ICTL_ANISETTE_URL`.## AI clients-- **MCP disconnected:** restarting the container ends the MCP process; reconnect in the client (`/mcp` in Claude Code).+- **The MCP tools are missing:** run `iphone-control setup --reconfigure` and pick *MCP registration*, or run `iphone-control mcp-config` to print the registration command, then start a new session.- **"守护进程正忙…已放弃执行":** an action queued for over 30 seconds and was dropped rather than tapping a screen that changed. Take a screenshot and retry.- **An action reports that the WDA connection dropped:** the request was already sent, so it may have happened. It isn't redone, to avoid tapping or typing twice. Take a screenshot first.- **Taps do nothing:** a system alert may be covering the screen; the result says so (「屏幕上有系统弹窗…」). Dismiss it first.- **Typed text is incomplete:** `iphone_type_text` reads the field back and fixes it; if it still reports a mismatch, the app rewrites the field while typing — type shorter pieces.+## No picture on the control page after switching devices++The picture area says why: not connected; pairing or Developer Mode still needed (run `iphone-control setup --reconfigure` and pick *Phone*); WDA starting (usually 10–60 seconds); or it needs unlocking. When the new device has no WDA yet and an Apple ID is signed in, click *Sign and install WDA*; it takes about 1–2 minutes, keep the phone unlocked. Without an Apple ID, run `iphone-control setup --reconfigure` and pick *Apple ID*. Switching is refused while an AI task runs, and when `IPHONE_UDID` is set. See [Several devices](../guide/multi-device).+## "Paired computer" icon stays and the phone won't auto-lock-The HID fallback opens a screen-mirroring session while in use and closes it after 30 seconds idle. If the icon doesn't go away, restart the daemon.+The HID fallback opens a screen-mirroring session while in use and closes it after 30 seconds idle. If the icon doesn't go away, restart the daemon (`iphone-control service restart`).## Reporting a problem-[Open an issue](https://github.com/Derrors/iphone-control/issues/new/choose) with the phone model, iOS version, how you run it, and the `doctor` output — with UDID, Apple ID and notification keys removed.+[Open an issue](https://github.com/Derrors/iphone-control/issues/new/choose) with the phone model, iOS version, how you installed it (one command, Homebrew, .deb or source), and the `doctor` output — with UDID, Apple ID and notification keys removed.diff --git a/website/guide/auto-unlock.md b/website/guide/auto-unlock.mdindex 4a02c2c..f8d43f8 100644--- a/website/guide/auto-unlock.md+++ b/website/guide/auto-unlock.md@@ -8,15 +8,17 @@## 开启+首次运行 `iphone-control` 的引导里会问要不要设(可选),以后可以运行 `iphone-control setup --reconfigure` 选「自动解锁密码」。也可以直接用命令:+```bash-docker exec -it iphone-control iphone-control passcode set+iphone-control passcode set```密码存给守护进程正在控制的那台设备;要给别的设备设,加 `--device <UDID 或设备名>`。只支持 4 位以上的纯数字密码。关闭:```bash-docker exec -it iphone-control iphone-control passcode clear # 正在控制的那台;别的设备加 --device-docker exec -it iphone-control iphone-control passcode clear --all # 所有设备+iphone-control passcode clear # 正在控制的那台;别的设备加 --device+iphone-control passcode clear --all # 所有设备```## 多台设备@@ -39,8 +41,8 @@ docker exec -it iphone-control iphone-control passcode clear --all # 所有先人工解锁手机。如果是密码错了(例如你改了锁屏密码),先更新密码,再恢复:```bash-docker exec -it iphone-control iphone-control passcode set-docker exec -it iphone-control iphone-control unlock-reset+iphone-control passcode set+iphone-control unlock-reset```如果是输入中途出错、进程被杀,密码本身可能没错,确认无误后只运行 `unlock-reset` 就行。`unlock-reset` 不会核对密码,`passcode set`、`passcode clear` 也不会解除停用。不要靠删除 `logs/` 来恢复,那会撤掉这层保护。diff --git a/website/guide/cli.md b/website/guide/cli.mdindex 1766445..8d5f825 100644--- a/website/guide/cli.md+++ b/website/guide/cli.md@@ -1,6 +1,8 @@# 命令行-所有命令都是 `iphone-control <命令>`。Docker 部署时前面加 `docker exec -it iphone-control`;从源码运行和在 macOS 上直接运行。`--help` 看帮助,`--version` 看版本。+所有命令都是 `iphone-control <命令>`。`--help` 看帮助,`--version` 看版本。++不带命令只运行 `iphone-control`:第一次是[首次运行引导](./getting-started#first-run),设置好以后显示状态(守护进程没在运行时先启动它)。## 全局选项@@ -15,15 +17,30 @@| 命令 | 作用 ||---|---|-| `daemon` | 常驻守护进程。容器的入口;从源码运行时由 systemd 或手动启动,macOS 上在终端里运行 |+| `daemon` | 常驻守护进程。一般由后台服务启动,也可以在终端里手动运行 || `mcp` | MCP stdio 服务,由 AI 客户端拉起 |-| `mcp-config [--container <容器名>]` | 打印把 MCP 注册到 Claude Code 的命令。在容器里或给了 `--container` 时打印 `docker exec` 的写法,否则直接调用本程序 |+| `mcp-config` | 打印把 MCP 注册到 Claude Code 的命令。程序路径用升级后不变的那个(Homebrew 用 `opt` 下的链接) |++## 后台服务++守护进程装成用户服务:macOS 是 launchd,Linux 是 systemd 用户服务。登录后自动启动,崩溃后自动重启。不用 root。++| 命令 | 作用 |+|---|---|+| `service install` | 装成后台服务并启动;已经有服务时直接启动 |+| `service uninstall` | 停止并移除本程序装的服务,数据保留。Homebrew 或 deb 包带的服务不删,只停用或提示怎么停 |+| `service start` / `stop` | 启动、停止 |+| `service restart` | 重启,改过 `~/.config/iphone-control/env` 后用 |+| `service status` | 装的是哪个服务、守护进程在不在运行 |++这些命令认得一行命令安装、`iphone-control service install`、`brew services` 和 deb 包装的服务,哪个在就作用于哪个。-## 安装与签名+## 设置与签名 {#setup}| 命令 | 作用 ||---|---|-| `setup` | 安装向导:配对、开发者模式、登录 Apple ID、签名安装 WDA。可重复运行,只作用于正在控制的那台 |+| `setup` | 把引导完整走一遍:语言、代理、后台服务、配对、开发者模式、Apple ID、签名安装 WDA、自动解锁、通知、注册 MCP。做过的步骤跳过。手机部分只作用于正在控制的那台 |+| `setup --reconfigure` | 重新设置其中一项,从菜单里选:全部重新走一遍、语言、代理、后台服务、Apple ID(重新登录并重签 WDA)、手机(配对、开发者模式、安装 WDA)、自动解锁密码、通知、注册 MCP(Claude Code、Codex) || `login [邮箱]` | 登录 Apple ID。密码和验证码只在这里输入;不给邮箱就交互输入 || `sign` | 立即签名并安装 WDA,同 `resign --force`。会把设备注册到 Apple ID || `resign [--force]` | 描述文件剩余不到 `RESIGN_MIN_DAYS` 天才重签;`--force` 立即重签。不带 `--force` 时不会替没装过 WDA 的设备注册 |@@ -61,12 +78,12 @@|---|---|| `notify-test [事件]` | 发测试通知:每类事件各一条,或只发一类(`resign`、`session`、`pin`、`pin-recovered`、`unlock`、`offline`、`online`) || `wda-bridge [--port <端口>]` | 把 WDA 桥接到 `127.0.0.1`,端口默认 8100,给别的工具用。WDA 没有认证,本机任何用户都能连上,用完就停 |-| `viewer [--port <端口>]` | 在浏览器里看实时画面,地址 `http://127.0.0.1:8200/`(默认端口):点一下是点击,拖动是滑动,按住是长按,另有输入框和硬件键。点击、输入和 MCP 调用一样经守护进程,和 agent 的操作排队,并先自动解锁。绑定启动时正在控制的设备:切换到别的设备后操作会被拒绝,要重新运行。画面来自 WDA 的 MJPEG 流,WDA 没就绪时没有画面。本机任何用户都能连上这个端口,用完就停 |+| `viewer [--port <端口>]` | 浏览器里的控制台,地址 `http://127.0.0.1:8200/`(默认端口),中英文(默认跟着 `IPHONE_CONTROL_LANG`,页面上可切换)。**画面:** 实时画面像触摸屏一样用:点一下是点击,拖动是滑动,按住是长按,滚动鼠标滚轮或触控板也能滚动页面,另有输入框和硬件键。iOS 27 起手指跟着鼠标实时移动(经 CoreDevice HID,最后一次触摸后 30 秒内手机保持亮屏);更低的版本在松开后发整段手势。操作都和 MCP 调用一样经守护进程,和 agent 的操作排队,并先自动解锁。画面来自 WDA 的 MJPEG 流,WDA 没就绪时没有画面。**设备面板:** 状态和就绪检查、已安装的 App、屏幕上的元素。页面跟着守护进程控制的设备走,在页面上或别处切换设备,画面和面板都会跟过去,见[多台设备](./multi-device#control-page)。**AI 任务:** 写下任务,交给本机的 agent 执行(PATH 里有的 Claude Code 或 Codex,在页面上选)。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。本机任何用户都能连上这个端口,用完就停 |调试用的 `debug` 子命令默认不编译,见[贡献指南](https://github.com/Derrors/iphone-control/blob/main/CONTRIBUTING.md#testing-on-a-real-phone)。## 使用说明-- **要守护进程在运行的:** `setup`、`status`、`doctor`、`sign`、`resign`、`devices`、`select`、`unlock-reset`、`wda-bridge`、`viewer`,以及 MCP 工具调用。-- **要在终端里交互运行的:** `setup`、`login`、`passcode set`,Docker 部署要带 `-it`。-- **环境变量:** 命令行读的是当前 shell 的环境。从源码运行和在 macOS 上,`~/.config/iphone-control/env` 只有守护进程会加载;用 `login`、`setup`(如果配了 `ICTL_ANISETTE_URL`)、`notify-test`、`mcp-config` 前先运行 `set -a; . ~/.config/iphone-control/env; set +a`。+- **要守护进程在运行的:** `setup` 的手机部分、`status`、`doctor`、`sign`、`resign`、`devices`、`select`、`unlock-reset`、`wda-bridge`、`viewer`,以及 MCP 工具调用。+- **要在终端里交互运行的:** 不带命令的 `iphone-control`(首次运行时)、`setup`、`login`、`passcode set`。+- **设置:** 每个命令启动时都会读 `~/.config/iphone-control/env`,环境里已经有的变量优先,见[配置](./configuration#settings-file)。diff --git a/website/guide/configuration.md b/website/guide/configuration.mdindex 04f6fee..05c2b05 100644--- a/website/guide/configuration.md+++ b/website/guide/configuration.md@@ -1,30 +1,36 @@# 配置-全部通过环境变量配置,都可以不填:+全部通过环境变量配置,都可以不填。-- **Docker**:写在仓库目录的 `.env`(从 `.env.example` 复制),改完 `docker compose up -d` 重建容器。-- **只写 compose 文件**:写在 `compose.yaml` 的 `environment:` 里(或同目录的 `.env` 加 `env_file`),改完同样 `docker compose up -d`。-- **从源码运行**:写在 `~/.config/iphone-control/env`(systemd 用户服务会读),改完 `systemctl --user restart iphone-control`。-- **macOS**:同样写在 `~/.config/iphone-control/env`,启动守护进程前加载,改完重启守护进程,见 [macOS](../deploy/macos#配置)。+## 设置文件 {#settings-file}++设置写在 `~/.config/iphone-control/env`,一行一个 `KEY=value`,权限 0600(里面有通知密钥,不要提交、不要分享)。首次运行 `iphone-control` 的引导和 `iphone-control setup --reconfigure` 会替你写好;也可以照模板手改。模板是仓库的 `packaging/env.example`,安装时也放了一份:++- 一行命令安装:`~/.config/iphone-control/env.example`+- Homebrew:`$(brew --prefix)/opt/iphone-control/share/iphone-control/env.example`+- deb 包:`/usr/share/doc/iphone-control/env.example`++守护进程启动时读这个文件,其他命令(`login`、`notify-test`、`mcp-config`,以及 AI 客户端拉起的 `mcp`)启动时也读,不用先在 shell 里加载。环境里已经有的变量优先,所以命令行上临时设的值会盖过文件里的。++手改后重启守护进程才生效:++```bash+iphone-control service restart+```## 常用| 变量 | 默认 | 含义 ||---|---|---|| `HTTP_PROXY` / `HTTPS_PROXY` | 直连 | 访问苹果、anisette、开发者镜像、推送通知用的代理 |-| `IPHONE_CONTROL_LANG` | `zh` | 界面语言:`zh` 或 `en`。工具说明和结果、命令行输出、日志、通知都按它。MCP 和命令行各自按自己的设置请求,守护进程按请求的语言回答;日志和通知按守护进程自己的设置。从源码运行时见表下说明 |-| `IPHONE_CONTROL_DEV_TOOLS` | 关 | 设为 `1` 时 MCP 服务多出[开发者工具](./tools#开发者工具-显式开启):日志、崩溃报告、安装和卸载 App、Web Inspector(在网页和 WebView 里执行 JavaScript)。风险见[安全与隐私](./security)。从源码运行时见表下说明 |+| `IPHONE_CONTROL_LANG` | `zh` | 界面语言:`zh` 或 `en`。工具说明和结果、命令行输出、日志、通知都按它。MCP 和命令行各自按自己的设置请求,守护进程按请求的语言回答;日志和通知按守护进程自己的设置。见表下说明 |+| `IPHONE_CONTROL_DEV_TOOLS` | 关 | 设为 `1` 时 MCP 服务多出[开发者工具](./tools#开发者工具-显式开启):日志、崩溃报告、安装和卸载 App、Web Inspector(在网页和 WebView 里执行 JavaScript)。风险见[安全与隐私](./security)。见表下说明 || `IPHONE_UDID` | 自动选 | 固定控制哪台设备。不设时自动选:正在控制的那台一直用到它断开;运行中可以用 `select` 命令或 `iphone_select_device` 工具切换。设了就不能切换 || `RESIGN_MIN_DAYS` | `2` | 描述文件剩余不到几天时重签 || `RESIGN_CHECK_HOURS` | `6` | 每隔几小时检查一次;手机重新连上或切换设备后 1 分钟内也查一次 || `OFFLINE_ALERT_MIN` | `10` | 手机离线超过几分钟推送提醒,`0` 不提醒 |-从源码运行和在 macOS 上,`~/.config/iphone-control/env` 只有守护进程会加载,MCP 服务由 AI 客户端拉起,读不到这个文件,所以 `IPHONE_CONTROL_LANG` 和 `IPHONE_CONTROL_DEV_TOOLS` 要写进 MCP 的配置。`iphone-control mcp-config` 读的是当前 shell 的环境变量,先加载再运行,打印的注册命令才会带上它们:--```bash-set -a; . ~/.config/iphone-control/env; set +a-iphone-control mcp-config-```+MCP 服务由 AI 客户端拉起,注册时写进去的环境变量优先于设置文件。引导和 `iphone-control mcp-config` 会把当时的 `IPHONE_CONTROL_LANG=en`、`IPHONE_CONTROL_DEV_TOOLS=1` 写进注册命令,所以改了这两项以后要重新注册:运行 `iphone-control setup --reconfigure` 选「注册 MCP」,再开一个新的会话。用 JSON 配置的客户端见[接入 AI 客户端](./mcp-clients#claude-desktop、cursor-等)。@@ -37,28 +43,16 @@ iphone-control mcp-config| `ICTL_ANISETTE_URL` | 自建 anisette 服务地址(默认用公共的第三方服务,见[安全与隐私](./security)) || `ICTL_DDI_URL` | 开发者镜像的下载地址,默认社区维护的镜像仓库 || `ICTL_DDI_DIR` | 自己从 Xcode 提取的开发者镜像目录。设了就不下载,也不会删里面的文件;缺文件时报错说明缺哪个。不设时用数据目录下的 `ddi/` 缓存,连续 3 次挂载失败后清掉重新下载 |-| `ICTL_MANAGE_USBMUXD` | 守护进程是否自己拉起 usbmuxd。默认:以 root 运行(容器)时拉起,普通用户不拉起,用系统的。`0` 或 `false` 不拉起,例如以 root 运行、宿主机又已有 usbmuxd 服务时 |-| `ICTL_USBMUXD_BIN` | 守护进程自己拉起 usbmuxd 时用的可执行文件,默认 `usbmuxd` |-| `ICTL_WDA_UNSIGNED` | 未签名 WDA 的路径。默认:镜像里的 `/usr/share/iphone-control/WDA-unsigned.ipa`;没有镜像(从源码运行)时是数据目录的 `wda/WDA-unsigned.ipa`,第一次签名前下载。自己指定的路径不会下载 |+| `ICTL_WDA_UNSIGNED` | 未签名 WDA 的路径。默认是数据目录的 `wda/WDA-unsigned.ipa`,第一次签名前下载。自己指定的路径不会下载 || `SCREEN_W` / `SCREEN_H` | HID 后备路线换算坐标用的屏幕尺寸(点):WDA 不可用、又没有这台设备的尺寸记录时才用,比如 WDA 从没连上过,或切到记录里没有尺寸的设备。不分设备,接多台时要小心 || `ICTL_LOG` | 日志级别,例如 `info,ictl_wda::http=debug` 记录每个 WDA 请求的耗时 |## 目录和控制接口-一般不用改,Docker 部署不要改(容器里 `ICTL_DATA_DIR` 已经固定,数据卷挂在那里)。要改时不能写成空值,守护进程、命令行和 MCP 要用同样的值:除了容器,只有守护进程会读配置文件,见[从源码 / 二进制](../deploy/source#运行)。+一般不用改。要改时写进[设置文件](#settings-file),不能写成空值:守护进程、命令行和 MCP 都要用同样的值。MCP 的注册命令里带着 `--socket`,改了 `ICTL_SOCKET` 要重新注册(`setup --reconfigure` 选「注册 MCP」)。| 变量 | 默认 | 含义 ||---|---|---|| `ICTL_DATA_DIR` | root:`/var/lib/iphone-control`<br>普通用户:`$XDG_DATA_HOME/iphone-control`,没设时 `~/.local/share/iphone-control` | 数据目录,同命令行的 `--data-dir` || `ICTL_SOCKET` | root:`/run/iphone-control/ctl.sock`<br>普通用户:`$XDG_RUNTIME_DIR/iphone-control/ctl.sock`,没有这个变量时(macOS)放在数据目录里 | 守护进程的控制接口,同命令行的 `--socket` || `XDG_DATA_HOME` / `XDG_RUNTIME_DIR` | 系统设置 | 不是本项目的变量,只影响普通用户时上面两项的默认位置 |--## 只给 Docker Compose 用的--用仓库自带的 `compose.yaml` 时才有这几项;自己写 compose 文件时直接改对应的 `container_name`、`image`、`volumes`。--| 变量 | 默认 | 含义 |-|---|---|---|-| `CONTAINER_NAME` | `iphone-control` | 容器名 |-| `IMAGE` | `iphone-control:local` | 镜像名;用预构建镜像时改成 `ghcr.io/derrors/iphone-control:<版本>` |-| `DATA_DIR` | `./data` | 数据目录,见[数据与备份](../deploy/backup) |diff --git a/website/guide/getting-started.md b/website/guide/getting-started.mdindex 50d80f1..defdcd7 100644--- a/website/guide/getting-started.md+++ b/website/guide/getting-started.md@@ -1,80 +1,114 @@# 快速开始-在 Linux 上用 Docker 部署,大约 15 分钟。不用 Docker 见[从源码 / 二进制](../deploy/source);用 Mac 的话见 [macOS](../deploy/macos),安装向导和接入客户端的步骤与这里相同。+装好程序、接上手机、运行 `iphone-control`,跟着引导走完,大约 15 分钟。Linux 和 Mac 的步骤相同,Mac 的细节见 [macOS](../deploy/macos)。## 准备-- 一台 Linux 主机,装好 Docker(含 Compose v2)+- 一台主机:Mac(Apple 芯片),或 Linux(x86_64、aarch64)- iPhone 或 iPad(iOS 17+)和能传数据的线- 一个免费 Apple ID(建议专门注册一个)-- 主机能访问苹果服务器和 GitHub;国内网络一般要配代理+- 主机能访问苹果服务器和 GitHub;国内网络一般要配代理(引导里会问)::: warning 一部手机只接一份-不要同时运行两份 iphone-control,或其他基于 usbmuxd 的工具(go-ios、pymobiledevice3 等)连同一部手机。Linux 宿主机装了 usbmuxd 的,先 `sudo systemctl mask usbmuxd`。+不要同时运行两份 iphone-control,或其他基于 usbmuxd 的工具(go-ios、pymobiledevice3 等)连同一部手机。:::-## 1. 启动+## 1. 安装 {#install}++三种方式任选一种,都以普通用户安装,不要用 root 或 sudo 运行 `iphone-control`。++**一行命令**(macOS、Linux):```bash-git clone https://github.com/Derrors/iphone-control && cd iphone-control-cp .env.example .env # 需要代理的话在这里填 HTTP_PROXY / HTTPS_PROXY-docker compose up -d --build+curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh```-首次构建要编译 Rust,需要几分钟。也可以直接用预构建镜像,见 [Docker 部署](../deploy/docker)。+程序装到 `~/.local/bin`,守护进程装成用户服务(macOS 是 launchd,Linux 是 systemd 用户服务),登录后自动启动。再运行一次就是升级。可以在 `sh` 后面加 `-s --` 再跟选项:`--version vX.Y.Z` 装指定版本,`--prefix DIR` 装到 `DIR/bin`,`--no-service` 只装程序、不装服务。-## 2. 运行安装向导--用数据线接上手机并解锁,然后:+**Homebrew**(macOS、Linux):```bash-docker exec -it iphone-control iphone-control setup+brew install derrors/tap/iphone-control+brew services start iphone-control```-向导分 6 步,每一步需要你在手机上做的事:+**Debian / Ubuntu 的 deb 包**:从 [GitHub Release](https://github.com/Derrors/iphone-control/releases) 下载 `iphone-control_<版本>_amd64.deb`(ARM 机器用 `_arm64.deb`),然后:-| 步骤 | 手机上要做的 |-|---|---|-| 1. 连接 | 解锁手机 |-| 2. 配对 | 弹出「要信任此电脑吗?」时点「信任」,输入锁屏密码 |-| 3. 开发者模式 | 设置 → 隐私与安全性 → 开发者模式 → 打开 → 重新启动;重启解锁后在弹窗里点「打开」 |-| 4. 登录 Apple ID | (在终端里)输入 Apple ID、密码和双重认证验证码 |-| 5. 签名安装 WDA | 保持手机解锁 |-| 6. 启动 WDA | 设置 → 通用 → VPN 与设备管理 → 信任你的 Apple ID;如果弹出「为 XCTest 输入 iPhone 密码」,输入锁屏密码 |+```bash+sudo apt install ./iphone-control_<版本>_amd64.deb+systemctl --user enable --now iphone-control # 以普通用户运行,每个用户各自开启+```-向导可以重复运行:已经完成的配对、开发者模式、登录会跳过,签名会重新做一遍。看到「WDA 就绪」就好了。+不开启也行,下面的引导会替你启动。-::: tip 密码只在这里输入-Apple ID 密码和验证码只在这个终端里输入,不会保存到磁盘;保存的只是登录后的会话。+::: tip Linux 要装系统的 usbmuxd+和手机通过 USB 通信要用系统的 usbmuxd:`sudo apt install usbmuxd`(其他发行版用对应的包管理器)。deb 包会自动装上它。:::-## 3. 接入 AI 客户端+Intel Mac 没有预编译版本,要从源码编译;参与开发也从源码运行。见[从源码编译](../deploy/source)。-```bash-docker exec -it iphone-control iphone-control mcp-config-```+## 2. 接上手机,运行 iphone-control {#first-run}-它会打印注册命令,Claude Code 直接执行即可:+用数据线接上手机并解锁,然后在终端里运行:```bash-claude mcp add iphone -s user -- docker exec -i iphone-control iphone-control mcp+iphone-control```-其他客户端见[接入 AI 客户端](./mcp-clients)。+第一次运行时,它会在终端里一步步带你完成设置。已经做好的步骤会跳过;中途退出了,再运行 `iphone-control` 会接着做。它要在终端里交互运行。-## 4. 试一下+| 步骤 | 你要做的 |+|---|---|+| 语言 | 选中文或 English |+| 代理 | 需要的话填代理地址,例如 `http://127.0.0.1:7890` |+| 后台服务 | 还没装服务时,回车装成后台服务并启动 |+| 等待手机连接 | 解锁手机 |+| 配对 | 手机上弹出「要信任此电脑吗?」时点「信任」,输入锁屏密码 |+| 开发者模式 | 手机上:设置 → 隐私与安全性 → 开发者模式 → 打开 → 重新启动;重启解锁后在弹窗里点「打开」 |+| 登录 Apple ID | 在终端里输入 Apple ID、密码和双重认证验证码 |+| 签名安装 WDA | 保持手机解锁 |+| 等待 WDA 启动 | 手机上:设置 → 通用 → VPN 与设备管理 → 信任你的 Apple ID(要联网);如果弹出「为 XCTest 输入 iPhone 密码」,输入锁屏密码 |+| 自动解锁(可选) | 要的话输入锁屏密码,见[自动解锁](./auto-unlock) |+| 通知(可选) | 选 Bark 或 Telegram,填 key 或 token,会发一条测试通知,见[通知](./notifications) |+| 注册 MCP | 找到 Claude Code 或 Codex 时,回车注册到它 |++看到「完成」就好了。设置保存在 `~/.config/iphone-control/env`,见[配置](./configuration#settings-file)。-在 Claude Code 里说:+::: tip 密码只在这里输入+Apple ID 密码和验证码只在这个终端里输入,不会保存到磁盘;保存的只是登录后的会话。+:::++以后再运行 `iphone-control` 只显示状态;守护进程没在运行时会先启动它。要改设置,运行 `iphone-control setup --reconfigure`,选要重新设置的那一项,见[命令行](./cli#setup)。++## 3. 试一下++开一个新的 Claude Code 或 Codex 会话,说:> 用 iPhone 打开设置,看看 iOS 版本是多少。-agent 会调用 `iphone_launch_app`、`iphone_tap_element`、`iphone_screenshot` 等工具完成。+agent 会调用 `iphone_launch_app`、`iphone_tap_element`、`iphone_screenshot` 等工具完成。其他客户端见[接入 AI 客户端](./mcp-clients)。++也可以在浏览器里看画面、直接操作手机,或把任务交给本机的 Claude Code、Codex 执行:++```bash+iphone-control viewer # 打开 http://127.0.0.1:8200+```## 检查状态```bash-docker exec iphone-control iphone-control status # 当前状态、描述文件还剩多久、最近日志-docker exec iphone-control iphone-control doctor # 逐层诊断,每项失败都给出修复办法+iphone-control status # 当前状态、描述文件还剩多久、最近日志+iphone-control doctor # 逐层诊断,每项失败都给出修复办法```遇到问题看[常见问题](../troubleshoot/faq)。++## 卸载++| 安装方式 | 卸载 |+|---|---|+| 一行命令 | `curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh \| sh -s -- --uninstall` |+| Homebrew | `brew services stop iphone-control`,再 `brew uninstall iphone-control` |+| deb 包 | `systemctl --user disable --now iphone-control`,再 `sudo apt remove iphone-control` |++数据目录 `~/.local/share/iphone-control`(Apple ID 会话、签名、自动解锁密码)会留着,不需要的话自己删除;手机上的 WebDriverAgent 在手机上删除。diff --git a/website/guide/mcp-clients.md b/website/guide/mcp-clients.mdindex 64b5de6..ee8a47d 100644--- a/website/guide/mcp-clients.md+++ b/website/guide/mcp-clients.md@@ -1,49 +1,43 @@# 接入 AI 客户端-MCP 服务由客户端按需拉起:Docker 部署时是 `docker exec -i iphone-control iphone-control mcp`,从源码运行时是 `iphone-control --socket <路径> mcp`。不确定时运行 `iphone-control mcp-config`,它会按你的部署方式打印正确的命令。+MCP 服务由客户端按需拉起,命令是 `iphone-control --socket <路径> mcp`。首次运行引导的最后一步会替你注册到 Claude Code 和 Codex;其他客户端照下面手动配置。不确定时运行 `iphone-control mcp-config`,它会打印这台机器上正确的命令。-## Claude Code+## Claude Code 和 Codex++引导找到 PATH 里的 `claude` 或 `codex` 时,会问要不要注册,相当于运行:```bash-claude mcp add iphone -s user -- docker exec -i iphone-control iphone-control mcp+claude mcp add iphone -s user -- /path/to/iphone-control --socket <路径> mcp+codex mcp add iphone -- /path/to/iphone-control --socket <路径> mcp```-`-s user` 让所有项目都能用。容器重启后 MCP 连接会断开,在 Claude Code 里运行 `/mcp` 重新连接。+注册完开一个新的会话就能用。`-s user` 让 Claude Code 的所有项目都能用。程序路径用的是升级后不变的那个:Homebrew 装的用 `opt` 下的链接,`brew upgrade` 后不用重新注册。-## Claude Desktop、Cursor 等+后来才装 Claude Code 或 Codex、或者要重新注册时,运行 `iphone-control setup --reconfigure`,选「注册 MCP」。也可以手动执行 `iphone-control mcp-config` 打印的命令。-在客户端的 MCP 配置文件里加上:+守护进程重启后 MCP 连接会断开,在 Claude Code 里运行 `/mcp` 重新连接。-```json-{- "mcpServers": {- "iphone": {- "command": "docker",- "args": ["exec", "-i", "iphone-control", "iphone-control", "mcp"]- }- }-}-```+## Claude Desktop、Cursor 等-从源码运行时把 `command`、`args` 换成 `mcp-config` 打印的命令,例如:+在客户端的 MCP 配置文件里加上,`command`、`args` 换成 `mcp-config` 打印的程序路径和参数,例如:```json{"mcpServers": {"iphone": {- "command": "/home/you/.cargo/bin/iphone-control",+ "command": "/home/you/.local/bin/iphone-control","args": ["--socket", "/run/user/1000/iphone-control/ctl.sock", "mcp"]}}}```-要开启[开发者工具](./tools#开发者工具-显式开启)或英文界面:直接运行时在 `iphone` 这一项里加 `"env": {"IPHONE_CONTROL_DEV_TOOLS": "1", "IPHONE_CONTROL_LANG": "en"}`;Docker 部署时在 `args` 的 `"-i"` 后面加 `"-e", "IPHONE_CONTROL_DEV_TOOLS=1"`(语言同样是 `"-e", "IPHONE_CONTROL_LANG=en"`)。+要开启[开发者工具](./tools#开发者工具-显式开启)或英文界面,在 `iphone` 这一项里加 `"env": {"IPHONE_CONTROL_DEV_TOOLS": "1", "IPHONE_CONTROL_LANG": "en"}`。macOS 上没有 `XDG_RUNTIME_DIR`,socket 在 `~/.local/share/iphone-control/ctl.sock`,同样以 `mcp-config` 打印的为准。Claude Desktop 的配置文件在 `~/Library/Application Support/Claude/claude_desktop_config.json`。::: warning 客户端和守护进程要在同一台机器上-MCP 服务经本机的 Unix socket 找守护进程。客户端在另一台电脑上时,用 SSH 拉起,例如 `"command": "ssh", "args": ["主机", "docker", "exec", "-i", "iphone-control", "iphone-control", "mcp"]`。+MCP 服务经本机的 Unix socket 找守护进程。客户端在另一台电脑上时,用 SSH 拉起,后面跟那台主机上 `mcp-config` 打印的程序路径和参数,例如 `"command": "ssh", "args": ["主机", "/home/you/.local/bin/iphone-control", "--socket", "/run/user/1000/iphone-control/ctl.sock", "mcp"]`。:::## 给 agent 的建议diff --git a/website/guide/multi-device.md b/website/guide/multi-device.mdindex 0533757..1e2d0d8 100644--- a/website/guide/multi-device.md+++ b/website/guide/multi-device.md@@ -2,7 +2,7 @@一台主机可以接多台 iPhone/iPad,但同一时间只控制一台:所有工具和命令都作用在它上面。只接一台时不用管这一页。-下面的命令在 Docker 部署时前面加 `docker exec -it iphone-control`。不要让两份 iphone-control 或其他基于 usbmuxd 的工具连同一台设备。+不要让两份 iphone-control 或其他基于 usbmuxd 的工具连同一台设备。## 查看和切换@@ -16,7 +16,22 @@ agent 用 `iphone_list_devices` 和 `iphone_select_device`,效果一样。- 只能选 USB 上接着的设备。先比 UDID,再比设备名;设备名包含这段文字且只有一台时也行,对上多台就报错,要用 UDID 指定。- 切换后 WDA 要 10~60 秒才起来,先用 `status`(或 `iphone_status`)确认就绪。没装过 WDA 的设备要先[安装](#给新设备安装)。-- `iphone-control viewer` 绑定启动时正在控制的设备:切换到别的设备后,它的操作会被拒绝,要重新运行才能看和操作新设备。+- 浏览器控制台 `iphone-control viewer` 也能切换,见[在控制台里切换](#control-page)。++## 在控制台里切换 {#control-page}++`iphone-control viewer` 页面上方的设备选择框用来切换控制哪台设备。++- **页面跟着守护进程走。** 在别处换了设备(另一个标签页、`iphone-control select`、`iphone_select_device` 工具,或拔掉后自动换了一台),页面 10 秒内会发现,提示一句,并把实时画面和面板(App、元素)换到新设备上。+- **操作只发给页面显示的那台。** 页面发出的每个操作都带着它显示的设备;守护进程已经不控制那台时,操作会被拒绝,不会发到另一部手机上。+- **新设备没就绪时**,画面区域会说明原因:+ - 没有连上设备:用数据线连上,确认数据线能传数据。+ - 还没配对或没开开发者模式:在终端运行 `iphone-control setup --reconfigure`,选「手机」。+ - 正在启动 WDA:通常 10~60 秒。+ - 设备重启后还没解锁过:在设备上手动解锁一次;首次启用 UI 自动化时在设备上输入锁屏密码。+- **没装 WDA 的设备**:已登录 Apple ID 时,画面区域有「签名并安装 WDA」按钮,大约 1~2 分钟,期间保持手机解锁。没登录时,它会提示在终端运行 `iphone-control setup --reconfigure`,选「Apple ID」。+- 同一时间只控制一台,不能并排看两部手机。+- AI 任务执行中不能切换;设了 `IPHONE_UDID` 时也不能切换。## 控制哪一台@@ -34,15 +49,17 @@ agent 用 `iphone_list_devices` 和 `iphone_select_device`,效果一样。```bashiphone-control select <新设备>-iphone-control setup+iphone-control setup --reconfigure # 选「手机」:配对、开发者模式、签名安装 WDA```-`setup` 只作用于正在控制的那台,所以要先 `select`。它会把设备注册到你的 Apple ID,占用账号的设备名额。自动重签不会替没装过 WDA 的设备注册,这时 `doctor` 会提示运行 `setup`。+设置只作用于正在控制的那台,所以要先 `select`。签名会把设备注册到你的 Apple ID,占用账号的设备名额。自动重签不会替没装过 WDA 的设备注册,这时 `doctor` 会提示运行 `setup`。也可以在控制台里切到新设备,点「签名并安装 WDA」(设备要已经配对、开了开发者模式)。## 重签自动重签只管正在控制的那台。闲置设备的描述文件 7 天后过期,切回去后 1 分钟内会自动检查,快过期或已过期就重签;也可以运行 `resign --force`。+给哪台设备重签都用同一张签名证书,不会让另一台失效。但如果闲置设备上的 WDA 是在别的机器(或旧的数据目录)签的,签它的证书可能已被吊销:切过去后 WDA 起不来时,守护进程会自动重签它,见[常见问题](../troubleshoot/faq#cert)。+## 自动解锁密码按设备分开存:@@ -64,4 +81,4 @@ iphone-control passcode set --device <UDID 或设备名> # 设备要接着- **iOS 26 没有 HID 后备:** WDA 重启期间操作会失败,iPhone 上也一样。- **屏幕尺寸不是 430×932:** iPad mini 5 竖放是 768×1024,以截图和 `iphone_status` 为准。-已验证:iPad mini 5,iOS 26.6.1(Linux,Docker)。+已验证:iPad mini 5,iOS 26.6.1(Linux)。diff --git a/website/guide/notifications.md b/website/guide/notifications.mdindex 6739509..0933085 100644--- a/website/guide/notifications.md+++ b/website/guide/notifications.md@@ -12,16 +12,24 @@| WDA 已恢复 | — || 自动解锁失败已停用 | 见[自动解锁](./auto-unlock) || 手机离线 / 恢复在线 | 检查数据线和主机 |+| 签名证书换了(签名时新建了证书,可能还吊销了一张旧的) | 一般不用管:用旧证书签的设备,WDA 起不来时会自动重签;用同一个 Apple ID 的其他机器、其他侧载工具要在那边重签,见[常见问题](../troubleshoot/faq#cert) |不重复推送的规则:- 重签失败、Apple ID 会话失效:20 小时内不重复,问题还在的话 20 小时后再推。- 要输密码、手机离线:推一次,直到恢复。只有这两类有恢复推送(「WDA 已恢复」「已重新连上」)。- 自动解锁停用:推一次,`unlock-reset` 后才可能再推。+- 签名证书换了:每次都推。- 这些记录只在内存里,守护进程重启后清空,还没解决的问题会再推一次。通知文字不带设备名,接着多台时用 `status` 看是哪台,见[多台设备](./multi-device)。+## 设置++最简单的是在引导里设:首次运行 `iphone-control` 时会问,以后运行 `iphone-control setup --reconfigure` 选「通知」。选 Bark 或 Telegram,填好后会发一条测试通知,并重启守护进程让设置生效。++也可以手动写进[设置文件](./configuration#settings-file) `~/.config/iphone-control/env`,改完运行 `iphone-control service restart`。+## Bark```ini@@ -39,10 +47,10 @@ TG_CHAT_ID=你的chat id## 测试```bash-docker exec iphone-control iphone-control notify-test # 每类事件各发一条,标题带「[测试]」-docker exec iphone-control iphone-control notify-test offline # 只发一类:resign / session / pin / pin-recovered / unlock / offline / online+iphone-control notify-test # 每类事件各发一条,标题带「[测试]」+iphone-control notify-test offline # 只发一类:resign / session / pin / pin-recovered / unlock / offline / online / cert```-::: info 容器整个挂掉时发不了通知-通知由守护进程发出。容器或主机宕机时需要宿主机侧的监控,本项目没有提供。+::: info 守护进程整个挂掉时发不了通知+通知由守护进程发出。守护进程崩溃后,后台服务会自动重启它;主机宕机时需要另外的监控,本项目没有提供。:::diff --git a/website/guide/security.md b/website/guide/security.mdindex 3891c21..8a0cb91 100644--- a/website/guide/security.md+++ b/website/guide/security.md@@ -7,20 +7,19 @@ iphone-control 本质上是一个手机遥控器:能访问它的人,就能## 存了什么- **数据目录**里有 Apple ID 会话、开发签名私钥、配对记录,开启自动解锁时还有**明文**的锁屏密码,要像密码一样保管和备份。Apple ID 密码本身不保存。-- **控制接口**是权限 0600 的 Unix socket,能连上它就能操控手机:主机 root、能 `docker exec` 进容器的人、从源码运行时的同一用户。-- **通知密钥**在 `.env` 或 `~/.config/iphone-control/env` 里。+- **控制接口**是权限 0600 的 Unix socket,能连上它就能操控手机:主机 root 和运行守护进程的那个用户。+- **通知密钥**在设置文件 `~/.config/iphone-control/env` 里,权限 0600。## 默认的保护-- **不开网络端口。** WDA 经 usbmuxd 直连手机。`wda-bridge` 和实时画面 `viewer` 都要显式开启,只绑 127.0.0.1,浏览器里的其他网页借不了它们操作手机。但它们没有登录,本机任何用户都能用,用完就停。-- **容器不用 privileged**,只开放 USB 字符设备。+- **不开网络端口。** WDA 经 usbmuxd 直连手机。`wda-bridge` 和实时画面 `viewer` 都要显式开启,只绑 127.0.0.1,浏览器里的其他网页借不了它们操作手机。但它们没有登录,本机任何用户都能用(包括在 viewer 上发起 AI 任务),用完就停。+- **不用 root。** 守护进程以你的普通用户身份作为用户服务运行,安装脚本拒绝以 root 运行。- **自动解锁默认关闭**,输错一次即停用。- **开发者工具默认关闭**。-- 依赖锁定精确版本,基础镜像锁 digest,下载的 WebDriverAgent 核对 sha256。+- 依赖锁定精确版本,下载的 WebDriverAgent 核对 sha256,安装脚本核对下载包的 sha256。## 需要知道的风险-- **容器以 root 运行。** 要读写 USB 设备节点,拔插后还要能重启 usbmuxd(容器里没有 udev)。- **anisette 服务。** 登录 Apple ID 默认用公共的第三方服务(`mac-ani.jkcoxson.com`)。它拿不到你的密码,但能看到你什么时候登录。介意的话自建 [anisette-v3-server](https://github.com/Dadoum/anisette-v3-server),设 `ICTL_ANISETTE_URL`。- **用专门的 Apple ID。** 主机被入侵时,专门的账号能把影响限制住。- **agent 用你的手在操作。** 它能发消息、付款、改设置。服务端会要求 agent 在这类操作前先问你,但这只是指示,不是强制。diff --git a/website/guide/what-is-iphone-control.md b/website/guide/what-is-iphone-control.mdindex 1a535e4..6313630 100644--- a/website/guide/what-is-iphone-control.md+++ b/website/guide/what-is-iphone-control.md@@ -24,9 +24,9 @@ iphone-control 让 AI agent(例如 Claude)操作一台用数据线接在 Lin| | ||---|---|-| 主机 | Linux,x86_64 或 arm64:Docker(Compose v2),或 Rust 1.88+ 从源码编译<br>macOS,Apple Silicon:预编译二进制,或 Rust 1.88+ 从源码编译,见 [macOS](../deploy/macos) |+| 主机 | Linux,x86_64 或 arm64:一行命令安装、Homebrew 或 deb 包(Debian 12+、Ubuntu 22.04+),要系统的 usbmuxd;也可以用 Rust 1.88+ 从源码编译<br>macOS,Apple Silicon:一行命令安装或 Homebrew,也可以从源码编译,见 [macOS](../deploy/macos)<br>不支持 Windows || 手机 | iPhone 或 iPad,iOS 17 及以上;HID 后备路线要 iOS 27 及以上 |-| 已在真机验证 | iPhone 15 Pro Max,iOS 27.0.1(Linux、macOS)<br>iPhone 12 mini,iOS 26.4.1(Linux)<br>iPad mini 5,iOS 26.6.1(Linux,Docker) |+| 已在真机验证 | iPhone 15 Pro Max,iOS 27.0.1(Linux、macOS)<br>iPhone 12 mini,iOS 26.4.1(Linux)<br>iPad mini 5,iOS 26.6.1(Linux) || 账号 | 免费 Apple ID 即可,建议专门注册一个 |其他机型和 iOS 版本应该也能用,但还没测过,欢迎[反馈](https://github.com/Derrors/iphone-control/issues)。@@ -49,13 +49,11 @@ iphone-control 让 AI agent(例如 Claude)操作一台用数据线接在 Lin- HID 后备路线要 iOS 27 及以上;更早的 iOS 全部经 WebDriverAgent 操作,WDA 重启期间操作会失败。- 免费 Apple ID 的描述文件 7 天有效。重签是自动的,但 Apple ID 会话失效后要运行 `login` 重新登录。- 登录 Apple ID 默认用公共的第三方 anisette 服务,可以设 `ICTL_ANISETTE_URL` 换成自建服务,见[配置](./configuration)。-- Docker 容器以 root 运行:要访问 USB 设备节点,拔插后还要重启容器里的 usbmuxd。**macOS**-- 只支持 Apple Silicon,Intel Mac 没测过。+- 预编译版本只支持 Apple Silicon;Intel Mac 要从源码编译,没测过。- 预编译二进制没有经过苹果公证,用浏览器下载的要先去掉隔离标记。-- 守护进程要在终端里前台运行,还没有 launchd 配置;不能用 Docker(没有 USB 直通)。- 手机的充电上限要改成 100%,开着「80% 上限」时 USB 大约每分钟断开一次。和 Linux 的其他区别见 [macOS 已知差异](../deploy/macos#已知差异)。diff --git a/website/index.md b/website/index.mdindex 3c6f472..d6fa5c0 100644--- a/website/index.md+++ b/website/index.md@@ -40,7 +40,7 @@ features:details: WDA 经 usbmuxd 直连手机,本机不监听任何网络端口;自动解锁默认关闭- icon: 📦title: 一个二进制- details: Rust 编写,Linux 上 Docker 一条命令部署,也可以从源码或预编译二进制运行;Mac 上直接运行预编译二进制+ details: Rust 编写。一行命令、Homebrew 或 deb 包安装,运行 iphone-control 一步步带你设置好;也可以从源码编译- icon: 🧭title: 省往返details: 操作可以顺带返回操作后的界面,自动等界面稳定、识别加载中和挡路的弹窗diff --git a/website/public/architecture-dark.svg b/website/public/architecture-dark.svgindex d04eddb..f8d6900 100644--- a/website/public/architecture-dark.svg+++ b/website/public/architecture-dark.svg@@ -21,7 +21,7 @@<!-- Linux host --><rect x="16" y="16" width="900" height="568" rx="24" fill="none" stroke="#3d444d" stroke-width="2" stroke-dasharray="8 6"/>- <text x="44" y="54" class="frame"><tspan style="font-weight:700;fill:#e6edf3">Linux or macOS host</tspan> · Docker, systemd user service or a terminal</text>+ <text x="44" y="54" class="frame"><tspan style="font-weight:700;fill:#e6edf3">Linux or macOS host</tspan> · launchd, systemd user service or a terminal</text><!-- AI client --><rect x="48" y="88" width="260" height="128" rx="16" fill="#151b23" stroke="#3d444d" stroke-width="1.5"/>diff --git a/website/public/architecture-light.svg b/website/public/architecture-light.svgindex f051f23..73775e4 100644--- a/website/public/architecture-light.svg+++ b/website/public/architecture-light.svg@@ -21,7 +21,7 @@<!-- Linux host --><rect x="16" y="16" width="900" height="568" rx="24" fill="none" stroke="#d0d7de" stroke-width="2" stroke-dasharray="8 6"/>- <text x="44" y="54" class="frame"><tspan style="font-weight:700;fill:#1f2328">Linux or macOS host</tspan> · Docker, systemd user service or a terminal</text>+ <text x="44" y="54" class="frame"><tspan style="font-weight:700;fill:#1f2328">Linux or macOS host</tspan> · launchd, systemd user service or a terminal</text><!-- AI client --><rect x="48" y="88" width="260" height="128" rx="16" fill="#f6f8fa" stroke="#d0d7de" stroke-width="1.5"/>diff --git a/website/troubleshoot/faq.md b/website/troubleshoot/faq.mdindex 5326df0..1e006c8 100644--- a/website/troubleshoot/faq.md+++ b/website/troubleshoot/faq.md@@ -3,7 +3,7 @@先运行这两个命令,大多数问题都能看出来:```bash-iphone-control status # Docker 部署前面加 docker exec -it iphone-control+iphone-control status # 守护进程和设备的状态、最近日志iphone-control doctor # 逐层检查,每项失败都给出修复办法```@@ -11,9 +11,9 @@ iphone-control doctor # 逐层检查,每项失败都给出修复办法| `status` 显示 | 含义 | 怎么办 ||---|---|---|-| 手机未连接 | usbmuxd 看不到手机 | 检查数据线、解锁手机;Linux 宿主机装了 usbmuxd 时 `sudo systemctl mask usbmuxd`。接着多台时,选定的那台没接也显示这个:看 `status` 的「选设备」行,或运行 `select auto`,见[多台设备](../guide/multi-device) |-| 未配对 | 没有配对记录 | 运行 `setup`,手机上点「信任」 |-| 开发者模式未打开 | — | 在手机的 设置 → 隐私与安全性 → 开发者模式 打开。手机被开发者工具连接过才会出现这个开关,运行 `setup` 会处理 |+| 手机未连接 | usbmuxd 看不到手机 | 检查数据线、解锁手机;Linux 上确认装了系统的 usbmuxd(`sudo apt install usbmuxd`)。接着多台时,选定的那台没接也显示这个:看 `status` 的「选设备」行,或运行 `select auto`,见[多台设备](../guide/multi-device) |+| 未配对 | 没有配对记录 | 运行 `setup --reconfigure` 选「手机」,手机上点「信任」 |+| 开发者模式未打开 | — | 在手机的 设置 → 隐私与安全性 → 开发者模式 打开。手机被开发者工具连接过才会出现这个开关,运行 `setup --reconfigure` 选「手机」会处理 || 手机锁屏,隧道建不起来 | 重启后还没解锁过 | 手动解锁一次;解锁前状态一直是这个,守护进程会定期重试 || WDA 还没签名安装 | — | 运行 `sign` 或 `setup` || 正在启动 WDA | 最长约 2 分钟 | 等一下。iOS 27 起期间点击、滑动、截图走 HID 后备,仍可用,但横屏时要 30 秒内从 WDA 拿到过方向,否则拒绝触摸;屏幕尺寸未知时报错,见[工具一览](../guide/tools#wda-不可用时-hid-后备)。更早的 iOS 要等 WDA 起来 |@@ -23,37 +23,47 @@ iphone-control doctor # 逐层检查,每项失败都给出修复办法## 手机连不上-- **两个 usbmuxd 在抢:** 很多发行版装了 usbmuxd,插上手机就被 udev 拉起,抢走 Docker 里的连接。`sudo systemctl mask usbmuxd`。+- **Linux 上没有 usbmuxd:** 守护进程用系统的 usbmuxd,不会自己启动。`sudo apt install usbmuxd`(deb 包会自动装)。以前为 Docker 部署做过 `sudo systemctl mask usbmuxd` 的,先 `sudo systemctl unmask usbmuxd`。+- **守护进程没在运行:** `iphone-control service status` 看看,`iphone-control service start` 启动。直接运行 `iphone-control` 也会在服务没运行时启动它。- **别的工具占着手机:** 同时运行 go-ios、pymobiledevice3 等会冲突。- **数据线:** 有的线只能充电。`lsusb` 里看不到 Apple 设备(`05ac`)时换根线或换个口。-- **拔插后:** Docker 部署大约 1 分钟内自动恢复。+- **拔插后:** 大约 1 分钟内自动恢复。- **充电时大约每分钟断开一次:** 手机开着「设置 → 电池 → 充电 → 80% 上限」时,在 80% 附近反复开始、停止充电,每次 USB-C 重新协商供电都会让 USB 断开 3~5 秒。用来做自动化的手机把上限改成 100%。-- **Mac 上:** 不能用 Docker(没有 USB 直通),见 [macOS](../deploy/macos)。usbmuxd 是系统自带的,`doctor` 报连不上时运行 `sudo launchctl kickstart -k system/com.apple.usbmuxd`。+- **Mac 上:** usbmuxd 是系统自带的,`doctor` 报连不上时运行 `sudo launchctl kickstart -k system/com.apple.usbmuxd`。见 [macOS](../deploy/macos)。## WDA 起不来- **「不受信任的开发者」:** 首次安装后在 设置 → 通用 → VPN 与设备管理 里信任你的 Apple ID(手机要联网)。+- <a id="cert"></a>**签名证书被吊销了:**`status` 报 `unexpected response`,描述文件却还有效;在设备上点 WebDriverAgentRunner 图标提示「无法验证 App」。+ - 原因:每个安装(每台机器、每个数据目录)有自己的签名私钥和证书,免费 Apple ID 同时最多两张证书。在新地方第一次签名(换机器、从 Docker 换成本机安装、删了数据目录),或在 AltStore、SideStore 等侧载工具里用同一个 Apple ID 签名,都会新建证书;满了就吊销一张旧的,用它签的 App 在每台设备上都起不来。+ - 守护进程会自己处理:设备拒绝启动 WDA 时,如果设备上的 WDA 不是本机证书签的,或本机的证书已不在 Apple ID 的团队里,就自动重签这台(同一台 6 小时内最多一次),并发通知。`doctor` 会显示这两项检查。+ - 手动处理:`iphone-control sign` 重签正在控制的设备;控制台里 WDA 启动失败时也有「重新签名并安装 WDA」按钮。+ - 别让两处同时用同一个 Apple ID 签名:不用的旧部署停掉,或给它们用不同的 Apple ID。- **签名过期:** 免费签名 7 天有效,会自动重签。`status` 能看到还剩多久,`resign --force` 立即重签。-- **Apple ID 会话失效:** 会收到通知,重新运行 `login`。-- **开发者镜像失败:** `status` 第一行显示「WDA 启动失败,稍后重试:开发者镜像:…」,详情在 `logs/daemon.log`;`doctor` 没有单独的镜像检查。下载需要能访问 GitHub,配好 `HTTP_PROXY` / `HTTPS_PROXY`,或用 `ICTL_DDI_DIR` 指向从 Xcode 提取的目录,见[配置](../guide/configuration#高级)。+- **Apple ID 会话失效:** 会收到通知。运行 `iphone-control setup --reconfigure` 选「Apple ID」,重新登录并重签 WDA。+- **开发者镜像失败:** `status` 第一行显示「WDA 启动失败,稍后重试:开发者镜像:…」,详情在 `logs/daemon.log`;`doctor` 没有单独的镜像检查。下载需要能访问 GitHub,配好代理(`iphone-control setup --reconfigure` 选「代理」),或用 `ICTL_DDI_DIR` 指向从 Xcode 提取的目录,见[配置](../guide/configuration#高级)。## 登录-- **输不了验证码:** `login`、`setup` 要在终端里交互运行,Docker 部署记得带 `-it`。+- **输不了验证码:** `login`、`setup` 和第一次运行的 `iphone-control` 都要在终端里交互运行,不能放进脚本或管道。- **anisette 报错:** 默认的公共 anisette 服务可能暂时不可用,稍后重试,或自建后设 `ICTL_ANISETTE_URL`。## AI 客户端-- **MCP 连接断开:** 容器重启会断开 MCP 进程,在客户端里重新连接(Claude Code 运行 `/mcp`)。+- **MCP 工具不见了:** 运行 `iphone-control setup --reconfigure` 选「注册 MCP」,或运行 `iphone-control mcp-config` 打印注册命令,然后开一个新会话。- **「守护进程正忙…已放弃执行」:** 一个操作排队超过 30 秒,为免点到已经变了的屏幕而放弃。截图看看再重试。- **操作报错说 WDA 连接中途断开:** 请求已经发出,动作可能已经做了,为免点两次、输两遍不会重做。先截图确认。- **点了没反应:** 可能有系统弹窗挡着,工具结果里会提示「屏幕上有系统弹窗…」,先点掉它。- **输入的字不全:** `iphone_type_text` 会读回核对并补上;仍提示对不上时,说明 App 在输入过程中改写了输入框,分几段输入。+## 控制台切换设备后没有画面++画面区域会写明原因:没连上、还要配对或打开开发者模式(运行 `iphone-control setup --reconfigure` 选「手机」)、WDA 正在启动(通常 10–60 秒)、要先解锁。新设备上还没装 WDA 时,已登录 Apple ID 的可以点「签名并安装 WDA」,大约 1–2 分钟,期间保持手机解锁;没登录的运行 `iphone-control setup --reconfigure` 选「Apple ID」。AI 任务执行中,或设了 `IPHONE_UDID` 时,不能切换设备。见[多台设备](../guide/multi-device)。+## 灵动岛一直显示「配对的电脑」、手机不自动锁屏-HID 后备路线使用时会开一个屏幕镜像会话,空闲 30 秒自动关闭。图标一直不消失时,重启一下守护进程。+HID 后备路线使用时会开一个屏幕镜像会话,空闲 30 秒自动关闭。图标一直不消失时,重启一下守护进程(`iphone-control service restart`)。## 报告问题-[提 issue](https://github.com/Derrors/iphone-control/issues/new/choose) 时请附上机型、iOS 版本、部署方式和 `doctor` 的输出,先去掉 UDID、Apple ID、通知密钥等隐私信息。+[提 issue](https://github.com/Derrors/iphone-control/issues/new/choose) 时请附上机型、iOS 版本、安装方式(一行命令、Homebrew、deb 或源码)和 `doctor` 的输出,先去掉 UDID、Apple ID、通知密钥等隐私信息。