diff --git a/README.en.md b/README.en.md index 6b55dcc4..3e5b640e 100644 --- a/README.en.md +++ b/README.en.md @@ -368,7 +368,7 @@ Double-click `ModAVD.exe` in the package root: it starts a local server that lis - It does only the step you explicitly ask for; it never goes online automatically and never downloads in the background: - `modavd update` (`status`) looks at local state only; `check` looks up the latest version; - `prepare` downloads, unpacks, verifies file by file against the `modavd-manifest.json` in the package, and stages the result; instances can be running; - - `install` runs `prepare` first if needed, then swaps in `sdk\emulator` and the other files in the package. All instances, the manager (including one left in the tray) and MCP clients must be closed first; if any program is using the files, it changes nothing (exit code 5), and the staged new version is kept so the next run can swap it in directly; + - `install` runs `prepare` first if needed, then swaps in `sdk\emulator` and the other files in the package. All instances and the manager (including one left in the tray) must be closed first; the MCP servers (`modavd mcp`) this root has running are stopped by `install` itself, and the AI assistant's next call starts the new version. If any other program is using the files, it changes nothing (exit code 5), and the staged new version is kept so the next run can swap it in directly; - `recover` finishes or rolls back a swap that was left unfinished last time (it also runs first at the start of every step). - The update source is chosen in the manager's "Settings": GitHub (the latest Release of `ModAVD/ModAVD`; only the changed files are fetched with HTTP Range requests and the rest is copied from the root, falling back to the full package, with the reason in `notices`, when the server does not serve ranges, more than 40% of the package or 3000 files changed, or the fetched data or the assembled result fails its checks) or MirrorChyan (downloads need a CDK, and it can provide delta packages; on errors it downloads from GitHub instead and says so in the result's `notices`). The optional GitHub token is used for GitHub version checks and downloads in the manager and CLI. The CDK and token are encrypted with Windows DPAPI and stored in `%LOCALAPPDATA%\ModAVD\update-settings.json`; only this Windows user can decrypt it, and the values stay out of logs, command-line arguments and API responses. - Settings the caller passes for one run (`status`, `check`, `prepare` and `install` accept them, `recover` does not; they only override "Settings", are never saved, and `source` / `cdk_set` in the result report what was in effect): diff --git a/README.md b/README.md index 8acabe58..2b90a61a 100644 --- a/README.md +++ b/README.md @@ -371,7 +371,7 @@ Apple Silicon macOS 可运行 `ModAVD` 管理器;`ModAVD.app` 放在包根目 - 只做明确要求的那一步,不自动联网、不在后台下载: - `modavd update`(`status`)只看本地;`check` 查最新版本; - `prepare` 下载、解包、按包里的 `modavd-manifest.json` 逐文件核对、暂存好,实例开着也行; - - `install` 需要时先 `prepare`,再换上 `sdk\emulator` 和包里的其他文件。要先关掉所有实例、管理器(包括托盘里的)和 MCP 客户端,有程序在用就什么都不动(退出码 5),暂存的新版留着,下次直接换; + - `install` 需要时先 `prepare`,再换上 `sdk\emulator` 和包里的其他文件。要先关掉所有实例和管理器(包括托盘里的);这个根目录开着的 MCP 服务(`modavd mcp`)由它自己关掉,AI 助手下次调用时用的就是新版。别的程序在用就什么都不动(退出码 5),暂存的新版留着,下次直接换; - `recover` 补完或退回上次没做完的换上(每一步开始前也会先做)。 - 更新源在管理器的「设置」里选:GitHub(`ModAVD/ModAVD` 的最新 Release;先按区间只下变了的文件、没变的从本地复制,服务器不认 Range、变了的超过整包 40% 或 3000 个文件、取回的数据或拼好后的清单核对不过时改下整包,原因写进 `notices`)或 Mirror 酱(填了 CDK 才能下载,能拿到增量包;出错时改从 GitHub 下,并在结果的 `notices` 里写明)。GitHub token 可留空,填好后用于管理器和命令行的 GitHub 版本查询及下载。CDK 和 token 用 Windows DPAPI 加密存在 `%LOCALAPPDATA%\ModAVD\update-settings.json`,只有这个 Windows 用户能解开,不写日志、不出现在命令行和接口返回里。 - 调用方传这一次的设置(`status`、`check`、`prepare`、`install` 都可以带,`recover` 不带;只盖过「设置」里的,不保存,`status` 等结果里的 `source`、`cdk_set` 是这次生效的): diff --git a/changelog.d/302-report-metadata-withheld.fix.md b/changelog.d/302-report-metadata-withheld.fix.md new file mode 100644 index 00000000..b4199738 --- /dev/null +++ b/changelog.d/302-report-metadata-withheld.fix.md @@ -0,0 +1,2 @@ +问题包里的 mas-avd.json 去不掉应用清单时不再附上,避免清单泄露 +A diagnostics report now leaves out mas-avd.json when its app list cannot be removed, so the list no longer leaks diff --git a/changelog.d/427.feat.md b/changelog.d/427.feat.md new file mode 100644 index 00000000..bfb953d4 --- /dev/null +++ b/changelog.d/427.feat.md @@ -0,0 +1,2 @@ +Windows 画面弹窗直接绘制共享内存帧,支持 2–30 帧/秒,默认 15 帧/秒。 +The Windows screen viewer draws shared-memory frames directly and supports 2–30 fps, with a default of 15 fps. diff --git a/changelog.d/429.change.md b/changelog.d/429.change.md new file mode 100644 index 00000000..17f638da --- /dev/null +++ b/changelog.d/429.change.md @@ -0,0 +1,2 @@ +管理器的卡片缩略图和画面弹窗统一使用共享内存截图。 +Manager thumbnails and the screen viewer use shared-memory capture. diff --git a/changelog.d/453-mirror-token-error.fix.md b/changelog.d/453-mirror-token-error.fix.md new file mode 100644 index 00000000..54ccd3da --- /dev/null +++ b/changelog.d/453-mirror-token-error.fix.md @@ -0,0 +1,2 @@ +更新源选 Mirror 酱时,查更新失败会同时显示 Mirror 酱的原因,不再只报 GitHub token 失效 (ModAVD/ModAVD#453) +With MirrorChyan as the update source, a failed check now shows MirrorChyan's reason instead of only an expired GitHub token diff --git a/changelog.d/461-mcp-stop-on-update.change.md b/changelog.d/461-mcp-stop-on-update.change.md new file mode 100644 index 00000000..fb12cca3 --- /dev/null +++ b/changelog.d/461-mcp-stop-on-update.change.md @@ -0,0 +1,2 @@ +更新时自动关掉 AI 助手开着的 modavd mcp,不用再手动关 (ModAVD/ModAVD#461) +Updating now stops the modavd mcp servers an AI assistant left running; no need to close them first diff --git a/changelog.d/issue-462-card-marks.change.md b/changelog.d/issue-462-card-marks.change.md new file mode 100644 index 00000000..df74744c --- /dev/null +++ b/changelog.d/issue-462-card-marks.change.md @@ -0,0 +1,2 @@ +实例卡片标记改成细框、无底色,ADB 改成字母 A;鼠标操作不再出现焦点框;名称提示不再写编号 +Card marks get thin frames, ADB is the letter A, focus rings are keyboard-only, and the name tooltip drops the index. diff --git a/changelog.d/issue-463-card-pill.change.md b/changelog.d/issue-463-card-pill.change.md new file mode 100644 index 00000000..5a10dff3 --- /dev/null +++ b/changelog.d/issue-463-card-pill.change.md @@ -0,0 +1,2 @@ +卡片视图不再显示开机中等状态标签,开机失败时点画面区查看原因 +Cards no longer show a status label; for a failed boot, click the screen for the reason diff --git a/cmd/modavd-gui/rsrc_windows_amd64.syso b/cmd/modavd-gui/rsrc_windows_amd64.syso index 93657ce2..f40e8ea5 100644 Binary files a/cmd/modavd-gui/rsrc_windows_amd64.syso and b/cmd/modavd-gui/rsrc_windows_amd64.syso differ diff --git a/internal/buildinfo/buildinfo.go b/internal/buildinfo/buildinfo.go index fea486f9..a54ac63e 100644 --- a/internal/buildinfo/buildinfo.go +++ b/internal/buildinfo/buildinfo.go @@ -4,7 +4,7 @@ package buildinfo // Version of modavd itself, kept in the source rather than set with -ldflags -X: release builds must come out byte // for byte the same for the same source (Mirror 酱 ships per-file deltas, and a version stamped per package would // change the exe in every release). The ModAVD package version comes from the root at run time. -var Version = "0.47.0" +var Version = "0.47.1" // Protocol is the version of the machine-readable contract: the commands, the JSON written by `--json`, the exit codes // and the MCP tool schemas. Callers such as AUTO-MAS check it (`modavd version --json`) before relying on a field. diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 4454d991..148918bd 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -460,7 +460,7 @@ func init() { "--cdk-dpapi 是用 Windows DPAPI 加密好的 CDK 的 base64,解不开或格式不对是 invalid_argument,CDK 不进日志和输出。" + "不自动联网,只做给出的那一步:" + "status(默认)只看本地;check 查最新版本;prepare 下载、按清单核对、暂存好,实例开着也行;" + - "install 需要时先 prepare,再换上 sdk\\emulator 和包里的其他文件,要先关掉所有实例、管理器(包括托盘里的)和 MCP 客户端;" + + "install 需要时先 prepare,再换上 sdk\\emulator 和包里的其他文件,要先关掉所有实例和管理器(包括托盘里的),这个根目录开着的 MCP 服务由它自己关掉;" + "recover 补完或退回上次没做完的换上。和 AUTO-MAS 用同一个 .update 目录,能接着对方没做完的做。" + "--automas-version 是调用方 AUTO-MAS 的版本,新版要求更高的 AUTO-MAS 时不装。" + "--after-pid、--reopen、--reopen-arg、--handoff-id 是管理器「设置」里点「更新」时用的:管理器下载核对好、关掉实例后启动这条命令并退出," + @@ -2074,9 +2074,12 @@ func runMCP(c *cmdCtx) (any, error) { c.log.Infof("MCP 服务已就绪,根目录 %s", r.Dir) } var mu sync.Mutex + // An update of the root this program belongs to asks the server to exit (ModAVD/ModAVD#461). + exe, _ := os.Executable() opt := mcp.Options{ Version: buildinfo.Version, Log: c.log, + Exit: update.WatchMCPExit(c.ctx, exe), NewManager: func(log *logx.Logger) (*emu.Manager, error) { mu.Lock() defer mu.Unlock() diff --git a/internal/i18n/locales/en/cli.json b/internal/i18n/locales/en/cli.json index 2046c2f7..2fa633d8 100644 --- a/internal/i18n/locales/en/cli.json +++ b/internal/i18n/locales/en/cli.json @@ -336,7 +336,7 @@ "挂不上:%v": "Could not attach: %v", "按应用走代理": "Per-app proxy", "按应用走代理:名单里的应用走代理,其余直连": "Per-app proxy: apps in the list go through the proxy, the rest connect directly", - "按管理器「设置」里选的更新源(GitHub 或 Mirror 酱,Mirror 酱下载要填 CDK);调用方有自己的设置时用 --source 和 --cdk-dpapi 传这一次的,只盖过「设置」、不保存,status 里的 source、cdk_set 是这次生效的。--cdk-dpapi 是用 Windows DPAPI 加密好的 CDK 的 base64,解不开或格式不对是 invalid_argument,CDK 不进日志和输出。不自动联网,只做给出的那一步:status(默认)只看本地;check 查最新版本;prepare 下载、按清单核对、暂存好,实例开着也行;install 需要时先 prepare,再换上 sdk\\emulator 和包里的其他文件,要先关掉所有实例、管理器(包括托盘里的)和 MCP 客户端;recover 补完或退回上次没做完的换上。和 AUTO-MAS 用同一个 .update 目录,能接着对方没做完的做。--automas-version 是调用方 AUTO-MAS 的版本,新版要求更高的 AUTO-MAS 时不装。--after-pid、--reopen、--reopen-arg、--handoff-id 是管理器「设置」里点「更新」时用的:管理器下载核对好、关掉实例后启动这条命令并退出,命令等它退出再换上新版,然后重新打开管理器。macOS 可用 --package ZIP --sha256 HEX 准备或安装本地完整签名包;摘要需从可信来源独立取得。--json 时每个进度在 stderr 的日志行里多一个 progress 对象(checking、extracting、verifying、installing 开始时各一行,percent 为 -1;downloading 第一行就带真实进度,之后约 2 秒一行,下完那行一定有):{\"stage\":\"checking|downloading|extracting|verifying|installing\",\"percent\":-1 或 0–100,\"done_bytes\":N,\"total_bytes\":N}。查不了是退出码 9(update_unavailable),下载没通过核对也是 9(update_rejected),有程序在用是 5。": "Uses the update source chosen in the manager's \"Settings\" (GitHub or MirrorChyan; downloading from MirrorChyan needs a CDK); a caller with its own settings passes this run's with --source and --cdk-dpapi, which only override \"Settings\" and are not saved; source and cdk_set in status are the ones in effect for this run. --cdk-dpapi is the base64 of the CDK encrypted with Windows DPAPI; if it cannot be decrypted or the format is wrong it is invalid_argument, and the CDK never goes into logs or output. It does not go online by itself and only does the step you give: status (default) only looks locally; check looks up the latest version; prepare downloads, verifies against the manifest and stages, even while instances are running; install runs prepare first if needed, then puts in sdk\\emulator and the other files of the package, and requires all instances, the manager (including in the tray) and MCP clients to be closed first; recover finishes or rolls back an install that was not completed. It uses the same .update folder as AUTO-MAS and can continue what the other side did not finish. --automas-version is the caller's AUTO-MAS version; if the new version needs a newer AUTO-MAS, it is not installed. --after-pid, --reopen, --reopen-arg and --handoff-id are used when \"Update\" is clicked in the manager's \"Settings\": the manager downloads and verifies, closes the instances, starts this command and exits; the command waits for it to exit, puts the new version in place, and then reopens the manager. On macOS, --package ZIP --sha256 HEX prepares or installs a local full signed package; the digest must be obtained independently from a trusted source. With --json, each progress step adds a progress object to the log line on stderr (one line each when checking, extracting, verifying and installing start, with percent -1; downloading carries real progress from its first line, then about one line every 2 seconds, and always one when the download finishes): {\"stage\":\"checking|downloading|extracting|verifying|installing\",\"percent\":-1 or 0-100,\"done_bytes\":N,\"total_bytes\":N}. Being unable to check is exit code 9 (update_unavailable), a download that fails verification is also 9 (update_rejected), and a program in use is 5.", + "按管理器「设置」里选的更新源(GitHub 或 Mirror 酱,Mirror 酱下载要填 CDK);调用方有自己的设置时用 --source 和 --cdk-dpapi 传这一次的,只盖过「设置」、不保存,status 里的 source、cdk_set 是这次生效的。--cdk-dpapi 是用 Windows DPAPI 加密好的 CDK 的 base64,解不开或格式不对是 invalid_argument,CDK 不进日志和输出。不自动联网,只做给出的那一步:status(默认)只看本地;check 查最新版本;prepare 下载、按清单核对、暂存好,实例开着也行;install 需要时先 prepare,再换上 sdk\\emulator 和包里的其他文件,要先关掉所有实例和管理器(包括托盘里的),这个根目录开着的 MCP 服务由它自己关掉;recover 补完或退回上次没做完的换上。和 AUTO-MAS 用同一个 .update 目录,能接着对方没做完的做。--automas-version 是调用方 AUTO-MAS 的版本,新版要求更高的 AUTO-MAS 时不装。--after-pid、--reopen、--reopen-arg、--handoff-id 是管理器「设置」里点「更新」时用的:管理器下载核对好、关掉实例后启动这条命令并退出,命令等它退出再换上新版,然后重新打开管理器。macOS 可用 --package ZIP --sha256 HEX 准备或安装本地完整签名包;摘要需从可信来源独立取得。--json 时每个进度在 stderr 的日志行里多一个 progress 对象(checking、extracting、verifying、installing 开始时各一行,percent 为 -1;downloading 第一行就带真实进度,之后约 2 秒一行,下完那行一定有):{\"stage\":\"checking|downloading|extracting|verifying|installing\",\"percent\":-1 或 0–100,\"done_bytes\":N,\"total_bytes\":N}。查不了是退出码 9(update_unavailable),下载没通过核对也是 9(update_rejected),有程序在用是 5。": "Uses the update source chosen in the manager's \"Settings\" (GitHub or MirrorChyan; downloading from MirrorChyan needs a CDK); a caller with its own settings passes this run's with --source and --cdk-dpapi, which only override \"Settings\" and are not saved; source and cdk_set in status are the ones in effect for this run. --cdk-dpapi is the base64 of the CDK encrypted with Windows DPAPI; if it cannot be decrypted or the format is wrong it is invalid_argument, and the CDK never goes into logs or output. It does not go online by itself and only does the step you give: status (default) only looks locally; check looks up the latest version; prepare downloads, verifies against the manifest and stages, even while instances are running; install runs prepare first if needed, then puts in sdk\\emulator and the other files of the package, and requires all instances and the manager (including in the tray) to be closed first; it stops the MCP servers this root folder has running itself; recover finishes or rolls back an install that was not completed. It uses the same .update folder as AUTO-MAS and can continue what the other side did not finish. --automas-version is the caller's AUTO-MAS version; if the new version needs a newer AUTO-MAS, it is not installed. --after-pid, --reopen, --reopen-arg and --handoff-id are used when \"Update\" is clicked in the manager's \"Settings\": the manager downloads and verifies, closes the instances, starts this command and exits; the command waits for it to exit, puts the new version in place, and then reopens the manager. On macOS, --package ZIP --sha256 HEX prepares or installs a local full signed package; the digest must be obtained independently from a trusted source. With --json, each progress step adds a progress object to the log line on stderr (one line each when checking, extracting, verifying and installing start, with percent -1; downloading carries real progress from its first line, then about one line every 2 seconds, and always one when the download finishes): {\"stage\":\"checking|downloading|extracting|verifying|installing\",\"percent\":-1 or 0-100,\"done_bytes\":N,\"total_bytes\":N}. Being unable to check is exit code 9 (update_unavailable), a download that fails verification is also 9 (update_rejected), and a program in use is 5.", "控制台 %d,adb %d,gRPC %d": "Console %d, adb %d, gRPC %d", "提示:%v": "Note: %v", "收集完成。": "Collection finished.", diff --git a/internal/i18n/locales/en/mcp.json b/internal/i18n/locales/en/mcp.json index 8dceb53c..b7faed9b 100644 --- a/internal/i18n/locales/en/mcp.json +++ b/internal/i18n/locales/en/mcp.json @@ -6,6 +6,7 @@ "MCP 服务没有设置实例管理器(NewManager)": "The MCP server has no instance manager set (NewManager)", "MCP 服务被中止": "MCP server was aborted", "MCP 消息编码失败: %v": "Failed to encode MCP message: %v", + "ModAVD 正在更新,MCP 服务退出;客户端重新连接后用的就是新版": "ModAVD is updating, MCP server exiting; the client gets the new version when it reconnects", "apk_path 不能为空": "apk_path cannot be empty", "apk_path 必须是宿主机上的绝对路径: %s": "apk_path must be an absolute path on the host: %s", "command 不能为空": "command cannot be empty", diff --git a/internal/i18n/locales/en/report.json b/internal/i18n/locales/en/report.json index 56741e33..fadc5a3f 100644 --- a/internal/i18n/locales/en/report.json +++ b/internal/i18n/locales/en/report.json @@ -64,6 +64,7 @@ "%s:%s,只取了最后 %s": null, "%s:关机前的内核日志 %d 份(取最新 %d 份)": null, "%s:收集这台实例时出错:%s": null, + "未附 mas-avd.json:它解析不了,或者里面的应用清单去不掉": null, "%s:模拟器日志 %d 份,logcat %d 份(各取最新 %d 份)": null, "%s:诊断开机失败现场 %d 个,%s": null, "%s:诊断日志超过 %s,丢掉了最旧的 %d 份": null, diff --git a/internal/i18n/locales/en/ui.json b/internal/i18n/locales/en/ui.json index d425b3d6..32c25e01 100644 --- a/internal/i18n/locales/en/ui.json +++ b/internal/i18n/locales/en/ui.json @@ -68,7 +68,7 @@ "保存主题设置失败: %v": "Cannot save the theme setting: %v", "保存语言设置失败: %v": "Cannot save the language setting: %v", "修改设置": "changing settings", - "先关掉它们(比如用 modavd mcp 的 AI 助手、别的命令行窗口);%v": "Close them first (for example an AI assistant that uses modavd mcp, or other command-line windows); %v", + "先关掉它们(比如别的命令行窗口);%v": "Close them first (for example other command-line windows); %v", "先用 GET /api/components/license 取许可协议(和这次一样的下载源),把它的 license_sha256 原样带上": "First get the license agreement with GET /api/components/license (same download source as this request), and send its license_sha256 back unchanged", "先阅读许可协议,再发送 accept_license: true": "Read the license agreement first, then send accept_license: true", "关掉管理器后运行 tools\\modavd.exe update install": "Close the manager and run tools\\modavd.exe update install", @@ -114,7 +114,7 @@ "实例 %d 截图失败: %s": "Instance %d screenshot failed: %s", "实例 %d 截图的数据不是 PNG(%d 字节)": "The screenshot data of instance %d is not a PNG (%d bytes)", "实例 %d 截图超时(%.0f 秒)": "Instance %d screenshot timed out (%.0f s)", - "实例 %d 本来就没开机": "Instance %d was not running", + "实例 %d 共享内存截图失败: %v": "Instance %d shared-memory capture failed: %v", "实例 %d 正在%s(任务 %s),等它做完再试": "Instance %d is busy (%s, task %s). Try again when it finishes", "实例 %d 正在%s,一台实例都没关": "Instance %d is busy (%s); no instance was shut down", "实例 %d 正在%s,等它做完再试": "Instance %d is busy (%s). Try again when it finishes", @@ -171,6 +171,10 @@ "当前平台暂不支持打开目录或浏览器": "Opening a folder or browser is not supported on this platform yet", "当前平台暂不支持窗口操作": "Window operations are not supported on this platform yet", "当前平台没有托盘图标和老板键": "This platform has no tray icon or boss key", + "取不到画面": "Cannot get the screen", + "实例 %d ADB 截图失败: %v": "Instance %d ADB screenshot failed: %v", + "实例 %d 本来就没开机": "Instance %d was already stopped", + "到顶栏「组件」检查共享内存截图组件和设置": "Open Components in the top bar to check shared-memory screenshots and their settings", "截图的显示尺寸读不出": "Cannot read the display size of the screenshot", "打不开管理器窗口: %v": "Cannot open the manager window: %v", "打开实例文件夹要给 index": "index is required to open an instance folder", diff --git a/internal/i18n/locales/en/update.json b/internal/i18n/locales/en/update.json index dd43ad8f..12ce3abf 100644 --- a/internal/i18n/locales/en/update.json +++ b/internal/i18n/locales/en/update.json @@ -280,7 +280,11 @@ "读不到": "unreadable", "读到了没取回的位置": "Read a position that was not fetched", "载荷版本清单与更新版本不一致": "The payload version manifest does not match the update version", - "还有程序在用模拟器或管理器的文件:%s。什么都没动,请先关掉所有实例、管理器(包括托盘里的,在托盘图标的菜单里退出)和 MCP 客户端再%s": "Programs are still using emulator or manager files: %s. Nothing was changed. Close all instances, managers (including the one in the tray: exit it from the tray icon menu), and MCP clients first, then %s", + "还有程序在用模拟器或管理器的文件:%s。什么都没动,请先关掉所有实例和管理器(包括托盘里的,在托盘图标的菜单里退出)再%s": "Programs are still using emulator or manager files: %s. Nothing was changed. Close all instances and managers (including the one in the tray: exit it from the tray icon menu) first, then %s", + "关掉这个根目录开着的 MCP 服务(%s),AI 助手下次调用时会用上新版": "Stopping the MCP servers of this root folder (%s); the AI assistant's next call uses the new version", + "MCP 服务(pid %d)%.0f 秒内没有退出,强制结束它": "The MCP server (pid %d) did not exit within %.0f s; force-stopping it", + "结束 MCP 服务(pid %d)失败(%v),什么都没动": "Could not end the MCP server (pid %d) (%v). Nothing was changed", + "通知 MCP 服务退出失败,什么都没动: %v": "Could not ask the MCP servers to exit. Nothing was changed: %v", "还没有准备好的新版,请先下载": "No prepared new version yet; download it first", "这个根目录在 mas-avd.json 里设了 sdkRoot(开发用的本地 SDK),不更新": "This root folder sets sdkRoot in mas-avd.json (a local SDK for development); not updating", "这个根目录正在更新": "This root folder is being updated", diff --git a/internal/i18n/locales/en/web.json b/internal/i18n/locales/en/web.json index c69a20a2..29d80d8d 100644 --- a/internal/i18n/locales/en/web.json +++ b/internal/i18n/locales/en/web.json @@ -83,7 +83,6 @@ "一开始就是 {gb} GB,按实际写入占电脑硬盘,不用管大小": "It is {gb} GB from the start and only takes as much space on the computer as is written; no need to care about the size", "一次最多选 {max} 个文件": "Select at most {max} files at a time", "一般要几分钟": "usually a few minutes", - "上次开机没有成功": "The last start failed", "上次补全中途失败,没能全部撤回:在「更多操作」里移除,或者再补全一次": "The last add failed halfway and could not be fully undone: remove it under “More actions”, or add it again", "下次开机生效。60 是默认;30 给锁 30 帧的游戏,帧间隔最匀;15 只适合纯挂机,整个系统都是 15 帧": "Takes effect at the next start. 60 is the default; 30 for games locked at 30 fps, the most even frame times; 15 only for idling, the whole system runs at 15 fps", "下次开机生效。要立即转屏,请点模拟器标题栏的旋转按钮。换分辨率时 DPI 会改成对应的默认值,自动化工具的分辨率也要跟着改。": "Changes take effect at the next start. To rotate now, use the emulator title bar. Changing the resolution resets DPI to its default. Update the resolution in your automation tool too.", @@ -160,6 +159,7 @@ "原因未知": "reason unknown", "去掉几个再保存": "Remove some, then save", "取不到画面": "Cannot get the screen", + "画面的像素数据不完整": "The screen frame has incomplete pixel data", "取消": "Cancel", "取消复制": "Cancel copy", "取消整理": "Cancel compacting", @@ -247,7 +247,8 @@ "实例运行中,内存、CPU、帧率、分辨率、DPI、数据盘和声音在下次开机生效。诊断设置立即生效。": "The instance is running. Memory, CPU, frame rate, resolution, DPI, data disk and sound take effect at the next start; the diagnostics setting takes effect at once.", "实例里没有装别的应用": "No other apps are installed in the instance", "实例里的 Google 服务框架联网登记后才有:开着网等一两分钟,再试一次。": "It exists once Google Services Framework in the instance has registered online: stay online for a minute or two, then try again.", - "实时 · 约 2 帧/秒": "Live · about 2 frames/s", + "目标 {fps} 帧/秒": "Target: {fps} fps", + "目标帧率": "Target frame rate", "实时画面,可以点按": "Live screen, you can tap it", "实时跟随": "Follow live", "实验功能,要用的话在实例的「更多操作」菜单里开启": "Experimental. To use it, turn it on from the instance's “More actions” menu", @@ -376,7 +377,6 @@ "新建失败:{reason}": "Create failed: {reason}", "新建实例": "Create instance", "新建时会在后台开机做完初始化再关机,一般要几分钟。": "Creating starts it in the background, runs initial setup and shuts it down; this usually takes a few minutes.", - "新建时的初始化没做完": "Initial setup did not finish", "新建的实例不带商店,要用的实例在「更多操作」里补全。": "New instances come without the store. To use it on an instance, add it under “More actions”.", "新建第一台实例": "Create the first instance", "方向": "Orientation", @@ -488,7 +488,6 @@ "没有导入:{reason}": "Not imported: {reason}", "没有成功": "Failed", "没有找到 MuMu 或雷电实例": "No MuMu or LDPlayer instances found", - "没有画面": "No screen", "没有移除干净,可以再移除一次": "It was not fully removed; you can remove it again", "没有第三方应用": "No third-party apps found", "没能先保存数据就关掉了": "It was stopped without saving the data first", diff --git a/internal/mcp/mcp.go b/internal/mcp/mcp.go index 0745f94b..62147cde 100644 --- a/internal/mcp/mcp.go +++ b/internal/mcp/mcp.go @@ -14,7 +14,8 @@ // that context and suppresses everything still to be sent for the request. Instances are never stopped by the server: // cancelling start_instance only stops waiting (killing qemu would lose guest data). // -// Shutdown, at EOF on in or when ctx ends: nothing more is written, and every call is canceled (start / stop just stop +// Shutdown, at EOF on in, when ctx ends or when an update of the root asks the server to exit (Options.Exit): nothing +// more is written, and every call is canceled (start / stop just stop // waiting) except the tools that write files without stopping half way (create / update / delete_instance, // install_apk, compact_disk, set_app_proxy). The process exits right after Serve returns, so those get up to // shutdownWait (30 s) to finish first: @@ -56,6 +57,9 @@ type Options struct { Version string // Log is the server's own diagnostics (stderr). Never stdout: stdout carries the protocol only. Log *logx.Logger + // Exit, when closed, ends the server the way EOF on in does (Serve returns nil): an update of the root is about to + // replace this program, and the client's next call starts the new one (update.WatchMCPExit). nil: never. + Exit <-chan struct{} } // instructions is handed to the model by the client (initialize / server/discover). @@ -78,8 +82,8 @@ const ( shutdownGrace = 2 * time.Second ) -// Serve reads requests from in and writes responses / notifications to out until in reaches EOF (returns nil) or -// ctx ends (errs.Canceled). Either way it returns only after the file-writing calls in flight have finished, at most +// Serve reads requests from in and writes responses / notifications to out until in reaches EOF or Options.Exit is +// closed (returns nil) or ctx ends (errs.Canceled). Either way it returns only after the file-writing calls in flight have finished, at most // about shutdownWait later (see the package comment). func Serve(ctx context.Context, in io.Reader, out io.Writer, opt Options) error { if opt.NewManager == nil { @@ -101,6 +105,7 @@ func Serve(ctx context.Context, in io.Reader, out io.Writer, opt Options) error type server struct { newBackend func(log *logx.Logger) (backend, error) log *logx.Logger + exit <-chan struct{} // Options.Exit info implementation tools []*toolDef byName map[string]*toolDef @@ -158,6 +163,7 @@ func newServer(opt Options, newBackend func(log *logx.Logger) (backend, error)) s := &server{ newBackend: newBackend, log: opt.Log, + exit: opt.Exit, info: implementation{Name: "modavd", Title: "ModAVD", Version: version}, tools: toolDefs(), byName: map[string]*toolDef{}, @@ -219,6 +225,10 @@ func (s *server) serve(ctx context.Context, in io.Reader, out io.Writer) error { return nil } return errs.Wrap(errs.Internal, err, "读取标准输入失败") + case <-s.exit: + s.log.Infof("ModAVD 正在更新,MCP 服务退出;客户端重新连接后用的就是新版") + s.shutdown(cancelAll, cancelKeep) + return nil case <-ctx.Done(): s.log.Infof("MCP 服务被中止") s.shutdown(cancelAll, cancelKeep) diff --git a/internal/mcp/mcp_test.go b/internal/mcp/mcp_test.go index 6ca9ede3..363bf0b7 100644 --- a/internal/mcp/mcp_test.go +++ b/internal/mcp/mcp_test.go @@ -1410,6 +1410,68 @@ func TestEOFLetsWritesFinish(t *testing.T) { } } +// TestUpdateExitShutsDown: an update's request to exit (Options.Exit) shuts the server down the way EOF does: the +// running start is canceled, the delete finishes first, nothing more is written, Serve returns nil and says why. +func TestUpdateExitShutsDown(t *testing.T) { + deleting := make(chan struct{}) + release := make(chan struct{}) + deleteCtx := make(chan error, 1) + startCtx := make(chan error, 1) + f := &fake{ + del: func(ctx context.Context, i int) (*emu.DeleteResult, error) { + close(deleting) + <-release + deleteCtx <- ctx.Err() + return &emu.DeleteResult{Index: i}, nil + }, + start: func(ctx context.Context, i int, opt emu.StartOptions) (*emu.StartResult, error) { + <-ctx.Done() + startCtx <- ctx.Err() + return nil, errs.Wrap(errs.Canceled, ctx.Err(), "已取消") + }, + } + exit := make(chan struct{}) + h := newHarness(t, f, func(s *server) { s.exit = exit }) + h.sendJSON(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": modernParams( + map[string]any{"name": "start_instance", "arguments": map[string]any{"index": 1}}, nil)}) + h.sendJSON(map[string]any{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": modernParams( + map[string]any{"name": "delete_instance", "arguments": map[string]any{"index": 2, "confirm": true}}, nil)}) + <-deleting + waitCalls(t, f, 2) + close(exit) + select { + case err := <-startCtx: + if err != context.Canceled { + t.Fatalf("start ctx %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("the start was not canceled") + } + select { + case err := <-h.done: + t.Fatalf("Serve returned (%v) while the delete was still running", err) + case <-time.After(150 * time.Millisecond): + } + close(release) + if err := <-deleteCtx; err != nil { + t.Fatalf("the delete was canceled: %v", err) + } + select { + case err := <-h.done: + if err != nil { + t.Fatalf("Serve after the exit request: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("Serve did not return once the delete was done") + } + for line := range h.lines { + t.Fatalf("output after the exit request: %s", line) + } + if !h.logs.contains("ModAVD 正在更新,MCP 服务退出") || !h.logs.contains("等 1 个正在写文件的请求做完再退出") { + t.Fatalf("exit not logged: %v", h.logs.lines) + } +} + // TestShutdownWaitIsBounded: a write that does not finish in time is canceled and Serve returns anyway. func TestShutdownWaitIsBounded(t *testing.T) { deleting := make(chan struct{}) diff --git a/internal/report/collect.go b/internal/report/collect.go index 8208db91..ddd3d0c8 100644 --- a/internal/report/collect.go +++ b/internal/report/collect.go @@ -697,10 +697,14 @@ func (c *collector) instanceFiles() error { dst := filepath.Join(c.stage, root.MetadataFile) if c.opt.Instances == nil { err = copyMetadata(cfgPath, dst) + } else if c.selectedMetadata != nil && hasProxyPackages(c.selectedMetadata) { + err = errMetadataWithheld } else if c.selectedMetadata != nil { err = os.WriteFile(dst, c.selectedMetadata.MarshalPython(), 0600) } - if err != nil { + if errors.Is(err, errMetadataWithheld) { + c.L("未附 mas-avd.json:它解析不了,或者里面的应用清单去不掉") + } else if err != nil { c.L("复制 mas-avd.json 失败:" + errText(err)) } } else { diff --git a/internal/report/parity_windows_test.go b/internal/report/parity_windows_test.go index 8e444071..abc02801 100644 --- a/internal/report/parity_windows_test.go +++ b/internal/report/parity_windows_test.go @@ -19,6 +19,7 @@ import ( "time" "modavd/internal/buildinfo" + "modavd/internal/jsonord" "modavd/internal/root" "modavd/internal/testutil" ) @@ -389,6 +390,15 @@ func TestCollectMatchesScript(t *testing.T) { t.Errorf("%s: %v", entry, err) continue } + if entry == root.MetadataFile { + // the report writes the parsed file back out, not the bytes it read + v, err := jsonord.Parse(want) + if err != nil { + t.Errorf("%s: %v", entry, err) + continue + } + want = v.MarshalPython() + } if f.sc.Limits != nil && int64(len(want)) > f.sc.Limits.MasTail && strings.HasPrefix(entry, "mas/") { want = want[int64(len(want))-f.sc.Limits.MasTail:] } diff --git a/internal/report/proxypackages_windows_test.go b/internal/report/proxypackages_windows_test.go index d1bc4e2f..4dbc781f 100644 --- a/internal/report/proxypackages_windows_test.go +++ b/internal/report/proxypackages_windows_test.go @@ -4,6 +4,7 @@ package report import ( "context" + "errors" "os" "path/filepath" "strings" @@ -73,18 +74,196 @@ func TestCollectDropsProxyPackages(t *testing.T) { } } -// A mas-avd.json that does not parse is copied as it is in a full report (it was before). -func TestCopyMetadataBadFile(t *testing.T) { - dir := testTempDir(t) - src, dst := filepath.Join(dir, "src.json"), filepath.Join(dir, "dst.json") - const bad = `{"instances": {"1": {"appProxyPackages": [` - if err := os.WriteFile(src, []byte(bad), 0o644); err != nil { +// A mas-avd.json that does not parse is not copied at all, whether or not it seems to have app lists; so is one +// with an app list where dropProxyPackages does not look. A parsed file is copied from the parsed tree, with the +// lists taken out under any spelling of the key. +func TestCopyMetadata(t *testing.T) { + const marker = "com.example.secret-app" + for _, tc := range []struct { + name, text string + withheld bool + }{ + {"broken with lists", `{"instances": {"1": {"appProxyPackages": [{"package":"` + marker + `"`, true}, + {"broken without lists", `{"instances": {"1": {"memoryMb": 4096`, true}, + {"empty", ``, true}, + {"not an object", `[1, 2]`, true}, + {"lists elsewhere", `{"instances": [{"appProxyPackages": [{"package":"` + marker + `"}]}]}`, true}, + {"lists at top level", `{"appProxyPackages": [{"package":"` + marker + `"}], "instances": {}}`, true}, + {"plain", `{"instances": {"1": {"memoryMb": 4096}}}`, false}, + {"escaped key", `{"instances": {"1": {"memoryMb": 4096, "\u0061ppProxyPackages": [{"package":"` + marker + `"}]}}}`, false}, + {"other case", `{"instances": {"1": {"memoryMb": 4096, "APPPROXYPACKAGES": [{"package":"` + marker + `"}], "appproxypackages": []}}}`, false}, + {"escaped instances", `{"\u0049nstances": {"1": {"memoryMb": 4096, "\u0041ppProxy\u0050ackages": [{"package":"` + marker + `"}]}}}`, false}, + {"with BOM", "\xef\xbb\xbf" + `{"instances": {"1": {"memoryMb": 4096, "appProxyPackages": [{"package":"` + marker + `"}]}}}`, false}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := testTempDir(t) + src, dst := filepath.Join(dir, "src.json"), filepath.Join(dir, "dst.json") + if err := os.WriteFile(src, []byte(tc.text), 0o644); err != nil { + t.Fatal(err) + } + err := copyMetadata(src, dst) + b, readErr := os.ReadFile(dst) + if tc.withheld { + if !errors.Is(err, errMetadataWithheld) { + t.Errorf("err = %v, want errMetadataWithheld", err) + } + if readErr == nil { + t.Errorf("dst was written: %q", b) + } + return + } + if err != nil { + t.Fatal(err) + } + if strings.Contains(strings.ToLower(string(b)), strings.ToLower(appproxy.PackagesMetaKey)) || strings.Contains(string(b), marker) { + t.Errorf("the copy has the app list: %s", b) + } + if _, err := jsonord.Parse(b); err != nil { + t.Fatalf("the copy does not parse: %v\n%s", err, b) + } + if !strings.Contains(string(b), "4096") { + t.Errorf("other keys are gone: %s", b) + } + }) + } +} + +// TestCollectDropsProxyPackagesAnySpelling: a full report of a mas-avd.json that spells the key in a way the file's +// writer never does (an escaped letter, other case, duplicates) has none of the app list in the ZIP. +func TestCollectDropsProxyPackagesAnySpelling(t *testing.T) { + f := newFixture(t, "full", testTempDir(t), "") + guardDials(t, f.adbPort) + meta := filepath.Join(f.root, root.MetadataFile) + b, err := os.ReadFile(meta) + if err != nil { + t.Fatal(err) + } + v, err := jsonord.Parse(b) + if err != nil { + t.Fatal(err) + } + const marker = "com.example.secret-app" + pkgs, err := jsonord.Parse([]byte(`[{"package":"` + marker + `","name":"Secret","uid":10123,"system":false}]`)) + if err != nil { t.Fatal(err) } - if err := copyMetadata(src, dst); err != nil { + inst := v.Obj().Get("instances").Obj().Get("1").Obj() + inst.Set("ZZESCAPED", pkgs) + inst.Set("ZZUPPER", pkgs) + inst.Set("ZZMIXED", pkgs) + text := strings.NewReplacer( + `"ZZESCAPED"`, `"\u0061ppProxyPackages"`, + `"ZZUPPER"`, `"APPPROXYPACKAGES"`, + `"ZZMIXED"`, `"AppProxy\u0050ackages"`, + `"instances"`, `"\u0049nstances"`, + ).Replace(string(v.MarshalPython())) + if !strings.Contains(text, `\u0061ppProxyPackages`) || !strings.Contains(text, `\u0049nstances`) { + t.Fatal("the fixture was not rewritten") + } + if err := os.WriteFile(meta, []byte(text), 0o644); err != nil { + t.Fatal(err) + } + res, err := collect(context.Background(), f.root, f.host, CollectOptions{ + OutDir: filepath.Join(f.base, "out"), StageDir: filepath.Join(f.base, "stage"), NoExplorer: true, + now: func() time.Time { return f.now }, getenv: f.getenv, pid: 4321, + }) + if err != nil { t.Fatal(err) } - if b, _ := os.ReadFile(dst); string(b) != bad { - t.Errorf("got %q", b) + _, files := readZip(t, res.ZipPath) + out, ok := files[root.MetadataFile] + if !ok { + t.Fatal("no mas-avd.json in the archive") + } + for name, data := range files { + if strings.Contains(string(data), marker) { + t.Errorf("%s in the archive has the app list", name) + } + } + if strings.Contains(strings.ToLower(string(out)), "proxypackages") { + t.Errorf("the archive's mas-avd.json still has the key:\n%s", out) + } + got, err := jsonord.Parse(out) + if err != nil { + t.Fatal(err) + } + if !got.Obj().Get("Instances").Obj().Get("1").Obj().Has("memoryMb") { + t.Errorf("other keys of instance 1 are gone:\n%s", out) + } +} + +// TestCollectScopedWithholdsStrayLists: a scoped report of a mas-avd.json with an app list where dropProxyPackages +// does not look (here at the top level) has no mas-avd.json and nothing of the list anywhere in the ZIP. +func TestCollectScopedWithholdsStrayLists(t *testing.T) { + f := newFixture(t, "full", testTempDir(t), "") + guardDials(t, f.adbPort) + meta := filepath.Join(f.root, root.MetadataFile) + b, err := os.ReadFile(meta) + if err != nil { + t.Fatal(err) + } + const marker = "com.example.secret-app" + stray := strings.Replace(string(b), `"instances"`, `"appProxyPackages": [{"package": "`+marker+`"}], "instances"`, 1) + if stray == string(b) { + t.Fatal("the fixture was not rewritten") + } + if err := os.WriteFile(meta, []byte(stray), 0o644); err != nil { + t.Fatal(err) + } + res, err := collect(context.Background(), f.root, f.host, CollectOptions{ + Instances: []int{1}, OutDir: filepath.Join(f.base, "out"), StageDir: filepath.Join(f.base, "stage"), NoExplorer: true, + now: func() time.Time { return f.now }, getenv: f.getenv, pid: 4321, + }) + if err != nil { + t.Fatal(err) + } + _, files := readZip(t, res.ZipPath) + if _, ok := files[root.MetadataFile]; ok { + t.Error("the archive has mas-avd.json") + } + for name, data := range files { + if strings.Contains(string(data), marker) { + t.Errorf("%s in the archive has the app list", name) + } + } +} + +// TestCollectWithholdsBrokenMetadata: a full report of a root whose mas-avd.json has app lists but does not +// parse has no mas-avd.json and nothing of the lists anywhere in the ZIP, and says why in its log. +func TestCollectWithholdsBrokenMetadata(t *testing.T) { + f := newFixture(t, "full", testTempDir(t), "") + guardDials(t, f.adbPort) + meta := filepath.Join(f.root, root.MetadataFile) + b, err := os.ReadFile(meta) + if err != nil { + t.Fatal(err) + } + const marker = "com.example.secret-app" + broken := strings.Replace(string(b), `"instances"`, `"appProxyPackages": [{"package": "`+marker+`"}], "instances"`, 1) + broken = strings.TrimRight(broken, " \r\n") + broken = broken[:len(broken)-1] // cut the closing brace: it no longer parses + if err := os.WriteFile(meta, []byte(broken), 0o644); err != nil { + t.Fatal(err) + } + res, err := collect(context.Background(), f.root, f.host, CollectOptions{ + OutDir: filepath.Join(f.base, "out"), StageDir: filepath.Join(f.base, "stage"), NoExplorer: true, + now: func() time.Time { return f.now }, getenv: f.getenv, pid: 4321, + }) + if err != nil { + t.Fatal(err) + } + _, files := readZip(t, res.ZipPath) + if _, ok := files[root.MetadataFile]; ok { + t.Error("the archive has mas-avd.json") + } + said := false + for name, data := range files { + if strings.Contains(string(data), marker) { + t.Errorf("%s in the archive has the app list", name) + } + said = said || strings.Contains(string(data), "未附 mas-avd.json") + } + if !said { + t.Error("nothing in the archive says mas-avd.json was left out") } } diff --git a/internal/report/selection.go b/internal/report/selection.go index 15231379..9bda2db7 100644 --- a/internal/report/selection.go +++ b/internal/report/selection.go @@ -3,6 +3,7 @@ package report import ( "bytes" "encoding/json" + "errors" "io" "os" "path/filepath" @@ -52,7 +53,8 @@ func (opt CollectOptions) selectionSummary(available []int) []string { return []string{"已选实例:" + names(opt.Instances), "未选实例:" + names(omitted)} } -// dropProxyPackages removes instances..appProxyPackages (the apps installed in the guest) from mas-avd.json. +// dropProxyPackages removes instances..appProxyPackages (the apps installed in the guest) from mas-avd.json. Keys +// are matched on their decoded text and without regard to case, the way encoding/json reads the file back. func dropProxyPackages(v *jsonord.Value) { for _, key := range v.Obj().Keys() { if !strings.EqualFold(key, "instances") { @@ -60,26 +62,67 @@ func dropProxyPackages(v *jsonord.Value) { } instances := v.Obj().Get(key).Obj() for _, k := range instances.Keys() { - instances.Get(k).Obj().Delete(appproxy.PackagesMetaKey) + inst := instances.Get(k).Obj() + for _, name := range inst.Keys() { + if strings.EqualFold(name, appproxy.PackagesMetaKey) { + inst.Delete(name) + } + } } } } -// copyMetadata copies mas-avd.json into a full report without the app lists. A file that does not parse is -// copied as it is. +// hasProxyPackages reports whether an app list key is anywhere in v, at any depth. +func hasProxyPackages(v *jsonord.Value) bool { + switch v.Kind() { + case jsonord.Object: + for _, key := range v.Obj().Keys() { + if strings.EqualFold(key, appproxy.PackagesMetaKey) || hasProxyPackages(v.Obj().Get(key)) { + return true + } + } + case jsonord.Array: + for _, item := range v.Items() { + if hasProxyPackages(item) { + return true + } + } + } + return false +} + +// errMetadataWithheld: mas-avd.json does not parse, or still has app lists after dropProxyPackages (they are +// somewhere it does not look), so the report goes without it. +var errMetadataWithheld = errors.New("mas-avd.json could not be cleaned of app lists") + +// copyMetadata copies mas-avd.json into a full report without the app lists. The file is read and cleaned outside +// the report's staging folder, and only the clean copy is written to dst. Nothing is decided on the raw text, where +// one key can be spelled several ways: the file is parsed, the app lists are taken out of the parsed tree, and the +// copy is written from that tree. When the file does not parse, or the tree still has an app list, nothing is +// written and errMetadataWithheld is returned. func copyMetadata(src, dst string) error { - if _, err := copyShared(src, dst, 0); err != nil { + tmp, err := os.CreateTemp("", "modavd-meta-*.json") + if err != nil { return err } - data, err := os.ReadFile(dst) - if err != nil || !bytes.Contains(data, []byte(appproxy.PackagesMetaKey)) { - return nil + tmpPath := tmp.Name() + tmp.Close() + defer os.Remove(tmpPath) + if _, err := copyShared(src, tmpPath, 0); err != nil { + return err + } + data, err := os.ReadFile(tmpPath) + if err != nil { + return err } v, err := jsonord.Parse(bytes.TrimPrefix(data, []byte{0xef, 0xbb, 0xbf})) if err != nil || v.Kind() != jsonord.Object { - return nil + return errMetadataWithheld } dropProxyPackages(v) + if hasProxyPackages(v) { + return errMetadataWithheld + } return os.WriteFile(dst, v.MarshalPython(), 0600) } diff --git a/internal/ui/API.en.md b/internal/ui/API.en.md index 53dd4bd5..85784830 100644 --- a/internal/ui/API.en.md +++ b/internal/ui/API.en.md @@ -44,7 +44,7 @@ GET `/api/keymap/vendor-sources?vendor=ldplayer` lists installations. Add `sourc | Method | Path | Request | Response | | --- | --- | --- | --- | -| GET | `/api/info` | | `{"version","protocol","root":RootInfo}` | +| GET | `/api/info` | | `{"version","protocol","root":RootInfo,"live_screenshots":bool}` | | GET | `/api/locale` | | `{"language","preference","system","languages":[{code,name}],"messages"}`: the language the manager shows now (`zh-CN` / `en`), the one chosen in the settings (`auto` follows the system), what `auto` picks, the languages on offer, and the translations of the page's own strings (keyed by the Chinese text; `{}` in Chinese). Text the back end sends to the page (errors, progress, logs, check items) is already translated into `language`; the CLI's `--json`, MCP, logs and problem reports are not translated and stay Chinese | | PUT | `/api/locale` | `{preference: "auto"\|"zh-CN"\|"en"}` | as above; saved for this Windows user in `%LOCALAPPDATA%\ModAVD\language.json` (the CLI follows it too); the manager switches at once and the page reloads | | GET | `/api/theme` | | `{"preference","saved"}`: the interface theme (`system` follows the system, `light`, `dark`); `saved` is `false` while none has been saved (it reads as `system`), and the page then moves its browser's old choice over once | @@ -70,7 +70,8 @@ GET `/api/keymap/vendor-sources?vendor=ldplayer` lists installations. Add `sourc | POST | `/api/instances/{i}/gles32-off` | `{}` | 202 `Job` (`kind` is `gles32-off`): removes the line written above; after a cold boot the instance reports 3.1 again (same as `gles32 off`); the result is a `GLES32Result`. The checks are the same as for `gles32-on` | | GET | `/api/instances/{i}/playstore-gsfid` | | `{"index","decimal","hex"}`: the GSF ID of a running instance (same as `modavd playstore gsfid --json`; the decimal form is what GSF records, the hex form is the same number, with negative numbers in two's complement); takes a few seconds. Used to register at https://www.google.com/android/uncertified/. If the instance is not running (according to the latest list) or a job is running on it, it is 409 `busy`; if there is no ID yet it is 422 `not_ready` with `details.reason` `no_gsf_id` (stay online for a minute or two and try again) | | POST | `/api/instances/{i}/input` | `{type:"tap", x, y}` (the coordinates are in the pixels this instance displays (1280×720 or 1920×1080, with width and height swapped in portrait)) or `{type:"key", key:"back"\|"home"\|"recents"}` | `{}` | -| GET | `/api/instances/{i}/screenshot` | | `image/png` in the current display orientation (a shared-memory frame is turned by the instance's orientation setting while the guest's rotation is not known yet), `X-Shot-Source: shm` for shared memory or `adb` for `adb exec-out screencap -p`, `Cache-Control: no-store`; 409 if the instance is not running | +| GET | `/api/instances/{i}/screenshot` | Optional query `after` with the previous `X-Shot-Frame` value (empty on the first live request) | On Windows, shared-memory `image/png` in the current display orientation and `X-Shot-Frame` when available. 204 when the requested frame is unchanged, 409 when not booted, or an error when shared memory is unavailable. `Cache-Control: no-store`. Uses the instance orientation setting until the guest rotation is known. macOS uses adb capture. | +| GET | `/api/instances/{i}/screenshot?format=rgba` | Windows screen viewer, with the same optional `after` query | `application/octet-stream` with shared-memory RGBA pixels in their original row order. `X-Shot-Width` and `X-Shot-Height` are the raw pixel dimensions, `X-Shot-Stride` is the row size in bytes, and `X-Shot-Rotation` is the counterclockwise rotation in degrees (0, 90, 180, 270). When available, `X-Shot-Frame` includes rotation. 204 for an unchanged frame, 409 when not booted, or an error when shared memory is unavailable. | | GET | `/api/instances/{i}/log?kind=emulator\|logcat&lines=300` | | `text/plain; charset=utf-8`, the tail of the newest log; 404 if there is none | | GET | `/api/instances/{i}/proxy` | | `ProxyView`, see below | | PUT | `/api/instances/{i}/proxy` | `{enabled?: bool, server?: string, apps?: [string]}` | `ProxyView`: the items given are replaced with the new values, the ones not given stay unchanged; giving no item at all returns 400 `usage`. `server` may omit the protocol (it is detected) or be `auto` (take this computer's proxy settings); when it is turned on for the first time without an address, `auto` is used as well. If the address cannot be probed, 502 `proxy_unavailable`. If the instance is running, it takes effect immediately and returns within a few seconds | diff --git a/internal/ui/API.md b/internal/ui/API.md index 97d315f6..f43e344a 100644 --- a/internal/ui/API.md +++ b/internal/ui/API.md @@ -44,7 +44,7 @@ GET `/api/keymap/vendor-sources?vendor=ldplayer` 列出安装,带 `sourceInsta | 方法 | 路径 | 请求 | 返回 | | --- | --- | --- | --- | -| GET | `/api/info` | | `{"version","protocol","root":RootInfo}` | +| GET | `/api/info` | | `{"version","protocol","root":RootInfo,"live_screenshots":bool}` | | GET | `/api/locale` | | `{"language","preference","system","languages":[{code,name}],"messages"}`:管理器现在用的语言(`zh-CN` / `en`)、设置里选的(`auto` 是跟随系统)、跟随系统时会选哪种、可选的语言,以及页面自己那部分字符串的译文(键是中文原文,中文时是 `{}`)。后端发给页面的文字(错误、进度、日志、检查项)已经按 `language` 翻好;命令行 `--json`、MCP、日志和问题包不翻,照旧是中文 | | PUT | `/api/locale` | `{preference: "auto"\|"zh-CN"\|"en"}` | 同上;记进这个 Windows 用户的 `%LOCALAPPDATA%\ModAVD\language.json`(命令行也按它选),管理器马上换语言,页面随后重新加载 | | GET | `/api/theme` | | `{"preference","saved"}`:界面主题(`system` 跟随系统 / `light` / `dark`),`saved` 是 `false` 时还没存过(按 `system`),页面会把自己浏览器里旧的选择搬过来一次 | @@ -70,7 +70,8 @@ GET `/api/keymap/vendor-sources?vendor=ldplayer` 列出安装,带 `sourceInsta | POST | `/api/instances/{i}/gles32-off` | `{}` | 202 `Job`(`kind` 是 `gles32-off`):去掉上面写进去的行,冷启动后实例改回报 3.1(同 `gles32 off`);结果是 `GLES32Result`。检查同 `gles32-on` | | GET | `/api/instances/{i}/playstore-gsfid` | | `{"index","decimal","hex"}`:开着的实例的 GSF ID(同 `modavd playstore gsfid --json`;十进制是 GSF 记的,十六进制是同一个数,负数按补码),几秒钟。用来到 https://www.google.com/android/uncertified/ 登记。没开机(按最近的列表)或实例上有任务在跑是 409 `busy`;还没有 ID 是 422 `not_ready`,`details.reason` 为 `no_gsf_id`(开着网等一两分钟再试) | | POST | `/api/instances/{i}/input` | `{type:"tap", x, y}`(坐标是这台实例显示的像素(1280×720 或 1920×1080,竖屏时宽高对调))或 `{type:"key", key:"back"\|"home"\|"recents"}` | `{}` | -| GET | `/api/instances/{i}/screenshot` | | 当前显示方向的 `image/png`(共享内存的帧在客体方向暂时读不到时按实例设置的方向转),`X-Shot-Source` 为 `shm`(共享内存)或 `adb`(`adb exec-out screencap -p`),`Cache-Control: no-store`;没开机回 409 | +| GET | `/api/instances/{i}/screenshot` | 可选查询参数 `after`,填上次返回的 `X-Shot-Frame`,实时取图的首次请求留空 | Windows 上共享内存的当前方向 `image/png` 和帧标识 `X-Shot-Frame`(可用时)。帧没变回 204,没开机回 409,共享内存不可用时报错。`Cache-Control: no-store`。读到客体方向前按实例设置的方向转。macOS 仍使用 adb 截图。 | +| GET | `/api/instances/{i}/screenshot?format=rgba` | Windows 画面弹窗使用,可选 `after` 同上 | `application/octet-stream`,共享内存的 RGBA 像素,按原始行顺序发送。响应头 `X-Shot-Width`、`X-Shot-Height` 是原始像素尺寸,`X-Shot-Stride` 是每行字节数,`X-Shot-Rotation` 是逆时针旋转角度(0、90、180、270)。`X-Shot-Frame`(可用时)包括方向,帧没变回 204。未开机回 409,共享内存不可用时报错。 | | GET | `/api/instances/{i}/log?kind=emulator\|logcat&lines=300` | | `text/plain; charset=utf-8`,最新那份日志的末尾;没有回 404 | | GET | `/api/instances/{i}/proxy` | | `ProxyView`,见下 | | PUT | `/api/instances/{i}/proxy` | `{enabled?: bool, server?: string, apps?: [string]}` | `ProxyView`:给出的项换成新值,没给的不变;一项都没给回 400 `usage`。`server` 可以不写协议(探测出来)或写 `auto`(取这台电脑的代理设置);第一次打开没给地址也按 `auto`。地址探测不到回 502 `proxy_unavailable`。实例开着就马上生效,几秒内回 | @@ -124,7 +125,7 @@ GET `/api/keymap/vendor-sources?vendor=ldplayer` 列出安装,带 `sourceInsta - `progress.step`:开机用 emu 的 `launch` / `boot` / `tune` / `ime` / `first_boot` / `vulkan_fix` / `done`;关机(含等被取消的开机停下)是 `stop`,安装是 `install`,这两种做完是 `done`;整理磁盘进行中是 `disk_compact`、做完是 `done`;复制实例是 `copy`(`done` / `total` 按复制的字节折成千分比)(进行中没有百分比,`total` 为 0,页面显示不定长进度条;做完 `done` = `total` = 1000);装执行桥的每一轮是 `bridge`;商店的装、卸进行中是 `playstore-install` / `playstore-uninstall`(没有百分比)、做完是 `done`;导入时核对文件是 `verifying`、解压镜像是 `extracting`(`done` / `total` 是字节);新建是 `create`、其中几次开机的上述各步(开机做完是 `setup`)、`create_stop`、`done`,几次开机合成一条不回退的进度。`total` 一律 1000。 - 安装任务的 `result.apk` 是用户上传的文件名,不是服务端的临时路径(临时文件任务结束就删了)。 - `progress` 在没有进度时为 `null`;`result` 是 `StartResult` / `StopResult` / `InstallResult` / `DiskCompactResult` / `InstanceInfo`(新建)/ `PlayStoreResult` / `PlayStoreImportResult` / `GLES32Result`,没完成时为 `null`;`error` 失败时是错误对象,否则 `null`。 -- 页面怎么提示失败:卡片下面不放失败提示框。有任务失败(`state` 为 `failed`,什么种类都算;`canceled` 不算),或有实例是 `create_failed` 而管理器里没有它的新建任务(比如命令行建的),而这一条还没在「问题反馈」里看过时,顶栏的「问题反馈」入口和不能开机时的「组件」一样变红、一明一暗地闪,悬停和读屏说是哪几条。点开直接定位到最新的那条(在「最近任务和消息」里,带原因、建议,内存不够的带「调小内存」);没有任务的 `create_failed` 实例按任务的样子列在最上面。卡片上「开机失败」「新建失败」的状态标签悬停是原因和建议,点它(或按 Enter、空格)同样打开「问题反馈」定位到那条任务;没有任务的新建失败定位到最上面那台实例的那一行。抽屉里列出来就算看过,入口变回原样;看过的记在页面的 `localStorage`(`modavd.feedback.seen:<根目录>`,最近 100 条),刷新不会再闪。软件渲染、磁盘空间这类一直在的状态不算。失败时右下角的提示照旧。 +- 页面怎么提示失败:卡片下面不放失败提示框。有任务失败(`state` 为 `failed`,什么种类都算;`canceled` 不算),或有实例是 `create_failed` 而管理器里没有它的新建任务(比如命令行建的),而这一条还没在「问题反馈」里看过时,顶栏的「问题反馈」入口和不能开机时的「组件」一样变红、一明一暗地闪,悬停和读屏说是哪几条。点开直接定位到最新的那条(在「最近任务和消息」里,带原因、建议,内存不够的带「调小内存」);没有任务的 `create_failed` 实例按任务的样子列在最上面。卡片视图不显示状态标签(读屏照旧读得到状态名);「开机失败」「新建失败」时画面区写着失败,悬停是原因和建议,点画面区(或按 Enter、空格)打开「问题反馈」定位到那条任务(开机失败的重新开机在「更多」里;列表视图的状态标签照旧);没有任务的新建失败定位到最上面那台实例的那一行。抽屉里列出来就算看过,入口变回原样;看过的记在页面的 `localStorage`(`modavd.feedback.seen:<根目录>`,最近 100 条),刷新不会再闪。软件渲染、磁盘空间这类一直在的状态不算。失败时右下角的提示照旧。 `DiskCompactResult` 保留非负的 `freed_bytes`。`before_on_disk_bytes` 和 `after_on_disk_bytes` 是整理前后宿主实际占用,新增的 `on_disk_delta_bytes` 等于后者减前者,正值表示占用增大。`skipped=true` 表示检查通过、预计收益不足,未重写原盘;此时前后占用相等、变化和释放量均为零。结果还包含 `reclaim_threshold_bytes` 和可省略的 `estimated_reclaimable_bytes`,详见 [整理预算与结果契约](../emu/COMPACT.md)。 - 同一实例同时只能有一个任务在跑;第二个回 409 `busy`。**例外**:开机任务进行中可以发关机(和 emu 一致:开机中照样能关)。 diff --git a/internal/ui/backend.go b/internal/ui/backend.go index ce7940f5..4bff3421 100644 --- a/internal/ui/backend.go +++ b/internal/ui/backend.go @@ -53,7 +53,7 @@ type backend interface { // GLES32 is `modavd gles32 on|off|status`; GLES32Check what it refuses before touching the instance (no bridge ...). GLES32(ctx context.Context, i int, action string) (*emu.GLES32Result, error) GLES32Check(i int, action string) error - // AdbRun is Manager.ADB.Run (the screenshot: exec-out screencap -p with Raw). + // AdbRun supports screenshot capture on hosts without ModAVDExtras. AdbRun(ctx context.Context, opt adb.RunOptions, args ...string) adb.Result // Serial is instance i's adb serial in the root's port plan. Serial(i int) string diff --git a/internal/ui/device.go b/internal/ui/device.go index b3b01c70..3f0f4f71 100644 --- a/internal/ui/device.go +++ b/internal/ui/device.go @@ -11,13 +11,11 @@ import ( "sync" "time" - "modavd/internal/adb" "modavd/internal/emu" "modavd/internal/errs" ) const ( - shotTimeout = 10 * time.Second // shotReuse: a capture this young is served again; several views of one instance (list thumbnail, detail) then // cost one screencap. shotReuse = 300 * time.Millisecond @@ -26,8 +24,6 @@ const ( inputTimeout = 10 * time.Second ) -var pngSignature = []byte("\x89PNG\r\n\x1a\n") - // shotCache holds at most one capture in flight per instance and its last result. type shotCache struct { mu sync.Mutex @@ -35,12 +31,11 @@ type shotCache struct { } type shotEntry struct { - data []byte - src string // shotSourceShm or shotSourceAdb: where data came from - at time.Time - flight *shotCall - // shmSkip: no shared-memory attempt before this time (the last one failed: library absent, sharing off, old emulator) - shmSkip time.Time + data []byte + id string + at time.Time + flight *shotCall + failureLogged time.Time rotation *shotRotation rotationRetry time.Time rotationRevision uint64 @@ -49,18 +44,10 @@ type shotEntry struct { type shotCall struct { done chan struct{} data []byte - src string + id string err error } -const ( - // X-Shot-Source values: the page refreshes thumbnails of an unfocused window only when they come from shared memory. - shotSourceShm = "shm" - shotSourceAdb = "adb" - // shmRetry: how long after a failed shared-memory capture the instance goes straight to adb. - shmRetry = 20 * time.Second -) - func (c *shotCache) entry(i int) *shotEntry { if c.by == nil { c.by = map[int]*shotEntry{} @@ -87,29 +74,78 @@ func (s *server) handleScreenshot(w http.ResponseWriter, r *http.Request) { if !ok { return } - data, src, err := s.screenshot(r.Context(), i) + query := r.URL.Query() + if query.Get("format") == "rgba" { + s.handleRawScreenshot(w, r, i, query.Get("after")) + return + } + data, id, err := s.screenshot(r.Context(), i, query.Has("after")) if err != nil { writeError(w, err) return } h := w.Header() - h.Set("Content-Type", "image/png") - h.Set("X-Shot-Source", src) h.Set("Cache-Control", "no-store") + if id != "" && id == query.Get("after") { + w.WriteHeader(http.StatusNoContent) + return + } + h.Set("Content-Type", "image/png") + if id != "" { + h.Set("X-Shot-Frame", id) + } h.Set("Content-Length", strconv.Itoa(len(data))) w.WriteHeader(http.StatusOK) w.Write(data) } -// screenshot joins the capture in flight, reuses one younger than shotReuse, or starts one. The capture runs on the -// server's context, so a viewer that goes away does not fail the others waiting for it. -func (s *server) screenshot(ctx context.Context, i int) ([]byte, string, error) { +func (s *server) handleRawScreenshot(w http.ResponseWriter, r *http.Request, i int, after string) { + if !sharedMemoryScreenshots { + s.handleNoAPI(w, r) + return + } + if in, ok := s.hub.cachedInstance(i, statusMaxAge); ok && !in.Running { + writeError(w, notBooted(i)) + return + } + s.shots.mu.Lock() + e := s.shots.entry(i) + s.shots.mu.Unlock() + ctx := r.Context() + frame, rotation, id, err := s.readSharedFrame(i, e, mxFmtRGBA, func(id string) bool { return id == after }) + if ctx.Err() != nil { + return + } + if err != nil { + writeError(w, s.screenshotError(ctx, i, e, err)) + return + } + h := w.Header() + h.Set("Cache-Control", "no-store") + if id != "" && id == after { + w.WriteHeader(http.StatusNoContent) + return + } + h.Set("Content-Type", "application/octet-stream") + h.Set("Content-Length", strconv.Itoa(len(frame.pixels))) + h.Set("X-Shot-Width", strconv.Itoa(frame.width)) + h.Set("X-Shot-Height", strconv.Itoa(frame.height)) + h.Set("X-Shot-Stride", strconv.Itoa(frame.stride)) + h.Set("X-Shot-Rotation", strconv.Itoa(int(rotation)*90)) + if id != "" { + h.Set("X-Shot-Frame", id) + } + w.Write(frame.pixels) +} + +// Thumbnails and input validation can reuse a recent PNG and share its capture in flight. +func (s *server) screenshot(ctx context.Context, i int, live bool) ([]byte, string, error) { s.shots.mu.Lock() e := s.shots.entry(i) - if e.data != nil && time.Since(e.at) < shotReuse { - data, src := e.data, e.src + if !live && e.data != nil && time.Since(e.at) < shotReuse { + data, id := e.data, e.id s.shots.mu.Unlock() - return data, src, nil + return data, id, nil } call := e.flight if call == nil { @@ -120,30 +156,27 @@ func (s *server) screenshot(ctx context.Context, i int) ([]byte, string, error) s.shots.mu.Unlock() select { case <-call.done: - return call.data, call.src, call.err + return call.data, call.id, call.err case <-ctx.Done(): return nil, "", errs.Wrap(errs.Canceled, ctx.Err(), "已取消") } } func (s *server) capture(i int, e *shotEntry, call *shotCall) { - ctx, cancel := context.WithTimeout(s.ctx, shotTimeout) - defer cancel() s.shots.mu.Lock() - skip := time.Now().Before(e.shmSkip) revision := e.rotationRevision s.shots.mu.Unlock() - data, src, shmFailed, err := s.captureOnce(ctx, i, e, skip) + data, id, err := s.captureOnce(i, e) s.shots.mu.Lock() e.flight = nil - if shmFailed { - e.shmSkip = time.Now().Add(shmRetry) - } - if err == nil && (src != shotSourceShm || revision == e.rotationRevision) { - e.data, e.src, e.at = data, src, time.Now() + if err != nil { + e.data = nil + } else if revision == e.rotationRevision { + e.data, e.id, e.at = data, id, time.Now() + e.failureLogged = time.Time{} } s.shots.mu.Unlock() - call.data, call.src, call.err = data, src, err + call.data, call.id, call.err = data, id, err close(call.done) } @@ -152,38 +185,81 @@ func notBooted(i int) error { return errs.Newf(errs.Busy, "实例 %d 没有开机", i).WithAdvice("开机后再看画面") } -// captureOnce takes the frame from the emulator's shared memory when it can (unless skipShm), else from adb screencap. -// shmFailed: the shared-memory attempt was made and failed, so the caller holds the next ones back for a while. -func (s *server) captureOnce(ctx context.Context, i int, e *shotEntry, skipShm bool) (data []byte, src string, shmFailed bool, err error) { - // A recent list that says offline saves an adb call (which would also start the private adb server). +func (s *server) captureOnce(i int, e *shotEntry) ([]byte, string, error) { if in, ok := s.hub.cachedInstance(i, statusMaxAge); ok && !in.Running { - return nil, "", false, notBooted(i) + return nil, "", notBooted(i) + } + data, id, err := s.capturePlatformFrame(i, e) + if err != nil { + return nil, "", s.screenshotError(s.ctx, i, e, err) + } + return data, id, nil +} + +func (s *server) screenshotError(ctx context.Context, i int, e *shotEntry, err error) error { + s.shots.mu.Lock() + logFailure := time.Since(e.failureLogged) >= 30*time.Second + if logFailure { + e.failureLogged = time.Now() } - if !skipShm && s.frame != nil { - png, ferr := s.captureSharedFrame(i, e) - if ferr == nil { - return png, shotSourceShm, false, nil + s.shots.mu.Unlock() + if logFailure { + if sharedMemoryScreenshots { + s.log.Warnf("实例 %d 共享内存截图失败: %v", i, err) + } else { + s.log.Warnf("实例 %d ADB 截图失败: %v", i, err) } - shmFailed = true } - data, err = s.captureAdb(ctx, i) - if err == nil { - src = shotSourceAdb + ctx, cancel := context.WithTimeout(ctx, 6*time.Second) + defer cancel() + in, statusErr := s.instanceNow(ctx, i) + if statusErr != nil { + return statusErr + } + if !in.Booted { + return notBooted(i) + } + if !sharedMemoryScreenshots { + return err + } + return errs.New(errs.Internal, "取不到画面").WithAdvice("到顶栏「组件」检查共享内存截图组件和设置") +} + +func (s *server) captureSharedFrame(i int, e *shotEntry) ([]byte, string, error) { + var cached []byte + frame, angle, id, err := s.readSharedFrame(i, e, mxFmtBGRA, func(id string) bool { + cached = s.cachedSharedFrame(e, id) + return cached != nil + }) + if err != nil { + return nil, "", err + } + if cached != nil { + return cached, id, nil } - return data, src, shmFailed, err + data, err := frame.png(angle) + return data, id, err } -// captureSharedFrame reads the shared frame and turns it upright: by the guest's display rotation when the watcher -// knows it, else by the instance's setting (fallbackShotRotation; never waiting for the watcher, never adb for it). -// The watcher starts only once a shared frame was read: an instance without shared memory stays on adb screencap and -// gets no adb shell for it. A rotation that changes while the frame is read is tried once more; capture does not keep -// a frame whose rotation changed meanwhile. -func (s *server) captureSharedFrame(i int, e *shotEntry) ([]byte, error) { +// readSharedFrame shares the rotation watcher between raw frames and thumbnails. If a +// metadata-only read can no longer be reused, or rotation changed, read again with pixels. +func (s *server) readSharedFrame(i int, e *shotEntry, format uint32, reusable func(string) bool) (sharedFrame, displayRotation, string, error) { for attempt := 0; ; attempt++ { before, knownBefore := s.currentShotRotation(e) - frame, err := s.frame(s.root.Dir, s.mgr.Serial(i)) + var skipPixels func(sharedFrame) bool + if attempt == 0 { + skipPixels = func(frame sharedFrame) bool { + angle := before.angle + if !knownBefore { + angle = s.fallbackShotRotation(i, frame) + } + id := frame.id(angle) + return id != "" && reusable(id) + } + } + frame, err := s.frame(s.root.Dir, s.mgr.Serial(i), format, skipPixels) if err != nil { - return nil, err + return frame, rotation0, "", err } rotation, known := s.shotRotationFor(i, e) if known && (!knownBefore || before != rotation) && attempt == 0 { @@ -193,36 +269,21 @@ func (s *server) captureSharedFrame(i int, e *shotEntry) ([]byte, error) { if !known { angle = s.fallbackShotRotation(i, frame) } - return frame.png(angle) + id := frame.id(angle) + if reuse := reusable(id); !reuse && frame.pixels == nil && attempt == 0 { + continue + } + return frame, angle, id, nil } } -func (s *server) captureAdb(ctx context.Context, i int) ([]byte, error) { - res := s.mgr.AdbRun(ctx, adb.RunOptions{Serial: s.mgr.Serial(i), Timeout: shotTimeout, Raw: true}, - "exec-out", "screencap", "-p") - if res.Code == 0 && bytes.HasPrefix(res.Stdout, pngSignature) { - return res.Stdout, nil - } - if ctx.Err() != nil { - if s.ctx.Err() != nil { - return nil, errs.New(errs.Canceled, "管理器正在退出") - } - return nil, errs.Newf(errs.Timeout, "实例 %d 截图超时(%.0f 秒)", i, shotTimeout.Seconds()) - } - // Find out why: an instance that is not (or no longer) booted is the usual reason, and a 409 for it. - ictx, cancel := context.WithTimeout(s.ctx, 6*time.Second) - defer cancel() - info, err := s.mgr.Info(ictx, i) - if err != nil { - return nil, err - } - if !info.Booted { - return nil, notBooted(i) - } - if res.Code != 0 { - return nil, errs.Newf(errs.Internal, "实例 %d 截图失败: %s", i, clip(res.Out, 300)) +func (s *server) cachedSharedFrame(e *shotEntry, id string) []byte { + s.shots.mu.Lock() + defer s.shots.mu.Unlock() + if id != "" && e.id == id { + return e.data } - return nil, errs.Newf(errs.Internal, "实例 %d 截图的数据不是 PNG(%d 字节)", i, len(res.Stdout)) + return nil } // clip keeps the first n bytes of s on a rune boundary. @@ -305,8 +366,8 @@ func (s *server) handleInput(w http.ResponseWriter, r *http.Request) { } if body.Type == "tap" { // Config describes the next boot. A running guest may still use the previous - // preset, so validate against its screenshot, shared with the viewer cache. - data, _, err := s.screenshot(r.Context(), i) + // preset, so validate against the current screenshot dimensions. + data, _, err := s.screenshot(r.Context(), i, false) if err != nil { writeError(w, err) return diff --git a/internal/ui/device_test.go b/internal/ui/device_test.go index 4f41c3f2..f44a581b 100644 --- a/internal/ui/device_test.go +++ b/internal/ui/device_test.go @@ -4,10 +4,9 @@ package ui import ( "bytes" + "context" "errors" "fmt" - "image" - "image/png" "io" "io/fs" "mime/multipart" @@ -17,11 +16,11 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "time" "unicode/utf8" - "modavd/internal/adb" "modavd/internal/emu" "modavd/internal/errs" "modavd/internal/root" @@ -51,11 +50,21 @@ func TestManagerBackendSerial(t *testing.T) { func TestScreenshot(t *testing.T) { h := newHarness(t, nil) h.f.put(3, emu.StatusOnline) - png := append(append([]byte{}, pngSignature...), []byte("IHDR rest of the image")...) - h.f.mu.Lock() - h.f.shot = adb.Result{Code: 0, Stdout: png} - h.f.shotDelay = 150 * time.Millisecond - h.f.mu.Unlock() + frame := sharedFrame{pixels: []byte{12, 34, 56, 0}, width: 1, height: 1, stride: 4} + want, err := frame.png(rotation0) + if err != nil { + t.Fatal(err) + } + var calls atomic.Int32 + h.s.frame = func(_, serial string, _ uint32, _ func(sharedFrame) bool) (sharedFrame, error) { + if serial != "emulator-21030" { + return sharedFrame{}, errors.New("no frame for " + serial) + } + frame := frame + frame.number = uint32(calls.Add(1)) + time.Sleep(150 * time.Millisecond) + return frame, nil + } // five viewers at once share one capture var wg sync.WaitGroup @@ -73,60 +82,38 @@ func TestScreenshot(t *testing.T) { } wg.Wait() for _, b := range bodies { - if !bytes.Equal(b, png) { + if !bytes.Equal(b, want) { t.Fatalf("screenshot body %q", b) } } - if n := h.f.adbCalls.Load(); n != 1 { + if n := calls.Load(); n != 1 { t.Fatalf("%d captures for five concurrent requests", n) } - // the serial is the root's (portBase 21000 in the fake), never counted from 20000 here - h.f.mu.Lock() - serials := append([]string(nil), h.f.shotSerials...) - h.f.mu.Unlock() - if len(serials) != 1 || serials[0] != "emulator-21030" { - t.Fatalf("captured serials %q", serials) - } - // a capture younger than 300 ms is served again - expect(t, h.do("GET", "/api/instances/3/screenshot", nil), 200, nil) - if n := h.f.adbCalls.Load(); n != 1 { - t.Fatalf("fresh capture not reused (%d captures)", n) + // Cards reuse a recent capture. Live requests sample shared memory again immediately. + resp := h.do("GET", "/api/instances/3/screenshot", nil) + before := resp.Header.Get("X-Shot-Frame") + expect(t, resp, 200, nil) + resp = h.do("GET", "/api/instances/3/screenshot?after="+before, nil) + if id := resp.Header.Get("X-Shot-Frame"); id == "" || id == before || calls.Load() != 2 { + t.Fatalf("live screenshot: old ID=%q, new ID=%q, captures=%d", before, id, calls.Load()) } - time.Sleep(shotReuse + 50*time.Millisecond) - expect(t, h.do("GET", "/api/instances/3/screenshot", nil), 200, nil) - if n := h.f.adbCalls.Load(); n != 2 { - t.Fatalf("stale capture reused (%d captures)", n) - } - - // adb output that is no PNG - h.f.mu.Lock() - h.f.shot = adb.Result{Code: 0, Stdout: []byte("/system/bin/sh: screencap: not found\r\n")} - h.f.shotDelay = 0 - h.f.mu.Unlock() - time.Sleep(shotReuse + 50*time.Millisecond) - expectError(t, h.do("GET", "/api/instances/3/screenshot", nil), 500, errs.Internal) - - // not booted: 409; unknown instance: 404 - h.f.mu.Lock() - h.f.shot = adb.Result{Code: 1, Out: "error: device 'emulator-20040' not found"} - h.f.mu.Unlock() + expect(t, resp, 200, nil) expectError(t, h.do("GET", "/api/instances/4/screenshot", nil), http.StatusConflict, errs.Busy) expectError(t, h.do("GET", "/api/instances/8/screenshot", nil), http.StatusNotFound, errs.NotFound) } -func displayPNG(t *testing.T, width, height int) []byte { - t.Helper() - var b bytes.Buffer - if err := png.Encode(&b, image.NewGray(image.Rect(0, 0, width, height))); err != nil { - t.Fatal(err) +func setFrameSize(s *server, width, height int) { + frame := sharedFrame{pixels: make([]byte, width*height*4), width: width, height: height, stride: width * 4} + s.frame = func(string, string, uint32, func(sharedFrame) bool) (sharedFrame, error) { return frame, nil } + s.readDisplayRotation = func(_ context.Context, _ int, _ string, publish func(displayRotation)) { + publish(rotation0) } - return b.Bytes() } func TestInputValidation(t *testing.T) { h := newHarness(t, nil) h.f.put(3, emu.StatusOnline) - h.f.shot = adb.Result{Code: 0, Stdout: displayPNG(t, 1280, 720)} + setFrameSize(h.s, 1280, 720) ok := map[string]string{ `{"type":"tap","x":100,"y":200}`: "input tap 100 200", @@ -422,7 +409,7 @@ func TestInputUsesLiveDisplayAfterPresetChange(t *testing.T) { in.Config.Width, in.Config.Height = 1920, 1080 } h.f.instances[3] = in - h.f.shot = adb.Result{Code: 0, Stdout: displayPNG(t, dimensions[0], dimensions[1])} + setFrameSize(h.s, dimensions[0], dimensions[1]) h.f.mu.Unlock() x, y := dimensions[0]-1, dimensions[1]-1 expect(t, h.do("POST", "/api/instances/3/input", fmt.Sprintf(`{"type":"tap","x":%d,"y":%d}`, x, y)), 200, nil) diff --git a/internal/ui/fake_test.go b/internal/ui/fake_test.go index f1497510..8431615e 100644 --- a/internal/ui/fake_test.go +++ b/internal/ui/fake_test.go @@ -77,12 +77,8 @@ type fake struct { toggles []string showHidden int - shot adb.Result - shotDelay time.Duration - shotSerials []string // the serial of each capture - adbCalls atomic.Int32 - listCalls atomic.Int32 - checks atomic.Int32 + listCalls atomic.Int32 + checks atomic.Int32 } type fakeInstall struct { @@ -474,20 +470,8 @@ func (b fakeBackend) DiskCompact(ctx context.Context, i int) (*emu.DiskCompactRe BeforeOnDiskBytes: 12 << 30, AfterOnDiskBytes: 10 << 30, FreedBytes: 2 << 30}, nil } -func (b fakeBackend) AdbRun(ctx context.Context, opt adb.RunOptions, args ...string) adb.Result { - b.f.adbCalls.Add(1) - b.f.mu.Lock() - res, delay := b.f.shot, b.f.shotDelay - b.f.shotSerials = append(b.f.shotSerials, opt.Serial) - b.f.mu.Unlock() - if delay > 0 { - select { - case <-time.After(delay): - case <-ctx.Done(): - return adb.Result{Code: -1, Out: "已取消"} - } - } - return res +func (fakeBackend) AdbRun(context.Context, adb.RunOptions, ...string) adb.Result { + panic("Windows manager screenshots must use shared memory") } func (b fakeBackend) RootInfo() emu.RootInfo { return fakeRoot } diff --git a/internal/ui/handlers.go b/internal/ui/handlers.go index ae37b8ed..39143ccf 100644 --- a/internal/ui/handlers.go +++ b/internal/ui/handlers.go @@ -26,10 +26,11 @@ func detached(r *http.Request) context.Context { return context.WithoutCancel(r. func (s *server) handleInfo(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, struct { - Version string `json:"version"` - Protocol int `json:"protocol"` - Root emu.RootInfo `json:"root"` - }{buildinfo.Version, buildinfo.Protocol, s.mgr.RootInfo()}) + Version string `json:"version"` + Protocol int `json:"protocol"` + Root emu.RootInfo `json:"root"` + LiveScreenshots bool `json:"live_screenshots"` + }{buildinfo.Version, buildinfo.Protocol, s.mgr.RootInfo(), sharedMemoryScreenshots}) } func (s *server) handleList(w http.ResponseWriter, r *http.Request) { diff --git a/internal/ui/shmshot.go b/internal/ui/shmshot.go index 7d9053ad..b8ba96ca 100644 --- a/internal/ui/shmshot.go +++ b/internal/ui/shmshot.go @@ -3,13 +3,43 @@ package ui import ( "bytes" "errors" + "fmt" "image" "image/png" + "sync" ) +const ( + mxFmtBGRA = 1 + mxFmtRGBA = 3 +) + +// PNG keeps its compressor and scanline buffers here across thumbnail captures. +type shotEncoderPool struct{ buffers sync.Pool } + +func (p *shotEncoderPool) Get() *png.EncoderBuffer { + if b := p.buffers.Get(); b != nil { + return b.(*png.EncoderBuffer) + } + return nil +} + +func (p *shotEncoderPool) Put(b *png.EncoderBuffer) { p.buffers.Put(b) } + +var shotEncoder = png.Encoder{CompressionLevel: png.BestSpeed, BufferPool: &shotEncoderPool{}} + type sharedFrame struct { pixels []byte width, height, stride int + number uint32 + timestamp uint64 +} + +func (f sharedFrame) id(angle displayRotation) string { + if f.timestamp == 0 && f.number == 0 { + return "" + } + return fmt.Sprintf("%x-%x-%x", f.timestamp, f.number, angle) } func (f sharedFrame) png(rotation displayRotation) ([]byte, error) { @@ -43,8 +73,7 @@ func (f sharedFrame) png(rotation displayRotation) ([]byte, error) { } } var b bytes.Buffer - enc := png.Encoder{CompressionLevel: png.BestSpeed} - if err := enc.Encode(&b, img); err != nil { + if err := shotEncoder.Encode(&b, img); err != nil { return nil, err } return b.Bytes(), nil diff --git a/internal/ui/shmshot_other.go b/internal/ui/shmshot_other.go index 26a27868..c5b15875 100644 --- a/internal/ui/shmshot_other.go +++ b/internal/ui/shmshot_other.go @@ -2,9 +2,41 @@ package ui -import "errors" +import ( + "bytes" + "context" + "errors" + "time" + + "modavd/internal/adb" + "modavd/internal/errs" +) + +const sharedMemoryScreenshots = false + +// Non-Windows packages have no shared-memory library. This is their screenshot path. +func (s *server) capturePlatformFrame(i int, _ *shotEntry) ([]byte, string, error) { + const timeout = 10 * time.Second + ctx, cancel := context.WithTimeout(s.ctx, timeout) + defer cancel() + res := s.mgr.AdbRun(ctx, adb.RunOptions{Serial: s.mgr.Serial(i), Timeout: timeout, Raw: true}, + "exec-out", "screencap", "-p") + if res.Code == 0 && bytes.HasPrefix(res.Stdout, []byte("\x89PNG\r\n\x1a\n")) { + return res.Stdout, "", nil + } + if ctx.Err() != nil { + if s.ctx.Err() != nil { + return nil, "", errs.New(errs.Canceled, "管理器正在退出") + } + return nil, "", errs.Newf(errs.Timeout, "实例 %d 截图超时(%.0f 秒)", i, timeout.Seconds()) + } + if res.Code != 0 { + return nil, "", errs.Newf(errs.Internal, "实例 %d 截图失败: %s", i, clip(res.Out, 300)) + } + return nil, "", errs.Newf(errs.Internal, "实例 %d 截图的数据不是 PNG(%d 字节)", i, len(res.Stdout)) +} // shmFrame: the screenshot library is Windows only; elsewhere thumbnails stay on adb. -func shmFrame(rootDir, serial string) (sharedFrame, error) { +func shmFrame(rootDir, serial string, _ uint32, _ func(sharedFrame) bool) (sharedFrame, error) { return sharedFrame{}, errors.New("shared-memory screenshots are not available on this platform") } diff --git a/internal/ui/shmshot_windows.go b/internal/ui/shmshot_windows.go index ff1b8a82..ae3bcf01 100644 --- a/internal/ui/shmshot_windows.go +++ b/internal/ui/shmshot_windows.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "path/filepath" + "runtime" "sync" "syscall" "unsafe" @@ -19,10 +20,14 @@ import ( // replacing the DLL. const ( - mxFmtBGRA = 1 - mxOK = 0 + sharedMemoryScreenshots = true + mxOK = 0 ) +func (s *server) capturePlatformFrame(i int, e *shotEntry) ([]byte, string, error) { + return s.captureSharedFrame(i, e) +} + type mxOpenParams struct { Size uint32 _ uint32 @@ -47,7 +52,7 @@ type mxFrameInfo struct { // shmMu: one capture at a time, so a library one capture frees is never in use by another. var shmMu sync.Mutex -func shmFrame(rootDir, serial string) (sharedFrame, error) { +func shmFrame(rootDir, serial string, format uint32, reuse func(sharedFrame) bool) (sharedFrame, error) { dll := filepath.Join(rootDir, "extras", "modavd_extras.dll") if _, err := os.Stat(dll); err != nil { return sharedFrame{}, err @@ -71,7 +76,7 @@ func shmFrame(rootDir, serial string) (sharedFrame, error) { if err != nil { return sharedFrame{}, err } - name, _ := syscall.BytePtrFromString("ModAVD manager thumbnail") + name, _ := syscall.BytePtrFromString("ModAVD Manager") p := mxOpenParams{AdbAddress: addr, ClientName: name} p.Size = uint32(unsafe.Sizeof(p)) var h uintptr @@ -85,7 +90,8 @@ func shmFrame(rootDir, serial string) (sharedFrame, error) { if len(buf) > 0 { b, n = uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)) } - r, _, _ := syscall.SyscallN(capture, h, 0, mxFmtBGRA, 0, b, n, uintptr(unsafe.Pointer(info))) + r, _, _ := syscall.SyscallN(capture, h, 0, uintptr(format), 0, b, n, uintptr(unsafe.Pointer(info))) + runtime.KeepAlive(buf) return int32(r) } var info mxFrameInfo @@ -98,10 +104,26 @@ func shmFrame(rootDir, serial string) (sharedFrame, error) { if info.Width <= 0 || info.Height <= 0 || int64(info.Stride) < int64(info.Width)*4 || size > 1<<28 { return sharedFrame{}, errors.New("shared frame has a bad size") } + if reuse != nil { + frame := sharedFrame{ + width: int(info.Width), height: int(info.Height), stride: int(info.Stride), + number: info.FrameNumber, timestamp: info.TimestampUs, + } + if reuse(frame) { + return frame, nil + } + } buf := make([]byte, int(size)) switch r := call(buf, &info); r { case mxOK: - return sharedFrame{pixels: buf, width: int(info.Width), height: int(info.Height), stride: int(info.Stride)}, nil + actualSize := int64(info.Stride) * int64(info.Height) + if info.Width <= 0 || info.Height <= 0 || int64(info.Stride) < int64(info.Width)*4 || actualSize > int64(len(buf)) { + return sharedFrame{}, errors.New("shared frame has a bad size") + } + return sharedFrame{ + pixels: buf[:actualSize], width: int(info.Width), height: int(info.Height), stride: int(info.Stride), + number: info.FrameNumber, timestamp: info.TimestampUs, + }, nil case -5: // MODAVD_E_BUFFER: grew in between, probe again continue default: diff --git a/internal/ui/shmshot_windows_test.go b/internal/ui/shmshot_windows_test.go index 30400017..9b9924a3 100644 --- a/internal/ui/shmshot_windows_test.go +++ b/internal/ui/shmshot_windows_test.go @@ -11,101 +11,133 @@ import ( "testing" "time" - "modavd/internal/adb" "modavd/internal/avd" "modavd/internal/emu" + "modavd/internal/errs" ) func TestScreenshotSharedMemory(t *testing.T) { h := newHarness(t, nil) h.f.put(3, emu.StatusOnline) - frame := sharedFrame{pixels: []byte{12, 34, 56, 0}, width: 1, height: 1, stride: 4} + frame := sharedFrame{pixels: []byte{12, 34, 56, 0}, width: 1, height: 1, stride: 4, number: 1} shm, err := frame.png(rotation0) if err != nil { t.Fatal(err) } - adbPNG := append(append([]byte{}, pngSignature...), []byte("from adb")...) - h.f.mu.Lock() - h.f.shot = adb.Result{Code: 0, Stdout: adbPNG} - h.f.mu.Unlock() var calls atomic.Int32 + var skipped atomic.Int32 var serial, dir atomic.Value fail := atomic.Bool{} - h.s.readDisplayRotation = func(ctx context.Context, _ int, _ string, publish func(displayRotation)) { - publish(rotation0) + h.s.readDisplayRotation = func(ctx context.Context, _ int, _ string, _ func(displayRotation)) { <-ctx.Done() } - h.s.frame = func(rootDir, ser string) (sharedFrame, error) { + h.s.frame = func(rootDir, ser string, _ uint32, reuse func(sharedFrame) bool) (sharedFrame, error) { calls.Add(1) dir.Store(rootDir) serial.Store(ser) if fail.Load() { return sharedFrame{}, errors.New("sharing is off") } - return frame, nil - } - get := func() (string, string) { - t.Helper() - resp := h.do("GET", "/api/instances/3/screenshot", nil) - defer resp.Body.Close() - if resp.StatusCode != 200 { - t.Fatalf("status %d", resp.StatusCode) + metadata := frame + metadata.pixels = nil + if reuse != nil && reuse(metadata) { + skipped.Add(1) + return metadata, nil } - b, _ := io.ReadAll(resp.Body) - return string(b), resp.Header.Get("X-Shot-Source") - } - - if body, src := get(); body != string(shm) || src != "shm" { - t.Fatalf("shared memory capture: %q from %q", body, src) + return frame, nil } - if n := h.f.adbCalls.Load(); n != 0 { - t.Fatalf("%d adb calls for a shared-memory frame", n) + resp := h.do("GET", "/api/instances/3/screenshot", nil) + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + id := resp.Header.Get("X-Shot-Frame") + if resp.StatusCode != 200 || id == "" || !bytes.Equal(body, shm) { + t.Fatalf("shared memory capture: status %d, frame %q", resp.StatusCode, id) } if serial.Load() != "emulator-21030" || dir.Load() != h.s.root.Dir { t.Fatalf("asked for %v in %v", serial.Load(), dir.Load()) } + expect(t, h.do("GET", "/api/instances/3/screenshot?after="+id, nil), 204, nil) + if skipped.Load() != 1 { + t.Fatal("unchanged frame still copied its pixels") + } - // shared memory fails: adb answers, and the next capture does not even try shared memory + // A failed read returns an error. A later request can read shared memory again immediately. fail.Store(true) - time.Sleep(shotReuse + 50*time.Millisecond) - if body, src := get(); body != string(adbPNG) || src != "adb" { - t.Fatalf("fallback: %q from %q", body, src) - } + expectError(t, h.do("GET", "/api/instances/3/screenshot?after="+id, nil), 500, errs.Internal) tried := calls.Load() - time.Sleep(shotReuse + 50*time.Millisecond) - if _, src := get(); src != "adb" || calls.Load() != tried { - t.Fatalf("shared memory retried inside the hold-back (%d -> %d calls)", tried, calls.Load()) + fail.Store(false) + expect(t, h.do("GET", "/api/instances/3/screenshot", nil), 200, nil) + if calls.Load() <= tried { + t.Fatal("shared memory was not retried") } +} - h.s.frame = func(string, string) (sharedFrame, error) { return sharedFrame{}, nil } - h.s.shots.forget(3) - if body, src := get(); body != string(adbPNG) || src != "adb" { - t.Fatalf("invalid frame: %q from %q", body, src) +func TestScreenshotRawFrame(t *testing.T) { + h := newHarness(t, nil) + h.f.put(3, emu.StatusOnline) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + h.s.shots.mu.Lock() + e := h.s.shots.entry(3) + e.rotation = &shotRotation{ctx: ctx, cancel: cancel, known: true, angle: rotation90} + h.s.shots.mu.Unlock() + frame := sharedFrame{pixels: []byte{1, 2, 3, 0, 4, 5, 6, 0, 0, 0, 0, 0}, + width: 2, height: 1, stride: 12, number: 1} + var copies atomic.Int32 + h.s.frame = func(_, _ string, format uint32, skip func(sharedFrame) bool) (sharedFrame, error) { + if format != mxFmtRGBA { + return sharedFrame{}, errors.New("expected the library's RGBA format") + } + if skip != nil && skip(frame) { + metadata := frame + metadata.pixels = nil + return metadata, nil + } + copies.Add(1) + return frame, nil } - - // no library function at all: adb only - h.s.frame = nil - h.s.shots.forget(3) - if _, src := get(); src != "adb" { - t.Fatalf("source %q without frame function", src) + const path = "/api/instances/3/screenshot?format=rgba&after=" + first := h.do("GET", path, nil) + body, err := io.ReadAll(first.Body) + first.Body.Close() + id := first.Header.Get("X-Shot-Frame") + if err != nil || first.StatusCode != 200 || id == "" || !bytes.Equal(body, frame.pixels) { + t.Fatalf("raw capture: status=%d id=%q body=%v err=%v", first.StatusCode, id, body, err) + } + for key, value := range map[string]string{ + "Content-Type": "application/octet-stream", "Content-Length": "12", "Cache-Control": "no-store", + "X-Shot-Width": "2", "X-Shot-Height": "1", "X-Shot-Stride": "12", "X-Shot-Rotation": "90", + } { + if got := first.Header.Get(key); got != value { + t.Errorf("%s = %q, want %q", key, got, value) + } + } + expect(t, h.do("GET", path+id, nil), 204, nil) + if copies.Load() != 1 { + t.Fatalf("copied %d raw frames before rotation, want 1", copies.Load()) + } + h.s.shots.mu.Lock() + e.rotation.angle = rotation270 + e.invalidateShotRotation() + h.s.shots.mu.Unlock() + rotated := h.do("GET", path+id, nil) + expect(t, rotated, 200, nil) + if rotated.Header.Get("X-Shot-Rotation") != "270" || rotated.Header.Get("X-Shot-Frame") == id || copies.Load() != 2 { + t.Fatal("rotation must return new raw pixels and rotation metadata even when the frame number stays the same") } } -// An instance without a shared frame (no extras library, sharing off) stays on adb screencap and gets no rotation -// watcher: that is an adb shell in the guest, and a shell for nothing. func TestScreenshotWithoutSharedFrameStartsNoRotationWatcher(t *testing.T) { h := newHarness(t, nil) h.f.put(3, emu.StatusOnline) - adbPNG := append(append([]byte{}, pngSignature...), []byte("from adb")...) - h.f.mu.Lock() - h.f.shot = adb.Result{Code: 0, Stdout: adbPNG} - h.f.mu.Unlock() var watchers atomic.Int32 h.s.readDisplayRotation = func(context.Context, int, string, func(displayRotation)) { watchers.Add(1) } - h.s.frame = func(string, string) (sharedFrame, error) { return sharedFrame{}, errors.New("sharing is off") } + h.s.frame = func(string, string, uint32, func(sharedFrame) bool) (sharedFrame, error) { + return sharedFrame{}, errors.New("sharing is off") + } - if _, src, err := h.s.screenshot(t.Context(), 3); err != nil || src != shotSourceAdb { + if _, src, err := h.s.screenshot(t.Context(), 3, false); errs.CodeOf(err) != errs.Internal { t.Fatalf("screenshot from %q: %v", src, err) } h.s.shots.mu.Lock() @@ -119,7 +151,7 @@ func TestScreenshotWithoutSharedFrameStartsNoRotationWatcher(t *testing.T) { // TestShmFrameWithoutLibrary: a root without extras\modavd_extras.dll just answers an error. func TestShmFrameWithoutLibrary(t *testing.T) { - if _, err := shmFrame(t.TempDir(), "emulator-21030"); err == nil { + if _, err := shmFrame(t.TempDir(), "emulator-21030", mxFmtBGRA, nil); err == nil { t.Fatal("no error without the library") } } @@ -143,7 +175,7 @@ func TestScreenshotReusesFirstFrameAndRetriesAfterRotation(t *testing.T) { } var readFrames atomic.Int32 var rotateOnRead, rotated atomic.Bool - h.s.frame = func(string, string) (sharedFrame, error) { + h.s.frame = func(string, string, uint32, func(sharedFrame) bool) (sharedFrame, error) { readFrames.Add(1) if rotateOnRead.CompareAndSwap(true, false) { publishAngle.Load().(func(displayRotation))(rotation270) @@ -157,13 +189,13 @@ func TestScreenshotReusesFirstFrameAndRetriesAfterRotation(t *testing.T) { } // the watcher has no rotation yet: the first frame does not wait for it - first, src, err := h.s.screenshot(t.Context(), 3) - if src != shotSourceShm || err != nil { + first, src, err := h.s.screenshot(t.Context(), 3, false) + if err != nil { t.Fatalf("initial screenshot from %q: %v", src, err) } reads := readFrames.Load() - reused, src, err := h.s.screenshot(t.Context(), 3) - if src != shotSourceShm || err != nil || !bytes.Equal(first, reused) || readFrames.Load() != reads { + reused, src, err := h.s.screenshot(t.Context(), 3, false) + if err != nil || !bytes.Equal(first, reused) || readFrames.Load() != reads { t.Fatalf("second request from %q, err=%v, read %d more raw frames", src, err, readFrames.Load()-reads) } @@ -185,14 +217,11 @@ func TestScreenshotReusesFirstFrameAndRetriesAfterRotation(t *testing.T) { e.at = time.Time{} h.s.shots.mu.Unlock() rotateOnRead.Store(true) - got, src, err := h.s.screenshot(t.Context(), 3) + got, src, err := h.s.screenshot(t.Context(), 3, false) want, encodeErr := after.png(rotation270) - if src != shotSourceShm || err != nil || encodeErr != nil || !bytes.Equal(got, want) { + if err != nil || encodeErr != nil || !bytes.Equal(got, want) { t.Fatalf("expected a fresh rotated frame, got %q (screenshot error %v, encoding error %v)", src, err, encodeErr) } - if n := h.f.adbCalls.Load(); n != 0 { - t.Fatalf("%d adb calls", n) - } } // ModAVD/ModAVD#391: while the guest's rotation is unknown (the watcher gets nothing), a frame is still read from @@ -213,12 +242,12 @@ func TestScreenshotUnknownRotationUsesInstanceSetting(t *testing.T) { <-ctx.Done() } wide := sharedFrame{pixels: []byte{1, 2, 3, 0, 4, 5, 6, 0}, width: 2, height: 1, stride: 8} - h.s.frame = func(string, string) (sharedFrame, error) { return wide, nil } + h.s.frame = func(string, string, uint32, func(sharedFrame) bool) (sharedFrame, error) { return wide, nil } for i, angle := range map[int]displayRotation{3: rotation270, 4: rotation0} { started := time.Now() - got, src, err := h.s.screenshot(t.Context(), i) - if err != nil || src != shotSourceShm { + got, src, err := h.s.screenshot(t.Context(), i, false) + if err != nil { t.Fatalf("instance %d: %q, %v", i, src, err) } if waited := time.Since(started); waited > time.Second { @@ -232,9 +261,6 @@ func TestScreenshotUnknownRotationUsesInstanceSetting(t *testing.T) { t.Errorf("instance %d: frame not turned by rotation %d", i, angle) } } - if n := h.f.adbCalls.Load(); n != 0 { - t.Fatalf("%d adb calls while the rotation is unknown", n) - } for deadline := time.Now().Add(5 * time.Second); watchers.Load() < 2; time.Sleep(5 * time.Millisecond) { if time.Now().After(deadline) { t.Fatalf("%d rotation watchers started, want one per instance", watchers.Load()) diff --git a/internal/ui/shotrotation.go b/internal/ui/shotrotation.go index ca5590ed..f68ddefb 100644 --- a/internal/ui/shotrotation.go +++ b/internal/ui/shotrotation.go @@ -154,9 +154,7 @@ func (s *server) runShotRotation(i int, e *shotEntry, r *shotRotation) { func (e *shotEntry) invalidateShotRotation() { e.rotationRevision++ - if e.src == shotSourceShm { - e.data = nil - } + e.data = nil } // Read events beginning just before the snapshot so a switch during dumpsys is visible. diff --git a/internal/ui/ui.go b/internal/ui/ui.go index c28bec3a..88c51216 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -134,7 +134,7 @@ type server struct { dev bool files map[string]*staticFile openPath func(path string) error - frame func(rootDir, serial string) (sharedFrame, error) + frame func(rootDir, serial string, format uint32, reuse func(sharedFrame) bool) (sharedFrame, error) launch func(url string) (*Window, error) removeOld func(log *logx.Logger) mux *http.ServeMux diff --git a/internal/ui/update_apply.go b/internal/ui/update_apply.go index 4d5bb59f..48cf0ba8 100644 --- a/internal/ui/update_apply.go +++ b/internal/ui/update_apply.go @@ -211,7 +211,8 @@ func stagedNewer(st *update.Status) bool { } // beforeStopping refuses what would make the swap fail after the instances were stopped for nothing: another -// program of the root running (an MCP server, another modavd), an instance being created (it must not be cancelled). +// program of the root running (another modavd; the root's MCP servers are stopped by the swap itself), an instance +// being created (it must not be cancelled). func (s *server) beforeStopping(ctx context.Context, b backend, version string) error { advice := version + " 已下载并核对好;处理好后再点「更新」,不用重新下载" progs, err := s.programsInUse() @@ -220,7 +221,7 @@ func (s *server) beforeStopping(ctx context.Context, b backend, version string) } if len(progs) > 0 { return errs.Newf(errs.Busy, "还有程序在用这个根目录的 modavd:%s。一台实例都没关", strings.Join(progs, "、")). - WithAdvice("先关掉它们(比如用 modavd mcp 的 AI 助手、别的命令行窗口);" + advice) + WithAdvice("先关掉它们(比如别的命令行窗口);" + advice) } list, err := b.List(ctx) if err != nil { diff --git a/internal/ui/update_apply_test.go b/internal/ui/update_apply_test.go index d452964a..0f542fb2 100644 --- a/internal/ui/update_apply_test.go +++ b/internal/ui/update_apply_test.go @@ -267,6 +267,10 @@ func TestUpdateApplyFailures(t *testing.T) { if c.code != errs.UpdateUnavailable && c.code != errs.Internal && !strings.Contains(done.Error.Advice, "不用重新下载") { t.Errorf("advice %q", done.Error.Advice) } + // The swap stops the root's MCP servers itself (ModAVD/ModAVD#461): nobody is asked to close them. + if strings.Contains(done.Error.Advice, "MCP") || strings.Contains(done.Error.Advice, "mcp") || strings.Contains(done.Error.Advice, "AI 助手") { + t.Errorf("advice still asks for the AI assistant: %q", done.Error.Advice) + } h.f.mu.Lock() n := len(h.f.stops) h.f.mu.Unlock() diff --git a/internal/ui/web/app.css b/internal/ui/web/app.css index 7d90419a..b2d82dc0 100644 --- a/internal/ui/web/app.css +++ b/internal/ui/web/app.css @@ -234,13 +234,14 @@ h1, h2, h3, p { margin: 0; } button, input, select, textarea { font: inherit; color: inherit; } button { -webkit-tap-highlight-color: transparent; } :focus { outline: none; } -:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } +/* the focus ring only for keyboard use (html.kbd, set in app.js): WebView2 focuses a dialog's first control on open and gives\n the focus back to the opener on close, which a mouse user saw as an error frame. :where keeps the specificity of the old\n global rule, so the rules below that turn it off still win. */ +:where(html.kbd) :focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } ::selection { background: var(--accent-tint-2); } .num { font-variant-numeric: tabular-nums; } .muted { color: var(--text-3); } .spacer { flex: 1; } -/* .pill-quiet: the card view's status label for 运行中 and 已关机, kept for screen readers (the list view shows it) */ -.sr-only, .grid:not(.is-list) .pill-quiet { +/* the card view's status label (.pill) is for screen readers only, in every state: the screen says it (the list view shows it) */ +.sr-only, .grid:not(.is-list) .pill { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; } @@ -332,7 +333,7 @@ button { -webkit-tap-highlight-color: transparent; } /* the 开机失败 / 新建失败 label of a card: it opens 问题反馈 at the task */ .pill-link { cursor: pointer; } .pill-link:hover { box-shadow: inset 0 0 0 1px var(--td); } -.pill-link:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } +html.kbd .pill-link:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } .bar { position: relative; height: 4px; border-radius: 2px; background: var(--bar-track); overflow: hidden; } @@ -393,7 +394,7 @@ button { -webkit-tap-highlight-color: transparent; } } .seg label:hover span { color: var(--text); } .seg input:checked + span { background: var(--seg-on); color: var(--text); box-shadow: var(--shadow-seg); } -.seg input:focus-visible + span { outline: 2px solid var(--focus); outline-offset: 1px; } +html.kbd .seg input:focus-visible + span { outline: 2px solid var(--focus); outline-offset: 1px; } .checkbox { display: flex; align-items: flex-start; gap: 10px; cursor: pointer; user-select: none; } .checkbox input { @@ -403,7 +404,7 @@ button { -webkit-tap-highlight-color: transparent; } } .checkbox input:checked { background: var(--accent-text) var(--tick) center / 14px no-repeat; border-color: var(--accent-text); } .checkbox.danger input:checked { background-color: var(--danger); background-image: var(--tick-w); border-color: var(--danger); } -.checkbox input:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } +html.kbd .checkbox input:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } /* ---- header ----------------------------------------------------------------------------------------------- */ @@ -422,7 +423,7 @@ button { -webkit-tap-highlight-color: transparent; } .brand-link { display: flex; align-items: center; gap: 10px; padding: 0; border: 0; background: none; color: inherit; font: inherit; cursor: default; } .brand-link:not(:disabled) { cursor: pointer; border-radius: 7px; } .brand-link:not(:disabled):hover .brand-name { text-decoration: underline; } -.brand-link:focus-visible { outline: 2px solid var(--accent, currentColor); outline-offset: 3px; } +html.kbd .brand-link:focus-visible { outline: 2px solid var(--accent, currentColor); outline-offset: 3px; } .brand-name { font-size: 15px; font-weight: 600; letter-spacing: .01em; } .brand-ver { padding: 2px 8px; border-radius: 6px; background: var(--ver-bg); @@ -602,9 +603,8 @@ button { -webkit-tap-highlight-color: transparent; } /* the title and, when 按应用走代理 is on, its mark (a button: it opens the dialog) */ .card-tline { display: flex; align-items: center; gap: 6px; min-width: 0; } .card-tline .card-title { min-width: 0; } -/* Card view: the name takes the rest of the title line, so the marks sit at its right end, where the status label is - (left of the label when it shows: the gap to it is the head's 8px). The head keeps the label's height (22px + the - label's 1px margin) whether or not the label is in the flow, so the card is the same height in every state. The list +/* Card view: the name takes the rest of the title line, so the marks sit at its right end. The status label is out of the + flow in every state; the head keeps a fixed height (23px), so the card is the same height in every state. The list view's title is a grid cell: its marks follow the name. */ .grid:not(.is-list) .card-head { gap: 8px; min-height: 23px; } .grid:not(.is-list) .card-tline .card-title { flex: 1; } @@ -615,33 +615,36 @@ button { -webkit-tap-highlight-color: transparent; } .grid:not(.is-list) .card-meta .act-more { width: 18px; height: 18px; border-radius: 5px; } /* Marks after the instance name in the card's title line: one rule for all of them, kept in cards.js next to where they are built (the same text is there). - Every mark is a single-glyph block: 18px square, with exactly one capital letter (10px cap height, 4px above and 4px - below at 1x) or one 12px icon (3px around it) in it. No words and no second letter; what a mark means goes in its + Every mark is a single glyph in an 18px cell with a 1px --line-2 frame (inset box-shadow, radius 5px) and no background colour: exactly one capital + letter (14px, 600, 10px cap height, 4px above and below at 1x) or one icon in it, whose ink is 10px too (y 4–14). The colour is --text-2 + (--tf for the adb tag and for a proxy mark in tone-warn / tone-err). The two marks that are buttons (cat head, A) darken their frame to --text-3 on hover. No words and no second letter; what a mark means goes in its title and aria-label. Today: cat head = 按应用走代理, G = Google Play 商店, - K = KernelSU, monitor with a slash = 无头 (headless). + K = KernelSU, monitor with a slash = 无头 (headless), A = copy the ADB address. Always-there marks come first, marks that follow the run state come last, so one appearing never pushes the others. - In the card view they are at the right end of the title line. The card view does not write 运行中 or 已关机 (the - screen and the power button say it): the status label shows only for the states in between and the failed ones, and - for the other two it is for screen readers only (.pill-quiet). - The card view is the title and one config line: a new state is another single-glyph block or a hover text, not a word + In the card view they are at the right end of the title line. The card view shows no status label in any state (the + screen says it: the picture, 未开机, the progress, 开机失败 / 新建失败); the label is for screen readers only (.sr-only). + The card view is the title and one config line: a new state is another single glyph or a hover text, not a word and not a line. The cat head is the only mark that is a button (it opens the proxy dialog) and the only one that - can have a state colour (--tb / --tf from .tone-*), and only when something is wrong (tone-warn, tone-err): while the + can have a state colour (--tf from .tone-*; the icon only, never a background), and only when something is wrong (tone-warn, tone-err): while the proxy works it looks like the others; the others are static. */ .pmark, .smark, .kmark, .hmark { display: inline-flex; align-items: center; justify-content: center; flex: none; width: 18px; height: 18px; padding: 0; border: 0; border-radius: 5px; - background: var(--sunken); color: var(--text-2); + background: none; color: var(--text-2); box-shadow: inset 0 0 0 1px var(--line-2); } .pmark { cursor: pointer; } -.pmark.tone-warn, .pmark.tone-err { background: var(--tb); color: var(--tf); } -.pmark:hover { box-shadow: inset 0 0 0 1px var(--td, var(--text-3)); } -.pmark:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; } -.pmark .ic, .hmark .ic { width: 12px; height: 12px; } -.smark, .kmark { font-size: 13px; font-weight: 600; line-height: 1; } +.pmark.tone-warn, .pmark.tone-err { color: var(--tf); } +.pmark:hover { box-shadow: inset 0 0 0 1px var(--text-3); } /* the two marks that are buttons: the frame darkens on hover */ +html.kbd .pmark:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; } +/* every mark is 10px of ink (the capital height of the 14px letters), y 4–14 of the 18px box: the monitor drawing is 12.5px tall at 16px, + so it is drawn at 12.83px; the cat head is 11.04px tall at 16px, so it is drawn at 14.5px (the same centre). */ +.pmark .ic { width: 14.5px; height: 14.5px; } +.hmark .ic { width: 12.83px; height: 12.83px; } +.smark, .kmark { font-size: 14px; font-weight: 600; line-height: 1; } /* A letter is centred on its capitals, not on its line box: the font leaves more room above the capitals than below the - baseline, so a flex-centred G sat 1.5px low. font-size-adjust fixes the capital height at 10px whatever the font + baseline, so a flex-centred G sat low. font-size-adjust fixes the capital height at 10px whatever the font (a 14px size scaled to cap-height 10/14), text-box trims the line to cap height and baseline, and the 4px padding - leaves 4px below. The two marks become blocks because text-box does not reach the anonymous box inside a flex + leaves 4px below. The two letters become blocks (the A of the ADB tag is the same, in its own rule below) because text-box does not reach the anonymous box inside a flex container. A browser without either property keeps the flex centring above. */ @supports (text-box: trim-both cap alphabetic) and (font-size-adjust: cap-height 0.7) { .smark, .kmark { @@ -656,12 +659,19 @@ button { -webkit-tap-highlight-color: transparent; } .adb-tag { display: inline-grid; place-items: center; flex: none; width: 18px; height: 18px; padding: 0; - border: 0; border-radius: 5px; - background: var(--tb); color: var(--tf); + border: 0; border-radius: 5px; box-shadow: inset 0 0 0 1px var(--line-2); + background: none; color: var(--tf); font-family: inherit; cursor: pointer; + font-size: 14px; font-weight: 600; line-height: 1; +} +@supports (text-box: trim-both cap alphabetic) and (font-size-adjust: cap-height 0.7) { + .adb-tag { + display: block; text-align: center; + font-size-adjust: cap-height 0.7143; + text-box: trim-both cap alphabetic; /* a button centres its 10px of cap height itself: 4px above and below, so no padding-top here */ + } } -.adb-tag .ic { width: 12px; height: 12px; } -.adb-tag:hover { box-shadow: inset 0 0 0 1px var(--td); } +.adb-tag:hover { box-shadow: inset 0 0 0 1px var(--text-3); } .adb { display: none; } .adb-addr { color: var(--text-2); white-space: nowrap; font-family: var(--mono); font-size: 12px; font-variant-numeric: tabular-nums; } @@ -804,7 +814,7 @@ dialog > .toasts .toast.out { animation-name: toast-out-left; } } .menu-item > .ic { color: var(--text-3); } .menu-item:hover, .menu-item:focus-visible { background: var(--hover); outline: none; } -.menu-item:focus-visible { box-shadow: inset 0 0 0 2px var(--focus); } +html.kbd .menu-item:focus-visible { box-shadow: inset 0 0 0 2px var(--focus); } .menu-item[aria-disabled="true"] { color: var(--text-3); opacity: .55; cursor: default; } .menu-item[aria-disabled="true"]:hover { background: transparent; } .menu-item.danger, .menu-item.danger > .ic { color: var(--err); } @@ -1006,7 +1016,7 @@ fieldset.keymap-profiles { border: 0; padding: 0; margin: 0 0 16px; min-width: 0 .group::before { content: ""; margin-bottom: -1px; } .group + .group { margin-top: 8px; } .row { padding: 10px 12px; border-top: 1px solid var(--line); } -.group .row:focus-visible, .fold-head:focus-visible { outline: none; box-shadow: inset 0 0 0 2px var(--focus); } +html.kbd .group .row:focus-visible, html.kbd .fold-head:focus-visible { outline: none; box-shadow: inset 0 0 0 2px var(--focus); } .row-title { min-width: 0; color: var(--text); font-size: 14px; overflow-wrap: anywhere; } /* what a row found and what to do: all of it (an item that did not pass says what to do, and that is the point of the row); a passed item, folded away in 其余 N 项已通过, keeps to three lines */ @@ -1140,7 +1150,9 @@ fieldset.keymap-profiles { border: 0; padding: 0; margin: 0 0 16px; min-width: 0 /* viewer: the dialog hugs the 16:9 frame (no side bands), the keys sit in the title row */ .dlg-viewer { --w: min(1180px, calc((100vh - 176px) * 16 / 9 + 40px)); } .dlg-viewer .dlg-body { padding: 0 20px 20px; overflow: hidden; scrollbar-gutter: auto; } -.viewer-tools { display: flex; align-items: center; gap: 12px; flex: none; margin-top: -2px; } +.viewer-tools { display: flex; align-items: center; gap: 8px 12px; flex: none; flex-wrap: wrap; margin-top: -2px; } +.viewer-rate { display: inline-flex; align-items: center; gap: 8px; font-size: 12px; } +.viewer-rate input { width: 88px; } .viewer-frame { position: relative; width: 100%; max-height: calc(100vh - 176px); aspect-ratio: 16 / 9; margin: 0 auto; border-radius: 10px; overflow: hidden; background: #120D0B; cursor: crosshair; user-select: none; @@ -1164,9 +1176,6 @@ fieldset.keymap-profiles { border: 0; padding: 0; margin: 0 0 16px; min-width: 0 animation: ripple .55s var(--ease) forwards; } .navkeys { display: flex; gap: 4px; } -.viewer-status { display: inline-flex; align-items: center; gap: 8px; color: var(--text-3); font-size: 12px; white-space: nowrap; } -.live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ok-dot); } -.live-dot.off { background: var(--idle-dot); } /* logs */ .dlg-logs { --w: 1080px; } diff --git a/internal/ui/web/dev/mock.js b/internal/ui/web/dev/mock.js index 4540c742..2b080606 100644 --- a/internal/ui/web/dev/mock.js +++ b/internal/ui/web/dev/mock.js @@ -897,7 +897,7 @@ function shade(hex, amt) { return `rgb(${c(n >> 16)},${c((n >> 8) & 255)},${c(n & 255)})`; } -async function screenshot(inst) { +async function screenshot(inst, format) { if (!canvas) { canvas = document.createElement('canvas'); canvas.width = 1280; canvas.height = 720; } const g = canvas.getContext('2d'); const t = now() / 1000; @@ -916,11 +916,19 @@ async function screenshot(inst) { g.strokeStyle = 'rgba(253,239,220,.9)'; g.lineWidth = 4; g.beginPath(); g.arc(tap.x, tap.y, 26 + (now() - tap.t) / 30, 0, 7); g.stroke(); } + const headers = { 'Cache-Control': 'no-store' }; + if (format === 'rgba') { + const { width, height } = canvas; + return new Response(g.getImageData(0, 0, width, height).data, { headers: { + ...headers, 'Content-Type': 'application/octet-stream', 'X-Shot-Width': width, + 'X-Shot-Height': height, 'X-Shot-Stride': width * 4, 'X-Shot-Rotation': 0, + } }); + } // toDataURL encodes on this thread: headless --virtual-time-budget does not wait for toBlob's encoder thread. const b64 = atob(canvas.toDataURL('image/png').split(',')[1]); const bytes = new Uint8Array(b64.length); for (let k = 0; k < b64.length; k++) bytes[k] = b64.charCodeAt(k); - return new Blob([bytes], { type: 'image/png' }); + return new Response(bytes, { headers: { ...headers, 'Content-Type': 'image/png' } }); } // ---- HTTP ------------------------------------------------------------------------------------------------------------ @@ -971,7 +979,7 @@ async function handle(url, init) { const p = url.pathname; let body = {}; if (typeof init.body === 'string') { try { body = JSON.parse(init.body); } catch { return errResp('usage', '请求体不是 JSON'); } } - await sleep(p.endsWith('/screenshot') ? 40 : 80 + Math.random() * 120); + await sleep(p.endsWith('/screenshot') ? 8 : 80 + Math.random() * 120); if (p === '/api/locale') { // the page's language: the mock stays Chinese (messages {}); a PUT is remembered and echoed if (method === 'PUT' && ['auto', 'zh-CN', 'en'].includes(body.preference)) db.localePreference = body.preference; @@ -1272,9 +1280,8 @@ async function handle(url, init) { if (act === 'screenshot') { window.__mockShots[i] = (window.__mockShots[i] || 0) + 1; if (inst.status !== 'online') return errResp('busy', `ModAVD 实例 ${i} 没有开机`); - if (db.shotfail) return errResp('internal', '截图失败:adb exec-out screencap 退出码 1', ''); - const blob = await screenshot(inst); - return new Response(blob, { status: 200, headers: { 'Content-Type': 'image/png', 'Cache-Control': 'no-store' } }); + if (db.shotfail || !inst.screencap.shm_ready) return errResp('internal', '取不到画面', ''); + return screenshot(inst, url.searchParams.get('format')); } if (act === 'proxy' && method === 'GET') return json(proxyView(inst)); if (act === 'proxy' && method === 'PUT') { diff --git a/internal/ui/web/js/app.js b/internal/ui/web/js/app.js index 559fb116..e17c071a 100644 --- a/internal/ui/web/js/app.js +++ b/internal/ui/web/js/app.js @@ -76,6 +76,12 @@ if (!themeParam) { // before the locale is read // ---- wiring +// the focus ring is for the keyboard only (html.kbd): WebView2 focuses a dialog's first control on open and gives the focus +// back on close, which looked like an error frame to a mouse user. Tab, the arrows, Enter, Space and Escape turn it on, a pointer turns it off. +const NAV_KEYS = new Set(['Tab', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown', 'Enter', ' ', 'Escape']); +addEventListener('keydown', (e) => { if (NAV_KEYS.has(e.key)) document.documentElement.classList.add('kbd'); }, true); +addEventListener('pointerdown', () => document.documentElement.classList.remove('kbd'), true); + initUI(); initGrid($('grid')); // ---- 卡片 / 列表 (?view= for screenshots, not remembered) diff --git a/internal/ui/web/js/cards.js b/internal/ui/web/js/cards.js index 7d9d6b29..289b5f0d 100644 --- a/internal/ui/web/js/cards.js +++ b/internal/ui/web/js/cards.js @@ -124,7 +124,7 @@ export function renderGrid() { } function makeCard(i) { - const c = { i, url: null, next: 0, last: 0, fail: 0, shm: false, visible: false }; + const c = { i, url: null, next: 0, last: 0, fail: 0, visible: false }; const view = () => { if (c.inst.status === 'online') openViewer(i); }; const menu = () => openMenu(c.more, menuItems(c)); c.img = h('img', { class: 'shot', alt: '', draggable: 'false' }); @@ -135,8 +135,12 @@ function makeCard(i) { // no live region here: a boot reports every 2.5 s; the toast at the end says how it went // decoration only: the screen itself is the button (a nested button would open the viewer twice) c.peek = h('span', { class: 'peek', 'aria-hidden': 'true' }, icon('screen')); + // 开机失败 and 新建失败: to the task in 问题反馈, landed on the way a click on the glowing 问题反馈 lands on a failure + const showFailure = () => { if (c.failure) panels.openActivity(c.failure.job, c.failure.inst); }; const activateScreen = () => { if (!c.inst) return; + // 开机失败 and 新建失败: the screen is the way to 问题反馈 at that task (开机 and 重试初始化 are in 更多) + if (c.failure) return showFailure(); if (c.inst.status === 'online') return openViewer(i); const mode = c.primary.dataset.mode; if (mode === 'blocked') panels.openComponents(); @@ -152,27 +156,29 @@ function makeCard(i) { h('div', { class: 'prog' }, h('div', { class: 'prog-row' }, h('span', { class: 'spin' }), c.progMsg), c.progBar), c.peek); c.title = h('h2', { class: 'card-title', id: `card-t-${i}` }); - // The marks after the instance name are single-glyph blocks. The rule (the styles are in app.css, with the same text): - // - A mark is an 18px square with exactly one capital letter (10px cap height, 4px above and 4px below at 1x) or one - // 12px icon in it. No words, no second letter; what it means goes in its title and aria-label. + // The marks after the instance name are single glyphs, with no box behind them. The rule (the styles are in app.css, with the same text): + // - A mark is an 18px cell with a 1px --line-2 frame (inset box-shadow, radius 5px) and no background colour, with exactly one capital + // letter (14px, weight 600, 10px cap height, 4px above and below at 1x) or one icon in it. The ink of every mark is 10px, y 4–14; + // the cat head is drawn at 14.5px and the monitor at 12.83px for that, the ADB tag is the letter A like G and K. Colour is + // --text-2 (--tf for the adb tag, which is a button too, and a proxy mark in tone-warn / tone-err; the icon only, never a background). + // The two buttons (cat head, A) darken the frame to --text-3 on hover. No words, no second letter; what it means goes in its title and aria-label. // - Today: cat head = 按应用走代理, G = Google Play 商店, K = KernelSU, // monitor with a slash = 无头 (headless). // - Order: marks that are always there come first; marks that come and go with the run state come last, so one // appearing never pushes the others. // - In the card view the marks sit at the right end of the title line (the name takes the rest of the width), where - // the status label is; when the label is shown the marks are right next to it, on its left. The list view keeps - // them after the name. - // - The card view does not write 运行中 or 已关机: the screen (or the 未开机 placeholder) already says it. - // The status label shows only for the states in between and the failed ones (开机中, 关机中, 新建中, - // 开机失败, 新建失败); for the other two it stays in the DOM for screen readers only (.pill-quiet). The list view - // always shows it (it has a status column). 诊断模式 is on the name's hover text in the card view. - // - The card view is the title and one config line. A new state is another single-glyph block or a hover text, not a + // the status label is in the list view. The list view keeps them after the name. + // - The card view shows no status label in any state (ModAVD/ModAVD#463): the screen already says it (the live picture, + // the 未开机 placeholder, the boot or shutdown progress, 开机失败 / 新建失败). The label stays in the DOM for screen + // readers only (.sr-only in the card view); the list view always shows it (it has a status column). + // 诊断模式 is on the name's hover text in the card view. + // - The card view is the title and one config line. A new state is another single glyph or a hover text, not a // word and not a line; the label showing or not never changes the card's height. // - There is no box under the card: nothing is added below the config line, so no state makes a card taller than - // another. The reason of a failure (开机失败, 新建失败) is the status label's hover text, and clicking the label - // opens 问题反馈 at that task; software rendering and a data disk that is nearly full are lines on the name's hover + // another. The reason of a failure (开机失败, 新建失败) is the screen's hover text, and clicking the screen + // (Enter, Space) opens 问题反馈 at that task (the list view's label does the same); software rendering and a data disk that is nearly full are lines on the name's hover // text, the first start's setup (about 1–2 minutes) is a line on the screen's hover text. - // - The cat head (pmark) is a single-glyph block too: an icon-only button that opens the 按应用走代理 dialog. It is + // - The cat head (pmark) is a single glyph too: an icon-only button that opens the 按应用走代理 dialog. It is // the only mark that is clickable and the only one that can carry a state colour, and only when something is wrong: // it looks like the other marks while the proxy works (tone ok) or has nothing to report yet (tone info), and takes // tone-warn / tone-err when the guest says part of it does not work. @@ -194,13 +200,11 @@ function makeCard(i) { c.cfg = h('span', { 'aria-hidden': 'true' }); c.cfgFull = h('span', { class: 'sr-only' }); c.pillText = h('span'); - // 开机失败 and 新建失败: the label is the way to the reason (its hover text) and to the task in 问题反馈 (click, Enter, - // Space), landed on the way a click on the glowing 问题反馈 lands on a failure - const showFailure = () => { if (c.failure) panels.openActivity(c.failure.job, c.failure.inst); }; - c.pill = h('span', { class: 'pill', onclick: showFailure, - onkeydown: (e) => { if (c.failure && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); showFailure(); } } }, c.pillText); + // the list view's label is the same way in (the card view's is for screen readers only, with no click) + c.pill = h('span', { class: 'pill', onclick: () => { if (getView() === 'list') showFailure(); }, + onkeydown: (e) => { if (getView() === 'list' && c.failure && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); showFailure(); } } }, c.pillText); const copyAdb = () => A.copy(c.inst.adb_address); - c.adbTag = btn('adb-tag tone-idle', icon('robot'), copyAdb); + c.adbTag = btn('adb-tag tone-idle', 'A', copyAdb); c.adb = h('span', { class: 'adb-addr' }); c.copy = ibtn('copy', t('复制 adb 地址'), copyAdb); c.adbList = h('div', { class: 'adb' }, c.adb, c.copy); @@ -240,7 +244,6 @@ function updateCard(c, inst) { const name = label(inst); c.el.dataset.status = v.key; setText(c.title, name); - const id = [t('编号 {index}', { index: inst.index }), inst.name].filter(Boolean).join(' · '); // diagnostics mode: the list view writes it under the name; the card view has no such line and, while running, no // status label either, so it is a line on the name's hover text (and in the status name screen readers read) const diag = inst.diagnostics ? t('诊断模式') : ''; @@ -250,7 +253,7 @@ function updateCard(c, inst) { const ds = inst.data_space; const warnings = [inst.software_renderer && t('软件渲染:显卡驱动不可用,游戏会卡'), ds && ds.message && (ds.advice ? ds.message + comma() + ds.advice : ds.message)]; - c.title.title = [id, ownTitle(inst) && name, diag, ...warnings].filter(Boolean).join('\n'); + c.title.title = [ownTitle(inst) && name, diag, ...warnings].filter(Boolean).join('\n'); const headless = inst.running && inst.window === false && v.key !== 'creating'; c.hmark.hidden = !headless; c.sub.hidden = !diag; @@ -266,15 +269,18 @@ function updateCard(c, inst) { if (cp != null) pt = t('新建中 {pct}%', { pct: Math.floor(cp) }); if (v.key === 'error') pt = FAIL[v.failed.kind]; setText(c.pillText, pt); - // the card view leaves 运行中 and 已关机 out (screen and power button say it); the label stays for screen readers - // 开机失败 and 新建失败: the hover text is the reason and the advice, the label opens 问题反馈 at the task + // The card view shows no label (it is sr-only there, with its text for screen readers); the failure's reason is the + // screen's hover text and the screen opens 问题反馈 at the task. The list view's label keeps both. const failure = failureOf(inst, v); c.failure = failure; - attr(c.pill, 'class', 'pill tone-' + tone + (v.key === 'online' || v.key === 'offline' ? ' pill-quiet' : '') + (failure ? ' pill-link' : '')); - attr(c.pill, 'title', [failure && (failure.advice ? failure.text + '\n' + failure.advice : failure.text), diag].filter(Boolean).join('\n') || null); - attr(c.pill, 'role', failure ? 'button' : diag ? 'img' : null); - attr(c.pill, 'tabindex', failure ? '0' : null); - attr(c.pill, 'aria-label', diag || failure ? [pt, diag, failure && t('查看详情')].filter(Boolean).join(' · ') : null); + const listed = getView() === 'list'; + const failTip = failure && (failure.advice ? failure.text + '\n' + failure.advice : failure.text); + const linked = !!failure && listed; + attr(c.pill, 'class', 'pill tone-' + tone + (linked ? ' pill-link' : '')); + attr(c.pill, 'title', listed ? [failTip, diag].filter(Boolean).join('\n') || null : null); + attr(c.pill, 'role', linked ? 'button' : diag ? 'img' : null); + attr(c.pill, 'tabindex', linked ? '0' : null); + attr(c.pill, 'aria-label', diag || linked ? [pt, diag, linked && t('查看详情')].filter(Boolean).join(' · ') : null); const address = inst.adb_address || null; c.adbTag.hidden = c.adbList.hidden = !address; @@ -311,7 +317,7 @@ function updateCard(c, inst) { c.el.classList.toggle('is-busy', busy); c.screen.classList.toggle('has-shot', live && v.key !== 'stopping' && !!c.url); c.screen.classList.toggle('busy', busy); - setText(c.phText, v.key === 'error' ? t('上次开机没有成功') : v.key === 'createfail' ? t('新建时的初始化没做完') : live ? t('正在取画面…') : t('未开机')); + setText(c.phText, v.key === 'error' ? t('开机失败') : v.key === 'createfail' ? t('新建失败') : live ? t('正在取画面…') : t('未开机')); if (busy) { const p = v.job && v.job.progress; const msg = (p && stripInst(p.message)) || (store ? store[1] : v.key === 'stopping' ? t('正在关机…') : v.key === 'creating' ? t('正在新建:后台开机做初始化…') : v.kind === 'import-game' ? t('正在导入游戏…') : v.kind === 'install' ? t('正在安装 APK…') @@ -347,16 +353,17 @@ function updateCard(c, inst) { attr(b, 'aria-busy', mode[0] === 'busy'); attr(b, 'aria-disabled', mode[0] === 'busy' || mode[0] === 'blocked'); } - const screenInteractive = live || mode[0] === 'start' || mode[0] === 'blocked' || mode[0] === 'resume'; + const screenInteractive = live || !!failure || mode[0] === 'start' || mode[0] === 'blocked' || mode[0] === 'resume'; attr(c.screen, 'tabindex', screenInteractive ? '0' : null); attr(c.screen, 'aria-disabled', screenInteractive ? null : 'true'); - attr(c.screen, 'aria-label', live ? t('打开「{name}」的画面', { name }) : mode[0] === 'blocked' ? t('打开组件') : mode[0] === 'start' ? t('开机') : mode[0] === 'resume' ? t('重试初始化') : null); + // a failed boot or create: the screen opens 问题反馈 at the task (the status for screen readers goes with it) + attr(c.screen, 'aria-label', failure ? [pt, t('查看详情')].join(' · ') : live ? t('打开「{name}」的画面', { name }) : mode[0] === 'blocked' ? t('打开组件') : mode[0] === 'start' ? t('开机') : mode[0] === 'resume' ? t('重试初始化') : null); // the card view hides the power button: what its hover text says (why a start is not possible, the first start's setup) is the screen's - c.screen.title = mode[0] === 'start' || mode[0] === 'blocked' ? [mode[0] === 'blocked' && BLOCKED, first && FIRST_START].filter(Boolean).join('\n') || null : null; + c.screen.title = failure ? failTip : mode[0] === 'start' || mode[0] === 'blocked' ? [mode[0] === 'blocked' && BLOCKED, first && FIRST_START].filter(Boolean).join('\n') || null : null; if (live && v.key !== 'stopping' && !c.url) tick(); } -// What the 开机失败 / 新建失败 label says and opens: the reason and the advice (its hover text), and where 问题反馈 +// What the 开机失败 / 新建失败 screen says and opens: the reason and the advice (its hover text), and where 问题反馈 // lands in 最近任务和消息: job, the task's row; inst, for a 新建失败 with no 新建 / 重试初始化 task of this manager // behind it (created from the command line), the instance's own row on top of the list. Nothing else is shown on the // card about it. @@ -390,6 +397,8 @@ function menuItems(c) { v.key === 'starting' && { label: t('关机'), icon: 'power', run: () => A.stop(i) }, // the card view has no power button (the list view does): the screen starts, and shutting down is here view !== 'list' && v.key === 'online' && { label: t('关机'), icon: 'power', run: () => A.stop(i) }, + // the screen of a failed boot opens 问题反馈, so the retry is here + view !== 'list' && v.key === 'error' && { label: t('开机'), icon: 'power', run: () => (rootBlocked() ? panels.openComponents() : A.start(i)) }, view !== 'list' && v.key === 'createfail' && { label: t('重试初始化'), icon: 'refresh', run: () => A.resumeCreate(i) }, // create's setup: our own create job is cancelled, one of another process (CLI, AUTO-MAS) is ended by a normal // stop with explicit cancellation; either way it shuts down normally and reads create_failed (resumable) @@ -455,14 +464,11 @@ function glesItem(inst, i, held) { } // ---- thumbnails: only while the card view is on screen, the card is in view and no dialog covers the grid (the first -// frame too). A frame is either read from the emulator's shared memory (cheap; the backend says so in X-Shot-Source) -// or comes from `adb exec-out screencap`, which runs a process in the guest. Shared-memory cards refresh about every -// second while the window has focus and every 2.5 s without it (window visible, not minimized); adb cards about every -// 5 s with focus and not at all without (ModAVD/ModAVD#361). Each interval counts from when the last frame arrived. A +// frame too). Visible cards refresh about every second with focus and every 2.5 s without it. +// Each interval counts from when the last frame arrived. A // failing card backs off up to 30 s and a 409 (not booted after all) waits for the next instances event. -const SHOT_EVERY_SHM = 1000; -const SHOT_EVERY_SHM_UNFOCUSED = 2500; -const SHOT_EVERY_ADB = 5000; +const SHOT_EVERY = 1000; +const SHOT_EVERY_UNFOCUSED = 2500; // A shutting-down card is still 'online' but shows no frame: the backend keeps answering until the guest is gone. const shotAllowed = (c) => !!c.inst && c.inst.status === 'online' && viewState(c.inst).key !== 'stopping'; @@ -470,13 +476,14 @@ function tick() { if (view !== 'card') return; if (document.visibilityState !== 'visible' || document.querySelector('dialog[open]')) return; const focused = document.hasFocus(); + const live = S.info?.live_screenshots !== false; + if (!live && !focused) return; const now = Date.now(); for (const c of cards.values()) { if (!shotAllowed(c) || c.inflight || !c.visible) continue; if (c.hold && c.hold === S.list) continue; - if (!focused && !c.shm) continue; let due = c.next; - if (!focused && !c.fail) due = Math.max(c.next, c.last + SHOT_EVERY_SHM_UNFOCUSED); + if (!focused && !c.fail) due = Math.max(c.next, c.last + SHOT_EVERY_UNFOCUSED); if (now >= due) shoot(c); } } @@ -486,16 +493,15 @@ async function shoot(c) { c.hold = null; let url = null; let ok = false; - let shm = false; try { const res = await fetch(`/api/instances/${c.i}/screenshot`, { credentials: 'same-origin', cache: 'no-store', signal: AbortSignal.timeout(8000) }); if (res.status === 409) { c.hold = S.list; + dropShot(c); ok = true; return; } if (!res.ok) return; - shm = res.headers.get('X-Shot-Source') === 'shm'; url = URL.createObjectURL(await res.blob()); // decode off screen first: the swap never shows a blank frame, and a broken image counts as a failure const im = new Image(); @@ -516,10 +522,10 @@ async function shoot(c) { c.inflight = false; if (ok) { c.fail = 0; - c.shm = shm; c.last = Date.now(); - c.next = c.last + (c.shm ? SHOT_EVERY_SHM : SHOT_EVERY_ADB); + c.next = c.last + (S.info?.live_screenshots === false ? 5000 : SHOT_EVERY); } else { + dropShot(c); c.fail++; c.next = Date.now() + Math.min(30000, 2000 * 2 ** c.fail); } diff --git a/internal/ui/web/js/display.js b/internal/ui/web/js/display.js index 52debec7..0cd3e396 100644 --- a/internal/ui/web/js/display.js +++ b/internal/ui/web/js/display.js @@ -1,3 +1,5 @@ +import { t } from './i18n.js'; + // Map a click through object-fit: contain, including portrait screenshots in a wide frame. export function displayTap(rect, width, height, clientX, clientY) { if (width <= 0 || height <= 0 || rect.width <= 0 || rect.height <= 0) return null; @@ -8,3 +10,47 @@ export function displayTap(rect, width, height, clientX, clientY) { if (x < 0 || x > 1 || y < 0 || y > 1) return null; return { type: 'tap', x: Math.round(x * (width - 1)), y: Math.round(y * (height - 1)) }; } + +// ImageData uses tight rows and ignores transforms. Stage rotated frames on a +// second canvas so drawImage can apply the same orientation as the PNG path. +export function paintFrame(canvas, source, headers, data) { + const width = Number(headers.get('X-Shot-Width')); + const height = Number(headers.get('X-Shot-Height')); + const stride = Number(headers.get('X-Shot-Stride')); + const rotation = Number(headers.get('X-Shot-Rotation') ?? NaN); + if (![width, height, stride].every(Number.isSafeInteger) || width <= 0 || height <= 0 + || stride < width * 4 || stride * height !== data.byteLength || ![0, 90, 180, 270].includes(rotation)) { + throw new Error(t('画面的像素数据不完整')); + } + const raw = new Uint8ClampedArray(data); + const rowBytes = width * 4; + let pixels = raw; + if (stride !== rowBytes) { + pixels = new Uint8ClampedArray(rowBytes * height); + for (let y = 0; y < height; y++) { + pixels.set(raw.subarray(y * stride, y * stride + rowBytes), y * rowBytes); + } + } + // The emulator's canvas is opaque, regardless of the alpha in shared memory. + for (let a = 3; a < pixels.length; a += 4) pixels[a] = 255; + const image = new ImageData(pixels, width, height); + const sideways = rotation === 90 || rotation === 270; + const displayWidth = sideways ? height : width; + const displayHeight = sideways ? width : height; + if (canvas.width !== displayWidth) canvas.width = displayWidth; + if (canvas.height !== displayHeight) canvas.height = displayHeight; + const g = canvas.getContext('2d', { alpha: false }); + if (rotation === 0) { + g.putImageData(image, 0, 0); + return; + } + if (source.width !== width) source.width = width; + if (source.height !== height) source.height = height; + source.getContext('2d', { alpha: false }).putImageData(image, 0, 0); + switch (rotation) { + case 90: g.setTransform(0, -1, 1, 0, 0, width); break; + case 180: g.setTransform(-1, 0, 0, -1, width, height); break; + case 270: g.setTransform(0, 1, -1, 0, height, 0); break; + } + g.drawImage(source, 0, 0); +} diff --git a/internal/ui/web/js/dom.js b/internal/ui/web/js/dom.js index 54b79e84..17e76b9c 100644 --- a/internal/ui/web/js/dom.js +++ b/internal/ui/web/js/dom.js @@ -93,7 +93,6 @@ const I = { refresh: '', window: '', monitorOff: '', - robot: '', eye: '', eyeOff: '', download: '', diff --git a/internal/ui/web/js/viewer.js b/internal/ui/web/js/viewer.js index 394fc16e..de1758c5 100644 --- a/internal/ui/web/js/viewer.js +++ b/internal/ui/web/js/viewer.js @@ -1,4 +1,4 @@ -// 画面 viewer (about 2 frames a second, click = tap) and the log viewer. +// 画面 viewer (click = tap) and the log viewer. import { t } from './i18n.js'; import { h, icon, btn, setText, attr } from './dom.js'; @@ -7,16 +7,19 @@ import { S, subscribe, instance, rootBlocked } from './store.js'; import { openDialog } from './ui.js'; import { label } from './format.js'; import * as A from './actions.js'; -import { displayTap } from './display.js'; +import { displayTap, paintFrame } from './display.js'; import { createBootScreen } from './bootview.js'; import { openComponents } from './panels.js'; -const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); - export function openViewer(i) { const inst = instance(i); if (!inst) return; - const img = h('img', { class: 'vshot', alt: t('{name} 的当前画面', { name: label(inst) }), draggable: 'false' }); + const liveFrames = S.info?.live_screenshots !== false; + const screenName = t('{name} 的当前画面', { name: label(inst) }); + const screen = liveFrames + ? h('canvas', { class: 'vshot', role: 'img', 'aria-label': screenName }) + : h('img', { class: 'vshot', alt: screenName, draggable: 'false' }); + const unrotated = liveFrames && h('canvas'); // not live: the card's placeholder (number tile on the dot pattern), what is going on, and 开机 when it is off const phMsg = h('span'); const phLead = h('span', { class: 'vph-lead' }); @@ -26,14 +29,15 @@ export function openViewer(i) { const ph = h('div', { class: 'ph vph' }, h('span', { class: 'ph-tile' }, h('span', { class: 'ph-num', text: String(i) })), h('p', { class: 'vph-text' }, phLead, phMsg), phSub, startBtn); const boot = createBootScreen(); - const frame = h('div', { class: 'viewer-frame off', role: 'group', 'aria-label': t('「{name}」的画面', { name: label(inst) }) }, img, ph, boot.el); - const dot = h('span', { class: 'live-dot off' }); - const status = h('span'); + const frame = h('div', { class: 'viewer-frame off', role: 'group', 'aria-label': t('「{name}」的画面', { name: label(inst) }) }, screen, ph, boot.el); + const fps = h('input', { type: 'range', min: '2', max: '30', value: '15', 'aria-label': t('目标帧率') }); + const target = h('span', { text: t('目标 {fps} 帧/秒', { fps: fps.value }) }); const keys = [['back', t('返回')], ['home', t('主页')], ['recents', t('最近任务')]].map(([k, name]) => btn('btn btn-secondary btn-sm', [icon(k), name], () => { if (!frame.classList.contains('off')) A.input(i, { type: 'key', key: k }); })); const ctl = openDialog({ title: t('「{name}」的画面', { name: label(inst) }), sub: t('点按画面即在模拟器上点按 · Esc 关闭'), cls: 'dlg-viewer', light: true, - tools: h('div', { class: 'viewer-tools' }, h('span', { class: 'viewer-status' }, dot, status), h('div', { class: 'navkeys' }, keys)), + tools: h('div', { class: 'viewer-tools' }, + liveFrames && h('label', { class: 'viewer-rate' }, fps, target), h('div', { class: 'navkeys' }, keys)), body: h('div', { class: 'dlg-body' }, frame), }); frame.setAttribute('aria-describedby', ctl.subEl.id); @@ -41,6 +45,9 @@ export function openViewer(i) { let alive = true; let url = null; let state = ''; + // due: when the current live poll was meant to start. Pacing from it rather than from when the + // frame finished keeps the target rate even when the OS rounds each timer up to its tick. + let timer, pending, frameID = '', fail = 0, due = 0; // s: live | wait | off | boot | error const setState = (s, text = '', sub = '') => { const blocked = s === 'off' && rootBlocked(); @@ -51,9 +58,7 @@ export function openViewer(i) { ph.hidden = live || s === 'boot'; boot.el.hidden = s !== 'boot'; frame.classList.toggle('booting', s === 'boot'); - img.hidden = !live; - dot.classList.toggle('off', !live); - setText(status, live ? t('实时 · 约 2 帧/秒') : s === 'wait' ? t('正在取画面…') : t('没有画面')); + screen.hidden = !live; for (const b of keys) attr(b, 'aria-disabled', !live || null); phLead.replaceChildren(s === 'wait' || s === 'boot' ? h('span', { class: 'spin' }) : s === 'error' ? icon('alert') : ''); setText(phMsg, text); @@ -65,53 +70,102 @@ export function openViewer(i) { const OFF = t('实例没有开机'); setState('wait', t('正在取画面…')); - (async () => { - let fail = 0; - while (alive) { - const t0 = performance.now(); - let wait = 500; - const cur = instance(i); - if (!cur) { setState('off', t('这台实例已经不在了')); break; } - if (cur.status === 'starting' || S.pending[i] === 'start') { setState('boot', t('正在开机,开好后这里会显示画面')); boot.update(cur); } - else if (cur.status !== 'online') setState('off', OFF, t('开机后这里会显示实时画面')); - else if (document.visibilityState === 'visible') { - let u = null; - try { - const res = await api.get(`/api/instances/${i}/screenshot`, { raw: true, signal: AbortSignal.timeout(8000) }); + const schedule = (ms) => { + clearTimeout(timer); + if (alive && !pending && document.visibilityState === 'visible') timer = setTimeout(poll, ms); + }; + async function poll() { + if (!alive || document.visibilityState !== 'visible') return; + const t0 = performance.now(); + const cur = instance(i); + if (!cur) { setState('off', t('这台实例已经不在了')); return; } + if (cur.status === 'starting' || S.pending[i] === 'start') { + frameID = ''; + due = 0; + setState('boot', t('正在开机,开好后这里会显示画面')); + boot.update(cur); + schedule(500); + return; + } + if (cur.status !== 'online') { + frameID = ''; + due = 0; + setState('off', OFF, t('开机后这里会显示实时画面')); + schedule(500); + return; + } + + pending = new AbortController(); + const signal = AbortSignal.any([pending.signal, AbortSignal.timeout(8000)]); + let u; + try { + const query = liveFrames ? `?format=rgba&after=${encodeURIComponent(frameID)}` : ''; + const res = await api.get(`/api/instances/${i}/screenshot${query}`, { raw: true, signal }); + if (res.status !== 204) { + if (liveFrames) { + const data = await res.arrayBuffer(); + signal.throwIfAborted(); + paintFrame(screen, unrotated, res.headers, data); + } else { u = URL.createObjectURL(await res.blob()); const im = new Image(); im.src = u; await im.decode(); - fail = 0; - if (alive) { - img.src = u; - if (url) URL.revokeObjectURL(url); - url = u; - u = null; - setState('live'); - } - } catch (e) { - if (e.status === 409) setState('off', OFF, t('开机后这里会显示实时画面')); - else { - fail++; - if (e.name === 'TimeoutError') setState('error', t('取画面超时'), t('模拟器可能卡住了,过一会儿会再试')); - else setState('error', e.message || t('取不到画面'), e.advice); - } + signal.throwIfAborted(); + screen.src = u; + if (url) URL.revokeObjectURL(url); + url = u; + u = null; } - if (u) URL.revokeObjectURL(u); - // every frame is an adb screencap: slower while the window is in the background, back off while it fails - if (!document.hasFocus()) wait = 2000; - if (fail) wait = Math.min(10000, 1000 * 2 ** fail); + frameID = res.headers.get('X-Shot-Frame') || ''; } - await sleep(Math.max(150, wait - (performance.now() - t0))); + signal.throwIfAborted(); + fail = 0; + setState('live'); + } catch (e) { + if (!pending.signal.aborted) { + frameID = ''; + fail++; + if (e.status === 409) setState('off', OFF, t('开机后这里会显示实时画面')); + else if (e.name === 'TimeoutError') setState('error', t('取画面超时'), t('模拟器可能卡住了,过一会儿会再试')); + else { + const title = t('取不到画面'); + setState('error', title, [e.message === title ? '' : e.message, e.advice].filter(Boolean).join(' · ')); + } + } + } finally { + if (u) URL.revokeObjectURL(u); + const now = performance.now(); + let wait; + if (pending.signal.aborted || fail) { + due = 0; + wait = pending.signal.aborted ? 0 : Math.min(10000, 500 * 2 ** fail) - (now - t0); + } else if (liveFrames) { + // A frame that ran past its slot starts the next one now instead of bursting to catch up. + due = Math.max((due || t0) + 1000 / Number(fps.value), now); + wait = due - now; + } else { + wait = (document.hasFocus() ? 500 : 2000) - (now - t0); + } + pending = null; + schedule(Math.max(0, wait)); } - })(); + } + const onVisibility = () => { + if (document.visibilityState !== 'visible') pending?.abort(); + schedule(0); + }; + document.addEventListener('visibilitychange', onVisibility); + fps.addEventListener('input', () => setText(target, t('目标 {fps} 帧/秒', { fps: fps.value }))); + schedule(0); frame.addEventListener('click', (e) => { if (frame.classList.contains('off')) return; const r = frame.getBoundingClientRect(); // The screenshot is the running display; config may already describe the next boot. - const tap = displayTap(r, img.naturalWidth, img.naturalHeight, e.clientX, e.clientY); + const width = liveFrames ? screen.width : screen.naturalWidth; + const height = liveFrames ? screen.height : screen.naturalHeight; + const tap = displayTap(r, width, height, e.clientX, e.clientY); if (!tap) return; const rip = h('span', { class: 'ripple' }); rip.style.left = (e.clientX - r.left) + 'px'; @@ -125,9 +179,16 @@ export function openViewer(i) { if (!cur) return; setText(ctl.titleEl, t('「{name}」的画面', { name: label(cur) })); attr(frame, 'aria-label', t('「{name}」的画面', { name: label(cur) })); - attr(img, 'alt', t('{name} 的当前画面', { name: label(cur) })); + attr(screen, liveFrames ? 'aria-label' : 'alt', t('{name} 的当前画面', { name: label(cur) })); + }); + ctl.onClose.push(() => { + alive = false; + clearTimeout(timer); + pending?.abort(); + document.removeEventListener('visibilitychange', onVisibility); + un(); + if (url) URL.revokeObjectURL(url); }); - ctl.onClose.push(() => { alive = false; un(); if (url) URL.revokeObjectURL(url); }); } // ---- logs diff --git a/internal/update/MACOS.en.md b/internal/update/MACOS.en.md index dd1b6278..f44aafff 100644 --- a/internal/update/MACOS.en.md +++ b/internal/update/MACOS.en.md @@ -40,6 +40,6 @@ The manager opens the system browser and needs no separate WebView helper. `CFBu The limits are: 20,000 ZIP entries, 4 GiB in total after extraction, a 16 MiB transport manifest, 12 MiB of encoded signature extended attributes, and a 1 MiB transaction journal. Writing must leave at least 20 GiB free; when the free space cannot be determined, the operation stops. A local input package is first copied to a temporary file of the updater's own, then its digest is checked and it is extracted. Before replacing anything, the digests of the staged content are computed again and the code signatures checked again; modification times alone are never taken as proof that the content can be trusted. -During installation the updater holds the start lock of the managed instances and scans for running executables under the SDK, app and tools directories. On macOS these checks are cooperative: a program started outside the manager can still race with them. Close all instances, manager windows and MCP clients before updating. The running updater can replace its own path; the old process keeps running on the old inode. The transaction journal is written before and after each unit is renamed. On recovery, the complete candidate version made up of the units in the staging area and in the current install is verified first, and then the installation is completed or the original files are restored. On rollback, the metadata undo record restores only the emulator version and update history this transaction changed, and keeps unrelated settings. A damaged or ambiguous transaction journal is left in place for inspection. +During installation the updater holds the start lock of the managed instances and scans for running executables under the SDK, app and tools directories. On macOS these checks are cooperative: a program started outside the manager can still race with them. Close all instances and manager windows before updating; the MCP servers this root has running are stopped by the update itself, and their client starts the new version with its next call. The running updater can replace its own path; the old process keeps running on the old inode. The transaction journal is written before and after each unit is renamed. On recovery, the complete candidate version made up of the units in the staging area and in the current install is verified first, and then the installation is completed or the original files are restored. On rollback, the metadata undo record restores only the emulator version and update history this transaction changed, and keeps unrelated settings. A damaged or ambiguous transaction journal is left in place for inspection. A remote release is chosen by its `macos-arm64` asset, which must come with a SHA256 digest and the full package size; with no compatible asset the result is `update_unavailable`. Publishing update packages in this format, distributing signatures and aligning the packaging configuration are left to a later release packaging stage. diff --git a/internal/update/MACOS.md b/internal/update/MACOS.md index 924ec87e..376d851a 100644 --- a/internal/update/MACOS.md +++ b/internal/update/MACOS.md @@ -40,6 +40,6 @@ ZIP 根目录须直接包含 `modavd-update-manifest.json`,不得在外面再 各项上限为:20,000 个 ZIP 条目、4 GiB 解压后总量、16 MiB 传输清单、12 MiB 编码后的签名扩展属性,以及 1 MiB 事务日志。写入时必须保留至少 20 GiB 可用空间,无法确定剩余空间时停止操作。本地输入包先复制到更新器专用的临时文件,再校验摘要并解压。替换前会重新计算暂存内容的摘要,并重新校验代码签名,不会仅凭修改时间判断内容可信。 -安装期间会持有受管理实例的启动锁,并扫描 SDK、应用和工具目录下正在运行的可执行文件路径。这些检查在 macOS 上属于协作式排他,管理器之外启动的程序仍可能与检查发生竞态。更新前须关闭所有实例、管理器窗口和 MCP 客户端。正在执行的更新器可以替换自身路径,原进程继续使用旧 inode 运行。每个单元重命名前后都会记录事务日志;恢复时,先校验由暂存区和当前安装目录中的单元共同组成的完整候选版本,再继续完成安装或还原原文件。回滚时,元数据撤销记录只恢复本事务修改的模拟器版本和更新历史,保留无关设置。遇到损坏或存在歧义的事务日志时,会保留现场供检查。 +安装期间会持有受管理实例的启动锁,并扫描 SDK、应用和工具目录下正在运行的可执行文件路径。这些检查在 macOS 上属于协作式排他,管理器之外启动的程序仍可能与检查发生竞态。更新前须关闭所有实例和管理器窗口;这个根目录开着的 MCP 服务由更新自己关掉,客户端下次调用时会用上新版。正在执行的更新器可以替换自身路径,原进程继续使用旧 inode 运行。每个单元重命名前后都会记录事务日志;恢复时,先校验由暂存区和当前安装目录中的单元共同组成的完整候选版本,再继续完成安装或还原原文件。回滚时,元数据撤销记录只恢复本事务修改的模拟器版本和更新历史,保留无关设置。遇到损坏或存在歧义的事务日志时,会保留现场供检查。 远端发布版本按 `macos-arm64` 选择资产,必须提供 SHA256 摘要和完整包大小;缺少兼容资产时返回 `update_unavailable`。按本格式发布更新包、分发签名和打包配置对齐,由后续发布打包阶段负责。 diff --git a/internal/update/caller_settings_test.go b/internal/update/caller_settings_test.go index 81f31ed4..6705e3d6 100644 --- a/internal/update/caller_settings_test.go +++ b/internal/update/caller_settings_test.go @@ -216,6 +216,30 @@ func TestGitHubTokenUnauthorized(t *testing.T) { } } +// TestMirrorErrorKeptWithBadToken: with MirrorChyan chosen, a stale GitHub token must not hide MirrorChyan's own failure (ModAVD#453). +func TestMirrorErrorKeptWithBadToken(t *testing.T) { + withSettings(t, SourceMirrorChyan, "") + token := "github_pat_fixture_453" + if _, err := SaveCredentials("", nil, &token); err != nil { + t.Fatal(err) + } + u := New(writeRoot(t, 36, nil), nil, Options{}) + u.httpClient = &http.Client{Transport: sourceTransport(func(req *http.Request) (*http.Response, error) { + resp := &http.Response{StatusCode: http.StatusUnauthorized, Header: make(http.Header), Request: req} + body := "" + if req.URL.Hostname() == "mirrorchyan.com" { + resp.StatusCode, body = 200, `{"code":7001,"msg":"fixture mirror failure"}` + } + resp.Body = io.NopCloser(strings.NewReader(body)) + return resp, nil + })} + _, err := u.Check(t.Context()) + if err == nil || !strings.Contains(err.Error(), "mirrorchyan: 填入的 CDK 已过期") || !strings.Contains(err.Error(), "GitHub token") || + errs.As(err).Advice == "" || strings.Contains(err.Error(), token) { + t.Fatalf("expected MirrorChyan's error plus the token note: %v", err) + } +} + // TestCallerSettingsOverride: --source / --cdk-dpapi of one run beat the saved settings, reach MirrorChyan, are // reported as in effect, and are never saved, logged or written anywhere in the root. func TestCallerSettingsOverride(t *testing.T) { diff --git a/internal/update/handoff.go b/internal/update/handoff.go index 541e995f..c559b8e2 100644 --- a/internal/update/handoff.go +++ b/internal/update/handoff.go @@ -232,9 +232,10 @@ func (u *Updater) LastManagerFailure(st *Status) *HandoffError { return &record.Failure } -// ProgramsInUse lists the other processes running this root's ModAVD.exe or tools\modavd.exe (an MCP server, another -// CLI ...), this process and the short-lived shutdown helpers aside. An install refuses them, so the manager asks -// before it stops any instance (the emulators themselves are what it stops, so they are not listed). +// ProgramsInUse lists the other processes running this root's ModAVD.exe or tools\modavd.exe (another CLI ...), this +// process, the short-lived shutdown helpers and this root's MCP servers (the install stops those itself) aside. An +// install refuses them, so the manager asks before it stops any instance (the emulators themselves are what it stops, +// so they are not listed). func (u *Updater) ProgramsInUse() ([]string, error) { uses, err := u.processesUsing(true) if err != nil { @@ -242,7 +243,7 @@ func (u *Updater) ProgramsInUse() ([]string, error) { } var out []string for _, p := range uses { - if p.RootProgram && !p.ShutdownHelper { + if p.RootProgram && !p.ShutdownHelper && !p.MCP { out = append(out, fmt.Sprintf("%s(pid %d)", p.Name, p.PID)) } } diff --git a/internal/update/inuse_test.go b/internal/update/inuse_test.go index e21b19a4..e2c5d60f 100644 --- a/internal/update/inuse_test.go +++ b/internal/update/inuse_test.go @@ -141,7 +141,7 @@ func TestWaitUntilUnused(t *testing.T) { return nil, errors.New("scan unavailable") } return c.states[min(scans-1, len(c.states)-1)], nil - }, func() time.Time { return clock }, func(d time.Duration) { + }, noMCPStop(t), func() time.Time { return clock }, func(d time.Duration) { if d <= 0 || d > 250*time.Millisecond || clock.Sub(start)+d > shutdownHelperWait { t.Fatalf("invalid wait %v at %v", d, clock.Sub(start)) } diff --git a/internal/update/mcpstop.go b/internal/update/mcpstop.go new file mode 100644 index 00000000..56d141ca --- /dev/null +++ b/internal/update/mcpstop.go @@ -0,0 +1,200 @@ +package update + +// An update stops this root's MCP servers (`tools\modavd.exe mcp`, started by an AI assistant) instead of refusing +// them (ModAVD/ModAVD#461): the swap replaces the program they run, and their client starts the new one with its next +// call. A server is asked to exit through a file it polls, .update\mcp-exit\, holding its process creation time +// (a leftover file of an earlier process with the same PID does not match). It then shuts down the way it does at EOF +// (internal/mcp: file-writing calls finish first, within its shutdownWait). One that has not exited by mcpStopWait is +// ended by the PID recorded in the scan, after checking that PID still names the same process running this root's +// program. Other modavd command lines still block the update. + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "modavd/internal/errs" + "modavd/internal/host" +) + +const ( + mcpExitDirName = "mcp-exit" + // mcpExitPoll is how often a server looks for its request. + mcpExitPoll = 500 * time.Millisecond + // mcpStopWait is a little longer than the server's own shutdown (internal/mcp shutdownWait 30 s plus shutdownGrace + // 2 s) and its polling. + mcpStopWait = 40 * time.Second + // mcpKillWait is how long a server that was ended is waited for before the next scan. + mcpKillWait = 5 * time.Second +) + +// mcpProcess is what stopping a server needs of its process (host.Process). Every call checks that the PID still names +// the scanned process (its creation time). +type mcpProcess interface { + Alive() bool + Wait(time.Duration) bool + Kill() error + ImagePath() (string, error) + StartedAt() time.Time +} + +func (l layout) mcpExitDir() string { return filepath.Join(l.dir(), mcpExitDirName) } + +func mcpExitPath(rootDir string, pid uint32) string { + return filepath.Join(rootDir, updateDirName, mcpExitDirName, strconv.FormatUint(uint64(pid), 10)) +} + +func startStamp(t time.Time) string { return strconv.FormatInt(t.UnixNano(), 10) } + +// rootCLI: path is this root's command-line program (tools\modavd.exe; tools/modavd on macOS). +func (u *Updater) rootCLI(path string) bool { + p := realOrSame(path) + for _, rel := range []string{"tools/modavd.exe", "tools/modavd"} { + if strings.EqualFold(p, realOrSame(u.l.at(rel))) { + return true + } + } + return false +} + +// mcpServer recognizes `modavd mcp` run from this root's tools\modavd.exe: before and after the command name only the +// global options --json / --quiet / --verbose and --root, which must name this root (absolute; without it the server +// still runs this root's program, which the swap replaces). Anything else (another command, --help, positional +// arguments, a relative or different --root, another root's program) is not one. +func (u *Updater) mcpServer(image string, args []string) bool { + if len(args) < 2 || !u.rootCLI(image) { + return false + } + command := false + for i := 1; i < len(args); i++ { + a := args[i] + if len(a) < 2 || a[0] != '-' || a == "--" { + if command || a != "mcp" { + return false + } + command = true + continue + } + name, value, has := strings.Cut(strings.TrimPrefix(strings.TrimPrefix(a, "-"), "-"), "=") + switch name { + case "root": + if !has { + if i++; i >= len(args) { + return false + } + value = args[i] + } + // Same trimming as the command line (`--root "D:\ModAVD\"` arrives as `D:\ModAVD"`). + value = strings.Trim(strings.TrimSpace(value), `"`) + if !filepath.IsAbs(value) || !strings.EqualFold(realOrSame(value), realOrSame(u.l.root)) { + return false + } + case "json", "quiet", "verbose": + if has { + if _, err := strconv.ParseBool(value); err != nil { + return false + } + } + default: + return false + } + } + return command +} + +// stopMCPServers asks servers (MCP uses of one scan) to exit, waits for them, and ends the ones still running after +// mcpStopWait. The requests are removed again before it returns. +func (u *Updater) stopMCPServers(servers []processUse, now func() time.Time, sleep func(time.Duration)) error { + var names []string + for _, p := range servers { + names = append(names, fmt.Sprintf("pid %d", p.PID)) + } + u.Log.Infof("关掉这个根目录开着的 MCP 服务(%s),AI 助手下次调用时会用上新版", strings.Join(names, "、")) + dir := u.l.mcpExitDir() + defer os.RemoveAll(dir) + if err := os.MkdirAll(dir, 0o755); err != nil { + return errs.Wrap(errs.Internal, err, "通知 MCP 服务退出失败,什么都没动: "+err.Error()) + } + for _, p := range servers { + if err := os.WriteFile(mcpExitPath(u.l.root, p.PID), []byte(startStamp(p.proc.StartedAt())), 0o644); err != nil { + return errs.Wrap(errs.Internal, err, "通知 MCP 服务退出失败,什么都没动: "+err.Error()) + } + } + deadline := now().Add(mcpStopWait) + left := servers + for { + var alive []processUse + for _, p := range left { + if p.proc.Alive() { + alive = append(alive, p) + } + } + left = alive + if len(left) == 0 { + return nil + } + wait := deadline.Sub(now()) + if wait <= 0 { + break + } + sleep(min(250*time.Millisecond, wait)) + } + for _, p := range left { + // The PID is the scan's; ImagePath and Kill fail or do nothing when it now names another process. + image, err := p.proc.ImagePath() + if err != nil || !u.rootCLI(image) { + continue + } + u.Log.Warnf("MCP 服务(pid %d)%.0f 秒内没有退出,强制结束它", p.PID, mcpStopWait.Seconds()) + if err := p.proc.Kill(); err != nil { + return swapBlocked("结束 MCP 服务(pid %d)失败(%v),什么都没动", p.PID, err) + } + p.proc.Wait(mcpKillWait) + } + return nil +} + +func (u *Updater) stopMCP(servers []processUse) error { + return u.stopMCPServers(servers, time.Now, time.Sleep) +} + +// WatchMCPExit is the MCP server's side (`modavd mcp`, exe its program): a channel closed when an update of the root +// whose tools directory holds exe asks this process to exit. nil when exe is not in a root's tools directory or this +// process's creation time is unknown (an update cannot recognize such a server; it keeps refusing to run beside it). +func WatchMCPExit(ctx context.Context, exe string) <-chan struct{} { + tools := filepath.Dir(realOrSame(exe)) + if !strings.EqualFold(filepath.Base(tools), "tools") { + return nil + } + pid := uint32(os.Getpid()) + self, ok := host.FindProcess(pid) + if !ok || self.StartedAt().IsZero() { + return nil + } + return watchMCPExit(ctx, filepath.Dir(tools), pid, self.StartedAt(), mcpExitPoll) +} + +func watchMCPExit(ctx context.Context, rootDir string, pid uint32, started time.Time, every time.Duration) <-chan struct{} { + ch := make(chan struct{}) + path, stamp := mcpExitPath(rootDir, pid), startStamp(started) + go func() { + t := time.NewTicker(every) + defer t.Stop() + for { + if b, err := os.ReadFile(path); err == nil && strings.TrimSpace(string(b)) == stamp { + close(ch) + return + } + select { + case <-ctx.Done(): + return + case <-t.C: + } + } + }() + return ch +} diff --git a/internal/update/mcpstop_test.go b/internal/update/mcpstop_test.go new file mode 100644 index 00000000..65ea1339 --- /dev/null +++ b/internal/update/mcpstop_test.go @@ -0,0 +1,349 @@ +package update + +import ( + "context" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + "time" + + "modavd/internal/errs" + "modavd/internal/logx" +) + +func TestMCPServerRecognition(t *testing.T) { + u := &Updater{l: layout{root: t.TempDir()}} + other := t.TempDir() + cli := u.l.at("tools/modavd.exe") + cases := []struct { + name, image string + args []string + want bool + }{ + {"mcp", cli, []string{cli, "mcp"}, true}, + {"macOS program name", u.l.at("tools/modavd"), []string{"modavd", "mcp"}, true}, + {"root before the command", cli, []string{cli, "--root", u.l.root, "mcp"}, true}, + {"root after the command", cli, []string{cli, "mcp", "--root", u.l.root}, true}, + {"root with =", cli, []string{cli, "--root=" + u.l.root, "mcp"}, true}, + {"root with a stray quote", cli, []string{cli, "mcp", "--root", u.l.root + `"`}, true}, + {"single dash root", cli, []string{cli, "-root", u.l.root, "mcp"}, true}, + {"global switches", cli, []string{cli, "--json", "mcp", "--quiet=true", "--verbose=false"}, true}, + {"another root's program", filepath.Join(other, "tools", "modavd.exe"), []string{cli, "mcp"}, false}, + {"another root's program serving this root", filepath.Join(other, "tools", "modavd.exe"), []string{cli, "mcp", "--root", u.l.root}, false}, + {"the manager program", u.l.at("ModAVD.exe"), []string{cli, "mcp"}, false}, + {"another root", cli, []string{cli, "mcp", "--root", other}, false}, + {"neighbor root prefix", cli, []string{cli, "mcp", "--root", u.l.root + "-other"}, false}, + {"relative root", cli, []string{cli, "mcp", "--root", "."}, false}, + {"root without value", cli, []string{cli, "mcp", "--root"}, false}, + {"another command", cli, []string{cli, "list"}, false}, + {"no command", cli, []string{cli, "--json"}, false}, + {"no arguments", cli, []string{cli}, false}, + {"unreadable argv", cli, nil, false}, + {"help", cli, []string{cli, "mcp", "--help"}, false}, + {"help first", cli, []string{cli, "-h", "mcp"}, false}, + {"positional argument", cli, []string{cli, "mcp", "extra"}, false}, + {"twice", cli, []string{cli, "mcp", "mcp"}, false}, + {"double dash", cli, []string{cli, "--", "mcp"}, false}, + {"bad switch value", cli, []string{cli, "--json=maybe", "mcp"}, false}, + {"unknown option", cli, []string{cli, "mcp", "--port", "1"}, false}, + {"logcat helper", cli, []string{cli, "__logcat", u.l.root, "0", "123", "456"}, false}, + {"bootwatch helper", cli, []string{cli, "__bootwatch", u.l.root, "0", "123", "456"}, false}, + } + if runtime.GOOS == "windows" { + cases = append(cases, struct { + name, image string + args []string + want bool + }{"case insensitive root", strings.ToUpper(cli), []string{cli, "mcp", "--root", strings.ToUpper(u.l.root)}, true}) + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := u.mcpServer(c.image, c.args); got != c.want { + t.Fatalf("mcpServer(%q, %q) = %v, want %v", c.image, c.args, got, c.want) + } + if u.shutdownHelper(c.image, c.args) && c.want { + t.Fatal("an MCP server is also a shutdown helper") + } + }) + } +} + +// fakeMCP is an MCP server process. exits: it ends by itself once asked (the file holds its creation time). +type fakeMCP struct { + t *testing.T + root string + pid uint32 + started time.Time + exits bool + image string + imageErr error + killErr error + + mu sync.Mutex + killed bool + waited time.Duration +} + +func (f *fakeMCP) asked() bool { + b, err := os.ReadFile(mcpExitPath(f.root, f.pid)) + return err == nil && string(b) == startStamp(f.started) +} + +func (f *fakeMCP) Alive() bool { + f.mu.Lock() + defer f.mu.Unlock() + return !f.killed && !(f.exits && f.asked()) +} + +func (f *fakeMCP) Wait(d time.Duration) bool { + f.mu.Lock() + defer f.mu.Unlock() + f.waited = d + return f.killed +} + +func (f *fakeMCP) Kill() error { + f.mu.Lock() + defer f.mu.Unlock() + if f.killErr != nil { + return f.killErr + } + f.killed = true + return nil +} + +func (f *fakeMCP) ImagePath() (string, error) { return f.image, f.imageErr } +func (f *fakeMCP) StartedAt() time.Time { return f.started } + +func (f *fakeMCP) use() processUse { + return processUse{PID: f.pid, Name: "modavd.exe", RootProgram: true, MCP: true, proc: f} +} + +type logLines struct { + mu sync.Mutex + lines []string +} + +func (l *logLines) sink(_ logx.Level, msg string) { + l.mu.Lock() + defer l.mu.Unlock() + l.lines = append(l.lines, msg) +} + +func (l *logLines) contains(s string) bool { + l.mu.Lock() + defer l.mu.Unlock() + for _, line := range l.lines { + if strings.Contains(line, s) { + return true + } + } + return false +} + +func mcpUpdater(t *testing.T) (*Updater, *logLines) { + logs := &logLines{} + u := &Updater{l: layout{root: t.TempDir()}, Log: logx.New(logs.sink)} + return u, logs +} + +// noMCPStop is waitUntilUnused's stopMCP where no MCP server is expected. +func noMCPStop(t *testing.T) func([]processUse) error { + return func(servers []processUse) error { + t.Fatalf("stopped %+v as MCP servers", servers) + return nil + } +} + +func TestStopMCPServers(t *testing.T) { + for _, c := range []struct { + name string + exits bool + image string // "" = this root's CLI + imageErr error + killErr error + wantKill bool + wantWait time.Duration + wantCode string + wantSleep bool + }{ + {name: "exits when asked", exits: true}, + {name: "ended after the wait", wantKill: true, wantWait: mcpStopWait, wantSleep: true}, + {name: "PID now names another process", imageErr: errors.New("gone"), wantWait: mcpStopWait, wantSleep: true}, + {name: "PID now runs another program", image: "other.exe", wantWait: mcpStopWait, wantSleep: true}, + {name: "kill fails", killErr: errors.New("denied"), wantWait: mcpStopWait, wantSleep: true, wantCode: errs.Busy}, + } { + t.Run(c.name, func(t *testing.T) { + u, logs := mcpUpdater(t) + image := c.image + if image == "" { + image = u.l.at("tools/modavd.exe") + } + f := &fakeMCP{t: t, root: u.l.root, pid: 4242, started: time.Unix(1700000000, 123456789), exits: c.exits, + image: image, imageErr: c.imageErr, killErr: c.killErr} + start := time.Unix(1, 0) + clock := start + slept := false + err := u.stopMCPServers([]processUse{f.use()}, func() time.Time { return clock }, func(d time.Duration) { + if d <= 0 || d > 250*time.Millisecond { + t.Fatalf("invalid sleep %v", d) + } + if !f.asked() { + t.Fatal("waiting before the server was asked to exit") + } + slept = true + clock = clock.Add(d) + }) + if errs.CodeOf(err) != c.wantCode || f.killed != c.wantKill || clock.Sub(start) != c.wantWait || slept != c.wantSleep { + t.Fatalf("err=%v killed=%v waited=%v slept=%v", err, f.killed, clock.Sub(start), slept) + } + if c.wantKill && (f.waited != mcpKillWait || !logs.contains("秒内没有退出,强制结束它")) { + t.Fatalf("kill not waited for or not logged: %v %v", f.waited, logs.lines) + } + if !logs.contains("关掉这个根目录开着的 MCP 服务(pid 4242)") { + t.Fatalf("stop not logged: %v", logs.lines) + } + if lexists(u.l.mcpExitDir()) { + t.Fatal("exit requests left behind") + } + }) + } +} + +func TestWaitUntilUnusedStopsMCP(t *testing.T) { + mcp := processUse{PID: 101, Name: "modavd.exe", RootProgram: true, MCP: true} + again := processUse{PID: 102, Name: "modavd.exe", RootProgram: true, MCP: true} + helper := processUse{PID: 111, Name: "emulator.exe", ShutdownHelper: true} + qemu := processUse{PID: 333, Name: "qemu-system-x86_64.exe"} + other := processUse{PID: 555, Name: "modavd.exe", RootProgram: true} + failed := errs.New(errs.Busy, "stop failed") + for _, c := range []struct { + name string + states [][]processUse + stopErr error + wantStops int + wantCode string + wantPID string + }{ + {name: "stopped", states: [][]processUse{{mcp}, nil}, wantStops: 1}, + {name: "beside a helper", states: [][]processUse{{mcp, helper}, {helper}, nil}, wantStops: 1}, + {name: "not stopped beside an instance", states: [][]processUse{{mcp, qemu}}, wantCode: errs.Busy, wantPID: "333"}, + {name: "not stopped beside another program", states: [][]processUse{{other, mcp}}, wantCode: errs.Busy, wantPID: "555"}, + {name: "started again blocks", states: [][]processUse{{mcp}, {again}}, wantStops: 1, wantCode: errs.Busy, wantPID: "102"}, + {name: "stop fails", states: [][]processUse{{mcp}}, stopErr: failed, wantStops: 1, wantCode: errs.Busy}, + } { + t.Run(c.name, func(t *testing.T) { + scans, stops := 0, 0 + clock := time.Unix(1, 0) + err := waitUntilUnused("装", func(bool) ([]processUse, error) { + scans++ + return c.states[min(scans-1, len(c.states)-1)], nil + }, func(servers []processUse) error { + stops++ + if len(servers) != 1 || servers[0].PID != 101 { + t.Fatalf("stopped %+v", servers) + } + return c.stopErr + }, func() time.Time { return clock }, func(d time.Duration) { clock = clock.Add(d) }) + if errs.CodeOf(err) != c.wantCode || stops != c.wantStops { + t.Fatalf("err=%v stops=%d", err, stops) + } + if c.stopErr != nil && err != c.stopErr { + t.Fatalf("stop error not returned: %v", err) + } + if c.wantPID != "" && !strings.Contains(err.Error(), "pid "+c.wantPID) { + t.Fatalf("remaining occupant missing from %v", err) + } + }) + } +} + +func TestScanRetriesSkipMCPServers(t *testing.T) { + mcp := processUse{PID: 101, Name: "modavd.exe", RootProgram: true, MCP: true} + scans := 0 + uses, err := scanWithProgramRetries(true, func(bool) ([]processUse, error) { + scans++ + return []processUse{mcp}, nil + }, func(time.Duration) { t.Fatal("waited for an MCP server to exit by itself") }) + if err != nil || scans != 1 || len(uses) != 1 { + t.Fatalf("scans=%d uses=%+v err=%v", scans, uses, err) + } +} + +func TestProgramsInUseLeavesOutMCPServers(t *testing.T) { + mcp := processUse{PID: 101, Name: "modavd.exe", RootProgram: true, MCP: true} + other := processUse{PID: 555, Name: "modavd.exe", RootProgram: true} + helper := processUse{PID: 111, Name: "modavd.exe", RootProgram: true, ShutdownHelper: true} + for _, c := range []struct { + name string + uses []processUse + want string + }{ + {"only an MCP server", []processUse{mcp, helper}, ""}, + {"another program too", []processUse{mcp, other}, "modavd.exe(pid 555)"}, + } { + t.Run(c.name, func(t *testing.T) { + u := &Updater{l: layout{root: t.TempDir()}} + u.scan = func(bool) ([]processUse, error) { return c.uses, nil } + got, err := u.ProgramsInUse() + if err != nil || strings.Join(got, "、") != c.want { + t.Fatalf("ProgramsInUse = %q, %v; want %q", got, err, c.want) + } + }) + } +} + +func TestProcessesBlockedNoLongerAsksForMCPClients(t *testing.T) { + err := processesBlocked("装", []processUse{{PID: 555, Name: "modavd.exe"}}) + if errs.CodeOf(err) != errs.Busy || strings.Contains(err.Error(), "MCP") || !strings.Contains(err.Error(), "modavd.exe(pid 555)") { + t.Fatalf("message: %v", err) + } +} + +func TestWatchMCPExit(t *testing.T) { + dir := t.TempDir() + started := time.Unix(1700000000, 5) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ch := watchMCPExit(ctx, dir, 77, started, 5*time.Millisecond) + closed := func(wait time.Duration) bool { + select { + case <-ch: + return true + case <-time.After(wait): + return false + } + } + if closed(50 * time.Millisecond) { + t.Fatal("closed without a request") + } + if err := os.MkdirAll(filepath.Join(dir, updateDirName, mcpExitDirName), 0o755); err != nil { + t.Fatal(err) + } + // Another process's request, and a leftover one for an earlier process with this PID. + if err := os.WriteFile(mcpExitPath(dir, 78), []byte(startStamp(started)), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(mcpExitPath(dir, 77), []byte(startStamp(started.Add(-time.Second))), 0o644); err != nil { + t.Fatal(err) + } + if closed(50 * time.Millisecond) { + t.Fatal("closed by another process's request") + } + if err := os.WriteFile(mcpExitPath(dir, 77), []byte(startStamp(started)), 0o644); err != nil { + t.Fatal(err) + } + if !closed(5 * time.Second) { + t.Fatal("the request was not seen") + } +} + +func TestWatchMCPExitOutsideRoot(t *testing.T) { + if ch := WatchMCPExit(context.Background(), filepath.Join(t.TempDir(), "bin", "modavd.exe")); ch != nil { + t.Fatal("a program outside a tools directory watches for requests") + } +} diff --git a/internal/update/mcpstop_windows_test.go b/internal/update/mcpstop_windows_test.go new file mode 100644 index 00000000..36dd8212 --- /dev/null +++ b/internal/update/mcpstop_windows_test.go @@ -0,0 +1,229 @@ +//go:build windows + +package update + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" + "time" + + "modavd/internal/errs" + "modavd/internal/win" +) + +// A copy of this test binary as \tools\modavd.exe, started as `modavd.exe mcp --root `: the command line +// of a real MCP server, which the go test flags cannot follow (they would end at "mcp" and run every test). So the +// fixture runs from init, before the testing package parses anything. "serve" waits for the update's request the way +// `modavd mcp` does (WatchMCPExit) and exits 0 when it comes; "ignore" never looks. +const mcpFixtureEnv, mcpFixtureReadyEnv = "MODAVD_UPDATE_TEST_MCP", "MODAVD_UPDATE_TEST_MCP_READY" + +func init() { + mode := os.Getenv(mcpFixtureEnv) + if mode == "" { + return + } + var exit <-chan struct{} + if mode == "serve" { + exe, _ := os.Executable() + if exit = WatchMCPExit(context.Background(), exe); exit == nil { + os.Exit(3) + } + } + if err := os.WriteFile(os.Getenv(mcpFixtureReadyEnv), nil, 0o600); err != nil { + os.Exit(4) + } + select { + case <-exit: + os.Exit(0) + case <-time.After(20 * time.Second): + os.Exit(5) + } +} + +// mcpChild starts the fixture from this root's tools\modavd.exe. +func mcpChild(t *testing.T, u *Updater, mode string) *exec.Cmd { + t.Helper() + cleanupOccupancyRoot(t, u.l.root) + cli := u.l.at("tools/modavd.exe") + if !isFile(cli) { + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + if err := copyFile(self, cli); err != nil { + t.Fatal(err) + } + } + ready := filepath.Join(t.TempDir(), "ready") + cmd := exec.Command(cli, "mcp", "--root", u.l.root) + cmd.Env = append(os.Environ(), mcpFixtureEnv+"="+mode, mcpFixtureReadyEnv+"="+ready) + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() }) + deadline := time.Now().Add(5 * time.Second) + for { + if _, err := os.Stat(ready); err == nil { + return cmd + } + if time.Now().After(deadline) { + t.Fatal("MCP fixture did not start") + } + time.Sleep(10 * time.Millisecond) + } +} + +func exitCodeWithin(t *testing.T, cmd *exec.Cmd, d time.Duration) int { + t.Helper() + done := make(chan error, 1) + go func() { done <- cmd.Wait() }() + select { + case <-done: + return cmd.ProcessState.ExitCode() + case <-time.After(d): + t.Fatal("process did not exit") + return -1 + } +} + +// The real scan recognizes the server from its command line, and the server exits by itself once asked. +func TestRealMCPServerExitsWhenAsked(t *testing.T) { + u, logs := mcpUpdater(t) + child := mcpChild(t, u, "serve") + uses, err := ownScan(u)(true) + if err != nil || len(uses) != 1 || !uses[0].MCP || !uses[0].RootProgram || uses[0].ShutdownHelper || + uses[0].PID != uint32(child.Process.Pid) { + t.Fatalf("server not recognized: %+v %v", uses, err) + } + started := time.Now() + if err := u.stopMCP(uses); err != nil { + t.Fatal(err) + } + if d := time.Since(started); d > 10*time.Second { + t.Fatalf("stopping took %v", d) + } + if code := exitCodeWithin(t, child, 5*time.Second); code != 0 { + t.Fatalf("server ended with %d, not by its own exit", code) + } + if logs.contains("强制结束") || lexists(u.l.mcpExitDir()) { + t.Fatalf("killed or left requests behind: %v", logs.lines) + } +} + +// A server that does not exit is ended by the scanned PID, after the wait; a PID whose creation time no longer +// matches is left alone. +func TestRealMCPServerKilledAfterWait(t *testing.T) { + u, logs := mcpUpdater(t) + child := mcpChild(t, u, "ignore") + uses, err := ownScan(u)(true) + if err != nil || len(uses) != 1 || !uses[0].MCP { + t.Fatalf("server not recognized: %+v %v", uses, err) + } + live, ok := win.FindProcess(uint32(child.Process.Pid)) + if !ok || live.Created == 0 { + t.Fatal("no fixture identity") + } + fastClock := func() (func() time.Time, func(time.Duration)) { + clock := time.Unix(1, 0) + return func() time.Time { return clock }, func(d time.Duration) { clock = clock.Add(d) } + } + + reused := live + reused.Created++ + now, sleep := fastClock() + if err := u.stopMCPServers([]processUse{{PID: reused.PID, Name: reused.Name, RootProgram: true, MCP: true, proc: reused}}, now, sleep); err != nil { + t.Fatal(err) + } + if !live.Alive() { + t.Fatal("a reused PID was ended") + } + + now, sleep = fastClock() + if err := u.stopMCPServers(uses, now, sleep); err != nil { + t.Fatal(err) + } + if code := exitCodeWithin(t, child, 5*time.Second); code != 1 || !logs.contains("强制结束") { + t.Fatalf("server not ended by its PID: exit %d, %v", code, logs.lines) + } +} + +// The whole install: the server of this root is stopped instead of refusing the update, and the swap goes on. +func TestInstallStopsMCPServer(t *testing.T) { + withSettings(t, SourceGitHub, "") + r := writeRoot(t, 36, nil) + f := newSources(t, 37, zipOf(t, 37, pkgFiles(37, nil), false)) + u := f.updater(r) + child := mcpChild(t, u, "serve") + u.scan = ownScan(u) + st, err := u.Install(context.Background()) + if err != nil || !st.Updated || read(t, r, "sdk/emulator/emulator.exe") != "emulator mas-37" { + t.Fatalf("install beside an MCP server: %+v %v", st, err) + } + if code := exitCodeWithin(t, child, 5*time.Second); code != 0 { + t.Fatalf("server ended with %d", code) + } + assertStartLocks(t, r, false) +} + +// A server started again while the locks were taken is stopped under them. +func TestLockForSwapStopsMCPStartedAgain(t *testing.T) { + withSettings(t, SourceGitHub, "") + r := writeRoot(t, 36, nil) + f := newSources(t, 37, zipOf(t, 37, pkgFiles(37, nil), false)) + u := f.updater(r) + cleanupOccupancyRoot(t, r.Dir) + var child *exec.Cmd + scans := 0 + u.scan = func(programs bool) ([]processUse, error) { + scans++ + if scans == 2 { + // the final scan, under the locks + assertStartLocks(t, r, true) + child = mcpChild(t, u, "serve") + } + return ownScan(u)(programs) + } + unlock, err := u.lockForSwap("装") + if err != nil { + t.Fatalf("lockForSwap: %v", err) + } + unlock() + if scans != 3 || child == nil { + t.Fatalf("scans = %d", scans) + } + if code := exitCodeWithin(t, child, 5*time.Second); code != 0 { + t.Fatalf("server ended with %d", code) + } +} + +// Another modavd command line of the root still refuses the update, with the message that no longer asks for MCP +// clients to be closed. +func TestInstallStillRefusesOtherCLI(t *testing.T) { + withSettings(t, SourceGitHub, "") + r := writeRoot(t, 36, nil) + cleanupOccupancyRoot(t, r.Dir) + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + cli := filepath.Join(r.Dir, "tools/modavd.exe") + if err := copyFile(self, cli); err != nil { + t.Fatal(err) + } + child := occupancyChild(t, cli) + f := newSources(t, 37, zipOf(t, 37, pkgFiles(37, nil), false)) + u := f.updater(r) + u.scan = ownScan(u) + st, err := u.Install(context.Background()) + if errs.CodeOf(err) != errs.Busy || st.Updated || st.Phase != phaseStaged { + t.Fatalf("install beside another CLI: %+v %v", st, err) + } + if p, ok := win.FindProcess(uint32(child.Process.Pid)); !ok || !p.Alive() { + t.Fatal("the other CLI was ended") + } +} diff --git a/internal/update/native_guard_darwin.go b/internal/update/native_guard_darwin.go index 9c535e06..16bc825c 100644 --- a/internal/update/native_guard_darwin.go +++ b/internal/update/native_guard_darwin.go @@ -90,10 +90,16 @@ func (u *Updater) nativeProcessesUsing(programs bool) ([]processUse, error) { } continue } - image = key(image) for _, prefix := range prefixes { - if strings.HasPrefix(image, prefix) && p.Alive() { - uses = append(uses, processUse{PID: p.PID, Name: p.Name}) + if strings.HasPrefix(key(image), prefix) && p.Alive() { + use := processUse{PID: p.PID, Name: p.Name, proc: p} + // This root's MCP server is stopped by the swap (stopMCPServers), not refused. + if programs && !p.StartedAt().IsZero() { + if args, err := p.CommandLine(); err == nil { + use.MCP = u.mcpServer(image, args) + } + } + uses = append(uses, use) break } } @@ -103,7 +109,9 @@ func (u *Updater) nativeProcessesUsing(programs bool) ([]processUse, error) { // Exclude managed starts through every rename and recovery. macOS allows an // executing inode to be renamed; this is advisory exclusion plus a final full -// process check, not the mandatory Windows PE image-lock mechanism. +// process check, not the mandatory Windows PE image-lock mechanism. Both checks +// stop this root's MCP servers (ensureNotInUse), the second one those started +// again while the locks were being taken. func (u *Updater) lockNativeSwap(verb string) (func(), error) { if err := u.ensureNotInUse(verb); err != nil { return nil, err diff --git a/internal/update/process_scan_windows_test.go b/internal/update/process_scan_windows_test.go index 9ddc9314..f04a0dea 100644 --- a/internal/update/process_scan_windows_test.go +++ b/internal/update/process_scan_windows_test.go @@ -128,7 +128,7 @@ func TestProcessScanUnreadableImageIdentity(t *testing.T) { t.Fatalf("live unreadable process lost Unknown: %+v, %v", uses, err) } return uses, err - }, time.Now, func(time.Duration) { t.Fatal("unknown process must block without waiting") }) + }, noMCPStop(t), time.Now, func(time.Duration) { t.Fatal("unknown process must block without waiting") }) if got := errs.CodeOf(err); c.wantBusy && got != errs.Busy || !c.wantBusy && err != nil { t.Fatalf("wantBusy=%v, err=%v", c.wantBusy, err) } diff --git a/internal/update/swap.go b/internal/update/swap.go index b4b8920c..bd3a96c3 100644 --- a/internal/update/swap.go +++ b/internal/update/swap.go @@ -600,6 +600,8 @@ type processUse struct { Unknown bool // its path could not be read; matched by name ShutdownHelper bool // verified root executable and complete shutdown-helper argv RootProgram bool // verified ModAVD.exe or tools/modavd.exe of this root + MCP bool // this root's MCP server (mcpServer), with a known creation time: stopped, not refused + proc mcpProcess } // emulatorNames are the image names that count as the emulator's when a process's path cannot be read (another @@ -609,7 +611,8 @@ var emulatorNames = []string{"qemu-system", "emulator", "netsimd"} // processesUsing lists the processes whose image is under \sdk\emulator (emulator, qemu, netsimd ...): running // exes do not stop a directory rename, so they are checked first. With programs, also the other processes running the -// root's ModAVD.exe or tools\modavd.exe (the manager, MCP servers, helpers), which the swap replaces. +// root's ModAVD.exe or tools\modavd.exe (the manager, MCP servers, helpers), which the swap replaces. MCP servers are +// marked: the swap stops them (stopMCPServers) instead of refusing them. func (u *Updater) processesUsing(programs bool) ([]processUse, error) { scan := u.scan if scan == nil { @@ -636,7 +639,8 @@ func scanWithProgramRetries(programs bool, scan func(bool) ([]processUse, error) if p.Unknown || (!p.ShutdownHelper && !p.RootProgram) { return uses, nil } - if p.RootProgram && !p.ShutdownHelper { + // An MCP server does not end by itself; the swap stops it. + if p.RootProgram && !p.ShutdownHelper && !p.MCP { haveProgram = true } } @@ -702,7 +706,9 @@ func (u *Updater) scanProcesses(programs bool, list func() ([]host.Process, erro } out = append(out, processUse{PID: p.PID, Name: p.Name, RootProgram: progs[lp], - ShutdownHelper: err == nil && u.shutdownHelper(path, args)}) + ShutdownHelper: err == nil && u.shutdownHelper(path, args), + MCP: err == nil && progs[lp] && !p.StartedAt().IsZero() && u.mcpServer(path, args), + proc: p}) } } return out, nil @@ -723,7 +729,17 @@ func realOrSame(p string) string { } func (u *Updater) ensureNotInUse(verb string) error { - return waitUntilUnused(verb, u.processesUsing, time.Now, time.Sleep) + return waitUntilUnused(verb, u.processesUsing, u.stopMCP, time.Now, time.Sleep) +} + +// onlyMCP: every use is one of this root's MCP servers. +func onlyMCP(uses []processUse) bool { + for _, p := range uses { + if !p.MCP { + return false + } + } + return len(uses) > 0 } // lockForSwap first lets shutdown helpers exit, then excludes managed and raw @@ -770,6 +786,16 @@ func (u *Updater) lockForSwap(verb string) (unlock func(), err error) { if err != nil { return nil, errs.Wrap(errs.Internal, err, "查不了有没有程序在用模拟器文件,什么都没动: "+err.Error()) } + if onlyMCP(uses) { + // An AI assistant started its MCP server again since ensureNotInUse: stop it too, under the locks, and check + // once more. + if err := u.stopMCP(uses); err != nil { + return nil, err + } + if uses, err = u.processesUsing(true); err != nil { + return nil, errs.Wrap(errs.Internal, err, "查不了有没有程序在用模拟器文件,什么都没动: "+err.Error()) + } + } if len(uses) != 0 { return nil, processesBlocked(verb, uses) } @@ -828,9 +854,13 @@ func roundToken(s string) bool { const shutdownHelperWait = 30 * time.Second // Keep scanning the entire root: helpers are never ignored, and any other use blocks immediately. -// One deadline covers all helpers, including helpers first seen on a later scan. -func waitUntilUnused(verb string, scan func(bool) ([]processUse, error), now func() time.Time, sleep func(time.Duration)) error { +// One deadline covers all helpers, including helpers first seen on a later scan. This root's MCP servers are stopped +// (stopMCP), once, when nothing but them and helpers is left; the helpers' deadline starts again after that. A server +// seen again on a later scan blocks like any other program. +func waitUntilUnused(verb string, scan func(bool) ([]processUse, error), stopMCP func([]processUse) error, + now func() time.Time, sleep func(time.Duration)) error { deadline := now().Add(shutdownHelperWait) + stopped := false var uses []processUse for { var err error @@ -842,12 +872,23 @@ func waitUntilUnused(verb string, scan func(bool) ([]processUse, error), now fun return nil } helperOnly := true + var servers []processUse for _, p := range uses { - if !p.ShutdownHelper || p.Unknown { + if p.MCP && !stopped { + servers = append(servers, p) + } else if !p.ShutdownHelper || p.Unknown { helperOnly = false break } } + if helperOnly && len(servers) > 0 { + if err := stopMCP(servers); err != nil { + return err + } + stopped = true + deadline = now().Add(shutdownHelperWait) + continue + } left := deadline.Sub(now()) if !helperOnly || left <= 0 { break @@ -866,6 +907,6 @@ func processesBlocked(verb string, uses []processUse) error { } parts = append(parts, s+")") } - return swapBlocked("还有程序在用模拟器或管理器的文件:%s。什么都没动,请先关掉所有实例、管理器(包括托盘里的,在托盘图标的菜单里退出)和 MCP 客户端再%s", + return swapBlocked("还有程序在用模拟器或管理器的文件:%s。什么都没动,请先关掉所有实例和管理器(包括托盘里的,在托盘图标的菜单里退出)再%s", strings.Join(parts, "、"), verb) } diff --git a/internal/update/updater.go b/internal/update/updater.go index 0fc32261..27c2535d 100644 --- a/internal/update/updater.go +++ b/internal/update/updater.go @@ -239,11 +239,10 @@ func (u *Updater) latest(ctx context.Context, st *Status) (*release, error) { mirrorErr = err } r, err := u.githubLatest(ctx) - if errors.Is(err, errGitHubToken) { - return nil, err - } if err != nil && mirrorErr != nil { - return nil, sourceError("mirrorchyan: %v;github: %v", mirrorErr, errs.As(err).Message) + // MirrorChyan is the chosen source: its error leads, and a bad token only explains the GitHub half. + return nil, sourceError("mirrorchyan: %v;github: %v", mirrorErr, errs.As(err).Message). + WithAdvice(errs.As(err).Advice) } return r, err } diff --git a/rsrc_windows_amd64.syso b/rsrc_windows_amd64.syso index 01dc6039..a83bc52f 100644 Binary files a/rsrc_windows_amd64.syso and b/rsrc_windows_amd64.syso differ diff --git a/scripts/test_create_cancel.mjs b/scripts/test_create_cancel.mjs index 158d64bf..8806cb17 100644 --- a/scripts/test_create_cancel.mjs +++ b/scripts/test_create_cancel.mjs @@ -558,25 +558,25 @@ test('clearing the boss key saves an empty one; a taken key on open is marked; n test('cards show diagnostics mode on the list line under the name, on the name\'s hover text and in the status name', async () => { const h = await settingsHarness(); const plain = h.makeCard({ ...h.inst, diagnostics: false }); - assert.equal(plain.title.title, '编号 3 · mas_3'); + assert.equal(plain.title.title, ''); assert.equal(plain.sub.textContent, ''); assert.equal(plain.sub.hidden, true); assert.ok(!plain.pill.getAttribute('title')); assert.ok(!plain.pill.getAttribute('aria-label')); h.patchCard(plain, { ...h.inst, title: 'Arknights Daily Main Account', diagnostics: false }); - assert.equal(plain.title.title, '编号 3 · mas_3\nArknights Daily Main Account'); + assert.equal(plain.title.title, 'Arknights Daily Main Account'); // the card view has no status label for running and shut down, so diagnostics mode is a line on the name's hover text h.patchCard(plain, { ...h.inst, title: 'Arknights Daily Main Account' }); - assert.equal(plain.title.title, '编号 3 · mas_3\nArknights Daily Main Account\n诊断模式'); + assert.equal(plain.title.title, 'Arknights Daily Main Account\n诊断模式'); for (const status of ['online', 'offline']) { const inst = { ...h.inst, status, running: status === 'online' }; h.patchCard(plain, inst); - assert.equal(plain.title.title, '编号 3 · mas_3\n诊断模式'); + assert.equal(plain.title.title, '诊断模式'); assert.equal(plain.sub.textContent, '诊断模式'); - assert.equal(plain.pill.getAttribute('title'), '诊断模式'); + assert.ok(!plain.pill.getAttribute('title'), 'the card view label has no hover text'); assert.equal(plain.pill.getAttribute('aria-label'), `${plain.pillText.textContent} · 诊断模式`); h.patchCard(plain, { ...inst, diagnostics: undefined }); - assert.equal(plain.title.title, '编号 3 · mas_3'); + assert.equal(plain.title.title, ''); assert.equal(plain.sub.hidden, true); assert.ok(!plain.pill.getAttribute('title')); assert.ok(!plain.pill.getAttribute('aria-label')); @@ -619,13 +619,12 @@ test('cards mark a headless instance in the title line, after the G and KernelSU assert.equal(c.hmark.hidden, true, 'a create in progress runs headless but is not marked'); }); -// ModAVD/ModAVD#435: the card's ADB address is a small robot mark after the title (the full address on hover and +// ModAVD/ModAVD#435: the card's ADB address is a small letter A mark after the title (the full address on hover and // for screen readers), hidden without a port; the config line keeps its full wording on hover and for screen readers. -test('cards show the ADB robot mark and the short config line', async () => { +test('cards show the ADB letter mark and the short config line', async () => { const h = await settingsHarness(); const c = h.makeCard({ ...h.inst, adb_address: '127.0.0.1:20011' }); - assert.equal(c.adbTag.textContent, ''); - assert.equal(c.adbTag.childNodes.length, 1); + assert.equal(c.adbTag.textContent, 'A'); assert.equal(c.adbTag.hidden, false); assert.equal(c.adbTag.getAttribute('title'), '127.0.0.1:20011'); assert.equal(c.adbTag.getAttribute('aria-label'), '复制 ADB 地址 127.0.0.1:20011'); @@ -694,40 +693,51 @@ test('the proxy mark is a cat-head button without words; only a problem gives it assert.equal(c.pmark.hidden, true); }); -// The card view writes neither 运行中 nor 已关机 (the screen and the power button say it); the label stays in the DOM for -// screen readers (.pill-quiet is the sr-only styling, only in the card view), and every other state shows it. -test('the status label is only for screen readers while running or shut down', async () => { +// ModAVD/ModAVD#463: the card view shows no status label in any state (the screen says it); the label stays in the DOM +// for screen readers (the sr-only styling is in the stylesheet, only in the card view) and takes no click, focus or +// hover text there. The list view keeps it as it was. +test('the card view has no visible status label in any state; the list view keeps it', async () => { const h = await settingsHarness({ diagnostics: false }); const c = h.makeCard({ ...h.inst, status: 'online', running: true }); - const quiet = cls => cls.split(' ').includes('pill-quiet'); - assert.equal(c.pillText.textContent, '运行中'); - assert.ok(quiet(c.pill.className), c.pill.className); - h.patchCard(c, { ...h.inst, status: 'offline', running: false }); - assert.equal(c.pillText.textContent, '已关机'); - assert.ok(quiet(c.pill.className), c.pill.className); - // the states in between, the failed ones and a create in progress show it - const failed = { id: 'j9', index: 3, kind: 'start', state: 'failed', created_at: '2026-12-02T10:00:00Z', finished_at: '2026-12-02T10:00:02Z' }; - for (const [inst, text, jobs] of [ + const failed = { id: 'j9', index: 3, kind: 'start', state: 'failed', created_at: '2026-12-02T10:00:00Z', finished_at: '2026-12-02T10:00:02Z', + error: { message: '原因', advice: '建议' } }; + const states = [ + [{ ...h.inst, status: 'online', running: true }, '运行中', []], + [{ ...h.inst, status: 'offline', running: false }, '已关机', []], [{ ...h.inst, status: 'starting', running: true, busy: 'starting' }, '开机中', []], [{ ...h.inst, status: 'online', running: true, busy: 'stopping' }, '关机中', []], [{ ...h.inst, status: 'creating', running: true }, '新建中', []], [{ ...h.inst, status: 'create_failed', running: false }, '新建失败', []], [{ ...h.inst, status: 'offline', running: false }, '开机失败', [failed]], - ]) { + ]; + for (const [inst, text, jobs] of states) { h.state.jobs.clear(); for (const j of jobs) h.state.jobs.set(j.id, j); h.patchCard(c, inst); - assert.equal(c.pillText.textContent, text); - assert.ok(!quiet(c.pill.className), `${text}: ${c.pill.className}`); - assert.match(c.pill.className, /^pill tone-/); + assert.equal(c.pillText.textContent, text, 'the state name stays in the DOM for screen readers'); + assert.match(c.pill.className, /^pill tone-\w+$/, `${text}: nothing but the tone in the card view`); + assert.equal(c.pill.getAttribute('title'), null, text); + assert.equal(c.pill.getAttribute('role'), null, text); + assert.equal(c.pill.getAttribute('tabindex'), null, `${text}: the invisible label is not a tab stop`); + h.activity.length = 0; + c.pill.dispatch('click'); + for (const fn of c.pill.events.get('keydown') || []) fn({ key: 'Enter', preventDefault() {} }); + assert.deepEqual(h.activity, [], `${text}: the card view's label opens nothing`); } + // the list view still shows the label, and a failed one is the link it was + h.setView('list'); + h.patchCard(c, states.at(-1)[0]); + assert.match(c.pill.className, /\bpill-link\b/); + assert.equal(c.pill.getAttribute('tabindex'), '0'); + assert.equal(c.pill.getAttribute('title'), '开机失败:原因\n建议'); + c.pill.dispatch('click'); + assert.deepEqual(h.activity, [['j9', null]]); + h.setView('card'); h.state.jobs.clear(); - // back to running: quiet again, and the name for screen readers still has the state + // 诊断模式 stays in the status name for screen readers h.patchCard(c, { ...h.inst, status: 'online', running: true, diagnostics: true }); - assert.ok(quiet(c.pill.className)); assert.equal(c.pill.getAttribute('aria-label'), '运行中 · 诊断模式'); }); - // ModAVD/ModAVD#377: nothing is under the config line, in any state: no box for a failure, a first start, software // rendering or a nearly full disk, so no state makes a card taller. What the boxes said is in hover texts. const failedStart = { id: 'j9', index: 3, kind: 'start', state: 'failed', created_at: '2026-12-02T10:00:00Z', finished_at: '2026-12-02T10:00:02Z', @@ -760,76 +770,79 @@ test('no state puts a box under the card', async () => { test('software rendering and a nearly full disk are lines on the name hover text', async () => { const h = await settingsHarness({ diagnostics: false }); const name = inst => h.makeCard(inst).title.title; - assert.equal(name({ ...h.inst }), '编号 3 · mas_3'); - assert.equal(name({ ...h.inst, software_renderer: true }), '编号 3 · mas_3\n软件渲染:显卡驱动不可用,游戏会卡'); - assert.equal(name({ ...h.inst, data_space: lowDisk }), '编号 3 · mas_3\n数据盘只剩 1.8 GB(共 47.0 GB),改成自动扩盘:modavd set 3 --data-gb auto'); + assert.equal(name({ ...h.inst }), ''); + assert.equal(name({ ...h.inst, software_renderer: true }), '软件渲染:显卡驱动不可用,游戏会卡'); + assert.equal(name({ ...h.inst, data_space: lowDisk }), '数据盘只剩 1.8 GB(共 47.0 GB),改成自动扩盘:modavd set 3 --data-gb auto'); // a data_space without a message (the disk is fine) adds nothing; one without advice is the message alone - assert.equal(name({ ...h.inst, data_space: { state: '', message: '', advice: '' } }), '编号 3 · mas_3'); - assert.equal(name({ ...h.inst, data_space: { state: 'host_low', message: '宿主盘只剩 12.0 GB', advice: '' } }), '编号 3 · mas_3\n宿主盘只剩 12.0 GB'); + assert.equal(name({ ...h.inst, data_space: { state: '', message: '', advice: '' } }), ''); + assert.equal(name({ ...h.inst, data_space: { state: 'host_low', message: '宿主盘只剩 12.0 GB', advice: '' } }), '宿主盘只剩 12.0 GB'); // one line each, after the diagnostics line assert.equal(name({ ...h.inst, title: '星铁', diagnostics: true, software_renderer: true, data_space: lowDisk }), - '编号 3 · mas_3\n星铁\n诊断模式\n软件渲染:显卡驱动不可用,游戏会卡\n数据盘只剩 1.8 GB(共 47.0 GB),改成自动扩盘:modavd set 3 --data-gb auto'); + '星铁\n诊断模式\n软件渲染:显卡驱动不可用,游戏会卡\n数据盘只剩 1.8 GB(共 47.0 GB),改成自动扩盘:modavd set 3 --data-gb auto'); const c = h.makeCard({ ...h.inst, software_renderer: true, data_space: lowDisk }); assert.equal(c.pill.getAttribute('aria-label'), null, 'the status name for screen readers does not carry them'); }); -test('a failed boot or create: the reason is the status label hover text, and the label opens 问题反馈 at the task', async () => { +test('a failed boot or create: the reason is the screen hover text, and the screen opens 问题反馈 at the task', async () => { const h = await settingsHarness({ diagnostics: false }); - const quiet = cls => cls.split(' ').includes('pill-quiet'); h.state.jobs.clear(); h.state.jobs.set(failedStart.id, failedStart); const c = h.makeCard({ ...h.inst, status: 'offline', running: false }); - assert.equal(c.pillText.textContent, '开机失败'); - assert.equal(c.pill.getAttribute('title'), '开机失败:电脑内存不足,模拟器分不到实例的内存\n请关闭部分程序、调小实例内存'); - assert.equal(c.pill.getAttribute('aria-label'), '开机失败 · 查看详情'); - assert.equal(c.pill.getAttribute('role'), 'button'); - assert.equal(c.pill.getAttribute('tabindex'), '0'); - assert.match(c.pill.className, /\bpill-link\b/); assert.equal(c.el.dataset.status, 'error'); - assert.equal(c.phText.textContent, '上次开机没有成功'); - // click, Enter and Space open 问题反馈 at the failed job; other keys do nothing - c.pill.dispatch('click'); - for (const key of ['Enter', ' ', 'a']) for (const fn of c.pill.events.get('keydown')) fn({ key, preventDefault() {} }); + assert.equal(c.phText.textContent, '开机失败', 'the screen says it'); + assert.equal(c.screen.title, '开机失败:电脑内存不足,模拟器分不到实例的内存\n请关闭部分程序、调小实例内存'); + assert.equal(c.screen.getAttribute('aria-label'), '开机失败 · 查看详情'); + assert.equal(c.screen.getAttribute('role'), 'button'); + assert.equal(c.screen.getAttribute('tabindex'), '0'); + assert.equal(c.screen.getAttribute('aria-disabled'), null); + // the label is not the way in any more (no title, no button role, no tab stop); screen readers still read its text + assert.equal(c.pillText.textContent, '开机失败'); + assert.equal(c.pill.getAttribute('title'), null); + assert.equal(c.pill.getAttribute('tabindex'), null); + // click, Enter and Space on the screen open 问题反馈 at the failed job (not a start); other keys do nothing + const started = h.started; + c.screen.dispatch('click'); + for (const key of ['Enter', ' ', 'a']) for (const fn of c.screen.events.get('keydown')) fn({ key, preventDefault() {} }); assert.deepEqual(h.activity, [['j9', null], ['j9', null], ['j9', null]]); - // with the diagnostics line the title and the name carry it too + if (started) assert.deepEqual(started, []); + // with the diagnostics line: it is on the name's hover text, not the screen's h.patchCard(c, { ...h.inst, status: 'offline', running: false, diagnostics: true }); - assert.equal(c.pill.getAttribute('title'), '开机失败:电脑内存不足,模拟器分不到实例的内存\n请关闭部分程序、调小实例内存\n诊断模式'); - assert.equal(c.pill.getAttribute('aria-label'), '开机失败 · 诊断模式 · 查看详情'); + assert.equal(c.title.title, '诊断模式'); + assert.equal(c.screen.title, '开机失败:电脑内存不足,模拟器分不到实例的内存\n请关闭部分程序、调小实例内存'); // nothing on the card closes it: it stays through updates, until a newer job (the next boot) starts h.patchCard(c, { ...h.inst, status: 'offline', running: false }); - assert.equal(c.pillText.textContent, '开机失败'); + assert.equal(c.phText.textContent, '开机失败'); assert.equal(h.state.dismissed, undefined, 'there is no way to dismiss it any more'); h.state.jobs.set('j10', { id: 'j10', index: 3, kind: 'start', state: 'running', created_at: '2026-12-02T10:05:00Z' }); h.patchCard(c, { ...h.inst, status: 'starting', running: true, busy: 'starting' }); assert.equal(c.pillText.textContent, '开机中'); - assert.equal(c.pill.getAttribute('title'), null); - assert.equal(c.pill.getAttribute('role'), null); - assert.equal(c.pill.getAttribute('tabindex'), null); - assert.doesNotMatch(c.pill.className, /pill-link/); + assert.equal(c.screen.title, null); + assert.equal(c.screen.getAttribute('aria-label'), null); h.activity.length = 0; - c.pill.dispatch('click'); - assert.deepEqual(h.activity, [], 'a label that is not a failure opens nothing'); - // a failed job of another kind is not a card state: the label stays quiet and opens nothing + c.screen.dispatch('click'); + assert.deepEqual(h.activity, [], 'a screen that is not a failure opens no 问题反馈'); + // a failed job of another kind is not a card state: the screen is the plain 开机 one and opens nothing h.state.jobs.clear(); h.state.jobs.set('j11', { ...failedStart, id: 'j11', kind: 'install' }); h.patchCard(c, { ...h.inst, status: 'offline', running: false }); assert.equal(c.pillText.textContent, '已关机'); - assert.ok(quiet(c.pill.className)); - c.pill.dispatch('click'); + assert.equal(c.screen.getAttribute('aria-label'), '开机'); + c.screen.dispatch('click'); assert.deepEqual(h.activity, []); - // 新建失败: the reason and the advice (with the log) on hover; its create job when there is one, else the instance's own row + // 新建失败: the reason and the advice (with the log) on the screen's hover; its create job when there is one, else the instance's own row h.state.jobs.clear(); const created = { ...h.inst, status: 'create_failed', running: false, initialized: false, creation_error: '后台开机做初始化时模拟器退出了', creation_log: 'logs\\mas_3.log' }; const cf = h.makeCard(created); assert.equal(cf.pillText.textContent, '新建失败'); - assert.equal(cf.pill.getAttribute('title'), '新建失败:后台开机做初始化时模拟器退出了\n点「重试初始化」再做一次,或在「更多」里删除这台实例;日志 logs\\mas_3.log'); - assert.equal(cf.pill.getAttribute('aria-label'), '新建失败 · 查看详情'); - cf.pill.dispatch('click'); + assert.equal(cf.phText.textContent, '新建失败'); + assert.equal(cf.screen.title, '新建失败:后台开机做初始化时模拟器退出了\n点「重试初始化」再做一次,或在「更多」里删除这台实例;日志 logs\\mas_3.log'); + assert.equal(cf.screen.getAttribute('aria-label'), '新建失败 · 查看详情'); + cf.screen.dispatch('click'); assert.deepEqual(h.activity, [[null, 3]]); h.state.jobs.set('j12', { ...failedStart, id: 'j12', kind: 'create' }); h.patchCard(cf, created); - cf.pill.dispatch('click'); + cf.screen.dispatch('click'); assert.deepEqual(h.activity, [[null, 3], ['j12', null]]); // the newest 新建 / 重试初始化 task, failed or canceled, is the row (问题反馈 lists the instance as that task); a newer // task of another kind does not take its place @@ -837,17 +850,16 @@ test('a failed boot or create: the reason is the status label hover text, and th h.state.jobs.set('j14', { ...failedStart, id: 'j14', kind: 'disk-compact', state: 'done', created_at: '2026-12-02T10:02:00Z' }); h.patchCard(cf, created); h.activity.length = 0; - cf.pill.dispatch('click'); + cf.screen.dispatch('click'); assert.deepEqual(h.activity, [['j13', null]]); h.patchCard(cf, { ...created, creation_error: '', creation_log: '' }); - assert.equal(cf.pill.getAttribute('title'), '新建失败:初始化没做完\n点「重试初始化」再做一次,或在「更多」里删除这台实例'); - // no 调小内存 link (it is on the task in 问题反馈), no dismiss button, no 详情 link: the visible text buttons are the retry and 画面 controls - const buttons = descendants(cf.el).filter(x => x.tagName === 'BUTTON').map(x => x.textContent.trim()).filter(Boolean); + assert.equal(cf.screen.title, '新建失败:初始化没做完\n点「重试初始化」再做一次,或在「更多」里删除这台实例'); + // no 调小内存 link (it is on the task in 问题反馈), no dismiss button, no 详情 link: the visible text buttons are the retry and 画面 controls (not the A mark) + const buttons = descendants(cf.el).filter(x => x.tagName === 'BUTTON' && x !== cf.adbTag).map(x => x.textContent.trim()).filter(Boolean); assert.deepEqual(buttons, ['重试初始化', '画面']); assert.doesNotMatch(cf.el.textContent, /调小内存|不再显示|详情/); h.state.jobs.clear(); }); - test('the first start of a new instance is a line on the 开机 button hover text', async () => { const h = await settingsHarness({ diagnostics: false, running: false }); const line = '首次开机会做初始化,约 1⁠–⁠2 分钟'; @@ -869,27 +881,34 @@ test('the first start of a new instance is a line on the 开机 button hover tex // The styling the tests above rely on, read from the stylesheet: quiet is the sr-only way (not display: none, which // would take it from screen readers) and only in the card view; the card head keeps the label's height; the proxy mark // is plain unless it carries tone-warn or tone-err; the name takes the width so the marks are at the right end. -test('the stylesheet hides the quiet status label for the card view only and keeps the card height', async () => { +test('the stylesheet hides the status label in the card view only and keeps the card height', async () => { const css = await readFile(new URL('../internal/ui/web/app.css', import.meta.url), 'utf8'); const rule = sel => { const i = css.indexOf(sel + ' {'); assert.ok(i >= 0, sel); return css.slice(i, css.indexOf('}', i)); }; - const srOnly = rule('.sr-only, .grid:not(.is-list) .pill-quiet'); + const srOnly = rule('.sr-only, .grid:not(.is-list) .pill'); assert.match(srOnly, /position: absolute; width: 1px; height: 1px/); assert.match(srOnly, /clip: rect\(0 0 0 0\)/); - assert.doesNotMatch(css, /pill-quiet[^{]*\{[^}]*display: none/); + assert.doesNotMatch(css, /\.grid:not\(\.is-list\) \.pill[^{]*\{[^}]*display: none/); + assert.doesNotMatch(css, /pill-quiet/); assert.match(rule('.grid:not(.is-list) .card-head'), /min-height: 23px/); assert.match(rule('.grid:not(.is-list) .card-tline .card-title'), /flex: 1/); - assert.doesNotMatch(rule('.pmark'), /var\(--tb\)/, 'plain by default'); - assert.match(rule('.pmark.tone-warn, .pmark.tone-err'), /background: var\(--tb\); color: var\(--tf\)/); + assert.doesNotMatch(rule('.pmark, .smark, .kmark, .hmark'), /var\(--(tb|sunken)\)/, 'no background colour behind a mark'); + assert.doesNotMatch(rule('.pmark.tone-warn, .pmark.tone-err'), /background/, 'the state colour is the icon only'); + assert.doesNotMatch(rule('.adb-tag'), /var\(--tb\)/); + assert.match(rule('.hmark .ic'), /width: 12\.83px; height: 12\.83px/, 'the monitor drawing is 12.5px of ink at 16px: 10px at 12.83px, the cap height of the 14px letters'); + assert.match(rule('.pmark.tone-warn, .pmark.tone-err'), /color: var\(--tf\)/); // no box under the card in either view: no styles for it, and the list row is one grid row assert.doesNotMatch(css, /\.notes\b|\.note \{|\.note-main|\.note-text|\.note-adv|\.note-links|\.is-list \.note\b/); assert.match(rule('.is-list .card'), /grid-template-areas: "pill title cfg adb power view more";/); assert.match(rule('.grid:not(.is-list) .card-actions'), /display: none/); assert.match(rule('.grid:not(.is-list) .card-body'), /gap: 4px/); assert.match(rule('.adb-tag'), /display: inline-grid/); + assert.match(rule('.card-title'), /font-size: 15px/); + assert.match(rule('.smark, .kmark'), /font-size: 14px/); + assert.match(rule('.pmark, .smark, .kmark, .hmark'), /box-shadow: inset 0 0 0 1px var\(--line-2\)/, 'a thin frame, no background colour'); assert.match(rule('.pill-link'), /cursor: pointer/); }); @@ -927,14 +946,16 @@ test('card screen: one button, decoration inside, and every hidden power action assert.equal((c.peek.events.get('click') || []).length, 0); c.screen.dispatch('click'); assert.deepEqual(opened, [3], 'one click, one viewer'); - // a failed create: the screen retries the setup + // a failed create: the screen opens 问题反馈 (ModAVD/ModAVD#463); the retry is in 更多 const f = h.makeCard({ ...h.inst, status: 'create_failed', running: false, initialized: false }); assert.equal(f.primary.dataset.mode, 'resume'); assert.equal(f.screen.getAttribute('tabindex'), '0'); - assert.equal(f.screen.getAttribute('aria-label'), '重试初始化'); + assert.equal(f.screen.getAttribute('aria-label'), '新建失败 · 查看详情'); f.screen.dispatch('click'); - assert.deepEqual(resumed, [3]); + assert.deepEqual(resumed, []); + assert.deepEqual(h.activity, [[null, 3]]); assert.deepEqual(started, []); + h.activity.length = 0; // a stopped one starts, with the first start's line as the screen's hover text const s = h.makeCard({ ...h.inst, status: 'offline', running: false, initialized: false }); assert.equal(s.screen.title, '首次开机会做初始化,约 1⁠–⁠2 分钟'); @@ -944,14 +965,22 @@ test('card screen: one button, decoration inside, and every hidden power action assert.equal(s.screen.title, null); h.patchCard(s, { ...h.inst, status: 'online', running: true, initialized: false }); assert.equal(s.screen.title, null); - // the menu: 关机 for a running instance and 重试初始化 for a failed create in the card view, neither in the list view + // the menu: 关机 for a running instance, 重试初始化 for a failed create and 开机 for a failed boot in the card view, none in the list view const labels = inst => h.cards.menuItems({ i: 3, inst }).filter(Boolean).map(x => x.label); const on = { index: 3, status: 'online', running: true }, bad = { index: 3, status: 'create_failed', running: false }; assert.ok(labels(on).includes('关机')); assert.ok(labels(bad).includes('重试初始化')); + h.state.jobs.set(failedStart.id, failedStart); + const failedBoot = { index: 3, status: 'offline', running: false }; + assert.ok(labels(failedBoot).includes('开机'), 'a failed boot is retried from 更多'); + h.state.jobs.clear(); + assert.ok(!labels(failedBoot).includes('开机'), 'a plain shut down instance starts from the screen'); + h.state.jobs.set(failedStart.id, failedStart); h.setView('list'); assert.ok(!labels(on).includes('关机'), 'the list view has the power button'); assert.ok(!labels(bad).includes('重试初始化')); + assert.ok(!labels(failedBoot).includes('开机')); + h.state.jobs.clear(); h.setView('card'); assert.ok(labels(on).includes('关机')); }); diff --git a/scripts/test_topbar_ui.mjs b/scripts/test_topbar_ui.mjs index c4e12a51..e663975a 100644 --- a/scripts/test_topbar_ui.mjs +++ b/scripts/test_topbar_ui.mjs @@ -765,6 +765,96 @@ test('the viewer says where to go while the root cannot boot', async () => { await turns(1); }); +test('the live viewer draws raw pixels, skips 204s, pauses when hidden and cancels on close', async () => { + const document = new Element('document'); + document.visibilityState = 'visible'; + document.removeEventListener = (type, fn) => { + document.events.set(type, (document.events.get(type) || []).filter(handler => handler !== fn)); + }; + const timers = new Map(); + const requests = []; + const callbacks = []; + const draws = []; + let nextTimer = 0, dialog, clock = 0; + const visible = { index: 3, status: 'online', title: 'Test' }; + const { mod } = await load('viewer.js', { + 'api.js': { api: { get: (path, { signal }) => new Promise((resolve, reject) => { + requests.push({ path, signal, resolve }); + signal.addEventListener('abort', () => reject(signal.reason), { once: true }); + }) } }, + 'i18n.js': { t: text => text }, + 'dom.js': { ...dom, h(tag, props, ...kids) { + const el = h(tag, props, ...kids); + if (tag === 'input') el.value = props.value; // the target-fps slider, as a browser reflects it + if (tag === 'canvas') el.getContext = () => ({ + putImageData: image => draws.push(['pixels', [...image.data]]), + setTransform: (...args) => draws.push(['transform', ...args]), + drawImage: () => draws.push(['draw']), + }); + return el; + } }, + 'store.js': { S: { info: {}, pending: {} }, subscribe: () => noop, instance: () => visible, rootBlocked: () => false }, + 'ui.js': { openDialog: options => { + dialog = options; + return { subEl: { id: 'viewer-sub' }, onClose: callbacks }; + } }, + 'format.js': { label: inst => inst.title }, + 'actions.js': {}, + 'bootview.js': { createBootScreen: () => ({ el: h('div'), update: noop }) }, + 'panels.js': { openComponents: noop }, + }, { + document, AbortController, AbortSignal, performance: { now: () => clock }, + setTimeout: (fn, ms) => { timers.set(++nextTimer, { fn, ms }); return nextTimer; }, + clearTimeout: id => timers.delete(id), + ImageData: class { constructor(data) { this.data = data; } }, + }); + const tick = () => { + assert.equal(timers.size, 1); + const [id, { fn }] = [...timers][0]; + timers.delete(id); + return fn(); + }; + const nextDelay = () => [...timers.values()][0].ms; + mod.openViewer(3); + let polling = tick(); + assert.match(requests[0].path, /\?format=rgba&after=$/); + assert.equal(timers.size, 0, 'a request in flight must not queue another poll'); + requests[0].resolve({ status: 200, + arrayBuffer: async () => Uint8Array.of(1, 2, 3, 0, 4, 5, 6, 0, 9, 9, 9, 9).buffer, + headers: new Headers({ 'X-Shot-Frame': 'frame-1', 'X-Shot-Width': '2', 'X-Shot-Height': '1', + 'X-Shot-Stride': '12', 'X-Shot-Rotation': '90' }) }); + clock = 10; + await polling; + // Default 15 fps: the next poll is due 66.7 ms after this one started, not after it finished. + assert.ok(Math.abs(nextDelay() - (1000 / 15 - 10)) < 1e-9); + const canvas = all(dialog.body).find(el => el.tagName === 'CANVAS'); + assert.deepEqual([canvas.width, canvas.height], [1, 2]); + assert.deepEqual(draws, [['pixels', [1, 2, 3, 255, 4, 5, 6, 255]], ['transform', 0, -1, 1, 0, 0, 2], ['draw']]); + clock = 78; // the timer fired late, as Windows rounds longer timers up to its 15.6 ms tick + polling = tick(); + assert.match(requests.at(-1).path, /\?format=rgba&after=frame-1$/); + clock = 80; + requests.at(-1).resolve({ status: 204 }); + await polling; + assert.ok(Math.abs(nextDelay() - (2000 / 15 - 80)) < 1e-9, 'a late timer must not push back the next frame'); + assert.equal(draws.length, 3, '204 must keep the canvas as it was'); + assert.equal(all(dialog.tools).some(el => el.classList.contains('viewer-status')), false); + + polling = tick(); + document.visibilityState = 'hidden'; + await document.dispatch('visibilitychange'); + await polling; + assert.equal(requests.at(-1).signal.aborted, true); + assert.equal(timers.size, 0); + document.visibilityState = 'visible'; + await document.dispatch('visibilitychange'); + polling = tick(); + callbacks.forEach(fn => fn()); + await polling; + assert.equal(requests.at(-1).signal.aborted, true); + assert.equal(timers.size, 0); +}); + // ---- keymap.js: offline profile drafts and revision conflicts test('a guarded dialog keeps Escape cancelable and releases the toast host on native close', async () => {