Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ modavd [--root <dir>] [--json] [--quiet] [--verbose] <command> [args]
modavd mcp --root D:\ModAVD
```

It supports both MCP 2026-07-28 (stateless, `server/discover`) and 2025-11-25 / 2025-06-18 (`initialize` handshake). The root folder is fixed at startup and is not a tool parameter. Tools: `list_instances`, `get_instance`, `check_host`, `create_instance`, `update_instance`, `delete_instance`, `start_instance` (with progress), `stop_instance`, `set_window_visible`, `shell`, `install_apk`.
It supports both MCP 2026-07-28 (stateless, `server/discover`) and 2025-11-25 / 2025-06-18 (`initialize` handshake). The root folder is fixed at startup and is not a tool parameter. Tools: `list_instances`, `get_instance`, `check_host`, `create_instance`, `update_instance`, `delete_instance`, `start_instance` (with progress), `stop_instance`, `set_window_visible`, `shell`, `install_apk`, `disk_info` (data disk size), `trim_disk` (reclaim space while running; the emulator must support discard), `compact_disk` (shrink the data disk; the instance must be stopped).

To register it in Claude Code (in PowerShell, `--` needs quotes, or it gets swallowed):

Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数]
| `start <i> [--window \| --headless] [--timeout 300] [--no-bridge]` | 开机(默认无头,`--window` 带窗口),等开完并做完开机后的设置,返回前确认 `/sdcard` 能写进文件(一般这时早已就绪;最多再等 60 秒,到点只警告);实例正在关机时(比如刚点了模拟器窗口的 ×)先等它关完(最多 30 秒)再开机;实例还没有执行桥时接着装上,`--no-bridge` 这次不装。运行中不换方式:实例已经在运行时,给了 `--window` / `--headless` 而它不是这种方式,就报错(退出码 5),不接管也不重启,要换先 `stop` 再 `start`;两个都不给就照原样接管 |
| `stop <i> [--force]`、`stop --all` | 关机:前台开着应用时先按 HOME,等 2 秒让它保存;再 sync,让安卓正常关机(前台应用先收到暂停、停止),不成再 sync + kill;`--force` 是 sync + 强杀 |
| `bridge <i> install\|uninstall\|verify` | 装、卸、检查 arm64 执行桥;开机时会自动装,一般不用手动跑(见下) |
| `disk <i> trim` | 磁盘回收:在开着的实例里对数据盘触发一次 FITRIM,让模拟器释放已删文件占着的空间;模拟器太旧、不支持回收时返回不支持(退出码 4) |
| `disk <i> info` | 看数据盘的大小:逻辑大小、覆盖层在宿主上实际占的空间;实例关机时再给已分配的大小和估计能回收多少(开着时这两个数要关机后才有);只读 |
| `disk <i> compact` | 整理数据盘:关机状态下把覆盖层重写一遍、丢掉已释放的簇、把文件缩小;转换后先校验再原子替换,原盘在替换成功前不动;仅在 NTFS/ReFS 卷上进行,实例有快照、或剩余空间不够放下新文件时拒绝 |
| `check [--memory M]` | 开机前的电脑检查 |
| `report-config [--no-clipboard]` | 复制电脑配置和开着实例里的游戏信息(只读) |
| `collect-info [--out-dir D] [--stage-dir D] [--keep-stage] [--no-explorer]` | 收集问题信息并打包(只读) |
Expand Down Expand Up @@ -134,7 +137,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数]
modavd mcp --root D:\ModAVD
```

