ui: confirm native VM closes in the desktop client

This commit is contained in:
YXC0915 committed 2026-12-01 12:05:05 +08:00
1 parent c2c168da4e
commit e7a6dd7a5b
16 files changed
+162 -8

No files matched your search

+31 -2
View File
@@ -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<string | null>(null)
const [discardSuspendTarget, setDiscardSuspendTarget] = useState<string | null>(null)
const [vmCloseRequests, setVMCloseRequests] = useState<string[]>([])
const [cloneSource, setCloneSource] = useState<string | null>(null)
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
const [sendTextTarget, setSendTextTarget] = useState<string | null>(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 = () => {
<DeleteDialog locale={locale} name={deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
)}
{vmCloseTarget && (
<VMCloseDialog
locale={locale}
name={displayNames[vmCloseTarget] || vmCloseTarget}
canSuspend={canSuspend}
busy={Object.prototype.hasOwnProperty.call(busy, vmCloseTarget)}
onStop={() => finishVMWindowClose(vmCloseTarget, 'stop')}
onSuspend={() => finishVMWindowClose(vmCloseTarget, 'suspend')}
onCancel={() => finishVMWindowClose(vmCloseTarget)}
/>
)}
{discardSuspendTarget && (
<ConfirmDialog
title={tr('discardSuspendTitle', { name: displayNames[discardSuspendTarget] || discardSuspendTarget })}
+36
View File
@@ -0,0 +1,36 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import React from 'react'
import { t } from '../i18n'
import type { Locale } from '../types'
import { Button } from '../ui/controls'
interface Props {
locale: Locale
name: string
canSuspend: boolean
busy: boolean
onStop: () => void
onSuspend: () => void
onCancel: () => void
}
export const VMCloseDialog: React.FC<Props> = ({ locale, name, canSuspend, busy, onStop, onSuspend, onCancel }) => (
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<div className="dialog-body">
<Alert.Title className="dialog-title">{t(locale, 'vmCloseTitle', { name })}</Alert.Title>
<Alert.Description className="dialog-desc">
{t(locale, canSuspend ? 'vmCloseDesc' : 'vmCloseDescNoSuspend')}
</Alert.Description>
</div>
<div className="dialog-foot">
<Button disabled={busy} onClick={onStop}>{t(locale, 'stop')}</Button>
<Button variant="primary" disabled={busy || !canSuspend} onClick={onSuspend}>{t(locale, 'suspend')}</Button>
<Alert.Cancel asChild><Button>{t(locale, 'cancel')}</Button></Alert.Cancel>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
)
+6
View File
@@ -214,6 +214,9 @@ export const vmZh: Record<string, string> = {
"typeIntoVM": "在虚拟机里键入",
"typeUntypeable": "未连接 Guest Tools 时仅支持美式键盘 ASCII 字符;安装并连接 Guest Tools 后即可输入中文与任意 Unicode 文本",
"upgradeToNVMe": "升级到 NVMe",
"vmCloseDesc": "关机将请求系统关闭。挂起会保存当前会话。",
"vmCloseDescNoSuspend": "当前运行时不支持挂起。关机将请求系统关闭。",
"vmCloseTitle": "关闭「{name}」?",
}
export const vmEn: Record<string, string> = {
@@ -430,4 +433,7 @@ export const vmEn: Record<string, string> = {
"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}”?",
}
+3
View File
@@ -888,6 +888,9 @@ export type I18nKey =
| "validationPassed"
| "vcpus"
| "viewLogs"
| "vmCloseDesc"
| "vmCloseDescNoSuspend"
| "vmCloseTitle"
| "vmDir"
| "vmName"
| "welcomeCheckHost"
+1
View File
@@ -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'),
+3
View File
@@ -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"
+3
View File
@@ -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) })
+22
View File
@@ -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 }
+1 -1
View File
@@ -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 }
+16 -4
View File
@@ -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 <args>` 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
+1 -1
View File
@@ -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 {
+18
View File
@@ -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"`
+9
View File
@@ -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())
+3
View File
@@ -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",
+3
View File
@@ -50,6 +50,9 @@
"state_resuming": "恢复中",
"state_broken": "出错",
"suspend": "挂起",
"vmCloseTitle": "关闭「{name}」?",
"vmCloseDesc": "关机将请求系统关闭。挂起会保存当前会话。",
"vmCloseDescNoSuspend": "当前运行时不支持挂起。关机将请求系统关闭。",
"resume": "恢复",
"resumeUnavailable": "切换到支持挂起的内核后可恢复",
"discardSuspend": "放弃挂起状态",
+6
View File
@@ -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.