From c3f04693713929daa0a03f6414b8348ad466cef5 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 5 Dec 2026 20:54:01 +0100 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=97=B6=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E5=85=B3=E6=8E=89=E6=9C=AC=E6=A0=B9=E7=9B=AE=E5=BD=95=E7=9A=84?= =?UTF-8?q?=20MCP=20=E6=9C=8D=E5=8A=A1=EF=BC=8C=E4=B8=8D=E5=86=8D=E6=8B=A6?= =?UTF-8?q?=E4=B8=8B=E6=9D=A5=E8=AE=A9=E7=94=A8=E6=88=B7=E5=8E=BB=E5=85=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新(管理器和命令行 modavd update 都走 update 包换包前的检查)扫描时,把本根 tools\modavd.exe 跑的 `mcp`(只带 --root=本根 / --json / --quiet / --verbose) 认作 MCP 服务:在 .update\mcp-exit\ 写下它的进程创建时间请它退出,MCP 服务 每 0.5 秒查一次,对上了就照 EOF 的路径收尾(写文件的请求先做完)并在 stderr 说明 原因;更新这边最多等 40 秒,没退的按扫描时记下的 PID(核对创建时间和映像)强制 结束。持锁后的最终扫描若只剩新拉起的 MCP 服务,再关一次再扫。别的 modavd 命令行 照旧拦。ProgramsInUse、管理器提示、占用报错、命令行帮助、README 和 MACOS 文档 去掉要用户关 MCP 客户端的说法。 Refs ModAVD/ModAVD#461 --- README.en.md | 2 +- README.md | 2 +- changelog.d/461-mcp-stop-on-update.change.md | 2 + internal/cli/commands.go | 5 +- internal/i18n/locales/en/cli.json | 2 +- internal/i18n/locales/en/mcp.json | 1 + internal/i18n/locales/en/ui.json | 2 +- internal/i18n/locales/en/update.json | 6 +- internal/mcp/mcp.go | 16 +- internal/mcp/mcp_test.go | 62 ++++ internal/ui/update_apply.go | 5 +- internal/ui/update_apply_test.go | 4 + internal/update/MACOS.en.md | 2 +- internal/update/MACOS.md | 2 +- internal/update/handoff.go | 9 +- internal/update/inuse_test.go | 2 +- internal/update/mcpstop.go | 200 +++++++++++ internal/update/mcpstop_test.go | 349 +++++++++++++++++++ internal/update/mcpstop_windows_test.go | 229 ++++++++++++ internal/update/native_guard_darwin.go | 16 +- internal/update/process_scan_windows_test.go | 2 +- internal/update/swap.go | 57 ++- 22 files changed, 946 insertions(+), 31 deletions(-) create mode 100644 changelog.d/461-mcp-stop-on-update.change.md create mode 100644 internal/update/mcpstop.go create mode 100644 internal/update/mcpstop_test.go create mode 100644 internal/update/mcpstop_windows_test.go 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/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/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/ui.json b/internal/i18n/locales/en/ui.json index 9cd0292f..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", 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/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/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/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/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) }