同时支持 MCP 2026-07-28(无状态,`server/discover`)和 2025-11-25 / 2025-06-18(`initialize` 握手)。根目录在启动时定,不是工具参数。工具:`list_instances`、`get_instance`、`check_host`、`create_instance`、`update_instance`、`delete_instance`、`start_instance`(带进度)、`stop_instance`、`set_window_visible`、`shell`、`install_apk`。
同时支持 MCP 2026-07-28(无状态,`server/discover`)和 2025-11-25 / 2025-06-18(`initialize` 握手)。根目录在启动时定,不是工具参数。工具:`list_instances`、`get_instance`、`check_host`、`create_instance`、`update_instance`、`delete_instance`、`start_instance`(带进度)、`stop_instance`、`set_window_visible`、`shell`、`install_apk`、`disk_info`(数据盘大小)、`trim_disk`(开机态回收空间,模拟器要支持 discard)、`compact_disk`(关机态整理数据盘,实例须已关机)。

在 Claude Code 里注册(PowerShell 里 `--` 要加引号,否则会被吞掉):

Expand Down
2 changes: 1 addition & 1 deletion internal/cli/args_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ func TestCommandTable(t *testing.T) {
}
}
for _, name := range []string{"list", "info", "status", "create", "set", "delete", "start", "stop",
"check", "report-config", "collect-info", "window", "install", "shell", "adb", "servers", "version", "mcp", "help"} {
"check", "report-config", "collect-info", "window", "disk", "install", "shell", "adb", "servers", "version", "mcp", "help"} {
if !seen[name] {
t.Errorf("command %s missing", name)
}
Expand Down
8 changes: 7 additions & 1 deletion internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
// report-config [--no-clipboard] read-only configuration and installed-game report
// collect-info [--out-dir D] [--stage-dir D] ... read-only diagnostics zip
// window <i> show|hide emu.WindowResult
// disk <i> trim emu.DiskTrimResult {index,discard_max_bytes}
// disk <i> info emu.DiskInfoResult {index,overlay,running,needs_shutdown,logical_bytes,on_disk_bytes,allocated_bytes?,reclaimable_bytes?}
// disk <i> compact emu.DiskCompactResult {index,overlay,before_on_disk_bytes,after_on_disk_bytes,freed_bytes}
// install <i> <apk> emu.InstallResult
// shell <i> [--timeout S] <command...> emu.ShellResult
// adb <i> [--] <adb args...> no envelope: adb's own stdio and exit code
Expand Down Expand Up @@ -52,7 +55,7 @@
// (errs.Canceled); an emulator that was already launched keeps running (emu guarantees that). A run during which the
// context ended fails with errs.Canceled even when the command returned a result, unless the command is final (its
// result reports a change that was made: create, set, delete, start, stop, window, install, components fetch;
// or does not depend on the context: version, help, components status): a query whose adb calls were killed half way
// or does not depend on the context: version, help, components status; also bridge and disk trim / info): a query whose adb calls were killed half way
// would report what it saw by then, an online instance as starting. components fetch stops at Ctrl+C with
// errs.Canceled itself, between two reads of a download or an unpack and before the next component.
//
Expand Down Expand Up @@ -96,6 +99,9 @@ type manager interface {
AdbPassthrough(ctx context.Context, i int, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error)
InstallAPK(ctx context.Context, i int, apkPath string) (*emu.InstallResult, error)
Bridge(ctx context.Context, i int, action string) (*emu.BridgeResult, error)
DiskTrim(ctx context.Context, i int) (*emu.DiskTrimResult, error)
DiskInfo(ctx context.Context, i int) (*emu.DiskInfoResult, error)
DiskCompact(ctx context.Context, i int) (*emu.DiskCompactResult, error)
EnsureServers(ctx context.Context) (*emu.ServersResult, error)
// Running is the indexes whose qemu runs, from the process table only (no adb).
Running(ctx context.Context) ([]int, error)
Expand Down
41 changes: 41 additions & 0 deletions internal/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,19 @@ func init() {
final: true,
run: runBridge, human: humanOf(formatBridge), exit: exitBridge,
},
{
name: "disk", args: "<i> trim|info|compact", summary: "磁盘回收:触发回收或整理把客体已删文件占的空间还给宿主;看数据盘大小",
details: "trim:在客体的数据盘(/data)上触发一次回收(FITRIM,经 vold 空闲维护)," +
"让模拟器释放已删除文件在数据盘镜像里占着的空间。实例要开着并已开机完成;" +
"模拟器版本太旧、数据盘不支持回收时返回不支持(退出码 4),不会白跑。" +
"info:报数据盘的逻辑大小、在宿主上实际占的空间,以及(实例关机时)已分配的大小和估计能回收多少;" +
"实例开着时已分配和可回收的数要关机后才有,只读,不改任何东西。" +
"compact:关机状态下把数据盘覆盖层重写一遍、丢掉已释放的簇、把文件缩小;" +
"转换后先校验(check + compare)再原子替换,原盘在替换成功前不动;实例有快照时拒绝。",
posNames: []string{"实例编号", "trim、info 或 compact"}, minPos: 2, maxPos: 2,
final: true,
run: runDisk, human: formatDiskHuman,
},
{
name: "install", args: "<i> <apk>", summary: "在已开机的实例上安装 APK(adb install -r)",
details: "最多等 900 秒(游戏安装包有 1–3 GB)。",
Expand Down Expand Up @@ -992,6 +1005,34 @@ func runBridge(c *cmdCtx) (any, error) {
return m.Bridge(c.ctx, i, action)
}

// runDisk dispatches `disk <i> <action>` (trim, info, compact); add a case per new action.
func runDisk(c *cmdCtx) (any, error) {
i, err := parseIndex(c.inv.pos[0])
if err != nil {
return nil, err
}
action := strings.ToLower(c.inv.pos[1])
switch action {
case "trim", "info", "compact":
default:
return nil, errs.Newf(errs.Usage, "第二个参数只能是 trim、info 或 compact,收到「%s」", c.inv.pos[1]).
WithAdvice(findCommand("disk").usageAdvice())
}
m, err := c.mgr()
if err != nil {
return nil, err
}
switch action {
case "trim":
return m.DiskTrim(c.ctx, i)
case "info":
return m.DiskInfo(c.ctx, i)
case "compact":
return m.DiskCompact(c.ctx, i)
}
return nil, errs.Newf(errs.Internal, "disk 动作 %s 没有实现", action)
}

// exitBridge: 1 when the bridge did not end up as asked (installed after install, gone after uninstall), the script's
// exit code for verify. --json: 0, the result says it.
func exitBridge(data any, json bool) int {
Expand Down
54 changes: 54 additions & 0 deletions internal/cli/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,60 @@ func formatBridge(w io.Writer, r *emu.BridgeResult) {
}
}

func formatDisk(w io.Writer, r *emu.DiskTrimResult) {
fmt.Fprintf(w, "实例 %d 已触发磁盘回收(trim)\n", r.Index)
}

// formatDiskHuman picks the text form of a `disk` result by its type (trim and info return different results).
func formatDiskHuman(w io.Writer, data any) {
switch r := data.(type) {
case *emu.DiskTrimResult:
if r != nil {
formatDisk(w, r)
}
case *emu.DiskInfoResult:
if r != nil {
formatDiskInfo(w, r)
}
case *emu.DiskCompactResult:
if r != nil {
formatDiskCompact(w, r)
}
}
}

func formatDiskCompact(w io.Writer, r *emu.DiskCompactResult) {
fmt.Fprintf(w, "实例 %d 整理磁盘完成:覆盖层占用 %s → %s,省下 %s\n",
r.Index, fmtBytesGB(r.BeforeOnDiskBytes), fmtBytesGB(r.AfterOnDiskBytes), fmtBytesGB(r.FreedBytes))
}

// fmtBytesGB is a byte count in GB with one decimal ("12.3 GB").
func fmtBytesGB(b int64) string {
return fmt.Sprintf("%.1f GB", float64(b)/(1<<30))
}

func formatDiskInfo(w io.Writer, r *emu.DiskInfoResult) {
kv := func(k, v string) { fmt.Fprintf(w, "%s:%s\n", k, v) }
state := "已关机"
if r.Running {
state = "运行中"
}
kv("实例", strconv.Itoa(r.Index)+"("+state+")")
if r.LogicalBytes > 0 {
kv("数据盘逻辑大小", fmtBytesGB(r.LogicalBytes))
}
kv("覆盖层在宿主上占用", fmtBytesGB(r.OnDiskBytes))
if r.AllocatedBytes != nil {
kv("已分配(客体实际数据)", fmtBytesGB(*r.AllocatedBytes))
}
if r.ReclaimableBytes != nil {
kv("估计可回收", fmtBytesGB(*r.ReclaimableBytes))
}
for _, s := range r.Warnings {
fmt.Fprintln(w, "注意:"+s)
}
}

func formatShell(w io.Writer, r *emu.ShellResult) {
if r.Output == "" {
return
Expand Down
104 changes: 104 additions & 0 deletions internal/cli/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,31 @@ func (f *fakeManager) Bridge(ctx context.Context, i int, action string) (*emu.Br
return &emu.BridgeResult{Index: i, Action: action, Installed: action == "install", Warnings: []string{}}, nil
}

func (f *fakeManager) DiskTrim(ctx context.Context, i int) (*emu.DiskTrimResult, error) {
f.record("disk-trim " + itoa(i))
return &emu.DiskTrimResult{Index: i, DiscardMaxBytes: 2147483648}, nil
}

func (f *fakeManager) DiskInfo(ctx context.Context, i int) (*emu.DiskInfoResult, error) {
f.record("disk-info " + itoa(i))
const gb = int64(1) << 30
if i == 4 { // running: no allocated / reclaimable
return &emu.DiskInfoResult{Index: i, Overlay: "x", Running: true, NeedsShutdown: true,
LogicalBytes: 8 * gb, OnDiskBytes: 3 * gb,
Warnings: []string{"实例在运行:已分配和可回收的大小要关机后才能算"}}, nil
}
alloc, rec := 2*gb, gb
return &emu.DiskInfoResult{Index: i, Overlay: "x", LogicalBytes: 8 * gb, OnDiskBytes: 3 * gb,
ClusterBytes: 65536, AllocatedBytes: &alloc, ReclaimableBytes: &rec}, nil
}

func (f *fakeManager) DiskCompact(ctx context.Context, i int) (*emu.DiskCompactResult, error) {
f.record("disk-compact " + itoa(i))
const gb = int64(1) << 30
return &emu.DiskCompactResult{Index: i, Overlay: "x", BeforeOnDiskBytes: 3 * gb,
AfterOnDiskBytes: 2 * gb, FreedBytes: gb}, nil
}

func (f *fakeManager) InstallAPK(ctx context.Context, i int, apkPath string) (*emu.InstallResult, error) {
f.record("install " + itoa(i) + " " + apkPath)
if f.install != nil {
Expand Down Expand Up @@ -995,6 +1020,85 @@ func TestInstallMakesPathAbsolute(t *testing.T) {
}
}

func TestDiskTrim(t *testing.T) {
h := newHarness()
r := h.run(t, nil, "disk", "3", "trim")
if r.code != 0 || r.stdout != "实例 3 已触发磁盘回收(trim)\n" {
t.Errorf("text: code %d stdout %q stderr %q", r.code, r.stdout, r.stderr)
}
if got := h.fake.callList(); len(got) != 1 || got[0] != "disk-trim 3" {
t.Errorf("calls = %q", got)
}
r = h.run(t, nil, "--json", "disk", "mas_3", "TRIM")
if m := envelope(t, r.stdout); m["ok"] != true {
t.Errorf("json: %s", r.stdout)
}
if !strings.Contains(r.stdout, `"discard_max_bytes":2147483648`) {
t.Errorf("json data: %s", r.stdout)
}
// an unknown action is a usage error and reaches no manager
h = newHarness()
r = h.run(t, nil, "disk", "3", "flatten")
if r.code != 2 || len(h.fake.callList()) != 0 {
t.Errorf("bad action: code %d calls %q stderr %q", r.code, h.fake.callList(), r.stderr)
}
}

func TestDiskCompact(t *testing.T) {
h := newHarness()
r := h.run(t, nil, "disk", "3", "compact")
if r.code != 0 || r.stdout != "实例 3 整理磁盘完成:覆盖层占用 3.0 GB → 2.0 GB,省下 1.0 GB\n" {
t.Errorf("text: code %d stdout %q stderr %q", r.code, r.stdout, r.stderr)
}
if got := h.fake.callList(); len(got) != 1 || got[0] != "disk-compact 3" {
t.Errorf("calls = %q", got)
}
r = h.run(t, nil, "--json", "disk", "mas_3", "COMPACT")
if m := envelope(t, r.stdout); m["ok"] != true {
t.Errorf("json: %s", r.stdout)
}
for _, s := range []string{`"freed_bytes":1073741824`, `"before_on_disk_bytes":3221225472`, `"after_on_disk_bytes":2147483648`} {
if !strings.Contains(r.stdout, s) {
t.Errorf("json data lacks %s: %s", s, r.stdout)
}
}
}

func TestDiskInfo(t *testing.T) {
h := newHarness()
r := h.run(t, nil, "disk", "3", "info")
want := "实例:3(已关机)\n数据盘逻辑大小:8.0 GB\n覆盖层在宿主上占用:3.0 GB\n" +
"已分配(客体实际数据):2.0 GB\n估计可回收:1.0 GB\n"
if r.code != 0 || r.stdout != want {
t.Errorf("text: code %d stdout %q stderr %q", r.code, r.stdout, r.stderr)
}
if got := h.fake.callList(); len(got) != 1 || got[0] != "disk-info 3" {
t.Errorf("calls = %q", got)
}
r = h.run(t, nil, "--json", "disk", "mas_3", "INFO")
if m := envelope(t, r.stdout); m["ok"] != true {
t.Errorf("json: %s", r.stdout)
}
for _, s := range []string{`"logical_bytes":8589934592`, `"on_disk_bytes":3221225472`, `"allocated_bytes":2147483648`,
`"reclaimable_bytes":1073741824`, `"needs_shutdown":false`} {
if !strings.Contains(r.stdout, s) {
t.Errorf("json data lacks %s: %s", s, r.stdout)
}
}
// a running instance: no allocated / reclaimable, the flag and the warning say why
h = newHarness()
r = h.run(t, nil, "disk", "4", "info")
if r.code != 0 || strings.Contains(r.stdout, "估计可回收") || strings.Contains(r.stdout, "已分配(") ||
!strings.Contains(r.stdout, "要关机后才能算") || !strings.Contains(r.stdout, "运行中") {
t.Errorf("running text: code %d stdout %q", r.code, r.stdout)
}
r = h.run(t, nil, "--json", "disk", "4", "info")
if strings.Contains(r.stdout, "allocated_bytes") || strings.Contains(r.stdout, "reclaimable_bytes") ||
!strings.Contains(r.stdout, `"needs_shutdown":true`) {
t.Errorf("running json: %s", r.stdout)
}
}

func TestMCP(t *testing.T) {
h := newHarness()
var got mcp.Options
Expand Down
3 changes: 3 additions & 0 deletions internal/emu/afterboot.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,9 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe
},
// 10) orientation: the display stays landscape (persistent; set every boot so old instances get it)
func() { m.setupOrientation(ctx, i) },
// 10b) hand the clusters the guest freed back to the host, at most once a day (best effort, see autotrim.go);
// before the Vulkan fix, whose zygote restart is deliberately the last step
func() { m.autoTrim(ctx, i, mode) },
func() {
// 11) the guest Vulkan fix. Must be last: mounting it restarts zygote, system_server and every app
prog.emit("vulkan_fix", fmt.Sprintf("实例 %d 客体 Vulkan 驱动补丁", i), progressVulkanFix)
Expand Down
Loading
Loading