Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

Detect Windows optional features without elevation (#5745)

injaneity4179ea2fd562
diff --git a/apps/cua-spaces-desktop/src/bridge/spaces.ts b/apps/cua-spaces-desktop/src/bridge/spaces.ts
index 2fcfa4f6e5..494da6f978 100644
--- a/apps/cua-spaces-desktop/src/bridge/spaces.ts
+++ b/apps/cua-spaces-desktop/src/bridge/spaces.ts
@@ -8,7 +8,7 @@
import type { Native } from "../native/load";
import type { AppCreateSpaceArgs, AppSpace, AppWizardEnv, SpaceCreateProgress } from "../native/generated/index";
import { AppModel } from "../model/app-model";
-import type { RuntimeFix } from "../model/windows-runtime";
+import { RUNTIME_FIX_ACTIONS, type RuntimeFix, type RuntimeFixAction } from "../model/windows-runtime";
import { createNetworks, kindOf, osOf, runtimeOf } from "../model/backend";
import { isCancelled } from "../model/errors";
import { bool, string } from "./args";
@@ -133,9 +133,9 @@ export function spacesMethods(ctx: BridgeContext): Handlers {
},
"spaces.fixRuntime": (args) => {
const action = string(args, "action");
- if (action !== "install-docker" && action !== "start-docker" && action !== "restart-app") throw Failure.badArgs("action: install-docker | start-docker | restart-app");
+ if (!(RUNTIME_FIX_ACTIONS as readonly string[]).includes(action)) throw Failure.badArgs(`action: ${RUNTIME_FIX_ACTIONS.join(" | ")}`);
if (!model.windowsRuntime && !model.linuxRuntime) throw Failure.unsupported("no runtime fix on this system");
- model.fixRuntime(action);
+ model.fixRuntime(action as RuntimeFixAction);
return null;
},
// `{config, pendingId, os?, notifyWhenReady?}`. The create belongs to the app, not to the window:
diff --git a/apps/cua-spaces-desktop/src/model/windows-runtime.test.ts b/apps/cua-spaces-desktop/src/model/windows-runtime.test.ts
index 0b0b19abb2..76d4775057 100644
--- a/apps/cua-spaces-desktop/src/model/windows-runtime.test.ts
+++ b/apps/cua-spaces-desktop/src/model/windows-runtime.test.ts
@@ -9,6 +9,7 @@ import {
currentUser,
installFailedText,
parseInstallResult,
+ parseFeatures,
parseVirtualization,
signedByDocker,
windowsRuntimeAdvice,
@@ -16,7 +17,10 @@ import {
type WindowsSystem,
} from "./windows-runtime";
-const CLEAN: WindowsRuntimeFacts = { dockerInstalled: false, dockerRunning: false, virtualization: "on", restartPending: false };
+const CLEAN: WindowsRuntimeFacts = {
+ dockerInstalled: false, dockerRunning: false, virtualization: "on", restartPending: false,
+ features: { editionId: null, virtualMachinePlatform: "unknown", hypervisorPlatform: "unknown", subsystemLinux: "unknown" },
+};
const IDLE = { kind: "idle" } as const;
describe("windowsRuntimeAdvice", () => {
@@ -69,6 +73,17 @@ describe("windowsRuntimeAdvice", () => {
});
describe("probe parsing", () => {
+ it("reads edition and feature states independently, without treating absent features as disabled", () => {
+ for (const [input, expected] of [[1, "enabled"], [2, "disabled"], [3, "unknown"], [4, "unknown"], [null, "unknown"], ["2", "unknown"], [0, "unknown"]] as const) {
+ expect(parseFeatures(JSON.stringify({ editionId: "Core", virtualMachinePlatform: input, hypervisorPlatform: input, subsystemLinux: input }))).toEqual({
+ editionId: "Core", virtualMachinePlatform: expected, hypervisorPlatform: expected, subsystemLinux: expected,
+ });
+ }
+ expect(parseFeatures('{"editionId":"Core"}')).toEqual({ ...CLEAN.features, editionId: "Core" });
+ expect(parseFeatures('{"hypervisorPlatform":2}')).toEqual({ ...CLEAN.features, hypervisorPlatform: "disabled" });
+ for (const input of ["", "not JSON", "null", "[]", "42", '{"editionId":12}']) expect(parseFeatures(input)).toEqual(CLEAN.features);
+ });
+
it("counts a running hypervisor as virtualization on (it hides the firmware flag)", () => {
expect(parseVirtualization("True|False")).toBe("on");
expect(parseVirtualization("False|True")).toBe("on");
@@ -108,6 +123,8 @@ function fakeSystem(state: {
installed?: boolean;
running?: boolean;
hv?: string;
+ features?: string;
+ featureFailure?: "exit" | "throw";
rebootPending?: boolean;
signature?: string;
result?: string;
@@ -120,6 +137,11 @@ function fakeSystem(state: {
running: async () => state.running ?? false,
async powershell(script) {
ran.push(script);
+ if (script.includes("Win32_OptionalFeature")) {
+ if (state.featureFailure === "throw") throw new Error("unavailable");
+ if (state.featureFailure === "exit") return { code: 1, stdout: state.features ?? "", stderr: "unavailable" };
+ if (state.features !== undefined) return { code: 0, stdout: state.features, stderr: "" };
+ }
if (script.includes("Win32_ComputerSystem")) return { code: 0, stdout: state.hv ?? "True|True", stderr: "" };
if (script.includes("RebootPending")) return { code: 0, stdout: state.rebootPending ? "pending" : "clear", stderr: "" };
if (script.includes("Get-AuthenticodeSignature")) return { code: 0, stdout: state.signature ?? "Valid|CN=Docker Inc, O=Docker Inc", stderr: "" };
@@ -150,6 +172,84 @@ function fakeSystem(state: {
const settle = () => new Promise((r) => setTimeout(r, 0));
describe("WindowsRuntime", () => {
+ it("offers Windows Features for disabled Virtual Machine Platform on Home", async () => {
+ const f = fakeSystem({ installed: true, features: JSON.stringify({ editionId: "Core", virtualMachinePlatform: 2 }) });
+ const a = await new WindowsRuntime(f.sys, "C:\\tmp").advice();
+ expect(a.reason).toContain("Virtual Machine Platform");
+ expect(a.fix).toMatchObject({ action: "open-windows-features", label: "Open Windows Features", busy: false, termsUrl: null });
+ expect(a.fix?.note).toContain("restart this PC");
+ expect(JSON.stringify(a)).not.toContain("Hyper-V");
+ });
+
+ it("refreshes feature facts and preserves Docker, restart and active-install precedence across editions", async () => {
+ for (const editionId of ["Core", "CoreSingleLanguage", "Professional", "Enterprise"]) {
+ for (const feature of ["virtualMachinePlatform", "hypervisorPlatform", "subsystemLinux"]) {
+ const state = { installed: true, features: JSON.stringify({ editionId, [feature]: 2 }) };
+ const f = fakeSystem(state);
+ const w = new WindowsRuntime(f.sys, "C:\\tmp");
+ expect((await w.facts()).features).toMatchObject({ editionId, [feature]: "disabled" });
+ const a = await w.advice();
+ expect(a.fix?.action).toBe(feature === "hypervisorPlatform" ? "start-docker" : "open-windows-features");
+ if (feature === "subsystemLinux") expect(a.reason).toContain("Windows Subsystem for Linux");
+ const facts = await w.facts();
+ const alternatives = [
+ windowsRuntimeAdvice({ ...facts, dockerInstalled: false }, IDLE, 0),
+ windowsRuntimeAdvice({ ...facts, restartPending: true }, IDLE, 0),
+ windowsRuntimeAdvice(facts, { kind: "downloading", percent: 10 }, 0),
+ windowsRuntimeAdvice(facts, { kind: "installing" }, 0),
+ ] as const;
+ expect(alternatives[0].fix?.action).toBe("install-docker");
+ expect(alternatives[1].reason).toMatch(/^Restart this PC/);
+ expect(alternatives[1].fix).toBeNull();
+ expect(alternatives.slice(2).every((a) => a.fix?.busy)).toBe(true);
+ expect(JSON.stringify([a, ...alternatives])).not.toContain("Hyper-V");
+ state.features = JSON.stringify({ editionId, [feature]: 1 });
+ expect((await w.facts()).features).toMatchObject({ [feature]: "enabled" });
+ expect((await w.advice()).fix?.action).toBe("start-docker");
+ }
+ }
+ });
+
+ it("returns unknown facts on failed or malformed probes", async () => {
+ for (const featureFailure of [undefined, "exit", "throw"] as const) {
+ const f = fakeSystem({ installed: true, features: "invalid JSON", featureFailure });
+ const w = new WindowsRuntime(f.sys, "C:\\tmp");
+ expect((await w.facts()).features).toEqual(CLEAN.features);
+ expect((await w.advice()).fix?.action).toBe("start-docker");
+ }
+ });
+
+ it("opens only Windows Features without starting an install or changing phase", async () => {
+ const f = fakeSystem({ installed: true });
+ const w = new WindowsRuntime(f.sys, "C:\\tmp");
+ w.run("open-windows-features");
+ await settle();
+ expect(f.ran).toEqual(["launch optionalfeatures.exe"]);
+ f.sys.running = async () => false;
+ expect((await w.advice()).fix?.action).toBe("start-docker");
+ });
+
+ it("skips feature probing while a download or install is active", async () => {
+ const f = fakeSystem({ features: '{"virtualMachinePlatform":2}' });
+ let finishDownload!: () => void;
+ let finishInstall!: () => void;
+ f.sys.download = () => new Promise<void>((resolve) => { finishDownload = resolve; });
+ const powershell = f.sys.powershell;
+ f.sys.powershell = (script, ms) => script.includes("-Verb RunAs") ? new Promise((resolve) => { finishInstall = () => resolve({ code: 0, stdout: "", stderr: "" }); }) : powershell(script, ms);
+ const w = new WindowsRuntime(f.sys, "C:\\tmp");
+ expect((await w.facts()).features.virtualMachinePlatform).toBe("disabled");
+ f.ran.length = 0;
+ w.run("install-docker");
+ expect((await w.advice()).fix?.label).toContain("Downloading");
+ expect(f.ran.some((s) => s.includes("Win32_OptionalFeature"))).toBe(false);
+ finishDownload();
+ await settle();
+ expect((await w.advice()).fix?.label).toContain("Installing");
+ expect(f.ran.some((s) => s.includes("Win32_OptionalFeature"))).toBe(false);
+ finishInstall();
+ await settle();
+ });
+
it("installs, then starts Docker Desktop when no restart is needed", async () => {
const f = fakeSystem({ result: "0|False|True" });
const w = new WindowsRuntime(f.sys, "C:\\tmp", () => 1_000);
diff --git a/apps/cua-spaces-desktop/src/model/windows-runtime.ts b/apps/cua-spaces-desktop/src/model/windows-runtime.ts
index 33dbd9ea87..e11c7ef374 100644
--- a/apps/cua-spaces-desktop/src/model/windows-runtime.ts
+++ b/apps/cua-spaces-desktop/src/model/windows-runtime.ts
@@ -29,7 +29,23 @@ import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
/** What the page's fix button does (`spaces.fixRuntime {action}`). */
-export type RuntimeFixAction = "install-docker" | "start-docker" | "restart-app";
+export const RUNTIME_FIX_ACTIONS = ["install-docker", "start-docker", "restart-app", "open-windows-features"] as const;
+export type RuntimeFixAction = (typeof RUNTIME_FIX_ACTIONS)[number];
+
+type ContractAction = import("../../../cua-spaces-web/src/bridge/contracts/new-space").RuntimeFixAction;
+type Assert<T extends true> = T;
+export type RuntimeFixActionsMatch = Assert<
+ [Exclude<RuntimeFixAction, ContractAction> | Exclude<ContractAction, RuntimeFixAction>] extends [never] ? true : false
+>;
+
+export type FeatureState = "enabled" | "disabled" | "unknown";
+
+export interface WindowsFeatures {
+ editionId: string | null;
+ virtualMachinePlatform: FeatureState;
+ hypervisorPlatform: FeatureState;
+ subsystemLinux: FeatureState;
+}
/** A step the page can offer next to the "no local runtime" reason. */
export interface RuntimeFix {
@@ -55,6 +71,7 @@ export interface WindowsRuntimeFacts {
virtualization: "on" | "off" | "unknown";
/** Windows waits for a restart to finish turning on WSL 2 / the install. */
restartPending: boolean;
+ features: WindowsFeatures;
}
/** Where a fix the app started is now. */
@@ -124,6 +141,22 @@ export function windowsRuntimeAdvice(facts: WindowsRuntimeFacts, phase: FixPhase
fix: installFix(),
};
}
+ const disabled = [
+ facts.features.virtualMachinePlatform === "disabled" ? "Virtual Machine Platform" : null,
+ facts.features.subsystemLinux === "disabled" ? "Windows Subsystem for Linux" : null,
+ ].filter(Boolean);
+ if (disabled.length) {
+ return {
+ reason: `Windows features are turned off: ${disabled.join(", ")}.`,
+ fix: {
+ action: "open-windows-features",
+ label: "Open Windows Features",
+ note: "Turn on the listed features, then restart this PC and open Cua Spaces again.",
+ busy: false,
+ termsUrl: null,
+ },
+ };
+ }
if (facts.dockerRunning || phase.kind === "starting") {
const waited = phase.kind === "starting" ? now - phase.since : 0;
return {
@@ -235,13 +268,14 @@ export class WindowsRuntime {
async facts(): Promise<WindowsRuntimeFacts> {
const exe = dockerDesktopExe();
- const [dockerInstalled, dockerRunning, virtualization, restartPending] = await Promise.all([
+ const [dockerInstalled, dockerRunning, virtualization, restartPending, features] = await Promise.all([
this.sys.exists(exe),
this.sys.running("Docker Desktop.exe"),
this.readVirtualization(),
this.restartAsked ? Promise.resolve(true) : this.readRestartPending(),
+ this.phase.kind === "downloading" || this.phase.kind === "installing" ? Promise.resolve(parseFeatures("")) : this.readFeatures(),
]);
- return { dockerInstalled, dockerRunning, virtualization, restartPending };
+ return { dockerInstalled, dockerRunning, virtualization, restartPending, features };
}
/** The advice now; a finished start (the engine answered) is the caller's to see. */
@@ -260,14 +294,25 @@ export class WindowsRuntime {
/** Runs `action` in the background; the page sees its progress in the options. */
run(action: RuntimeFixAction): void {
if (this.phase.kind === "downloading" || this.phase.kind === "installing") return;
- if (action === "restart-app") return;
- if (action === "start-docker") {
- this.start();
- return;
+ switch (action) {
+ case "restart-app":
+ return;
+ case "start-docker":
+ this.start();
+ return;
+ case "open-windows-features":
+ this.sys.launch("optionalfeatures.exe");
+ return;
+ case "install-docker":
+ void this.install().catch((e: unknown) => {
+ this.phase = { kind: "failed", message: installFailedText(e) };
+ });
+ return;
+ default: {
+ const exhaustive: never = action;
+ throw new Error(`Unknown runtime fix: ${exhaustive}`);
+ }
}
- void this.install().catch((e: unknown) => {
- this.phase = { kind: "failed", message: installFailedText(e) };
- });
}
private start(): void {
@@ -316,6 +361,27 @@ export class WindowsRuntime {
this.start();
}
+ private async readFeatures(): Promise<WindowsFeatures> {
+ const r = await this.sys
+ .powershell(
+ `$result = @{}
+try { $result.editionId = (Get-ItemProperty -LiteralPath 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' -Name EditionID -ErrorAction Stop).EditionID } catch {}
+try {
+ Get-CimInstance Win32_OptionalFeature -Filter "Name='VirtualMachinePlatform' OR Name='HypervisorPlatform' OR Name='Microsoft-Windows-Subsystem-Linux'" -ErrorAction Stop | ForEach-Object {
+ switch ($_.Name) {
+ 'VirtualMachinePlatform' { $result.virtualMachinePlatform = $_.InstallState }
+ 'HypervisorPlatform' { $result.hypervisorPlatform = $_.InstallState }
+ 'Microsoft-Windows-Subsystem-Linux' { $result.subsystemLinux = $_.InstallState }
+ }
+ }
+} catch {}
+ConvertTo-Json -InputObject $result -Compress`,
+ 15_000,
+ )
+ .catch(() => null);
+ return parseFeatures(r?.code === 0 ? r.stdout : "");
+ }
+
private async readVirtualization(): Promise<WindowsRuntimeFacts["virtualization"]> {
if (this.virtualization) return this.virtualization;
const r = await this.sys
@@ -349,6 +415,21 @@ export function parseVirtualization(stdout: string): WindowsRuntimeFacts["virtua
return "unknown";
}
+export function parseFeatures(stdout: string): WindowsFeatures {
+ let raw: Record<string, unknown> = {};
+ try {
+ const value: unknown = JSON.parse(stdout);
+ if (value && typeof value === "object" && !Array.isArray(value)) raw = value as Record<string, unknown>;
+ } catch {}
+ const state = (value: unknown): FeatureState => (value === 1 ? "enabled" : value === 2 ? "disabled" : "unknown");
+ return {
+ editionId: typeof raw.editionId === "string" ? raw.editionId : null,
+ virtualMachinePlatform: state(raw.virtualMachinePlatform),
+ hypervisorPlatform: state(raw.hypervisorPlatform),
+ subsystemLinux: state(raw.subsystemLinux),
+ };
+}
+
export function signedByDocker(stdout: string): boolean {
const [status, subject = ""] = stdout.trim().split("|");
return status === "Valid" && /\bO="?Docker Inc/i.test(subject);
diff --git a/apps/cua-spaces-desktop/test/bridge-registry.test.ts b/apps/cua-spaces-desktop/test/bridge-registry.test.ts
index 8e7350b3df..9dd70c3d2c 100644
--- a/apps/cua-spaces-desktop/test/bridge-registry.test.ts
+++ b/apps/cua-spaces-desktop/test/bridge-registry.test.ts
@@ -42,6 +42,17 @@ function registryOf(ctx = stubContext()): BridgeRegistry {
}
describe("the method table", () => {
+ it("routes Windows Features fixes and rejects arbitrary runtime actions", async () => {
+ const ctx = stubContext();
+ const actions: string[] = [];
+ Object.assign(ctx.model, { windowsRuntime: {}, fixRuntime: (action: string) => actions.push(action) });
+ const r = registryOf(ctx);
+ expect(await r.dispatch({ id: "fix", method: "spaces.fixRuntime", args: { action: "open-windows-features" } })).toEqual({ id: "fix", ok: true, result: null });
+ expect(actions).toEqual(["open-windows-features"]);
+ expect(await r.dispatch({ id: "bad", method: "spaces.fixRuntime", args: { action: "reboot" } })).toMatchObject({ ok: false, error: { code: "bad_args" } });
+ expect(actions).toEqual(["open-windows-features"]);
+ });
+
it("lists the SwiftUI host's methods in its order", () => {
expect([...METHODS]).toEqual(swiftMethods());
});
diff --git a/apps/cua-spaces-web/src/bridge/contracts/new-space.ts b/apps/cua-spaces-web/src/bridge/contracts/new-space.ts
index 956a533724..b9980551b4 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/new-space.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/new-space.ts
@@ -56,7 +56,7 @@ export interface LocalStatus {
}
/** `spaces.fixRuntime`'s actions. */
-export type RuntimeFixAction = "install-docker" | "start-docker" | "restart-app";
+export type RuntimeFixAction = "install-docker" | "start-docker" | "restart-app" | "open-windows-features";
/** A step the host offers next to "no local runtime" (`LocalStatus.fix`). */
export interface RuntimeFix {
diff --git a/libs/cua/crates/cua-vmm/src/preflight.rs b/libs/cua/crates/cua-vmm/src/preflight.rs
index a662e8c452..6179326b5b 100644
--- a/libs/cua/crates/cua-vmm/src/preflight.rs
+++ b/libs/cua/crates/cua-vmm/src/preflight.rs
@@ -74,6 +74,19 @@ pub async fn gather(req: &Request) -> Facts {
/// its local network gets `patience` for someone to answer macOS's prompt
/// (the probe's own connect raises it) before it counts as blocked.
pub async fn gather_waiting(req: &Request, patience: std::time::Duration) -> Facts {
+ let gap = if req.runs == Runs::Vm {
+ virtualization(req.host).await
+ } else {
+ None
+ };
+ gather_with_virtualization(req, gap, patience).await
+}
+
+async fn gather_with_virtualization(
+ req: &Request,
+ gap: Option<VirtGap>,
+ patience: std::time::Duration,
+) -> Facts {
let mut facts = Facts {
free_bytes: crate::disk::space(&crate::host::cua_home())
.ok()
@@ -84,7 +97,7 @@ pub async fn gather_waiting(req: &Request, patience: std::time::Duration) -> Fac
facts.engine = engine().await;
}
if req.runs == Runs::Vm {
- facts.virtualization = virtualization(req.host);
+ facts.virtualization = gap;
} else if req.host == Host::Macos && mac_unsupported() && linux_needs_builtin_runtime().await {
// A Linux container here runs in the built-in runtime's VM.
facts.virtualization = Some(VirtGap::MacUnsupported);
@@ -140,6 +153,7 @@ fn qemu_issue(req: &Request, installed: impl FnOnce() -> bool) -> Option<Issue>
/// every app and the CLI read it from one place.
pub async fn report() -> BTreeMap<String, Vec<Issue>> {
let mut out = BTreeMap::new();
+ let gap = virtualization(Host::current()).await;
for (name, guest, runs) in [
("linux_container", Guest::Linux, Runs::Container),
("linux_vm", Guest::Linux, Runs::Vm),
@@ -153,7 +167,7 @@ pub async fn report() -> BTreeMap<String, Vec<Issue>> {
// The image's real size is unknown here and it may already be on
// disk, so a guess must not block a create that would work: the
// create's own disk guards decide.
- let mut facts = gather(&req).await;
+ let mut facts = gather_with_virtualization(&req, gap, std::time::Duration::ZERO).await;
facts.free_bytes = None;
out.insert(name.to_string(), evaluate(&req, &facts));
}
@@ -183,11 +197,9 @@ async fn engine() -> Engine {
}
}
-fn virtualization(host: Host) -> Option<VirtGap> {
+async fn virtualization(host: Host) -> Option<VirtGap> {
match host {
- Host::Windows => {
- windows_hypervisor_platform_off().then_some(VirtGap::HypervisorPlatformOff)
- }
+ Host::Windows => windows_hypervisor_platform().await,
Host::Linux => match crate::host::kvm_usable() {
Ok(()) => None,
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
@@ -216,17 +228,30 @@ async fn linux_needs_builtin_runtime() -> bool {
}
}
-/// QEMU's `whpx` accelerator needs the Windows Hypervisor Platform feature,
-/// whose library (`WinHvPlatform.dll`) is only in System32 when it is on.
-fn windows_hypervisor_platform_off() -> bool {
+async fn windows_hypervisor_platform() -> Option<VirtGap> {
if !cfg!(windows) {
- return false;
+ return None;
+ }
+ let mut command = tokio::process::Command::new("powershell.exe");
+ command.args([
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_OptionalFeature -Filter \"Name='HypervisorPlatform'\" | Select-Object -ExpandProperty InstallState | ConvertTo-Json -Compress",
+ ]).kill_on_drop(true);
+ let output = tokio::time::timeout(std::time::Duration::from_secs(5), command.output())
+ .await
+ .ok()?
+ .ok()?;
+ if !output.status.success() {
+ return None;
}
- let root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
- !std::path::Path::new(&root)
- .join("System32")
- .join("WinHvPlatform.dll")
- .exists()
+ parse_hypervisor_platform(&String::from_utf8_lossy(&output.stdout))
+}
+
+fn parse_hypervisor_platform(stdout: &str) -> Option<VirtGap> {
+ (serde_json::from_str::<u32>(stdout.trim()).ok() == Some(2))
+ .then_some(VirtGap::HypervisorPlatformOff)
}
/// Whether this process is blocked from the local network the macOS VMs
@@ -252,6 +277,35 @@ async fn local_network_blocked(patience: std::time::Duration) -> bool {
mod tests {
use super::*;
+ #[test]
+ fn optional_feature_state_only_blocks_vms_when_disabled() {
+ use pf::{FixAction, IssueKind, Pane};
+ let mut req = request(Guest::Windows, Runs::Vm, None);
+ req.host = Host::Windows;
+ for output in ["1", "2", "3", "4", "null", "", "invalid", "\"2\"", "[2]"] {
+ let facts = Facts {
+ virtualization: parse_hypervisor_platform(output),
+ ..Default::default()
+ };
+ let issues = pf::evaluate(&req, &facts);
+ if output == "2" {
+ assert_eq!(issues.len(), 1);
+ assert_eq!(issues[0].kind, IssueKind::VirtualizationUnavailable);
+ assert_eq!(
+ issues[0].fix.as_ref().unwrap().action,
+ FixAction::OpenSettings(Pane::WindowsFeatures)
+ );
+ assert!(issues[0].message.contains("restart"));
+ } else {
+ assert!(issues.is_empty(), "{output}");
+ }
+ let mut container = req;
+ container.guest = Guest::Linux;
+ container.runs = Runs::Container;
+ assert!(pf::evaluate(&container, &facts).is_empty());
+ }
+ }
+
#[test]
fn estimates_grow_with_the_guest() {
assert!(estimate(Guest::Macos, Runs::Vm) > estimate(Guest::Windows, Runs::Vm));