From e7a6dd7a5b5a18890d2804c438a372b9e9564ea5 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 12:05:05 +0800 Subject: [PATCH] ui: confirm native VM closes in the desktop client --- frontend/src/App.tsx | 33 +++++++++++++++++++-- frontend/src/components/VMCloseDialog.tsx | 36 +++++++++++++++++++++++ frontend/src/i18n/domains/vm.gen.ts | 6 ++++ frontend/src/i18n/keys.gen.ts | 3 ++ frontend/src/wails.ts | 1 + internal/app/app.go | 3 ++ internal/app/suspend_flow.go | 3 ++ internal/app/window_launch.go | 22 ++++++++++++++ internal/cli/handoff_other.go | 2 +- internal/cli/handoff_windows.go | 20 ++++++++++--- internal/cli/start.go | 2 +- internal/cli/window_args.go | 18 ++++++++++++ internal/cli/window_args_test.go | 9 ++++++ locales/en-US/vm.json | 3 ++ locales/zh-CN/vm.json | 3 ++ main.go | 6 ++++ 16 files changed, 162 insertions(+), 8 deletions(-) create mode 100644 frontend/src/components/VMCloseDialog.tsx diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 11d5d38..38e2665 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -2,6 +2,7 @@ import { Minus, Moon, Square, Sun, X } from 'lucide-react' import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react' import type { WizardDraft } from './components/CreateWizard' import { DeleteDialog } from './components/DeleteDialog' +import { VMCloseDialog } from './components/VMCloseDialog' import { CloneDialog } from './components/CloneDialog' import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog' import { SendTextDialog } from './components/SendTextDialog' @@ -89,6 +90,7 @@ export const App: React.FC = () => { const [affinityVersion, setAffinityVersion] = useState(0) const [deleteTarget, setDeleteTarget] = useState(null) const [discardSuspendTarget, setDiscardSuspendTarget] = useState(null) + const [vmCloseRequests, setVMCloseRequests] = useState([]) const [cloneSource, setCloneSource] = useState(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [sendTextTarget, setSendTextTarget] = useState(null) @@ -874,9 +876,21 @@ export const App: React.FC = () => { // Global shortcuts (docs/design-guidelines.md §6). Dialogs own the keyboard while open. const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {}) + const appDialogOpen = showSetup || showWizard || showSettings || affinityTarget || deleteTarget || + discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate + const vmCloseTarget = appDialogOpen ? undefined : vmCloseRequests[0] + const finishVMWindowClose = (name: string, action?: 'stop' | 'suspend') => { + setVMCloseRequests((requests) => requests.filter((target) => target !== name)) + if (action) { + setSelected(name) + onVMActionFor(name, action, true) + } else if (vmCloseRequests.length === 1) { + api.FocusVMWindow(name).catch(() => {}) + } + } shortcutRef.current = (e: KeyboardEvent) => { if (!e.ctrlKey || e.altKey || e.metaKey) return - if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return + if (appDialogOpen || vmCloseTarget) return if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return const k = e.key.toLowerCase() if (k === 'n') { e.preventDefault(); openWizard() } @@ -902,7 +916,10 @@ export const App: React.FC = () => { setSelected(name) setDiscardSuspendTarget(name) }) - return () => { offSelect(); offNew(); offDiscard() } + const offClose = events.onVMCloseRequest((name) => { + setVMCloseRequests((requests) => requests.includes(name) ? requests : [...requests, name]) + }) + return () => { offSelect(); offNew(); offDiscard(); offClose() } }, []) // Native Wails file drag-and-drop delivery into the selected VM's shared folder. @@ -1305,6 +1322,18 @@ export const App: React.FC = () => { setDeleteTarget(null)} onConfirm={confirmDelete} /> )} + {vmCloseTarget && ( + finishVMWindowClose(vmCloseTarget, 'stop')} + onSuspend={() => finishVMWindowClose(vmCloseTarget, 'suspend')} + onCancel={() => finishVMWindowClose(vmCloseTarget)} + /> + )} + {discardSuspendTarget && ( void + onSuspend: () => void + onCancel: () => void +} + +export const VMCloseDialog: React.FC = ({ locale, name, canSuspend, busy, onStop, onSuspend, onCancel }) => ( + { if (!open) onCancel() }}> + + + +
+ {t(locale, 'vmCloseTitle', { name })} + + {t(locale, canSuspend ? 'vmCloseDesc' : 'vmCloseDescNoSuspend')} + +
+
+ + + +
+
+
+
+) diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index 1a97e4e..d03f387 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -214,6 +214,9 @@ export const vmZh: Record = { "typeIntoVM": "在虚拟机里键入", "typeUntypeable": "未连接 Guest Tools 时仅支持美式键盘 ASCII 字符;安装并连接 Guest Tools 后即可输入中文与任意 Unicode 文本", "upgradeToNVMe": "升级到 NVMe", + "vmCloseDesc": "关机将请求系统关闭。挂起会保存当前会话。", + "vmCloseDescNoSuspend": "当前运行时不支持挂起。关机将请求系统关闭。", + "vmCloseTitle": "关闭「{name}」?", } export const vmEn: Record = { @@ -430,4 +433,7 @@ export const vmEn: Record = { "typeIntoVM": "Type into the VM", "typeUntypeable": "Only US-keyboard ASCII characters work without Guest Tools; connect Guest Tools for Chinese and Unicode text", "upgradeToNVMe": "Upgrade to NVMe", + "vmCloseDesc": "Shut down asks macOS to shut down. Suspend saves the session.", + "vmCloseDescNoSuspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", + "vmCloseTitle": "Close “{name}”?", } diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 9ee8854..68e7e96 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -888,6 +888,9 @@ export type I18nKey = | "validationPassed" | "vcpus" | "viewLogs" + | "vmCloseDesc" + | "vmCloseDescNoSuspend" + | "vmCloseTitle" | "vmDir" | "vmName" | "welcomeCheckHost" diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index 182aaa8..d279a68 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -181,6 +181,7 @@ export const events = { onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb), onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb), onTrayDiscardSuspend: (cb: (name: string) => void) => eventsOn('reims:tray-discard-suspend', cb), + onVMCloseRequest: (cb: (name: string) => void) => eventsOn('reims:vm-close-request', cb), // Renderer health watchdog & crash reporting (internal/app/ui_health.go). onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb), emitUIPong: () => eventsEmit('reims:ui-pong'), diff --git a/internal/app/app.go b/internal/app/app.go index 9c035eb..07227eb 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1474,6 +1474,9 @@ func (a *App) StartVM(name string) error { host.ShouldUseFixedGuestMode(curDetail.Borderless, curDetail.Resolution, rep.PrimaryDisplay) { c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1") } + if prep.Runtime.Manifest.HasCapability("client-window-close") { + c.Env = append(c.Env, vmCloseRequestEnv(name)...) + } a.mu.Lock() a.transitions[name] = "starting" diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index ea960b6..35350cd 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -130,6 +130,9 @@ func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error { host.ShouldUseFixedGuestMode(d.Borderless, d.Resolution, rep.PrimaryDisplay) { prep.Client.Env = append(prep.Client.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1") } + if prep.Runtime.Manifest.HasCapability("client-window-close") { + prep.Client.Env = append(prep.Client.Env, vmCloseRequestEnv(name)...) + } startAt := time.Now() out := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) diff --git a/internal/app/window_launch.go b/internal/app/window_launch.go index 8f02579..b3c42db 100644 --- a/internal/app/window_launch.go +++ b/internal/app/window_launch.go @@ -6,11 +6,13 @@ package app import ( "fmt" + "os" "path/filepath" "strings" "github.com/Nwflower/reims-go/internal/cli" "github.com/wailsapp/wails/v2/pkg/options" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // afterStartup runs the launch request once the window's context exists. A @@ -41,6 +43,15 @@ func (a *App) onSecondInstance(data options.SecondInstanceData) { // (double-click while running in the tray) brings the window forward. A // `vm start` handed over from the command line leaves the window as it is. func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) { + if w.CloseVM != "" { + if a.ctx != nil { + go func() { + a.ShowMainWindow() + wailsRuntime.EventsEmit(a.ctx, "reims:vm-close-request", w.CloseVM) + }() + } + return + } if w.StartVM == "" { if secondLaunch && !w.Background { a.ShowMainWindow() @@ -70,6 +81,17 @@ func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) { }() } +func vmCloseRequestEnv(name string) []string { + executable, err := os.Executable() + if err != nil { + return nil + } + return []string{ + "REIMS_GO_VM_CLOSE_EXE=" + executable, + "REIMS_GO_VM_CLOSE_NAME=" + name, + } +} + // logCapture keeps the last few log lines one source emits while it is // registered, for reporting a failed start back to the command line. type logCapture struct{ lines []string } diff --git a/internal/cli/handoff_other.go b/internal/cli/handoff_other.go index e5c0b49..22c4aaf 100644 --- a/internal/cli/handoff_other.go +++ b/internal/cli/handoff_other.go @@ -9,6 +9,6 @@ const windowHandoffWorks = false func findWindow() uintptr { return 0 } -func sendToWindow(uintptr, []string) error { return errors.ErrUnsupported } +func sendToWindow(uintptr, []string, uint32) error { return errors.ErrUnsupported } func spawnWindow([]string) error { return errors.ErrUnsupported } diff --git a/internal/cli/handoff_windows.go b/internal/cli/handoff_windows.go index f62ce91..c3c76da 100644 --- a/internal/cli/handoff_windows.go +++ b/internal/cli/handoff_windows.go @@ -23,15 +23,17 @@ import ( const ( wmCopyData = 0x004A wailsCopyDataID = 1542 + smtoAbortIfHung = 0x0002 hwndMessage = ^uintptr(2) // HWND_MESSAGE, (HWND)-3 detachedProcess = 0x00000008 windowHandoffWorks = true ) var ( - user32 = syscall.NewLazyDLL("user32.dll") - procFindWindowExW = user32.NewProc("FindWindowExW") - procSendMessageW = user32.NewProc("SendMessageW") + user32 = syscall.NewLazyDLL("user32.dll") + procFindWindowExW = user32.NewProc("FindWindowExW") + procSendMessageW = user32.NewProc("SendMessageW") + procSendMessageTimeoutW = user32.NewProc("SendMessageTimeoutW") ) type copyDataStruct struct { @@ -57,7 +59,7 @@ func findWindow() uintptr { // sendToWindow delivers args to the running window as if a second // `reims-go.exe ` had been launched. -func sendToWindow(hwnd uintptr, args []string) error { +func sendToWindow(hwnd uintptr, args []string, timeoutMS uint32) error { wd, _ := os.Getwd() payload, err := json.Marshal(options.SecondInstanceData{Args: args, WorkingDirectory: wd}) if err != nil { @@ -72,6 +74,16 @@ func sendToWindow(hwnd uintptr, args []string) error { cbData: uint32(len(buf) * 2), lpData: uintptr(unsafe.Pointer(&buf[0])), } + if timeoutMS != 0 { + var result uintptr + sent, _, _ := procSendMessageTimeoutW.Call(hwnd, wmCopyData, 0, + uintptr(unsafe.Pointer(&cds)), smtoAbortIfHung, uintptr(timeoutMS), uintptr(unsafe.Pointer(&result))) + runtime.KeepAlive(buf) + if sent == 0 { + return errors.New("desktop window did not respond") + } + return nil + } procSendMessageW.Call(hwnd, wmCopyData, 0, uintptr(unsafe.Pointer(&cds))) runtime.KeepAlive(buf) return nil diff --git a/internal/cli/start.go b/internal/cli/start.go index 3cbf862..a090314 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -97,7 +97,7 @@ func startInWindow(ctx context.Context, cfg *config.Config, name string) error { w := WindowArgs{StartVM: name, StartResult: result} if hwnd := findWindow(); hwnd != 0 { fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.handing_to_window", i18n.Vars{"name": name})) - if err := sendToWindow(hwnd, w.Args()); err != nil { + if err := sendToWindow(hwnd, w.Args(), 0); err != nil { return err } } else { diff --git a/internal/cli/window_args.go b/internal/cli/window_args.go index 48c15be..690f3df 100644 --- a/internal/cli/window_args.go +++ b/internal/cli/window_args.go @@ -14,6 +14,7 @@ const ( flagSafeMode = "--safe-mode" flagStartVM = "--start-vm=" flagStartResult = "--start-result=" + flagCloseVM = "--close-vm=" flagWaitPID = "--wait-pid=" ) @@ -30,6 +31,8 @@ type WindowArgs struct { // StartResult is a file the window writes a StartResult to once StartVM // has returned, so the command that asked can report it. StartResult string + // CloseVM requests a close confirmation in the running desktop window. + CloseVM string // WaitPID is a Reims-Go process that is quitting after installing an // update: the new window waits for it to exit before taking the // single-instance lock, which it would otherwise hand straight back to it. @@ -50,6 +53,11 @@ func ParseWindowArgs(args []string) (w WindowArgs, ok bool) { w.StartVM = strings.TrimPrefix(a, flagStartVM) case strings.HasPrefix(a, flagStartResult): w.StartResult = strings.TrimPrefix(a, flagStartResult) + case strings.HasPrefix(a, flagCloseVM): + w.CloseVM = strings.TrimPrefix(a, flagCloseVM) + if w.CloseVM == "" { + return WindowArgs{}, false + } case strings.HasPrefix(a, flagWaitPID): pid, err := strconv.ParseUint(strings.TrimPrefix(a, flagWaitPID), 10, 32) if err != nil || pid == 0 { @@ -78,12 +86,22 @@ func (w WindowArgs) Args() []string { if w.StartResult != "" { out = append(out, flagStartResult+w.StartResult) } + if w.CloseVM != "" { + out = append(out, flagCloseVM+w.CloseVM) + } if w.WaitPID != 0 { out = append(out, flagWaitPID+strconv.FormatUint(uint64(w.WaitPID), 10)) } return out } +// ForwardVMClose asks an existing desktop instance to show a confirmation. +func ForwardVMClose(name string) bool { + const timeoutMS = 500 + hwnd := findWindow() + return hwnd != 0 && sendToWindow(hwnd, WindowArgs{CloseVM: name}.Args(), timeoutMS) == nil +} + // StartResult is the JSON the window writes to WindowArgs.StartResult. type StartResult struct { OK bool `json:"ok"` diff --git a/internal/cli/window_args_test.go b/internal/cli/window_args_test.go index 84d34f0..9949fc1 100644 --- a/internal/cli/window_args_test.go +++ b/internal/cli/window_args_test.go @@ -24,6 +24,8 @@ func TestParseWindowArgs(t *testing.T) { {[]string{"--background", "vm", "list"}, WindowArgs{}, false}, {[]string{"--help"}, WindowArgs{}, false}, {[]string{"--start-vm", "m0"}, WindowArgs{}, false}, // value must be joined with = + {[]string{"--close-vm=mac os"}, WindowArgs{CloseVM: "mac os"}, true}, + {[]string{"--close-vm="}, WindowArgs{}, false}, {[]string{"--wait-pid=4242"}, WindowArgs{WaitPID: 4242}, true}, {[]string{"--background", "--wait-pid=7"}, WindowArgs{Background: true, WaitPID: 7}, true}, {[]string{"--wait-pid=0"}, WindowArgs{}, false}, @@ -40,6 +42,13 @@ func TestParseWindowArgs(t *testing.T) { } } +func TestCloseWindowArgsRoundTrip(t *testing.T) { + want := WindowArgs{CloseVM: "macOS Test"} + if got, ok := ParseWindowArgs(want.Args()); !ok || got != want { + t.Fatalf("close request round trip = %+v, %v", got, ok) + } +} + func TestWindowArgsRoundTrip(t *testing.T) { w := WindowArgs{Background: true, StartVM: "mac os", StartResult: `D:\Data\tmp\cli-start-9.json`, WaitPID: 31337} got, ok := ParseWindowArgs(w.Args()) diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index 6f2f87e..bc05abf 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -50,6 +50,9 @@ "state_resuming": "Resuming", "state_broken": "Error", "suspend": "Suspend", + "vmCloseTitle": "Close “{name}”?", + "vmCloseDesc": "Shut down asks macOS to shut down. Suspend saves the session.", + "vmCloseDescNoSuspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", "resume": "Resume", "resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM", "discardSuspend": "Discard saved state", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index a8ab8f3..7f73d4a 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -50,6 +50,9 @@ "state_resuming": "恢复中", "state_broken": "出错", "suspend": "挂起", + "vmCloseTitle": "关闭「{name}」?", + "vmCloseDesc": "关机将请求系统关闭。挂起会保存当前会话。", + "vmCloseDescNoSuspend": "当前运行时不支持挂起。关机将请求系统关闭。", "resume": "恢复", "resumeUnavailable": "切换到支持挂起的内核后可恢复", "discardSuspend": "放弃挂起状态", diff --git a/main.go b/main.go index dba7dff..9fb98c7 100644 --- a/main.go +++ b/main.go @@ -35,6 +35,12 @@ func main() { os.Exit(cli.Main(args)) } launch, _ := cli.ParseWindowArgs(args) + if launch.CloseVM != "" { + if !cli.ForwardVMClose(launch.CloseVM) { + os.Exit(1) + } + return + } if launch.WaitPID != 0 { // Relaunched by an in-app update: let the old window exit first, or the // single-instance lock below hands this launch back to it.