From d40327e72499a038e140b2053112e03d36517fbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A3=A0=E6=B8=9A=E5=90=AC=E6=BD=AE?= <108173440+reiasu2@users.noreply.github.com> Date: Sat, 5 Dec 2026 11:50:51 +0800 Subject: [PATCH 1/3] fix(input): adapt to runtimes without --capture and clarify modifier key settings --- .../capture-compat-and-input-settings.json | 7 + frontend/scripts/test-keymap.mjs | 61 +++++- frontend/src/App.tsx | 9 +- frontend/src/components/CreateWizard.tsx | 28 ++- frontend/src/components/SettingsModal.tsx | 33 ++- frontend/src/components/VMPage.tsx | 2 +- frontend/src/components/vmSettings/keymap.tsx | 32 +-- frontend/src/i18n/domains/settings.gen.ts | 20 +- frontend/src/i18n/keys.gen.ts | 2 + frontend/src/lib/vmKeymap.ts | 31 +++ frontend/wailsjs/go/models.ts | 4 + internal/app/app.go | 4 + internal/app/create_flow.go | 2 +- internal/app/dataroot_flow_test.go | 68 ++++++ internal/app/macos_settings.go | 11 +- internal/cli/macos_native.go | 2 +- internal/macos/macosdriver/clone.go | 10 +- internal/macos/reims/capture_compat.go | 85 ++++++++ internal/macos/reims/compat_test.go | 195 ++++++++++++++++++ internal/macos/reims/reims.go | 24 ++- locales/en-US/settings.json | 10 +- locales/zh-CN/settings.json | 10 +- 22 files changed, 588 insertions(+), 62 deletions(-) create mode 100644 changes/capture-compat-and-input-settings.json create mode 100644 internal/macos/reims/capture_compat.go diff --git a/changes/capture-compat-and-input-settings.json b/changes/capture-compat-and-input-settings.json new file mode 100644 index 0000000..c94ac87 --- /dev/null +++ b/changes/capture-compat-and-input-settings.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["reiasu2"], + "zh": "适配新版运行时移除 `reims-ctl set --capture` 参数,按运行时能力隐藏「点击窗口时捕获键鼠」并避免新建、克隆与保存设置报错,同时将修饰键状态行独立显示并明确「拦截宿主机全局热键」用途与立即生效说明。", + "en": "Detect whether the active runtime supports `reims-ctl set --capture` so newer runtimes omit `--capture` during create, clone, and settings updates and hide the retired capture toggle, while moving modifier-key status to its own row and clarifying global host hotkey blocking." +} diff --git a/frontend/scripts/test-keymap.mjs b/frontend/scripts/test-keymap.mjs index cdeacd8..a3bd6a6 100644 --- a/frontend/scripts/test-keymap.mjs +++ b/frontend/scripts/test-keymap.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict' import test from 'node:test' import { loadTestModule } from './load-test-module.mjs' -const { createKeymapRequests, keymapPresetUpdate, keymapUpdate } = await loadTestModule(`export * from './lib/vmKeymap'`) +const { createKeymapRequests, keymapPresetUpdate, keymapStatusHint, keymapUpdate, visibleKeymapPresets } = await loadTestModule(`export * from './lib/vmKeymap'`) const off = { preset: 'off', bindings: {}, capture_host_shortcuts: false } const custom = { preset: 'custom', bindings: { lwin: 'lcmd' }, capture_host_shortcuts: true } @@ -89,3 +89,62 @@ test('a read started before a write cannot restore the old keymap', async () => await read assert.deepEqual(state, { keymap: custom, busy: false, error: '' }) }) + +test('visibleKeymapPresets hides win_to_cmd on modern runtimes unless already selected', () => { + assert.deepEqual(visibleKeymapPresets('off', false), ['off', 'swap_alt_win', 'custom']) + assert.deepEqual(visibleKeymapPresets('swap_alt_win', false), ['off', 'swap_alt_win', 'custom']) + assert.deepEqual(visibleKeymapPresets('custom', false), ['off', 'swap_alt_win', 'custom']) + assert.deepEqual(visibleKeymapPresets('win_to_cmd', false), ['off', 'win_to_cmd', 'swap_alt_win', 'custom']) + assert.deepEqual(visibleKeymapPresets('off', true), ['off', 'win_to_cmd', 'swap_alt_win', 'custom']) + assert.deepEqual(visibleKeymapPresets('swap_alt_win', true), ['off', 'win_to_cmd', 'swap_alt_win', 'custom']) +}) + +test('keymapStatusHint returns null when both preset and shortcut capture are off', () => { + const base = { + preset: 'off', + bindings: {}, + capture_host_shortcuts: false, + needs_guest_tools: false, + guest_connected: true, + guest_agent_version: 5, + required_agent_version: 5, + input_service_available: true, + guest_keymap_active: true, + hook_active: true, + running: true, + } + assert.equal(keymapStatusHint(base), null) +}) + +test('keymapStatusHint resolves priority when only capture_host_shortcuts is enabled', () => { + const base = { + preset: 'off', + bindings: {}, + capture_host_shortcuts: true, + needs_guest_tools: false, + guest_connected: false, + guest_agent_version: 0, + required_agent_version: 4, + input_service_available: true, + guest_keymap_active: false, + hook_active: true, + running: true, + } + assert.deepEqual(keymapStatusHint(base), { key: 'keymapRunning' }) + assert.deepEqual(keymapStatusHint({ ...base, hook_active: false }), { key: 'keymapInactive' }) + assert.deepEqual(keymapStatusHint({ ...base, running: false }), { key: 'keymapStopped' }) + assert.deepEqual(keymapStatusHint({ ...base, input_service_available: false, running: false }), { key: 'keymapInputServiceRequired' }) + assert.deepEqual(keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: false }), { key: 'keymapWaiting' }) + assert.deepEqual( + keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 3, required_agent_version: 4 }), + { key: 'keymapUpgrade', vars: { version: 4 } }, + ) + assert.deepEqual( + keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 4, required_agent_version: 4, guest_keymap_active: false }), + { key: 'keymapPending' }, + ) + assert.deepEqual( + keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 4, required_agent_version: 4, guest_keymap_active: true }), + { key: 'keymapRunning' }, + ) +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 31fb25a..79f78eb 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -368,8 +368,12 @@ export const App: React.FC = () => { useEffect(() => { if (!selectedVM || !selectedIsMacOS) { setDetail(null); return } - api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null)) - }, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, selectedTransition, selectedIsMacOS, detailRevision]) + let live = true + api.GetVMDetail(selectedVM.name) + .then((d) => { if (live) setDetail(d) }) + .catch(() => { if (live) setDetail(null) }) + return () => { live = false } + }, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, selectedTransition, selectedIsMacOS, detailRevision, state?.active_runtime?.commit, state?.runtime_capture_supported]) useEffect(() => { if (!selectedVM || selectedIsMacOS) { setVMInfoLoaded(null); return } @@ -1446,6 +1450,7 @@ export const App: React.FC = () => { locale={locale} host={state.host} fixedModeSupported={fixedModeSupported} + captureSupported={state.runtime_capture_supported} tasks={Object.values(taskMap)} draft={wizardDraft} onClose={() => { setShowWizard(false); setWizardDraft(null) }} diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index c944f12..76c9cde 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -53,6 +53,7 @@ interface Props { locale: Locale host: HostReport fixedModeSupported?: boolean + captureSupported?: boolean tasks?: Task[] draft?: WizardDraft | null onClose: () => void @@ -80,7 +81,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI { mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' }, ] -export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported = false, tasks = [], draft, onClose, onSubmit }) => { +export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onClose, onSubmit }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const [step, setStep] = useState(draft?.step ?? 1) // Once the user has reached the review step, keep validating so step markers stay current. @@ -126,7 +127,7 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported resolution: recommendedResolution(host), displays: 1, borderless: false, - capture: false, + ...(captureSupported ? { capture: false } : {}), audio: true, network: false, network_mode: 'off', @@ -159,6 +160,9 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported const buildPayload = (): CreateOpts => { const p: CreateOpts = { ...opts, offline: opts.source_mode === 'offline' } + if (!captureSupported) { + delete p.capture + } if (p.source_mode === 'offline') { p.installer = '' p.disk = '' @@ -229,7 +233,7 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported .finally(() => { if (live) setChecking(false) }) }, 200) return () => { live = false; clearTimeout(timer) } - }, [step, reviewed, opts, validationRefresh]) + }, [step, reviewed, opts, validationRefresh, captureSupported]) const pickDir = async () => { const dir = await api.PickDirectory(tr('vmDir')) @@ -668,11 +672,13 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported title={tr('enableAudio')} control={ set({ audio })} />} /> - set({ capture })} />} - /> + {captureSupported && ( + set({ capture })} />} + /> + )} = ({ locale, host, fixedModeSupported locale={locale} host={host} opts={opts} + captureSupported={captureSupported} networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name} issues={issues} checking={checking} @@ -765,6 +772,7 @@ interface ReviewProps { locale: Locale host: HostReport opts: CreateOpts + captureSupported: boolean issues: ValidationIssue[] checking: boolean command: string @@ -780,7 +788,7 @@ type Row = { label: string; value: string; mono?: boolean } const fileName = (p?: string) => (p ?? '').split(/[\\/]/).pop() || (p ?? '') /** Step ⑤: what will be created, grouped by the step that set it, with the CLI equivalent folded away. */ -const Review: React.FC = ({ locale, host, opts, issues, checking, command, onEdit, onName, onDir, onPickDir, onStartAfter, networkUplink }) => { +const Review: React.FC = ({ locale, host, opts, captureSupported, issues, checking, command, onEdit, onName, onDir, onPickDir, onStartAfter, networkUplink }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const [copied, setCopied] = useState(false) const onOff = (b?: boolean) => tr(b ? 'summaryOn' : 'off') @@ -835,7 +843,7 @@ const Review: React.FC = ({ locale, host, opts, issues, checking, c ...graphicsRows, { label: tr('fieldAudio'), value: onOff(opts.audio) }, { label: tr('fieldNetwork'), value: opts.network_mode === 'bridge' ? `${tr('networkBridge')} · ${networkUplink ?? tr('bridgeUplink')}` : tr((opts.network_mode ?? (opts.network ? 'nat' : 'off')) === 'off' ? 'off' : 'networkNAT') }, - { label: tr('captureInput'), value: onOff(opts.capture) }, + ...(captureSupported ? [{ label: tr('captureInput'), value: onOff(opts.capture) }] : []), { label: tr('summarySSH'), value: opts.ssh_port ? tr('summarySSHPort', { n: opts.ssh_port }) : tr('off') }, { label: tr('summaryLogs'), value: onOff(opts.logs) }, ], diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 95e3c63..6992ec7 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -119,7 +119,7 @@ function baseline(detail: VMDetail, host: HostReport): SetOpts { disk_controller: detail.disk_controller, resolution: detail.resolution, borderless: detail.borderless, - capture: detail.capture, + ...(detail.capture_supported ? { capture: detail.capture } : {}), gpu: icd ?? (detail.gpu || 'auto'), logs: detail.logs, log_level: detail.log_level, @@ -201,13 +201,22 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level)) }, [base]) + useEffect(() => { + setForm((f) => { + if (!detail.capture_supported) { + return f.capture === undefined ? f : { ...f, capture: undefined } + } + return f.capture === undefined ? { ...f, capture: detail.capture } : f + }) + }, [detail.capture_supported, detail.capture]) + const set = (patch: Partial) => { edited.current = true setForm((f) => ({ ...f, ...patch })) const touched = Object.keys(patch) setIssues((list) => list.filter((i) => !touched.includes(i.field))) } - const dirty = (f: Field) => !same(f, form[f], base[f]) + const dirty = (f: Field) => (f === 'capture' && !detail.capture_supported ? false : !same(f, form[f], base[f])) const reset = (f: Field) => () => { set({ [f]: base[f] } as Partial) if (f === 'resolution' || f === 'borderless') setCustomRes(false) @@ -725,15 +734,17 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats const input = ( <> - - set({ capture })} />} - /> - - + {detail.capture_supported && ( + + set({ capture })} />} + /> + + )} + = ({ · Ctrl+Alt+G {tr('shortcutBarRelease')}

