diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 2f43c0b..ceda025 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -41,6 +41,9 @@ const errText = (e: unknown) => parseAppError(e).summary const failKey: Record = { start: 'failStart', + suspend: 'failSuspend', + resume: 'failResume', + discardSuspend: 'failDiscardSuspend', focus: 'failFocus', fullscreen: 'failFullscreen', screenshot: 'failScreenshot', @@ -85,6 +88,7 @@ export const App: React.FC = () => { const [affinityTarget, setAffinityTarget] = useState(null) const [affinityVersion, setAffinityVersion] = useState(0) const [deleteTarget, setDeleteTarget] = useState(null) + const [discardSuspendTarget, setDiscardSuspendTarget] = useState(null) const [cloneSource, setCloneSource] = useState(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [sendTextTarget, setSendTextTarget] = useState(null) @@ -331,6 +335,15 @@ export const App: React.FC = () => { const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : '' const pending = selectedVM ? (state?.pending_changes[selectedVM.name] ?? []) : [] const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime + const activeManifest = state?.active_runtime?.manifest + const canSuspend = Boolean( + activeManifest?.capabilities?.some((c) => c.toLowerCase() === 'vm-suspend') + || ( + activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('win32-mapped-ram-io')) + && activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('intel-whpx-suspend')) + && activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('reims-vgpu-snapshot-replay')) + ), + ) onTaskRef.current = (task: Task) => { if (task.kind === 'app-update' && task.status === 'failed' && !notifiedTasks.current.has(task.id)) { @@ -667,6 +680,9 @@ export const App: React.FC = () => { } switch (action) { case 'start': return runVMAction(name, action, () => api.StartVM(name)) + case 'suspend': return runVMAction(name, action, () => api.SuspendVM(name), tr('toastSuspended', { name })) + case 'resume': return runVMAction(name, action, () => api.ResumeVM(name), tr('toastResumed', { name })) + case 'discardSuspend': return setDiscardSuspendTarget(name) case 'focus': return api.FocusVMWindow(name).catch((e) => fail(tr('failFocus'), e)) case 'fullscreen': return runVMAction(name, action, async () => { @@ -705,23 +721,25 @@ export const App: React.FC = () => { } const onSidebarContextAction = (name: string, action: VMAction | 'settings') => { + const vm = vms.find((v) => v.name === name) + const st = state?.transitions[name] ?? vm?.state ?? 'stopped' if (action === 'settings') { + if (st === 'suspended' || st === 'suspending' || st === 'resuming') return setSelected(name) api.GetVMDetail(name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e)) return } - const vm = vms.find((v) => v.name === name) - const st = state?.transitions[name] ?? vm?.state ?? 'stopped' onVMActionFor(name, action, st === 'running') } - // The state's own main action (Start, or Show Window while running), shared by + // The state's own main action (Start, Resume while suspended, or Show Window while running), shared by // Ctrl+Enter and a double-click in the sidebar. const primaryAction = (name: string) => { const vm = vms.find((v) => v.name === name) if (!vm || activeVMBusy(name)) return const st = state?.transitions[name] ?? vm.state if (st === 'stopped') onVMActionFor(name, 'start', false) + else if (st === 'suspended') onVMActionFor(name, 'resume', false) else if (st === 'running') onVMActionFor(name, 'focus', true) } @@ -731,6 +749,12 @@ export const App: React.FC = () => { if (name) runVMAction(name, 'delete', () => api.DeleteVM(name, keepFiles), tr('toastDeleted', { name })) } + const confirmDiscardSuspend = () => { + const name = discardSuspendTarget + setDiscardSuspendTarget(null) + if (name) runVMAction(name, 'discardSuspend', () => api.DiscardSuspend(name), tr('toastDiscardSuspend', { name })) + } + const confirmOnlineRecovery = () => { const name = onlineRecoveryTarget setOnlineRecoveryTarget(null) @@ -859,11 +883,11 @@ export const App: React.FC = () => { const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {}) shortcutRef.current = (e: KeyboardEvent) => { if (!e.ctrlKey || e.altKey || e.metaKey) return - if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return + if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return const k = e.key.toLowerCase() if (k === 'n') { e.preventDefault(); openWizard() } - else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) } + else if (k === ',' && detail && effectiveState !== 'suspended' && effectiveState !== 'suspending' && effectiveState !== 'resuming') { e.preventDefault(); setShowSettings(true) } else if (k === 'l') { e.preventDefault(); toggleLogs() } else if (k === 'b' && !showSetup) { e.preventDefault(); toggleSidebar() } else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(selectedVM.name) } @@ -950,10 +974,11 @@ export const App: React.FC = () => { state: effectiveState, busy: Object.prototype.hasOwnProperty.call(busy, selectedVM.name), graphics: detail?.name === selectedVM.name ? detail.graphics : undefined, + canSuspend, } : null} onNewVM={openWizard} onVMAction={onVMAction} - onVMSettings={() => { if (detail) setShowSettings(true) }} + onVMSettings={() => { if (detail && effectiveState !== 'suspended') setShowSettings(true) }} onVMDelete={() => { if (selectedVM) setDeleteTarget(selectedVM.name) }} onNavigate={setSelected} onOpenURL={(url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) }} @@ -1019,6 +1044,7 @@ export const App: React.FC = () => { busyActions={busy} selected={selected} hostReady={hostReady} + canSuspend={canSuspend} onSelect={setSelected} displayNames={displayNames} macosMajors={macosMajors} @@ -1077,6 +1103,7 @@ export const App: React.FC = () => { onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))} macosMajor={macosMajors[selectedVM.name] ?? null} state={effectiveState} + canSuspend={canSuspend} guideActive={state.active_guides?.includes(selectedVM.name) ?? false} installGuideEnabled={!!state.install_guide_enabled} detail={detail} @@ -1281,6 +1308,25 @@ export const App: React.FC = () => { setDeleteTarget(null)} onConfirm={confirmDelete} /> )} + {discardSuspendTarget && ( + setDiscardSuspendTarget(null)} + > +
+

{tr('discardSuspendDesc')}

+
+
+ + + + + +
+
+ )} + {cloneSource && ( selected: string hostReady: boolean + /** Whether the active runtime supports VM suspend/resume. */ + canSuspend?: boolean onSelect: (id: string) => void /** VM name → display name (its note); empty or missing shows the name. */ displayNames?: Record @@ -44,7 +46,7 @@ interface Props { } export const Sidebar: React.FC = ({ - locale, vms, transitions, busyActions = {}, selected, hostReady, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, + locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, }) => { const tr = (k: I18nKey) => t(locale, k) const listRef = useRef(null) @@ -118,7 +120,8 @@ export const Sidebar: React.FC = ({ const st = transitions[vm.name] ?? vm.state const running = st === 'running' const stopped = st === 'stopped' - const transitioning = st === 'starting' || st === 'stopping' + const suspended = st === 'suspended' + const transitioning = st === 'starting' || st === 'stopping' || st === 'suspending' || st === 'resuming' const busyAction = Object.prototype.hasOwnProperty.call(busyActions, vm.name) ? busyActions[vm.name] : undefined const vmBusy = !!busyAction const label = displayNames[vm.name] || vm.name @@ -159,6 +162,16 @@ export const Sidebar: React.FC = ({ {tr('start')} )} + {suspended && ( + <> + onVMContextAction(vm.name, 'resume')}> + {tr('resume')} + + onVMContextAction(vm.name, 'discardSuspend')}> + {tr('discardSuspend')} + + + )} {running && ( <> onVMContextAction(vm.name, 'focus')}> @@ -170,6 +183,11 @@ export const Sidebar: React.FC = ({ onVMContextAction(vm.name, 'screenshot')}> {tr('copyScreenshot')} + {canSuspend && ( + onVMContextAction(vm.name, 'suspend')}> + {tr('suspend')} + + )} onVMContextAction(vm.name, 'stop')}> {tr('stop')} @@ -184,7 +202,7 @@ export const Sidebar: React.FC = ({ )} - onVMContextAction(vm.name, 'settings')}> + onVMContextAction(vm.name, 'settings')}> {tr('settingsEllipsis')} onVMContextAction(vm.name, 'openSharedFolder')}> @@ -199,7 +217,7 @@ export const Sidebar: React.FC = ({ {tr('openFolder')} - onVMContextAction(vm.name, 'delete')}> + onVMContextAction(vm.name, 'delete')}> {tr('delete')} diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index 79560e4..4253d95 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -27,7 +27,7 @@ interface Props { canDark?: boolean onThemeMode: (mode: ThemeMode) => void /** The selected VM and its current state, or null on the system pages. */ - vm: { name: string; state: string; busy: boolean; graphics?: string } | null + vm: { name: string; state: string; busy: boolean; graphics?: string; canSuspend?: boolean } | null onNewVM: () => void onVMAction: (action: VMAction) => void onVMSettings: () => void @@ -62,7 +62,8 @@ export const TitleMenus: React.FC = ({ const running = vm?.state === 'running' const stopped = vm?.state === 'stopped' - const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' + const suspended = vm?.state === 'suspended' + const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming' const vmBusy = !vm || vm.busy const canFullscreen = running && vm?.graphics !== 'vmware-svga' const stats = useVMStats(canFullscreen && vm ? vm.name : null, running) @@ -218,17 +219,21 @@ export const TitleMenus: React.FC = ({ {running ? item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }) - : item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })} + : suspended + ? item(tr('resume'), () => onVMAction('resume'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }) + : item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })} {item(fullscreenLabel, () => onVMAction('fullscreen'), { disabled: vmBusy || !canFullscreen })} + {item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })} {item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })} {item(tr('restart'), () => onVMAction('restart'), { disabled: vmBusy || !running })} {item(tr('copyScreenshot'), () => onVMAction('screenshot'), { disabled: vmBusy || !running })} - {item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm })} + {item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm || suspended || transitioning })} {item(tr('openFolder'), () => onVMAction('openFolder'), { disabled: !vm })} + {suspended && item(tr('discardSuspend'), () => onVMAction('discardSuspend'), { danger: true, disabled: vmBusy })} {item(tr('forceStop'), () => onVMAction('forceStop'), { danger: true, disabled: !vm || !(running || transitioning) })} - {item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || transitioning })} + {item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || suspended || transitioning })} ))} {menu('view', tr('menuView'), ( diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index e8b60ea..f42998f 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -27,6 +27,7 @@ import { Minimize2, Monitor, Network, + Pause, Pencil, Play, Plus, @@ -55,6 +56,9 @@ import { VersionArt } from './VersionArt' export type VMAction = | 'start' + | 'suspend' + | 'resume' + | 'discardSuspend' | 'stop' | 'forceStop' | 'restart' @@ -92,6 +96,8 @@ interface Props { /** macOS major version (26, 15, …) for the artwork shown before a first frame; null if unknown. */ macosMajor: number | null state: string + /** Whether the active runtime supports VM suspend/resume. */ + canSuspend?: boolean /** Whether the native VM-window installation guide is currently active for this boot. */ guideActive: boolean /** Whether the builtin.install-guide plugin is enabled. */ @@ -132,13 +138,14 @@ interface Spec { } export const VMPage: React.FC = ({ - locale, name, displayName, onDisplayNameSaved, macosMajor, state, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, + locale, name, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const busy = busyAction !== undefined const running = state === 'running' + const suspended = state === 'suspended' const installing = !!detail && (detail.has_installer || detail.recovery_mode) - const transitioning = state === 'starting' || state === 'stopping' + const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' // Polled here rather than in App so each tick re-renders only this page. const stats = useVMStats(name, running) @@ -318,7 +325,7 @@ export const VMPage: React.FC = ({ } // One primary action per state (docs/design-guidelines.md §4): Start while - // stopped, Show Window while running. Ctrl+Enter triggers it (App.tsx). + // stopped, Resume while suspended, Show Window while running. Ctrl+Enter triggers it (App.tsx). let primary: React.ReactNode = null let secondary: React.ReactNode = null if (state === 'stopped') { @@ -329,10 +336,27 @@ export const VMPage: React.FC = ({ ) + } else if (suspended) { + primary = ( + + + + ) + secondary = ( + + ) } else if (state === 'starting') { primary = } else if (state === 'stopping') { primary = + } else if (state === 'suspending') { + primary = + } else if (state === 'resuming') { + primary = } else if (running) { const showLabel = tr(guideActive ? 'showInstallGuide' : 'showWindow') primary = ( @@ -343,7 +367,14 @@ export const VMPage: React.FC = ({ ) secondary = ( - + <> + {canSuspend && ( + + )} + + ) } else if (state === 'broken') { primary = @@ -413,6 +444,11 @@ export const VMPage: React.FC = ({ : <> {tr('enterFullscreen')}} )} + {canSuspend && ( + onAction('suspend')}> + {tr('suspend')} + + )} onAction('restart')}> {tr('restart')} @@ -431,15 +467,15 @@ export const VMPage: React.FC = ({ {detail && ( <> {installing ? ( - onAction('finishInstall')}> + onAction('finishInstall')}> {tr('finishInstall')} ) : ( <> - onAction('enterRecovery')}> + onAction('enterRecovery')}> {tr('enterRecovery')} - onAction('cloneVM')}> + onAction('cloneVM')}> {tr('cloneVM')} @@ -478,12 +514,17 @@ export const VMPage: React.FC = ({ ))} + {suspended && ( + onAction('discardSuspend')}> + {tr('discardSuspend')} + + )} {(running || transitioning) && ( onAction('forceStop')}> {tr('forceStop')} )} - + {tr('delete')} @@ -563,11 +604,23 @@ export const VMPage: React.FC = ({ onCopy(rows.join('\n')) } - const pillClass = running ? ' is-running' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : '' + const pillClass = running ? ' is-running' : suspended ? ' is-suspended' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : '' const dropStyle = detail && !installing ? ({ '--wails-drop-target': 'drop' } as React.CSSProperties) : undefined + const formatSuspendTime = (iso?: string) => { + if (!iso) return '' + const ms = Date.parse(iso) + if (!Number.isFinite(ms)) return '' + try { + const loc = locale === 'en-XA' ? 'en-US' : locale + return new Intl.DateTimeFormat(loc, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(ms)) + } catch { + return '' + } + } + return (
{dropping && ( @@ -588,10 +641,10 @@ export const VMPage: React.FC = ({ thumb={thumb} art={} running={running} - startLabel={tr('start')} + startLabel={suspended ? tr('resume') : tr('start')} showLabel={tr('showWindow')} shotLabel={tr('copyScreenshot')} - onStart={state === 'stopped' && !busy ? () => onAction('start') : undefined} + onStart={!busy && (state === 'stopped' || suspended) ? () => onAction(suspended ? 'resume' : 'start') : undefined} onShow={running && !busy ? () => onAction('focus') : undefined} onScreenshot={running && !busy ? () => onAction('screenshot') : undefined} /> @@ -631,8 +684,10 @@ export const VMPage: React.FC = ({
{primary} {secondary} - - + + + + {menu}
@@ -667,6 +722,28 @@ export const VMPage: React.FC = ({
)} + {suspended && (() => { + const suspTime = formatSuspendTime(detail?.suspend_info?.created_at) + const suspSize = detail?.suspend_info?.vmstate_size + ? formatBytes(detail.suspend_info.vmstate_size, locale) + : (detail?.memory ? formatMemory(detail.memory, locale) : '—') + return ( +
+ + +
+ ) + })()} + {pending.length > 0 && (
@@ -1041,12 +1118,12 @@ export const VMPage: React.FC = ({ {tr('snapshotsTitle')} · {tr('snapshotHint')} - +
diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index ecfcaed..312faa3 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -24,6 +24,10 @@ export const vmZh: Record = { "diagBackingChainWarn": "当前系统盘 CoW 派生链深度为 {depth} 层(≥ 2),未分配簇读穿透会拖慢小文件 I/O,建议合并为独立镜像或基于基础镜像重新派生", "diagExternalDriveWarn": "数据目录在外置或网络盘上({dir}),读写会明显变慢", "diagHighMemWarn": "宿主内存已用 {pct}%,虚拟机可能会卡顿", + "discardSuspend": "放弃挂起状态", + "discardSuspendConfirm": "放弃并关机", + "discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。", + "discardSuspendTitle": "放弃「{name}」的挂起状态?", "displayNameEdit": "点按以修改显示名称", "displayNameEditEllipsis": "修改显示名称…", "displayNameLabel": "显示名称", @@ -41,6 +45,7 @@ export const vmZh: Record = { "failAttachInstaller": "挂载镜像失败", "failCloneVM": "派生 CoW 副本失败", "failDelete": "删除失败", + "failDiscardSuspend": "放弃挂起状态失败", "failEject": "弹出安装盘失败", "failEnterRecovery": "进入恢复模式失败", "failExportDiagnostics": "导出排障日志失败", @@ -50,10 +55,12 @@ export const vmZh: Record = { "failGuestTools": "Guest Tools 操作失败", "failOpenFolder": "无法打开文件夹", "failRestart": "重启失败", + "failResume": "恢复失败", "failScreenshot": "截屏失败", "failSnapshot": "恢复点操作失败", "failStart": "启动失败", "failStop": "关机失败", + "failSuspend": "挂起失败", "failType": "键入失败", "failUpgradeNVMe": "升级到 NVMe 失败", "fieldAudio": "音频", @@ -111,6 +118,7 @@ export const vmZh: Record = { "pendingTitle": "下次启动生效", "pickRecoveryTitle": "选择离线镜像(.img / .dmg)", "restartToApply": "重启以应用", + "resume": "恢复", "sendText": "发送文本到虚拟机…", "sendTextConfirm": "发送 (Ctrl+Enter)", "sendTextDesc": "支持中文、Emoji、宿主机输入法与语音输入,按 Ctrl+Enter 发送到 macOS 当前输入框。", @@ -155,14 +163,23 @@ export const vmZh: Record = { "state_broken": "出错", "state_creating": "正在创建", "state_driver_unavailable": "驱动不可用", + "state_resuming": "恢复中", "state_running": "运行中", "state_starting": "启动中", "state_stopped": "已停止", "state_stopping": "停止中", + "state_suspended": "已挂起", + "state_suspending": "挂起中", + "suspend": "挂起", + "suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", + "suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", + "suspendedNoticeTitle": "已保存运行状态", + "suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置", "techInfo": "技术信息", "toastCloned": "已派生 CoW 副本「{name}」", "toastDeleted": "已删除 {name}", "toastDiagExported": "已导出脱敏排障日志包 (.zip)", + "toastDiscardSuspend": "已放弃 {name} 的挂起状态", "toastEjected": "已弹出安装盘", "toastEnterRecovery": "已进入恢复模式,启动后可在引导菜单选 Recovery", "toastEnterRecoveryNextStart": "已准备进入恢复模式,重启后显示引导菜单", @@ -182,11 +199,13 @@ export const vmZh: Record = { "toastOnlineRecoveryStarted": "正在拉取在线恢复镜像(约 1 GB),完成后自动挂载", "toastPreventSleepOff": "已关闭 macOS 防休眠守护", "toastPreventSleepOn": "已开启 macOS 防休眠守护", + "toastResumed": "{name} 已恢复", "toastScreenshotCopied": "已复制虚拟机画面", "toastSnapshotCreated": "已创建恢复点 {name}", "toastSnapshotDeleted": "已删除恢复点 {name}", "toastSnapshotRestored": "已回滚到 {name}", "toastStopped": "{name} 已关机", + "toastSuspended": "{name} 已挂起", "toastTyped": "{n, plural, other {已键入 # 个字符}}", "toggleFullscreen": "切换全屏", "typeClipboard": "粘贴剪贴板到虚拟机", @@ -219,6 +238,10 @@ export const vmEn: Record = { "diagBackingChainWarn": "System disk CoW backing chain is {depth} layers deep (\u003e= 2); read-through slows small-file I/O — consider flattening or re-deriving from the base image", "diagExternalDriveWarn": "The data folder is on an external or network drive ({dir}); disk access will be slow", "diagHighMemWarn": "Host memory is {pct}% used; the VM may stutter", + "discardSuspend": "Discard saved state", + "discardSuspendConfirm": "Discard \u0026 Power Off", + "discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.", + "discardSuspendTitle": "Discard saved state for “{name}”?", "displayNameEdit": "Click to change the display name", "displayNameEditEllipsis": "Change Display Name…", "displayNameLabel": "Display name", @@ -236,6 +259,7 @@ export const vmEn: Record = { "failAttachInstaller": "Couldn’t attach the image", "failCloneVM": "Couldn’t create CoW clone", "failDelete": "Couldn’t delete", + "failDiscardSuspend": "Couldn’t discard saved state", "failEject": "Couldn’t eject the installer", "failEnterRecovery": "Couldn’t enter recovery mode", "failExportDiagnostics": "Couldn’t export diagnostics", @@ -245,10 +269,12 @@ export const vmEn: Record = { "failGuestTools": "Guest Tools operation failed", "failOpenFolder": "Couldn’t open the folder", "failRestart": "Couldn’t restart", + "failResume": "Couldn’t resume", "failScreenshot": "Screenshot failed", "failSnapshot": "Restore point failed", "failStart": "Couldn’t start", "failStop": "Couldn’t shut down", + "failSuspend": "Couldn’t suspend", "failType": "Couldn’t type into the VM", "failUpgradeNVMe": "Couldn’t upgrade to NVMe", "fieldAudio": "Audio", @@ -306,6 +332,7 @@ export const vmEn: Record = { "pendingTitle": "Applies on next start", "pickRecoveryTitle": "Choose an offline image (.img / .dmg)", "restartToApply": "Restart to apply", + "resume": "Resume", "sendText": "Send text to VM…", "sendTextConfirm": "Send (Ctrl+Enter)", "sendTextDesc": "Supports Chinese, emoji, host IME, and dictation. Press Ctrl+Enter to inject into the focused macOS field.", @@ -350,14 +377,23 @@ export const vmEn: Record = { "state_broken": "Error", "state_creating": "Creating", "state_driver_unavailable": "Driver unavailable", + "state_resuming": "Resuming", "state_running": "Running", "state_starting": "Starting", "state_stopped": "Stopped", "state_stopping": "Stopping", + "state_suspended": "Suspended", + "state_suspending": "Suspending", + "suspend": "Suspend", + "suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.", + "suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.", + "suspendedNoticeTitle": "Saved state ready", + "suspendedSettingsHint": "Resume or discard saved state before changing settings", "techInfo": "Technical details", "toastCloned": "CoW clone “{name}” created", "toastDeleted": "{name} deleted", "toastDiagExported": "Redacted diagnostics archive exported (.zip)", + "toastDiscardSuspend": "Discarded saved state for {name}", "toastEjected": "Installer ejected", "toastEnterRecovery": "Recovery mode ready — pick Recovery in OpenCore on next start", "toastEnterRecoveryNextStart": "Recovery mode ready — restart to open the boot menu", @@ -377,11 +413,13 @@ export const vmEn: Record = { "toastOnlineRecoveryStarted": "Downloading online recovery image (~1 GB); will attach when ready", "toastPreventSleepOff": "Prevent-sleep guard disabled", "toastPreventSleepOn": "Prevent-sleep guard enabled", + "toastResumed": "{name} resumed", "toastScreenshotCopied": "VM screenshot copied", "toastSnapshotCreated": "Created restore point {name}", "toastSnapshotDeleted": "Deleted restore point {name}", "toastSnapshotRestored": "Restored to {name}", "toastStopped": "{name} shut down", + "toastSuspended": "{name} suspended", "toastTyped": "{n, plural, one {Typed # character} other {Typed # characters}}", "toggleFullscreen": "Toggle full screen", "typeClipboard": "Send clipboard to VM", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 5b2752c..ffd4062 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -137,6 +137,10 @@ export type I18nKey = | "diagBackingChainWarn" | "diagExternalDriveWarn" | "diagHighMemWarn" + | "discardSuspend" + | "discardSuspendConfirm" + | "discardSuspendDesc" + | "discardSuspendTitle" | "diskCompactAction" | "diskCompactDesc" | "diskCompactDone" @@ -202,6 +206,7 @@ export type I18nKey = | "failCloneVM" | "failCreate" | "failDelete" + | "failDiscardSuspend" | "failDownload" | "failEject" | "failEnterRecovery" @@ -213,12 +218,14 @@ export type I18nKey = | "failGuestTools" | "failOpenFolder" | "failRestart" + | "failResume" | "failRuntime" | "failSSH" | "failScreenshot" | "failSnapshot" | "failStart" | "failStop" + | "failSuspend" | "failType" | "failUpgradeNVMe" | "fieldAudio" @@ -617,6 +624,7 @@ export type I18nKey = | "resolution" | "restart" | "restartToApply" + | "resume" | "runtimeAlpha" | "runtimeAlphaHint" | "runtimeChannel_alpha" @@ -740,10 +748,13 @@ export type I18nKey = | "state_broken" | "state_creating" | "state_driver_unavailable" + | "state_resuming" | "state_running" | "state_starting" | "state_stopped" | "state_stopping" + | "state_suspended" + | "state_suspending" | "statsCPU" | "statsDisk" | "statsDiskSub" @@ -774,6 +785,11 @@ export type I18nKey = | "summarySSH" | "summarySSHPort" | "summarySource" + | "suspend" + | "suspendedNoticeDesc" + | "suspendedNoticeDescWithTime" + | "suspendedNoticeTitle" + | "suspendedSettingsHint" | "taskAppUpdate" | "taskCreate" | "taskDownload" @@ -800,6 +816,7 @@ export type I18nKey = | "toastCreated" | "toastDeleted" | "toastDiagExported" + | "toastDiscardSuspend" | "toastDownloadPaused" | "toastEjected" | "toastEnterRecovery" @@ -822,6 +839,7 @@ export type I18nKey = | "toastPreventSleepOff" | "toastPreventSleepOn" | "toastQueueCanceled" + | "toastResumed" | "toastRuntimeReady" | "toastSSHConfigWritten" | "toastSSHUserSaved" @@ -832,6 +850,7 @@ export type I18nKey = | "toastSnapshotDeleted" | "toastSnapshotRestored" | "toastStopped" + | "toastSuspended" | "toastTyped" | "toggleFullscreen" | "typeClipboard" diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 9be43de..d8c5c50 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -292,6 +292,10 @@ h1, h2, h3, p { margin: 0; } .status { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; display: inline-block; } .status-running { background: var(--status-running); } .status-stopped { border: 1.5px solid var(--status-idle); } +.status-suspended { + width: 7px; height: 8px; border-radius: 0; + background: linear-gradient(90deg, var(--status-busy) 0 2.5px, transparent 2.5px 4.5px, var(--status-busy) 4.5px 7px); +} .status-busy { background: conic-gradient(var(--status-busy) 0 50%, transparent 50% 100%); border: 1.5px solid var(--status-busy); animation: pulse 1.4s ease-in-out infinite; } .status-warn { background: var(--status-busy); } .status-broken { background: var(--status-error); border-radius: 1.5px; transform: rotate(45deg); width: 7px; height: 7px; } @@ -366,6 +370,7 @@ h1, h2, h3, p { margin: 0; } .vm-hero-pill.is-running { background: var(--ok-soft); border-color: transparent; color: var(--ok-text); } +.vm-hero-pill.is-suspended, .vm-hero-pill.is-busy { background: var(--warn-soft); border-color: transparent; color: var(--warn-text); } diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 49822da..92b48b5 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -48,7 +48,7 @@ export type RemoteRuntime = Model & { } export type VMListItem = Model & { - state: 'running' | 'stopped' | 'broken' + state: 'running' | 'stopped' | 'suspended' | 'broken' } export type PendingChange = app.PendingChange @@ -63,6 +63,7 @@ export type AppState = Omit, 'config' | 'host' | 'optimizati } export type AppUpdateInfo = version.UpdateInfo +export type SuspendInfo = reims.SuspendInfo export type VMDetail = reims.VMDetail export type VMStats = app.VMStats export type DriveShareSettings = Model diff --git a/frontend/src/ui/controls.tsx b/frontend/src/ui/controls.tsx index c014fe2..f7db8c9 100644 --- a/frontend/src/ui/controls.tsx +++ b/frontend/src/ui/controls.tsx @@ -87,11 +87,12 @@ export const IconButton = React.forwardRef( ) IconButton.displayName = 'IconButton' -export type StatusKind = 'running' | 'stopped' | 'busy' | 'broken' | 'warn' +export type StatusKind = 'running' | 'stopped' | 'suspended' | 'busy' | 'broken' | 'warn' export function statusKind(state: string): StatusKind { if (state === 'running') return 'running' - if (state === 'starting' || state === 'stopping' || state === 'creating') return 'busy' + if (state === 'suspended') return 'suspended' + if (state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' || state === 'creating') return 'busy' if (state === 'driver_unavailable') return 'warn' if (state === 'broken') return 'broken' return 'stopped' diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index e4d401a..ded8dce 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -47,6 +47,8 @@ export function DeleteSnapshot(arg1:string,arg2:string):Promise; export function DeleteVM(arg1:string,arg2:boolean):Promise; +export function DiscardSuspend(arg1:string):Promise; + export function DeliverFileToGuest(arg1:string):Promise; export function DeliverPathsToGuest(arg1:string,arg2:Array):Promise>; @@ -183,6 +185,8 @@ export function ResizeVMDisk(arg1:string,arg2:string):Promise; +export function ResumeVM(arg1:string):Promise; + export function RestoreSnapshot(arg1:string,arg2:string):Promise; export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise; @@ -225,6 +229,8 @@ export function SuggestDataRoots():Promise>; export function SuggestLanguagePack():Promise; +export function SuspendVM(arg1:string):Promise; + export function ToggleBorderless(arg1:string,arg2:boolean):Promise; export function ToggleVMFullscreen(arg1:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 2de951a..da78976 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -78,6 +78,10 @@ export function DeleteVM(arg1, arg2) { return window['go']['app']['App']['DeleteVM'](arg1, arg2); } +export function DiscardSuspend(arg1) { + return window['go']['app']['App']['DiscardSuspend'](arg1); +} + export function DeliverFileToGuest(arg1) { return window['go']['app']['App']['DeliverFileToGuest'](arg1); } @@ -350,6 +354,10 @@ export function RestartVM(arg1) { return window['go']['app']['App']['RestartVM'](arg1); } +export function ResumeVM(arg1) { + return window['go']['app']['App']['ResumeVM'](arg1); +} + export function RestoreSnapshot(arg1, arg2) { return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2); } @@ -434,6 +442,10 @@ export function SuggestLanguagePack() { return window['go']['app']['App']['SuggestLanguagePack'](); } +export function SuspendVM(arg1) { + return window['go']['app']['App']['SuspendVM'](arg1); +} + export function ToggleBorderless(arg1, arg2) { return window['go']['app']['App']['ToggleBorderless'](arg1, arg2); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 9883e88..bd48390 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -2296,6 +2296,52 @@ export namespace reims { this.guest_lang = source["guest_lang"]; } } + export class SuspendInfo { + schema_version: number; + vm_name: string; + cpus: number; + memory: string; + graphics: string; + displays: number; + resolution: string; + disk_controller: string; + cpu_model?: string; + audio: boolean; + audio_backend?: string; + network: boolean; + ssh_port: number; + extra_args?: string; + runtime_commit: string; + vendor_qemu_commit?: string; + created_at: string; + vmstate_size: number; + + static createFrom(source: any = {}) { + return new SuspendInfo(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.schema_version = source["schema_version"]; + this.vm_name = source["vm_name"]; + this.cpus = source["cpus"]; + this.memory = source["memory"]; + this.graphics = source["graphics"]; + this.displays = source["displays"]; + this.resolution = source["resolution"]; + this.disk_controller = source["disk_controller"]; + this.cpu_model = source["cpu_model"]; + this.audio = source["audio"]; + this.audio_backend = source["audio_backend"]; + this.network = source["network"]; + this.ssh_port = source["ssh_port"]; + this.extra_args = source["extra_args"]; + this.runtime_commit = source["runtime_commit"]; + this.vendor_qemu_commit = source["vendor_qemu_commit"]; + this.created_at = source["created_at"]; + this.vmstate_size = source["vmstate_size"]; + } + } export class VMDetail { name: string; state: string; @@ -2337,6 +2383,7 @@ export namespace reims { guest_tools_disabled?: boolean; shared_dir?: string; guest_lang?: string; + suspend_info?: SuspendInfo; static createFrom(source: any = {}) { return new VMDetail(source); @@ -2384,7 +2431,26 @@ export namespace reims { this.guest_tools_disabled = source["guest_tools_disabled"]; this.shared_dir = source["shared_dir"]; this.guest_lang = source["guest_lang"]; + this.suspend_info = this.convertValues(source["suspend_info"], SuspendInfo); } + + convertValues(a: any, classs: any, asMap: boolean = false): any { + if (!a) { + return a; + } + if (a.slice && a.map) { + return (a as any[]).map(elem => this.convertValues(elem, classs)); + } else if ("object" === typeof a) { + if (asMap) { + for (const key of Object.keys(a)) { + a[key] = new classs(a[key]); + } + return a; + } + return new classs(a); + } + return a; + } } export class VMListItem { name: string; diff --git a/internal/app/app.go b/internal/app/app.go index 061e539..310bfdd 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -265,6 +265,7 @@ func (a *App) pollVMs(ctx context.Context) { if err != nil { continue } + enrichVMListStates(vms) watchExits(ctx, vms, exitWatched, a.wakePoll) type pinCandidate struct { name string @@ -291,7 +292,10 @@ func (a *App) pollVMs(ctx context.Context) { } } if tr, ok := a.transitions[vm.Name]; ok { - if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") { + if (tr == "starting" && vm.State == "running") || + (tr == "stopping" && vm.State == "stopped") || + (tr == "suspending" && (vm.State == "suspended" || vm.State == "stopped")) || + (tr == "resuming" && vm.State == "running") { delete(a.transitions, vm.Name) if vm.State == "stopped" { delete(a.pendingChanges, vm.Name) @@ -454,7 +458,12 @@ func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) { if err != nil { return nil, err } - return c.List(ctx) + vms, err := c.List(ctx) + if err != nil { + return nil, err + } + enrichVMListStates(vms) + return vms, nil } // qemuImage is the executable reims-ctl reports as a running VM's PID. @@ -676,6 +685,7 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) { d.RecoveryMode = isRecoveryModeActive(d) a.populateGuestToolsDetail(&d) a.populateGuestLangDetail(&d) + a.populateSuspendDetail(&d) return d, nil } @@ -767,6 +777,7 @@ func (a *App) startTray() { }, GetSnapshot: func() tray.Snapshot { a.mu.Lock() + cfgCopy := *a.cfg loc := a.cfg.Locale cached := append([]reims.VMListItem(nil), a.lastVMs...) transitions := make(map[string]string, len(a.transitions)) @@ -774,6 +785,10 @@ func (a *App) startTray() { transitions[k] = v } a.mu.Unlock() + canSuspend := false + if active, err := rt.ResolveActive(&cfgCopy); err == nil && active != nil { + canSuspend = active.Manifest.HasCapability("vm-suspend") + } if len(cached) == 0 { if vms, err := a.listVMsInternal(context.Background()); err == nil { cached = vms @@ -797,9 +812,10 @@ func (a *App) startTray() { } effLoc := i18n.EffectiveLocale(loc) return tray.Snapshot{ - Locale: effLoc, - LocaleZh: effLoc == i18n.ZhCN, - VMs: items, + Locale: effLoc, + LocaleZh: effLoc == i18n.ZhCN, + CanSuspend: canSuspend, + VMs: items, } }, }) @@ -827,6 +843,12 @@ func (a *App) trayVMAction(name string, act tray.Action) { switch act { case tray.ActStart: err, failTitle = a.StartVM(name), i18n.M(loc, "tray.notify.start_fail", vars) + case tray.ActSuspend: + err, failTitle = a.SuspendVM(name), i18n.M(loc, "tray.notify.suspend_fail", vars) + case tray.ActResume: + err, failTitle = a.ResumeVM(name), i18n.M(loc, "tray.notify.resume_fail", vars) + case tray.ActDiscardSuspend: + err, failTitle = a.DiscardSuspend(name), i18n.M(loc, "tray.notify.discard_suspend_fail", vars) case tray.ActStop: err, failTitle = a.StopVM(name, false), i18n.M(loc, "tray.notify.stop_fail", vars) case tray.ActForceStop: @@ -878,7 +900,13 @@ func (a *App) SetDataRoot(dir string) error { curAppUpdateChannel := a.cfg.AppUpdateChannel curMinToTray := a.cfg.MinimizeToTray for _, v := range a.lastVMs { - if v.State == "running" || v.State == "starting" || v.State == "stopping" { + if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" { + a.mu.Unlock() + return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil) + } + } + for _, tr := range a.transitions { + if tr != "" { a.mu.Unlock() return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil) } @@ -1235,7 +1263,7 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) { a.mu.Lock() tr := a.transitions[name] a.mu.Unlock() - if tr == "stopping" { + if tr == "stopping" || tr == "suspending" { return } @@ -1313,6 +1341,7 @@ func stripLegacyManagedExtraArgs(extraArgs string) string { s := reims.StripGuestToolsArgs(extraArgs) s = reims.StripOfflineHelperArgs(s) s = qmp.StripLegacyWin10RebootArgs(s) + s = reims.StripIncomingDeferArgs(s) return strings.TrimSpace(s) } @@ -1322,6 +1351,10 @@ func (a *App) StartVM(name string) error { return err } c := prep.Client + curDetail, _ := c.Show(context.Background(), name) + if curDetail.State == "stopped" && reims.HasSuspendState(curDetail.Directory) { + return a.ResumeVM(name) + } a.mu.Lock() root := a.cfg.DataRoot tmpDir := a.cfg.TempDir() @@ -1331,7 +1364,6 @@ func (a *App) StartVM(name string) error { a.emitLog(name, "Start refused: "+err.Error()) return err } - curDetail, _ := c.Show(context.Background(), name) if err := prep.CheckMemory(curDetail.Memory, rep); err != nil { a.emitLog(name, "Start refused: "+err.Error()) return err diff --git a/internal/app/clone_flow.go b/internal/app/clone_flow.go index 42ca1d1..1ab10e6 100644 --- a/internal/app/clone_flow.go +++ b/internal/app/clone_flow.go @@ -46,6 +46,9 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error { if a.isVMRunning(ctx, c, sourceName, src) { return i18n.NewCodedError(loc, "E_VM_CLONE_RUNNING", "err.clone.source_running", i18n.Vars{"name": sourceName}, nil) } + if a.isVMSuspended(src) { + return i18n.NewCodedError(loc, "E_VM_CLONE_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": sourceName}, nil) + } if src.HasInstaller { return i18n.NewCodedError(loc, "E_VM_CLONE_RECOVERY", "err.clone.in_recovery", i18n.Vars{"name": sourceName}, nil) } diff --git a/internal/app/disk_flow.go b/internal/app/disk_flow.go index f1bf3cf..fc3e7ed 100644 --- a/internal/app/disk_flow.go +++ b/internal/app/disk_flow.go @@ -31,6 +31,9 @@ func (a *App) ResizeVMDisk(name, newSize string) (reims.DiskResizeResult, error) if a.isVMRunning(ctx, c, name, d) { return reims.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name) } + if a.isVMSuspended(d) { + return reims.DiskResizeResult{}, fmt.Errorf("resume or discard suspend state for %s before resizing its disk", name) + } diskPath := resolveVMDiskPath(d) if diskPath == "" { return reims.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name) @@ -77,6 +80,9 @@ func (a *App) CompactVMDisk(name string) (reims.DiskCompactResult, error) { if a.isVMRunning(ctx, c, name, d) { return reims.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name) } + if a.isVMSuspended(d) { + return reims.DiskCompactResult{}, fmt.Errorf("resume or discard suspend state for %s before reclaiming disk space", name) + } diskPath := resolveVMDiskPath(d) if diskPath == "" { return reims.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name) diff --git a/internal/app/snapshot_flow.go b/internal/app/snapshot_flow.go index 306aa7b..426fc75 100644 --- a/internal/app/snapshot_flow.go +++ b/internal/app/snapshot_flow.go @@ -85,6 +85,9 @@ func (a *App) runSnapshotOp(name, flag, snapName, verb string) error { if a.isVMRunning(ctx, c, name, d) { return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_RUNNING", "err.snapshot.vm_running", i18n.Vars{"name": name}, nil) } + if a.isVMSuspended(d) { + return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil) + } diskPath := resolveVMDiskPath(d) if diskPath == "" { return i18n.NewCodedError(loc, "E_SNAPSHOT_NO_DISK", "err.clone.no_disk", i18n.Vars{"name": name}, nil) diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go new file mode 100644 index 0000000..dc9ee8c --- /dev/null +++ b/internal/app/suspend_flow.go @@ -0,0 +1,356 @@ +package app + +import ( + "context" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/internal/plugin/builtin" + "github.com/Nwflower/reims-go/internal/qmp" + "github.com/Nwflower/reims-go/internal/vmstart" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +// enrichVMListStates overlays state="suspended" onto stopped VMs that have a +// complete suspend snapshot (suspend.vmstate + suspend.json) in their folder. +func enrichVMListStates(vms []reims.VMListItem) { + for i := range vms { + if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) { + vms[i].State = "suspended" + } + } +} + +func (a *App) populateSuspendDetail(d *reims.VMDetail) { + if d == nil || d.Directory == "" { + return + } + if d.State == "stopped" && reims.HasSuspendState(d.Directory) { + d.State = "suspended" + if info, err := reims.ReadSuspendInfo(d.Directory); err == nil { + d.SuspendInfo = info + } + } +} + +func (a *App) isVMSuspended(d reims.VMDetail) bool { + return d.State == "suspended" || (d.State == "stopped" && reims.HasSuspendState(d.Directory)) +} + +// SuspendVM pauses a running Intel VM, saves its RAM, CPU, device, and vGPU +// state to suspend.vmstate, and cleanly exits QEMU so the host can close +// Reims-Go or reboot Windows and later resume instantaneously. +func (a *App) SuspendVM(name string) error { + loc := a.locale() + prep, err := a.prep(name) + if err != nil { + return err + } + if !prep.Runtime.Manifest.HasCapability("vm-suspend") { + return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + + a.mu.Lock() + if tr := a.transitions[name]; tr != "" { + a.mu.Unlock() + return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + a.mu.Unlock() + + ctx := a.baseCtx() + c := prep.Client + d, err := c.Show(ctx, name) + if err != nil { + return err + } + if !a.isVMRunning(ctx, c, name, d) { + return i18n.NewCodedError(loc, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": name}, nil) + } + if d.Directory == "" { + return fmt.Errorf("VM %s has no directory", name) + } + if memGB, ok := reims.ParseSizeGB(d.Memory); ok { + dirRep := host.Inspect(d.Directory) + needGB := memGB + 1.0 + if dirRep.FreeDiskGB > 0 && dirRep.FreeDiskGB < needGB { + return i18n.NewCodedError(loc, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{ + "need": fmt.Sprintf("%.1f", needGB), + "avail": fmt.Sprintf("%.1f", dirRep.FreeDiskGB), + }, nil) + } + } + + oldPID := a.cachedVMPID(name) + a.cancelRebootWatcher(name) + stopVMMonitor(name) + + a.mu.Lock() + mgr := a.pluginMgr + gt := a.guestTools + a.transitions[name] = "suspending" + a.mu.Unlock() + if mgr != nil { + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{ + VMName: name, + VMDir: d.Directory, + DriverID: builtin.IDDriverReimsMacOS, + }) + } + a.emitStateChanged() + + tmpPath := reims.SuspendStatePath(d.Directory) + ".tmp" + _ = os.Remove(tmpPath) + + a.emitLog(name, fmt.Sprintf("Suspending %s to disk (%s)...", name, reims.SuspendStateFileName)) + lastPct := -1 + err = qmp.SuspendToFile(ctx, d.Directory, tmpPath, func(p qmp.MigrateProgress) { + if p.Total > 0 { + pct := int(p.Transferred * 100 / p.Total) + if pct >= lastPct+25 || p.Status == "completed" { + lastPct = pct + a.emitLog(name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct)) + } + } + }) + if err != nil { + _ = os.Remove(tmpPath) + a.clearTransition(name) + a.emitLog(name, "Suspend error: "+err.Error()) + a.wakePoll() + a.emitStateChanged() + return err + } + + a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout) + + st, statErr := os.Stat(tmpPath) + if statErr != nil || st.Size() <= 0 { + _ = os.Remove(tmpPath) + a.clearTransition(name) + a.wakePoll() + a.emitStateChanged() + if statErr != nil { + return fmt.Errorf("suspend snapshot missing after save: %w", statErr) + } + return fmt.Errorf("suspend snapshot is empty after save") + } + + finalPath := reims.SuspendStatePath(d.Directory) + _ = os.Remove(finalPath) + if err := os.Rename(tmpPath, finalPath); err != nil { + _ = os.Remove(tmpPath) + a.clearTransition(name) + a.wakePoll() + a.emitStateChanged() + return fmt.Errorf("finalize suspend snapshot: %w", err) + } + + info := reims.BuildSuspendInfo(d, prep.Runtime, st.Size()) + if err := reims.WriteSuspendInfo(d.Directory, info); err != nil { + _ = reims.RemoveSuspendState(d.Directory) + a.clearTransition(name) + a.wakePoll() + a.emitStateChanged() + return fmt.Errorf("write suspend metadata: %w", err) + } + + if gt != nil { + gt.UnregisterVM(name) + } + if mgr != nil { + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{ + VMName: name, + VMDir: d.Directory, + DriverID: builtin.IDDriverReimsMacOS, + }) + } + a.clearTransition(name) + a.emitLog(name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", name, float64(st.Size())/float64(1<<30))) + a.wakePoll() + a.emitStateChanged() + return nil +} + +// ResumeVM launches a fresh QEMU process in `-incoming defer` mode (via +// `reims-ctl set --extra-args`), restores the VM's RAM, CPU, devices, and vGPU +// state from suspend.vmstate, and resumes guest execution. On any restore +// failure, suspend.vmstate and suspend.json are preserved so the user can retry. +func (a *App) ResumeVM(name string) error { + loc := a.locale() + prep, err := a.prep(name) + if err != nil { + return err + } + if !prep.Runtime.Manifest.HasCapability("vm-suspend") { + return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + + a.mu.Lock() + root := a.cfg.DataRoot + if tr := a.transitions[name]; tr != "" { + a.mu.Unlock() + return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + mgr := a.pluginMgr + a.mu.Unlock() + + ctx := a.baseCtx() + c := prep.Client + d, err := c.Show(ctx, name) + if err != nil { + return err + } + if a.isVMRunning(ctx, c, name, d) { + return fmt.Errorf("%s", i18n.T(loc, "vm.already_running", name)) + } + if !reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": name}, nil) + } + meta, err := reims.ReadSuspendInfo(d.Directory) + if err != nil { + return fmt.Errorf("read suspend metadata: %w", err) + } + if diffs := reims.ValidateSuspendCompatibility(*meta, d, prep.Runtime); len(diffs) > 0 { + return i18n.NewCodedError(loc, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{ + "diffs": strings.Join(diffs, ", "), + }, nil) + } + + rep := host.Inspect(root) + if err := prep.CheckWHPX(rep); err != nil { + a.emitLog(name, "Resume refused: "+err.Error()) + return err + } + if err := prep.CheckMemory(d.Memory, rep); err != nil { + a.emitLog(name, "Resume refused: "+err.Error()) + return err + } + + a.cancelRebootWatcher(name) + + if prep.Runtime.Manifest.HasCapability("win32-unicode-input") { + if env := a.inputBridgeEnv(name, d.Directory); len(env) > 0 { + c.Env = append(c.Env, env...) + } + } + if prep.Runtime.Manifest.HasCapability("display-fixed-mode") && + host.ShouldUseFixedGuestMode(d.Borderless, d.Resolution, rep.PrimaryDisplay) { + c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1") + } + + origExtraArgs := reims.StripIncomingDeferArgs(d.ExtraArgs) + incomingArgs := reims.MergeIncomingDeferArgs(origExtraArgs) + if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &incomingArgs}, io.Discard, io.Discard); err != nil { + return fmt.Errorf("prepare incoming extra-args: %w", err) + } + restoredExtra := false + restoreExtra := func() { + if restoredExtra { + return + } + restoredExtra = true + if rerr := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &origExtraArgs}, io.Discard, io.Discard); rerr != nil { + a.emitLog(name, "Warning: could not restore extra-args after incoming launch: "+rerr.Error()) + } + } + defer restoreExtra() + + a.mu.Lock() + a.transitions[name] = "resuming" + a.mu.Unlock() + a.emitStateChanged() + + startAt := time.Now() + w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) + a.emitLog(name, fmt.Sprintf("Resuming %s from %s...", name, reims.SuspendStateFileName)) + if err := c.Start(ctx, name, w, w); err != nil { + restoreExtra() + a.clearTransition(name) + a.emitLog(name, "Resume launch error: "+err.Error()) + a.wakePoll() + a.emitStateChanged() + return err + } + restoreExtra() + + if err := qmp.ResumeFromFile(ctx, d.Directory, reims.SuspendStatePath(d.Directory), nil); err != nil { + a.emitLog(name, "Resume snapshot error (suspend state preserved for retry): "+err.Error()) + // Clean up the paused incoming QEMU process without touching suspend.vmstate. + if qerr := qmp.QuitVM(context.Background(), d.Directory); qerr != nil { + _ = c.StopForce(context.Background(), name, io.Discard, io.Discard) + } + a.clearTransition(name) + a.wakePoll() + a.emitStateChanged() + return err + } + + if rerr := reims.RemoveSuspendState(d.Directory); rerr != nil { + a.emitLog(name, "Warning: could not remove consumed suspend files: "+rerr.Error()) + } + + if mgr != nil { + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{ + VMName: name, + VMDir: d.Directory, + DriverID: builtin.IDDriverReimsMacOS, + }) + } + a.startVMMonitor(name, d, startAt) + a.clearTransition(name) + a.emitLog(name, fmt.Sprintf("Resumed %s in %.1fs", name, time.Since(startAt).Seconds())) + a.wakePoll() + a.emitStateChanged() + return nil +} + +// DiscardSuspend deletes a suspended VM's saved RAM/device snapshot so the VM +// returns to the ordinary stopped state (equivalent to powering off). +func (a *App) DiscardSuspend(name string) error { + loc := a.locale() + c, err := a.client() + if err != nil { + return err + } + a.mu.Lock() + if tr := a.transitions[name]; tr != "" { + a.mu.Unlock() + return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + a.mu.Unlock() + + ctx := a.baseCtx() + d, err := c.Show(ctx, name) + if err != nil { + return err + } + if a.isVMRunning(ctx, c, name, d) { + return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": name}, nil) + } + if err := reims.RemoveSuspendState(d.Directory); err != nil { + return err + } + a.emitLog(name, "Discarded suspend state for "+name) + a.wakePoll() + a.emitStateChanged() + return nil +} + +func (a *App) clearTransition(name string) { + a.mu.Lock() + delete(a.transitions, name) + a.mu.Unlock() +} + +func (a *App) emitStateChanged() { + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + } +} diff --git a/internal/app/suspend_flow_test.go b/internal/app/suspend_flow_test.go new file mode 100644 index 0000000..686c25f --- /dev/null +++ b/internal/app/suspend_flow_test.go @@ -0,0 +1,58 @@ +package app + +import ( + "os" + "testing" + + "github.com/Nwflower/reims-go/internal/driver/reims" + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) { + suspendedDir := t.TempDir() + stoppedDir := t.TempDir() + + if err := os.WriteFile(reims.SuspendStatePath(suspendedDir), []byte("0123456789"), 0o644); err != nil { + t.Fatal(err) + } + if err := reims.WriteSuspendInfo(suspendedDir, reims.BuildSuspendInfo( + reims.VMDetail{Name: "mac-a", CPUs: 8, Memory: "8G", Graphics: "reims-vgpu"}, + rt.Installed{Commit: "3731afd"}, + 10, + )); err != nil { + t.Fatal(err) + } + + vms := []reims.VMListItem{ + {Name: "mac-a", Dir: suspendedDir, State: "stopped"}, + {Name: "mac-b", Dir: stoppedDir, State: "stopped"}, + {Name: "mac-c", Dir: suspendedDir, State: "running"}, + } + enrichVMListStates(vms) + if vms[0].State != "suspended" { + t.Fatalf("mac-a state = %q, want suspended", vms[0].State) + } + if vms[1].State != "stopped" { + t.Fatalf("mac-b state = %q, want stopped", vms[1].State) + } + if vms[2].State != "running" { + t.Fatalf("running VM must stay running, got %q", vms[2].State) + } + + a := &App{} + det := reims.VMDetail{Name: "mac-a", Directory: suspendedDir, State: "stopped"} + a.populateSuspendDetail(&det) + if det.State != "suspended" || det.SuspendInfo == nil || det.SuspendInfo.VMStateSize != 10 { + t.Fatalf("populateSuspendDetail failed: %+v", det) + } + if !a.isVMSuspended(det) { + t.Fatal("expected isVMSuspended=true") + } +} + +func TestStripLegacyManagedExtraArgsStripsIncomingDefer(t *testing.T) { + got := stripLegacyManagedExtraArgs("-machine kernel-irqchip=on -incoming defer") + if got != "-machine kernel-irqchip=on" { + t.Fatalf("stripLegacyManagedExtraArgs = %q", got) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index cc733c6..5242e24 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -134,6 +134,9 @@ func printUsage(loc i18n.Locale) { "cli.usage.cmd_vm_compact", "cli.usage.cmd_vm_start", "cli.usage.cmd_vm_stop", + "cli.usage.cmd_vm_suspend", + "cli.usage.cmd_vm_resume", + "cli.usage.cmd_vm_discard_suspend", "cli.usage.cmd_vm_type", "cli.usage.cmd_inst_list", "cli.usage.cmd_inst_dl", @@ -370,7 +373,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error { func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error { if len(args) == 0 { - return fmt.Errorf("usage: reims-go vm ") + return fmt.Errorf("usage: reims-go vm ") } prep, err := vmstart.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) }) if err != nil { @@ -389,6 +392,13 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e fmt.Println(i18n.T(loc, "vm.empty")) return nil } + for i := range vms { + if st, _ := vms[i]["state"].(string); st == "stopped" { + if dir, _ := vms[i]["dir"].(string); reims.HasSuspendState(dir) { + vms[i]["state"] = "suspended" + } + } + } enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") return enc.Encode(vms) @@ -519,6 +529,9 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e AudioBackend: strings.TrimSpace(*audioBackend), GuestLang: strings.TrimSpace(*guestLang), } + if d, serr := client.Show(ctx, setOpts.Name); serr == nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_SET_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": setOpts.Name}, nil) + } if reims.HasCtlSetChanges(setOpts) { if err := client.Set(ctx, setOpts, os.Stdout, os.Stderr); err != nil { return err @@ -544,6 +557,21 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e return fmt.Errorf("usage: reims-go vm stop ") } return client.Stop(ctx, args[1], os.Stdout, os.Stderr) + case "suspend": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go vm suspend ") + } + return suspendVM(ctx, cfg, prep, args[1]) + case "resume": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go vm resume ") + } + return resumeVM(ctx, cfg, prep, args[1]) + case "discard-suspend": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go vm discard-suspend ") + } + return discardSuspendVM(ctx, cfg, prep, args[1]) case "eject": if len(args) < 2 { return fmt.Errorf("usage: reims-go vm eject ") @@ -583,6 +611,9 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if d.State == "running" { return fmt.Errorf("%s", i18n.T(loc, "vm.resize.stop_first", args[1])) } + if reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_RESIZE_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil) + } diskPath := resolveCLIDiskPath(d) res, err := reims.ResizeDisk(ctx, active.QemuImgPath(), client.Env, diskPath, args[2], os.Stdout, os.Stderr) if err != nil { @@ -602,6 +633,9 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if d.State == "running" { return fmt.Errorf("%s", i18n.T(loc, "vm.compact.stop_first", args[1])) } + if reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_COMPACT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil) + } diskPath := resolveCLIDiskPath(d) res, err := reims.CompactDisk(ctx, active.QemuImgPath(), client.Env, diskPath, os.Stdout, os.Stderr) if err != nil { diff --git a/internal/cli/start.go b/internal/cli/start.go index d81ed1a..b6b215c 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -11,6 +11,7 @@ import ( "time" "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/plugin" @@ -49,6 +50,9 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s if viaWindow && windowHandoffWorks { return startInWindow(ctx, cfg, name) } + if d.State == "stopped" && reims.HasSuspendState(d.Directory) { + return resumeVM(ctx, cfg, prep, name) + } // Honour the core plugin's WHPX setting, as the window does. st := plugin.ReadState(cfg.DataRoot) diff --git a/internal/cli/suspend.go b/internal/cli/suspend.go new file mode 100644 index 0000000..e120f83 --- /dev/null +++ b/internal/cli/suspend.go @@ -0,0 +1,179 @@ +package cli + +import ( + "context" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/qmp" + "github.com/Nwflower/reims-go/internal/vmstart" +) + +func suspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { + loc := cfg.Locale + if !prep.Runtime.Manifest.HasCapability("vm-suspend") { + return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + d, err := prep.Client.Show(ctx, name) + if err != nil { + return err + } + if d.State != "running" { + return i18n.NewCodedError(loc, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": name}, nil) + } + if memGB, ok := reims.ParseSizeGB(d.Memory); ok { + dirRep := host.Inspect(d.Directory) + needGB := memGB + 1.0 + if dirRep.FreeDiskGB > 0 && dirRep.FreeDiskGB < needGB { + return i18n.NewCodedError(loc, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{ + "need": fmt.Sprintf("%.1f", needGB), + "avail": fmt.Sprintf("%.1f", dirRep.FreeDiskGB), + }, nil) + } + } + var oldPID int + if vms, lerr := prep.Client.List(ctx); lerr == nil { + for _, vm := range vms { + if vm.Name == name && vm.PID != nil && *vm.PID > 0 { + oldPID = *vm.PID + break + } + } + } + + tmpPath := reims.SuspendStatePath(d.Directory) + ".tmp" + _ = os.Remove(tmpPath) + fmt.Fprintf(os.Stderr, "Suspending %s to %s...\n", name, reims.SuspendStateFileName) + if err := qmp.SuspendToFile(ctx, d.Directory, tmpPath, nil); err != nil { + _ = os.Remove(tmpPath) + return err + } + if oldPID > 0 { + waitCtx, cancel := context.WithTimeout(ctx, 12*time.Second) + _ = host.WaitProcessExit(waitCtx, uint32(oldPID), "qemu-system-x86_64.exe") + cancel() + } + st, err := os.Stat(tmpPath) + if err != nil || st.Size() <= 0 { + _ = os.Remove(tmpPath) + if err != nil { + return err + } + return fmt.Errorf("suspend snapshot is empty after save") + } + finalPath := reims.SuspendStatePath(d.Directory) + _ = os.Remove(finalPath) + if err := os.Rename(tmpPath, finalPath); err != nil { + _ = os.Remove(tmpPath) + return err + } + if err := reims.WriteSuspendInfo(d.Directory, reims.BuildSuspendInfo(d, prep.Runtime, st.Size())); err != nil { + _ = reims.RemoveSuspendState(d.Directory) + return err + } + fmt.Printf("Suspended %s (%.2f GiB saved)\n", name, float64(st.Size())/float64(1<<30)) + return nil +} + +func resumeVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { + loc := cfg.Locale + if !prep.Runtime.Manifest.HasCapability("vm-suspend") { + return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + rep := host.Inspect(cfg.DataRoot) + d, err := prep.Client.Show(ctx, name) + if err != nil { + return err + } + if d.State == "running" { + return fmt.Errorf("%s", i18n.T(loc, "vm.already_running", name)) + } + if !reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": name}, nil) + } + meta, err := reims.ReadSuspendInfo(d.Directory) + if err != nil { + return err + } + if diffs := reims.ValidateSuspendCompatibility(*meta, d, prep.Runtime); len(diffs) > 0 { + return i18n.NewCodedError(loc, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{ + "diffs": strings.Join(diffs, ", "), + }, nil) + } + if err := prep.CheckWHPX(rep); err != nil { + return err + } + if err := prep.CheckMemory(d.Memory, rep); err != nil { + return err + } + + origExtraArgs := reims.StripIncomingDeferArgs(d.ExtraArgs) + incomingArgs := reims.MergeIncomingDeferArgs(origExtraArgs) + if err := prep.Client.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &incomingArgs}, io.Discard, io.Discard); err != nil { + return err + } + restored := false + restoreExtra := func() { + if restored { + return + } + restored = true + _ = prep.Client.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &origExtraArgs}, io.Discard, io.Discard) + } + defer restoreExtra() + + fmt.Fprintf(os.Stderr, "Resuming %s from %s...\n", name, reims.SuspendStateFileName) + startAt := time.Now() + if err := prep.Client.Start(ctx, name, os.Stdout, os.Stderr); err != nil { + restoreExtra() + return err + } + restoreExtra() + + if err := qmp.ResumeFromFile(ctx, d.Directory, reims.SuspendStatePath(d.Directory), nil); err != nil { + if qerr := qmp.QuitVM(context.Background(), d.Directory); qerr != nil { + _ = prep.Client.StopForce(context.Background(), name, io.Discard, io.Discard) + } + return err + } + _ = reims.RemoveSuspendState(d.Directory) + + if vms, lerr := prep.Client.List(ctx); lerr == nil { + for _, vm := range vms { + if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { + vmDir := vm.Dir + if vmDir == "" { + vmDir = d.Directory + } + if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" { + fmt.Fprintln(os.Stderr, line) + } + } + } + } + fmt.Printf("Resumed %s in %.1fs\n", name, time.Since(startAt).Seconds()) + return nil +} + +func discardSuspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { + loc := cfg.Locale + d, err := prep.Client.Show(ctx, name) + if err != nil { + return err + } + if d.State == "running" { + return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": name}, nil) + } + if err := reims.RemoveSuspendState(d.Directory); err != nil { + return err + } + fmt.Printf("Discarded suspend state for %s\n", name) + return nil +} diff --git a/internal/driver/reims/reims.go b/internal/driver/reims/reims.go index 17dcc5d..06b51de 100644 --- a/internal/driver/reims/reims.go +++ b/internal/driver/reims/reims.go @@ -88,8 +88,9 @@ type VMDetail struct { GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"` // GuestToolsDisabled is set when the Guest Tools plugin is switched off. GuestToolsDisabled bool `json:"guest_tools_disabled,omitempty"` - SharedDir string `json:"shared_dir,omitempty"` - GuestLang string `json:"guest_lang,omitempty"` + SharedDir string `json:"shared_dir,omitempty"` + GuestLang string `json:"guest_lang,omitempty"` + SuspendInfo *SuspendInfo `json:"suspend_info,omitempty"` } type ValidationIssue struct { @@ -258,6 +259,10 @@ func ValidateSetLocalized(o SetOpts, current VMDetail, rep host.Report, loc i18n if strings.TrimSpace(o.Name) == "" { issues = append(issues, ValidationIssue{Field: "name", Code: "missing_name", Message: i18n.T(loc, "validate.missing_name")}) } + if current.State == "suspended" { + issues = append(issues, ValidationIssue{Field: "state", Code: "vm_suspended", Message: i18n.T(loc, "validate.vm_suspended")}) + return issues + } if o.CPUs != 0 && (o.CPUs < 1 || (rep.LogicalCPUs > 0 && o.CPUs > rep.LogicalCPUs)) { issues = append(issues, ValidationIssue{Field: "cpus", Code: "invalid_cpus", Message: i18n.T(loc, "validate.invalid_cpus", max(rep.LogicalCPUs, 1))}) } diff --git a/internal/driver/reims/suspend.go b/internal/driver/reims/suspend.go new file mode 100644 index 0000000..b4035d4 --- /dev/null +++ b/internal/driver/reims/suspend.go @@ -0,0 +1,240 @@ +package reims + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +const ( + // SuspendStateFileName holds the QEMU mapped-ram + device VMState snapshot. + SuspendStateFileName = "suspend.vmstate" + // SuspendMetaFileName records the hardware and runtime fingerprint used to + // create suspend.vmstate so incompatible resumes are caught before launch. + SuspendMetaFileName = "suspend.json" + // SuspendSchemaVersion is the current metadata schema version. + SuspendSchemaVersion = 1 +) + +// SuspendInfo describes a VM's saved suspend-to-disk state inside its VM folder. +type SuspendInfo struct { + SchemaVersion int `json:"schema_version"` + VMName string `json:"vm_name"` + CPUs int `json:"cpus"` + Memory string `json:"memory"` + Graphics string `json:"graphics"` + Displays int `json:"displays"` + Resolution string `json:"resolution"` + DiskController string `json:"disk_controller"` + CPUModel string `json:"cpu_model,omitempty"` + Audio bool `json:"audio"` + AudioBackend string `json:"audio_backend,omitempty"` + Network bool `json:"network"` + SSHPort int `json:"ssh_port"` + ExtraArgs string `json:"extra_args,omitempty"` + RuntimeCommit string `json:"runtime_commit"` + VendorQemuCommit string `json:"vendor_qemu_commit,omitempty"` + CreatedAt string `json:"created_at"` + VMStateSize int64 `json:"vmstate_size"` +} + +// SuspendStatePath returns the path to a VM's suspend snapshot file. +func SuspendStatePath(vmDir string) string { + return filepath.Join(vmDir, SuspendStateFileName) +} + +// SuspendMetaPath returns the path to a VM's suspend metadata JSON file. +func SuspendMetaPath(vmDir string) string { + return filepath.Join(vmDir, SuspendMetaFileName) +} + +// HasSuspendState reports whether vmDir contains a complete suspend snapshot +// (both a non-empty suspend.vmstate and its suspend.json metadata). +func HasSuspendState(vmDir string) bool { + if strings.TrimSpace(vmDir) == "" { + return false + } + st, err := os.Stat(SuspendStatePath(vmDir)) + if err != nil || st.IsDir() || st.Size() <= 0 { + return false + } + mst, err := os.Stat(SuspendMetaPath(vmDir)) + if err != nil || mst.IsDir() || mst.Size() <= 0 { + return false + } + return true +} + +// ReadSuspendInfo reads suspend.json from vmDir and refreshes VMStateSize from +// the actual suspend.vmstate file on disk. +func ReadSuspendInfo(vmDir string) (*SuspendInfo, error) { + b, err := os.ReadFile(SuspendMetaPath(vmDir)) + if err != nil { + return nil, err + } + var info SuspendInfo + if err := json.Unmarshal(b, &info); err != nil { + return nil, fmt.Errorf("parse %s: %w", SuspendMetaFileName, err) + } + if st, err := os.Stat(SuspendStatePath(vmDir)); err == nil && !st.IsDir() { + info.VMStateSize = st.Size() + } + return &info, nil +} + +// WriteSuspendInfo atomically writes suspend.json inside vmDir. +func WriteSuspendInfo(vmDir string, info SuspendInfo) error { + if info.SchemaVersion == 0 { + info.SchemaVersion = SuspendSchemaVersion + } + if info.CreatedAt == "" { + info.CreatedAt = time.Now().UTC().Format(time.RFC3339) + } + info.ExtraArgs = StripIncomingDeferArgs(info.ExtraArgs) + b, err := json.MarshalIndent(info, "", " ") + if err != nil { + return err + } + b = append(b, '\n') + tmp := SuspendMetaPath(vmDir) + ".tmp" + if err := os.WriteFile(tmp, b, 0o644); err != nil { + return err + } + return os.Rename(tmp, SuspendMetaPath(vmDir)) +} + +// BuildSuspendInfo snapshots a VM's hardware and runtime fingerprint for suspend.json. +func BuildSuspendInfo(d VMDetail, active rt.Installed, vmstateSize int64) SuspendInfo { + return SuspendInfo{ + SchemaVersion: SuspendSchemaVersion, + VMName: d.Name, + CPUs: d.CPUs, + Memory: strings.TrimSpace(d.Memory), + Graphics: strings.TrimSpace(d.Graphics), + Displays: d.Displays, + Resolution: strings.TrimSpace(d.Resolution), + DiskController: strings.TrimSpace(d.DiskController), + CPUModel: strings.TrimSpace(d.CPUModel), + Audio: d.Audio, + AudioBackend: strings.TrimSpace(d.AudioBackend), + Network: d.Network, + SSHPort: d.SSHPort, + ExtraArgs: StripIncomingDeferArgs(d.ExtraArgs), + RuntimeCommit: strings.TrimSpace(active.Commit), + VendorQemuCommit: strings.TrimSpace(active.Manifest.VendorQemuCommit), + CreatedAt: time.Now().UTC().Format(time.RFC3339), + VMStateSize: vmstateSize, + } +} + +// RemoveSuspendState deletes suspend.vmstate, suspend.json, and any partial +// temporary files inside vmDir. +func RemoveSuspendState(vmDir string) error { + if strings.TrimSpace(vmDir) == "" { + return nil + } + var firstErr error + for _, name := range []string{ + SuspendMetaFileName, + SuspendMetaFileName + ".tmp", + SuspendStateFileName, + SuspendStateFileName + ".tmp", + } { + if err := os.Remove(filepath.Join(vmDir, name)); err != nil && !os.IsNotExist(err) && firstErr == nil { + firstErr = err + } + } + return firstErr +} + +// ValidateSuspendCompatibility checks that the VM hardware and runtime match +// the fingerprint stored when the VM was suspended. Returns human-readable +// mismatch descriptions; an empty slice means compatible. +func ValidateSuspendCompatibility(meta SuspendInfo, cur VMDetail, active rt.Installed) []string { + var diffs []string + if meta.CPUs > 0 && cur.CPUs > 0 && meta.CPUs != cur.CPUs { + diffs = append(diffs, fmt.Sprintf("CPUs (%d -> %d)", meta.CPUs, cur.CPUs)) + } + if meta.Memory != "" && cur.Memory != "" && !strings.EqualFold(strings.TrimSpace(meta.Memory), strings.TrimSpace(cur.Memory)) { + diffs = append(diffs, fmt.Sprintf("Memory (%s -> %s)", meta.Memory, cur.Memory)) + } + if meta.Graphics != "" && cur.Graphics != "" && !strings.EqualFold(strings.TrimSpace(meta.Graphics), strings.TrimSpace(cur.Graphics)) { + diffs = append(diffs, fmt.Sprintf("Graphics (%s -> %s)", meta.Graphics, cur.Graphics)) + } + if meta.Displays > 0 && cur.Displays > 0 && meta.Displays != cur.Displays { + diffs = append(diffs, fmt.Sprintf("Displays (%d -> %d)", meta.Displays, cur.Displays)) + } + if meta.DiskController != "" && cur.DiskController != "" && !strings.EqualFold(strings.TrimSpace(meta.DiskController), strings.TrimSpace(cur.DiskController)) { + diffs = append(diffs, fmt.Sprintf("Disk controller (%s -> %s)", meta.DiskController, cur.DiskController)) + } + if meta.Audio != cur.Audio { + diffs = append(diffs, fmt.Sprintf("Audio (%v -> %v)", meta.Audio, cur.Audio)) + } + if meta.Network != cur.Network { + diffs = append(diffs, fmt.Sprintf("Network (%v -> %v)", meta.Network, cur.Network)) + } + if meta.VendorQemuCommit != "" && active.Manifest.VendorQemuCommit != "" && + !strings.EqualFold(strings.TrimSpace(meta.VendorQemuCommit), strings.TrimSpace(active.Manifest.VendorQemuCommit)) { + diffs = append(diffs, fmt.Sprintf("QEMU commit (%s -> %s)", shortRev(meta.VendorQemuCommit), shortRev(active.Manifest.VendorQemuCommit))) + } else if meta.RuntimeCommit != "" && active.Commit != "" && + !strings.EqualFold(strings.TrimSpace(meta.RuntimeCommit), strings.TrimSpace(active.Commit)) { + diffs = append(diffs, fmt.Sprintf("Runtime (%s -> %s)", meta.RuntimeCommit, active.Commit)) + } + return diffs +} + +func shortRev(rev string) string { + rev = strings.TrimSpace(rev) + if len(rev) > 8 { + return rev[:8] + } + return rev +} + +// HasIncomingDeferArg reports whether extraArgs contains `-incoming defer`. +func HasIncomingDeferArg(extraArgs string) bool { + tokens := splitShellTokens(extraArgs) + for i := 0; i < len(tokens); i++ { + tok := tokens[i] + if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" { + return true + } + if tok == "-incoming=defer" { + return true + } + } + return false +} + +// StripIncomingDeferArgs removes any `-incoming defer` / `-incoming=defer` +// arguments from QEMU extra-args while leaving all other arguments intact. +func StripIncomingDeferArgs(existing string) string { + tokens := splitShellTokens(existing) + cleaned := make([]string, 0, len(tokens)) + for i := 0; i < len(tokens); i++ { + tok := tokens[i] + if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" { + i++ + continue + } + if tok == "-incoming=defer" { + continue + } + cleaned = append(cleaned, tok) + } + return strings.Join(cleaned, " ") +} + +// MergeIncomingDeferArgs idempotently appends `-incoming defer` to extra-args. +func MergeIncomingDeferArgs(existing string) string { + base := StripIncomingDeferArgs(existing) + if base == "" { + return "-incoming defer" + } + return base + " -incoming defer" +} diff --git a/internal/driver/reims/suspend_test.go b/internal/driver/reims/suspend_test.go new file mode 100644 index 0000000..4401ca6 --- /dev/null +++ b/internal/driver/reims/suspend_test.go @@ -0,0 +1,114 @@ +package reims + +import ( + "os" + "strings" + "testing" + + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +func TestSuspendStateLifecycle(t *testing.T) { + dir := t.TempDir() + if HasSuspendState(dir) { + t.Fatal("empty dir should not have suspend state") + } + + // Only vmstate without meta -> incomplete. + if err := os.WriteFile(SuspendStatePath(dir), []byte("vmstate-bytes"), 0o644); err != nil { + t.Fatal(err) + } + if HasSuspendState(dir) { + t.Fatal("vmstate without suspend.json should not count as complete suspend state") + } + + active := rt.Installed{ + Commit: "3731afd-p9", + Manifest: rt.Manifest{ + VendorQemuCommit: "4571bc5fecb039e8cfd6837e077810fbe074e11b", + }, + } + detail := VMDetail{ + Name: "tahoe", + CPUs: 8, + Memory: "8G", + Graphics: "reims-vgpu", + Displays: 1, + Resolution: "1920x1080", + DiskController: "nvme", + Audio: true, + Network: true, + ExtraArgs: "-machine kernel-irqchip=on -incoming defer", + } + info := BuildSuspendInfo(detail, active, 13) + if err := WriteSuspendInfo(dir, info); err != nil { + t.Fatalf("WriteSuspendInfo: %v", err) + } + if !HasSuspendState(dir) { + t.Fatal("expected HasSuspendState=true after writing both files") + } + + got, err := ReadSuspendInfo(dir) + if err != nil { + t.Fatalf("ReadSuspendInfo: %v", err) + } + if got.VMStateSize != 13 || got.CPUs != 8 || got.ExtraArgs != "-machine kernel-irqchip=on" { + t.Fatalf("unexpected suspend info: %+v", got) + } + + // Compatible check passes. + if diffs := ValidateSuspendCompatibility(*got, detail, active); len(diffs) != 0 { + t.Fatalf("expected compatible, got %v", diffs) + } + + // Hardware and runtime mismatch checks trigger. + changedDetail := detail + changedDetail.CPUs = 12 + changedDetail.Memory = "16G" + changedRT := active + changedRT.Manifest.VendorQemuCommit = "deadbeef00000000000000000000000000000000" + diffs := ValidateSuspendCompatibility(*got, changedDetail, changedRT) + if len(diffs) != 3 { + t.Fatalf("expected 3 diffs, got %v", diffs) + } + + if err := RemoveSuspendState(dir); err != nil { + t.Fatalf("RemoveSuspendState: %v", err) + } + if HasSuspendState(dir) { + t.Fatal("expected HasSuspendState=false after RemoveSuspendState") + } +} + +func TestIncomingDeferArgsIdempotent(t *testing.T) { + if HasIncomingDeferArg("") || HasIncomingDeferArg("-machine q35") { + t.Fatal("unexpected HasIncomingDeferArg=true") + } + m := MergeIncomingDeferArgs(`-drive "id=x,file=C:/a b/c.img"`) + if !HasIncomingDeferArg(m) { + t.Fatalf("expected -incoming defer in %q", m) + } + if m2 := MergeIncomingDeferArgs(m); m2 != m { + t.Fatalf("MergeIncomingDeferArgs not idempotent: %q vs %q", m2, m) + } + if s := StripIncomingDeferArgs(m + " -incoming=defer"); s != `-drive "id=x,file=C:/a b/c.img"` { + t.Fatalf("StripIncomingDeferArgs = %q", s) + } +} + +func TestValidateSetRejectsSuspendedVM(t *testing.T) { + issues := ValidateSetLocalized( + SetOpts{Name: "tahoe", CPUs: 6}, + VMDetail{Name: "tahoe", State: "suspended", CPUs: 8, Memory: "8G"}, + host.Report{LogicalCPUs: 16, TotalRAMGB: 32}, + i18n.EnUS, + ) + if len(issues) == 0 || issues[0].Code != "vm_suspended" { + t.Fatalf("expected vm_suspended validation issue, got %+v", issues) + } + if !strings.Contains(strings.ToLower(issues[0].Message), "suspend") { + t.Fatalf("unexpected message: %q", issues[0].Message) + } +} diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 25560a6..edc8c67 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -45,11 +45,14 @@ var catalog = map[Locale]map[string]string{ "cli.usage.cmd_version": " version 查看当前版本", "cli.usage.cmd_vm_compact": " vm compact 停机回收 .qcow2 磁盘未用空间", "cli.usage.cmd_vm_create": " vm create [options] 创建 macOS 虚拟机(可指定目录/核数/内存/硬盘/显卡)", + "cli.usage.cmd_vm_discard_suspend": " vm discard-suspend 放弃已保存的挂起状态并回到关机状态", "cli.usage.cmd_vm_list": " vm list 列出已创建的虚拟机", "cli.usage.cmd_vm_resize": " vm resize <大小> 停机扩容虚拟磁盘(如 256G 或 +64G)", + "cli.usage.cmd_vm_resume": " vm resume 从磁盘挂起状态恢复虚拟机", "cli.usage.cmd_vm_set": " vm set [options] 修改虚拟机配置(下次启动生效)", "cli.usage.cmd_vm_start": " vm start 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动", "cli.usage.cmd_vm_stop": " vm stop|eject 停止 / 弹出安装盘", + "cli.usage.cmd_vm_suspend": " vm suspend 挂起运行中的虚拟机至磁盘(退出后或重启宿主可秒级恢复)", "cli.usage.cmd_vm_type": " vm type [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)", "cli.usage.header": "reims-go - Windows 一站式免编译 reims-vgpu 启动器", "cli.usage.line_cmd": " reims-go [--lang ] [--data-root DIR] <命令> [参数]", @@ -134,6 +137,14 @@ var catalog = map[Locale]map[string]string{ "err.snapshot.qcow2_only": "恢复点仅支持 .qcow2 格式磁盘", "err.snapshot.qemu_img_failed": "恢复点操作未完成({snap})", "err.snapshot.vm_running": "请先停止「{name}」再创建、回滚或删除恢复点", + "err.suspend.action_blocked": "虚拟机「{name}」当前处于挂起状态,请先恢复并关机,或放弃挂起状态后再执行此操作", + "err.suspend.busy": "虚拟机「{name}」正在执行状态切换,请稍后再试", + "err.suspend.discard_running": "虚拟机「{name}」正在运行,无法放弃挂起状态", + "err.suspend.disk_space": "磁盘可用空间不足以保存挂起文件(需要约 {need} GB,当前可用 {avail} GB)", + "err.suspend.incompatible": "虚拟机硬件或运行时版本与挂起时不一致({diffs})。请恢复原配置/运行时,或放弃挂起状态后重新启动", + "err.suspend.not_found": "未找到「{name}」的完整挂起状态文件", + "err.suspend.not_running": "虚拟机「{name}」未在运行,无法挂起", + "err.suspend.unsupported_runtime": "当前激活的便携运行时尚未包含虚拟机挂起/恢复支持,请更新至包含挂起补丁的运行时版本", "err.update_changed": "已下载的更新文件被改动过,请重新下载", "err.update_dev_build": "开发版本不支持应用内更新", "err.update_no_asset": "这个版本没有提供 Windows 程序文件,请到发布页手动下载", @@ -429,35 +440,44 @@ var catalog = map[Locale]map[string]string{ "toastSSHUserSaved": "已保存 SSH 用户名", "toastSaved": "已保存", "toastSavedNextStart": "已保存,下次启动生效", + "tray.menu.discard_suspend": "放弃挂起状态(&X)", "tray.menu.force_stop": "强制关机(&F)", "tray.menu.new_vm": "新建虚拟机(&N)…", "tray.menu.open_in_app": "在 Reims-Go 中查看(&V)", "tray.menu.quit": "退出 Reims-Go(&Q)", "tray.menu.restart": "重启(&R)", + "tray.menu.resume": "恢复(&U)", "tray.menu.screenshot": "复制屏幕截图(&C)", "tray.menu.shared_folder": "打开共享文件夹(&H)", "tray.menu.show": "显示 Reims-Go(&O)", "tray.menu.show_window": "显示窗口(&W)", "tray.menu.start": "启动(&S)", "tray.menu.stop": "关机(&D)", + "tray.menu.suspend": "挂起(&P)", "tray.menu.toggle_fullscreen": "切换全屏", + "tray.notify.discard_suspend_fail": "无法放弃 {name} 的挂起状态", "tray.notify.focus_fail": "找不到 {name} 的窗口", "tray.notify.force_stop_fail": "无法强制关机 {name}", "tray.notify.fullscreen_fail": "无法切换 {name} 全屏", "tray.notify.restart_fail": "无法重启 {name}", + "tray.notify.resume_fail": "无法恢复 {name}", "tray.notify.screenshot_fail": "截图失败:{name}", "tray.notify.screenshot_ok": "已复制屏幕截图", "tray.notify.shared_fail": "无法打开共享文件夹", "tray.notify.start_fail": "无法启动 {name}", "tray.notify.stop_fail": "无法关机 {name}", + "tray.notify.suspend_fail": "无法挂起 {name}", "tray.running": "{count, plural, =1 {Reims-Go — 1 台虚拟机运行中} other {Reims-Go — # 台虚拟机运行中}}", "tray.running.many": "Reims-Go — {count} 台虚拟机运行中", "tray.running.one": "Reims-Go — 1 台虚拟机运行中", "tray.state.broken": "配置损坏", + "tray.state.resuming": "正在恢复…", "tray.state.running": "运行中", "tray.state.starting": "启动中…", "tray.state.stopped": "已停止", "tray.state.stopping": "正在关机…", + "tray.state.suspended": "已挂起", + "tray.state.suspending": "正在挂起…", "tray.state.unknown": "未知", "updateCancel": "取消下载", "updateCapsuleAvailable": "{v} 可用", @@ -498,6 +518,7 @@ var catalog = map[Locale]map[string]string{ "validate.missing_name": "虚拟机名称不能为空", "validate.missing_release": "请选择要离线安装的 macOS 版本", "validate.name_taken": "已存在名为 {name} 的虚拟机", + "validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置", "viewLogs": "查看日志", "vm.already_running": "{name} 已在运行中", "vm.compact.done": "{name}:磁盘已瘦身 {before, number, .2} GB -> {after, number, .2} GB(回收 {saved, number, .2} GB)", @@ -557,11 +578,14 @@ var catalog = map[Locale]map[string]string{ "cli.usage.cmd_version": " version Show current version", "cli.usage.cmd_vm_compact": " vm compact Compact stopped .qcow2 disk to reclaim unused space", "cli.usage.cmd_vm_create": " vm create [options] Create a macOS VM (custom dir, CPUs, RAM, disk size, GPU)", + "cli.usage.cmd_vm_discard_suspend": " vm discard-suspend Discard a saved suspend state and return the VM to powered off", "cli.usage.cmd_vm_list": " vm list List virtual machines", "cli.usage.cmd_vm_resize": " vm resize Expand stopped VM disk (e.g. 256G or +64G)", + "cli.usage.cmd_vm_resume": " vm resume Resume a suspended VM from disk", "cli.usage.cmd_vm_set": " vm set [options] Update VM settings (applies on next start)", "cli.usage.cmd_vm_start": " vm start Start a VM in the Reims-Go window process (launched in the tray if needed),\n with clipboard and shared folders; with --data-root it starts in this process", "cli.usage.cmd_vm_stop": " vm stop|eject Stop / eject installer", + "cli.usage.cmd_vm_suspend": " vm suspend Suspend a running VM to disk for fast resume across restarts", "cli.usage.cmd_vm_type": " vm type [text] Type text into a running VM as US-keyboard keys (stdin if no text)", "cli.usage.header": "reims-go - Portable one-stop reims-vgpu launcher for Windows", "cli.usage.line_cmd": " reims-go [--lang ] [--data-root DIR] [args]", @@ -646,6 +670,14 @@ var catalog = map[Locale]map[string]string{ "err.snapshot.qcow2_only": "Restore points are only supported on .qcow2 disks", "err.snapshot.qemu_img_failed": "Restore point operation could not finish ({snap})", "err.snapshot.vm_running": "Stop “{name}” before creating, restoring or deleting a restore point", + "err.suspend.action_blocked": "VM “{name}” is suspended; resume and shut it down or discard its saved state before doing this", + "err.suspend.busy": "VM “{name}” is busy transitioning; try again in a moment", + "err.suspend.discard_running": "VM “{name}” is currently running; suspend state cannot be discarded", + "err.suspend.disk_space": "Not enough free disk space to save the suspend file (need about {need} GB, {avail} GB available)", + "err.suspend.incompatible": "VM hardware or runtime differs from when it was suspended ({diffs}). Restore the previous configuration/runtime or discard the saved state", + "err.suspend.not_found": "No complete suspend state found for “{name}”", + "err.suspend.not_running": "VM “{name}” is not running and cannot be suspended", + "err.suspend.unsupported_runtime": "The active portable runtime does not support VM suspend/resume; update to a runtime built with suspend support", "err.update_changed": "The downloaded update changed on disk; download it again", "err.update_dev_build": "In-app update is disabled in development builds", "err.update_no_asset": "This release has no Windows executable; download it from the release page", @@ -941,35 +973,44 @@ var catalog = map[Locale]map[string]string{ "toastSSHUserSaved": "Saved SSH username", "toastSaved": "Saved", "toastSavedNextStart": "Saved — applies on next start", + "tray.menu.discard_suspend": "Discard Saved Stat&e", "tray.menu.force_stop": "&Force Shut Down", "tray.menu.new_vm": "&New Virtual Machine…", "tray.menu.open_in_app": "Show in &Reims-Go", "tray.menu.quit": "&Quit Reims-Go", "tray.menu.restart": "&Restart", + "tray.menu.resume": "Res&ume", "tray.menu.screenshot": "&Copy Screenshot", "tray.menu.shared_folder": "Open S&hared Folder", "tray.menu.show": "&Show Reims-Go", "tray.menu.show_window": "Show &Window", "tray.menu.start": "&Start", "tray.menu.stop": "Shut &Down", + "tray.menu.suspend": "Sus&pend", "tray.menu.toggle_fullscreen": "Toggle full screen", + "tray.notify.discard_suspend_fail": "Couldn't discard saved state for {name}", "tray.notify.focus_fail": "Couldn't find the window of {name}", "tray.notify.force_stop_fail": "Couldn't force shut down {name}", "tray.notify.fullscreen_fail": "Couldn’t toggle full screen for {name}", "tray.notify.restart_fail": "Couldn't restart {name}", + "tray.notify.resume_fail": "Couldn't resume {name}", "tray.notify.screenshot_fail": "Screenshot failed: {name}", "tray.notify.screenshot_ok": "Screenshot copied", "tray.notify.shared_fail": "Couldn't open the shared folder", "tray.notify.start_fail": "Couldn't start {name}", "tray.notify.stop_fail": "Couldn't shut down {name}", + "tray.notify.suspend_fail": "Couldn't suspend {name}", "tray.running": "{count, plural, one {Reims-Go — # VM running} other {Reims-Go — # VMs running}}", "tray.running.many": "Reims-Go — {count} VMs running", "tray.running.one": "Reims-Go — 1 VM running", "tray.state.broken": "Broken", + "tray.state.resuming": "Resuming…", "tray.state.running": "Running", "tray.state.starting": "Starting…", "tray.state.stopped": "Stopped", "tray.state.stopping": "Shutting down…", + "tray.state.suspended": "Suspended", + "tray.state.suspending": "Suspending…", "tray.state.unknown": "Unknown", "updateCancel": "Cancel download", "updateCapsuleAvailable": "{v} available", @@ -1010,6 +1051,7 @@ var catalog = map[Locale]map[string]string{ "validate.missing_name": "VM name is required", "validate.missing_release": "Choose the macOS release to install offline", "validate.name_taken": "A VM named {name} already exists", + "validate.vm_suspended": "Resume or discard the VM's suspended state before changing its settings", "viewLogs": "View logs", "vm.already_running": "{name} is already running", "vm.compact.done": "{name}: compacted disk {before, number, .2} GB -> {after, number, .2} GB (reclaimed {saved, number, .2} GB)", @@ -1074,6 +1116,13 @@ var paramOrder = map[string][]string{ "err.plugin.system_locked": {"id"}, "err.snapshot.qemu_img_failed": {"snap"}, "err.snapshot.vm_running": {"name"}, + "err.suspend.action_blocked": {"name"}, + "err.suspend.busy": {"name"}, + "err.suspend.discard_running": {"name"}, + "err.suspend.disk_space": {"need", "avail"}, + "err.suspend.incompatible": {"diffs"}, + "err.suspend.not_found": {"name"}, + "err.suspend.not_running": {"name"}, "err.update_not_writable": {"dir"}, "err.vm_not_running": {"name"}, "err.vm_window_not_found": {"name"}, @@ -1145,13 +1194,16 @@ var paramOrder = map[string][]string{ "toastInstallerReady": {"v"}, "toastRuntimeReady": {"v"}, "toastSSHConfigWritten": {"alias"}, + "tray.notify.discard_suspend_fail": {"name"}, "tray.notify.focus_fail": {"name"}, "tray.notify.force_stop_fail": {"name"}, "tray.notify.fullscreen_fail": {"name"}, "tray.notify.restart_fail": {"name"}, + "tray.notify.resume_fail": {"name"}, "tray.notify.screenshot_fail": {"name"}, "tray.notify.start_fail": {"name"}, "tray.notify.stop_fail": {"name"}, + "tray.notify.suspend_fail": {"name"}, "tray.running": {"count"}, "tray.running.many": {"count"}, "updateCapsuleAvailable": {"v"}, diff --git a/internal/qmp/client.go b/internal/qmp/client.go index f593836..bc7ba3b 100644 --- a/internal/qmp/client.go +++ b/internal/qmp/client.go @@ -52,8 +52,15 @@ type qmpReply struct { Event string `json:"event"` } -// Query runs one command and waits for its JSON return value, skipping async events. +// Query runs one command with the default 5-second timeout and waits for its +// JSON return value, skipping async events. func (c *Conn) Query(command string, args any) (json.RawMessage, error) { + return c.QueryWithTimeout(command, args, 5*time.Second) +} + +// QueryWithTimeout runs one command and waits up to timeout for its JSON return +// value, skipping async events. +func (c *Conn) QueryWithTimeout(command string, args any, timeout time.Duration) (json.RawMessage, error) { req := map[string]any{"execute": command} if args != nil { req["arguments"] = args @@ -62,7 +69,10 @@ func (c *Conn) Query(command string, args any) (json.RawMessage, error) { if err != nil { return nil, err } - _ = c.nc.SetDeadline(time.Now().Add(5 * time.Second)) + if timeout <= 0 { + timeout = 5 * time.Second + } + _ = c.nc.SetDeadline(time.Now().Add(timeout)) if _, err := c.nc.Write(append(b, '\n')); err != nil { return nil, fmt.Errorf("QMP %s: %w", command, err) } @@ -84,8 +94,16 @@ func (c *Conn) Query(command string, args any) (json.RawMessage, error) { return nil, fmt.Errorf("QMP %s: connection closed", command) } -// Execute runs one command and waits for its reply, skipping async events. +// Execute runs one command with the default timeout and waits for its reply, +// skipping async events. func (c *Conn) Execute(command string, args any) error { _, err := c.Query(command, args) return err } + +// ExecuteWithTimeout runs one command and waits up to timeout for its reply, +// skipping async events. +func (c *Conn) ExecuteWithTimeout(command string, args any, timeout time.Duration) error { + _, err := c.QueryWithTimeout(command, args, timeout) + return err +} diff --git a/internal/qmp/migrate.go b/internal/qmp/migrate.go new file mode 100644 index 0000000..effe1d1 --- /dev/null +++ b/internal/qmp/migrate.go @@ -0,0 +1,275 @@ +package qmp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "strings" + "time" +) + +const ( + // DefaultMultifdChannels is the parallel I/O channel count used for + // mapped-ram file snapshots on Windows. + DefaultMultifdChannels = 4 + + migratePollInterval = 200 * time.Millisecond + migrateCmdTimeout = 2 * time.Minute + migrateTotalTimeout = 15 * time.Minute +) + +// MigrateProgress carries the latest snapshot save/load progress from QMP +// `query-migrate`. +type MigrateProgress struct { + Status string `json:"status"` + Transferred int64 `json:"transferred"` + Remaining int64 `json:"remaining"` + Total int64 `json:"total"` + TotalTimeMs int64 `json:"total_time_ms"` +} + +type migrateInfo struct { + Status string `json:"status"` + ErrorDesc string `json:"error-desc"` + TotalTimeMs int64 `json:"total-time"` + RAM *struct { + Transferred int64 `json:"transferred"` + Remaining int64 `json:"remaining"` + Total int64 `json:"total"` + } `json:"ram"` +} + +type vmStatusReply struct { + Running bool `json:"running"` + Status string `json:"status"` +} + +// SuspendToFile pauses a running Intel VM via QMP, writes a mapped-ram + +// multifd file snapshot to vmstatePath, waits for completion, and shuts down +// QEMU cleanly via `quit`. +// +// If migration fails before reaching completion while the VM is merely paused +// (not postmigrate), SuspendToFile attempts to resume the guest with `cont` so +// the running VM is not left frozen. +func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress)) error { + c, err := Dial(ctx, "unix", SocketPath(vmDir)) + if err != nil { + return err + } + defer c.Close() + return suspendToFileConn(ctx, c, vmstatePath, onProgress) +} + +func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error { + if err := c.ExecuteWithTimeout("stop", nil, 30*time.Second); err != nil { + return fmt.Errorf("pause VM before suspend: %w", err) + } + st, err := queryVMStatus(c) + if err != nil { + tryResumePaused(c) + return fmt.Errorf("verify paused state: %w", err) + } + if st.Running { + return fmt.Errorf("VM remained running after stop (status=%s)", st.Status) + } + + if err := configureMappedRAM(c); err != nil { + tryResumePaused(c) + return err + } + + args := map[string]any{ + "channels": fileChannels(vmstatePath), + } + if err := c.ExecuteWithTimeout("migrate", args, migrateCmdTimeout); err != nil { + tryResumePaused(c) + return fmt.Errorf("start snapshot save: %w", err) + } + + if err := waitMigrateDone(ctx, c, onProgress); err != nil { + tryResumePaused(c) + return fmt.Errorf("save snapshot: %w", err) + } + + // Migration completed (RUN_STATE_POSTMIGRATE): never send `cont` here; + // exit QEMU cleanly so the disk and WHPX partition close. + if err := c.ExecuteWithTimeout("quit", nil, 15*time.Second); err != nil { + // QEMU may close the QMP socket immediately upon receiving `quit`. + if !isConnClosedErr(err) { + return fmt.Errorf("quit QEMU after suspend: %w", err) + } + } + return nil +} + +// ResumeFromFile connects to a QEMU process started with `-incoming defer`, +// loads the mapped-ram + multifd file snapshot from vmstatePath, waits for +// completion, and resumes execution with `cont`. +// +// On any error, vmstatePath is left untouched so the caller can retry. +func ResumeFromFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress)) error { + c, err := dialMigrateConnWithRetry(ctx, "unix", SocketPath(vmDir), 10*time.Second) + if err != nil { + return err + } + defer c.Close() + return resumeFromFileConn(ctx, c, vmstatePath, onProgress) +} + +func resumeFromFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error { + if err := configureMappedRAM(c); err != nil { + return err + } + args := map[string]any{ + "channels": fileChannels(vmstatePath), + "exit-on-error": false, + } + if err := c.ExecuteWithTimeout("migrate-incoming", args, migrateCmdTimeout); err != nil { + return fmt.Errorf("start snapshot restore: %w", err) + } + if err := waitMigrateDone(ctx, c, onProgress); err != nil { + return fmt.Errorf("restore snapshot: %w", err) + } + if err := c.ExecuteWithTimeout("cont", nil, 30*time.Second); err != nil { + return fmt.Errorf("resume VM execution after restore: %w", err) + } + return nil +} + +// QuitVM sends QMP `quit` to the VM's QMP socket (best-effort cleanup for a +// failed incoming-resume QEMU process). +func QuitVM(ctx context.Context, vmDir string) error { + c, err := Dial(ctx, "unix", SocketPath(vmDir)) + if err != nil { + return err + } + defer c.Close() + if err := c.ExecuteWithTimeout("quit", nil, 10*time.Second); err != nil && !isConnClosedErr(err) { + return err + } + return nil +} + +func configureMappedRAM(c *Conn) error { + caps := map[string]any{ + "capabilities": []map[string]any{ + {"capability": "mapped-ram", "state": true}, + {"capability": "multifd", "state": true}, + }, + } + if err := c.ExecuteWithTimeout("migrate-set-capabilities", caps, 15*time.Second); err != nil { + return fmt.Errorf("enable mapped-ram/multifd capabilities: %w", err) + } + params := map[string]any{ + "multifd-channels": DefaultMultifdChannels, + } + if err := c.ExecuteWithTimeout("migrate-set-parameters", params, 15*time.Second); err != nil { + return fmt.Errorf("set multifd-channels: %w", err) + } + return nil +} + +func fileChannels(vmstatePath string) []map[string]any { + return []map[string]any{ + { + "channel-type": "main", + "addr": map[string]any{ + "transport": "file", + "filename": filepath.Clean(vmstatePath), + "offset": 0, + }, + }, + } +} + +func queryVMStatus(c *Conn) (vmStatusReply, error) { + raw, err := c.QueryWithTimeout("query-status", nil, 15*time.Second) + if err != nil { + return vmStatusReply{}, err + } + var st vmStatusReply + if err := json.Unmarshal(raw, &st); err != nil { + return vmStatusReply{}, fmt.Errorf("parse query-status: %w", err) + } + return st, nil +} + +func tryResumePaused(c *Conn) { + st, err := queryVMStatus(c) + if err != nil || st.Running { + return + } + // Only resume when QEMU is still in ordinary paused state (never postmigrate). + if st.Status == "paused" { + _ = c.ExecuteWithTimeout("cont", nil, 10*time.Second) + } +} + +func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgress)) error { + deadline := time.Now().Add(migrateTotalTimeout) + for { + if err := ctx.Err(); err != nil { + return err + } + if time.Now().After(deadline) { + return errors.New("timed out waiting for migration to finish") + } + raw, err := c.QueryWithTimeout("query-migrate", nil, migrateCmdTimeout) + if err != nil { + return err + } + var info migrateInfo + if err := json.Unmarshal(raw, &info); err != nil { + return fmt.Errorf("parse query-migrate: %w", err) + } + prog := MigrateProgress{ + Status: info.Status, + TotalTimeMs: info.TotalTimeMs, + } + if info.RAM != nil { + prog.Transferred = info.RAM.Transferred + prog.Remaining = info.RAM.Remaining + prog.Total = info.RAM.Total + } + if onProgress != nil { + onProgress(prog) + } + switch info.Status { + case "completed": + return nil + case "failed", "cancelled": + desc := strings.TrimSpace(info.ErrorDesc) + if desc != "" { + return fmt.Errorf("migration %s: %s", info.Status, desc) + } + return fmt.Errorf("migration %s", info.Status) + } + sleep(ctx, migratePollInterval) + } +} + +func dialMigrateConnWithRetry(ctx context.Context, network, addr string, timeout time.Duration) (*Conn, error) { + deadline := time.Now().Add(timeout) + var lastErr error + for { + c, err := Dial(ctx, network, addr) + if err == nil { + return c, nil + } + lastErr = err + if ctx.Err() != nil || time.Now().After(deadline) { + return nil, lastErr + } + sleep(ctx, 100*time.Millisecond) + } +} + +func isConnClosedErr(err error) bool { + if err == nil { + return false + } + s := strings.ToLower(err.Error()) + return strings.Contains(s, "connection closed") || strings.Contains(s, "eof") || strings.Contains(s, "wsarecv") || strings.Contains(s, "broken pipe") +} diff --git a/internal/qmp/migrate_test.go b/internal/qmp/migrate_test.go new file mode 100644 index 0000000..0c863d2 --- /dev/null +++ b/internal/qmp/migrate_test.go @@ -0,0 +1,229 @@ +package qmp + +import ( + "bufio" + "context" + "encoding/json" + "net" + "strings" + "sync" + "testing" +) + +type mockQMPReq struct { + Execute string `json:"execute"` + Arguments json.RawMessage `json:"arguments"` +} + +func startMockQMP(t *testing.T, handle func(req mockQMPReq) (reply map[string]any, closeAfter bool)) (string, func() []mockQMPReq) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen mock QMP: %v", err) + } + t.Cleanup(func() { _ = ln.Close() }) + + var mu sync.Mutex + var recorded []mockQMPReq + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go func(nc net.Conn) { + defer nc.Close() + _, _ = nc.Write([]byte(`{"QMP":{"version":{"qemu":{"major":9,"minor":2,"micro":0}},"capabilities":[]}}` + "\n")) + sc := bufio.NewScanner(nc) + for sc.Scan() { + var req mockQMPReq + if err := json.Unmarshal(sc.Bytes(), &req); err != nil { + return + } + if req.Execute == "qmp_capabilities" { + _, _ = nc.Write([]byte(`{"return":{}}` + "\n")) + continue + } + mu.Lock() + recorded = append(recorded, req) + mu.Unlock() + reply, closeAfter := handle(req) + if reply != nil { + b, _ := json.Marshal(reply) + _, _ = nc.Write(append(b, '\n')) + } + if closeAfter { + return + } + } + }(conn) + } + }() + return ln.Addr().String(), func() []mockQMPReq { + mu.Lock() + defer mu.Unlock() + return append([]mockQMPReq(nil), recorded...) + } +} + +func TestSuspendToFileHappyPath(t *testing.T) { + polls := 0 + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "stop", "migrate-set-capabilities", "migrate-set-parameters", "migrate": + return map[string]any{"return": map[string]any{}}, false + case "query-status": + return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false + case "query-migrate": + polls++ + if polls == 1 { + return map[string]any{"return": map[string]any{ + "status": "active", + "ram": map[string]any{"transferred": 1024, "remaining": 1024, "total": 2048}, + }}, false + } + return map[string]any{"return": map[string]any{ + "status": "completed", + "total-time": 4500, + "ram": map[string]any{"transferred": 2048, "remaining": 0, "total": 2048}, + }}, false + case "quit": + return map[string]any{"return": map[string]any{}}, true + default: + t.Errorf("unexpected QMP command: %s", req.Execute) + return map[string]any{"return": map[string]any{}}, false + } + }) + + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("Dial: %v", err) + } + defer c.Close() + + var progress []MigrateProgress + if err := suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, func(p MigrateProgress) { + progress = append(progress, p) + }); err != nil { + t.Fatalf("suspendToFileConn: %v", err) + } + if len(progress) != 2 || progress[1].Status != "completed" { + t.Fatalf("unexpected progress: %+v", progress) + } + got := cmds() + var names []string + for _, r := range got { + names = append(names, r.Execute) + } + want := "stop,query-status,migrate-set-capabilities,migrate-set-parameters,migrate,query-migrate,query-migrate,quit" + if strings.Join(names, ",") != want { + t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want) + } +} + +func TestSuspendToFileFailureResumesPausedVM(t *testing.T) { + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "stop", "migrate-set-capabilities", "migrate-set-parameters", "cont": + return map[string]any{"return": map[string]any{}}, false + case "query-status": + return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false + case "migrate": + return map[string]any{"error": map[string]any{"class": "GenericError", "desc": "disk full"}}, false + default: + return map[string]any{"return": map[string]any{}}, false + } + }) + + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("Dial: %v", err) + } + defer c.Close() + + err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil) + if err == nil || !strings.Contains(err.Error(), "disk full") { + t.Fatalf("expected disk full error, got %v", err) + } + var sawCont bool + for _, r := range cmds() { + if r.Execute == "cont" { + sawCont = true + } + if r.Execute == "quit" { + t.Fatal("must not quit QEMU when migrate fails") + } + } + if !sawCont { + t.Fatal("expected cont rollback when migrate fails while paused") + } +} + +func TestResumeFromFileHappyPath(t *testing.T) { + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "migrate-set-capabilities", "migrate-set-parameters", "migrate-incoming", "cont": + return map[string]any{"return": map[string]any{}}, false + case "query-migrate": + return map[string]any{"return": map[string]any{"status": "completed", "total-time": 1900}}, false + default: + t.Errorf("unexpected QMP command: %s", req.Execute) + return map[string]any{"return": map[string]any{}}, false + } + }) + + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("Dial: %v", err) + } + defer c.Close() + + if err := resumeFromFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil); err != nil { + t.Fatalf("resumeFromFileConn: %v", err) + } + got := cmds() + var names []string + var sawExitOnErrorFalse bool + for _, r := range got { + names = append(names, r.Execute) + if r.Execute == "migrate-incoming" && strings.Contains(string(r.Arguments), `"exit-on-error":false`) { + sawExitOnErrorFalse = true + } + } + want := "migrate-set-capabilities,migrate-set-parameters,migrate-incoming,query-migrate,cont" + if strings.Join(names, ",") != want { + t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want) + } + if !sawExitOnErrorFalse { + t.Fatal("expected migrate-incoming to pass exit-on-error:false") + } +} + +func TestResumeFromFileFailedDoesNotCont(t *testing.T) { + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "migrate-set-capabilities", "migrate-set-parameters", "migrate-incoming": + return map[string]any{"return": map[string]any{}}, false + case "query-migrate": + return map[string]any{"return": map[string]any{"status": "failed", "error-desc": "corrupt RVGSNAP1 snapshot"}}, false + default: + return map[string]any{"return": map[string]any{}}, false + } + }) + + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("Dial: %v", err) + } + defer c.Close() + + err = resumeFromFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil) + if err == nil || !strings.Contains(err.Error(), "corrupt RVGSNAP1 snapshot") { + t.Fatalf("expected corrupt snapshot error, got %v", err) + } + for _, r := range cmds() { + if r.Execute == "cont" { + t.Fatal("must not issue cont when restore failed") + } + } +} diff --git a/internal/runtime/kinds.go b/internal/runtime/kinds.go index 97eeeb7..cf09333 100644 --- a/internal/runtime/kinds.go +++ b/internal/runtime/kinds.go @@ -152,6 +152,7 @@ func (m Manifest) EffectiveCapabilities() []string { for _, c := range m.Capabilities { add(c) } + var hasWin32MappedRAM, hasIntelWHPXSuspend, hasVGPUSnapshotReplay bool for _, p := range m.Patches { low := strings.ToLower(p.Name) switch { @@ -169,8 +170,17 @@ func (m Manifest) EffectiveCapabilities() []string { } case strings.Contains(low, "display-fixed-mode"): add("display-fixed-mode") + case strings.Contains(low, "win32-mapped-ram-io"): + hasWin32MappedRAM = true + case strings.Contains(low, "intel-whpx-suspend"): + hasIntelWHPXSuspend = true + case strings.Contains(low, "reims-vgpu-snapshot-replay"): + hasVGPUSnapshotReplay = true } } + if hasWin32MappedRAM && hasIntelWHPXSuspend && hasVGPUSnapshotReplay { + add("vm-suspend") + } return out } diff --git a/internal/runtime/kinds_test.go b/internal/runtime/kinds_test.go index 9e5bffd..2f2422b 100644 --- a/internal/runtime/kinds_test.go +++ b/internal/runtime/kinds_test.go @@ -85,6 +85,41 @@ func TestKindRegistryAndCapabilities(t *testing.T) { t.Fatalf("%s: HasCapability(win32-unicode-input) = %v, want %v", tc.name, got, tc.want) } } + + // vm-suspend requires all three runtime pieces (Win32 mapped-ram I/O, Intel WHPX suspend, + // and vGPU snapshot replay) unless explicitly declared in Capabilities. + for _, tc := range []struct { + name string + m Manifest + want bool + }{ + { + name: "partial-suspend-patches", + m: Manifest{Patches: []Patch{ + {Name: "qemu-win32-mapped-ram-io.patch"}, + {Name: "qemu-intel-whpx-suspend.patch"}, + }}, + want: false, + }, + { + name: "all-suspend-patches", + m: Manifest{Patches: []Patch{ + {Name: "qemu-win32-mapped-ram-io.patch"}, + {Name: "qemu-intel-whpx-suspend.patch"}, + {Name: "reims-vgpu-snapshot-replay.patch"}, + }}, + want: true, + }, + { + name: "explicit-vm-suspend-capability", + m: Manifest{Capabilities: []string{"vm-suspend"}}, + want: true, + }, + } { + if got := tc.m.HasCapability("vm-suspend"); got != tc.want { + t.Fatalf("%s: HasCapability(vm-suspend) = %v, want %v", tc.name, got, tc.want) + } + } } func TestMultiKindCoexistenceAndCompatibility(t *testing.T) { diff --git a/internal/tray/tray.go b/internal/tray/tray.go index a13a046..4523320 100644 --- a/internal/tray/tray.go +++ b/internal/tray/tray.go @@ -25,9 +25,10 @@ func (v VMItem) title() string { // Snapshot holds the live state read each time the user opens the tray menu. type Snapshot struct { - Locale i18n.Locale - LocaleZh bool // legacy fallback when Locale is empty - VMs []VMItem + Locale i18n.Locale + LocaleZh bool // legacy fallback when Locale is empty + CanSuspend bool + VMs []VMItem } // Action is a per-VM command picked from the tray menu. @@ -43,6 +44,9 @@ const ( ActSharedFolder ActOpenInApp ActToggleFullscreen + ActSuspend + ActResume + ActDiscardSuspend ) // Callbacks wires tray actions back into the Wails application. Each runs @@ -72,6 +76,7 @@ const ( dotNone dotKind = iota dotRunning dotStopped + dotSuspended dotBusy dotBroken ) @@ -91,8 +96,11 @@ type menuEntry struct { type texts struct { show, newVM, quit string start, stop, forceStop, restart, showWindow, shot string + suspend, resume, discardSuspend string shared, openInApp string - running, stopped, starting, stopping, broken, unknown string + running, stopped, suspended string + starting, stopping, suspending, resuming string + broken, unknown string toggleFullscreen string } @@ -107,23 +115,29 @@ func menuTexts(snap Snapshot) texts { } } return texts{ - show: i18n.T(loc, "tray.menu.show"), - newVM: i18n.T(loc, "tray.menu.new_vm"), - quit: i18n.T(loc, "tray.menu.quit"), - start: i18n.T(loc, "tray.menu.start"), - stop: i18n.T(loc, "tray.menu.stop"), - forceStop: i18n.T(loc, "tray.menu.force_stop"), - restart: i18n.T(loc, "tray.menu.restart"), - showWindow: i18n.T(loc, "tray.menu.show_window"), - shot: i18n.T(loc, "tray.menu.screenshot"), - shared: i18n.T(loc, "tray.menu.shared_folder"), - openInApp: i18n.T(loc, "tray.menu.open_in_app"), - running: i18n.T(loc, "tray.state.running"), - stopped: i18n.T(loc, "tray.state.stopped"), - starting: i18n.T(loc, "tray.state.starting"), - stopping: i18n.T(loc, "tray.state.stopping"), - broken: i18n.T(loc, "tray.state.broken"), - unknown: i18n.T(loc, "tray.state.unknown"), + show: i18n.T(loc, "tray.menu.show"), + newVM: i18n.T(loc, "tray.menu.new_vm"), + quit: i18n.T(loc, "tray.menu.quit"), + start: i18n.T(loc, "tray.menu.start"), + stop: i18n.T(loc, "tray.menu.stop"), + forceStop: i18n.T(loc, "tray.menu.force_stop"), + restart: i18n.T(loc, "tray.menu.restart"), + suspend: i18n.T(loc, "tray.menu.suspend"), + resume: i18n.T(loc, "tray.menu.resume"), + discardSuspend: i18n.T(loc, "tray.menu.discard_suspend"), + showWindow: i18n.T(loc, "tray.menu.show_window"), + shot: i18n.T(loc, "tray.menu.screenshot"), + shared: i18n.T(loc, "tray.menu.shared_folder"), + openInApp: i18n.T(loc, "tray.menu.open_in_app"), + running: i18n.T(loc, "tray.state.running"), + stopped: i18n.T(loc, "tray.state.stopped"), + suspended: i18n.T(loc, "tray.state.suspended"), + starting: i18n.T(loc, "tray.state.starting"), + stopping: i18n.T(loc, "tray.state.stopping"), + suspending: i18n.T(loc, "tray.state.suspending"), + resuming: i18n.T(loc, "tray.state.resuming"), + broken: i18n.T(loc, "tray.state.broken"), + unknown: i18n.T(loc, "tray.state.unknown"), toggleFullscreen: i18n.T(loc, "tray.menu.toggle_fullscreen"), } @@ -138,7 +152,7 @@ func decodeVMCmd(id int) (int, Action, bool) { } off := id - cmdVMBase act := Action(off % vmSlot) - if act < ActStart || act > ActToggleFullscreen { + if act < ActStart || act > ActDiscardSuspend { return 0, 0, false } return off / vmSlot, act, true @@ -174,13 +188,34 @@ func buildMenu(snap Snapshot) []menuEntry { sub = []menuEntry{ show, cmd(ActToggleFullscreen, t.toggleFullscreen), cmd(ActScreenshot, t.shot), cmd(ActSharedFolder, t.shared), sep, + } + if snap.CanSuspend { + sub = append(sub, cmd(ActSuspend, t.suspend)) + } + sub = append(sub, cmd(ActRestart, t.restart), cmd(ActStop, t.stop), cmd(ActForceStop, t.forceStop), sep, cmd(ActOpenInApp, t.openInApp), + ) + case "suspended": + dot, state = dotSuspended, t.suspended + resume := cmd(ActResume, t.resume) + resume.Default = true + sub = []menuEntry{ + resume, cmd(ActDiscardSuspend, t.discardSuspend), sep, + cmd(ActSharedFolder, t.shared), sep, + cmd(ActOpenInApp, t.openInApp), } - case "starting", "stopping": - dot, state = dotBusy, t.starting - if vm.State == "stopping" { + case "starting", "stopping", "suspending", "resuming": + dot = dotBusy + switch vm.State { + case "stopping": state = t.stopping + case "suspending": + state = t.suspending + case "resuming": + state = t.resuming + default: + state = t.starting } sub = []menuEntry{cmd(ActForceStop, t.forceStop), sep, cmd(ActOpenInApp, t.openInApp)} case "broken": @@ -209,6 +244,8 @@ func dotPixels(size int, kind dotKind) []byte { switch kind { case dotRunning: r, g, b = 0x30, 0xD1, 0x58 + case dotSuspended: + r, g, b = 0xFF, 0x9F, 0x0A case dotBusy: r, g, b = 0xFF, 0x9F, 0x0A case dotBroken: @@ -219,12 +256,49 @@ func dotPixels(size int, kind dotKind) []byte { return px } c := float64(size) / 2 + const ss = 4 // 4×4 supersampling for smooth edges + if kind == dotSuspended { + halfH := float64(size) * 0.28 + barW := maxf(1.8, float64(size)*0.15) + gap := maxf(1.2, float64(size)*0.12) + for y := 0; y < size; y++ { + for x := 0; x < size; x++ { + hits := 0 + for sy := 0; sy < ss; sy++ { + for sx := 0; sx < ss; sx++ { + dx := float64(x) + (float64(sx)+0.5)/ss - c + dy := float64(y) + (float64(sy)+0.5)/ss - c + adx := dx + if adx < 0 { + adx = -adx + } + ady := dy + if ady < 0 { + ady = -ady + } + if ady <= halfH && adx >= gap/2 && adx <= gap/2+barW { + hits++ + } + } + } + if hits == 0 { + continue + } + a := hits * 255 / (ss * ss) + off := (y*size + x) * 4 + px[off+0] = uint8(int(b) * a / 255) + px[off+1] = uint8(int(g) * a / 255) + px[off+2] = uint8(int(r) * a / 255) + px[off+3] = uint8(a) + } + } + return px + } outer := float64(size) * 0.28 // dot diameter ≈ 56% of the check-mark cell inner := 0.0 if kind == dotStopped { inner = outer - maxf(1.4, float64(size)*0.09) } - const ss = 4 // 4×4 supersampling for smooth edges for y := 0; y < size; y++ { for x := 0; x < size; x++ { hits := 0 diff --git a/internal/tray/tray_test.go b/internal/tray/tray_test.go index 7365594..ced0237 100644 --- a/internal/tray/tray_test.go +++ b/internal/tray/tray_test.go @@ -18,10 +18,11 @@ func findEntry(entries []menuEntry, label string) *menuEntry { } func TestBuildMenuPerState(t *testing.T) { - menu := buildMenu(Snapshot{LocaleZh: true, VMs: []VMItem{ + menu := buildMenu(Snapshot{LocaleZh: true, CanSuspend: true, VMs: []VMItem{ {Name: "macos-tahoe", Label: "日常", State: "running"}, {Name: "macos-dev", State: "stopped"}, {Name: "macos-busy", State: "starting"}, + {Name: "macos-sleep", State: "suspended"}, }}) if !menu[0].Default || menu[0].ID != cmdShow { t.Fatalf("first item should be the default Show, got %+v", menu[0]) @@ -40,6 +41,15 @@ func TestBuildMenuPerState(t *testing.T) { if len(run.Sub) < 2 || run.Sub[1].ID != vmCmd(0, ActToggleFullscreen) || run.Sub[1].Label != "切换全屏" || run.Sub[1].Default { t.Fatalf("running VM should offer Toggle Fullscreen after Show Window: %+v", run.Sub) } + var hasSuspend bool + for _, e := range run.Sub { + if e.ID == vmCmd(0, ActSuspend) { + hasSuspend = true + } + } + if !hasSuspend { + t.Fatalf("running VM with CanSuspend should offer Suspend: %+v", run.Sub) + } stop := findEntry(menu, "macos-dev\t已停止") if stop == nil || stop.Dot != dotStopped || stop.Sub[0].ID != vmCmd(1, ActStart) || !stop.Sub[0].Default { @@ -55,18 +65,23 @@ func TestBuildMenuPerState(t *testing.T) { if busy == nil || busy.Dot != dotBusy || busy.Sub[0].ID != vmCmd(2, ActForceStop) { t.Fatalf("starting VM should only offer force stop first: %+v", busy) } + + susp := findEntry(menu, "macos-sleep\t已挂起") + if susp == nil || susp.Dot != dotSuspended || susp.Sub[0].ID != vmCmd(3, ActResume) || !susp.Sub[0].Default { + t.Fatalf("suspended VM should default to Resume: %+v", susp) + } } func TestDecodeVMCmdRoundTrip(t *testing.T) { for i := 0; i < maxTrayVMs; i++ { - for act := ActStart; act <= ActToggleFullscreen; act++ { + for act := ActStart; act <= ActDiscardSuspend; act++ { gi, ga, ok := decodeVMCmd(vmCmd(i, act)) if !ok || gi != i || ga != act { t.Fatalf("vmCmd(%d,%d) decoded to (%d,%d,%v)", i, act, gi, ga, ok) } } } - for _, id := range []int{cmdShow, cmdQuit, cmdNewVM, cmdVMBase, vmCmd(0, ActToggleFullscreen+1), cmdVMBase + maxTrayVMs*vmSlot} { + for _, id := range []int{cmdShow, cmdQuit, cmdNewVM, cmdVMBase, vmCmd(0, ActDiscardSuspend+1), cmdVMBase + maxTrayVMs*vmSlot} { if _, _, ok := decodeVMCmd(id); ok { t.Fatalf("id %d should not decode as a VM command", id) } @@ -84,9 +99,15 @@ func TestDotPixels(t *testing.T) { if alpha(ring, size/2, size/2) != 0 { t.Fatal("stopped dot should be a ring with a clear centre") } - for i := 0; i < len(run); i += 4 { - if run[i] > run[i+3] || run[i+1] > run[i+3] || run[i+2] > run[i+3] { - t.Fatal("pixels must be premultiplied (colour ≤ alpha)") + paused := dotPixels(size, dotSuspended) + if alpha(paused, 0, 0) != 0 || alpha(paused, size/2-2, size/2) == 0 || alpha(paused, size/2+2, size/2) == 0 { + t.Fatal("suspended mark should draw two visible vertical pause bars") + } + for _, buf := range [][]byte{run, paused} { + for i := 0; i < len(buf); i += 4 { + if buf[i] > buf[i+3] || buf[i+1] > buf[i+3] || buf[i+2] > buf[i+3] { + t.Fatal("pixels must be premultiplied (colour ≤ alpha)") + } } } } diff --git a/internal/vmstart/vmstart.go b/internal/vmstart/vmstart.go index 6f85da2..6250d60 100644 --- a/internal/vmstart/vmstart.go +++ b/internal/vmstart/vmstart.go @@ -147,6 +147,11 @@ func waitForCommitMemory( // language preset and the WHPX nested-virtualization fallback. cur is updated // to match what was written through `reims-ctl set`. func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) { + if stripped := reims.StripIncomingDeferArgs(cur.ExtraArgs); stripped != cur.ExtraArgs { + if err := p.setExtraArgs(ctx, name, stripped); err == nil { + cur.ExtraArgs = stripped + } + } p.syncOfflineHelper(ctx, name, cur) p.syncRecoveryBootPicker(ctx, name, cur) p.ReplayGuestLang(ctx, cur.Directory) diff --git a/locales/en-US/native.json b/locales/en-US/native.json index a39e657..0b80880 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -407,6 +407,9 @@ "tray.menu.new_vm": "&New Virtual Machine…", "tray.menu.quit": "&Quit Reims-Go", "tray.menu.start": "&Start", + "tray.menu.suspend": "Sus&pend", + "tray.menu.resume": "Res&ume", + "tray.menu.discard_suspend": "Discard Saved Stat&e", "tray.menu.stop": "Shut &Down", "tray.menu.force_stop": "&Force Shut Down", "tray.menu.restart": "&Restart", @@ -417,8 +420,11 @@ "tray.menu.open_in_app": "Show in &Reims-Go", "tray.state.running": "Running", "tray.state.stopped": "Stopped", + "tray.state.suspended": "Suspended", "tray.state.starting": "Starting…", "tray.state.stopping": "Shutting down…", + "tray.state.suspending": "Suspending…", + "tray.state.resuming": "Resuming…", "tray.state.broken": "Broken", "tray.state.unknown": "Unknown", "tray.notify.start_fail": { @@ -427,6 +433,24 @@ "name" ] }, + "tray.notify.suspend_fail": { + "message": "Couldn't suspend {name}", + "$params": [ + "name" + ] + }, + "tray.notify.resume_fail": { + "message": "Couldn't resume {name}", + "$params": [ + "name" + ] + }, + "tray.notify.discard_suspend_fail": { + "message": "Couldn't discard saved state for {name}", + "$params": [ + "name" + ] + }, "tray.notify.stop_fail": { "message": "Couldn't shut down {name}", "$params": [ @@ -820,6 +844,9 @@ "cli.usage.cmd_vm_compact": " vm compact Compact stopped .qcow2 disk to reclaim unused space", "cli.usage.cmd_vm_start": " vm start Start a VM in the Reims-Go window process (launched in the tray if needed),\n with clipboard and shared folders; with --data-root it starts in this process", "cli.usage.cmd_vm_stop": " vm stop|eject Stop / eject installer", + "cli.usage.cmd_vm_suspend": " vm suspend Suspend a running VM to disk for fast resume across restarts", + "cli.usage.cmd_vm_resume": " vm resume Resume a suspended VM from disk", + "cli.usage.cmd_vm_discard_suspend": " vm discard-suspend Discard a saved suspend state and return the VM to powered off", "cli.usage.cmd_vm_type": " vm type [text] Type text into a running VM as US-keyboard keys (stdin if no text)", "cli.usage.cmd_inst_list": " installer list List offline macOS installers Apple offers (needs network)", "cli.usage.cmd_inst_dl": " installer download Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)", @@ -954,6 +981,51 @@ }, "core.start.warn.whpx_irqchip_applied": "Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically", "validate.invalid_guest_lang": "Invalid guest language code (expected format like zh-Hans:0 or en-US:0)", + "validate.vm_suspended": "Resume or discard the VM's suspended state before changing its settings", + "err.suspend.unsupported_runtime": "The active portable runtime does not support VM suspend/resume; update to a runtime built with suspend support", + "err.suspend.busy": { + "message": "VM “{name}” is busy transitioning; try again in a moment", + "$params": [ + "name" + ] + }, + "err.suspend.not_running": { + "message": "VM “{name}” is not running and cannot be suspended", + "$params": [ + "name" + ] + }, + "err.suspend.disk_space": { + "message": "Not enough free disk space to save the suspend file (need about {need} GB, {avail} GB available)", + "$params": [ + "need", + "avail" + ] + }, + "err.suspend.not_found": { + "message": "No complete suspend state found for “{name}”", + "$params": [ + "name" + ] + }, + "err.suspend.incompatible": { + "message": "VM hardware or runtime differs from when it was suspended ({diffs}). Restore the previous configuration/runtime or discard the saved state", + "$params": [ + "diffs" + ] + }, + "err.suspend.discard_running": { + "message": "VM “{name}” is currently running; suspend state cannot be discarded", + "$params": [ + "name" + ] + }, + "err.suspend.action_blocked": { + "message": "VM “{name}” is suspended; resume and shut it down or discard its saved state before doing this", + "$params": [ + "name" + ] + }, "err.dataroot.busy_vms": "Stop all running virtual machines before switching the data folder", "err.dataroot.busy_tasks": "Wait for active download or creation tasks to finish before switching the data folder", "font.script.zh_hant": "Traditional Chinese (繁體中文)", diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index b3b8382..f5bfc2c 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -43,9 +43,28 @@ "fieldVMName": "VM name", "state_running": "Running", "state_stopped": "Stopped", + "state_suspended": "Suspended", "state_starting": "Starting", "state_stopping": "Stopping", + "state_suspending": "Suspending", + "state_resuming": "Resuming", "state_broken": "Error", + "suspend": "Suspend", + "resume": "Resume", + "discardSuspend": "Discard saved state", + "discardSuspendTitle": "Discard saved state for “{name}”?", + "discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.", + "discardSuspendConfirm": "Discard & Power Off", + "suspendedNoticeTitle": "Saved state ready", + "suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.", + "suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.", + "suspendedSettingsHint": "Resume or discard saved state before changing settings", + "toastSuspended": "{name} suspended", + "toastResumed": "{name} resumed", + "toastDiscardSuspend": "Discarded saved state for {name}", + "failSuspend": "Couldn’t suspend", + "failResume": "Couldn’t resume", + "failDiscardSuspend": "Couldn’t discard saved state", "pendingTitle": "Applies on next start", "restartToApply": "Restart to apply", "guideTitle": "Recovery mode", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index ca93bef..b36a181 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -407,6 +407,9 @@ "tray.menu.new_vm": "新建虚拟机(&N)…", "tray.menu.quit": "退出 Reims-Go(&Q)", "tray.menu.start": "启动(&S)", + "tray.menu.suspend": "挂起(&P)", + "tray.menu.resume": "恢复(&U)", + "tray.menu.discard_suspend": "放弃挂起状态(&X)", "tray.menu.stop": "关机(&D)", "tray.menu.force_stop": "强制关机(&F)", "tray.menu.restart": "重启(&R)", @@ -417,8 +420,11 @@ "tray.menu.open_in_app": "在 Reims-Go 中查看(&V)", "tray.state.running": "运行中", "tray.state.stopped": "已停止", + "tray.state.suspended": "已挂起", "tray.state.starting": "启动中…", "tray.state.stopping": "正在关机…", + "tray.state.suspending": "正在挂起…", + "tray.state.resuming": "正在恢复…", "tray.state.broken": "配置损坏", "tray.state.unknown": "未知", "tray.notify.start_fail": { @@ -427,6 +433,24 @@ "name" ] }, + "tray.notify.suspend_fail": { + "message": "无法挂起 {name}", + "$params": [ + "name" + ] + }, + "tray.notify.resume_fail": { + "message": "无法恢复 {name}", + "$params": [ + "name" + ] + }, + "tray.notify.discard_suspend_fail": { + "message": "无法放弃 {name} 的挂起状态", + "$params": [ + "name" + ] + }, "tray.notify.stop_fail": { "message": "无法关机 {name}", "$params": [ @@ -820,6 +844,9 @@ "cli.usage.cmd_vm_compact": " vm compact 停机回收 .qcow2 磁盘未用空间", "cli.usage.cmd_vm_start": " vm start 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动", "cli.usage.cmd_vm_stop": " vm stop|eject 停止 / 弹出安装盘", + "cli.usage.cmd_vm_suspend": " vm suspend 挂起运行中的虚拟机至磁盘(退出后或重启宿主可秒级恢复)", + "cli.usage.cmd_vm_resume": " vm resume 从磁盘挂起状态恢复虚拟机", + "cli.usage.cmd_vm_discard_suspend": " vm discard-suspend 放弃已保存的挂起状态并回到关机状态", "cli.usage.cmd_vm_type": " vm type [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)", "cli.usage.cmd_inst_list": " installer list 列出 Apple 提供的离线安装包版本(需联网)", "cli.usage.cmd_inst_dl": " installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)", @@ -954,6 +981,51 @@ }, "core.start.warn.whpx_irqchip_applied": "宿主拒绝了嵌套虚拟化属性,已自动启用 kernel-irqchip=off 兼容参数", "validate.invalid_guest_lang": "客户机系统语言标识格式无效(如 zh-Hans:0、en-US:0)", + "validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置", + "err.suspend.unsupported_runtime": "当前激活的便携运行时尚未包含虚拟机挂起/恢复支持,请更新至包含挂起补丁的运行时版本", + "err.suspend.busy": { + "message": "虚拟机「{name}」正在执行状态切换,请稍后再试", + "$params": [ + "name" + ] + }, + "err.suspend.not_running": { + "message": "虚拟机「{name}」未在运行,无法挂起", + "$params": [ + "name" + ] + }, + "err.suspend.disk_space": { + "message": "磁盘可用空间不足以保存挂起文件(需要约 {need} GB,当前可用 {avail} GB)", + "$params": [ + "need", + "avail" + ] + }, + "err.suspend.not_found": { + "message": "未找到「{name}」的完整挂起状态文件", + "$params": [ + "name" + ] + }, + "err.suspend.incompatible": { + "message": "虚拟机硬件或运行时版本与挂起时不一致({diffs})。请恢复原配置/运行时,或放弃挂起状态后重新启动", + "$params": [ + "diffs" + ] + }, + "err.suspend.discard_running": { + "message": "虚拟机「{name}」正在运行,无法放弃挂起状态", + "$params": [ + "name" + ] + }, + "err.suspend.action_blocked": { + "message": "虚拟机「{name}」当前处于挂起状态,请先恢复并关机,或放弃挂起状态后再执行此操作", + "$params": [ + "name" + ] + }, "err.dataroot.busy_vms": "仍有虚拟机正在运行,请先全部关机后再切换数据目录", "err.dataroot.busy_tasks": "仍有后台下载或创建任务进行中,请等待任务结束或取消后再切换数据目录", "font.script.zh_hant": "繁体中文(繁體中文)", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index c50d9cf..3a68042 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -43,9 +43,28 @@ "fieldVMName": "虚拟机名称", "state_running": "运行中", "state_stopped": "已停止", + "state_suspended": "已挂起", "state_starting": "启动中", "state_stopping": "停止中", + "state_suspending": "挂起中", + "state_resuming": "恢复中", "state_broken": "出错", + "suspend": "挂起", + "resume": "恢复", + "discardSuspend": "放弃挂起状态", + "discardSuspendTitle": "放弃「{name}」的挂起状态?", + "discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。", + "discardSuspendConfirm": "放弃并关机", + "suspendedNoticeTitle": "已保存运行状态", + "suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", + "suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", + "suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置", + "toastSuspended": "{name} 已挂起", + "toastResumed": "{name} 已恢复", + "toastDiscardSuspend": "已放弃 {name} 的挂起状态", + "failSuspend": "挂起失败", + "failResume": "恢复失败", + "failDiscardSuspend": "放弃挂起状态失败", "pendingTitle": "下次启动生效", "restartToApply": "重启以应用", "guideTitle": "恢复模式",