Files
Reims-Go/internal/cli/autoinstall.go
T
千川白浪 2e879ab074 fix(app,ui,overlay,ocr,cli): 加固 #134 自动装机受保护阶段授权、升级默认项与会话生命周期 (#210)
* fix(app,ui,overlay,ocr,cli): harden autoinstall auth, upgrade defaults, and lifecycle after #134

* fix(app,cli,ui): address PR #210 review findings and keep default auto-install enabled
2026-12-06 17:26:51 +08:00

177 lines
5.3 KiB
Go

package cli
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/control"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
)
// callDesktopAutoInstall is a seam overridden by CLI unit tests to verify
// desktop control-channel forwarding without spawning a desktop process.
var callDesktopAutoInstall = func(ctx context.Context, req control.AutoInstallRequest, out any) error {
return control.Call(ctx, control.HostPluginID, control.ChannelAutoInstall, req, out)
}
var desktopPIDForAutoInstall = DesktopWindowPID
func isDesktopDataRootMismatch(err error) bool {
return err != nil && strings.Contains(err.Error(), "data_root_mismatch")
}
func isDesktopControlUnavailable(err error) bool {
if err == nil {
return false
}
if errors.Is(err, errors.ErrUnsupported) || errors.Is(err, os.ErrNotExist) {
return true
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "cannot find the file") ||
strings.Contains(msg, "file does not exist") ||
strings.Contains(msg, "no such file") ||
strings.Contains(msg, "timed out") ||
strings.Contains(msg, "unsupported")
}
func cmdVMAutoInstall(cfg *config.Config, _ i18n.Locale, args []string) error {
if len(args) == 0 {
return errors.New("usage: reims-go vm autoinstall <list|preflight|status|resume|stop|diagnostic> [flags] [vm]")
}
sub := args[0]
fs := flag.NewFlagSet("vm autoinstall "+sub, flag.ContinueOnError)
driverID := fs.String("driver", driver.BuiltinReimsMacOSDriverID, "Guest VM driver ID")
pluginID := fs.String("plugin", "", "Auto-installer plugin ID (default: first enabled provider)")
guestLang := fs.String("guest-lang", "zh-Hans:0", "Guest language with :0 US keyboard layout")
if err := fs.Parse(args[1:]); err != nil {
return err
}
vmName := ""
if fs.NArg() > 0 {
vmName = strings.TrimSpace(fs.Arg(0))
}
switch sub {
case "list", "preflight", "status":
case "resume":
if vmName == "" {
return errors.New("usage: reims-go vm autoinstall resume <vm>")
}
case "stop":
if vmName == "" {
return errors.New("usage: reims-go vm autoinstall stop <vm>")
}
case "diagnostic":
if vmName == "" {
return errors.New("usage: reims-go vm autoinstall diagnostic <vm>")
}
default:
return fmt.Errorf("unknown vm autoinstall subcommand %q", sub)
}
// `resume` prompts the user in the desktop app (confirmPromptTimeout = 2m),
// so give it a longer timeout than quick status/stop queries.
timeout := 20 * time.Second
if sub == "resume" {
timeout = 150 * time.Second
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Live auto-install runners, overlays, input locks, and protected-phase
// grants live in the desktop process. Forward stateful subcommands there
// first so CLI and GUI never split-brain or launch doomed short-lived runners.
if sub == "status" || sub == "resume" || sub == "stop" || sub == "diagnostic" {
var desktopOut any
req := control.AutoInstallRequest{
Action: sub,
DataRoot: cfg.DataRoot,
PluginID: strings.TrimSpace(*pluginID),
DriverID: *driverID,
VMName: vmName,
}
err := callDesktopAutoInstall(ctx, req, &desktopOut)
if err == nil {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(desktopOut)
}
if sub == "resume" {
if isDesktopDataRootMismatch(err) {
return errors.New("auto-install resume requires the Reims-Go desktop app to be open on the same data directory")
}
if isDesktopControlUnavailable(err) {
return errors.New("auto-install resume requires the Reims-Go desktop app to be running; open the desktop app and resume from there or retry this command")
}
return err
}
if sub == "stop" && !isDesktopDataRootMismatch(err) {
if desktopPIDForAutoInstall() != 0 {
return fmt.Errorf("Reims-Go desktop app is running, but the control channel could not be reached (%w); stop auto-install from the desktop app to avoid leaving a live session running", err)
}
if !isDesktopControlUnavailable(err) {
return err
}
}
if (sub == "status" || sub == "diagnostic") && !isDesktopDataRootMismatch(err) && !isDesktopControlUnavailable(err) {
return err
}
}
mgr, _, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
providers := mgr.Registry().AutoInstallers()
if sub == "list" {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(providers)
}
if len(providers) == 0 {
return errors.New("no enabled auto-installer plugin found")
}
pid := strings.TrimSpace(*pluginID)
if pid == "" {
pid = providers[0].PluginID
}
vmRef := ""
if vmName != "" {
vmRef = driver.NewVMRef(*driverID, vmName).Key()
}
var method string
payload := map[string]any{"vm": vmRef}
switch sub {
case "preflight":
method = "autoinstall/preflight"
payload["guest_lang"] = *guestLang
case "status":
method = "autoinstall/status"
case "stop":
method = "autoinstall/stop"
case "diagnostic":
method = "autoinstall/diagnosticSummary"
}
var out any
if err := mgr.CallSidecar(ctx, pid, method, payload, &out); err != nil {
return err
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(out)
}