- ) : detail.capture ? ( + ) : (!detail.capture_supported || detail.capture) ? (

Ctrl+Alt+Win {tr('shortcutBarRelease')}

diff --git a/frontend/src/components/vmSettings/keymap.tsx b/frontend/src/components/vmSettings/keymap.tsx index 6e68d2f..72bef70 100644 --- a/frontend/src/components/vmSettings/keymap.tsx +++ b/frontend/src/components/vmSettings/keymap.tsx @@ -1,10 +1,17 @@ import React, { useEffect, useRef, useState } from 'react' import { I18nKey, t } from '../../i18n' -import { createKeymapRequests, keymapPresetUpdate, keymapUpdate, type KeymapState } from '../../lib/vmKeymap' +import { createKeymapRequests, keymapPresetUpdate, keymapStatusHint, keymapUpdate, visibleKeymapPresets, type KeymapState } from '../../lib/vmKeymap' import { Locale, VMKeymapGuestModifier, VMKeymapHostModifier, VMKeymapPreset } from '../../types' -import { PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../../ui/settings' +import { PopupSelect, Segmented, SetGroup, SetRow, SetValue, Switch } from '../../ui/settings' import { api } from '../../wails' +const PRESET_LABEL: Record = { + off: 'keymapPresetOff', + win_to_cmd: 'keymapPresetWinToCmd', + swap_alt_win: 'keymapPresetSwapAltWin', + custom: 'keymapPresetCustom', +} + /** The VM's modifier key mapping, refreshed while shown. */ export function useKeymap(vm: string, running: boolean, shown: boolean) { const activeVMNameRef = useRef(vm) @@ -28,24 +35,20 @@ export function useKeymap(vm: string, running: boolean, shown: boolean) { return { keymap, keymapErr, keymapBusy, write: keymapRequests.write } } -export const KeymapSection: React.FC<{ locale: Locale; vm: string; state: ReturnType }> = ({ locale, vm, state }) => { +export const KeymapSection: React.FC<{ locale: Locale; vm: string; state: ReturnType; captureSupported: boolean }> = ({ locale, vm, state, captureSupported }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const { keymap, keymapErr, keymapBusy, write } = state + const statusHint = keymap ? keymapStatusHint(keymap) : null + const presetOptions = keymap + ? visibleKeymapPresets(keymap.preset, captureSupported).map((value) => ({ value, label: tr(PRESET_LABEL[value]) })) + : [] return ( {keymapErr &&
{keymapErr}
} {keymap && <> - label={tr('keymapPresetTitle')} value={keymap.preset} - options={[{ value: 'off', label: tr('keymapPresetOff') }, { value: 'win_to_cmd', label: tr('keymapPresetWinToCmd') }, { value: 'swap_alt_win', label: tr('keymapPresetSwapAltWin') }, { value: 'custom', label: tr('keymapPresetCustom') }]} + options={presetOptions} onChange={(preset) => { const request = keymapPresetUpdate(keymap, preset) if (request) void write(vm, request) @@ -55,6 +58,9 @@ export const KeymapSection: React.FC<{ locale: Locale; vm: string; state: Return control={ { void write(vm, keymapUpdate(keymap, { capture_host_shortcuts })) }} />} /> + {statusHint && ( + + )} {keymap.preset === 'custom' && ([ ['lwin', 'keymapHostLwin'], ['rwin', 'keymapHostRwin'], diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index ea30f84..7dd140d 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -99,7 +99,7 @@ export const settingsZh: Record = { "bridgeUplink": "出口网卡", "bridgeUplinkHint": "每台虚拟机独立选择一张已连接的有线或 WLAN 网卡", "captureInput": "点击窗口时捕获键鼠", - "captureInputHint": "开启后 ⌘Tab 等快捷键交给 macOS;关闭时 Win 键和 Alt+Tab 留给 Windows", + "captureInputHint": "开启后将指针锁定在窗口内,并将 ⌘Tab 等快捷键交给 macOS;关闭后鼠标可自由移出窗口,Win 键和 Alt+Tab 留给 Windows", "catAdvanced": "高级", "catAudio": "音频", "catCompute": "处理器与内存", @@ -357,9 +357,9 @@ export const settingsZh: Record = { "kernelIrqchipLabel": "中断加速", "kernelIrqchipOff": "关闭", "kernelIrqchipOn": "开启", - "keymapCaptureHostShortcutsDesc": "虚拟机获得焦点时,拦截 Windows 的 Win 和 Alt 快捷键。未单独映射的 Win 和 Alt 在 macOS 中仍用作 Command 和 Option。", - "keymapCaptureHostShortcutsTitle": "聚焦时拦截宿主机快捷键", - "keymapGroupNote": "仅在此虚拟机窗口位于前台时生效。Ctrl+Alt+Win 保留用于释放捕获。", + "keymapCaptureHostShortcutsDesc": "虚拟机获得焦点时拦截宿主机及第三方软件的 Win / Alt 全局热键(如截图 Alt+A、Ctrl+Alt+A),避免误触;未单独映射的 Win 和 Alt 在 macOS 中仍对应 Command 和 Option", + "keymapCaptureHostShortcutsTitle": "拦截宿主机全局热键", + "keymapGroupNote": "仅在此虚拟机窗口位于前台时生效;更改立即生效,无需点击保存。Ctrl+Alt+Win 保留用于释放键盘捕获", "keymapGroupTitle": "修饰键映射", "keymapGuestDefault": "默认", "keymapGuestDisabled": "禁用", @@ -381,11 +381,13 @@ export const settingsZh: Record = { "keymapInputServiceRequired": "请启用宿主输入服务以使用修饰键映射", "keymapPending": "等待 Guest Tools 启用修饰键映射", "keymapPresetCustom": "自定义", + "keymapPresetDesc": "调整修饰键映射(如将空格旁的 Alt 与 Win 互换以贴合 Mac 键位);不改键位时保持关闭即可", "keymapPresetOff": "关闭", "keymapPresetSwapAltWin": "Alt ↔ Win", "keymapPresetTitle": "映射预设", "keymapPresetWinToCmd": "Win → ⌘", "keymapRunning": "虚拟机获得焦点时生效", + "keymapStatusTitle": "生效状态", "keymapStopped": "虚拟机启动后生效", "keymapUpgrade": "请将 Guest Tools 更新到版本 {version}", "keymapWaiting": "等待 Guest Tools 连接", @@ -635,7 +637,7 @@ export const settingsEn: Record = { "bridgeUplink": "Uplink adapter", "bridgeUplinkHint": "Choose one connected wired or WLAN adapter independently for each VM", "captureInput": "Capture keyboard and mouse on click", - "captureInputHint": "When on, shortcuts like ⌘Tab go to macOS; when off, Win and Alt+Tab stay with Windows", + "captureInputHint": "When on, locks the pointer inside the window and sends shortcuts like ⌘Tab to macOS; when off, the mouse moves freely outside the window and Win and Alt+Tab stay with Windows", "catAdvanced": "Advanced", "catAudio": "Audio", "catCompute": "CPU \u0026 Memory", @@ -893,9 +895,9 @@ export const settingsEn: Record = { "kernelIrqchipLabel": "Interrupt acceleration", "kernelIrqchipOff": "Off", "kernelIrqchipOn": "On", - "keymapCaptureHostShortcutsDesc": "Block Windows shortcuts that use Win or Alt while the VM is focused. Unmapped Win and Alt keys act as Command and Option in macOS.", - "keymapCaptureHostShortcutsTitle": "Capture Host Shortcuts", - "keymapGroupNote": "Applies only while this VM is focused. Ctrl+Alt+Win is reserved for releasing capture.", + "keymapCaptureHostShortcutsDesc": "Blocks Win and Alt global hotkeys from the host and third-party apps (such as Alt+A or Ctrl+Alt+A for screenshots) while the VM is focused, preventing accidental triggers; unmapped Win and Alt keys still act as Command and Option in macOS", + "keymapCaptureHostShortcutsTitle": "Block host global hotkeys", + "keymapGroupNote": "Active only while this VM window is focused; changes apply immediately without clicking Save. Ctrl+Alt+Win is reserved for releasing keyboard capture", "keymapGroupTitle": "Modifier keys", "keymapGuestDefault": "Default", "keymapGuestDisabled": "Disabled", @@ -917,11 +919,13 @@ export const settingsEn: Record = { "keymapInputServiceRequired": "Enable Host Input Service to use modifier mapping", "keymapPending": "Waiting for Guest Tools to activate modifier mapping", "keymapPresetCustom": "Custom", + "keymapPresetDesc": "Remaps modifier keys (such as swapping Alt and Win next to Space to match a Mac keyboard); leave Off if no remapping is needed", "keymapPresetOff": "Off", "keymapPresetSwapAltWin": "Alt ↔ Win", "keymapPresetTitle": "Preset", "keymapPresetWinToCmd": "Win → ⌘", "keymapRunning": "Active while this VM is focused", + "keymapStatusTitle": "Status", "keymapStopped": "Applies when this VM is running", "keymapUpgrade": "Update Guest Tools to version {version}", "keymapWaiting": "Waiting for Guest Tools to connect", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 5d4e124..daafc4f 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -621,11 +621,13 @@ export type I18nKey = | "keymapInputServiceRequired" | "keymapPending" | "keymapPresetCustom" + | "keymapPresetDesc" | "keymapPresetOff" | "keymapPresetSwapAltWin" | "keymapPresetTitle" | "keymapPresetWinToCmd" | "keymapRunning" + | "keymapStatusTitle" | "keymapStopped" | "keymapUpgrade" | "keymapWaiting" diff --git a/frontend/src/lib/vmKeymap.ts b/frontend/src/lib/vmKeymap.ts index d12657a..162a0a1 100644 --- a/frontend/src/lib/vmKeymap.ts +++ b/frontend/src/lib/vmKeymap.ts @@ -8,6 +8,37 @@ type KeymapAPI = { export type KeymapState = { keymap: VMKeymapStatus | null; error: string; busy: boolean } +type KeymapStatusKey = + | 'keymapInputServiceRequired' + | 'keymapStopped' + | 'keymapWaiting' + | 'keymapUpgrade' + | 'keymapPending' + | 'keymapRunning' + | 'keymapInactive' + +type KeymapStatusHint = { key: KeymapStatusKey; vars?: { version: number } } + +const ALL_KEYMAP_PRESETS: readonly VMKeymapPreset[] = ['off', 'win_to_cmd', 'swap_alt_win', 'custom'] +const MODERN_KEYMAP_PRESETS: readonly VMKeymapPreset[] = ['off', 'swap_alt_win', 'custom'] + +export function visibleKeymapPresets(preset: VMKeymapPreset, captureSupported: boolean): readonly VMKeymapPreset[] { + if (!captureSupported && preset !== 'win_to_cmd') return MODERN_KEYMAP_PRESETS + return ALL_KEYMAP_PRESETS +} + +export function keymapStatusHint(keymap: VMKeymapStatus): KeymapStatusHint | null { + if (keymap.preset === 'off' && !keymap.capture_host_shortcuts) return null + if (!keymap.input_service_available) return { key: 'keymapInputServiceRequired' } + if (!keymap.running) return { key: 'keymapStopped' } + if (keymap.needs_guest_tools && !keymap.guest_connected) return { key: 'keymapWaiting' } + if (keymap.needs_guest_tools && (keymap.guest_agent_version ?? 0) < keymap.required_agent_version) { + return { key: 'keymapUpgrade', vars: { version: keymap.required_agent_version } } + } + if (keymap.needs_guest_tools && !keymap.guest_keymap_active) return { key: 'keymapPending' } + return { key: keymap.hook_active ? 'keymapRunning' : 'keymapInactive' } +} + type KeymapRequest = Required export function keymapUpdate(current: VMKeymapStatus, changes: Partial): KeymapRequest { diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index e955050..b280621 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -7,6 +7,7 @@ export namespace app { optimizations: host.Optimization[]; runtimes: runtime.Installed[]; active_runtime?: runtime.Installed; + runtime_capture_supported: boolean; can_suspend: boolean; vms: driver.VMListItem[]; vm_list_error?: string; @@ -37,6 +38,7 @@ export namespace app { this.optimizations = this.convertValues(source["optimizations"], host.Optimization); this.runtimes = this.convertValues(source["runtimes"], runtime.Installed); this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed); + this.runtime_capture_supported = source["runtime_capture_supported"]; this.can_suspend = source["can_suspend"]; this.vms = this.convertValues(source["vms"], driver.VMListItem); this.vm_list_error = source["vm_list_error"]; @@ -3196,6 +3198,7 @@ export namespace reims { log_level: string; stop_timeout: number; capture: boolean; + capture_supported: boolean; borderless: boolean; extra_args: string; guest_tools_attached: boolean; @@ -3248,6 +3251,7 @@ export namespace reims { this.log_level = source["log_level"]; this.stop_timeout = source["stop_timeout"]; this.capture = source["capture"]; + this.capture_supported = source["capture_supported"]; this.borderless = source["borderless"]; this.extra_args = source["extra_args"]; this.guest_tools_attached = source["guest_tools_attached"]; diff --git a/internal/app/app.go b/internal/app/app.go index 05df261..a6e8a30 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -74,6 +74,8 @@ type AppState struct { DetectedLocale string `json:"detected_locale,omitempty"` EffectiveLocale string `json:"effective_locale,omitempty"` MissingFontHint string `json:"missing_font_hint,omitempty"` + + RuntimeCaptureSupported bool `json:"runtime_capture_supported"` } type rebootWatcherEntry struct { @@ -450,6 +452,8 @@ func (a *App) GetState() AppState { DetectedLocale: string(i18n.DetectOSLocaleTag()), EffectiveLocale: string(i18n.EffectiveLocale(cfgCopy.Locale)), MissingFontHint: host.CheckMissingLocaleFontsForUI(string(i18n.EffectiveLocale(cfgCopy.Locale)), i18n.EffectiveLocale(cfgCopy.Locale)), + + RuntimeCaptureSupported: !needsSetup && !rootStatus.ReadOnly && active != nil && runtimeSupportsCapture(*active), } } diff --git a/internal/app/create_flow.go b/internal/app/create_flow.go index e54cc68..7aaa035 100644 --- a/internal/app/create_flow.go +++ b/internal/app/create_flow.go @@ -186,7 +186,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) { finishTask(err) return fmt.Errorf("record VM driver ownership: %w", err) } - if postSet, ok := reims.PostCreateSetOpts(opts); ok { + if postSet, ok := reims.PostCreateSetOptsWithCapture(opts, c.SupportsSetCapture()); ok { var parts []string if postSet.DiskController != "" { parts = append(parts, "disk="+strings.ToUpper(postSet.DiskController)) diff --git a/internal/app/dataroot_flow_test.go b/internal/app/dataroot_flow_test.go index 8753a62..8128c17 100644 --- a/internal/app/dataroot_flow_test.go +++ b/internal/app/dataroot_flow_test.go @@ -2,7 +2,9 @@ package app import ( "context" + "fmt" "os" + "os/exec" "path/filepath" "strings" "testing" @@ -11,6 +13,7 @@ import ( "github.com/Nwflower/reims-go/internal/datamigrate" "github.com/Nwflower/reims-go/internal/dataroot" "github.com/Nwflower/reims-go/internal/macos/reims" + rt "github.com/Nwflower/reims-go/internal/runtime" "github.com/Nwflower/reims-go/internal/version" ) @@ -92,6 +95,71 @@ func TestReadOnlyFolderRefusesWrites(t *testing.T) { } } +// The copied test executable acts as reims-ctl when called with set --help. +func init() { + marker := os.Getenv("REIMS_TEST_READ_ONLY_CAPTURE_MARKER") + if marker == "" || len(os.Args) != 3 || os.Args[1] != "set" || os.Args[2] != "--help" { + return + } + if err := os.WriteFile(marker, nil, 0o600); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + fmt.Println(" --capture ") + os.Exit(0) +} + +func TestReadOnlyFolderSkipsCaptureProbe(t *testing.T) { + cfg := config.Default() + cfg.DataRoot = t.TempDir() + cfg.ActiveRuntime = "test-rt" + installDummyRuntime(t, cfg.DataRoot) + if err := os.WriteFile(filepath.Join(cfg.DataRoot, datamigrate.StampFile), []byte(`{"data_version": 999}`), 0o644); err != nil { + t.Fatal(err) + } + active, err := rt.ResolveActive(cfg) + if err != nil { + t.Fatal(err) + } + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + binary, err := os.ReadFile(exe) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(active.ReimsCtlPath(), binary, 0o700); err != nil { + t.Fatal(err) + } + marker := filepath.Join(t.TempDir(), "capture-probed") + t.Setenv("REIMS_TEST_READ_ONLY_CAPTURE_MARKER", marker) + output, err := exec.CommandContext(t.Context(), active.ReimsCtlPath(), "set", "--help").CombinedOutput() + if err != nil || !strings.Contains(string(output), "--capture") { + t.Fatalf("test runtime help = %q, err = %v", output, err) + } + if err := os.Remove(marker); err != nil { + t.Fatalf("clear test runtime's probe marker: %v", err) + } + + a := &App{cfg: cfg, root: dataroot.Open(cfg.DataRoot, version.Version)} + state := a.GetState() + if !state.DataRoot.ReadOnly || state.ActiveRuntime == nil || state.RuntimeCaptureSupported { + t.Errorf("GetState: read-only = %t, active runtime = %v, capture supported = %t", state.DataRoot.ReadOnly, state.ActiveRuntime, state.RuntimeCaptureSupported) + } + off := false + opts := reims.CreateOpts{Name: "test", Capture: &off} + preview, err := a.PreviewCreate(opts) + if err != nil || strings.Contains(preview, "--capture") { + t.Errorf("read-only PreviewCreate = %q, err = %v", preview, err) + } + for _, path := range []string{cfg.TempDir(), marker} { + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Errorf("stat %q = %v, want not exist", path, err) + } + } +} + func TestSetDataRoot_RelocatesMovedVMRegistry(t *testing.T) { t.Setenv("REIMS_CTL_CONFIG_DIR", "") base := t.TempDir() diff --git a/internal/app/macos_settings.go b/internal/app/macos_settings.go index 25425fc..dc5a231 100644 --- a/internal/app/macos_settings.go +++ b/internal/app/macos_settings.go @@ -63,7 +63,16 @@ func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue { } func (a *App) PreviewCreate(opts reims.CreateOpts) (string, error) { - return reims.PreviewCreateCommand(opts) + if !a.dataRootUsable() { + return reims.PreviewCreateCommandWithCapture(opts, false) + } + cfg := a.runtimeConfig() + active, err := rt.ResolveActive(&cfg) + return reims.PreviewCreateCommandWithCapture(opts, err == nil && runtimeSupportsCapture(*active)) +} + +func runtimeSupportsCapture(active rt.Installed) bool { + return reims.ProbeReimsCTLSupportsCapture(active.ReimsCtlPath(), nil) } func (a *App) CreateVM(opts reims.CreateOpts) error { diff --git a/internal/cli/macos_native.go b/internal/cli/macos_native.go index e24e249..343890f 100644 --- a/internal/cli/macos_native.go +++ b/internal/cli/macos_native.go @@ -110,7 +110,7 @@ func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in if err := driver.WriteOwnerDriver(createdDir, driver.BuiltinReimsMacOSDriverID); err != nil { return err } - if postSet, ok := reims.PostCreateSetOpts(opts); ok { + if postSet, ok := reims.PostCreateSetOptsWithCapture(opts, client.SupportsSetCapture()); ok { if err := client.Set(ctx, postSet, os.Stdout, os.Stderr); err != nil { fmt.Fprintf(os.Stderr, "Warning: could not apply post-create defaults: %v\n", err) } diff --git a/internal/macos/macosdriver/clone.go b/internal/macos/macosdriver/clone.go index 946d7f2..13e9bba 100644 --- a/internal/macos/macosdriver/clone.go +++ b/internal/macos/macosdriver/clone.go @@ -173,17 +173,21 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s if err := reims.CreateCoWOverlay(ctx, active.QemuImgPath(), env, srcDisk, overlayPath, stdout, stderr); err != nil { return err } - audio, network, logs, capture := src.Audio, src.Network, src.Logs, src.Capture + audio, network, logs := src.Audio, src.Network, src.Logs // 克隆默认回到 NAT,不能复用源虚拟机的独立帧端口。 if src.NetworkMode == "bridge" { network = true } - createOpts := reims.CreateOpts{Name: cloneName, SourceMode: "disk", Disk: overlayPath, DiskMode: "in-place", DiskController: src.DiskController, CPUs: src.CPUs, Memory: src.Memory, Graphics: src.Graphics, GPU: src.GPU, Resolution: src.Resolution, Displays: src.Displays, Capture: &capture, Audio: &audio, Network: &network, SSHPort: clonePort, Logs: &logs, Start: false} + createOpts := reims.CreateOpts{Name: cloneName, SourceMode: "disk", Disk: overlayPath, DiskMode: "in-place", DiskController: src.DiskController, CPUs: src.CPUs, Memory: src.Memory, Graphics: src.Graphics, GPU: src.GPU, Resolution: src.Resolution, Displays: src.Displays, Audio: &audio, Network: &network, SSHPort: clonePort, Logs: &logs, Start: false} + captureSupported := c.SupportsSetCapture() + if captureSupported { + createOpts.Capture = &src.Capture + } if err := c.RegisterCoWClone(ctx, createOpts, stdout, stderr); err != nil { return err } cloneRegistered = true - if postSet, ok := reims.PostCreateSetOpts(createOpts); ok { + if postSet, ok := reims.PostCreateSetOptsWithCapture(createOpts, captureSupported); ok { if err := c.Set(ctx, postSet, stdout, stderr); err != nil { _, _ = fmt.Fprintf(stdout, "Warning: could not apply clone settings: %v\n", err) } diff --git a/internal/macos/reims/capture_compat.go b/internal/macos/reims/capture_compat.go new file mode 100644 index 0000000..b392707 --- /dev/null +++ b/internal/macos/reims/capture_compat.go @@ -0,0 +1,85 @@ +package reims + +import ( + "bytes" + "context" + "os" + "regexp" + "strings" + "sync" + "time" +) + +type captureProbeKey struct { + path string + mtime int64 +} + +type captureProbeCall struct { + done chan struct{} + ok bool + err error +} + +var ( + captureProbeMu sync.Mutex + captureProbeCache = map[captureProbeKey]bool{} + captureProbeInFlight = map[captureProbeKey]*captureProbeCall{} + captureOption = regexp.MustCompile(`(?m)(?:^|\s)--capture(?:\s|,|=|$)`) +) + +// ProbeReimsCTLSupportsCapture checks set --help and caches successful checks +// for the current version of the binary. +func ProbeReimsCTLSupportsCapture(binaryPath string, env []string) bool { + ok, err := probeReimsCTLSupportsCapture(binaryPath, env) + return err == nil && ok +} + +func probeReimsCTLSupportsCapture(binaryPath string, env []string) (bool, error) { + binaryPath = strings.TrimSpace(binaryPath) + if binaryPath == "" { + return false, os.ErrNotExist + } + info, err := os.Stat(binaryPath) + if err != nil { + return false, err + } + key := captureProbeKey{path: binaryPath, mtime: info.ModTime().UnixNano()} + captureProbeMu.Lock() + if cached, found := captureProbeCache[key]; found { + captureProbeMu.Unlock() + return cached, nil + } + if call := captureProbeInFlight[key]; call != nil { + captureProbeMu.Unlock() + <-call.done + return call.ok, call.err + } + call := &captureProbeCall{done: make(chan struct{})} + captureProbeInFlight[key] = call + captureProbeMu.Unlock() + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + var output bytes.Buffer + client := Client{Binary: binaryPath, Env: env} + err = client.run(ctx, &output, &output, "set", "--help") + captureProbeMu.Lock() + call.err = err + if err == nil { + call.ok = captureOption.Match(output.Bytes()) + captureProbeCache[key] = call.ok + } + delete(captureProbeInFlight, key) + close(call.done) + captureProbeMu.Unlock() + return call.ok, call.err +} + +func (c *Client) SupportsSetCapture() bool { + return ProbeReimsCTLSupportsCapture(c.Binary, c.Env) +} + +func (c *Client) probeSetCapture() (bool, error) { + return probeReimsCTLSupportsCapture(c.Binary, c.Env) +} diff --git a/internal/macos/reims/compat_test.go b/internal/macos/reims/compat_test.go index 4f8fe40..840a73a 100644 --- a/internal/macos/reims/compat_test.go +++ b/internal/macos/reims/compat_test.go @@ -11,7 +11,9 @@ import ( "reflect" "slices" "strings" + "sync" "testing" + "time" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" @@ -228,6 +230,136 @@ func TestMain(m *testing.M) { os.Exit(m.Run()) } +func captureTestClient(t *testing.T, helpMode string) (Client, string) { + t.Helper() + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + // Subtests reuse the running executable with different help output. + captureProbeMu.Lock() + previous := captureProbeCache + captureProbeCache = map[captureProbeKey]bool{} + captureProbeMu.Unlock() + t.Cleanup(func() { + captureProbeMu.Lock() + captureProbeCache = previous + captureProbeMu.Unlock() + }) + dir := t.TempDir() + return Client{Binary: exe, Env: append(os.Environ(), + "REIMS_TEST_CTL_DIR="+dir, "REIMS_TEST_CTL_CAPTURE_HELP="+helpMode)}, dir +} + +func TestProbeReimsCTLSupportsCapture(t *testing.T) { + for _, path := range []string{"", filepath.Join(t.TempDir(), "missing.exe")} { + if ProbeReimsCTLSupportsCapture(path, nil) { + t.Errorf("probe reported support for %q", path) + } + } + for _, tc := range []struct { + mode string + want bool + }{ + {mode: "stdout", want: true}, + {mode: "stderr", want: true}, + {mode: "absent"}, + } { + t.Run(tc.mode, func(t *testing.T) { + c, dir := captureTestClient(t, tc.mode) + if got := ProbeReimsCTLSupportsCapture(c.Binary, c.Env); got != tc.want { + t.Fatalf("probe = %t, want %t", got, tc.want) + } + if got := c.SupportsSetCapture(); got != tc.want { + t.Fatalf("cached probe = %t, want %t", got, tc.want) + } + calls, err := os.ReadFile(filepath.Join(dir, "commands")) + if err != nil || string(calls) != "set\t--help\n" { + t.Fatalf("cached probe calls = %q, err = %v", calls, err) + } + }) + } + t.Run("error", func(t *testing.T) { + c, dir := captureTestClient(t, "error") + if c.SupportsSetCapture() { + t.Fatal("unsuccessful probe reported support") + } + if !ProbeReimsCTLSupportsCapture(c.Binary, append(c.Env, "REIMS_TEST_CTL_CAPTURE_HELP=stdout")) { + t.Fatal("successful probe after failure did not report support") + } + if !c.SupportsSetCapture() { + t.Fatal("successful retry was not cached") + } + calls, err := os.ReadFile(filepath.Join(dir, "commands")) + if err != nil || string(calls) != "set\t--help\nset\t--help\n" { + t.Fatalf("probe calls = %q, err = %v, want one failed call and one successful call", calls, err) + } + }) +} + +func TestProbeReimsCTLSupportsCaptureConcurrent(t *testing.T) { + c, dir := captureTestClient(t, "slow-stdout") + const callers = 16 + start := make(chan struct{}) + results := make(chan bool, callers) + var ready sync.WaitGroup + ready.Add(callers) + for range callers { + go func() { + ready.Done() + <-start + results <- c.SupportsSetCapture() + }() + } + ready.Wait() + close(start) + for range callers { + if !<-results { + t.Error("concurrent probe did not report support") + } + } + if !ProbeReimsCTLSupportsCapture(c.Binary, append(c.Env, "REIMS_TEST_CTL_CAPTURE_HELP=error")) { + t.Error("concurrent probe result was not cached") + } + calls, err := os.ReadFile(filepath.Join(dir, "commands")) + if err != nil || string(calls) != "set\t--help\n" { + t.Fatalf("probe calls = %q, err = %v, want one help call", calls, err) + } +} + +func TestSetSkipsUnsupportedCapture(t *testing.T) { + c, dir := captureTestClient(t, "absent") + off := false + if err := c.Set(t.Context(), SetOpts{Name: "test", Capture: &off}, nil, nil); err != nil { + t.Fatal(err) + } + if err := c.Set(t.Context(), SetOpts{Name: "test", Capture: &off, CPUs: 4}, nil, nil); err != nil { + t.Fatal(err) + } + calls, err := os.ReadFile(filepath.Join(dir, "commands")) + if err != nil || string(calls) != "set\t--help\nset\ttest\t--cpus\t4\n" { + t.Fatalf("commands = %q, err = %v", calls, err) + } + if err := c.Set(t.Context(), SetOpts{Capture: &off}, nil, nil); err == nil { + t.Fatal("capture-only set with missing name accepted") + } +} + +func TestShowCaptureSupported(t *testing.T) { + for _, mode := range []string{"stdout", "absent"} { + t.Run(mode, func(t *testing.T) { + c, _ := captureTestClient(t, mode) + detail, err := c.Show(t.Context(), "test") + if err != nil { + t.Fatal(err) + } + if want := mode == "stdout"; detail.CaptureSupported != want { + t.Fatalf("capture_supported = %t, want %t", detail.CaptureSupported, want) + } + }) + } +} + func TestHelperProcess(t *testing.T) { dir := os.Getenv("REIMS_TEST_CTL_DIR") if dir == "" { @@ -237,6 +369,11 @@ func TestHelperProcess(t *testing.T) { if len(args) < 2 { t.Fatalf("expected ctl command and VM name, got %q", args) } + helpMode := os.Getenv("REIMS_TEST_CTL_CAPTURE_HELP") + isSetHelp := slices.Equal(args, []string{"set", "--help"}) + if isSetHelp && helpMode == "" { + return + } log, err := os.OpenFile(filepath.Join(dir, "commands"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) if err != nil { t.Fatal(err) @@ -248,6 +385,33 @@ func TestHelperProcess(t *testing.T) { if args[0] == os.Getenv("REIMS_TEST_CTL_FAIL") { os.Exit(7) } + if helpMode != "" { + switch { + case isSetHelp: + switch helpMode { + case "slow-stdout": + time.Sleep(200 * time.Millisecond) + fallthrough + case "stdout": + fmt.Println(" --capture ") + case "stderr": + fmt.Fprintln(os.Stderr, " --capture=") + case "absent": + fmt.Println(" --capture-mode \n --other--capture ") + case "error": + fmt.Println(" --capture ") + os.Exit(2) + default: + t.Fatalf("unexpected capture help mode %q", helpMode) + } + case slices.Equal(args, []string{"show", "test"}): + fmt.Println("test\n state stopped") + case slices.Equal(args, []string{"set", "test", "--cpus", "4"}): + default: + t.Fatalf("unexpected capture test command %q", args) + } + return + } gpuFile := filepath.Join(dir, "gpu") switch args[0] { case "show": @@ -466,6 +630,37 @@ func TestCreateDefaultNVMeAndPreview(t *testing.T) { } } +func TestPostCreateSetOptsAndPreviewWithCapture(t *testing.T) { + for _, tc := range []struct { + name, controller, wantSet string + supported bool + }{ + {name: "legacy NVMe", controller: "nvme", supported: true, wantSet: "set test --disk-controller nvme --capture false"}, + {name: "modern NVMe", controller: "nvme", wantSet: "set test --disk-controller nvme"}, + {name: "legacy AHCI", controller: "ahci", supported: true, wantSet: "set test --capture false"}, + {name: "modern AHCI", controller: "ahci"}, + } { + t.Run(tc.name, func(t *testing.T) { + opts := CreateOpts{Name: "test", MacOS: "tahoe", DiskController: tc.controller} + postSet, ok := PostCreateSetOptsWithCapture(opts, tc.supported) + if ok != (tc.wantSet != "") { + t.Fatalf("post-create set needed = %t, want %q", ok, tc.wantSet) + } + if ok { + args, err := BuildSetArgs(postSet) + if err != nil || strings.Join(args, " ") != tc.wantSet { + t.Fatalf("post-create set = %q, err = %v, want %q", args, err, tc.wantSet) + } + } + cmd, err := PreviewCreateCommandWithCapture(opts, tc.supported) + _, set, _ := strings.Cut(cmd, " && reims-ctl ") + if err != nil || set != tc.wantSet { + t.Fatalf("preview = %q, err = %v, want set %q", cmd, err, tc.wantSet) + } + }) + } +} + func TestMergeAndStripGuestToolsArgs(t *testing.T) { base := `-drive id=reimshelp,if=none,format=raw,readonly=on,file=D:/help.img -device usb-storage,id=reimshelp-dev,drive=reimshelp,bus=xhci.0` merged := MergeGuestToolsArgs(base, `D:\Data\reims-go\cache\m0-tools.img`) diff --git a/internal/macos/reims/reims.go b/internal/macos/reims/reims.go index b58f719..7f9c0b6 100644 --- a/internal/macos/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -112,6 +112,7 @@ type VMDetail struct { LogLevel string `json:"log_level"` StopTimeout int `json:"stop_timeout"` Capture bool `json:"capture"` + CaptureSupported bool `json:"capture_supported"` Borderless bool `json:"borderless"` ExtraArgs string `json:"extra_args"` GuestToolsAttached bool `json:"guest_tools_attached"` @@ -448,13 +449,17 @@ func EffectiveCreateCapture(o CreateOpts) bool { // `reims-ctl create` does not accept directly (upstream 3731afd defaults to // SATA/AHCI and capture=true). func PostCreateSetOpts(o CreateOpts) (SetOpts, bool) { + return PostCreateSetOptsWithCapture(o, true) +} + +func PostCreateSetOptsWithCapture(o CreateOpts, captureSupported bool) (SetOpts, bool) { so := SetOpts{Name: o.Name} need := false if dc := EffectiveCreateDiskController(o); dc != "ahci" { so.DiskController = dc need = true } - if !EffectiveCreateCapture(o) { + if captureSupported && !EffectiveCreateCapture(o) { off := false so.Capture = &off need = true @@ -464,6 +469,10 @@ func PostCreateSetOpts(o CreateOpts) (SetOpts, bool) { // PreviewCreateCommand formats the exact CLI command shown on Step 5 of the wizard. func PreviewCreateCommand(o CreateOpts) (string, error) { + return PreviewCreateCommandWithCapture(o, true) +} + +func PreviewCreateCommandWithCapture(o CreateOpts, captureSupported bool) (string, error) { args, err := BuildCreateArgs(o) if err != nil { return "", err @@ -481,7 +490,7 @@ func PreviewCreateCommand(o CreateOpts) (string, error) { return strings.Join(quoted, " ") } cmd := quoteArgs(args) - if so, ok := PostCreateSetOpts(o); ok { + if so, ok := PostCreateSetOptsWithCapture(o, captureSupported); ok { if setArgs, err := BuildSetArgs(so); err == nil { cmd += " && " + quoteArgs(setArgs) } @@ -763,6 +772,7 @@ func (c *Client) Show(ctx context.Context, name string) (VMDetail, error) { return VMDetail{}, fmt.Errorf("reims-ctl show %s: %w (%s)", name, err, strings.TrimSpace(errBuf.String())) } d := ParseShow(name, out.String()) + d.CaptureSupported = c.SupportsSetCapture() applyBorderlessResolutionFallback(&d) return d, nil } @@ -824,10 +834,20 @@ func (c *Client) Create(ctx context.Context, o CreateOpts, stdout, stderr io.Wri } func (c *Client) Set(ctx context.Context, o SetOpts, stdout, stderr io.Writer) error { + skipCapture := false + if o.Capture != nil { + if supported, probeErr := c.probeSetCapture(); probeErr == nil && !supported { + skipCapture = true + o.Capture = nil + } + } args, err := BuildSetArgs(o) if err != nil { return err } + if skipCapture && len(args) == 2 { + return nil + } return c.run(ctx, stdout, stderr, args...) } diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index bdabe48..d2fb5b8 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -28,10 +28,12 @@ "bridgeRepair": "Check and repair", "bridgeApplyHint": "Network changes apply separately. Shut down this VM to change mode; bridged uplinks can change while running without reconfiguring other VMs. Host adapter IP, DNS, and bindings remain unchanged", "keymapGroupTitle": "Modifier keys", - "keymapGroupNote": "Applies only while this VM is focused. Ctrl+Alt+Win is reserved for releasing capture.", + "keymapGroupNote": "Active only while this VM window is focused; changes apply immediately without clicking Save. Ctrl+Alt+Win is reserved for releasing keyboard capture", "keymapPresetTitle": "Preset", - "keymapCaptureHostShortcutsTitle": "Capture Host Shortcuts", - "keymapCaptureHostShortcutsDesc": "Block Windows shortcuts that use Win or Alt while the VM is focused. Unmapped Win and Alt keys act as Command and Option in macOS.", + "keymapPresetDesc": "Remaps modifier keys (such as swapping Alt and Win next to Space to match a Mac keyboard); leave Off if no remapping is needed", + "keymapCaptureHostShortcutsTitle": "Block host global hotkeys", + "keymapCaptureHostShortcutsDesc": "Blocks Win and Alt global hotkeys from the host and third-party apps (such as Alt+A or Ctrl+Alt+A for screenshots) while the VM is focused, preventing accidental triggers; unmapped Win and Alt keys still act as Command and Option in macOS", + "keymapStatusTitle": "Status", "keymapRunning": "Active while this VM is focused", "keymapStopped": "Applies when this VM is running", "keymapWaiting": "Waiting for Guest Tools to connect", @@ -326,7 +328,7 @@ "diskController": "Disk interface", "diskControllerWarn": "Eject the installer before switching", "captureInput": "Capture keyboard and mouse on click", - "captureInputHint": "When on, shortcuts like ⌘Tab go to macOS; when off, Win and Alt+Tab stay with Windows", + "captureInputHint": "When on, locks the pointer inside the window and sends shortcuts like ⌘Tab to macOS; when off, the mouse moves freely outside the window and Win and Alt+Tab stay with Windows", "stopTimeout": "Shutdown timeout", "stopTimeoutHint": "0 waits indefinitely", "extraArgs": "Extra QEMU arguments", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index d616199..36ced8b 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -28,10 +28,12 @@ "bridgeRepair": "检查并修复", "bridgeApplyHint": "网络设置单独应用。切换模式需关闭此虚拟机,更换桥接出口支持运行中应用,不影响其他虚拟机。宿主网卡的 IP、DNS 和绑定保持不变", "keymapGroupTitle": "修饰键映射", - "keymapGroupNote": "仅在此虚拟机窗口位于前台时生效。Ctrl+Alt+Win 保留用于释放捕获。", + "keymapGroupNote": "仅在此虚拟机窗口位于前台时生效;更改立即生效,无需点击保存。Ctrl+Alt+Win 保留用于释放键盘捕获", "keymapPresetTitle": "映射预设", - "keymapCaptureHostShortcutsTitle": "聚焦时拦截宿主机快捷键", - "keymapCaptureHostShortcutsDesc": "虚拟机获得焦点时,拦截 Windows 的 Win 和 Alt 快捷键。未单独映射的 Win 和 Alt 在 macOS 中仍用作 Command 和 Option。", + "keymapPresetDesc": "调整修饰键映射(如将空格旁的 Alt 与 Win 互换以贴合 Mac 键位);不改键位时保持关闭即可", + "keymapCaptureHostShortcutsTitle": "拦截宿主机全局热键", + "keymapCaptureHostShortcutsDesc": "虚拟机获得焦点时拦截宿主机及第三方软件的 Win / Alt 全局热键(如截图 Alt+A、Ctrl+Alt+A),避免误触;未单独映射的 Win 和 Alt 在 macOS 中仍对应 Command 和 Option", + "keymapStatusTitle": "生效状态", "keymapRunning": "虚拟机获得焦点时生效", "keymapStopped": "虚拟机启动后生效", "keymapWaiting": "等待 Guest Tools 连接", @@ -326,7 +328,7 @@ "diskController": "磁盘接口", "diskControllerWarn": "切换前先弹出安装盘", "captureInput": "点击窗口时捕获键鼠", - "captureInputHint": "开启后 ⌘Tab 等快捷键交给 macOS;关闭时 Win 键和 Alt+Tab 留给 Windows", + "captureInputHint": "开启后将指针锁定在窗口内,并将 ⌘Tab 等快捷键交给 macOS;关闭后鼠标可自由移出窗口,Win 键和 Alt+Tab 留给 Windows", "stopTimeout": "关机等待时间", "stopTimeoutHint": "0 表示一直等待", "extraArgs": "额外 QEMU 参数", From ed1a0ba254ae9e43f029173251effa4ce3c54bac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A3=A0=E6=B8=9A=E5=90=AC=E6=BD=AE?= <108173440+reiasu2@users.noreply.github.com> Date: Sat, 5 Dec 2026 12:01:30 +0800 Subject: [PATCH 2/3] fix(reims): drop uncalled PostCreateSetOpts and PreviewCreateCommand wrappers --- internal/macos/reims/compat_test.go | 4 ++-- internal/macos/reims/reims.go | 12 ++---------- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/internal/macos/reims/compat_test.go b/internal/macos/reims/compat_test.go index 840a73a..6e9fc52 100644 --- a/internal/macos/reims/compat_test.go +++ b/internal/macos/reims/compat_test.go @@ -611,7 +611,7 @@ func TestCreateDefaultNVMeAndPreview(t *testing.T) { if EffectiveCreateCapture(opts) { t.Fatalf("EffectiveCreateCapture default = true, want false") } - cmd, err := PreviewCreateCommand(opts) + cmd, err := PreviewCreateCommandWithCapture(opts, true) if err != nil { t.Fatal(err) } @@ -621,7 +621,7 @@ func TestCreateDefaultNVMeAndPreview(t *testing.T) { opts.DiskController = "ahci" on := true opts.Capture = &on - cmdAhciCaptureOn, err := PreviewCreateCommand(opts) + cmdAhciCaptureOn, err := PreviewCreateCommandWithCapture(opts, true) if err != nil { t.Fatal(err) } diff --git a/internal/macos/reims/reims.go b/internal/macos/reims/reims.go index 7f9c0b6..b5c7ea6 100644 --- a/internal/macos/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -445,13 +445,9 @@ func EffectiveCreateCapture(o CreateOpts) bool { return false } -// PostCreateSetOpts returns follow-up `reims-ctl set` options for defaults that +// PostCreateSetOptsWithCapture returns follow-up `reims-ctl set` options for defaults that // `reims-ctl create` does not accept directly (upstream 3731afd defaults to // SATA/AHCI and capture=true). -func PostCreateSetOpts(o CreateOpts) (SetOpts, bool) { - return PostCreateSetOptsWithCapture(o, true) -} - func PostCreateSetOptsWithCapture(o CreateOpts, captureSupported bool) (SetOpts, bool) { so := SetOpts{Name: o.Name} need := false @@ -467,11 +463,7 @@ func PostCreateSetOptsWithCapture(o CreateOpts, captureSupported bool) (SetOpts, return so, need } -// PreviewCreateCommand formats the exact CLI command shown on Step 5 of the wizard. -func PreviewCreateCommand(o CreateOpts) (string, error) { - return PreviewCreateCommandWithCapture(o, true) -} - +// PreviewCreateCommandWithCapture formats the exact CLI command shown on Step 5 of the wizard. func PreviewCreateCommandWithCapture(o CreateOpts, captureSupported bool) (string, error) { args, err := BuildCreateArgs(o) if err != nil { From 3d5c6cb82602bb28ee7a91118402dfd8392ce1aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Fri, 4 Dec 2026 23:01:43 -0700 Subject: [PATCH 3/3] fix(input): preserve legacy capture when the probe fails --- internal/app/app.go | 2 +- internal/app/create_flow.go | 2 +- internal/app/macos_settings.go | 6 ++-- internal/cli/macos_native.go | 2 +- internal/macos/macosdriver/clone.go | 8 ++--- internal/macos/reims/capture_compat.go | 16 ++++----- internal/macos/reims/compat_test.go | 46 ++++++++++++++++++-------- internal/macos/reims/reims.go | 11 +++--- 8 files changed, 50 insertions(+), 43 deletions(-) diff --git a/internal/app/app.go b/internal/app/app.go index a6e8a30..8c87b9b 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -453,7 +453,7 @@ func (a *App) GetState() AppState { EffectiveLocale: string(i18n.EffectiveLocale(cfgCopy.Locale)), MissingFontHint: host.CheckMissingLocaleFontsForUI(string(i18n.EffectiveLocale(cfgCopy.Locale)), i18n.EffectiveLocale(cfgCopy.Locale)), - RuntimeCaptureSupported: !needsSetup && !rootStatus.ReadOnly && active != nil && runtimeSupportsCapture(*active), + RuntimeCaptureSupported: !needsSetup && !rootStatus.ReadOnly && active != nil && runtimeAllowsCapture(*active), } } diff --git a/internal/app/create_flow.go b/internal/app/create_flow.go index 7aaa035..b006061 100644 --- a/internal/app/create_flow.go +++ b/internal/app/create_flow.go @@ -186,7 +186,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) { finishTask(err) return fmt.Errorf("record VM driver ownership: %w", err) } - if postSet, ok := reims.PostCreateSetOptsWithCapture(opts, c.SupportsSetCapture()); ok { + if postSet, ok := reims.PostCreateSetOptsWithCapture(opts, c.AllowsSetCapture()); ok { var parts []string if postSet.DiskController != "" { parts = append(parts, "disk="+strings.ToUpper(postSet.DiskController)) diff --git a/internal/app/macos_settings.go b/internal/app/macos_settings.go index dc5a231..4531365 100644 --- a/internal/app/macos_settings.go +++ b/internal/app/macos_settings.go @@ -68,11 +68,11 @@ func (a *App) PreviewCreate(opts reims.CreateOpts) (string, error) { } cfg := a.runtimeConfig() active, err := rt.ResolveActive(&cfg) - return reims.PreviewCreateCommandWithCapture(opts, err == nil && runtimeSupportsCapture(*active)) + return reims.PreviewCreateCommandWithCapture(opts, err == nil && runtimeAllowsCapture(*active)) } -func runtimeSupportsCapture(active rt.Installed) bool { - return reims.ProbeReimsCTLSupportsCapture(active.ReimsCtlPath(), nil) +func runtimeAllowsCapture(active rt.Installed) bool { + return reims.ReimsCTLAllowsSetCapture(active.ReimsCtlPath(), nil) } func (a *App) CreateVM(opts reims.CreateOpts) error { diff --git a/internal/cli/macos_native.go b/internal/cli/macos_native.go index 343890f..2ee753c 100644 --- a/internal/cli/macos_native.go +++ b/internal/cli/macos_native.go @@ -110,7 +110,7 @@ func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in if err := driver.WriteOwnerDriver(createdDir, driver.BuiltinReimsMacOSDriverID); err != nil { return err } - if postSet, ok := reims.PostCreateSetOptsWithCapture(opts, client.SupportsSetCapture()); ok { + if postSet, ok := reims.PostCreateSetOptsWithCapture(opts, client.AllowsSetCapture()); ok { if err := client.Set(ctx, postSet, os.Stdout, os.Stderr); err != nil { fmt.Fprintf(os.Stderr, "Warning: could not apply post-create defaults: %v\n", err) } diff --git a/internal/macos/macosdriver/clone.go b/internal/macos/macosdriver/clone.go index 13e9bba..d186342 100644 --- a/internal/macos/macosdriver/clone.go +++ b/internal/macos/macosdriver/clone.go @@ -178,16 +178,12 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s if src.NetworkMode == "bridge" { network = true } - createOpts := reims.CreateOpts{Name: cloneName, SourceMode: "disk", Disk: overlayPath, DiskMode: "in-place", DiskController: src.DiskController, CPUs: src.CPUs, Memory: src.Memory, Graphics: src.Graphics, GPU: src.GPU, Resolution: src.Resolution, Displays: src.Displays, Audio: &audio, Network: &network, SSHPort: clonePort, Logs: &logs, Start: false} - captureSupported := c.SupportsSetCapture() - if captureSupported { - createOpts.Capture = &src.Capture - } + createOpts := reims.CreateOpts{Name: cloneName, SourceMode: "disk", Disk: overlayPath, DiskMode: "in-place", DiskController: src.DiskController, CPUs: src.CPUs, Memory: src.Memory, Graphics: src.Graphics, GPU: src.GPU, Resolution: src.Resolution, Displays: src.Displays, Capture: &src.Capture, Audio: &audio, Network: &network, SSHPort: clonePort, Logs: &logs, Start: false} if err := c.RegisterCoWClone(ctx, createOpts, stdout, stderr); err != nil { return err } cloneRegistered = true - if postSet, ok := reims.PostCreateSetOptsWithCapture(createOpts, captureSupported); ok { + if postSet, ok := reims.PostCreateSetOptsWithCapture(createOpts, c.AllowsSetCapture()); ok { if err := c.Set(ctx, postSet, stdout, stderr); err != nil { _, _ = fmt.Fprintf(stdout, "Warning: could not apply clone settings: %v\n", err) } diff --git a/internal/macos/reims/capture_compat.go b/internal/macos/reims/capture_compat.go index b392707..128cfa2 100644 --- a/internal/macos/reims/capture_compat.go +++ b/internal/macos/reims/capture_compat.go @@ -28,11 +28,11 @@ var ( captureOption = regexp.MustCompile(`(?m)(?:^|\s)--capture(?:\s|,|=|$)`) ) -// ProbeReimsCTLSupportsCapture checks set --help and caches successful checks -// for the current version of the binary. -func ProbeReimsCTLSupportsCapture(binaryPath string, env []string) bool { +// ReimsCTLAllowsSetCapture keeps the legacy option unless set --help +// successfully confirms that the runtime removed it. +func ReimsCTLAllowsSetCapture(binaryPath string, env []string) bool { ok, err := probeReimsCTLSupportsCapture(binaryPath, env) - return err == nil && ok + return err != nil || ok } func probeReimsCTLSupportsCapture(binaryPath string, env []string) (bool, error) { @@ -76,10 +76,6 @@ func probeReimsCTLSupportsCapture(binaryPath string, env []string) (bool, error) return call.ok, call.err } -func (c *Client) SupportsSetCapture() bool { - return ProbeReimsCTLSupportsCapture(c.Binary, c.Env) -} - -func (c *Client) probeSetCapture() (bool, error) { - return probeReimsCTLSupportsCapture(c.Binary, c.Env) +func (c *Client) AllowsSetCapture() bool { + return ReimsCTLAllowsSetCapture(c.Binary, c.Env) } diff --git a/internal/macos/reims/compat_test.go b/internal/macos/reims/compat_test.go index 6e9fc52..74fe627 100644 --- a/internal/macos/reims/compat_test.go +++ b/internal/macos/reims/compat_test.go @@ -251,10 +251,10 @@ func captureTestClient(t *testing.T, helpMode string) (Client, string) { "REIMS_TEST_CTL_DIR="+dir, "REIMS_TEST_CTL_CAPTURE_HELP="+helpMode)}, dir } -func TestProbeReimsCTLSupportsCapture(t *testing.T) { +func TestReimsCTLAllowsSetCapture(t *testing.T) { for _, path := range []string{"", filepath.Join(t.TempDir(), "missing.exe")} { - if ProbeReimsCTLSupportsCapture(path, nil) { - t.Errorf("probe reported support for %q", path) + if _, err := probeReimsCTLSupportsCapture(path, nil); !os.IsNotExist(err) { + t.Errorf("probe error for %q = %v, want file not found", path, err) } } for _, tc := range []struct { @@ -267,10 +267,10 @@ func TestProbeReimsCTLSupportsCapture(t *testing.T) { } { t.Run(tc.mode, func(t *testing.T) { c, dir := captureTestClient(t, tc.mode) - if got := ProbeReimsCTLSupportsCapture(c.Binary, c.Env); got != tc.want { + if got := ReimsCTLAllowsSetCapture(c.Binary, c.Env); got != tc.want { t.Fatalf("probe = %t, want %t", got, tc.want) } - if got := c.SupportsSetCapture(); got != tc.want { + if got := c.AllowsSetCapture(); got != tc.want { t.Fatalf("cached probe = %t, want %t", got, tc.want) } calls, err := os.ReadFile(filepath.Join(dir, "commands")) @@ -281,13 +281,13 @@ func TestProbeReimsCTLSupportsCapture(t *testing.T) { } t.Run("error", func(t *testing.T) { c, dir := captureTestClient(t, "error") - if c.SupportsSetCapture() { - t.Fatal("unsuccessful probe reported support") + if !c.AllowsSetCapture() { + t.Fatal("unsuccessful probe disabled the legacy option") } - if !ProbeReimsCTLSupportsCapture(c.Binary, append(c.Env, "REIMS_TEST_CTL_CAPTURE_HELP=stdout")) { - t.Fatal("successful probe after failure did not report support") + if ReimsCTLAllowsSetCapture(c.Binary, append(c.Env, "REIMS_TEST_CTL_CAPTURE_HELP=absent")) { + t.Fatal("successful retry did not detect removal") } - if !c.SupportsSetCapture() { + if c.AllowsSetCapture() { t.Fatal("successful retry was not cached") } calls, err := os.ReadFile(filepath.Join(dir, "commands")) @@ -308,7 +308,7 @@ func TestProbeReimsCTLSupportsCaptureConcurrent(t *testing.T) { go func() { ready.Done() <-start - results <- c.SupportsSetCapture() + results <- c.AllowsSetCapture() }() } ready.Wait() @@ -318,7 +318,7 @@ func TestProbeReimsCTLSupportsCaptureConcurrent(t *testing.T) { t.Error("concurrent probe did not report support") } } - if !ProbeReimsCTLSupportsCapture(c.Binary, append(c.Env, "REIMS_TEST_CTL_CAPTURE_HELP=error")) { + if !ReimsCTLAllowsSetCapture(c.Binary, append(c.Env, "REIMS_TEST_CTL_CAPTURE_HELP=absent")) { t.Error("concurrent probe result was not cached") } calls, err := os.ReadFile(filepath.Join(dir, "commands")) @@ -345,15 +345,32 @@ func TestSetSkipsUnsupportedCapture(t *testing.T) { } } +func TestPostCreateKeepsCaptureOffWhenHelpFails(t *testing.T) { + c, dir := captureTestClient(t, "error") + off := false + opts := CreateOpts{Name: "test", DiskController: "ahci", Capture: &off} + postSet, ok := PostCreateSetOptsWithCapture(opts, c.AllowsSetCapture()) + if !ok || postSet.Capture == nil || *postSet.Capture { + t.Fatalf("post-create options = %+v, ok = %t, want capture disabled", postSet, ok) + } + if err := c.Set(t.Context(), postSet, nil, nil); err != nil { + t.Fatal(err) + } + calls, err := os.ReadFile(filepath.Join(dir, "commands")) + if err != nil || string(calls) != "set\t--help\nset\t--help\nset\ttest\t--capture\tfalse\n" { + t.Fatalf("commands = %q, err = %v, want the legacy set after failed probes", calls, err) + } +} + func TestShowCaptureSupported(t *testing.T) { - for _, mode := range []string{"stdout", "absent"} { + for _, mode := range []string{"stdout", "absent", "error"} { t.Run(mode, func(t *testing.T) { c, _ := captureTestClient(t, mode) detail, err := c.Show(t.Context(), "test") if err != nil { t.Fatal(err) } - if want := mode == "stdout"; detail.CaptureSupported != want { + if want := mode != "absent"; detail.CaptureSupported != want { t.Fatalf("capture_supported = %t, want %t", detail.CaptureSupported, want) } }) @@ -407,6 +424,7 @@ func TestHelperProcess(t *testing.T) { case slices.Equal(args, []string{"show", "test"}): fmt.Println("test\n state stopped") case slices.Equal(args, []string{"set", "test", "--cpus", "4"}): + case helpMode == "error" && slices.Equal(args, []string{"set", "test", "--capture", "false"}): default: t.Fatalf("unexpected capture test command %q", args) } diff --git a/internal/macos/reims/reims.go b/internal/macos/reims/reims.go index b5c7ea6..d79dbac 100644 --- a/internal/macos/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -764,7 +764,7 @@ func (c *Client) Show(ctx context.Context, name string) (VMDetail, error) { return VMDetail{}, fmt.Errorf("reims-ctl show %s: %w (%s)", name, err, strings.TrimSpace(errBuf.String())) } d := ParseShow(name, out.String()) - d.CaptureSupported = c.SupportsSetCapture() + d.CaptureSupported = c.AllowsSetCapture() applyBorderlessResolutionFallback(&d) return d, nil } @@ -826,12 +826,9 @@ func (c *Client) Create(ctx context.Context, o CreateOpts, stdout, stderr io.Wri } func (c *Client) Set(ctx context.Context, o SetOpts, stdout, stderr io.Writer) error { - skipCapture := false - if o.Capture != nil { - if supported, probeErr := c.probeSetCapture(); probeErr == nil && !supported { - skipCapture = true - o.Capture = nil - } + skipCapture := o.Capture != nil && !c.AllowsSetCapture() + if skipCapture { + o.Capture = nil } args, err := BuildSetArgs(o) if err != nil {