Skip to content

armgit / WSM

Public Imported from GitHub
0

Run macOS applications on your Windows desktop, with a background runtime and integrated app windows.

C++

Prepare WSM preview repository

mxhm11cr6f6f22352e9a
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..045b8da
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+*.sh text eol=lf
+*.plist text eol=lf
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..c82543f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,69 @@
+# WSM — Windows Subsystem for macOS
+# Keep proprietary Apple software, large images, caches, and build artifacts out of git.
+
+upstream/
+third_party/
+toolchains/
+cache/
+build/
+dist/
+logs/
+
+runtime/images/
+runtime/snapshots/
+runtime/apps/
+runtime/reims-ctl/
+runtime/config/local*.json
+
+*.dmg
+*.pkg
+*.iso
+*.qcow2
+*.raw
+*.img
+*.vmdk
+*.vhdx
+*.bin
+*.fd
+*.rom
+*.pdb
+*.ilk
+*.obj
+*.o
+*.lib
+*.a
+*.dll
+*.exe
+*.msi
+
+# Node / Electron / Web UI
+node_modules/
+src/wsm-manager/dist/
+src/wsm-manager/out/
+
+# Python
+__pycache__/
+*.pyc
+.venv/
+
+# IDE
+.vs/
+.vscode/
+*.user
+
+# Per-machine runtime state and secrets (guest SSH key and password), never committed.
+runtime/base/
+runtime/config/guest/
+runtime/config/license-acceptance.json
+runtime/config/runtime-ready.json
+runtime/config/apps.json
+
+# Per-machine runtime state written by wsmd
+runtime/config/recent-apps.txt
+runtime/config/setup-cleaned
+runtime/config/compact-*
+runtime/config/no-autopause
+runtime/config/share-token
+runtime/config/share-off
+runtime/config/hidden-apps.txt
+runtime/config/setup-running
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 0000000..70ec145
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,24 @@
+cmake_minimum_required(VERSION 3.25)
+project(WSM VERSION 0.1.0 LANGUAGES C CXX)
+
+set(CMAKE_CXX_STANDARD 20)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+set(CMAKE_CXX_EXTENSIONS OFF)
+
+if(MSVC)
+ add_compile_options(/W4 /utf-8 /EHsc /MP)
+ add_compile_definitions(_CRT_SECURE_NO_WARNINGS NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)
+endif()
+
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
+set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib")
+
+add_subdirectory(src/wsm-proto)
+add_subdirectory(src/wsm-core)
+add_subdirectory(src/wsm-compositor)
+add_subdirectory(src/wsm-services)
+add_subdirectory(src/wsm-runtime)
+
+enable_testing()
+add_subdirectory(tests)
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..265761d
--- /dev/null
+++ b/README.md
@@ -0,0 +1,134 @@
+<p align="center"><img src="assets/branding/wsm-icon.png" width="128" alt="WSM icon"></p>
+<h1 align="center">WSM</h1>
+<p align="center"><strong>Windows Subsystem for macOS</strong><br>Like WSL — but for macOS apps.</p>
+<p align="center"><img src="assets/branding/release-badge.svg" alt="0.2.0 preview"> <img src="assets/branding/platform-badge.svg" alt="Windows x64"> <img src="assets/branding/runtime-badge.svg" alt="macOS Tahoe"></p>
+
+WSM brings macOS applications to your Windows desktop. Inspired by the convenience of WSL, it manages a virtualized macOS runtime in the background and presents supported apps in their own windows alongside your Windows applications.
+
+After setup, add an app through the WSM library or open a supported Mac installer from File Explorer. WSM integrates app windows with the Windows taskbar, offers Start menu and desktop shortcuts, and provides shared clipboard and Windows drive access. The runtime can pause when idle and resume when needed.
+
+> **Preview:** WSM is under development. App compatibility and functionality vary, and some integrations are still being improved.
+
+[Getting started](#getting-started) · [Features](#features) · [Screenshots](#screenshots) · [Performance](#performance) · [How it works](#how-it-works) · [FAQ](#faq)
+
+## See it running
+
+![Safari on the Windows desktop](assets/screenshots/s1.png)
+
+### Safari on Windows
+
+[![Animated preview of Safari on the Windows desktop](assets/videos/safari-preview.gif)](assets/videos/safari.mp4)
+
+[Watch the full Safari video](assets/videos/safari.mp4)
+
+### WSM App Library
+
+[![Animated preview of the WSM app library](assets/videos/library-preview.gif)](assets/videos/library.mp4)
+
+[Watch the full library video](assets/videos/library.mp4)
+
+## Features
+
+- **Individual app windows** — macOS applications appear alongside Windows applications, with their own taskbar icons.
+- **App library and installation** — manage apps from WSM or open supported `.dmg`, `.pkg`, and `.app` files.
+- **GPU acceleration** — a virtual GPU exposes Metal support to the macOS runtime.
+- **Desktop integration** — shortcuts, keyboard mapping, clipboard sharing, and access to Windows drives.
+- **Background runtime** — WSM manages the runtime and can pause it when inactive.
+
+## Getting started
+
+### Requirements
+
+- Windows 10 (21H2 or newer) or Windows 11 on x64.
+- Hardware virtualization enabled and Windows Hypervisor Platform available.
+- 6 GB RAM minimum; more memory is recommended for multitasking.
+- A Vulkan-capable GPU; an SSD and sufficient free disk space for macOS are recommended.
+- An internet connection for initial setup.
+
+### Installation
+
+1. Download `WSM-Setup-0.2.0.exe` from the release when it becomes available.
+2. Run the installer and choose where to install WSM.
+3. Open WSM and follow the setup wizard to prepare the macOS runtime.
+4. Add a supported app or choose a built-in app from the library, then launch it from WSM or its shortcut.
+
+The WSM package does not include a macOS disk image; setup downloads macOS from Apple. The first launch after a full shutdown takes longer than launching an app when the runtime is already running.
+
+## Screenshots
+
+**Mac App Store on the Windows desktop**
+
+![Mac App Store on the full Windows desktop](assets/screenshots/s2.png)
+
+**Safari on the Windows desktop**
+
+![Safari on the full Windows desktop](assets/screenshots/s1.png)
+
+## Performance
+
+Example measurements from a Windows 11 system with the WSM runtime on an SSD:
+
+| Measurement | Result |
+| --- | --- |
+| Cold boot to ready | 47–49 seconds |
+| Resume from idle and open an app | Around 2.5 seconds |
+| Warm app launch to first paint | Around 1.4–2.4 seconds |
+| Compacted runtime disk | 18.7 GB |
+
+Results depend on hardware, storage, app, and configuration. See [performance notes](docs/PERFORMANCE.md) for more context.
+
+## How it works
+
+WSM uses a virtualized macOS environment with hardware acceleration. Its host service manages the runtime, tracks macOS windows and forwards their contents and input to individual Windows windows. The manager provides setup and the app library; guest-side services handle application integration and shared resources.
+
+```text
+Windows desktop & WSM Manager
+ ↓
+Host service & window compositor
+ ↓
+Virtualized macOS runtime & guest services
+ ↓
+macOS applications
+```
+
+## Project structure
+
+- `src/wsm-core` — host checks and runtime management.
+- `src/wsm-runtime` — background service, app management, setup and streaming.
+- `src/wsm-compositor` — Windows window composition.
+- `src/wsm-manager` — setup wizard and app library interface.
+- `src/wsm-guest` and `src/wsm-guest-agent` — guest-side scripts and integration.
+- `src/wsm-services` and `src/wsm-proto` — services and shared protocol definitions.
+- `tests` — core tests; `packaging` — release packaging.
+
+## FAQ
+
+### Is WSM a virtual machine?
+
+WSM uses a virtualized macOS runtime behind the scenes. Its goal is to integrate individual applications into your Windows workflow, rather than require you to work inside a separate desktop.
+
+### Will every Mac app work?
+
+Compatibility varies with the app, its architecture, and its requirements. WSM is a preview, and some applications or integrations may not work yet.
+
+### Can I access Windows files?
+
+WSM exposes Windows drives inside macOS through `~/Windows`. An application may ask for permission to access a shared volume.
+
+### Why is the first launch slower?
+
+The macOS runtime needs to start after a full shutdown. Opening an app while it is already running or resuming from idle is generally faster. An SSD is recommended.
+
+## Roadmap
+
+- Mirror the macOS menu bar into app windows.
+- Improve application compatibility and desktop integration.
+- Explore a lighter runtime mode.
+
+## Building from source
+
+The native components use C++20, CMake, MSVC and WebView2. The current build configuration also references development-machine paths and separately acquired dependencies; it needs adjustment before it is portable. The release packaging script expects a prepared runtime and build outputs.
+
+## Acknowledgments
+
+WSM builds on work from QEMU, reims-vgpu, OpenCore, EDK2 and other upstream projects. macOS and related marks belong to Apple Inc.; Windows belongs to Microsoft Corporation. WSM is an independent project and is not affiliated with either company.
diff --git a/assets/brand/wsm-1024.png b/assets/brand/wsm-1024.png
new file mode 100644
index 0000000..013a2db
Binary files /dev/null and b/assets/brand/wsm-1024.png differ
diff --git a/assets/brand/wsm-128.png b/assets/brand/wsm-128.png
new file mode 100644
index 0000000..4fa10ba
Binary files /dev/null and b/assets/brand/wsm-128.png differ
diff --git a/assets/brand/wsm-16.png b/assets/brand/wsm-16.png
new file mode 100644
index 0000000..e30a7e1
Binary files /dev/null and b/assets/brand/wsm-16.png differ
diff --git a/assets/brand/wsm-24.png b/assets/brand/wsm-24.png
new file mode 100644
index 0000000..306480a
Binary files /dev/null and b/assets/brand/wsm-24.png differ
diff --git a/assets/brand/wsm-256.png b/assets/brand/wsm-256.png
new file mode 100644
index 0000000..4c32998
Binary files /dev/null and b/assets/brand/wsm-256.png differ
diff --git a/assets/brand/wsm-32.png b/assets/brand/wsm-32.png
new file mode 100644
index 0000000..7b12698
Binary files /dev/null and b/assets/brand/wsm-32.png differ
diff --git a/assets/brand/wsm-48.png b/assets/brand/wsm-48.png
new file mode 100644
index 0000000..950076a
Binary files /dev/null and b/assets/brand/wsm-48.png differ
diff --git a/assets/brand/wsm-64.png b/assets/brand/wsm-64.png
new file mode 100644
index 0000000..d190e66
Binary files /dev/null and b/assets/brand/wsm-64.png differ
diff --git a/assets/brand/wsm-source.webp b/assets/brand/wsm-source.webp
new file mode 100644
index 0000000..c401170
Binary files /dev/null and b/assets/brand/wsm-source.webp differ
diff --git a/assets/brand/wsm.ico b/assets/brand/wsm.ico
new file mode 100644
index 0000000..be5dccc
Binary files /dev/null and b/assets/brand/wsm.ico differ
diff --git a/assets/branding/platform-badge.svg b/assets/branding/platform-badge.svg
new file mode 100644
index 0000000..6d88cdf
--- /dev/null
+++ b/assets/branding/platform-badge.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="164" height="24" role="img" aria-label="Windows · 10 · 11 · x64"><rect width="164" height="24" rx="5" fill="#1e293b"/><path d="M68 0h91a5 5 0 0 1 5 5v14a5 5 0 0 1-5 5H68z" fill="#0ea5e9"/><g fill="#fff" font-family="Verdana,Arial,sans-serif" font-size="11" text-anchor="middle"><text x="34" y="16">Windows</text><text x="116" y="16">10 · 11 · x64</text></g></svg>
diff --git a/assets/branding/release-badge.svg b/assets/branding/release-badge.svg
new file mode 100644
index 0000000..52bba0f
--- /dev/null
+++ b/assets/branding/release-badge.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="172" height="24" role="img" aria-label="Release · 0.2.0 · Preview"><rect width="172" height="24" rx="5" fill="#1e293b"/><path d="M64 0h103a5 5 0 0 1 5 5v14a5 5 0 0 1-5 5H64z" fill="#2563eb"/><g fill="#fff" font-family="Verdana,Arial,sans-serif" font-size="11" text-anchor="middle"><text x="32" y="16">Release</text><text x="118" y="16">0.2.0 · Preview</text></g></svg>
diff --git a/assets/branding/runtime-badge.svg b/assets/branding/runtime-badge.svg
new file mode 100644
index 0000000..130de78
--- /dev/null
+++ b/assets/branding/runtime-badge.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="132" height="24" role="img" aria-label="macOS · Tahoe 26"><rect width="132" height="24" rx="5" fill="#1e293b"/><path d="M56 0h71a5 5 0 0 1 5 5v14a5 5 0 0 1-5 5H56z" fill="#7c3aed"/><g fill="#fff" font-family="Verdana,Arial,sans-serif" font-size="11" text-anchor="middle"><text x="28" y="16">macOS</text><text x="94" y="16">Tahoe 26</text></g></svg>
diff --git a/assets/branding/wsm-icon.png b/assets/branding/wsm-icon.png
new file mode 100644
index 0000000..4c32998
Binary files /dev/null and b/assets/branding/wsm-icon.png differ
diff --git a/assets/screenshots/app-store.jpg b/assets/screenshots/app-store.jpg
new file mode 100644
index 0000000..f615d70
Binary files /dev/null and b/assets/screenshots/app-store.jpg differ
diff --git a/assets/screenshots/coteditor.jpg b/assets/screenshots/coteditor.jpg
new file mode 100644
index 0000000..8657488
Binary files /dev/null and b/assets/screenshots/coteditor.jpg differ
diff --git a/assets/screenshots/library.jpg b/assets/screenshots/library.jpg
new file mode 100644
index 0000000..f3de686
Binary files /dev/null and b/assets/screenshots/library.jpg differ
diff --git a/assets/screenshots/s1.png b/assets/screenshots/s1.png
new file mode 100644
index 0000000..e54f7e7
Binary files /dev/null and b/assets/screenshots/s1.png differ
diff --git a/assets/screenshots/s2.png b/assets/screenshots/s2.png
new file mode 100644
index 0000000..d52731a
Binary files /dev/null and b/assets/screenshots/s2.png differ
diff --git a/assets/screenshots/safari-video.jpg b/assets/screenshots/safari-video.jpg
new file mode 100644
index 0000000..6a78993
Binary files /dev/null and b/assets/screenshots/safari-video.jpg differ
diff --git a/assets/screenshots/safari.jpg b/assets/screenshots/safari.jpg
new file mode 100644
index 0000000..ec58b2a
Binary files /dev/null and b/assets/screenshots/safari.jpg differ
diff --git a/assets/videos/library-preview.gif b/assets/videos/library-preview.gif
new file mode 100644
index 0000000..09b8817
Binary files /dev/null and b/assets/videos/library-preview.gif differ
diff --git a/assets/videos/library.mp4 b/assets/videos/library.mp4
new file mode 100644
index 0000000..496fc0b
Binary files /dev/null and b/assets/videos/library.mp4 differ
diff --git a/assets/videos/safari-preview.gif b/assets/videos/safari-preview.gif
new file mode 100644
index 0000000..b03ac7e
Binary files /dev/null and b/assets/videos/safari-preview.gif differ
diff --git a/assets/videos/safari.mp4 b/assets/videos/safari.mp4
new file mode 100644
index 0000000..07877bc
Binary files /dev/null and b/assets/videos/safari.mp4 differ
diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md
new file mode 100644
index 0000000..e3f59ea
--- /dev/null
+++ b/docs/PERFORMANCE.md
@@ -0,0 +1,13 @@
+# WSM performance
+
+These example measurements were recorded on Windows 11 with the runtime stored on an SSD. Performance varies with the host system, storage, workload and configuration.
+
+| Measurement | Example result |
+| --- | --- |
+| Cold boot to ready | 47–49 seconds |
+| Resume from idle and open an app | Around 2.5 seconds |
+| Warm app launch to first paint | Around 1.4–2.4 seconds |
+| Compacted runtime disk | 18.7 GB |
+| Keystroke to pixel | Approximately 46 ms median in one test |
+
+The runtime can pause after inactivity. SSD storage is recommended, especially for startup and app launches.
diff --git a/packaging/build-release.ps1 b/packaging/build-release.ps1
new file mode 100644
index 0000000..2622952
--- /dev/null
+++ b/packaging/build-release.ps1
@@ -0,0 +1,91 @@
+# WSM release packager.
+#
+# Builds dist\WSM-<ver>-win64\ (and a .zip of it): everything a clean Windows PC needs to set up
+# the macOS runtime and run Mac apps, and nothing from this machine (no runtime disk, no apps
+# list, no browser cache, no keys). macOS itself is never shipped: setup downloads it from Apple
+# on the user's PC.
+#
+# Layout (paths the code resolves relative to the install root):
+# bin\ wsm.exe, wsmd.exe, WsmManager.exe, wsmlaunch.exe
+# ui\ the WSM library and setup wizard
+# src\wsm-guest\... scripts WSM copies into macOS (install, trim, shrink, first boot)
+# cache\cargo\bin\ reims-ctl.exe + reims-util.exe (runtime owner, OpenCore builder)
+# runtime\reims-ctl\qemu\current\ QEMU with reims-vgpu, x86-64 only, debug info stripped
+# runtime\reims-ctl\prebuilt\ the GPU option ROM and macOS GPU kexts
+# licenses\
+param([string]$Version = "0.2.0", [switch]$NoZip)
+
+$ErrorActionPreference = 'Stop'
+$root = Split-Path -Parent $PSScriptRoot
+$stage = Join-Path $root "dist\WSM-$Version-win64"
+$zip = Join-Path $root "dist\WSM-$Version-win64.zip"
+$strip = Join-Path $root "toolchains\msys64\clang64\bin\llvm-strip.exe"
+
+function Copy-Dir($from, $to, [string[]]$excludeFiles = @(), [string[]]$excludeDirs = @()) {
+ New-Item -ItemType Directory -Force -Path $to | Out-Null
+ $args = @($from, $to, '/E', '/NFL', '/NDL', '/NJH', '/NJS', '/NP', '/R:1', '/W:1')
+ if ($excludeFiles.Count) { $args += '/XF'; $args += $excludeFiles }
+ if ($excludeDirs.Count) { $args += '/XD'; $args += $excludeDirs }
+ & robocopy @args | Out-Null
+ if ($LASTEXITCODE -ge 8) { throw "copy failed: $from -> $to (robocopy $LASTEXITCODE)" }
+}
+
+# Fresh stage every time: an old stage once picked up a WebView2 browser cache.
+if (Test-Path $stage) { Remove-Item -Recurse -Force $stage }
+New-Item -ItemType Directory -Force -Path "$stage\bin", "$stage\ui", "$stage\licenses" | Out-Null
+
+# 1. WSM itself.
+foreach ($exe in 'wsm.exe', 'wsmd.exe', 'WsmManager.exe', 'wsmlaunch.exe') {
+ $p = Join-Path $root "build\native\bin\$exe"
+ if (-not (Test-Path $p)) { throw "missing $exe - build first (cmake --build build\native)" }
+ Copy-Item $p "$stage\bin\" -Force
+}
+Copy-Dir (Join-Path $root 'src\wsm-manager') "$stage\ui"
+foreach ($d in 'agent', 'provision') {
+ Copy-Dir (Join-Path $root "src\wsm-guest\$d") "$stage\src\wsm-guest\$d"
+}
+
+# 2. The runtime owner.
+New-Item -ItemType Directory -Force -Path "$stage\cache\cargo\bin" | Out-Null
+foreach ($exe in 'reims-ctl.exe', 'reims-util.exe') { Copy-Item (Join-Path $root "cache\cargo\bin\$exe") "$stage\cache\cargo\bin\" -Force }
+Copy-Dir (Join-Path $root 'runtime\reims-ctl\prebuilt') "$stage\runtime\reims-ctl\prebuilt"
+
+# 3. QEMU, as a real folder (reims-ctl loads qemu\current\bin\qemu-system-x86_64.exe).
+# Only what an x86-64 macOS guest uses: no firmware for other CPUs, no second (windowless)
+# QEMU build, no developer tools.
+$qemu = (Get-Item (Join-Path $root 'runtime\reims-ctl\qemu\current')).FullName
+$t = (Get-Item $qemu).Target; if ($t) { $qemu = @($t)[0] }
+$otherCpus = @('edk2-aarch64-*', 'edk2-riscv64-*', 'edk2-loongarch64-*', 'hexagon*', 'hppa-firmware*', 'openbios-*',
+ 's390-ccw.img', 'slof.bin', 'skiboot.lid', 'u-boot*', 'palcode-clipper', 'opensbi-*', 'npcm*',
+ 'ast27x0_bootrom.bin', 'QEMU,*.bin', 'vof*.bin', 'pnv-pnor.bin', 'qemu_vga.ndrv', 'dtb')
+$devTools = @('qemu-system-x86_64w.exe', 'qemu-io.exe', 'qemu-nbd.exe', 'qemu-storage-daemon.exe', 'qemu-edid.exe',
+ 'elf2dmp.exe', '*.exe.debug-orig', '*.pdb')
+Copy-Dir $qemu "$stage\runtime\reims-ctl\qemu\current" ($otherCpus + $devTools) @('include')
+if (Test-Path $strip) {
+ Get-ChildItem "$stage\runtime\reims-ctl\qemu\current\bin\*.exe" | ForEach-Object { & $strip --strip-debug $_.FullName }
+} else { Write-Warning "llvm-strip not found: QEMU ships with debug info (~170 MB more)" }
+
+# 4. Licences (QEMU is GPL-2.0: its source is the reims-vgpu checkout's QEMU tree).
+foreach ($l in @(@('upstream\reims-vgpu\LICENSE', 'LICENSE-reims-vgpu.txt'), @('upstream\metal2vulkan\LICENSE', 'LICENSE-metal2vulkan.txt'),
+ @('upstream\maclator\LICENSE', 'LICENSE-maclator.txt'), @('upstream\rebar\LICENSE', 'LICENSE-rebar.txt'))) {
+ $p = Join-Path $root $l[0]; if (Test-Path $p) { Copy-Item $p (Join-Path "$stage\licenses" $l[1]) }
+}
+foreach ($l in Get-ChildItem $qemu -File -Filter 'COPYING*' -ErrorAction SilentlyContinue) { Copy-Item $l.FullName "$stage\licenses\QEMU-$($l.Name).txt" }
+foreach ($l in @('edk2-licenses.txt')) { $p = Join-Path $qemu "share\$l"; if (Test-Path $p) { Copy-Item $p "$stage\licenses\$l" } }
+
+# 5. Nothing personal may be in the package.
+$leaks = Get-ChildItem $stage -Recurse -Force | Where-Object {
+ $_.FullName -match '\\(webview2|EBWebView|vms|installers|base|snapshots)(\\|$)' -or
+ $_.Name -in @('apps.json', 'id_ed25519', 'id_ed25519.pub', 'password', 'runtime-ready.json', 'license-acceptance.json', 'recent-apps.txt') -or
+ $_.Extension -in @('.qcow2', '.img', '.dmg')
+}
+if ($leaks) { $leaks | ForEach-Object { Write-Host " leak: $($_.FullName)" }; throw "the package contains files from this machine" }
+
+$size = (Get-ChildItem $stage -Recurse -File | Measure-Object Length -Sum).Sum
+Write-Host ("Staged {0} ({1:N0} MB)" -f $stage, ($size / 1MB))
+if (-not $NoZip) {
+ if (Test-Path $zip) { Remove-Item -Force $zip }
+ & "$env:SystemRoot\System32\tar.exe" -a -cf $zip -C (Split-Path $stage) (Split-Path $stage -Leaf)
+ if ($LASTEXITCODE -ne 0) { throw "zip failed" }
+ Write-Host ("Packaged {0} ({1:N0} MB)" -f $zip, ((Get-Item $zip).Length / 1MB))
+}
diff --git a/src/wsm-arm64/README.md b/src/wsm-arm64/README.md
new file mode 100644
index 0000000..a877b67
--- /dev/null
+++ b/src/wsm-arm64/README.md
@@ -0,0 +1,15 @@
+# WSM ARM64 Application Translation Backend
+
+WSM distinguishes clearly between execution modes:
+
+1. **Native x86-64 Execution (Preferred)**: Universal Mach-O binaries (`FAT_MAGIC`) and x86-64 binaries execute natively inside the WHPX-accelerated x86-64 XNU guest with zero CPU translation overhead.
+2. **ARM64-to-x86-64 Application Translation (Pinned Upstreams)**:
+ - **`rebar`** (`F:\WSM\upstream\rebar`, pinned commit `4b233da`): Lightweight C/Objective-C ARM64 interpreter + x86-64 JIT + Mach-O loader + host framework bridge (`rebar-wrap` supports transparent LaunchAgent wrapping of ARM64-only `.app` bundles).
+ - **`maclator`** (`F:\WSM\upstream\maclator`, pinned commit `2d2f5b3`): Rust-based ARM64 interpreter + x86-64 JIT + persistent AOT cache + arm64e dyld shared cache loader + ANGLE/Metal GPU bridge (verified upstream on ARM64 Chromium 157 and VS Code).
+3. **Full-System ARM64 Emulation (Optional)**: `reims-vgpu` also supports ARM64 macOS guests via Ambrosia UEFI firmware under QEMU TCG (slow on x86-64 hosts, intended only for compatibility testing; native virtualization on future Windows ARM64 hosts).
+
+## Automatic Routing in WSM
+
+`wsm-appman` (`src/wsm-runtime/src/app_registry.cpp`) parses Mach-O headers (`MH_MAGIC_64`, `FAT_MAGIC`, `FAT_CIGAM`) on import:
+- If an x86-64 slice exists (`X86_64` or `Universal`), `requires_arm64_translation = false`.
+- If only an ARM64 slice exists (`Arm64`), `requires_arm64_translation = true` and `wsm-guest-agent` routes execution through `rebar` / `maclator` inside the macOS guest.
diff --git a/src/wsm-compositor/CMakeLists.txt b/src/wsm-compositor/CMakeLists.txt
new file mode 100644
index 0000000..67be1be
--- /dev/null
+++ b/src/wsm-compositor/CMakeLists.txt
@@ -0,0 +1,15 @@
+add_library(wsm-compositor STATIC
+ src/compositor.cpp
+)
+
+target_include_directories(wsm-compositor PUBLIC
+ "${CMAKE_CURRENT_SOURCE_DIR}/include"
+)
+
+target_link_libraries(wsm-compositor PUBLIC
+ wsm-proto
+ d3d11
+ dxgi
+ dcomp
+ user32
+)
diff --git a/src/wsm-compositor/include/wsm/compositor.hpp b/src/wsm-compositor/include/wsm/compositor.hpp
new file mode 100644
index 0000000..501dc24
--- /dev/null
+++ b/src/wsm-compositor/include/wsm/compositor.hpp
@@ -0,0 +1,87 @@
+#pragma once
+#include "wsm/protocol.hpp"
+
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+namespace wsm::compositor {
+
+struct WindowSummary {
+ uint64_t window_id = 0;
+ uint32_t pid = 0;
+ std::string title;
+ int32_t x = 0;
+ int32_t y = 0;
+ int32_t width = 0;
+ int32_t height = 0;
+ bool visible = false;
+ bool focused = false;
+ uint64_t frames_presented = 0;
+};
+
+struct InputCallbacks {
+ std::function<void(const proto::InputKeyEvent&)> on_key;
+ std::function<void(const proto::InputMouseMoveEvent&)> on_mouse_move;
+ std::function<void(const proto::InputMouseButtonEvent&)> on_mouse_button;
+ std::function<void(const proto::InputScrollEvent&)> on_scroll;
+ std::function<void(const proto::WindowActionEvent&)> on_window_action;
+ // For popup (guest-drawn) windows: a Win32 hit-test code for client point (x, y), e.g.
+ // HTCAPTION for empty title bar (native drag) or HTMINBUTTON for the guest's minimize
+ // button; 0 sends the point to the guest as normal input.
+ std::function<int(uint64_t window_id, int x, int y)> hit_caption;
+};
+
+// Translates a Windows VK code to a macOS Carbon/CGKeyCode virtual keycode
+uint32_t vk_to_mac_keycode(uint32_t vk_code) noexcept;
+
+class RootlessCompositor {
+public:
+ RootlessCompositor();
+ ~RootlessCompositor();
+
+ RootlessCompositor(const RootlessCompositor&) = delete;
+ RootlessCompositor& operator=(const RootlessCompositor&) = delete;
+
+ // Initializes D3D11 + DXGI + DirectComposition on the host GPU and starts the HWND message pump thread
+ bool start(InputCallbacks callbacks, std::string& err);
+ void stop();
+
+ bool is_running() const noexcept;
+ std::string gpu_adapter_name() const;
+
+ // Guest -> Host window lifecycle & frame submission
+ bool create_or_update_window(const proto::WindowDescriptor& desc, const std::string& title);
+ bool destroy_window(uint64_t window_id);
+ // Supports full-frame or partial dirty-rect upload + DXGI Present1 damage tracking
+ bool present_bgra_frame(uint64_t window_id, uint32_t width, uint32_t height,
+ uint32_t stride, const uint8_t* bgra_pixels,
+ uint32_t dirty_x = 0, uint32_t dirty_y = 0,
+ uint32_t dirty_w = 0, uint32_t dirty_h = 0);
+
+ // Benchmarks real DirectComposition hardware frame submission latency (microseconds)
+ struct PerfMetrics {
+ uint64_t frames = 0;
+ double avg_us = 0.0;
+ double p50_us = 0.0;
+ double p99_us = 0.0;
+ double fps = 0.0;
+ };
+ PerfMetrics benchmark_present(uint32_t width, uint32_t height, uint32_t frame_count, bool dirty_rect_only);
+
+ std::vector<WindowSummary> list_windows() const;
+
+ // Groups the window on the taskbar with its app's shortcut (AppUserModelID) and sets its icon.
+ bool set_window_identity(uint64_t window_id, const std::string& app_user_model_id,
+ const std::string& icon_path);
+
+private:
+ struct Impl;
+ std::unique_ptr<Impl> impl_;
+};
+
+} // namespace wsm::compositor
diff --git a/src/wsm-compositor/src/compositor.cpp b/src/wsm-compositor/src/compositor.cpp
new file mode 100644
index 0000000..20a0cad
--- /dev/null
+++ b/src/wsm-compositor/src/compositor.cpp
@@ -0,0 +1,756 @@
+#include "wsm/compositor.hpp"
+
+#include <windows.h>
+#include <windowsx.h>
+#include <shellapi.h>
+#include <d3d11.h>
+#include <dxgi1_3.h>
+#include <dcomp.h>
+#include <dwmapi.h>
+#include <shobjidl.h>
+#include <propkey.h>
+#include <propvarutil.h>
+#include <wrl/client.h>
+
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <cstring>
+#include <thread>
+
+#pragma comment(lib, "d3d11.lib")
+#pragma comment(lib, "dxgi.lib")
+#pragma comment(lib, "dcomp.lib")
+#pragma comment(lib, "user32.lib")
+#pragma comment(lib, "shell32.lib")
+#pragma comment(lib, "dwmapi.lib")
+#pragma comment(lib, "propsys.lib")
+#pragma comment(lib, "ole32.lib")
+
+namespace wsm::compositor {
+
+using Microsoft::WRL::ComPtr;
+
+namespace {
+
+constexpr UINT WM_WSM_CREATE_OR_UPDATE = WM_APP + 1;
+constexpr UINT WM_WSM_DESTROY = WM_APP + 2;
+constexpr UINT WM_WSM_QUIT = WM_APP + 3;
+
+std::wstring utf8_to_wide(const std::string& s) {
+ if (s.empty()) return {};
+ int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), static_cast<int>(s.size()), nullptr, 0);
+ if (len <= 0) return {};
+ std::wstring out(static_cast<size_t>(len), L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), static_cast<int>(s.size()), out.data(), len);
+ return out;
+}
+
+uint32_t current_modifiers() {
+ uint32_t m = 0;
+ if (GetKeyState(VK_SHIFT) & 0x8000) m |= 1u << 0;
+ if (GetKeyState(VK_CONTROL) & 0x8000) m |= 1u << 1;
+ if (GetKeyState(VK_MENU) & 0x8000) m |= 1u << 2;
+ if ((GetKeyState(VK_LWIN) & 0x8000) || (GetKeyState(VK_RWIN) & 0x8000)) m |= 1u << 3;
+ return m;
+}
+
+struct WindowEntry {
+ uint64_t window_id = 0;
+ uint32_t pid = 0;
+ std::string title;
+ proto::WindowRect bounds{};
+ bool visible = true;
+ bool focused = false;
+ bool in_move = false; // the user is dragging/sizing it (Windows modal move loop)
+ uint64_t frames_presented = 0;
+
+ HWND hwnd = nullptr;
+ ComPtr<IDXGISwapChain1> swap_chain;
+ ComPtr<IDCompositionTarget> dcomp_target;
+ ComPtr<IDCompositionVisual> dcomp_visual;
+ uint32_t surface_w = 0;
+ uint32_t surface_h = 0;
+};
+
+struct CreateUpdatePayload {
+ proto::WindowDescriptor desc;
+ std::string title;
+};
+
+} // namespace
+
+uint32_t vk_to_mac_keycode(uint32_t vk) noexcept {
+ switch (vk) {
+ case 'A': return 0x00; case 'S': return 0x01; case 'D': return 0x02; case 'F': return 0x03;
+ case 'H': return 0x04; case 'G': return 0x05; case 'Z': return 0x06; case 'X': return 0x07;
+ case 'C': return 0x08; case 'V': return 0x09; case 'B': return 0x0B; case 'Q': return 0x0C;
+ case 'W': return 0x0D; case 'E': return 0x0E; case 'R': return 0x0F; case 'Y': return 0x10;
+ case 'T': return 0x11; case '1': return 0x12; case '2': return 0x13; case '3': return 0x14;
+ case '4': return 0x15; case '6': return 0x16; case '5': return 0x17; case '9': return 0x19;
+ case '7': return 0x1A; case '8': return 0x1C; case '0': return 0x1D; case 'O': return 0x1F;
+ case 'U': return 0x20; case 'I': return 0x22; case 'P': return 0x23; case 'L': return 0x25;
+ case 'J': return 0x26; case 'K': return 0x28; case 'N': return 0x2D; case 'M': return 0x2E;
+ case VK_RETURN: return 0x24;
+ case VK_TAB: return 0x30;
+ case VK_SPACE: return 0x31;
+ case VK_BACK: return 0x33;
+ case VK_ESCAPE: return 0x35;
+ case VK_LWIN: return 0x37; // Command
+ case VK_SHIFT:
+ case VK_LSHIFT: return 0x38;
+ case VK_MENU:
+ case VK_LMENU: return 0x3A; // Option
+ case VK_CONTROL:
+ case VK_LCONTROL: return 0x3B;
+ case VK_LEFT: return 0x7B;
+ case VK_RIGHT: return 0x7C;
+ case VK_DOWN: return 0x7D;
+ case VK_UP: return 0x7E;
+ case VK_DELETE: return 0x75;
+ default: return 0xFF;
+ }
+}
+
+struct RootlessCompositor::Impl {
+ InputCallbacks callbacks;
+ std::atomic<bool> running{false};
+ std::thread pump_thread;
+ DWORD pump_thread_id = 0;
+ HWND control_hwnd = nullptr;
+
+ ComPtr<ID3D11Device> d3d_device;
+ ComPtr<ID3D11DeviceContext> d3d_context;
+ ComPtr<IDXGIFactory2> dxgi_factory;
+ ComPtr<IDCompositionDevice> dcomp_device;
+ std::string adapter_name;
+
+ mutable std::recursive_mutex mutex;
+ std::unordered_map<uint64_t, std::unique_ptr<WindowEntry>> windows;
+ std::unordered_map<HWND, uint64_t> hwnd_to_id;
+
+ bool init_d3d_and_dcomp(std::string& err) {
+ UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
+ D3D_FEATURE_LEVEL levels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0 };
+ D3D_FEATURE_LEVEL achieved{};
+
+ HRESULT hr = D3D11CreateDevice(
+ nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, flags,
+ levels, 2, D3D11_SDK_VERSION,
+ &d3d_device, &achieved, &d3d_context
+ );
+ if (FAILED(hr)) {
+ err = "D3D11CreateDevice failed";
+ return false;
+ }
+
+ ComPtr<ID3D10Multithread> mt;
+ if (SUCCEEDED(d3d_device.As(&mt))) {
+ mt->SetMultithreadProtected(TRUE);
+ }
+
+ ComPtr<IDXGIDevice> dxgi_device;
+ hr = d3d_device.As(&dxgi_device);
+ if (FAILED(hr)) {
+ err = "QueryInterface(IDXGIDevice) failed";
+ return false;
+ }
+
+ ComPtr<IDXGIAdapter> adapter;
+ if (SUCCEEDED(dxgi_device->GetAdapter(&adapter))) {
+ DXGI_ADAPTER_DESC desc{};
+ if (SUCCEEDED(adapter->GetDesc(&desc))) {
+ int len = WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1, nullptr, 0, nullptr, nullptr);
+ if (len > 1) {
+ adapter_name.resize(static_cast<size_t>(len - 1));
+ WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1, adapter_name.data(), len, nullptr, nullptr);
+ }
+ }
+ adapter->GetParent(IID_PPV_ARGS(&dxgi_factory));
+ }
+
+ if (!dxgi_factory) {
+ hr = CreateDXGIFactory2(0, IID_PPV_ARGS(&dxgi_factory));
+ if (FAILED(hr)) {
+ err = "CreateDXGIFactory2 failed";
+ return false;
+ }
+ }
+
+ hr = DCompositionCreateDevice(dxgi_device.Get(), IID_PPV_ARGS(&dcomp_device));
+ if (FAILED(hr)) {
+ err = "DCompositionCreateDevice failed";
+ return false;
+ }
+ return true;
+ }
+
+ bool ensure_swapchain(WindowEntry& entry, uint32_t w, uint32_t h) {
+ if (w == 0) w = 1;
+ if (h == 0) h = 1;
+ if (entry.swap_chain && entry.surface_w == w && entry.surface_h == h) {
+ return true;
+ }
+ if (entry.swap_chain) {
+ HRESULT hr = entry.swap_chain->ResizeBuffers(2, w, h, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
+ if (SUCCEEDED(hr)) {
+ entry.surface_w = w;
+ entry.surface_h = h;
+ return true;
+ }
+ entry.swap_chain.Reset();
+ }
+
+ DXGI_SWAP_CHAIN_DESC1 scd{};
+ scd.Width = w;
+ scd.Height = h;
+ scd.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
+ scd.SampleDesc.Count = 1;
+ scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
+ scd.BufferCount = 2;
+ scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
+ scd.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
+
+ HRESULT hr = dxgi_factory->CreateSwapChainForComposition(
+ d3d_device.Get(), &scd, nullptr, &entry.swap_chain
+ );
+ if (FAILED(hr)) return false;
+
+ if (!entry.dcomp_target) {
+ hr = dcomp_device->CreateTargetForHwnd(entry.hwnd, TRUE, &entry.dcomp_target);
+ if (FAILED(hr)) return false;
+ }
+ if (!entry.dcomp_visual) {
+ hr = dcomp_device->CreateVisual(&entry.dcomp_visual);
+ if (FAILED(hr)) return false;
+ }
+ entry.dcomp_visual->SetContent(entry.swap_chain.Get());
+ entry.dcomp_target->SetRoot(entry.dcomp_visual.Get());
+ dcomp_device->Commit();
+
+ entry.surface_w = w;
+ entry.surface_h = h;
+ return true;
+ }
+
+ static LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
+ auto* self = reinterpret_cast<Impl*>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
+ if (!self) return DefWindowProcW(hwnd, msg, wParam, lParam);
+
+ if (hwnd == self->control_hwnd) {
+ if (msg == WM_WSM_CREATE_OR_UPDATE) {
+ std::unique_ptr<CreateUpdatePayload> p(reinterpret_cast<CreateUpdatePayload*>(lParam));
+ self->handle_create_or_update(p->desc, p->title);
+ return 0;
+ } else if (msg == WM_WSM_DESTROY) {
+ uint64_t wid = static_cast<uint64_t>(wParam);
+ self->handle_destroy(wid);
+ return 0;
+ } else if (msg == WM_WSM_QUIT) {
+ PostQuitMessage(0);
+ return 0;
+ }
+ return DefWindowProcW(hwnd, msg, wParam, lParam);
+ }
+
+ uint64_t wid = 0;
+ {
+ std::lock_guard<std::recursive_mutex> lock(self->mutex);
+ auto it = self->hwnd_to_id.find(hwnd);
+ if (it != self->hwnd_to_id.end()) wid = it->second;
+ }
+ if (wid == 0) return DefWindowProcW(hwnd, msg, wParam, lParam);
+
+ switch (msg) {
+ case WM_CLOSE:
+ if (self->callbacks.on_window_action) {
+ proto::WindowActionEvent ev{};
+ ev.window_id = wid;
+ ev.action = static_cast<uint32_t>(proto::WindowActionKind::Close);
+ self->callbacks.on_window_action(ev);
+ }
+ return 0;
+ case WM_SETFOCUS:
+ case WM_KILLFOCUS: {
+ bool focused = (msg == WM_SETFOCUS);
+ {
+ std::lock_guard<std::recursive_mutex> lock(self->mutex);
+ if (auto it = self->windows.find(wid); it != self->windows.end()) {
+ it->second->focused = focused;
+ }
+ }
+ if (focused && self->callbacks.on_window_action) {
+ proto::WindowActionEvent ev{};
+ ev.window_id = wid;
+ ev.action = static_cast<uint32_t>(proto::WindowActionKind::Focus);
+ self->callbacks.on_window_action(ev);
+ }
+ break;
+ }
+ case WM_NCHITTEST:
+ if (self->callbacks.hit_caption && (GetWindowLongW(hwnd, GWL_STYLE) & WS_POPUP) &&
+ !(GetWindowLongW(hwnd, GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
+ POINT pt{GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
+ ScreenToClient(hwnd, &pt);
+ int ht = self->callbacks.hit_caption(wid, pt.x, pt.y);
+ return ht ? ht : HTCLIENT;
+ }
+ break;
+ case WM_NCLBUTTONDOWN:
+ if (wParam == HTMINBUTTON) { ShowWindow(hwnd, SW_MINIMIZE); return 0; }
+ if (wParam == HTMAXBUTTON || wParam == HTCLOSE) return 0;
+ if (wParam == HTCAPTION && self->callbacks.on_mouse_button) {
+ // The press goes to the app at once (a toolbar button reacts on press, not
+ // after the release). Windows' drag detection then decides: the mouse moved
+ // past the drag threshold -> release in the app, native Windows move
+ // (instant); released in place -> the release goes to the app (a click).
+ POINT pt{GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
+ POINT cpt = pt;
+ ScreenToClient(hwnd, &cpt);
+ proto::InputMouseButtonEvent ev{};
+ ev.window_id = wid;
+ ev.x = cpt.x;
+ ev.y = cpt.y;
+ ev.button = 0;
+ ev.modifiers = current_modifiers();
+ ev.pressed = 1;
+ self->callbacks.on_mouse_button(ev);
+ bool drag = DragDetect(hwnd, pt) != FALSE;
+ ev.pressed = 0;
+ self->callbacks.on_mouse_button(ev);
+ if (drag && (GetAsyncKeyState(VK_LBUTTON) & 0x8000))
+ return DefWindowProcW(hwnd, msg, wParam, lParam); // still held: move the window
+ return 0;
+ }
+ break;
+ case WM_NCLBUTTONUP:
+ if (wParam == HTMINBUTTON || wParam == HTMAXBUTTON || wParam == HTCLOSE) return 0;
+ break;
+ case WM_NCLBUTTONDBLCLK:
+ // No Windows maximize (the guest owns the window's size). The second click of a
+ // double-click on the bar goes to the app, which then sees a double-click.
+ if (wParam == HTCAPTION && self->callbacks.on_mouse_button) {
+ POINT pt{GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
+ ScreenToClient(hwnd, &pt);
+ proto::InputMouseButtonEvent ev{};
+ ev.window_id = wid;
+ ev.x = pt.x;
+ ev.y = pt.y;
+ ev.modifiers = current_modifiers();
+ ev.pressed = 1;
+ self->callbacks.on_mouse_button(ev);
+ ev.pressed = 0;
+ self->callbacks.on_mouse_button(ev);
+ }
+ return 0;
+ case WM_ENTERSIZEMOVE:
+ case WM_EXITSIZEMOVE: {
+ // While the user drags, Windows owns the position: runtime updates must not
+ // move the window back under the mouse (that made drags stutter).
+ std::lock_guard<std::recursive_mutex> lock(self->mutex);
+ if (auto it = self->windows.find(wid); it != self->windows.end())
+ it->second->in_move = (msg == WM_ENTERSIZEMOVE);
+ break;
+ }
+ case WM_MOVE:
+ if (self->callbacks.on_window_action) {
+ proto::WindowActionEvent ev{};
+ ev.window_id = wid;
+ ev.action = static_cast<uint32_t>(proto::WindowActionKind::Move);
+ ev.arg1 = static_cast<short>(LOWORD(lParam));
+ ev.arg2 = static_cast<short>(HIWORD(lParam));
+ self->callbacks.on_window_action(ev);
+ }
+ break;
+ case WM_SIZE:
+ if (self->callbacks.on_window_action) {
+ proto::WindowActionEvent ev{};
+ ev.window_id = wid;
+ ev.action = static_cast<uint32_t>(proto::WindowActionKind::Resize);
+ ev.arg1 = LOWORD(lParam);
+ ev.arg2 = HIWORD(lParam);
+ self->callbacks.on_window_action(ev);
+ }
+ break;
+ case WM_MOUSEMOVE:
+ if (self->callbacks.on_mouse_move) {
+ proto::InputMouseMoveEvent ev{};
+ ev.window_id = wid;
+ ev.x = GET_X_LPARAM(lParam);
+ ev.y = GET_Y_LPARAM(lParam);
+ ev.modifiers = current_modifiers();
+ self->callbacks.on_mouse_move(ev);
+ }
+ return 0;
+ case WM_LBUTTONDOWN: case WM_LBUTTONUP:
+ case WM_RBUTTONDOWN: case WM_RBUTTONUP:
+ case WM_MBUTTONDOWN: case WM_MBUTTONUP:
+ // Keep receiving moves while a button is held (drags that leave the window).
+ if (msg == WM_LBUTTONDOWN || msg == WM_RBUTTONDOWN || msg == WM_MBUTTONDOWN) SetCapture(hwnd);
+ else if (!(wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON))) ReleaseCapture();
+ if (self->callbacks.on_mouse_button) {
+ proto::InputMouseButtonEvent ev{};
+ ev.window_id = wid;
+ ev.x = GET_X_LPARAM(lParam);
+ ev.y = GET_Y_LPARAM(lParam);
+ ev.button = (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONUP) ? 0
+ : (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONUP) ? 1 : 2;
+ ev.pressed = (msg == WM_LBUTTONDOWN || msg == WM_RBUTTONDOWN || msg == WM_MBUTTONDOWN) ? 1 : 0;
+ ev.modifiers = current_modifiers();
+ self->callbacks.on_mouse_button(ev);
+ }
+ return 0;
+ case WM_MOUSEWHEEL:
+ if (self->callbacks.on_scroll) {
+ proto::InputScrollEvent ev{};
+ ev.window_id = wid;
+ ev.delta_y = static_cast<float>(GET_WHEEL_DELTA_WPARAM(wParam)) / static_cast<float>(WHEEL_DELTA);
+ ev.modifiers = current_modifiers();
+ self->callbacks.on_scroll(ev);
+ }
+ return 0;
+ case WM_KEYDOWN:
+ case WM_KEYUP:
+ case WM_SYSKEYDOWN:
+ case WM_SYSKEYUP:
+ if (self->callbacks.on_key) {
+ proto::InputKeyEvent ev{};
+ ev.window_id = wid;
+ ev.vk_code = static_cast<uint32_t>(wParam);
+ ev.mac_keycode = vk_to_mac_keycode(ev.vk_code);
+ ev.modifiers = current_modifiers();
+ ev.pressed = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN) ? 1 : 0;
+ ev.repeat = (ev.pressed && ((lParam & (1 << 30)) != 0)) ? 1 : 0;
+ self->callbacks.on_key(ev);
+ }
+ return 0;
+ default:
+ break;
+ }
+ return DefWindowProcW(hwnd, msg, wParam, lParam);
+ }
+
+ void handle_create_or_update(const proto::WindowDescriptor& desc, const std::string& title) {
+ std::lock_guard<std::recursive_mutex> lock(mutex);
+ auto it = windows.find(desc.window_id);
+ if (it == windows.end()) {
+ auto entry = std::make_unique<WindowEntry>();
+ entry->window_id = desc.window_id;
+ entry->pid = desc.pid;
+ entry->title = title;
+ entry->bounds = desc.bounds;
+ entry->visible = desc.visible != 0;
+
+ // Popup = the guest draws its own window chrome (macOS title bar, traffic lights);
+ // Windows adds rounded corners and a shadow. Menu = transient, never takes focus.
+ const bool popup = (desc.style_flags & (1u << 3)) != 0;
+ const bool menu = (desc.style_flags & (1u << 6)) != 0;
+ DWORD style = popup ? (WS_POPUP | WS_SYSMENU | WS_MINIMIZEBOX) : WS_OVERLAPPEDWINDOW;
+ DWORD ex_style = WS_EX_NOREDIRECTIONBITMAP;
+ if (menu) ex_style |= WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE;
+ else if (popup) ex_style |= WS_EX_APPWINDOW;
+
+ int w = desc.bounds.width > 0 ? desc.bounds.width : 800;
+ int h = desc.bounds.height > 0 ? desc.bounds.height : 600;
+ std::wstring wtitle = utf8_to_wide(title.empty() ? "macOS Application (WSM)" : title);
+
+ HWND hwnd = CreateWindowExW(
+ ex_style, L"WsmRootlessWindowClass", wtitle.c_str(), style,
+ desc.bounds.x, desc.bounds.y, w, h,
+ nullptr, nullptr, GetModuleHandleW(nullptr), nullptr
+ );
+ if (!hwnd) return;
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
+ if (popup) {
+ // The window's shape comes from its own pixels (transparent corners cut by the
+ // streamer to macOS's radius), so Windows must not round or frame it.
+ DWORD corner = 1 /*DWMWCP_DONOTROUND*/;
+ DwmSetWindowAttribute(hwnd, 33 /*DWMWA_WINDOW_CORNER_PREFERENCE*/, &corner, sizeof(corner));
+ DWORD border = 0xFFFFFFFE /*DWMWA_COLOR_NONE*/;
+ DwmSetWindowAttribute(hwnd, 34 /*DWMWA_BORDER_COLOR*/, &border, sizeof(border));
+ }
+ DragAcceptFiles(hwnd, TRUE);
+ entry->hwnd = hwnd;
+ ensure_swapchain(*entry, static_cast<uint32_t>(w), static_cast<uint32_t>(h));
+
+ hwnd_to_id[hwnd] = desc.window_id;
+ if (entry->visible) {
+ ShowWindow(hwnd, menu ? SW_SHOWNOACTIVATE : SW_SHOW);
+ if (!menu) SetForegroundWindow(hwnd);
+ }
+ windows[desc.window_id] = std::move(entry);
+ } else {
+ auto& entry = *it->second;
+ // The window list arrives ~10x a second, mostly unchanged: touch the HWND only for
+ // real changes, and never reposition it while the user is dragging it.
+ if (entry.title != title) {
+ entry.title = title;
+ SetWindowTextW(entry.hwnd, utf8_to_wide(title).c_str());
+ }
+ entry.visible = desc.visible != 0;
+ RECT cur{};
+ GetWindowRect(entry.hwnd, &cur);
+ bool same = cur.left == desc.bounds.x && cur.top == desc.bounds.y &&
+ cur.right - cur.left == static_cast<LONG>(desc.bounds.width) &&
+ cur.bottom - cur.top == static_cast<LONG>(desc.bounds.height);
+ entry.bounds = desc.bounds;
+ if (!same && !entry.in_move)
+ SetWindowPos(entry.hwnd, nullptr, desc.bounds.x, desc.bounds.y,
+ desc.bounds.width, desc.bounds.height,
+ SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING);
+ if (!entry.visible) ShowWindow(entry.hwnd, SW_HIDE);
+ else if (!IsWindowVisible(entry.hwnd)) ShowWindow(entry.hwnd, SW_SHOWNOACTIVATE);
+ }
+ }
+
+ void handle_destroy(uint64_t wid) {
+ std::lock_guard<std::recursive_mutex> lock(mutex);
+ auto it = windows.find(wid);
+ if (it == windows.end()) return;
+ HWND hwnd = it->second->hwnd;
+ hwnd_to_id.erase(hwnd);
+ if (hwnd) DestroyWindow(hwnd);
+ windows.erase(it);
+ }
+};
+
+RootlessCompositor::RootlessCompositor() : impl_(std::make_unique<Impl>()) {}
+RootlessCompositor::~RootlessCompositor() { stop(); }
+
+bool RootlessCompositor::start(InputCallbacks callbacks, std::string& err) {
+ if (impl_->running.load()) return true;
+ impl_->callbacks = std::move(callbacks);
+
+ if (!impl_->init_d3d_and_dcomp(err)) {
+ return false;
+ }
+
+ std::atomic<bool> ready{false};
+ impl_->pump_thread = std::thread([this, &ready]() {
+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ WNDCLASSEXW wc{};
+ wc.cbSize = sizeof(wc);
+ wc.lpfnWndProc = Impl::WindowProc;
+ wc.hInstance = GetModuleHandleW(nullptr);
+ wc.hCursor = LoadCursorW(nullptr, IDC_ARROW);
+ wc.lpszClassName = L"WsmRootlessWindowClass";
+ RegisterClassExW(&wc);
+
+ impl_->control_hwnd = CreateWindowExW(
+ 0, L"WsmRootlessWindowClass", L"WsmControl", 0,
+ 0, 0, 0, 0, HWND_MESSAGE, nullptr, GetModuleHandleW(nullptr), nullptr
+ );
+ SetWindowLongPtrW(impl_->control_hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(impl_.get()));
+ impl_->pump_thread_id = GetCurrentThreadId();
+ impl_->running.store(true);
+ ready.store(true);
+
+ MSG msg{};
+ while (GetMessageW(&msg, nullptr, 0, 0) > 0) {
+ TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
+
+ // Cleanup remaining windows
+ std::lock_guard<std::recursive_mutex> lock(impl_->mutex);
+ for (auto& [id, entry] : impl_->windows) {
+ if (entry->hwnd) DestroyWindow(entry->hwnd);
+ }
+ impl_->windows.clear();
+ impl_->hwnd_to_id.clear();
+ if (impl_->control_hwnd) {
+ DestroyWindow(impl_->control_hwnd);
+ impl_->control_hwnd = nullptr;
+ }
+ impl_->running.store(false);
+ });
+
+ while (!ready.load()) {
+ Sleep(1);
+ }
+ return true;
+}
+
+void RootlessCompositor::stop() {
+ if (impl_->control_hwnd) {
+ PostMessageW(impl_->control_hwnd, WM_WSM_QUIT, 0, 0);
+ }
+ if (impl_->pump_thread.joinable()) {
+ impl_->pump_thread.join();
+ }
+}
+
+bool RootlessCompositor::is_running() const noexcept {
+ return impl_->running.load();
+}
+
+std::string RootlessCompositor::gpu_adapter_name() const {
+ return impl_->adapter_name;
+}
+
+bool RootlessCompositor::create_or_update_window(const proto::WindowDescriptor& desc, const std::string& title) {
+ if (!impl_->running.load() || !impl_->control_hwnd) return false;
+ auto* payload = new CreateUpdatePayload{desc, title};
+ return PostMessageW(impl_->control_hwnd, WM_WSM_CREATE_OR_UPDATE, 0, reinterpret_cast<LPARAM>(payload)) != 0;
+}
+
+bool RootlessCompositor::destroy_window(uint64_t window_id) {
+ if (!impl_->running.load() || !impl_->control_hwnd) return false;
+ return PostMessageW(impl_->control_hwnd, WM_WSM_DESTROY, static_cast<WPARAM>(window_id), 0) != 0;
+}
+
+bool RootlessCompositor::present_bgra_frame(uint64_t window_id, uint32_t width, uint32_t height,
+ uint32_t stride, const uint8_t* bgra_pixels,
+ uint32_t dirty_x, uint32_t dirty_y,
+ uint32_t dirty_w, uint32_t dirty_h) {
+ if (!bgra_pixels || width == 0 || height == 0) return false;
+ std::lock_guard<std::recursive_mutex> lock(impl_->mutex);
+ auto it = impl_->windows.find(window_id);
+ if (it == impl_->windows.end()) return false;
+ auto& entry = *it->second;
+
+ if (!impl_->ensure_swapchain(entry, width, height)) return false;
+
+ ComPtr<ID3D11Texture2D> backbuffer;
+ if (FAILED(entry.swap_chain->GetBuffer(0, IID_PPV_ARGS(&backbuffer)))) return false;
+
+ bool partial = (dirty_w > 0 && dirty_h > 0 &&
+ dirty_x + dirty_w <= width && dirty_y + dirty_h <= height &&
+ entry.frames_presented > 0);
+
+ if (partial) {
+ D3D11_BOX box{dirty_x, dirty_y, 0, dirty_x + dirty_w, dirty_y + dirty_h, 1};
+ const uint8_t* src = bgra_pixels + static_cast<size_t>(dirty_y) * stride + static_cast<size_t>(dirty_x) * 4u;
+ impl_->d3d_context->UpdateSubresource(backbuffer.Get(), 0, &box, src, stride, 0);
+
+ RECT dirty_rect{
+ static_cast<LONG>(dirty_x), static_cast<LONG>(dirty_y),
+ static_cast<LONG>(dirty_x + dirty_w), static_cast<LONG>(dirty_y + dirty_h)
+ };
+ DXGI_PRESENT_PARAMETERS params{};
+ params.DirtyRectsCount = 1;
+ params.pDirtyRects = &dirty_rect;
+ HRESULT hr = entry.swap_chain->Present1(0, 0, &params);
+ if (SUCCEEDED(hr)) {
+ entry.frames_presented++;
+ return true;
+ }
+ return false;
+ }
+
+ D3D11_BOX box{0, 0, 0, width, height, 1};
+ impl_->d3d_context->UpdateSubresource(backbuffer.Get(), 0, &box, bgra_pixels, stride, 0);
+ HRESULT hr = entry.swap_chain->Present(0, 0);
+ if (SUCCEEDED(hr)) {
+ entry.frames_presented++;
+ return true;
+ }
+ return false;
+}
+
+RootlessCompositor::PerfMetrics RootlessCompositor::benchmark_present(uint32_t width, uint32_t height,
+ uint32_t frame_count,
+ bool dirty_rect_only) {
+ PerfMetrics m{};
+ if (!impl_->running.load() || frame_count == 0) return m;
+
+ const uint64_t bench_wid = 88888;
+ proto::WindowDescriptor desc{};
+ desc.window_id = bench_wid;
+ desc.pid = GetCurrentProcessId();
+ desc.bounds = {40, 40, static_cast<int32_t>(width), static_cast<int32_t>(height)};
+ desc.visible = 1;
+ create_or_update_window(desc, "WSM DirectComposition Benchmark");
+ Sleep(150);
+
+ std::vector<uint8_t> pixels(static_cast<size_t>(width) * height * 4u, 0xCC);
+ std::vector<double> samples_us;
+ samples_us.reserve(frame_count);
+
+ // Warmup frame
+ present_bgra_frame(bench_wid, width, height, width * 4u, pixels.data());
+
+ auto t_start = std::chrono::steady_clock::now();
+ for (uint32_t i = 0; i < frame_count; ++i) {
+ auto t0 = std::chrono::steady_clock::now();
+ if (dirty_rect_only) {
+ present_bgra_frame(bench_wid, width, height, width * 4u, pixels.data(), 64, 64, 128, 64);
+ } else {
+ present_bgra_frame(bench_wid, width, height, width * 4u, pixels.data());
+ }
+ auto t1 = std::chrono::steady_clock::now();
+ samples_us.push_back(std::chrono::duration<double, std::micro>(t1 - t0).count());
+ }
+ auto t_end = std::chrono::steady_clock::now();
+
+ destroy_window(bench_wid);
+ Sleep(50);
+
+ std::sort(samples_us.begin(), samples_us.end());
+ double sum = 0.0;
+ for (double v : samples_us) sum += v;
+ double total_sec = std::chrono::duration<double>(t_end - t_start).count();
+
+ m.frames = samples_us.size();
+ m.avg_us = sum / static_cast<double>(samples_us.size());
+ m.p50_us = samples_us[samples_us.size() / 2];
+ m.p99_us = samples_us[(samples_us.size() * 99) / 100];
+ m.fps = total_sec > 0.0 ? static_cast<double>(m.frames) / total_sec : 0.0;
+ return m;
+}
+
+bool RootlessCompositor::set_window_identity(uint64_t window_id, const std::string& app_user_model_id,
+ const std::string& icon_path) {
+ HWND hwnd = nullptr;
+ {
+ std::lock_guard<std::recursive_mutex> lock(impl_->mutex);
+ auto it = impl_->windows.find(window_id);
+ if (it == impl_->windows.end()) return false;
+ hwnd = it->second->hwnd;
+ }
+ if (!hwnd) return false;
+ if (!app_user_model_id.empty()) {
+ CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
+ IPropertyStore* props = nullptr;
+ if (SUCCEEDED(SHGetPropertyStoreForWindow(hwnd, IID_PPV_ARGS(&props)))) {
+ PROPVARIANT pv;
+ std::wstring id = utf8_to_wide(app_user_model_id);
+ if (SUCCEEDED(InitPropVariantFromString(id.c_str(), &pv))) {
+ props->SetValue(PKEY_AppUserModel_ID, pv);
+ PropVariantClear(&pv);
+ }
+ props->Release();
+ }
+ }
+ if (!icon_path.empty()) {
+ std::wstring ip = utf8_to_wide(icon_path);
+ auto big = static_cast<HICON>(LoadImageW(nullptr, ip.c_str(), IMAGE_ICON, 32, 32, LR_LOADFROMFILE));
+ auto little = static_cast<HICON>(LoadImageW(nullptr, ip.c_str(), IMAGE_ICON, 16, 16, LR_LOADFROMFILE));
+ if (big) SendMessageW(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(big));
+ if (little) SendMessageW(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(little));
+ }
+ return true;
+}
+
+std::vector<WindowSummary> RootlessCompositor::list_windows() const {
+ std::lock_guard<std::recursive_mutex> lock(impl_->mutex);
+ std::vector<WindowSummary> out;
+ out.reserve(impl_->windows.size());
+ for (const auto& [id, e] : impl_->windows) {
+ WindowSummary s{};
+ s.window_id = e->window_id;
+ s.pid = e->pid;
+ s.title = e->title;
+ s.x = e->bounds.x;
+ s.y = e->bounds.y;
+ s.width = e->bounds.width;
+ s.height = e->bounds.height;
+ s.visible = e->visible;
+ s.focused = e->focused;
+ s.frames_presented = e->frames_presented;
+ out.push_back(std::move(s));
+ }
+ return out;
+}
+
+} // namespace wsm::compositor
diff --git a/src/wsm-core/CMakeLists.txt b/src/wsm-core/CMakeLists.txt
new file mode 100644
index 0000000..cad5fa4
--- /dev/null
+++ b/src/wsm-core/CMakeLists.txt
@@ -0,0 +1,16 @@
+add_library(wsm-core STATIC
+ src/host_probe.cpp
+ src/vm_manager.cpp
+ src/qmp_unix.cpp
+)
+
+target_include_directories(wsm-core PUBLIC
+ "${CMAKE_CURRENT_SOURCE_DIR}/include"
+)
+
+target_link_libraries(wsm-core PUBLIC
+ wsm-proto
+ WinHvPlatform
+ dxgi
+ ws2_32
+)
diff --git a/src/wsm-core/include/wsm/host_probe.hpp b/src/wsm-core/include/wsm/host_probe.hpp
new file mode 100644
index 0000000..6950312
--- /dev/null
+++ b/src/wsm-core/include/wsm/host_probe.hpp
@@ -0,0 +1,49 @@
+#pragma once
+#include "wsm/paths.hpp"
+#include <cstdint>
+#include <string>
+
+namespace wsm::core {
+
+struct WhpxCapabilities {
+ bool dll_present = false;
+ bool hypervisor_present = false;
+ bool partition_create_verified = false;
+ uint64_t features_mask = 0;
+ uint64_t extended_vm_exits_mask = 0;
+ uint32_t processor_vendor = 0;
+ std::string error_detail;
+};
+
+struct GpuAdapterInfo {
+ std::string name;
+ uint32_t vendor_id = 0;
+ uint32_t device_id = 0;
+ uint64_t dedicated_vram_bytes = 0;
+ bool vulkan_supported = false;
+ uint32_t vulkan_api_major = 0;
+ uint32_t vulkan_api_minor = 0;
+ uint32_t vulkan_api_patch = 0;
+ bool ext_external_memory_win32 = false;
+ bool ext_external_semaphore_win32 = false;
+ bool is_discrete = false;
+};
+
+struct HostSystemReport {
+ std::string os_version;
+ std::string cpu_name;
+ uint32_t logical_cpus = 0;
+ uint64_t total_ram_bytes = 0;
+ uint64_t avail_ram_bytes = 0;
+ WhpxCapabilities whpx;
+ GpuAdapterInfo primary_gpu;
+ std::string wsm_root;
+ uint64_t storage_free_bytes = 0;
+};
+
+WhpxCapabilities probe_whpx(bool verify_partition_lifecycle = true);
+GpuAdapterInfo probe_primary_gpu();
+HostSystemReport probe_host_system(const std::string& wsm_root = wsm::core::resolve_wsm_root() + "");
+std::string host_report_to_json(const HostSystemReport& r);
+
+} // namespace wsm::core
diff --git a/src/wsm-core/include/wsm/paths.hpp b/src/wsm-core/include/wsm/paths.hpp
new file mode 100644
index 0000000..382b115
--- /dev/null
+++ b/src/wsm-core/include/wsm/paths.hpp
@@ -0,0 +1,93 @@
+#pragma once
+#include <windows.h>
+#include <shlobj.h>
+#include <filesystem>
+#include <fstream>
+#include <string>
+
+namespace wsm::core {
+
+// Portable, machine-agnostic WSM path resolver.
+// Priority:
+// 1. %WSM_ROOT% environment variable (if set)
+// 2. %LOCALAPPDATA%\WSM\root.txt (user-selected storage folder in WSM Manager)
+// 3. Directory containing the executable if it contains a `runtime` or `ui` sibling
+// 4. %LOCALAPPDATA%\WSM (universal default on any Windows 10/11 PC)
+inline std::string resolve_wsm_root() {
+ namespace fs = std::filesystem;
+
+ // 1. Environment variable override
+ char env_buf[MAX_PATH] = {};
+ DWORD n = GetEnvironmentVariableA("WSM_ROOT", env_buf, MAX_PATH);
+ if (n > 0 && n < MAX_PATH) {
+ return std::string(env_buf, n);
+ }
+
+ // 2. Persistent user-chosen storage path (%LOCALAPPDATA%\WSM\root.txt)
+ char local_app[MAX_PATH] = {};
+ if (SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_LOCAL_APPDATA, nullptr, 0, local_app))) {
+ fs::path cfg = fs::path(local_app) / "WSM" / "root.txt";
+ if (fs::exists(cfg)) {
+ std::ifstream f(cfg);
+ std::string line;
+ if (std::getline(f, line) && !line.empty()) {
+ while (!line.empty() && (line.back() == '\r' || line.back() == '\n' || line.back() == ' ')) line.pop_back();
+ if (!line.empty()) return line;
+ }
+ }
+ }
+
+ // 3. Portable layout relative to exe (e.g. <root>\bin\wsmd.exe or <root>\build\native\bin\wsmd.exe)
+ char exe_buf[MAX_PATH] = {};
+ if (GetModuleFileNameA(nullptr, exe_buf, MAX_PATH) > 0) {
+ fs::path p = fs::path(exe_buf).parent_path();
+ for (int up = 0; up < 4; ++up) {
+ if (fs::exists(p / "src" / "wsm-manager") || fs::exists(p / "ui")) {
+ return p.string();
+ }
+ if (!p.has_parent_path() || p == p.parent_path()) break;
+ p = p.parent_path();
+ }
+ }
+
+ // 4. Universal fallback: %LOCALAPPDATA%\WSM
+ if (local_app[0] != '\0') {
+ return (fs::path(local_app) / "WSM").string();
+ }
+ return "C:\\WSM";
+}
+
+inline bool save_wsm_root(const std::string& new_root) {
+ namespace fs = std::filesystem;
+ char local_app[MAX_PATH] = {};
+ if (FAILED(SHGetFolderPathA(nullptr, CSIDL_LOCAL_APPDATA, nullptr, 0, local_app))) return false;
+ fs::path dir = fs::path(local_app) / "WSM";
+ std::error_code ec;
+ fs::create_directories(dir, ec);
+ std::ofstream f(dir / "root.txt", std::ios::trunc);
+ if (!f) return false;
+ f << new_root << "\n";
+ return true;
+}
+
+// Auto-tunes guest vCPUs & RAM dynamically for ANY host PC (8 GB / 16 GB / 32 GB / 64 GB+)
+inline void compute_recommended_guest_resources(uint32_t& out_vcpus, uint32_t& out_ram_mb) {
+ SYSTEM_INFO si{};
+ GetSystemInfo(&si);
+ uint32_t threads = si.dwNumberOfProcessors;
+ out_vcpus = (threads >= 12) ? 6 : (threads >= 8 ? 4 : (threads >= 4 ? 2 : 2));
+
+ MEMORYSTATUSEX ms{};
+ ms.dwLength = sizeof(ms);
+ uint64_t total_mb = 8192;
+ if (GlobalMemoryStatusEx(&ms)) {
+ total_mb = ms.ullTotalPhys / (1024ULL * 1024ULL);
+ }
+ // Use ~33% of host RAM, clamped to [4096 MB, 12288 MB] so Windows never swap-thrashes
+ uint64_t target = (total_mb / 3ULL / 1024ULL) * 1024ULL;
+ if (target < 4096) target = 4096;
+ if (target > 12288) target = 12288;
+ out_ram_mb = static_cast<uint32_t>(target);
+}
+
+} // namespace wsm::core
diff --git a/src/wsm-core/include/wsm/qmp_unix.hpp b/src/wsm-core/include/wsm/qmp_unix.hpp
new file mode 100644
index 0000000..277bc56
--- /dev/null
+++ b/src/wsm-core/include/wsm/qmp_unix.hpp
@@ -0,0 +1,55 @@
+#pragma once
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace wsm::core {
+
+// Native Windows Winsock AF_UNIX QMP client for reims-ctl / QEMU unix: sockets.
+// Enables headless screendump capture, input-send-event injection, and VM control
+// directly inside WSM Manager without opening a separate Reims or QEMU window.
+class QmpUnixClient {
+public:
+ // Empty = the default runtime's socket under the WSM root.
+ explicit QmpUnixClient(std::string socket_path = {});
+
+ bool execute(const std::string& json_cmd, std::string& response, uint32_t timeout_ms = 3000) const;
+ bool capture_screendump_ppm(const std::string& out_ppm_path, std::string& err) const;
+ bool send_mouse_click(int32_t abs_x_32k, int32_t abs_y_32k, const std::string& button = "left") const;
+ bool send_key_qcode(const std::string& qcode) const;
+ bool type_ascii_text(const std::string& text) const;
+
+private:
+ std::string socket_path_;
+};
+
+// One QMP connection kept open for many commands (QmpUnixClient pays a connect, the greeting
+// and qmp_capabilities on every command, which put that handshake into every keystroke and
+// every frame). QEMU serves one client per QMP socket, so a session needs a socket of its own
+// (RuntimeHost gives the runtime wsm-in.sock and wsm-cap.sock); when that socket isn't there
+// it falls back to a per-command QmpUnixClient on the shared one. Thread-safe.
+class QmpSession {
+public:
+ QmpSession(std::string own_socket, std::string fallback_socket = {});
+ ~QmpSession();
+ QmpSession(const QmpSession&) = delete;
+ QmpSession& operator=(const QmpSession&) = delete;
+
+ bool execute(const std::string& json_cmd, std::string& response, uint32_t timeout_ms = 3000);
+ bool capture_screendump_ppm(const std::string& out_ppm_path, std::string& err);
+ void close();
+
+private:
+ bool connect_locked(uint32_t timeout_ms);
+ bool read_line_locked(std::string& line);
+ std::string own_, fallback_;
+ uintptr_t sock_ = ~static_cast<uintptr_t>(0);
+ std::string buf_;
+ int64_t retry_after_ms_ = 0;
+ void* mu_ = nullptr; // std::mutex, kept out of this header
+};
+
+// Converts a binary P6 PPM screendump into a 24-bit BMP buffer for zero-dependency HTTP streaming to WSM Manager
+bool ppm_file_to_bmp_bytes(const std::string& ppm_path, std::vector<uint8_t>& out_bmp);
+
+} // namespace wsm::core
diff --git a/src/wsm-core/include/wsm/vm_manager.hpp b/src/wsm-core/include/wsm/vm_manager.hpp
new file mode 100644
index 0000000..2c46505
--- /dev/null
+++ b/src/wsm-core/include/wsm/vm_manager.hpp
@@ -0,0 +1,92 @@
+#pragma once
+#include "wsm/paths.hpp"
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace wsm::core {
+
+enum class VmState {
+ NotInstalled,
+ Stopped,
+ Starting,
+ Booting,
+ WaitingForGuest,
+ Ready,
+ Paused,
+ Stopping,
+ Crashed,
+};
+
+struct VmConfig {
+ std::string name = "wsm-default";
+ std::string qemu_binary = wsm::core::resolve_wsm_root() + "\\runtime\\reims-ctl\\qemu\\current\\bin\\qemu-system-x86_64.exe";
+ std::string ovmf_code_path = wsm::core::resolve_wsm_root() + "\\runtime\\reims-ctl\\vms\\wsm-default\\OVMF_CODE.fd";
+ std::string ovmf_vars_path = wsm::core::resolve_wsm_root() + "\\runtime\\reims-ctl\\vms\\wsm-default\\OVMF_VARS.fd";
+ std::string opencore_disk = wsm::core::resolve_wsm_root() + "\\runtime\\reims-ctl\\vms\\wsm-default\\opencore.qcow2";
+ std::string system_disk = wsm::core::resolve_wsm_root() + "\\runtime\\reims-ctl\\vms\\wsm-default\\disk.qcow2";
+ std::string reims_rom_path = wsm::core::resolve_wsm_root() + "\\runtime\\reims-ctl\\prebuilt\\ReimsGraphics-4da5fbb5f7090a4f.rom";
+ std::string shared_dir = wsm::core::resolve_wsm_root() + "\\fs";
+ std::string log_dir = wsm::core::resolve_wsm_root() + "\\logs";
+
+ uint32_t vcpus = 6;
+ uint32_t ram_mb = 5120;
+ uint32_t display_width = 1920;
+ uint32_t display_height = 1080;
+ bool headless = true; // REIMS_VGPU_WINDOW=0 for rootless mode
+ bool enable_reims_vgpu = true;
+ bool enable_whpx = true;
+
+ uint16_t qmp_port = 4444;
+ uint16_t agent_port = 4445; // Host <-> Guest WSM agent bridge
+ uint16_t ssh_forward_port = 2222;
+ std::string smc_osk = "ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc";
+};
+
+struct VmStatus {
+ VmState state = VmState::Stopped;
+ uint32_t pid = 0;
+ uint32_t last_exit_code = 0;
+ uint64_t uptime_ms = 0;
+ bool qmp_reachable = false;
+ std::string last_error;
+ std::string qemu_log_path;
+ std::string qemu_cmdline;
+};
+
+class VmManager {
+public:
+ VmManager() = default;
+ ~VmManager();
+
+ VmManager(const VmManager&) = delete;
+ VmManager& operator=(const VmManager&) = delete;
+
+ std::string build_qemu_command(const VmConfig& cfg) const;
+
+ bool start(const VmConfig& cfg, std::string& err);
+ bool stop_graceful(uint32_t timeout_ms = 10000);
+ bool force_terminate();
+ bool save_snapshot(const std::string& tag, std::string& err);
+ bool load_snapshot(const std::string& tag, std::string& err);
+ bool send_qmp_command(const std::string& json_cmd, std::string& response) const;
+
+ // Reads last N lines of captured QEMU stdout/stderr log
+ std::string read_qemu_log_tail(size_t max_lines = 40) const;
+
+ VmStatus status(bool guest_agent_connected = false) const;
+
+private:
+ VmConfig config_{};
+ VmState state_ = VmState::Stopped;
+ void* process_handle_ = nullptr;
+ void* log_file_handle_ = nullptr;
+ uint32_t pid_ = 0;
+ uint32_t last_exit_code_ = 0;
+ uint64_t start_tick_ms_ = 0;
+ std::string last_error_;
+ std::string last_cmdline_;
+ std::string qemu_log_path_;
+};
+
+} // namespace wsm::core
diff --git a/src/wsm-core/src/host_probe.cpp b/src/wsm-core/src/host_probe.cpp
new file mode 100644
index 0000000..ee462c6
--- /dev/null
+++ b/src/wsm-core/src/host_probe.cpp
@@ -0,0 +1,371 @@
+#include "wsm/host_probe.hpp"
+
+#include <windows.h>
+#include <WinHvPlatform.h>
+#include <dxgi1_6.h>
+#include <wrl/client.h>
+
+#include <cstring>
+#include <sstream>
+#include <vector>
+
+#pragma comment(lib, "WinHvPlatform.lib")
+#pragma comment(lib, "dxgi.lib")
+
+namespace wsm::core {
+
+namespace {
+
+// Minimal Vulkan types for dynamic loading (no Vulkan SDK required at compile time)
+using VkResult = int32_t;
+using VkFlags = uint32_t;
+using VkInstance = void*;
+using VkPhysicalDevice = void*;
+
+struct VkApplicationInfo {
+ uint32_t sType;
+ const void* pNext;
+ const char* pApplicationName;
+ uint32_t applicationVersion;
+ const char* pEngineName;
+ uint32_t engineVersion;
+ uint32_t apiVersion;
+};
+
+struct VkInstanceCreateInfo {
+ uint32_t sType;
+ const void* pNext;
+ VkFlags flags;
+ const VkApplicationInfo* pApplicationInfo;
+ uint32_t enabledLayerCount;
+ const char* const* ppEnabledLayerNames;
+ uint32_t enabledExtensionCount;
+ const char* const* ppEnabledExtensionNames;
+};
+
+struct VkPhysicalDeviceProperties {
+ uint32_t apiVersion;
+ uint32_t driverVersion;
+ uint32_t vendorID;
+ uint32_t deviceID;
+ uint32_t deviceType;
+ char deviceName[256];
+ uint8_t pipelineCacheUUID[16];
+ uint8_t limits_and_sparse[1024]; // oversized padding for ABI safety
+};
+
+struct VkExtensionProperties {
+ char extensionName[256];
+ uint32_t specVersion;
+};
+
+using PFN_vkCreateInstance = VkResult(__stdcall*)(const VkInstanceCreateInfo*, const void*, VkInstance*);
+using PFN_vkDestroyInstance = void(__stdcall*)(VkInstance, const void*);
+using PFN_vkEnumeratePhysicalDevices = VkResult(__stdcall*)(VkInstance, uint32_t*, VkPhysicalDevice*);
+using PFN_vkGetPhysicalDeviceProperties = void(__stdcall*)(VkPhysicalDevice, VkPhysicalDeviceProperties*);
+using PFN_vkEnumerateDeviceExtensionProperties = VkResult(__stdcall*)(VkPhysicalDevice, const char*, uint32_t*, VkExtensionProperties*);
+
+std::string wide_to_utf8(const wchar_t* wstr) {
+ if (!wstr || !*wstr) return {};
+ int len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, nullptr, 0, nullptr, nullptr);
+ if (len <= 1) return {};
+ std::string out(static_cast<size_t>(len - 1), '\0');
+ WideCharToMultiByte(CP_UTF8, 0, wstr, -1, out.data(), len, nullptr, nullptr);
+ return out;
+}
+
+std::string json_escape(const std::string& s) {
+ std::string out;
+ out.reserve(s.size() + 8);
+ for (char c : s) {
+ switch (c) {
+ case '"': out += "\\\""; break;
+ case '\\': out += "\\\\"; break;
+ case '\n': out += "\\n"; break;
+ case '\r': out += "\\r"; break;
+ case '\t': out += "\\t"; break;
+ default: out.push_back(c); break;
+ }
+ }
+ return out;
+}
+
+std::string read_cpu_brand_string() {
+ HKEY hKey = nullptr;
+ if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
+ "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
+ 0, KEY_READ, &hKey) != ERROR_SUCCESS) {
+ return "Unknown x86_64 CPU";
+ }
+ char buf[256] = {};
+ DWORD size = sizeof(buf) - 1;
+ DWORD type = 0;
+ std::string result = "Unknown x86_64 CPU";
+ if (RegQueryValueExA(hKey, "ProcessorNameString", nullptr, &type,
+ reinterpret_cast<LPBYTE>(buf), &size) == ERROR_SUCCESS) {
+ result = buf;
+ }
+ RegCloseKey(hKey);
+ return result;
+}
+
+std::string read_os_version() {
+ HKEY hKey = nullptr;
+ std::string product = "Windows 11";
+ std::string build = "unknown";
+ if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
+ "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
+ 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
+ char buf[128] = {};
+ DWORD size = sizeof(buf) - 1;
+ if (RegQueryValueExA(hKey, "ProductName", nullptr, nullptr,
+ reinterpret_cast<LPBYTE>(buf), &size) == ERROR_SUCCESS) {
+ product = buf;
+ }
+ size = sizeof(buf) - 1;
+ if (RegQueryValueExA(hKey, "CurrentBuildNumber", nullptr, nullptr,
+ reinterpret_cast<LPBYTE>(buf), &size) == ERROR_SUCCESS) {
+ build = buf;
+ }
+ RegCloseKey(hKey);
+ }
+ return product + " (Build " + build + ")";
+}
+
+} // namespace
+
+WhpxCapabilities probe_whpx(bool verify_partition_lifecycle) {
+ WhpxCapabilities caps{};
+
+ HMODULE hWhp = LoadLibraryW(L"WinHvPlatform.dll");
+ if (!hWhp) {
+ caps.error_detail = "WinHvPlatform.dll not found. Enable Windows Hypervisor Platform.";
+ return caps;
+ }
+ caps.dll_present = true;
+ FreeLibrary(hWhp);
+
+ WHV_CAPABILITY cap{};
+ UINT32 written = 0;
+ HRESULT hr = WHvGetCapability(WHvCapabilityCodeHypervisorPresent, &cap, sizeof(cap), &written);
+ if (FAILED(hr) || !cap.HypervisorPresent) {
+ std::ostringstream oss;
+ oss << "WHvGetCapability(HypervisorPresent) failed or false (hr=0x"
+ << std::hex << static_cast<uint32_t>(hr) << ")";
+ caps.error_detail = oss.str();
+ return caps;
+ }
+ caps.hypervisor_present = true;
+
+ std::memset(&cap, 0, sizeof(cap));
+ if (SUCCEEDED(WHvGetCapability(WHvCapabilityCodeFeatures, &cap, sizeof(cap), &written))) {
+ caps.features_mask = cap.Features.AsUINT64;
+ }
+
+ std::memset(&cap, 0, sizeof(cap));
+ if (SUCCEEDED(WHvGetCapability(WHvCapabilityCodeExtendedVmExits, &cap, sizeof(cap), &written))) {
+ caps.extended_vm_exits_mask = cap.ExtendedVmExits.AsUINT64;
+ }
+
+ std::memset(&cap, 0, sizeof(cap));
+ if (SUCCEEDED(WHvGetCapability(WHvCapabilityCodeProcessorVendor, &cap, sizeof(cap), &written))) {
+ caps.processor_vendor = static_cast<uint32_t>(cap.ProcessorVendor);
+ }
+
+ if (verify_partition_lifecycle) {
+ WHV_PARTITION_HANDLE partition = nullptr;
+ hr = WHvCreatePartition(&partition);
+ if (SUCCEEDED(hr) && partition != nullptr) {
+ WHV_PARTITION_PROPERTY prop{};
+ prop.ProcessorCount = 1;
+ hr = WHvSetPartitionProperty(partition, WHvPartitionPropertyCodeProcessorCount, &prop, sizeof(prop));
+ if (SUCCEEDED(hr)) {
+ hr = WHvSetupPartition(partition);
+ if (SUCCEEDED(hr)) {
+ hr = WHvCreateVirtualProcessor(partition, 0, 0);
+ if (SUCCEEDED(hr)) {
+ caps.partition_create_verified = true;
+ WHvDeleteVirtualProcessor(partition, 0);
+ } else {
+ caps.error_detail = "WHvCreateVirtualProcessor failed";
+ }
+ } else {
+ caps.error_detail = "WHvSetupPartition failed";
+ }
+ } else {
+ caps.error_detail = "WHvSetPartitionProperty(ProcessorCount) failed";
+ }
+ WHvDeletePartition(partition);
+ } else {
+ caps.error_detail = "WHvCreatePartition failed";
+ }
+ }
+
+ return caps;
+}
+
+GpuAdapterInfo probe_primary_gpu() {
+ GpuAdapterInfo info{};
+
+ // 1. DXGI probe for discrete GPU + VRAM
+ Microsoft::WRL::ComPtr<IDXGIFactory6> factory;
+ if (SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) {
+ Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter;
+ for (UINT idx = 0;
+ factory->EnumAdapterByGpuPreference(idx, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,
+ IID_PPV_ARGS(&adapter)) != DXGI_ERROR_NOT_FOUND;
+ ++idx) {
+ DXGI_ADAPTER_DESC1 desc{};
+ if (SUCCEEDED(adapter->GetDesc1(&desc))) {
+ if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) {
+ adapter.Reset();
+ continue;
+ }
+ info.name = wide_to_utf8(desc.Description);
+ info.vendor_id = desc.VendorId;
+ info.device_id = desc.DeviceId;
+ info.dedicated_vram_bytes = static_cast<uint64_t>(desc.DedicatedVideoMemory);
+ info.is_discrete = (desc.DedicatedVideoMemory >= 1024ULL * 1024ULL * 1024ULL);
+ break;
+ }
+ adapter.Reset();
+ }
+ }
+
+ // 2. Vulkan dynamic probe (vulkan-1.dll) for API version and Win32 external memory extensions
+ HMODULE hVk = LoadLibraryW(L"vulkan-1.dll");
+ if (hVk) {
+ auto fnCreateInstance = reinterpret_cast<PFN_vkCreateInstance>(GetProcAddress(hVk, "vkCreateInstance"));
+ auto fnDestroyInstance = reinterpret_cast<PFN_vkDestroyInstance>(GetProcAddress(hVk, "vkDestroyInstance"));
+ auto fnEnumPhys = reinterpret_cast<PFN_vkEnumeratePhysicalDevices>(GetProcAddress(hVk, "vkEnumeratePhysicalDevices"));
+ auto fnGetProps = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties>(GetProcAddress(hVk, "vkGetPhysicalDeviceProperties"));
+ auto fnEnumExt = reinterpret_cast<PFN_vkEnumerateDeviceExtensionProperties>(GetProcAddress(hVk, "vkEnumerateDeviceExtensionProperties"));
+
+ if (fnCreateInstance && fnDestroyInstance && fnEnumPhys && fnGetProps && fnEnumExt) {
+ VkApplicationInfo appInfo{};
+ appInfo.sType = 0; // VK_STRUCTURE_TYPE_APPLICATION_INFO
+ appInfo.pApplicationName = "WSM";
+ appInfo.applicationVersion = 1;
+ appInfo.pEngineName = "WSM";
+ appInfo.engineVersion = 1;
+ appInfo.apiVersion = (1u << 22) | (3u << 12); // Vulkan 1.3
+
+ VkInstanceCreateInfo ci{};
+ ci.sType = 1; // VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO
+ ci.pApplicationInfo = &appInfo;
+
+ VkInstance inst = nullptr;
+ if (fnCreateInstance(&ci, nullptr, &inst) == 0 && inst != nullptr) {
+ uint32_t devCount = 0;
+ if (fnEnumPhys(inst, &devCount, nullptr) == 0 && devCount > 0) {
+ std::vector<VkPhysicalDevice> devs(devCount);
+ if (fnEnumPhys(inst, &devCount, devs.data()) == 0) {
+ VkPhysicalDevice chosen = devs[0];
+ VkPhysicalDeviceProperties chosenProps{};
+ for (auto d : devs) {
+ VkPhysicalDeviceProperties p{};
+ fnGetProps(d, &p);
+ if (p.deviceType == 2) { // VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU
+ chosen = d;
+ chosenProps = p;
+ break;
+ }
+ if (chosen == d) chosenProps = p;
+ }
+ info.vulkan_supported = true;
+ info.vulkan_api_major = (chosenProps.apiVersion >> 22) & 0x7Fu;
+ info.vulkan_api_minor = (chosenProps.apiVersion >> 12) & 0x3FFu;
+ info.vulkan_api_patch = chosenProps.apiVersion & 0xFFFu;
+ if (info.name.empty()) {
+ info.name = chosenProps.deviceName;
+ info.vendor_id = chosenProps.vendorID;
+ info.device_id = chosenProps.deviceID;
+ }
+
+ uint32_t extCount = 0;
+ if (fnEnumExt(chosen, nullptr, &extCount, nullptr) == 0 && extCount > 0) {
+ std::vector<VkExtensionProperties> exts(extCount);
+ if (fnEnumExt(chosen, nullptr, &extCount, exts.data()) == 0) {
+ for (const auto& e : exts) {
+ if (std::strcmp(e.extensionName, "VK_KHR_external_memory_win32") == 0) {
+ info.ext_external_memory_win32 = true;
+ } else if (std::strcmp(e.extensionName, "VK_KHR_external_semaphore_win32") == 0) {
+ info.ext_external_semaphore_win32 = true;
+ }
+ }
+ }
+ }
+ }
+ }
+ fnDestroyInstance(inst, nullptr);
+ }
+ }
+ FreeLibrary(hVk);
+ }
+
+ return info;
+}
+
+HostSystemReport probe_host_system(const std::string& wsm_root) {
+ HostSystemReport r{};
+ r.os_version = read_os_version();
+ r.cpu_name = read_cpu_brand_string();
+ r.wsm_root = wsm_root;
+
+ SYSTEM_INFO si{};
+ GetSystemInfo(&si);
+ r.logical_cpus = si.dwNumberOfProcessors;
+
+ MEMORYSTATUSEX ms{};
+ ms.dwLength = sizeof(ms);
+ if (GlobalMemoryStatusEx(&ms)) {
+ r.total_ram_bytes = ms.ullTotalPhys;
+ r.avail_ram_bytes = ms.ullAvailPhys;
+ }
+
+ ULARGE_INTEGER freeBytes{};
+ if (GetDiskFreeSpaceExA(wsm_root.c_str(), &freeBytes, nullptr, nullptr)) {
+ r.storage_free_bytes = freeBytes.QuadPart;
+ }
+
+ r.whpx = probe_whpx(true);
+ r.primary_gpu = probe_primary_gpu();
+ return r;
+}
+
+std::string host_report_to_json(const HostSystemReport& r) {
+ std::ostringstream oss;
+ oss << "{\n"
+ << " \"os_version\": \"" << json_escape(r.os_version) << "\",\n"
+ << " \"cpu_name\": \"" << json_escape(r.cpu_name) << "\",\n"
+ << " \"logical_cpus\": " << r.logical_cpus << ",\n"
+ << " \"total_ram_mb\": " << (r.total_ram_bytes / (1024ULL * 1024ULL)) << ",\n"
+ << " \"avail_ram_mb\": " << (r.avail_ram_bytes / (1024ULL * 1024ULL)) << ",\n"
+ << " \"wsm_root\": \"" << json_escape(r.wsm_root) << "\",\n"
+ << " \"storage_free_gb\": " << (r.storage_free_bytes / (1024ULL * 1024ULL * 1024ULL)) << ",\n"
+ << " \"whpx\": {\n"
+ << " \"dll_present\": " << (r.whpx.dll_present ? "true" : "false") << ",\n"
+ << " \"hypervisor_present\": " << (r.whpx.hypervisor_present ? "true" : "false") << ",\n"
+ << " \"partition_create_verified\": " << (r.whpx.partition_create_verified ? "true" : "false") << ",\n"
+ << " \"features_mask\": " << r.whpx.features_mask << ",\n"
+ << " \"extended_vm_exits_mask\": " << r.whpx.extended_vm_exits_mask << ",\n"
+ << " \"error_detail\": \"" << json_escape(r.whpx.error_detail) << "\"\n"
+ << " },\n"
+ << " \"gpu\": {\n"
+ << " \"name\": \"" << json_escape(r.primary_gpu.name) << "\",\n"
+ << " \"vendor_id\": " << r.primary_gpu.vendor_id << ",\n"
+ << " \"device_id\": " << r.primary_gpu.device_id << ",\n"
+ << " \"dedicated_vram_mb\": " << (r.primary_gpu.dedicated_vram_bytes / (1024ULL * 1024ULL)) << ",\n"
+ << " \"is_discrete\": " << (r.primary_gpu.is_discrete ? "true" : "false") << ",\n"
+ << " \"vulkan_supported\": " << (r.primary_gpu.vulkan_supported ? "true" : "false") << ",\n"
+ << " \"vulkan_api\": \"" << r.primary_gpu.vulkan_api_major << "."
+ << r.primary_gpu.vulkan_api_minor << "."
+ << r.primary_gpu.vulkan_api_patch << "\",\n"
+ << " \"ext_external_memory_win32\": " << (r.primary_gpu.ext_external_memory_win32 ? "true" : "false") << ",\n"
+ << " \"ext_external_semaphore_win32\": " << (r.primary_gpu.ext_external_semaphore_win32 ? "true" : "false") << "\n"
+ << " }\n"
+ << "}";
+ return oss.str();
+}
+
+} // namespace wsm::core
diff --git a/src/wsm-core/src/qmp_unix.cpp b/src/wsm-core/src/qmp_unix.cpp
new file mode 100644
index 0000000..1c42b63
--- /dev/null
+++ b/src/wsm-core/src/qmp_unix.cpp
@@ -0,0 +1,357 @@
+#include "wsm/qmp_unix.hpp"
+#include "wsm/paths.hpp"
+
+#include <winsock2.h>
+#include <afunix.h>
+#include <windows.h>
+
+#include <chrono>
+#include <cstring>
+#include <mutex>
+#include <fstream>
+#include <sstream>
+
+#pragma comment(lib, "ws2_32.lib")
+
+namespace wsm::core {
+
+QmpUnixClient::QmpUnixClient(std::string socket_path) : socket_path_(std::move(socket_path)) {
+ if (socket_path_.empty()) {
+ // WSM_QMP_SOCKET (dev aid): drive another VM, e.g. a test copy, with the same tools.
+ char env[MAX_PATH] = {};
+ DWORD n = GetEnvironmentVariableA("WSM_QMP_SOCKET", env, MAX_PATH);
+ socket_path_ = (n > 0 && n < MAX_PATH) ? std::string(env, n)
+ : resolve_wsm_root() + "\\runtime\\reims-ctl\\vms\\wsm-default\\qmp.sock";
+ }
+}
+
+bool QmpUnixClient::execute(const std::string& json_cmd, std::string& response, uint32_t timeout_ms) const {
+ WSADATA wsa{};
+ if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return false;
+
+ SOCKET s = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (s == INVALID_SOCKET) {
+ WSACleanup();
+ return false;
+ }
+
+ DWORD to = timeout_ms;
+ setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&to), sizeof(to));
+ setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&to), sizeof(to));
+
+ SOCKADDR_UN addr{};
+ addr.sun_family = AF_UNIX;
+ if (socket_path_.size() >= sizeof(addr.sun_path)) {
+ closesocket(s);
+ WSACleanup();
+ return false;
+ }
+ std::memcpy(addr.sun_path, socket_path_.c_str(), socket_path_.size() + 1);
+
+ if (connect(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
+ closesocket(s);
+ WSACleanup();
+ return false;
+ }
+
+ auto read_line = [&](std::string& line) -> bool {
+ line.clear();
+ char ch = 0;
+ while (recv(s, &ch, 1, 0) == 1) {
+ if (ch == '\n') return true;
+ if (ch != '\r') line.push_back(ch);
+ if (line.size() > 65536) break;
+ }
+ return !line.empty();
+ };
+
+ std::string line;
+ if (!read_line(line)) { // QMP greeting
+ closesocket(s);
+ WSACleanup();
+ return false;
+ }
+
+ const char* caps = "{\"execute\":\"qmp_capabilities\"}\n";
+ send(s, caps, static_cast<int>(std::strlen(caps)), 0);
+ read_line(line);
+
+ std::string payload = json_cmd + "\n";
+ send(s, payload.c_str(), static_cast<int>(payload.size()), 0);
+
+ bool ok = false;
+ for (int i = 0; i < 8; ++i) {
+ if (!read_line(line)) break;
+ if (line.find("\"return\"") != std::string::npos || line.find("\"error\"") != std::string::npos) {
+ response = line;
+ ok = (line.find("\"return\"") != std::string::npos);
+ break;
+ }
+ }
+
+ closesocket(s);
+ WSACleanup();
+ return ok;
+}
+
+bool QmpUnixClient::capture_screendump_ppm(const std::string& out_ppm_path, std::string& err) const {
+ std::string escaped;
+ for (char c : out_ppm_path) {
+ if (c == '\\') escaped += "/";
+ else escaped.push_back(c);
+ }
+ std::string resp;
+ std::string cmd = "{\"execute\":\"screendump\",\"arguments\":{\"filename\":\"" + escaped + "\",\"device\":\"gfx\",\"head\":0,\"format\":\"ppm\"}}";
+ if (!execute(cmd, resp, 5000)) {
+ err = resp.empty() ? "QMP AF_UNIX screendump failed" : resp;
+ return false;
+ }
+ return true;
+}
+
+bool QmpUnixClient::send_mouse_click(int32_t abs_x_32k, int32_t abs_y_32k, const std::string& button) const {
+ std::string resp;
+ std::ostringstream move_cmd;
+ move_cmd << "{\"execute\":\"input-send-event\",\"arguments\":{\"device\":\"gfx\",\"head\":0,\"events\":["
+ << "{\"type\":\"abs\",\"data\":{\"axis\":\"x\",\"value\":" << abs_x_32k << "}},"
+ << "{\"type\":\"abs\",\"data\":{\"axis\":\"y\",\"value\":" << abs_y_32k << "}}"
+ << "]}}";
+ if (!execute(move_cmd.str(), resp, 1500)) return false;
+
+ std::string down = "{\"execute\":\"input-send-event\",\"arguments\":{\"events\":[{\"type\":\"btn\",\"data\":{\"down\":true,\"button\":\"" + button + "\"}}]}}";
+ std::string up = "{\"execute\":\"input-send-event\",\"arguments\":{\"events\":[{\"type\":\"btn\",\"data\":{\"down\":false,\"button\":\"" + button + "\"}}]}}";
+ execute(down, resp, 1500);
+ Sleep(40);
+ return execute(up, resp, 1500);
+}
+
+bool QmpUnixClient::send_key_qcode(const std::string& qcode) const {
+ std::string resp;
+ std::string cmd = "{\"execute\":\"send-key\",\"arguments\":{\"keys\":[{\"type\":\"qcode\",\"data\":\"" + qcode + "\"}],\"hold-time\":30}}";
+ return execute(cmd, resp, 1500);
+}
+
+bool QmpUnixClient::type_ascii_text(const std::string& text) const {
+ auto send_combo = [&](bool shift, const std::string& qcode) {
+ std::string resp;
+ std::string cmd = "{\"execute\":\"send-key\",\"arguments\":{\"keys\":[";
+ if (shift) cmd += "{\"type\":\"qcode\",\"data\":\"shift\"},";
+ cmd += "{\"type\":\"qcode\",\"data\":\"" + qcode + "\"}],\"hold-time\":25}}";
+ execute(cmd, resp, 1500);
+ Sleep(35);
+ };
+
+ for (char c : text) {
+ if (c >= 'a' && c <= 'z') { send_combo(false, std::string(1, c)); }
+ else if (c >= 'A' && c <= 'Z') { send_combo(true, std::string(1, static_cast<char>(c - 'A' + 'a'))); }
+ else if (c >= '0' && c <= '9') { send_combo(false, std::string(1, c)); }
+ else if (c == ' ') send_combo(false, "spc");
+ else if (c == '-') send_combo(false, "minus");
+ else if (c == '_') send_combo(true, "minus");
+ else if (c == '=') send_combo(false, "equal");
+ else if (c == '+') send_combo(true, "equal");
+ else if (c == '/') send_combo(false, "slash");
+ else if (c == '\\') send_combo(false, "backslash");
+ else if (c == '.') send_combo(false, "dot");
+ else if (c == ',') send_combo(false, "comma");
+ else if (c == ':') send_combo(true, "semicolon");
+ else if (c == ';') send_combo(false, "semicolon");
+ else if (c == '&') send_combo(true, "7");
+ else if (c == '*') send_combo(true, "8");
+ else if (c == '"') send_combo(true, "apostrophe");
+ else if (c == '\'') send_combo(false, "apostrophe");
+ else if (c == '\n') send_combo(false, "ret");
+ else if (c == '\t') send_combo(false, "tab");
+ else if (c == '|') send_combo(true, "backslash");
+ else if (c == '!') send_combo(true, "1");
+ else if (c == '@') send_combo(true, "2");
+ else if (c == '#') send_combo(true, "3");
+ else if (c == '$') send_combo(true, "4");
+ else if (c == '%') send_combo(true, "5");
+ else if (c == '^') send_combo(true, "6");
+ else if (c == '(') send_combo(true, "9");
+ else if (c == ')') send_combo(true, "0");
+ else if (c == '<') send_combo(true, "comma");
+ else if (c == '>') send_combo(true, "dot");
+ else if (c == '?') send_combo(true, "slash");
+ else if (c == '[') send_combo(false, "bracket_left");
+ else if (c == ']') send_combo(false, "bracket_right");
+ else if (c == '{') send_combo(true, "bracket_left");
+ else if (c == '}') send_combo(true, "bracket_right");
+ else if (c == '`') send_combo(false, "grave_accent");
+ else if (c == '~') send_combo(true, "grave_accent");
+ }
+ return true;
+}
+
+bool ppm_file_to_bmp_bytes(const std::string& ppm_path, std::vector<uint8_t>& out_bmp) {
+ std::ifstream f(ppm_path, std::ios::binary);
+ if (!f) return false;
+
+ std::string magic;
+ int width = 0, height = 0, maxval = 0;
+ f >> magic >> width >> height >> maxval;
+ if (magic != "P6" || width <= 0 || height <= 0 || width > 4096 || height > 4096 || maxval != 255) {
+ return false;
+ }
+ f.get(); // consume single whitespace byte after maxval
+
+ size_t rgb_size = static_cast<size_t>(width) * static_cast<size_t>(height) * 3u;
+ std::vector<uint8_t> rgb(rgb_size);
+ f.read(reinterpret_cast<char*>(rgb.data()), static_cast<std::streamsize>(rgb_size));
+ if (!f) return false;
+
+ // Downsample 2x if > 1280px wide for snappy embedded UI streaming over localhost
+ int out_w = (width > 1280) ? width / 2 : width;
+ int out_h = (width > 1280) ? height / 2 : height;
+ int step = (width > 1280) ? 2 : 1;
+
+ uint32_t row_stride = static_cast<uint32_t>((out_w * 3 + 3) & ~3);
+ uint32_t img_size = row_stride * static_cast<uint32_t>(out_h);
+ uint32_t file_size = 54u + img_size;
+
+ out_bmp.assign(file_size, 0);
+ out_bmp[0] = 'B'; out_bmp[1] = 'M';
+ std::memcpy(&out_bmp[2], &file_size, 4);
+ uint32_t off = 54;
+ std::memcpy(&out_bmp[10], &off, 4);
+ uint32_t hdr_sz = 40;
+ std::memcpy(&out_bmp[14], &hdr_sz, 4);
+ int32_t bw = out_w;
+ int32_t bh = -out_h; // top-down BMP
+ std::memcpy(&out_bmp[18], &bw, 4);
+ std::memcpy(&out_bmp[22], &bh, 4);
+ uint16_t planes = 1, bpp = 24;
+ std::memcpy(&out_bmp[26], &planes, 2);
+ std::memcpy(&out_bmp[28], &bpp, 2);
+ std::memcpy(&out_bmp[34], &img_size, 4);
+
+ for (int y = 0; y < out_h; ++y) {
+ uint8_t* dst = &out_bmp[54u + static_cast<size_t>(y) * row_stride];
+ const uint8_t* src_row = &rgb[static_cast<size_t>(y * step) * width * 3u];
+ for (int x = 0; x < out_w; ++x) {
+ const uint8_t* px = src_row + static_cast<size_t>(x * step) * 3u;
+ dst[x * 3 + 0] = px[2]; // B
+ dst[x * 3 + 1] = px[1]; // G
+ dst[x * 3 + 2] = px[0]; // R
+ }
+ }
+ return true;
+}
+
+
+// ---------------------------------------------------------------- QmpSession
+
+namespace {
+int64_t qmp_now_ms() {
+ return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+std::once_flag g_wsa_once;
+}
+
+QmpSession::QmpSession(std::string own_socket, std::string fallback_socket)
+ : own_(std::move(own_socket)), fallback_(std::move(fallback_socket)), mu_(new std::mutex) {
+ std::call_once(g_wsa_once, [] { WSADATA w{}; WSAStartup(MAKEWORD(2, 2), &w); });
+}
+
+QmpSession::~QmpSession() {
+ close();
+ delete static_cast<std::mutex*>(mu_);
+}
+
+void QmpSession::close() {
+ std::lock_guard<std::mutex> lk(*static_cast<std::mutex*>(mu_));
+ if (sock_ != ~static_cast<uintptr_t>(0)) closesocket(static_cast<SOCKET>(sock_));
+ sock_ = ~static_cast<uintptr_t>(0);
+ buf_.clear();
+}
+
+bool QmpSession::read_line_locked(std::string& line) {
+ for (;;) {
+ size_t nl = buf_.find('\n');
+ if (nl != std::string::npos) {
+ line = buf_.substr(0, nl);
+ if (!line.empty() && line.back() == '\r') line.pop_back();
+ buf_.erase(0, nl + 1);
+ return true;
+ }
+ char tmp[8192];
+ int n = recv(static_cast<SOCKET>(sock_), tmp, sizeof(tmp), 0);
+ if (n <= 0) return false;
+ buf_.append(tmp, static_cast<size_t>(n));
+ if (buf_.size() > (1u << 20)) return false;
+ }
+}
+
+bool QmpSession::connect_locked(uint32_t timeout_ms) {
+ if (sock_ != ~static_cast<uintptr_t>(0)) return true;
+ if (own_.empty() || qmp_now_ms() < retry_after_ms_) return false;
+ SOCKET s = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (s == INVALID_SOCKET) return false;
+ SOCKADDR_UN addr{};
+ addr.sun_family = AF_UNIX;
+ if (own_.size() >= sizeof(addr.sun_path)) { closesocket(s); return false; }
+ std::memcpy(addr.sun_path, own_.c_str(), own_.size() + 1);
+ DWORD to = timeout_ms;
+ setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&to), sizeof(to));
+ setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&to), sizeof(to));
+ if (connect(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
+ closesocket(s);
+ retry_after_ms_ = qmp_now_ms() + 2000; // not there (older runtime profile, or stopped)
+ return false;
+ }
+ sock_ = static_cast<uintptr_t>(s);
+ buf_.clear();
+ std::string line;
+ const char* caps = "{\"execute\":\"qmp_capabilities\"}\n";
+ if (!read_line_locked(line) || send(s, caps, static_cast<int>(std::strlen(caps)), 0) <= 0) {
+ closesocket(s); sock_ = ~static_cast<uintptr_t>(0); return false;
+ }
+ while (read_line_locked(line)) {
+ if (line.find("\"return\"") != std::string::npos) return true;
+ if (line.find("\"error\"") != std::string::npos) break;
+ }
+ closesocket(s);
+ sock_ = ~static_cast<uintptr_t>(0);
+ return false;
+}
+
+bool QmpSession::execute(const std::string& json_cmd, std::string& response, uint32_t timeout_ms) {
+ {
+ std::lock_guard<std::mutex> lk(*static_cast<std::mutex*>(mu_));
+ for (int attempt = 0; attempt < 2; ++attempt) {
+ if (!connect_locked(timeout_ms)) break;
+ DWORD to = timeout_ms;
+ setsockopt(static_cast<SOCKET>(sock_), SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&to), sizeof(to));
+ std::string payload = json_cmd + "\n";
+ bool sent = send(static_cast<SOCKET>(sock_), payload.c_str(), static_cast<int>(payload.size()), 0) > 0;
+ std::string line;
+ // Skip asynchronous events ({"event": ...}) until this command's reply.
+ while (sent && read_line_locked(line)) {
+ if (line.find("\"return\"") != std::string::npos || line.find("\"error\"") != std::string::npos) {
+ response = line;
+ return line.find("\"return\"") != std::string::npos;
+ }
+ }
+ // Dropped (QEMU restarted, paused too long, timeout): reconnect once.
+ closesocket(static_cast<SOCKET>(sock_));
+ sock_ = ~static_cast<uintptr_t>(0);
+ buf_.clear();
+ }
+ }
+ return QmpUnixClient(fallback_).execute(json_cmd, response, timeout_ms);
+}
+
+bool QmpSession::capture_screendump_ppm(const std::string& out_ppm_path, std::string& err) {
+ std::string escaped;
+ for (char c : out_ppm_path) escaped.push_back(c == '\\' ? '/' : c);
+ std::string resp;
+ if (!execute("{\"execute\":\"screendump\",\"arguments\":{\"filename\":\"" + escaped +
+ "\",\"device\":\"gfx\",\"head\":0,\"format\":\"ppm\"}}", resp, 5000)) {
+ err = resp.empty() ? "QMP screendump failed" : resp;
+ return false;
+ }
+ return true;
+}
+
+} // namespace wsm::core
diff --git a/src/wsm-core/src/vm_manager.cpp b/src/wsm-core/src/vm_manager.cpp
new file mode 100644
index 0000000..f34d848
--- /dev/null
+++ b/src/wsm-core/src/vm_manager.cpp
@@ -0,0 +1,395 @@
+#include "wsm/vm_manager.hpp"
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+
+#include <deque>
+#include <filesystem>
+#include <fstream>
+#include <sstream>
+
+#pragma comment(lib, "ws2_32.lib")
+
+namespace wsm::core {
+
+VmManager::~VmManager() {
+ if (process_handle_) {
+ CloseHandle(static_cast<HANDLE>(process_handle_));
+ process_handle_ = nullptr;
+ }
+ if (log_file_handle_) {
+ CloseHandle(static_cast<HANDLE>(log_file_handle_));
+ log_file_handle_ = nullptr;
+ }
+}
+
+std::string VmManager::build_qemu_command(const VmConfig& cfg) const {
+ std::ostringstream cmd;
+ cmd << "\"" << cfg.qemu_binary << "\" "
+ << "-name \"" << cfg.name << "\" "
+ << "-machine q35,memory-backend=ram,max-ram-below-4g=1G "
+ << "-object memory-backend-ram,id=ram,size=" << cfg.ram_mb << "M,share=on ";
+
+ if (cfg.enable_whpx) {
+ cmd << "-accel whpx ";
+ }
+
+ // Verified macOS Tahoe 26 WHPX CPU + PCI topology (matches reims-ctl slot assignments)
+ cmd << "-m " << cfg.ram_mb << "M "
+ << "-cpu Skylake-Client-noTSX-IBRS,kvm=on,vendor=GenuineIntel,+invtsc,vmware-cpuid-freq=on,"
+ "+ssse3,+sse4.2,+popcnt,+avx,+aes,+xsave,+xsaveopt,check "
+ << "-smp " << cfg.vcpus << ",sockets=1,cores=" << cfg.vcpus << ",threads=1 "
+ << "-global ICH9-LPC.acpi-pci-hotplug-with-bridge-support=off "
+ << "-global ICH9-LPC.disable_s3=1 "
+ << "-device pcie-root-port,bus=pcie.0,addr=0x1,slot=1,speed=16,width=32 ";
+
+ if (!cfg.smc_osk.empty()) {
+ cmd << "-device isa-applesmc,osk=\"" << cfg.smc_osk << "\" ";
+ }
+
+ cmd << "-smbios type=2 "
+ << "-smbios type=17,speed=2666,memory_type=26 "
+ << "-drive if=pflash,format=raw,readonly=on,file=\"" << cfg.ovmf_code_path << "\" "
+ << "-drive if=pflash,format=raw,file=\"" << cfg.ovmf_vars_path << "\" ";
+
+ // Storage on explicit PCI slot 0x2 (avoids collision with pcie-root-port at 0x1)
+ cmd << "-device ich9-ahci,id=sata,addr=0x2 ";
+ if (std::filesystem::exists(cfg.opencore_disk)) {
+ cmd << "-drive id=OpenCore,if=none,format=qcow2,file=\"" << cfg.opencore_disk << "\" "
+ << "-device ide-hd,bus=sata.2,drive=OpenCore,bootindex=1 ";
+ }
+ if (std::filesystem::exists(cfg.system_disk)) {
+ cmd << "-drive id=MacHDD,if=none,format=qcow2,cache.no-flush=on,file=\"" << cfg.system_disk << "\" "
+ << "-device ide-hd,bus=sata.3,drive=MacHDD,rotation_rate=1 ";
+ }
+
+ // Paravirtualized GPU (reims-graphics-pci, PCI 1234:5247 -> Metal2Vulkan)
+ // CRITICAL: -vga none prevents QEMU from attaching default VGA to pcie.0 slot 0x1!
+ if (cfg.enable_reims_vgpu) {
+ cmd << "-vga none "
+ << "-device reims-graphics-pci,id=gfx,bus=pcie.0,addr=0x4,resolution="
+ << cfg.display_width << "x" << cfg.display_height;
+ if (std::filesystem::exists(cfg.reims_rom_path)) {
+ cmd << ",romfile=\"" << cfg.reims_rom_path << "\"";
+ }
+ cmd << " ";
+ } else {
+ cmd << "-vga std ";
+ }
+
+ if (cfg.headless) {
+ cmd << "-display none ";
+ }
+
+ // USB HID for keyboard & pointer injection on explicit PCI slot 0x5
+ cmd << "-device qemu-xhci,id=xhci,addr=0x5,conditional-intr-mapping=on,p2=7,p3=7 "
+ << "-device usb-kbd,bus=xhci.0 "
+ << "-device usb-tablet,bus=xhci.0 ";
+
+ // Networking on explicit PCI slot 0x3 with hostfwd for WSM agent (4445) & SSH (2222)
+ cmd << "-netdev user,id=net0,ipv6=off,"
+ << "hostfwd=tcp:127.0.0.1:" << cfg.agent_port << "-:" << cfg.agent_port << ","
+ << "hostfwd=tcp:127.0.0.1:" << cfg.ssh_forward_port << "-:22 "
+ << "-device virtio-net-pci,netdev=net0,addr=0x3 ";
+
+ // DirectSound + VirtIO audio on explicit PCI slot 0x7
+ cmd << "-audiodev dsound,id=snd0 "
+ << "-device virtio-sound-pci,id=audio,audiodev=snd0,addr=0x7,streams=1 ";
+
+ // QMP control socket on localhost TCP + guest serial log
+ cmd << "-qmp tcp:127.0.0.1:" << cfg.qmp_port << ",server=on,wait=off "
+ << "-serial file:\"" << cfg.log_dir << "\\" << cfg.name << "-serial.log\"";
+
+ return cmd.str();
+}
+
+std::string VmManager::read_qemu_log_tail(size_t max_lines) const {
+ if (qemu_log_path_.empty() || !std::filesystem::exists(qemu_log_path_)) return {};
+ std::ifstream f(qemu_log_path_);
+ if (!f) return {};
+ std::deque<std::string> lines;
+ std::string line;
+ while (std::getline(f, line)) {
+ if (!line.empty() && line.back() == '\r') line.pop_back();
+ lines.push_back(line);
+ if (lines.size() > max_lines) lines.pop_front();
+ }
+ std::ostringstream oss;
+ for (size_t i = 0; i < lines.size(); ++i) {
+ oss << lines[i];
+ if (i + 1 < lines.size()) oss << "\n";
+ }
+ return oss.str();
+}
+
+bool VmManager::start(const VmConfig& cfg, std::string& err) {
+ // Check live process status first so stale crashed handles don't block restart
+ if (process_handle_) {
+ DWORD code = 0;
+ if (GetExitCodeProcess(static_cast<HANDLE>(process_handle_), &code) && code == STILL_ACTIVE) {
+ err = "VM is already running (PID " + std::to_string(pid_) + ").";
+ return false;
+ }
+ CloseHandle(static_cast<HANDLE>(process_handle_));
+ process_handle_ = nullptr;
+ pid_ = 0;
+ }
+ if (log_file_handle_) {
+ CloseHandle(static_cast<HANDLE>(log_file_handle_));
+ log_file_handle_ = nullptr;
+ }
+
+ if (!std::filesystem::exists(cfg.qemu_binary)) {
+ err = "QEMU binary not found: " + cfg.qemu_binary;
+ last_error_ = err;
+ return false;
+ }
+ if (!std::filesystem::exists(cfg.opencore_disk) || !std::filesystem::exists(cfg.system_disk)) {
+ err = "macOS virtual disk or OpenCore image not found. Provision macOS in macOS Setup first.";
+ last_error_ = err;
+ state_ = VmState::NotInstalled;
+ return false;
+ }
+
+ // Guard against duplicate instance already listening on QMP port
+ {
+ std::string probe;
+ config_ = cfg;
+ if (send_qmp_command("{\"execute\":\"query-status\"}", probe)) {
+ err = "Another QEMU instance is already listening on QMP port " + std::to_string(cfg.qmp_port) + ".";
+ last_error_ = err;
+ return false;
+ }
+ }
+
+ std::filesystem::create_directories(cfg.log_dir);
+ qemu_log_path_ = cfg.log_dir + "\\" + cfg.name + "-qemu.log";
+ last_cmdline_ = build_qemu_command(cfg);
+
+ if (cfg.headless) {
+ SetEnvironmentVariableA("REIMS_VGPU_WINDOW", "0");
+ } else {
+ SetEnvironmentVariableA("REIMS_VGPU_WINDOW", "1");
+ }
+ SetEnvironmentVariableA("REIMS_VGPU_LOG", "info");
+
+ // Redirect QEMU stdout and stderr directly to qemu_log_path_ for real crash diagnostics
+ SECURITY_ATTRIBUTES sa{};
+ sa.nLength = sizeof(sa);
+ sa.bInheritHandle = TRUE;
+ HANDLE hLog = CreateFileA(
+ qemu_log_path_.c_str(),
+ GENERIC_WRITE,
+ FILE_SHARE_READ | FILE_SHARE_WRITE,
+ &sa,
+ CREATE_ALWAYS,
+ FILE_ATTRIBUTE_NORMAL,
+ nullptr
+ );
+
+ STARTUPINFOA si{};
+ si.cb = sizeof(si);
+ if (hLog != INVALID_HANDLE_VALUE) {
+ si.dwFlags = STARTF_USESTDHANDLES;
+ si.hStdOutput = hLog;
+ si.hStdError = hLog;
+ si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
+ }
+
+ PROCESS_INFORMATION pi{};
+ std::string mutable_cmd = last_cmdline_;
+ BOOL ok = CreateProcessA(
+ nullptr,
+ mutable_cmd.data(),
+ nullptr,
+ nullptr,
+ hLog != INVALID_HANDLE_VALUE ? TRUE : FALSE,
+ CREATE_NO_WINDOW,
+ nullptr,
+ nullptr,
+ &si,
+ &pi
+ );
+
+ if (!ok) {
+ DWORD e = GetLastError();
+ if (hLog != INVALID_HANDLE_VALUE) CloseHandle(hLog);
+ err = "CreateProcessA failed for QEMU (Win32 error " + std::to_string(e) + ")";
+ last_error_ = err;
+ state_ = VmState::Crashed;
+ return false;
+ }
+
+ CloseHandle(pi.hThread);
+ process_handle_ = pi.hProcess;
+ log_file_handle_ = (hLog != INVALID_HANDLE_VALUE) ? hLog : nullptr;
+ pid_ = pi.dwProcessId;
+ last_exit_code_ = 0;
+ start_tick_ms_ = GetTickCount64();
+ state_ = VmState::Starting;
+ last_error_.clear();
+
+ // Wait briefly (600 ms) to catch immediate startup failures (bad args, locked disk, WHPX/GPU error)
+ DWORD wait = WaitForSingleObject(pi.hProcess, 600);
+ if (wait == WAIT_OBJECT_0) {
+ DWORD code = 1;
+ GetExitCodeProcess(pi.hProcess, &code);
+ last_exit_code_ = code;
+ state_ = VmState::Crashed;
+ std::string tail = read_qemu_log_tail(12);
+ err = "QEMU exited immediately (code " + std::to_string(code) + "): " +
+ (tail.empty() ? "no stderr output" : tail);
+ last_error_ = err;
+ return false;
+ }
+
+ state_ = VmState::Booting;
+ return true;
+}
+
+bool VmManager::send_qmp_command(const std::string& json_cmd, std::string& response) const {
+ WSADATA wsa{};
+ if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return false;
+
+ SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (sock == INVALID_SOCKET) {
+ WSACleanup();
+ return false;
+ }
+
+ DWORD timeout = 1500;
+ setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&timeout), sizeof(timeout));
+ setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&timeout), sizeof(timeout));
+
+ sockaddr_in addr{};
+ addr.sin_family = AF_INET;
+ addr.sin_port = htons(config_.qmp_port);
+ inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
+
+ if (connect(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
+ closesocket(sock);
+ WSACleanup();
+ return false;
+ }
+
+ char buf[4096];
+ recv(sock, buf, sizeof(buf) - 1, 0);
+
+ const char* caps = "{\"execute\":\"qmp_capabilities\"}\n";
+ send(sock, caps, static_cast<int>(strlen(caps)), 0);
+ recv(sock, buf, sizeof(buf) - 1, 0);
+
+ std::string payload = json_cmd + "\n";
+ send(sock, payload.c_str(), static_cast<int>(payload.size()), 0);
+ int n = recv(sock, buf, sizeof(buf) - 1, 0);
+ if (n > 0) {
+ buf[n] = '\0';
+ response = buf;
+ }
+
+ closesocket(sock);
+ WSACleanup();
+ return n > 0;
+}
+
+bool VmManager::stop_graceful(uint32_t timeout_ms) {
+ if (!process_handle_) return true;
+ state_ = VmState::Stopping;
+ std::string resp;
+ send_qmp_command("{\"execute\":\"system_powerdown\"}", resp);
+
+ DWORD wait = WaitForSingleObject(static_cast<HANDLE>(process_handle_), timeout_ms);
+ if (wait == WAIT_OBJECT_0) {
+ CloseHandle(static_cast<HANDLE>(process_handle_));
+ process_handle_ = nullptr;
+ if (log_file_handle_) {
+ CloseHandle(static_cast<HANDLE>(log_file_handle_));
+ log_file_handle_ = nullptr;
+ }
+ pid_ = 0;
+ state_ = VmState::Stopped;
+ return true;
+ }
+ return force_terminate();
+}
+
+bool VmManager::force_terminate() {
+ if (!process_handle_) {
+ state_ = VmState::Stopped;
+ return true;
+ }
+ TerminateProcess(static_cast<HANDLE>(process_handle_), 1);
+ WaitForSingleObject(static_cast<HANDLE>(process_handle_), 3000);
+ CloseHandle(static_cast<HANDLE>(process_handle_));
+ process_handle_ = nullptr;
+ if (log_file_handle_) {
+ CloseHandle(static_cast<HANDLE>(log_file_handle_));
+ log_file_handle_ = nullptr;
+ }
+ pid_ = 0;
+ state_ = VmState::Stopped;
+ return true;
+}
+
+bool VmManager::save_snapshot(const std::string& tag, std::string& err) {
+ std::string resp;
+ std::string cmd = "{\"execute\":\"human-monitor-command\",\"arguments\":{\"command-line\":\"savevm " + tag + "\"}}";
+ if (!send_qmp_command(cmd, resp)) {
+ err = "QMP savevm failed";
+ return false;
+ }
+ return true;
+}
+
+bool VmManager::load_snapshot(const std::string& tag, std::string& err) {
+ std::string resp;
+ std::string cmd = "{\"execute\":\"human-monitor-command\",\"arguments\":{\"command-line\":\"loadvm " + tag + "\"}}";
+ if (!send_qmp_command(cmd, resp)) {
+ err = "QMP loadvm failed";
+ return false;
+ }
+ return true;
+}
+
+VmStatus VmManager::status(bool guest_agent_connected) const {
+ VmStatus st{};
+ st.state = state_;
+ st.pid = pid_;
+ st.last_exit_code = last_exit_code_;
+ st.last_error = last_error_;
+ st.qemu_log_path = qemu_log_path_;
+ st.qemu_cmdline = last_cmdline_;
+
+ if (!process_handle_) {
+ if (!config_.system_disk.empty() && !std::filesystem::exists(config_.system_disk)) {
+ st.state = VmState::NotInstalled;
+ }
+ return st;
+ }
+
+ DWORD code = 0;
+ if (GetExitCodeProcess(static_cast<HANDLE>(process_handle_), &code) && code != STILL_ACTIVE) {
+ st.last_exit_code = code;
+ st.state = (code == 0) ? VmState::Stopped : VmState::Crashed;
+ if (code != 0 && st.last_error.empty()) {
+ std::string tail = read_qemu_log_tail(10);
+ st.last_error = "QEMU exited with code " + std::to_string(code) +
+ (tail.empty() ? "" : ": " + tail);
+ }
+ } else {
+ st.uptime_ms = GetTickCount64() - start_tick_ms_;
+ std::string resp;
+ st.qmp_reachable = send_qmp_command("{\"execute\":\"query-status\"}", resp);
+ if (guest_agent_connected) {
+ st.state = VmState::Ready;
+ } else if (st.qmp_reachable) {
+ st.state = VmState::WaitingForGuest;
+ } else {
+ st.state = VmState::Booting;
+ }
+ }
+ return st;
+}
+
+} // namespace wsm::core
diff --git a/src/wsm-guest-agent/Makefile b/src/wsm-guest-agent/Makefile
new file mode 100644
index 0000000..cfd8a6e
--- /dev/null
+++ b/src/wsm-guest-agent/Makefile
@@ -0,0 +1,11 @@
+CC = clang
+CFLAGS = -O2 -Wall -fobjc-arc
+FRAMEWORKS = -framework Foundation -framework AppKit -framework CoreGraphics
+
+all: wsm-guest-agent
+
+wsm-guest-agent: wsm_guest_agent.m
+ $(CC) $(CFLAGS) wsm_guest_agent.m -o wsm-guest-agent $(FRAMEWORKS)
+
+clean:
+ rm -f wsm-guest-agent
diff --git a/src/wsm-guest-agent/com.wsm.guestagent.plist b/src/wsm-guest-agent/com.wsm.guestagent.plist
new file mode 100644
index 0000000..f0ea767
--- /dev/null
+++ b/src/wsm-guest-agent/com.wsm.guestagent.plist
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>com.wsm.guestagent</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>/usr/local/bin/wsm-guest-agent</string>
+ <string>4445</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <true/>
+ <key>StandardOutPath</key>
+ <string>/tmp/wsm-guest-agent.log</string>
+ <key>StandardErrorPath</key>
+ <string>/tmp/wsm-guest-agent.err</string>
+</dict>
+</plist>
diff --git a/src/wsm-guest-agent/install-in-guest.sh b/src/wsm-guest-agent/install-in-guest.sh
new file mode 100644
index 0000000..e32c216
--- /dev/null
+++ b/src/wsm-guest-agent/install-in-guest.sh
@@ -0,0 +1,48 @@
+#!/bin/bash
+# WSM Zero-Touch Guest Bootstrapper
+# 1. Mounts Windows W:\ (F:\WSM\fs) natively at /Volumes/WSM (smb://10.0.2.2/qemu)
+# 2. Creates ~/WSM symlink and auto-mount LaunchAgent (com.wsm.mount)
+# 3. Compiles and registers wsm-guest-agent (rootless windows + clipboard + input)
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+
+echo "==> [1/3] Mounting Windows WSM Drive (W:\ <-> /Volumes/WSM)..."
+sudo mkdir -p /Volumes/WSM
+mount_smbfs -N //[email protected]/qemu /Volumes/WSM 2>/dev/null || true
+ln -sfn /Volumes/WSM "$HOME/WSM"
+
+mkdir -p "$HOME/Library/LaunchAgents"
+cat > "$HOME/Library/LaunchAgents/com.wsm.mount.plist" <<'EOF'
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key><string>com.wsm.mount</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>/bin/sh</string>
+ <string>-c</string>
+ <string>mkdir -p /Volumes/WSM && mount_smbfs -N //[email protected]/qemu /Volumes/WSM</string>
+ </array>
+ <key>RunAtLoad</key><true/>
+</dict>
+</plist>
+EOF
+launchctl load -w "$HOME/Library/LaunchAgents/com.wsm.mount.plist" 2>/dev/null || true
+
+echo "==> [2/3] Building wsm-guest-agent..."
+clang -O2 -Wall -fobjc-arc "$SCRIPT_DIR/wsm_guest_agent.m" \
+ -o /tmp/wsm-guest-agent \
+ -framework Foundation -framework AppKit -framework CoreGraphics
+
+sudo mkdir -p /usr/local/bin
+sudo mv /tmp/wsm-guest-agent /usr/local/bin/wsm-guest-agent
+sudo chmod +x /usr/local/bin/wsm-guest-agent
+
+echo "==> [3/3] Registering LaunchAgent (com.wsm.guestagent)..."
+cp "$SCRIPT_DIR/com.wsm.guestagent.plist" "$HOME/Library/LaunchAgents/com.wsm.guestagent.plist"
+launchctl unload "$HOME/Library/LaunchAgents/com.wsm.guestagent.plist" 2>/dev/null || true
+launchctl load -w "$HOME/Library/LaunchAgents/com.wsm.guestagent.plist"
+
+echo "==> WSM Guest integration complete! Windows W:\ is live at /Volumes/WSM and ~/WSM."
diff --git a/src/wsm-guest-agent/wsm_guest_agent.m b/src/wsm-guest-agent/wsm_guest_agent.m
new file mode 100644
index 0000000..e5ad3de
--- /dev/null
+++ b/src/wsm-guest-agent/wsm_guest_agent.m
@@ -0,0 +1,314 @@
+// WSM Guest Integration Agent (macOS x86_64 / arm64)
+// Connects to Windows host wsmd.exe over virtio-net/vsock TCP bridge (port 4445).
+// Discovers genuine macOS application windows via CoreGraphics / AppKit,
+// streams per-window surfaces to WSM DirectComposition compositor,
+// injects host keyboard/mouse/scroll events via CGEventPost,
+// syncs NSPasteboard <-> Windows Clipboard, and launches .app bundles
+// (routing ARM64-only binaries through rebar/maclator when on x86_64 guest).
+
+#import <Foundation/Foundation.h>
+#import <AppKit/AppKit.h>
+#import <CoreGraphics/CoreGraphics.h>
+
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <string.h>
+
+#define WSM_MAGIC 0x57534D31u
+#define WSM_PROTO_VERSION 1u
+
+#pragma pack(push, 1)
+typedef struct {
+ uint32_t magic;
+ uint16_t version;
+ uint16_t channel;
+ uint16_t type;
+ uint16_t flags;
+ uint32_t seq;
+ uint32_t payload_size;
+} WsmFrameHeader;
+
+typedef struct {
+ uint64_t window_id;
+ uint64_t parent_window_id;
+ uint32_t pid;
+ uint32_t style_flags;
+ int32_t x, y, width, height;
+ float scale_factor;
+ uint8_t visible;
+ uint8_t focused;
+ uint16_t title_len;
+} WsmWindowDescriptor;
+
+typedef struct {
+ uint64_t window_id;
+ uint32_t width;
+ uint32_t height;
+ uint32_t stride;
+ uint32_t pixel_format; // 0 = BGRA8888
+ uint32_t dirty_x, dirty_y, dirty_w, dirty_h;
+ uint64_t iosurface_id;
+ uint64_t timestamp_us;
+} WsmWindowFrameHeader;
+
+typedef struct {
+ uint64_t window_id;
+ uint32_t vk_code;
+ uint32_t mac_keycode;
+ uint32_t modifiers;
+ uint8_t pressed;
+ uint8_t repeat;
+ uint16_t reserved;
+} WsmInputKeyEvent;
+
+typedef struct {
+ uint64_t window_id;
+ int32_t x, y;
+ uint32_t modifiers;
+} WsmInputMouseMoveEvent;
+
+typedef struct {
+ uint64_t window_id;
+ int32_t x, y;
+ uint8_t button;
+ uint8_t pressed;
+ uint16_t clicks;
+ uint32_t modifiers;
+} WsmInputMouseButtonEvent;
+#pragma pack(pop)
+
+static uint32_t g_seq = 1;
+
+static BOOL send_all(int fd, const void *buf, size_t len) {
+ const uint8_t *p = (const uint8_t *)buf;
+ while (len > 0) {
+ ssize_t n = send(fd, p, len, 0);
+ if (n <= 0) return NO;
+ p += n;
+ len -= (size_t)n;
+ }
+ return YES;
+}
+
+static BOOL send_frame(int fd, uint16_t channel, uint16_t type, const void *payload, uint32_t size) {
+ WsmFrameHeader hdr = {
+ .magic = WSM_MAGIC,
+ .version = WSM_PROTO_VERSION,
+ .channel = channel,
+ .type = type,
+ .flags = 0,
+ .seq = g_seq++,
+ .payload_size = size
+ };
+ if (!send_all(fd, &hdr, sizeof(hdr))) return NO;
+ if (size > 0 && payload) {
+ return send_all(fd, payload, size);
+ }
+ return YES;
+}
+
+static void inject_key_event(const WsmInputKeyEvent *ev) {
+ if (ev->mac_keycode == 0xFF) return;
+ CGEventRef keyEv = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)ev->mac_keycode, ev->pressed != 0);
+ if (!keyEv) return;
+ CGEventFlags flags = 0;
+ if (ev->modifiers & (1u << 0)) flags |= kCGEventFlagMaskShift;
+ if (ev->modifiers & (1u << 1)) flags |= kCGEventFlagMaskControl;
+ if (ev->modifiers & (1u << 2)) flags |= kCGEventFlagMaskAlternate;
+ if (ev->modifiers & (1u << 3)) flags |= kCGEventFlagMaskCommand;
+ CGEventSetFlags(keyEv, flags);
+ CGEventPost(kCGHIDEventTap, keyEv);
+ CFRelease(keyEv);
+}
+
+static void inject_mouse_button(const WsmInputMouseButtonEvent *ev) {
+ CGPoint pt = CGPointMake(ev->x, ev->y);
+ CGEventType type = kCGEventLeftMouseDown;
+ CGMouseButton btn = kCGMouseButtonLeft;
+ if (ev->button == 0) {
+ type = ev->pressed ? kCGEventLeftMouseDown : kCGEventLeftMouseUp;
+ btn = kCGMouseButtonLeft;
+ } else if (ev->button == 1) {
+ type = ev->pressed ? kCGEventRightMouseDown : kCGEventRightMouseUp;
+ btn = kCGMouseButtonRight;
+ } else {
+ type = ev->pressed ? kCGEventOtherMouseDown : kCGEventOtherMouseUp;
+ btn = kCGMouseButtonCenter;
+ }
+ CGEventRef mEv = CGEventCreateMouseEvent(NULL, type, pt, btn);
+ if (mEv) {
+ CGEventPost(kCGHIDEventTap, mEv);
+ CFRelease(mEv);
+ }
+}
+
+static void sync_visible_windows(int fd) {
+ CFArrayRef list = CGWindowListCopyWindowInfo(
+ kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,
+ kCGNullWindowID
+ );
+ if (!list) return;
+
+ CFIndex count = CFArrayGetCount(list);
+ for (CFIndex i = 0; i < count; i++) {
+ NSDictionary *info = (__bridge NSDictionary *)CFArrayGetValueAtIndex(list, i);
+ NSNumber *layer = info[(id)kCGWindowLayer];
+ if (layer && layer.intValue != 0) continue; // Only normal application windows
+
+ NSString *owner = info[(id)kCGWindowOwnerName] ?: @"";
+ if ([owner isEqualToString:@"Window Server"] || [owner isEqualToString:@"Dock"]) continue;
+
+ uint64_t wid = [info[(id)kCGWindowNumber] unsignedLongLongValue];
+ uint32_t pid = [info[(id)kCGWindowOwnerPID] unsignedIntValue];
+ NSString *name = info[(id)kCGWindowName] ?: owner;
+ NSDictionary *boundsDict = info[(id)kCGWindowBounds];
+ CGRect rect = CGRectZero;
+ if (boundsDict) CGRectMakeWithDictionaryRepresentation((__bridge CFDictionaryRef)boundsDict, &rect);
+ if (rect.size.width < 16 || rect.size.height < 16) continue;
+
+ const char *titleUtf8 = name.UTF8String ?: "";
+ uint16_t titleLen = (uint16_t)strnlen(titleUtf8, 512);
+
+ WsmWindowDescriptor desc = {0};
+ desc.window_id = wid;
+ desc.pid = pid;
+ desc.style_flags = 0x7; // resizable, closable, minimizable
+ desc.x = (int32_t)rect.origin.x;
+ desc.y = (int32_t)rect.origin.y;
+ desc.width = (int32_t)rect.size.width;
+ desc.height = (int32_t)rect.size.height;
+ desc.scale_factor = 1.0f;
+ desc.visible = 1;
+ desc.title_len = titleLen;
+
+ NSMutableData *buf = [NSMutableData dataWithCapacity:sizeof(desc) + titleLen];
+ [buf appendBytes:&desc length:sizeof(desc)];
+ if (titleLen > 0) [buf appendBytes:titleUtf8 length:titleLen];
+ send_frame(fd, 2 /* Window */, 0x0102 /* WindowUpdated */, buf.bytes, (uint32_t)buf.length);
+
+ // Capture per-window image as BGRA32 (zero-desktop-chrome, rootless)
+ CGImageRef img = CGWindowListCreateImage(
+ CGRectNull,
+ kCGWindowListOptionIncludingWindow,
+ (CGWindowID)wid,
+ kCGWindowImageBoundsIgnoreFraming | kCGWindowImageNominalResolution
+ );
+ if (img) {
+ uint32_t w = (uint32_t)CGImageGetWidth(img);
+ uint32_t h = (uint32_t)CGImageGetHeight(img);
+ uint32_t stride = w * 4;
+ if (w > 0 && h > 0 && (size_t)stride * h <= 32 * 1024 * 1024) {
+ NSMutableData *frameData = [NSMutableData dataWithLength:sizeof(WsmWindowFrameHeader) + (size_t)stride * h];
+ WsmWindowFrameHeader *fh = (WsmWindowFrameHeader *)frameData.mutableBytes;
+ fh->window_id = wid;
+ fh->width = w;
+ fh->height = h;
+ fh->stride = stride;
+ fh->pixel_format = 0; // BGRA8888
+ fh->dirty_w = w;
+ fh->dirty_h = h;
+
+ uint8_t *pixels = (uint8_t *)frameData.mutableBytes + sizeof(WsmWindowFrameHeader);
+ CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
+ CGContextRef ctx = CGBitmapContextCreate(
+ pixels, w, h, 8, stride, cs,
+ kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst
+ );
+ if (ctx) {
+ CGContextDrawImage(ctx, CGRectMake(0, 0, w, h), img);
+ CGContextRelease(ctx);
+ send_frame(fd, 2, 0x0103 /* WindowFrame */, frameData.bytes, (uint32_t)frameData.length);
+ }
+ CGColorSpaceRelease(cs);
+ }
+ CGImageRelease(img);
+ }
+ }
+ CFRelease(list);
+}
+
+int main(int argc, const char *argv[]) {
+ @autoreleasepool {
+ int port = 4445;
+ if (argc >= 2) port = atoi(argv[1]);
+
+ int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
+ int opt = 1;
+ setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
+
+ struct sockaddr_in addr = {0};
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = INADDR_ANY;
+ addr.sin_port = htons((uint16_t)port);
+
+ if (bind(listen_fd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(listen_fd, 4) != 0) {
+ NSLog(@"[wsm-guest-agent] Failed to bind port %d", port);
+ return 1;
+ }
+ NSLog(@"[wsm-guest-agent] Listening on port %d for Windows WSM host...", port);
+
+ while (1) {
+ int client = accept(listen_fd, NULL, NULL);
+ if (client < 0) continue;
+ NSLog(@"[wsm-guest-agent] Host connected.");
+
+ NSInteger lastPasteboardCount = [NSPasteboard generalPasteboard].changeCount;
+ while (1) {
+ @autoreleasepool {
+ sync_visible_windows(client);
+
+ // Sync macOS clipboard -> Windows host
+ NSPasteboard *pb = [NSPasteboard generalPasteboard];
+ if (pb.changeCount != lastPasteboardCount) {
+ lastPasteboardCount = pb.changeCount;
+ NSString *str = [pb stringForType:NSPasteboardTypeString];
+ if (str) {
+ const char *utf8 = str.UTF8String;
+ send_frame(client, 3 /* Clipboard */, 0x0201 /* ClipboardData */,
+ utf8, (uint32_t)strlen(utf8));
+ }
+ }
+
+ // Non-blocking poll for incoming host input events
+ fd_set rfds;
+ FD_ZERO(&rfds);
+ FD_SET(client, &rfds);
+ struct timeval tv = {0, 16000}; // ~60 Hz pacing
+ if (select(client + 1, &rfds, NULL, NULL, &tv) > 0) {
+ WsmFrameHeader hdr;
+ ssize_t r = recv(client, &hdr, sizeof(hdr), MSG_WAITALL);
+ if (r <= 0) break;
+ if (hdr.magic == WSM_MAGIC && hdr.payload_size <= 65536) {
+ uint8_t *payload = hdr.payload_size ? malloc(hdr.payload_size) : NULL;
+ if (payload && recv(client, payload, hdr.payload_size, MSG_WAITALL) <= 0) {
+ free(payload);
+ break;
+ }
+ if (hdr.type == 0x0120 && hdr.payload_size == sizeof(WsmInputKeyEvent)) {
+ inject_key_event((const WsmInputKeyEvent *)payload);
+ } else if (hdr.type == 0x0122 && hdr.payload_size == sizeof(WsmInputMouseButtonEvent)) {
+ inject_mouse_button((const WsmInputMouseButtonEvent *)payload);
+ } else if (hdr.type == 0x0010 && hdr.payload_size > 0) {
+ // LaunchApp: open genuine macOS .app bundle via NSWorkspace / open
+ NSString *appPath = [[NSString alloc] initWithBytes:payload length:hdr.payload_size encoding:NSUTF8StringEncoding];
+ if (appPath.length > 0) {
+ NSURL *url = [NSURL fileURLWithPath:appPath];
+ [[NSWorkspace sharedWorkspace] openApplicationAtURL:url
+ configuration:[NSWorkspaceOpenConfiguration configuration]
+ completionHandler:nil];
+ }
+ }
+ free(payload);
+ }
+ }
+ }
+ }
+ close(client);
+ NSLog(@"[wsm-guest-agent] Host disconnected.");
+ }
+ }
+ return 0;
+}
diff --git a/src/wsm-guest/agent/wsm-install.sh b/src/wsm-guest/agent/wsm-install.sh
new file mode 100644
index 0000000..7bcedb4
--- /dev/null
+++ b/src/wsm-guest/agent/wsm-install.sh
@@ -0,0 +1,130 @@
+#!/bin/zsh
+# Runs inside the macOS runtime (as the runtime user, passwordless sudo). Installs whatever Mac
+# software is in <file>: .dmg (any layout, license prompts accepted), .pkg/.mpkg, .zip, .tar(.gz),
+# or an .app bundle. Installing inside macOS keeps code signatures, symlinks and xattrs intact.
+#
+# wsm-install.sh <file> <icon-dir>
+#
+# Output (stdout), one line per installed app:
+# APP <bundle id>\t<name>\t<version>\t<app path>\t<icon png>
+# Progress/errors go to stderr as "STAGE <text>" / "ERROR <text>".
+setopt NULL_GLOB
+f="$1"; icons="${2:-$HOME/Library/Caches/WSM/icons}"
+mkdir -p "$icons"
+work=$(mktemp -d /tmp/wsm-install.XXXXXX)
+marker="$work/.marker"; touch "$marker"; sleep 1
+mounts=()
+cleanup() { for m in $mounts; do hdiutil detach "$m" -force -quiet 2>/dev/null; done; rm -rf "$work"; }
+trap cleanup EXIT
+stage() { echo "STAGE $*" >&2; }
+fail() { echo "ERROR $*" >&2; exit 1; }
+
+typeset -a installed
+
+install_app() { # copy an .app bundle into /Applications
+ local src="$1" dst="/Applications/${1:t}"
+ [[ "${src:A}" == "${dst:A}" ]] && return 0
+ stage "Installing ${1:t:r}"
+ sudo rm -rf "$dst"
+ sudo ditto "$src" "$dst" || fail "couldn't copy ${1:t}"
+ sudo xattr -dr com.apple.quarantine "$dst" 2>/dev/null
+ installed+=("$dst")
+}
+
+install_pkg() { # run Apple's installer on a package
+ stage "Running installer for ${1:t:r}"
+ sudo installer -pkg "$1" -target / >&2 || fail "the package installer failed for ${1:t}"
+ # Apps the package created or replaced.
+ for a in /Applications/*.app /Applications/*/*.app; do
+ [[ -n $(find "$a" -maxdepth 0 -cnewer "$marker" 2>/dev/null) ]] && installed+=("$a")
+ done
+}
+
+handle_dir() { # install the apps (or else packages) found in a folder
+ local d="$1" found=0
+ for a in "$d"/*.app "$d"/*/*.app; do
+ # Disk images carry a link to /Applications: never look through links, and never
+ # treat something already in /Applications as the thing to install.
+ [[ -L "$a" || -L "${a:h}" ]] && continue
+ [[ "${a:A}" == /Applications/* ]] && continue
+ install_app "$a"; found=1
+ done
+ (( found )) && return 0
+ for p in "$d"/*.pkg "$d"/*.mpkg "$d"/*/*.pkg "$d"/*/*.mpkg; do
+ [[ -L "$p" || -L "${p:h}" ]] && continue
+ install_pkg "$p"; found=1
+ done
+ (( found )) && return 0
+ for i in "$d"/*.dmg "$d"/*.zip; do handle_file "$i"; found=1; done
+ (( found )) || fail "no Mac app was found inside"
+}
+
+handle_file() {
+ local x="$1"
+ case "${x:l}" in
+ *.app|*.app/) install_app "${x%/}" ;;
+ *.pkg|*.mpkg) install_pkg "$x" ;;
+ *.dmg)
+ stage "Opening disk image"
+ local mp="$work/mnt${#mounts}"
+ mkdir -p "$mp"
+ yes | hdiutil attach -nobrowse -readonly -noautoopen -noverify -mountpoint "$mp" "$x" >/dev/null 2>&1 \
+ || fail "the disk image couldn't be opened"
+ mounts+=("$mp")
+ handle_dir "$mp" ;;
+ *.zip)
+ stage "Unpacking"
+ local out="$work/zip${RANDOM}"; mkdir -p "$out"
+ ditto -x -k "$x" "$out" || fail "the archive couldn't be unpacked"
+ rm -rf "$out/__MACOSX"
+ handle_dir "$out" ;;
+ *.tar|*.tar.gz|*.tgz|*.tar.bz2|*.tar.xz)
+ stage "Unpacking"
+ local out="$work/tar${RANDOM}"; mkdir -p "$out"
+ tar -xf "$x" -C "$out" || fail "the archive couldn't be unpacked"
+ handle_dir "$out" ;;
+ *) if [[ -d "$x" ]]; then handle_dir "$x"; else fail "this isn't a Mac app, disk image or package"; fi ;;
+ esac
+}
+
+if [[ "$f" == --builtin ]]; then
+ # An app that ships with macOS (Safari, TextEdit, …): nothing to copy, just report it.
+ a="$2"; icons="${3:-$HOME/Library/Caches/WSM/icons}"; mkdir -p "$icons"
+ [[ "$a" == /Applications/*.app || "$a" == /System/Applications/*.app || "$a" == /System/Applications/Utilities/*.app ]] \
+ || fail "that isn't a built-in Mac app"
+ [[ -d "$a" ]] || fail "${a:t:r} isn't part of this macOS"
+ installed+=("$a")
+else
+ [[ -e "$f" ]] || fail "file not found"
+ handle_file "$f"
+fi
+(( ${#installed} )) || fail "nothing was installed"
+
+stage "Finishing"
+for a in ${(u)installed}; do
+ plist="$a/Contents/Info.plist"
+ [[ -f "$plist" ]] || continue
+ id=$(/usr/libexec/PlistBuddy -c "Print :CFBundleIdentifier" "$plist" 2>/dev/null)
+ name=$(/usr/libexec/PlistBuddy -c "Print :CFBundleDisplayName" "$plist" 2>/dev/null)
+ [[ -z "$name" ]] && name=$(/usr/libexec/PlistBuddy -c "Print :CFBundleName" "$plist" 2>/dev/null)
+ [[ -z "$name" ]] && name="${a:t:r}"
+ ver=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "$plist" 2>/dev/null)
+ [[ -z "$id" ]] && continue
+ png="$icons/$id.png"
+ # The icon exactly as Finder shows it (works for .icns and asset-catalog icons).
+ osascript -l JavaScript - "$a" "$png" >/dev/null 2>&1 <<'JXA'
+ObjC.import('AppKit');
+function run(argv) {
+ var img = $.NSWorkspace.sharedWorkspace.iconForFile(argv[0]);
+ img.setSize($.NSMakeSize(256, 256));
+ var rep = $.NSBitmapImageRep.alloc.initWithBitmapDataPlanesPixelsWidePixelsHighBitsPerSampleSamplesPerPixelHasAlphaIsPlanarColorSpaceNameBytesPerRowBitsPerPixel(
+ null, 256, 256, 8, 4, true, false, "NSCalibratedRGBColorSpace", 0, 0);
+ $.NSGraphicsContext.saveGraphicsState;
+ $.NSGraphicsContext.setCurrentContext($.NSGraphicsContext.graphicsContextWithBitmapImageRep(rep));
+ img.drawInRectFromRectOperationFraction($.NSMakeRect(0, 0, 256, 256), $.NSZeroRect, 2, 1.0);
+ $.NSGraphicsContext.restoreGraphicsState;
+ rep.representationUsingTypeProperties(4, $()).writeToFileAtomically(argv[1], true);
+}
+JXA
+ printf 'APP %s\t%s\t%s\t%s\t%s\n' "$id" "$name" "$ver" "$a" "$png"
+done
diff --git a/src/wsm-guest/agent/wsm-shrink.sh b/src/wsm-guest/agent/wsm-shrink.sh
new file mode 100644
index 0000000..234497a
--- /dev/null
+++ b/src/wsm-guest/agent/wsm-shrink.sh
@@ -0,0 +1,46 @@
+#!/bin/zsh
+# Makes the runtime's disk image small. Runs inside macOS (runtime user, passwordless sudo).
+# 1. Deletes what a hidden runtime never needs: installer leftovers, downloaded AI/Siri models,
+# aerial wallpapers, caches, old logs, swap/sleep images.
+# 2. Fills the free space with zeros and deletes that file again. QEMU runs the disk with
+# detect-zeroes=unmap, so the zeros cost nothing and mark every free block as empty; a
+# `qemu-img convert` afterwards keeps only real data.
+setopt NULL_GLOB
+say() { echo "shrink: $*"; }
+before=$(df -k /System/Volumes/Data | awk 'NR==2 {print $3}')
+
+say "removing leftovers"
+sudo rm -rf "/macOS Install Data" /Applications/Install\ macOS*.app "/System/Volumes/Data/macOS Install Data" 2>/dev/null
+# The installer moves its own 17 GB "Install macOS" app aside here after setup. The empty
+# top folder is SIP-protected and stays; everything inside it can go.
+sudo rm -rf "/System/Volumes/Data/Previous Content/"* 2>/dev/null
+sudo rm -rf /Library/Updates/* /private/var/db/softwareupdate/* 2>/dev/null
+# On-demand assets: Apple Intelligence / Siri / dictation models, voices, aerials.
+sudo rm -rf /System/Library/AssetsV2/com_apple_MobileAsset_UAF_* /System/Library/AssetsV2/com_apple_MobileAsset_Trial* \
+ /System/Library/AssetsV2/com_apple_MobileAsset_VoiceServices* /System/Library/AssetsV2/com_apple_MobileAsset_Speech* \
+ /System/Library/AssetsV2/com_apple_MobileAsset_LinguisticData* 2>/dev/null
+sudo rm -rf /private/var/MobileAsset/AssetsV2/com_apple_MobileAsset_UAF_* /private/var/MobileAsset/AssetsV2/com_apple_MobileAsset_Trial* 2>/dev/null
+sudo rm -rf "/Library/Application Support/com.apple.idleassetsd/Customer/"* 2>/dev/null
+# Logs. Caches stay: they're small, and deleting them made macOS rebuild its font and system
+# caches at the next boot (minutes of full CPU, app launches 10 s instead of 2).
+sudo log erase --all >/dev/null 2>&1
+sudo rm -rf /private/var/log/*.gz /private/var/log/asl/*.asl /Library/Logs/DiagnosticReports/* ~/Library/Logs/* 2>/dev/null
+sudo mdutil -a -i off >/dev/null 2>&1; sudo mdutil -a -E >/dev/null 2>&1
+sudo rm -f /private/var/vm/sleepimage 2>/dev/null
+# Local snapshots hold deleted data alive.
+for s in $(tmutil listlocalsnapshotdates / 2>/dev/null | grep -E '^[0-9]'); do sudo tmutil deletelocalsnapshots $s >/dev/null 2>&1; done
+sync
+after=$(df -k /System/Volumes/Data | awk 'NR==2 {print $3}')
+say "freed $(( (before - after) / 1024 )) MB"
+
+# --leftovers-only: run after setup, without the slow zero fill (that's only worth it right
+# before compacting the image offline).
+[[ "$1" == --leftovers-only ]] && { say "done; data volume uses $(df -h /System/Volumes/Data | awk 'NR==2 {print $3}')"; exit 0; }
+
+say "zeroing free space"
+Z=/private/var/tmp/wsm-zero
+sudo dd if=/dev/zero of=$Z bs=16m 2>/dev/null # stops when the disk is full
+sync
+sudo rm -f $Z
+sync
+say "done; data volume uses $(df -h /System/Volumes/Data | awk 'NR==2 {print $3}')"
diff --git a/src/wsm-guest/agent/wsm-trim.sh b/src/wsm-guest/agent/wsm-trim.sh
new file mode 100644
index 0000000..5577026
--- /dev/null
+++ b/src/wsm-guest/agent/wsm-trim.sh
@@ -0,0 +1,135 @@
+#!/bin/zsh
+# Runtime profile: gives the machine to the user's apps, not to macOS.
+# Runs inside the runtime (as the runtime user, passwordless sudo). Idempotent and versioned:
+# services are disabled persistently (launchd override database on the Data volume) and stopped
+# now. Nothing on the sealed system volume is touched.
+#
+# Kept on purpose, because apps rely on them: accountsd, cloudd (CloudKit), contactsd, quicklook,
+# talagent (window restoration), usernoted, coreaudiod, networking, mobileassetd (fonts),
+# keychain/security, WindowServer/Dock/Finder (the session), wallpaper (WSM's flat backdrop).
+VERSION=8
+STAMP=/Library/WSM/trim-version
+U=$(id -u)
+# The stamp alone isn't proof: launchd writes its override database lazily, so a runtime that
+# was powered off right after trimming kept the stamp but lost the disables (seen: 10 of ~140).
+# Re-apply whenever a sentinel job is no longer disabled.
+applied() { launchctl print-disabled gui/$U 2>/dev/null | grep -q '"com.apple.tipsd" => disabled' &&
+ launchctl print-disabled gui/$U 2>/dev/null | grep -q '"com.apple.suggestd" => disabled'; }
+[[ "$1" != "--force" && -f $STAMP && "$(cat $STAMP)" == "$VERSION" ]] && applied && { echo "trim: up to date (v$VERSION)"; exit 0; }
+
+user_jobs=(
+ # Siri, Apple Intelligence, suggestions, knowledge graph
+ com.apple.assistantd com.apple.assistant_service com.apple.assistant_cdmd com.apple.siri.context.service
+ com.apple.siriactionsd com.apple.siriinferenced com.apple.siriknowledged com.apple.sirittsd com.apple.SiriTTSTrainingAgent
+ com.apple.intelligencecontextd com.apple.intelligenceflowd com.apple.intelligenceplatformd com.apple.intelligencetasksd
+ com.apple.generativeexperiencesd com.apple.knowledge-agent com.apple.knowledgeconstructiond com.apple.suggestd
+ com.apple.duetexpertd com.apple.parsecd com.apple.parsec-fbf com.apple.triald com.apple.mlhostd com.apple.translationd
+ com.apple.spotlightknowledged com.apple.spotlightknowledged.importer com.apple.spotlightknowledged.updater
+ com.apple.ContextStoreAgent com.apple.routined com.apple.CoreRoutine.helperservice com.apple.biomesyncd
+ # Spotlight UI and indexing helpers
+ com.apple.Spotlight com.apple.corespotlightd com.apple.managedcorespotlightd com.apple.metadata.mdbulkimport com.apple.helpd
+ # Messages, FaceTime, calls, continuity, sharing
+ com.apple.imagent com.apple.imcore.imtransferagent com.apple.imdpersistence.IMDPersistenceAgent
+ com.apple.telephonyutilities.callservicesd com.apple.callhistoryd com.apple.CallHistoryPluginHelper com.apple.CallHistorySyncHelper
+ com.apple.callintelligenced com.apple.sharingd com.apple.rapportd com.apple.RapportUIAgent com.apple.StatusKitAgent
+ com.apple.sociallayerd com.apple.liveactivitiesd
+ # Find My, family, Screen Time, device management
+ com.apple.findmy.findmylocateagent com.apple.findmymacmessenger com.apple.icloud.findmydeviced.findmydevice-user-agent
+ com.apple.icloud.searchpartyuseragent com.apple.familycircled com.apple.familynotificationd com.apple.FamilyControlsAgent
+ com.apple.familycontrols.useragent com.apple.ScreenTimeAgent com.apple.ScreenTimeSettingsAgent com.apple.UsageTrackingAgent
+ com.apple.dmd com.apple.AppSSOAgent
+ # Photos, media, iCloud Drive, Music/TV libraries
+ com.apple.photoanalysisd com.apple.photolibraryd com.apple.mediaanalysisd com.apple.cloudphotod com.apple.CloudPhotosConfiguration
+ com.apple.amp.mediasharingd com.apple.AMPLibraryAgent com.apple.itunescloudd com.apple.bird
+ # Ads, updates (the App Store and Apple ID stay on: see store_user below)
+ com.apple.ap.adprivacyd com.apple.ap.promotedcontentd com.apple.SoftwareUpdateNotificationManager com.apple.financed
+ # Widgets, news, weather, tips, games, home, wallet, maps, location history
+ com.apple.chronod com.apple.newsd com.apple.weatherd com.apple.tipsd com.apple.gamed com.apple.homed com.apple.passd
+ com.apple.navd com.apple.geod com.apple.CoreLocationAgent com.apple.notificationcenterui.agent
+ # Contacts sync (contactsd itself stays), diagnostics, crash reporting, hardware we don't have
+ com.apple.AddressBook.SourceSync com.apple.AddressBook.abd com.apple.AddressBook.AssistantService
+ com.apple.metrickitd com.apple.diagnosticextensionsd com.apple.ReportCrash com.apple.spindump_agent
+ com.apple.accessibility.heard com.apple.wifi.WiFiAgent com.apple.remindd com.apple.SafariBookmarksSyncAgent
+ com.apple.weatherd com.apple.tipsd com.apple.helpd
+)
+system_jobs=(
+ com.apple.analyticsd com.apple.audioanalyticsd com.apple.ecosystemanalyticsd com.apple.wifianalyticsd
+ com.apple.osanalytics.osanalyticshelper com.apple.systemstats.analysis com.apple.systemstats.daily
+ com.apple.systemstats.microstackshot_periodic com.apple.spindump com.apple.metadata.mds.spindump
+ com.apple.PerfPowerServices com.apple.PerfPowerServicesExtended com.apple.perfpowermetricd
+ com.apple.triald.system com.apple.modelmanagerd com.apple.contextstored
+ com.apple.softwareupdated com.apple.mobile.softwareupdated com.apple.managedappdistributiond
+ com.apple.gamepolicyd com.apple.findmymacd com.apple.findmymacmessenger com.apple.findmy.findmybeaconingd
+ com.apple.icloud.findmydeviced com.apple.icloud.searchpartyd com.apple.backupd com.apple.backupd-helper
+ com.apple.InstallerDiagnostics.installerdiagd com.apple.InstallerDiagnostics.installerdiagwatcher
+ com.apple.wifip2pd com.apple.wifivelocityd com.apple.biometrickitd com.apple.inputanalyticsd com.apple.mediaanalysisd
+)
+
+# The App Store and Apple ID: kept on (WSM offers the App Store), and switched back on for
+# runtimes trimmed before v8, which had them off.
+store_user=(com.apple.appstoreagent com.apple.appstorecomponentsd com.apple.commerce com.apple.amsaccountsd
+ com.apple.amsengagementd com.apple.identityservicesd com.apple.followupd com.apple.FollowUpUI)
+for j in $store_user; do launchctl enable gui/$U/$j 2>/dev/null; sudo launchctl enable user/$U/$j 2>/dev/null; done
+sudo launchctl enable system/com.apple.appstored 2>/dev/null
+
+ok=0; refused=()
+for j in $user_jobs; do
+ launchctl disable gui/$U/$j 2>/dev/null; sudo launchctl disable user/$U/$j 2>/dev/null
+ sudo launchctl bootout gui/$U/$j 2>/dev/null; sudo launchctl bootout user/$U/$j 2>/dev/null
+ ok=$((ok + 1))
+done
+for j in $system_jobs; do
+ if sudo launchctl disable system/$j 2>/dev/null; then ok=$((ok + 1)); else refused+=$j; fi
+ sudo launchctl bootout system/$j 2>/dev/null
+done
+
+# Spotlight: stop indexing every volume (mds stays for apps that query metadata).
+sudo mdutil -a -i off >/dev/null 2>&1
+# No automatic update checks or downloads, no Time Machine prompts.
+sudo defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled -bool false
+sudo defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticDownload -bool false
+sudo defaults write /Library/Preferences/com.apple.commerce AutoUpdate -bool false
+sudo defaults write /Library/Preferences/com.apple.TimeMachine DoNotOfferNewDisksForBackup -bool true 2>/dev/null
+# Interface work nobody sees: no animations, no transparency, no sleep of the display.
+defaults write NSGlobalDomain NSAutomaticWindowAnimationsEnabled -bool false
+defaults write NSGlobalDomain NSWindowResizeTime -float 0.001
+defaults write com.apple.universalaccess reduceMotion -bool true 2>/dev/null
+defaults write com.apple.universalaccess reduceTransparency -bool true 2>/dev/null
+defaults write com.apple.dock autohide -bool true
+defaults write com.apple.dock launchanim -bool false
+defaults write com.apple.dock mineffect -string scale
+sudo pmset -a displaysleep 0 sleep 0 disksleep 0 powernap 0 >/dev/null 2>&1
+# No startup chime when the runtime boots (OpenCore and macOS both honour StartupMute); app
+# sound is unaffected.
+sudo nvram StartupMute=%01 2>/dev/null
+
+# Nothing of macOS's own desktop may show up inside an app's window on Windows (WSM crops each
+# window out of the runtime's screen): no desktop widgets, no "click wallpaper to reveal
+# desktop" (a click in a window's transparent corner would slide every window away), no Stage
+# Manager, no edge tiling, no hot corners (bottom-right opened Quick Note), no Tips banners.
+defaults write com.apple.WindowManager StandardHideWidgets -bool true
+defaults write com.apple.WindowManager StageManagerHideWidgets -bool true
+defaults write com.apple.WindowManager EnableStandardClickToShowDesktop -bool false
+defaults write com.apple.WindowManager GloballyEnabled -bool false
+defaults write com.apple.WindowManager EnableTilingByEdgeDrag -bool false
+defaults write com.apple.WindowManager EnableTopTilingByEdgeDrag -bool false
+defaults write com.apple.WindowManager EnableTilingOptionAccelerator -bool false
+for c in tl tr bl br; do defaults write com.apple.dock wvous-$c-corner -int 1; defaults write com.apple.dock wvous-$c-modifier -int 0; done
+defaults write com.apple.dock show-recents -bool false
+defaults write com.apple.finder CreateDesktop -bool false # no desktop icons
+defaults write NSGlobalDomain NSQuitAlwaysKeepsWindows -bool false
+# Don't reopen at login the apps that were open at shutdown: they'd pop up on the Windows
+# desktop by themselves. Apps open when the user opens them.
+defaults write com.apple.loginwindow TALLogoutSavesState -bool false
+defaults write com.apple.loginwindow LoginwindowLaunchesRelaunchApps -bool false
+find ~/Library/Preferences/ByHost -name "com.apple.loginwindow.*.plist" -delete 2>/dev/null
+pkill -x Tips 2>/dev/null
+killall Dock Finder NotificationCenter WindowManager tipsd chronod 2>/dev/null
+
+# Make the override database reach the disk before anything can power the runtime off.
+sync; sleep 1; sync
+on=$(launchctl print-disabled gui/$U 2>/dev/null | grep -c '=> disabled')
+sudo mkdir -p /Library/WSM && echo $VERSION | sudo tee $STAMP >/dev/null && sync
+echo "trim: v$VERSION applied ($ok jobs off, $on disabled in the session)"
+(( ${#refused} )) && echo "trim: SIP kept: ${refused[*]}"
+exit 0
diff --git a/src/wsm-guest/provision/wsm-offline-setup.sh b/src/wsm-guest/provision/wsm-offline-setup.sh
new file mode 100644
index 0000000..8be5dcd
--- /dev/null
+++ b/src/wsm-guest/provision/wsm-offline-setup.sh
@@ -0,0 +1,185 @@
+#!/bin/sh
+# Runs in macOS Recovery against the installed system's Data volume. Prepares a fresh macOS so it
+# boots straight to an auto-logged-in session with remote login on, without Setup Assistant.
+# Writes only to the Data volume; the sealed system volume is never touched.
+#
+# sh wsm-offline-setup.sh <payload dir>
+set -eu
+P=${1:?payload dir}
+log() { echo "wsm-setup: $*"; }
+
+# The Data volume: the APFS volume with the Data role on the internal disk.
+D=
+for v in /Volumes/*; do
+ case "$v" in */Installer|*/RECOVERY|*/WSMPAYLOAD) continue ;; esac
+ if diskutil info "$v" 2>/dev/null | grep -q "APFS Volume Role: *Data"; then D=$v; fi
+ if [ -z "$D" ] && [ -d "$v - Data/private/var" ]; then D="$v - Data"; fi
+done
+if [ -z "$D" ]; then
+ for dev in $(diskutil apfs list | awk '/APFS Volume Disk \(Role\):/ && /Data/ {print $6}'); do
+ diskutil mount "$dev" >/dev/null 2>&1 || true
+ D=$(diskutil info "$dev" | awk -F': *' '/Mount Point/ {print $2}')
+ done
+fi
+[ -n "$D" ] && [ -d "$D/private/var" ] || { log "no Data volume"; exit 2; }
+log "data volume: $D"
+
+DS="$D/private/var/db/dslocal/nodes/Default"
+U=wsm
+UID_=501
+PW=$(cat "$P/password")
+
+# 1. Account: dscl against the offline directory node.
+if ! dscl -f "$DS" localonly -read "/Local/Target/Users/$U" >/dev/null 2>&1; then
+ dscl -f "$DS" localonly -create "/Local/Target/Users/$U"
+ dscl -f "$DS" localonly -create "/Local/Target/Users/$U" UserShell /bin/zsh
+ dscl -f "$DS" localonly -create "/Local/Target/Users/$U" RealName "WSM"
+ dscl -f "$DS" localonly -create "/Local/Target/Users/$U" UniqueID $UID_
+ dscl -f "$DS" localonly -create "/Local/Target/Users/$U" PrimaryGroupID 20
+ dscl -f "$DS" localonly -create "/Local/Target/Users/$U" NFSHomeDirectory "/Users/$U"
+ dscl -f "$DS" localonly -passwd "/Local/Target/Users/$U" "$PW"
+ dscl -f "$DS" localonly -append "/Local/Target/Groups/admin" GroupMembership "$U"
+ dscl -f "$DS" localonly -append "/Local/Target/Groups/com.apple.access_ssh" GroupMembership "$U" 2>/dev/null || true
+fi
+H="$D/Users/$U"
+mkdir -p "$H/.ssh" "$H/Library/Preferences" "$H/Library/LaunchAgents"
+cp "$P/authorized_keys" "$H/.ssh/authorized_keys"
+chmod 700 "$H/.ssh"; chmod 600 "$H/.ssh/authorized_keys"
+# WSM runs its maintenance (runtime profile, app installs) with sudo, without a prompt.
+mkdir -p "$D/private/etc/sudoers.d"
+echo "$U ALL=(ALL) NOPASSWD: ALL" > "$D/private/etc/sudoers.d/$U"
+chown 0:0 "$D/private/etc/sudoers.d/$U"; chmod 440 "$D/private/etc/sudoers.d/$U"
+log "account ready"
+
+# 2. Skip Setup Assistant (system and per-user).
+touch "$D/private/var/db/.AppleSetupDone"
+touch "$D/private/var/db/.AppleDiagnosticsSetupDone" 2>/dev/null || true
+SYS="${D% - Data}"
+VER=$(defaults read "$SYS/System/Library/CoreServices/SystemVersion" ProductVersion 2>/dev/null || true)
+BLD=$(defaults read "$SYS/System/Library/CoreServices/SystemVersion" ProductBuildVersion 2>/dev/null || true)
+# Per-user screens after the first login ("Update Mac Automatically", App Store, sync, …): every
+# DidSee key Tahoe's Setup Assistant knows (grep -ao 'DidSee[A-Za-z0-9]*' on Setup Assistant.app),
+# plus the older ones, and no reason for the per-user mini setup to launch.
+SA="$H/Library/Preferences/com.apple.SetupAssistant.plist"
+for k in DidSeeAccessibility DidSeeActivationLock DidSeeAppStore DidSeeAppearance DidSeeAppearanceSetup DidSeeApplePaySetup \
+ DidSeeAutoUpdatePrompt DidSeeCloudSetup DidSeeLockdownMode DidSeePrivacy DidSeeScreenTime DidSeeSiriSetup \
+ DidSeeSyncSetup DidSeeSyncSetup2 DidSeeTermsOfAddress DidSeeTouchIDSetup DidSeeiCloudLoginForStorageServices \
+ DidSeeTrueTone DidSeeIntelligence DidSeeAvatarSetup DidSeeWallpaper; do
+ defaults write "$SA" "$k" -bool true
+done
+[ -n "$VER" ] && defaults write "$SA" DidSeeNewFeaturesProductVersion -string "$VER"
+defaults write "$SA" LastSeenCloudProductVersion -string 99
+defaults write "$SA" LastSeenBuddyBuildVersion -string 99Z999
+defaults write "$SA" GestureMovieSeen none
+defaults write "$SA" MiniBuddyLaunchReason -int 0
+defaults write "$SA" MiniBuddyLaunchedPostMigration -bool true
+defaults write "$SA" MiniBuddyShouldLaunchToResumeSetup -bool false
+defaults write "$SA" SkipFirstLoginOptimization -bool true
+# Apple's license ("Terms and Conditions", then "welcome / Get Started"): Setup Assistant shows it
+# while the installer's cookie exists ("Showing terms because cookie exists"); Agree deletes the
+# cookie and records the first-run tasks as done. The user accepted the license with WSM's
+# Install button, so do the same here.
+rm -f "$D/private/var/db/.AppleSetupTermsOfService" "$D/private/var/db/.AppleSetupResume"
+GSA="$D/Library/Preferences/com.apple.SetupAssistant"
+defaults write "$GSA" DidRunFLO -bool true
+defaults write "$GSA" DidSeeCloudSetup -bool true
+defaults write "$GSA" MiniBuddyLaunchReason -int 0
+defaults write "$GSA" MiniBuddyLaunchedPostMigration -bool true
+defaults write "$GSA" MiniBuddyShouldLaunchToResumeMigration -bool false
+defaults write "$GSA" MiniBuddyShouldLaunchToResumeSetup -bool false
+defaults write "$GSA" PostMacBuddyCleanupCompleted -bool true
+[ -n "$VER" ] && defaults write "$GSA" LastPreLoginTasksPerformedVersion -string "$VER"
+[ -n "$BLD" ] && defaults write "$GSA" LastPreLoginTasksPerformedBuild -string "$BLD"
+log "setup assistant skipped (license agreed${VER:+, macOS $VER $BLD})"
+
+# 3. Automatic login (kcpassword holds the password, obfuscated as macOS expects).
+cp "$P/kcpassword" "$D/private/etc/kcpassword" 2>/dev/null || cp "$P/kcpassword" "$D/private/var/db/kcpassword"
+chmod 600 "$D/private/etc/kcpassword" 2>/dev/null || true
+defaults write "$D/Library/Preferences/com.apple.loginwindow" autoLoginUser "$U"
+defaults write "$D/Library/Preferences/com.apple.loginwindow" DisableScreenLock -bool true
+log "auto login on"
+
+# 4. Remote login (sshd) for the host's runtime service; reached only through 127.0.0.1 forwarding.
+OVR="$D/private/var/db/com.apple.xpc.launchd/disabled.plist"
+mkdir -p "$(dirname "$OVR")"
+[ -f "$OVR" ] || defaults write "$OVR" _wsm -bool true
+defaults write "$OVR" com.openssh.sshd -bool false
+log "ssh enabled"
+
+# 5. Runtime profile: per-user settings that cut background work and keep the display awake.
+# System daemons on the sealed volume stay as Apple ships them (the volume can't be modified);
+# they are disabled through the launchd override database, which lives on the Data volume.
+for svc in com.apple.photoanalysisd com.apple.mediaanalysisd com.apple.photolibraryd com.apple.suggestd \
+ com.apple.knowledge-agent com.apple.siriknowledged com.apple.assistantd com.apple.Siri.agent \
+ com.apple.tipsd com.apple.gamed com.apple.newsd com.apple.weatherd com.apple.ScreenTimeAgent \
+ com.apple.findmy.findmylocateagent com.apple.familycircled com.apple.followupd com.apple.parsecd \
+ com.apple.intelligenceplatformd com.apple.generativeexperiencesd com.apple.spotlightknowledged; do
+ defaults write "$D/private/var/db/com.apple.xpc.launchd/disabled.$UID_.plist" "$svc" -bool true
+done
+for svc in com.apple.backupd-helper com.apple.backupd com.apple.mds com.apple.metadata.mds.spindump \
+ com.apple.softwareupdated com.apple.mobile.softwareupdated com.apple.analyticsd \
+ com.apple.ReportCrash.Root com.apple.diagnosticd.osactivity; do
+ defaults write "$OVR" "$svc" -bool true
+done
+defaults write "$D/Library/Preferences/com.apple.SoftwareUpdate" AutomaticCheckEnabled -bool false
+defaults write "$D/Library/Preferences/com.apple.SoftwareUpdate" AutomaticDownload -bool false
+defaults write "$D/Library/Preferences/com.apple.TimeMachine" AutoBackup -bool false
+defaults write "$D/Library/Preferences/com.apple.TimeMachine" DoNotOfferNewDisksForBackup -bool true
+defaults write "$H/Library/Preferences/com.apple.screensaver" idleTime -int 0
+defaults write "$D/Library/Preferences/com.apple.PowerManagement" "AC Power" -dict "Display Sleep Timer" -int 0 "System Sleep Timer" -int 0 "Disk Sleep Timer" -int 0
+defaults write "$H/Library/Preferences/com.apple.dock" autohide -bool true
+defaults write "$H/Library/Preferences/com.apple.dock" launchanim -bool false
+defaults write "$H/Library/Preferences/com.apple.universalaccess" reduceMotion -bool true
+defaults write "$H/Library/Preferences/com.apple.universalaccess" reduceTransparency -bool true
+defaults write "$H/Library/Preferences/NSGlobalDomain" NSAutomaticWindowAnimationsEnabled -bool false
+defaults write "$H/Library/Preferences/com.apple.loginwindow" TALLogoutSavesState -bool false
+touch "$H/.hushlogin"
+# Spotlight indexing off for the system volume (index lives on Data).
+touch "$D/.metadata_never_index" 2>/dev/null || true
+log "runtime profile applied"
+
+# 6. Keyboard Setup Assistant: QEMU's USB keyboard (vendor 0x627, product 1) is unknown to
+# macOS, which opens a "cannot identify your keyboard" window on first login. Declare it ANSI.
+defaults write "$D/Library/Preferences/com.apple.keyboardtype" keyboardtype -dict-add "1-1575-0" -int 40
+
+# 7. First-login watchdog. On first login loginwindow waits for User Account Updater, whose
+# Settings plug-in (IndexSettings) can block for good on the trimmed runtime profile; the
+# desktop (Finder/Dock) never starts. The watchdog ends a stuck IndexSettings so login
+# continues, then removes itself once the runtime user's Finder is running.
+mkdir -p "$D/Library/WSM" "$D/Library/LaunchDaemons"
+cat > "$D/Library/WSM/first-login-watchdog.sh" <<'EOF'
+#!/bin/sh
+i=0
+while [ $i -lt 240 ]; do
+ if pgrep -x Finder >/dev/null 2>&1 && [ "$(stat -f %Su /dev/console)" = wsm ]; then break; fi
+ for pid in $(pgrep -f SettingsUAUPlugin.bundle/Contents/Resources/IndexSettings); do
+ et=$(ps -o etime= -p "$pid" | tr -d ' ')
+ case "$et" in *:*:*|[2-9]:*|1[0-9]:*) kill "$pid" ;; esac # running > 2 minutes
+ done
+ i=$((i + 1)); sleep 5
+done
+launchctl bootout system/com.wsm.firstlogin 2>/dev/null
+rm -f /Library/LaunchDaemons/com.wsm.firstlogin.plist
+EOF
+chmod 755 "$D/Library/WSM/first-login-watchdog.sh"
+cat > "$D/Library/LaunchDaemons/com.wsm.firstlogin.plist" <<'EOF'
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+ <key>Label</key><string>com.wsm.firstlogin</string>
+ <key>ProgramArguments</key><array><string>/Library/WSM/first-login-watchdog.sh</string></array>
+ <key>RunAtLoad</key><true/>
+</dict></plist>
+EOF
+chown 0:0 "$D/Library/LaunchDaemons/com.wsm.firstlogin.plist"
+chmod 644 "$D/Library/LaunchDaemons/com.wsm.firstlogin.plist"
+log "first-login fixes installed"
+
+chown -R $UID_:20 "$H"
+# `defaults write` from Recovery creates these root-only (0600). macOS ships them 0644, and
+# loginwindow's auto-login doesn't happen when it can't read com.apple.loginwindow.plist.
+chmod 644 "$D/Library/Preferences/"*.plist 2>/dev/null || true
+echo WSM-SETUP-OK > "$D/private/var/db/.wsm-setup-done"
+# The host shuts Recovery down next: everything above must be on the disk first.
+sync; sync
+log "done"
diff --git a/src/wsm-manager/app.js b/src/wsm-manager/app.js
new file mode 100644
index 0000000..adc3737
--- /dev/null
+++ b/src/wsm-manager/app.js
@@ -0,0 +1,420 @@
+"use strict";
+// WSM library. Talks to wsmd on 127.0.0.1:17421. Never shows virtualization vocabulary to the user.
+const API = location.origin.startsWith("http") ? location.origin : "http://127.0.0.1:17421";
+const $ = (id) => document.getElementById(id);
+const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
+
+const state = {
+ apps: [], runtime: "unknown", setup: null, busy: new Set(), running: new Set(),
+ menuFor: null, install: null, lastJobSeen: 0, justInstalled: new Set(), glow: new Map(),
+};
+
+async function api(path, opts = {}) {
+ const r = await fetch(API + path, opts);
+ const text = await r.text();
+ let body; try { body = JSON.parse(text); } catch { body = { raw: text }; }
+ if (!r.ok && body && body.ok === undefined) body.ok = false;
+ return body;
+}
+
+// ---------- status pill ----------
+const RUNTIME_COPY = {
+ ready: { tone: "ready", text: "Ready" },
+ waiting_for_guest: { tone: "busy", text: "Waking up…" },
+ booting: { tone: "busy", text: "Waking up…" },
+ starting: { tone: "busy", text: "Waking up…" },
+ stopping: { tone: "busy", text: "Going to sleep…" },
+ paused: { tone: "idle", text: "Resting · apps open in a few seconds" },
+ stopped: { tone: "idle", text: "Asleep · opening an app wakes it" },
+ crashed: { tone: "bad", text: "The runtime stopped unexpectedly.", action: ["Restart", restartRuntime] },
+ not_installed: { tone: "bad", text: "The macOS runtime isn't installed yet.", action: ["Set up now", () => (location.href = "/setup")] },
+};
+
+function renderStatus() {
+ let s = RUNTIME_COPY[state.runtime] || { tone: "idle", text: "Checking the runtime…" };
+ if (state.setup && state.setup.running) s = { tone: "busy", text: `Installing the runtime · ${Math.round(state.setup.percent || 0)}%` };
+ if (state.runtime === "ready" && state.running.size) s = { tone: "ready", text: `Ready · ${state.running.size} open` };
+ const pill = $("status");
+ pill.dataset.tone = s.tone;
+ if ($("status-text").textContent !== s.text) $("status-text").textContent = s.text;
+ const a = $("status-action");
+ if (s.action) { a.hidden = false; a.textContent = s.action[0]; a.onclick = s.action[1]; } else a.hidden = true;
+
+ $("rt-state").textContent = s.text;
+ const awake = ["ready", "waiting_for_guest", "booting", "starting"].includes(state.runtime);
+ $("rt-toggle").textContent = awake ? "Sleep" : "Wake";
+}
+
+// ---------- icons: each tile glows in its icon's own colour ----------
+function sampleGlow(img, id) {
+ if (state.glow.has(id)) return state.glow.get(id);
+ try {
+ const c = document.createElement("canvas"); c.width = c.height = 24;
+ const g = c.getContext("2d", { willReadFrequently: true });
+ g.drawImage(img, 0, 0, 24, 24);
+ const d = g.getImageData(0, 0, 24, 24).data;
+ let r = 0, gg = 0, b = 0, n = 0;
+ for (let i = 0; i < d.length; i += 4) {
+ const a = d[i + 3], mx = Math.max(d[i], d[i + 1], d[i + 2]), mn = Math.min(d[i], d[i + 1], d[i + 2]);
+ if (a < 200 || mx - mn < 30) continue; // skip transparent and grey pixels
+ r += d[i]; gg += d[i + 1]; b += d[i + 2]; n++;
+ }
+ const v = n ? `${(r / n) | 0}, ${(gg / n) | 0}, ${(b / n) | 0}` : "80, 120, 255";
+ state.glow.set(id, v);
+ return v;
+ } catch { return "80, 120, 255"; }
+}
+
+function attachTilt(tile) {
+ if (reduceMotion) return;
+ const icon = tile.querySelector(".tile-icon");
+ tile.addEventListener("pointermove", (e) => {
+ const r = tile.getBoundingClientRect();
+ const x = (e.clientX - r.left) / r.width - 0.5, y = (e.clientY - r.top) / r.height - 0.5;
+ tile.style.setProperty("--ry", `${(x * 16).toFixed(1)}deg`);
+ tile.style.setProperty("--rx", `${(-y * 16).toFixed(1)}deg`);
+ });
+ tile.addEventListener("pointerleave", () => { tile.style.setProperty("--rx", "0deg"); tile.style.setProperty("--ry", "0deg"); });
+ icon.addEventListener("transitionend", () => {});
+}
+
+// ---------- shelf ----------
+function initials(name) { return (name || "?").trim().charAt(0).toUpperCase(); }
+
+function makeTile(app, i, firstPaint) {
+ const node = $("tile-tpl").content.firstElementChild.cloneNode(true);
+ node.dataset.id = app.id;
+ if (firstPaint) node.style.setProperty("--i", i); else node.style.animation = "none";
+ node.querySelector(".tile-name").textContent = app.name;
+ node.title = `${app.name} ${app.version || ""}`.trim();
+ const img = node.querySelector("img");
+ img.crossOrigin = "anonymous";
+ img.src = `${API}/api/apps/icon?id=${encodeURIComponent(app.id)}`;
+ img.onload = () => node.style.setProperty("--glow", sampleGlow(img, app.id));
+ img.onerror = () => {
+ const f = document.createElement("span");
+ f.className = "fallback-icon"; f.textContent = initials(app.name);
+ img.replaceWith(f);
+ };
+ if (state.glow.has(app.id)) node.style.setProperty("--glow", state.glow.get(app.id));
+ if (state.justInstalled.has(app.id)) { node.classList.add("pop"); state.justInstalled.delete(app.id); }
+ node.addEventListener("click", () => openApp(app));
+ node.addEventListener("contextmenu", (e) => { e.preventDefault(); showMenu(e.clientX, e.clientY, app); });
+ attachTilt(node);
+ return node;
+}
+
+function syncTileState(node, app) {
+ const busy = state.busy.has(app.id);
+ const running = state.running.has(app.name);
+ node.toggleAttribute("data-busy", busy);
+ node.toggleAttribute("data-running", running && !busy);
+ const note = busy ? "Opening…" : running ? "Open" : app.requires_arm64_translation ? "Apple silicon only" : "";
+ const el = node.querySelector(".tile-note");
+ if (el.textContent !== note) el.textContent = note;
+}
+
+function installTile(job) {
+ let node = document.querySelector(".tile.installing");
+ if (!node) {
+ node = document.createElement("div");
+ node.className = "tile installing";
+ node.innerHTML = `<span class="tile-icon"><span class="ring-box"><span class="ring"></span></span></span>
+ <span class="tile-name"></span><span class="tile-note"></span>`;
+ $("shelf").appendChild(node);
+ }
+ node.style.setProperty("--p", job.percent || 0);
+ node.querySelector(".tile-name").textContent = (job.file || "App").replace(/\.(dmg|pkg|mpkg|zip|tgz|tar|gz|app)$/i, "");
+ node.querySelector(".tile-note").textContent = job.stage || "Installing…";
+}
+
+function renderApps() {
+ const shelf = $("shelf");
+ const installing = state.install && state.install.running;
+ const any = state.apps.length > 0 || installing;
+ $("empty").hidden = any;
+ shelf.hidden = !any;
+ $("count").hidden = state.apps.length === 0;
+ $("count").textContent = state.apps.length;
+
+ // Keyed update: tiles stay put (no re-entrance animation) when only their state changes.
+ const firstPaint = !shelf.dataset.painted; shelf.dataset.painted = "1";
+ const keep = new Set(state.apps.map((a) => a.id));
+ shelf.querySelectorAll(".tile[data-id]").forEach((n) => { if (!keep.has(n.dataset.id)) n.remove(); });
+ state.apps.forEach((app, i) => {
+ let node = shelf.querySelector(`.tile[data-id="${CSS.escape(app.id)}"]`);
+ if (!node) {
+ node = makeTile(app, i, firstPaint);
+ const inst = shelf.querySelector(".tile.installing");
+ shelf.insertBefore(node, inst);
+ }
+ syncTileState(node, app);
+ });
+ if (installing) installTile(state.install);
+ else shelf.querySelector(".tile.installing")?.remove();
+
+ // Apps that come with macOS, offered until they're in the library.
+ for (const b of BUILTIN_APPS) {
+ let s = shelf.querySelector(`.suggest-tile[data-builtin="${b.id}"]`);
+ const show = !state.apps.some((a) => a.id === b.id) && !(installing && state.install.file === b.path.split("/").pop());
+ if (!show) { s?.remove(); continue; }
+ if (!s) {
+ s = document.createElement("button");
+ s.className = "tile suggest-tile";
+ s.dataset.builtin = b.id;
+ s.innerHTML = `<span class="tile-icon">${b.icon}</span><span class="tile-name"></span><span class="tile-note">Built into macOS · Add</span>`;
+ s.querySelector(".tile-name").textContent = b.name;
+ s.title = `Add ${b.name} to your apps`;
+ s.onclick = () => addBuiltin(b);
+ }
+ shelf.appendChild(s);
+ }
+
+ // A dashed "Add app" tile always closes the shelf.
+ let add = shelf.querySelector(".add-tile");
+ if (!add) {
+ add = document.createElement("button");
+ add.className = "tile add-tile";
+ add.style.setProperty("--i", state.apps.length);
+ add.innerHTML = `<span class="tile-icon"><span class="add-box"><svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg></span></span>
+ <span class="tile-name">Add app</span><span class="tile-note">or drop a file</span>`;
+ add.onclick = addApp;
+ }
+ shelf.appendChild(add);
+}
+
+async function openApp(app) {
+ if (state.busy.has(app.id)) return;
+ state.busy.add(app.id); renderApps();
+ try {
+ const r = await api("/api/apps/launch", { method: "POST", body: app.id });
+ if (r.ok === false) toast(r.error || `${app.name} couldn't open.`, "bad");
+ } catch { toast("WSM's background service isn't responding. Close and reopen WSM.", "bad"); }
+ // Keep bouncing until its window shows up (or give up after a while).
+ const t0 = Date.now();
+ const wait = setInterval(() => {
+ if (state.running.has(app.name) || Date.now() - t0 > 45000) {
+ clearInterval(wait); state.busy.delete(app.id); renderApps();
+ }
+ }, 400);
+}
+
+// ---------- installing ----------
+async function addApp() {
+ const pick = await api("/api/dialog/pick-app", { method: "POST" });
+ if (!pick.ok) return;
+ installFile(pick.path);
+}
+
+const BUILTIN_APPS = [
+ {
+ id: "com.apple.Safari", name: "Safari", path: "/Applications/Safari.app",
+ icon: `<svg class="builtin-icon" viewBox="0 0 64 64" aria-hidden="true">
+ <defs><linearGradient id="sf-g" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#1ec8ff"/><stop offset="1" stop-color="#1a6dff"/></linearGradient></defs>
+ <rect x="4" y="4" width="56" height="56" rx="14" fill="#fff"/>
+ <circle cx="32" cy="32" r="22" fill="url(#sf-g)"/>
+ <path d="M44 20 L35 35 L29 29 Z" fill="#ff3b30"/><path d="M20 44 L29 29 L35 35 Z" fill="#fff"/>
+ </svg>`,
+ },
+ {
+ // Sign in with an Apple ID there; apps downloaded from it join this library by themselves.
+ id: "com.apple.AppStore", name: "App Store", path: "/System/Applications/App Store.app",
+ icon: `<svg class="builtin-icon" viewBox="0 0 64 64" aria-hidden="true">
+ <defs><linearGradient id="as-g" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#1dc0fb"/><stop offset="1" stop-color="#1a74f0"/></linearGradient></defs>
+ <rect x="4" y="4" width="56" height="56" rx="14" fill="url(#as-g)"/>
+ <g stroke="#fff" stroke-width="4.5" stroke-linecap="round" fill="none">
+ <path d="M27 17 L42 43"/><path d="M37 17 L22 43"/><path d="M17 38 H47"/>
+ </g>
+ </svg>`,
+ },
+];
+
+async function addBuiltin(b) {
+ if (state.install && state.install.running) { toast("Another app is being added. One moment."); return; }
+ let r;
+ try { r = await api("/api/apps/add-builtin", { method: "POST", body: b.path }); }
+ catch { toast("WSM's background service isn't responding. Close and reopen WSM.", "bad"); return; }
+ if (!r.ok) { toast(r.error || `Couldn't add ${b.name}.`, "bad"); return; }
+ state.install = { running: true, job: r.job, percent: 5, stage: "Getting ready", file: b.path.split("/").pop() };
+ renderApps();
+ pollInstall();
+}
+
+async function installFile(path) {
+ const name = path.split(/[\\/]/).pop();
+ let r;
+ try { r = await api("/api/apps/install", { method: "POST", body: path }); }
+ catch { toast("WSM's background service isn't responding. Close and reopen WSM.", "bad"); return; }
+ if (!r.ok) { toast(r.error || `Couldn't install ${name}.`, "bad"); return; }
+ state.install = { running: true, job: r.job, percent: 2, stage: "Getting ready", file: name };
+ renderApps();
+ pollInstall();
+}
+
+// Installs can also start from File Explorer, so the library always watches for them.
+let installTimer;
+async function pollInstall() {
+ clearTimeout(installTimer);
+ let s;
+ try { s = await api("/api/apps/install/status"); } catch { s = null; }
+ if (s && s.job) {
+ const wasRunning = state.install && state.install.running;
+ if (s.running) { state.install = s; renderApps(); }
+ else if (s.done && s.job !== state.lastJobSeen && (wasRunning || state.lastJobSeen)) {
+ state.install = null;
+ if (s.ok) {
+ s.apps.forEach((a) => { state.justInstalled.add(a.id); });
+ const names = s.apps.map((a) => a.name).join(", ");
+ if (s.opens === false) {
+ // Picked up by itself (an App Store download): it's in the library and Start menu now.
+ toast(`${names} was added to your apps.`, "ok");
+ } else {
+ toast(`${names} is installed and opening.`, "ok");
+ s.apps.forEach((a) => state.busy.add(a.id));
+ setTimeout(() => s.apps.forEach((a) => { state.busy.delete(a.id); renderApps(); }), 8000);
+ }
+ } else toast(s.error || "Couldn't install the app.", "bad");
+ await refreshApps();
+ }
+ if (s.done) state.lastJobSeen = s.job;
+ } else if (s && !state.lastJobSeen) state.lastJobSeen = -1;
+ installTimer = setTimeout(pollInstall, state.install && state.install.running ? 500 : 2000);
+}
+
+// Drop a Mac app anywhere on the window to install it. The page can't see file paths, so it
+// hands the files to WSM's window, which posts the real path back.
+window.chrome?.webview?.addEventListener("message", (e) => { if (e.data?.installPath) installFile(e.data.installPath); });
+let dragDepth = 0;
+document.addEventListener("dragenter", (e) => { e.preventDefault(); dragDepth++; document.body.classList.add("dropping"); });
+document.addEventListener("dragover", (e) => e.preventDefault());
+document.addEventListener("dragleave", () => { if (--dragDepth <= 0) { dragDepth = 0; document.body.classList.remove("dropping"); } });
+document.addEventListener("drop", (e) => {
+ e.preventDefault();
+ dragDepth = 0;
+ document.body.classList.remove("dropping");
+ const files = e.dataTransfer?.files;
+ if (files?.length && window.chrome?.webview?.postMessageWithAdditionalObjects)
+ window.chrome.webview.postMessageWithAdditionalObjects("install", files);
+ else if (files?.length) toast("Drop files on the WSM window to install them.");
+});
+
+// ---------- context menu ----------
+function showMenu(x, y, app) {
+ const m = $("menu");
+ state.menuFor = app;
+ m.hidden = false;
+ m.style.left = Math.min(x, innerWidth - m.offsetWidth - 8) + "px";
+ m.style.top = Math.min(y, innerHeight - m.offsetHeight - 8) + "px";
+ m.querySelector("button").focus();
+}
+function hideMenu() { $("menu").hidden = true; state.menuFor = null; }
+$("menu").addEventListener("click", async (e) => {
+ const act = e.target.closest("button")?.dataset.act, app = state.menuFor;
+ hideMenu();
+ if (!app) return;
+ if (act === "open") openApp(app);
+ if (act === "remove") {
+ const tile = document.querySelector(`.tile[data-id="${CSS.escape(app.id)}"]`);
+ if (tile && !reduceMotion) {
+ tile.animate([{ opacity: 1, transform: "scale(1)" }, { opacity: 0, transform: "scale(.6)", filter: "blur(4px)" }],
+ { duration: 320, easing: "cubic-bezier(.2,.8,.2,1)", fill: "forwards" });
+ await new Promise((r) => setTimeout(r, 300));
+ }
+ await api("/api/apps/remove", { method: "POST", body: app.id });
+ toast(`Uninstalled ${app.name}.`);
+ refreshApps();
+ }
+});
+document.addEventListener("click", (e) => { if (!$("menu").contains(e.target)) hideMenu(); });
+
+// ---------- settings ----------
+function setSettings(open) {
+ $("settings").classList.toggle("open", open);
+ $("settings").setAttribute("aria-hidden", String(!open));
+ $("scrim").hidden = !open;
+ requestAnimationFrame(() => $("scrim").classList.toggle("show", open));
+ if (open) $("close-settings").focus();
+}
+$("open-settings").onclick = () => setSettings(true);
+$("close-settings").onclick = () => setSettings(false);
+$("scrim").onclick = () => setSettings(false);
+document.addEventListener("keydown", (e) => { if (e.key === "Escape") { hideMenu(); setSettings(false); } });
+
+async function restartRuntime() {
+ await api("/api/vm/start", { method: "POST" });
+ refreshRuntime();
+}
+$("rt-toggle").onclick = async () => {
+ const awake = ["ready", "waiting_for_guest", "booting", "starting"].includes(state.runtime);
+ await api(awake ? "/api/vm/sleep" : "/api/vm/start", { method: "POST" });
+ refreshRuntime();
+};
+$("open-shared").onclick = () => api("/api/fs/open", { method: "POST" });
+$("export-report").onclick = async () => {
+ const r = await api("/api/diagnostics/export", { method: "POST" });
+ toast(r.ok ? `Report saved to ${r.path}` : "Couldn't save the report.", r.ok ? "ok" : "bad");
+};
+$("add-app").onclick = addApp;
+$("empty-add").onclick = addApp;
+
+// ---------- toast ----------
+let toastTimer;
+function toast(msg, tone = "") {
+ const t = $("toast");
+ t.hidden = true; void t.offsetWidth; // restart the entrance animation
+ t.textContent = msg; t.dataset.tone = tone; t.hidden = false;
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => (t.hidden = true), tone === "bad" ? 7000 : 4200);
+}
+
+// ---------- polling ----------
+async function refreshApps() {
+ try { state.apps = await api("/api/apps"); if (!Array.isArray(state.apps)) state.apps = []; } catch { state.apps = []; }
+ renderApps();
+}
+async function refreshRuntime() {
+ try {
+ const [vm, setup, wins] = await Promise.all([api("/api/vm/status"), api("/api/provision/status"), api("/api/windows")]);
+ state.runtime = setup && setup.vm_exists === false ? "not_installed" : vm.state;
+ state.setup = setup;
+ state.running = new Set(Array.isArray(wins) ? wins.map((w) => w.title) : []);
+ if (vm.ram_mb) {
+ const used = vm.working_set_mb || 0;
+ $("rt-mem").textContent = used
+ ? `${(used / 1024).toFixed(1)} GB in use of ${(vm.ram_mb / 1024).toFixed(0)} GB`
+ : `Up to ${(vm.ram_mb / 1024).toFixed(0)} GB while Mac apps are open`;
+ $("rt-meter").style.width = `${Math.min(100, (used / vm.ram_mb) * 100).toFixed(0)}%`;
+ }
+ } catch { state.runtime = "unknown"; }
+ renderStatus();
+ renderApps();
+}
+
+// The runtime's disk speed matters more than anything else. Say so once if it's a hard disk.
+async function checkStorage() {
+ let s; try { s = await api("/api/system/storage"); } catch { return; }
+ if (!s || !s.drive) return;
+ $("storage-row").hidden = false;
+ $("storage-note").textContent = s.slow
+ ? `The runtime is on a hard disk (${s.drive}). Mac apps start much faster from an SSD.`
+ : `The runtime is on ${s.drive}${s.bus === "nvme" ? " (NVMe SSD)" : s.bus === "usb" ? " (USB drive)" : ""}.`;
+ let seen = false; try { seen = sessionStorage.getItem("wsm-slow-disk") === "1"; } catch {}
+ if (s.slow && !seen) {
+ toast(`Mac apps are on a hard disk (${s.drive}), so they'll start slowly. An SSD makes them start in seconds.`);
+ try { sessionStorage.setItem("wsm-slow-disk", "1"); } catch {}
+ }
+}
+
+$("free-space").onclick = async () => {
+ const r = await api("/api/vm/compact", { method: "POST" }).catch(() => null);
+ toast(r && r.ok ? "WSM will free up space the next time no Mac app is open for a few minutes." : "Couldn't schedule that. Try again.", r && r.ok ? "ok" : "bad");
+};
+
+refreshApps();
+refreshRuntime();
+pollInstall();
+checkStorage();
+setInterval(refreshRuntime, 2500);
+
+// Deep link: WsmManager.exe --settings opens straight to Settings.
+if (location.hash === "#settings") setSettings(true);
diff --git a/src/wsm-manager/index.html b/src/wsm-manager/index.html
new file mode 100644
index 0000000..23b41cb
--- /dev/null
+++ b/src/wsm-manager/index.html
@@ -0,0 +1,159 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>WSM</title>
+ <link rel="stylesheet" href="/ui/styles.css" />
+</head>
+<body>
+ <div class="aurora" aria-hidden="true"><i></i><i></i><i></i></div>
+
+ <main class="well" id="library" aria-labelledby="lib-title">
+ <header class="lib-head">
+ <div class="brand">
+ <img class="brand-mark" src="/ui/wsm.png" alt="" />
+ <div>
+ <h1 id="lib-title">Mac apps <span class="count" id="count" hidden></span></h1>
+ <p class="pill" id="status" role="status" aria-live="polite">
+ <span class="orb" aria-hidden="true"></span>
+ <span id="status-text">Checking the runtime…</span>
+ <button class="link" id="status-action" hidden></button>
+ </p>
+ </div>
+ </div>
+ <div class="lib-actions">
+ <button class="btn primary" id="add-app">
+ <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M8 3v10M3 8h10"/></svg>
+ Install app
+ </button>
+ <button class="icon-btn" id="open-settings" aria-label="Settings" title="Settings">
+ <svg viewBox="0 0 20 20" aria-hidden="true"><circle cx="10" cy="10" r="2.6"/><path d="M10 2.5v2M10 15.5v2M17.5 10h-2M4.5 10h-2M15.3 4.7l-1.4 1.4M6.1 13.9l-1.4 1.4M15.3 15.3l-1.4-1.4M6.1 6.1L4.7 4.7"/></svg>
+ </button>
+ </div>
+ </header>
+
+ <section class="shelf" id="shelf" aria-label="Installed apps"></section>
+
+ <section class="empty" id="empty" hidden>
+ <div class="stack" aria-hidden="true">
+ <span></span>
+ <span><svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg></span>
+ <span></span>
+ </div>
+ <h2>Bring your first Mac app</h2>
+ <p>Drop a <kbd>.dmg</kbd>, <kbd>.pkg</kbd>, <kbd>.zip</kbd> or <kbd>.app</kbd> here, or double-click one in File Explorer. It lands on your Desktop and in Start, and opens in its own window.</p>
+ <button class="btn primary" id="empty-add">Choose a file</button>
+ </section>
+ </main>
+
+ <div class="drop" aria-hidden="true">
+ <div class="drop-card">
+ <div class="arrow"><svg viewBox="0 0 24 24"><path d="M12 4v13M6 11l6 6 6-6M5 20h14"/></svg></div>
+ <b>Drop to install</b>
+ <span>.dmg, .pkg, .zip or .app</span>
+ </div>
+ </div>
+
+ <div class="scrim" id="scrim" hidden></div>
+ <aside class="settings" id="settings" aria-labelledby="settings-title" aria-hidden="true">
+ <header class="settings-head">
+ <h2 id="settings-title">Settings</h2>
+ <button class="icon-btn" id="close-settings" aria-label="Close settings">
+ <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4 4l8 8M12 4l-8 8"/></svg>
+ </button>
+ </header>
+
+ <div class="settings-body">
+ <section class="group">
+ <h3>Runtime</h3>
+ <div class="group-card">
+ <div class="row">
+ <div>
+ <div class="row-title" id="rt-version">macOS Tahoe</div>
+ <div class="row-sub" id="rt-state">—</div>
+ </div>
+ <button class="btn" id="rt-toggle">Sleep</button>
+ </div>
+ <div class="row">
+ <div>
+ <div class="row-title">Mode</div>
+ <div class="row-sub">Full compatibility runs every macOS framework. Lightweight is coming later.</div>
+ </div>
+ <div class="segmented" role="radiogroup" aria-label="Runtime">
+ <button role="radio" aria-checked="true" class="seg on">Full</button>
+ <button role="radio" aria-checked="false" class="seg" disabled title="Not available yet">Light</button>
+ </div>
+ </div>
+ <div class="row" id="storage-row" hidden>
+ <div>
+ <div class="row-title">Storage</div>
+ <div class="row-sub" id="storage-note">—</div>
+ </div>
+ <button class="btn" id="free-space" title="Gives unused space inside macOS back to Windows. Runs the next time no Mac app is open.">Free up space</button>
+ </div>
+ <div class="row">
+ <div>
+ <div class="row-title">Memory</div>
+ <div class="row-sub" id="rt-mem">—</div>
+ <div class="meter" aria-hidden="true"><i id="rt-meter"></i></div>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <section class="group">
+ <h3>Files</h3>
+ <div class="group-card">
+ <div class="row">
+ <div>
+ <div class="row-title">Shared folder</div>
+ <div class="row-sub">Files here are available to your Mac apps.</div>
+ </div>
+ <button class="btn" id="open-shared">Open</button>
+ </div>
+ </div>
+ </section>
+
+ <section class="group">
+ <h3>Troubleshooting</h3>
+ <div class="group-card">
+ <div class="row">
+ <div>
+ <div class="row-title">Diagnostic report</div>
+ <div class="row-sub">Collects logs with your user name and file paths removed.</div>
+ </div>
+ <button class="btn" id="export-report">Save</button>
+ </div>
+ <div class="row">
+ <div>
+ <div class="row-title">Repair the runtime</div>
+ <div class="row-sub">Reinstalls the macOS runtime. Files in the shared folder are kept.</div>
+ </div>
+ <a class="btn" href="/setup">Repair</a>
+ </div>
+ </div>
+ </section>
+
+ <p class="about"><img src="/ui/wsm.png" alt="" /><span id="about">WSM 0.3</span></p>
+ </div>
+ </aside>
+
+ <div class="toast" id="toast" role="status" aria-live="polite" hidden></div>
+
+ <template id="tile-tpl">
+ <button class="tile">
+ <span class="tile-icon"><img alt="" /><span class="run-dot" aria-hidden="true"></span></span>
+ <span class="tile-name"></span>
+ <span class="tile-note"></span>
+ </button>
+ </template>
+
+ <div class="menu" id="menu" role="menu" hidden>
+ <button role="menuitem" data-act="open"><svg viewBox="0 0 16 16"><path d="M6 3H3v10h10v-3M9 3h4v4M13 3L7 9"/></svg>Open</button>
+ <button role="menuitem" data-act="remove" class="danger"><svg viewBox="0 0 16 16"><path d="M3 4h10M6 4V2.5h4V4M4.5 4l.7 9.5h5.6l.7-9.5"/></svg>Uninstall</button>
+ </div>
+
+ <script src="/ui/app.js"></script>
+</body>
+</html>
diff --git a/src/wsm-manager/setup.html b/src/wsm-manager/setup.html
new file mode 100644
index 0000000..2550915
--- /dev/null
+++ b/src/wsm-manager/setup.html
@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Set up WSM</title>
+ <link rel="stylesheet" href="/ui/styles.css" />
+</head>
+<body>
+ <div class="aurora" aria-hidden="true"><i></i><i></i><i></i></div>
+
+ <!-- shared gradient for the progress ring -->
+ <svg width="0" height="0" aria-hidden="true" style="position:absolute">
+ <defs><linearGradient id="ring-grad" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#3156ff"/><stop offset="1" stop-color="#19b5f2"/></linearGradient></defs>
+ </svg>
+
+ <div class="wizard">
+ <nav class="rail glass-pane" aria-label="Setup steps">
+ <img class="brand-mark" src="/ui/wsm.png" alt="" />
+ <h1>Set up WSM</h1>
+ <p>A few minutes now, then Mac apps just open.</p>
+ <ol class="steps" id="steps">
+ <li data-step="welcome"><span class="mark"><span>1</span><svg viewBox="0 0 12 12"><path d="M2.5 6.5l2.2 2.2 4.8-5"/></svg></span>Welcome</li>
+ <li data-step="runtime"><span class="mark"><span>2</span><svg viewBox="0 0 12 12"><path d="M2.5 6.5l2.2 2.2 4.8-5"/></svg></span>Runtime</li>
+ <li data-step="review"><span class="mark"><span>3</span><svg viewBox="0 0 12 12"><path d="M2.5 6.5l2.2 2.2 4.8-5"/></svg></span>Review</li>
+ <li data-step="install"><span class="mark"><span>4</span><svg viewBox="0 0 12 12"><path d="M2.5 6.5l2.2 2.2 4.8-5"/></svg></span>Install</li>
+ </ol>
+ <div class="rail-foot">macOS runs out of sight. You only ever see your apps.</div>
+ </nav>
+
+ <main class="pane glass-pane" id="pane" aria-live="polite"></main>
+ </div>
+
+ <script src="/ui/setup.js"></script>
+</body>
+</html>
diff --git a/src/wsm-manager/setup.js b/src/wsm-manager/setup.js
new file mode 100644
index 0000000..7282f58
--- /dev/null
+++ b/src/wsm-manager/setup.js
@@ -0,0 +1,215 @@
+"use strict";
+// First-time setup. The user picks a runtime, presses Install (which is also the acceptance of
+// Apple's license, stated right above the button) and watches progress.
+// Every technical step (download, disks, installer, macOS first boot) happens out of sight.
+const API = location.origin;
+const pane = document.getElementById("pane");
+const steps = ["welcome", "runtime", "review", "install"];
+const S = { step: "welcome", runtime: "full", accepted: false, env: null, timer: null, shown: 0 };
+const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
+
+async function api(path, opts) { const r = await fetch(API + path, opts); try { return await r.json(); } catch { return {}; } }
+const gb = (b) => (b / 1e9).toFixed(1).replace(/\.0$/, "") + " GB";
+const CHECK = `<svg viewBox="0 0 12 12"><path d="M2.5 6.5l2.2 2.2 4.8-5"/></svg>`;
+
+// Fills the line down the step list up to the current step.
+function syncRail(step) {
+ const list = document.getElementById("steps");
+ const cur = steps.indexOf(step);
+ list.querySelectorAll("li").forEach((li) => {
+ const i = steps.indexOf(li.dataset.step);
+ li.classList.toggle("done", i < cur || step === "done");
+ if (i === cur) li.setAttribute("aria-current", "step"); else li.removeAttribute("aria-current");
+ });
+ const items = list.querySelectorAll("li");
+ const target = items[Math.min(Math.max(cur, 0), items.length - 1)];
+ const fill = step === "done" ? list.offsetHeight - 44 : target.offsetTop + target.offsetHeight / 2 - 22;
+ list.style.setProperty("--fill", `${Math.max(0, fill)}px`);
+}
+
+// Steps slide out to the left and the next slides in from the right.
+async function go(step) {
+ if (pane.children.length && !reduceMotion) {
+ pane.classList.remove("in"); pane.classList.add("out");
+ await new Promise((r) => setTimeout(r, 200));
+ }
+ pane.classList.remove("out");
+ S.step = step;
+ syncRail(step);
+ await VIEWS[step]();
+ pane.classList.remove("in"); void pane.offsetWidth; pane.classList.add("in");
+ const h = pane.querySelector("h2"); if (h) { h.tabIndex = -1; h.focus({ preventScroll: true }); }
+}
+
+function foot(...buttons) {
+ const f = document.createElement("div"); f.className = "foot";
+ for (const [label, fn, primary, disabled] of buttons) {
+ const b = document.createElement("button"); b.className = "btn" + (primary ? " primary" : " quiet");
+ b.textContent = label; b.onclick = fn; b.disabled = !!disabled; f.appendChild(b);
+ }
+ pane.appendChild(f); return f;
+}
+
+const ICON = {
+ window: `<svg viewBox="0 0 20 20"><rect x="2.5" y="4" width="15" height="12" rx="2.5"/><path d="M2.5 7.5h15M5 5.8h.01M7 5.8h.01"/></svg>`,
+ start: `<svg viewBox="0 0 20 20"><rect x="3" y="3" width="6" height="6" rx="1.5"/><rect x="11" y="3" width="6" height="6" rx="1.5"/><rect x="3" y="11" width="6" height="6" rx="1.5"/><rect x="11" y="11" width="6" height="6" rx="1.5"/></svg>`,
+ moon: `<svg viewBox="0 0 20 20"><path d="M16 12.5A6.5 6.5 0 0 1 7.5 4a6.5 6.5 0 1 0 8.5 8.5z"/></svg>`,
+};
+
+const VIEWS = {
+ welcome() {
+ pane.innerHTML = `
+ <div class="hero" aria-hidden="true">
+ <span class="glow"></span>
+ <span class="orbit"><i></i></span>
+ <span class="orbit two"><i></i></span>
+ <img src="/ui/wsm.png" alt="" />
+ </div>
+ <h2>Mac apps, at home on Windows</h2>
+ <p class="lede">WSM quietly adds a macOS runtime to this PC. Install a Mac app once and it opens like any Windows app.</p>
+ <div class="features">
+ <div class="feature"><div class="fi">${ICON.window}</div><b>Its own window</b><span>Each app on your desktop, never a Mac screen.</span></div>
+ <div class="feature"><div class="fi">${ICON.start}</div><b>Start and taskbar</b><span>Desktop icons, Start entries, pin to the taskbar.</span></div>
+ <div class="feature"><div class="fi">${ICON.moon}</div><b>Rests when idle</b><span>Sleeps when you're done, wakes in seconds.</span></div>
+ </div>`;
+ foot(["Get started", () => go("runtime"), true]);
+ },
+
+ runtime() {
+ pane.innerHTML = `
+ <h2>Choose a runtime</h2>
+ <p class="lede">You can change this later in Settings.</p>
+ <div class="choices" role="radiogroup" aria-label="Runtime">
+ <button class="choice" role="radio" data-v="full"><span class="dot"></span><span><b>Full compatibility <em class="tag">Recommended</em></b><span>Every macOS framework and service. Runs the widest range of apps. Uses about 5 GB of memory while Mac apps are open.</span></span></button>
+ <button class="choice" role="radio" data-v="light" disabled><span class="dot"></span><span><b>Lightweight <em class="tag">Later</em></b><span>Starts faster and uses less memory, for apps that need less of macOS.</span></span></button>
+ </div>`;
+ const sync = () => pane.querySelectorAll(".choice").forEach((c) => c.setAttribute("aria-checked", String(c.dataset.v === S.runtime)));
+ pane.querySelectorAll(".choice").forEach((c) => (c.onclick = () => { S.runtime = c.dataset.v; sync(); }));
+ sync();
+ foot(["Continue", () => go("review"), true], ["Back", () => go("welcome")]);
+ },
+
+ async review() {
+ S.env = S.env || await api("/api/setup/plan");
+ const e = S.env || {};
+ const reuse = e.reuse_installer;
+ const lowSpace = !!(e.free_bytes && e.free_bytes < (e.disk_needed_bytes || 40e9));
+ pane.innerHTML = `
+ <h2>Ready when you are</h2>
+ <p class="lede">${reuse
+ ? "Everything needed is already on this PC, so nothing will be downloaded."
+ : "The runtime is downloaded directly from Apple."}</p>
+ <dl class="facts">
+ <div class="fact"><dt>Runtime</dt><dd>${e.macos_name || "macOS Tahoe"}</dd></div>
+ <div class="fact"><dt>Download</dt><dd>${reuse ? "Nothing" : gb(e.download_bytes || 0)}</dd></div>
+ <div class="fact"><dt>Space needed</dt><dd>About ${gb(e.disk_needed_bytes || 40e9)} on ${e.drive || "F:"}</dd></div>
+ <div class="fact"><dt>Free space</dt><dd>${e.free_bytes ? gb(e.free_bytes) : "—"}</dd></div>
+ </dl>
+ <p class="lede">Takes about ${e.minutes || 45} minutes. Keep using your PC meanwhile; keep it plugged in and awake.</p>
+ <p class="fine">By selecting Install you agree to Apple's
+ <a href="https://www.apple.com/legal/sla/" target="_blank" rel="noopener">macOS Software License Agreement</a>.
+ WSM downloads macOS directly from Apple and never redistributes it.</p>`;
+ foot(["Install", () => { S.accepted = true; startInstall(); }, true, lowSpace], ["Back", () => go("runtime")]);
+ },
+
+ install() {
+ pane.innerHTML = `
+ <h2>Installing the macOS runtime</h2>
+ <p class="lede">You can close this window. Installation carries on in the background.</p>
+ <div class="install">
+ <div class="big-ring">
+ <svg viewBox="0 0 184 184"><circle class="track" cx="92" cy="92" r="85"/><circle class="fill" id="ring" cx="92" cy="92" r="85"/></svg>
+ <div class="num"><div><b id="pct">0%</b><small id="eta">Starting</small></div></div>
+ </div>
+ <ol class="phases" id="phases">
+ ${PHASES.map((p) => `<li data-at="${p.at}"><span class="pi">${CHECK}</span>${p.name}</li>`).join("")}
+ </ol>
+ </div>
+ <div class="detail" id="detail"></div>
+ <div id="err"></div>`;
+ S.shown = 0;
+ poll();
+ },
+
+ done() {
+ const colors = ["#3156ff", "#19b5f2", "#925cff", "#12a46b", "#f3b44f"];
+ const bits = Array.from({ length: 14 }, (_, i) =>
+ `<i style="--a:${(i * 360) / 14}deg;--c:${colors[i % colors.length]};animation-delay:${300 + (i % 3) * 40}ms"></i>`).join("");
+ pane.innerHTML = `
+ <div class="done-mark" aria-hidden="true">
+ <span class="disc"></span>
+ <svg viewBox="0 0 120 120"><path d="M36 62l16 16 34-36"/></svg>
+ <span class="burst">${bits}</span>
+ </div>
+ <h2>You're all set</h2>
+ <p class="lede">The macOS runtime is ready. Open any .dmg, .pkg or .zip, or drop it on WSM, and it installs with an icon on your Desktop.</p>`;
+ foot(["Open WSM", () => (location.href = "/"), true]);
+ },
+};
+
+// The checklist the ring walks through; "at" is the overall percent where each phase starts.
+const PHASES = [
+ { name: "Preparing this PC", at: 0 },
+ { name: "Getting macOS", at: 8 },
+ { name: "Installing macOS", at: 30 },
+ { name: "First start", at: 75 },
+ { name: "Finishing touches", at: 92 },
+];
+
+async function startInstall() {
+ const r = await api("/api/setup/begin", { method: "POST", body: JSON.stringify({ runtime: S.runtime, license_accepted: S.accepted }) });
+ if (r.ok === false && r.error) {
+ const box = document.createElement("div"); box.className = "err"; box.textContent = r.error;
+ pane.appendChild(box);
+ return;
+ }
+ go("install");
+}
+
+// Counts the number up smoothly instead of jumping.
+function animatePercent(to) {
+ const el = document.getElementById("pct"); if (!el) return;
+ const from = S.shown;
+ const t0 = performance.now(), dur = reduceMotion ? 0 : 900;
+ const step = (t) => {
+ const k = dur ? Math.min(1, (t - t0) / dur) : 1;
+ const v = Math.round(from + (to - from) * (1 - Math.pow(1 - k, 3)));
+ el.textContent = v + "%";
+ if (k < 1) requestAnimationFrame(step);
+ };
+ requestAnimationFrame(step);
+ S.shown = to;
+}
+
+async function poll() {
+ clearTimeout(S.timer);
+ const s = await api("/api/setup/progress");
+ const ring = document.getElementById("ring"); if (!ring) return;
+ const pct = Math.max(1, Math.min(100, Math.round(s.percent || 0)));
+ ring.style.strokeDashoffset = String(534 * (1 - pct / 100));
+ animatePercent(pct);
+ document.getElementById("eta").textContent = s.title || "Working";
+ document.getElementById("detail").textContent = s.detail || "";
+ document.querySelectorAll("#phases li").forEach((li, i, all) => {
+ const at = +li.dataset.at, next = i + 1 < all.length ? +all[i + 1].dataset.at : 101;
+ li.classList.toggle("done", pct >= next || s.state === "ready");
+ li.classList.toggle("now", pct >= at && pct < next && s.state !== "ready");
+ });
+ const err = document.getElementById("err");
+ if (s.state === "failed") {
+ err.innerHTML = "";
+ const box = document.createElement("div"); box.className = "err"; box.textContent = s.error || "Setup stopped.";
+ err.appendChild(box);
+ const f = foot(["Try again", async () => { f.remove(); err.innerHTML = ""; await api("/api/setup/begin", { method: "POST", body: JSON.stringify({ runtime: S.runtime, license_accepted: true, retry: true }) }); poll(); }, true],
+ ["Save diagnostic report", async () => { const r = await api("/api/diagnostics/export", { method: "POST" }); box.textContent = r.ok ? "Report saved to " + r.path : "Couldn't save the report."; }]);
+ return;
+ }
+ if (s.state === "ready") { setTimeout(() => go("done"), 700); return; }
+ S.timer = setTimeout(poll, 2000);
+}
+
+(async () => {
+ const s = await api("/api/setup/progress");
+ if (s.state && s.state !== "idle" && s.state !== "failed" && s.state !== "ready") { S.accepted = true; go("install"); }
+ else go(location.hash === "#done" ? "done" : "welcome");
+})();
diff --git a/src/wsm-manager/styles.css b/src/wsm-manager/styles.css
new file mode 100644
index 0000000..73ef2ed
--- /dev/null
+++ b/src/wsm-manager/styles.css
@@ -0,0 +1,509 @@
+/* WSM — Mac apps, at home on Windows.
+ Palette and glass come from the WSM icon: brand blue into cyan, frosted panes over Mica.
+ Motion is soft and springy, and always stops for prefers-reduced-motion. */
+@property --p { syntax: "<number>"; inherits: true; initial-value: 0; }
+:root {
+ color-scheme: light dark;
+ --ink: #10131a;
+ --ink-2: #4c5466;
+ --ink-3: #868ea0;
+ --well: rgba(255, 255, 255, 0.6);
+ --glass: rgba(255, 255, 255, 0.62);
+ --glass-strong: rgba(255, 255, 255, 0.86);
+ --solid: #f6f7fb;
+ --line: rgba(16, 24, 48, 0.08);
+ --line-strong: rgba(16, 24, 48, 0.14);
+ --hover: rgba(16, 24, 48, 0.05);
+ --shadow: 0 1px 2px rgba(16, 24, 48, .06), 0 10px 30px rgba(16, 24, 48, .10);
+ --shadow-lift: 0 2px 4px rgba(16, 24, 48, .08), 0 24px 48px rgba(16, 24, 48, .16);
+
+ --brand-1: #3156ff;
+ --brand-2: #19b5f2;
+ --accent: #2f5cf5;
+ --accent-ink: #ffffff;
+ --accent-soft: rgba(47, 92, 245, 0.12);
+ --ok: #12a46b;
+ --warn: #c27a00;
+ --bad: #d4351f;
+ --aurora-a: rgba(49, 86, 255, 0.30);
+ --aurora-b: rgba(25, 181, 242, 0.26);
+ --aurora-c: rgba(146, 92, 255, 0.18);
+
+ --display: "Segoe UI Variable Display", "Segoe UI Variable", "Segoe UI", system-ui, sans-serif;
+ --text: "Segoe UI Variable Text", "Segoe UI Variable", "Segoe UI", system-ui, sans-serif;
+
+ --t-xs: 11.5px;
+ --t-sm: 12.5px;
+ --t-base: 14px;
+ --t-md: 16px;
+ --t-lg: 22px;
+ --t-xl: 32px;
+ --t-2xl: 44px;
+
+ /* Radius grows with the surface: controls < cards < panes < the window's content well. */
+ --r-sm: 8px;
+ --r-md: 12px;
+ --r-lg: 18px;
+ --r-xl: 24px;
+ --ease: cubic-bezier(.2, .8, .2, 1);
+ --ease-out: cubic-bezier(.16, 1, .3, 1);
+ --spring: cubic-bezier(.34, 1.56, .64, 1);
+}
+@media (prefers-color-scheme: dark) {
+ :root {
+ --ink: #f3f5fb;
+ --ink-2: #a9b1c4;
+ --ink-3: #747d92;
+ --well: rgba(16, 18, 26, 0.6);
+ --glass: rgba(34, 38, 52, 0.58);
+ --glass-strong: rgba(36, 40, 54, 0.92);
+ --solid: #1d2130;
+ --line: rgba(255, 255, 255, 0.07);
+ --line-strong: rgba(255, 255, 255, 0.13);
+ --hover: rgba(255, 255, 255, 0.06);
+ --shadow: 0 1px 2px rgba(0, 0, 0, .3), 0 12px 32px rgba(0, 0, 0, .35);
+ --shadow-lift: 0 2px 6px rgba(0, 0, 0, .35), 0 28px 56px rgba(0, 0, 0, .5);
+ --accent: #6f97ff;
+ --accent-ink: #081233;
+ --accent-soft: rgba(111, 151, 255, 0.16);
+ --ok: #3ad69a;
+ --warn: #f3b44f;
+ --bad: #ff8b78;
+ --aurora-a: rgba(49, 86, 255, 0.34);
+ --aurora-b: rgba(25, 181, 242, 0.22);
+ --aurora-c: rgba(146, 92, 255, 0.22);
+ }
+}
+
+* { box-sizing: border-box; }
+[hidden] { display: none !important; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: transparent;
+ color: var(--ink);
+ font: 400 var(--t-base)/1.45 var(--text);
+ -webkit-font-smoothing: antialiased;
+ user-select: none;
+ overflow: hidden;
+}
+button, a, input { font: inherit; color: inherit; }
+button { cursor: default; }
+svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
+:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: var(--r-sm); }
+
+/* ---------- ambient aurora (behind the content well) ---------- */
+.aurora { position: fixed; inset: -20%; z-index: -1; pointer-events: none; filter: blur(70px); opacity: .9; }
+.aurora i { position: absolute; border-radius: 50%; }
+.aurora i:nth-child(1) { width: 55vw; height: 55vw; left: 5%; top: -5%; background: radial-gradient(circle, var(--aurora-a), transparent 65%); animation: drift-a 32s ease-in-out infinite alternate; }
+.aurora i:nth-child(2) { width: 45vw; height: 45vw; right: 0; top: 20%; background: radial-gradient(circle, var(--aurora-b), transparent 65%); animation: drift-b 38s ease-in-out infinite alternate; }
+.aurora i:nth-child(3) { width: 50vw; height: 50vw; left: 30%; bottom: -15%; background: radial-gradient(circle, var(--aurora-c), transparent 65%); animation: drift-c 44s ease-in-out infinite alternate; }
+@keyframes drift-a { to { transform: translate(12vw, 8vh) scale(1.15); } }
+@keyframes drift-b { to { transform: translate(-14vw, 10vh) scale(.9); } }
+@keyframes drift-c { to { transform: translate(-8vw, -12vh) scale(1.1); } }
+
+/* ---------- controls ---------- */
+.btn {
+ position: relative; display: inline-flex; align-items: center; justify-content: center; gap: 8px;
+ height: 36px; padding: 0 16px; border: 1px solid var(--line-strong); border-radius: 999px;
+ background: var(--glass-strong); color: var(--ink); text-decoration: none; white-space: nowrap;
+ font-weight: 600; letter-spacing: .005em;
+ transition: background .2s, transform .25s var(--spring), box-shadow .25s, border-color .2s;
+}
+.btn:hover { background: color-mix(in srgb, var(--glass-strong) 85%, var(--ink)); }
+.btn:active { transform: scale(.95); transition-duration: .08s; }
+.btn.primary {
+ border-color: transparent; color: #fff; overflow: hidden;
+ background: linear-gradient(135deg, var(--brand-1), var(--brand-2));
+ box-shadow: 0 1px 0 rgba(255,255,255,.25) inset, 0 8px 22px color-mix(in srgb, var(--brand-1) 38%, transparent);
+}
+.btn.primary::after { /* a slow light sweep, so the main action feels alive */
+ content: ""; position: absolute; inset: 0; transform: translateX(-120%);
+ background: linear-gradient(100deg, transparent 30%, rgba(255,255,255,.35) 50%, transparent 70%);
+ animation: sweep 5s var(--ease) 1.2s infinite;
+}
+.btn.primary:hover { box-shadow: 0 1px 0 rgba(255,255,255,.25) inset, 0 12px 30px color-mix(in srgb, var(--brand-1) 50%, transparent); transform: translateY(-1px); }
+.btn.primary:active { transform: scale(.95); }
+@keyframes sweep { 0% { transform: translateX(-120%); } 30%, 100% { transform: translateX(120%); } }
+.btn.quiet { background: transparent; border-color: transparent; color: var(--ink-2); }
+.btn.quiet:hover { background: var(--hover); color: var(--ink); }
+.btn[disabled] { opacity: .45; pointer-events: none; }
+.btn svg { width: 15px; height: 15px; stroke-width: 2; }
+
+.icon-btn {
+ width: 36px; height: 36px; display: grid; place-items: center; border: 0; border-radius: 50%;
+ background: transparent; color: var(--ink-2); transition: background .2s, color .2s, transform .25s var(--spring);
+}
+.icon-btn:hover { background: var(--hover); color: var(--ink); }
+.icon-btn:active { transform: scale(.9); }
+.icon-btn svg { width: 18px; height: 18px; transition: transform .6s var(--ease-out); }
+#open-settings:hover svg { transform: rotate(90deg); }
+.link { border: 0; background: none; padding: 0; color: var(--accent); font-weight: 600; text-decoration: underline; text-underline-offset: 3px; }
+
+/* ---------- the content well ---------- */
+.well {
+ position: absolute; inset: 10px; display: flex; flex-direction: column; overflow: hidden;
+ border-radius: var(--r-xl); background: var(--well); border: 1px solid var(--line);
+ box-shadow: 0 1px 0 rgba(255,255,255,.4) inset;
+ backdrop-filter: blur(24px) saturate(1.3);
+ animation: well-in .7s var(--ease-out) both;
+}
+@keyframes well-in { from { opacity: 0; transform: scale(.985); } }
+
+/* ---------- library header ---------- */
+.lib-head { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 28px 36px 8px; }
+.brand { display: flex; align-items: center; gap: 16px; min-width: 0; }
+.brand-mark { width: 52px; height: 52px; flex: none; filter: drop-shadow(0 8px 16px color-mix(in srgb, var(--brand-1) 40%, transparent)); animation: float 6s ease-in-out infinite; }
+@keyframes float { 50% { transform: translateY(-4px) rotate(-2deg); } }
+.brand h1 { margin: 0; font: 650 var(--t-xl)/1.1 var(--display); letter-spacing: -0.022em; display: flex; align-items: baseline; gap: 12px; }
+.count { font: 600 var(--t-sm)/1 var(--text); color: var(--ink-3); padding: 5px 9px; border-radius: 999px; background: var(--hover); letter-spacing: 0; }
+.lib-actions { display: flex; gap: 6px; align-items: center; }
+
+/* runtime pill: a little living light that says how the runtime is doing */
+.pill { margin-top: 7px; display: inline-flex; align-items: center; gap: 9px; color: var(--ink-2); font-size: var(--t-base); min-height: 22px; }
+.orb { position: relative; width: 9px; height: 9px; border-radius: 50%; background: var(--ink-3); flex: none; transition: background .4s; }
+.orb::after { content: ""; position: absolute; inset: -5px; border-radius: 50%; border: 2px solid currentColor; opacity: 0; color: transparent; }
+.pill[data-tone="ready"] .orb { background: var(--ok); }
+.pill[data-tone="ready"] .orb::after { color: var(--ok); animation: halo 2.6s var(--ease-out) infinite; }
+.pill[data-tone="busy"] .orb { background: var(--accent); }
+.pill[data-tone="busy"] .orb::after { inset: -4px; opacity: 1; color: var(--accent); border-color: var(--accent) transparent transparent transparent; animation: spin 0.9s linear infinite; }
+.pill[data-tone="idle"] .orb { background: var(--ink-3); animation: sleep 3.6s ease-in-out infinite; }
+.pill[data-tone="bad"] .orb { background: var(--bad); }
+.pill .link { font-size: var(--t-base); }
+@keyframes halo { 0% { opacity: .55; transform: scale(.6); } 100% { opacity: 0; transform: scale(1.9); } }
+@keyframes sleep { 50% { opacity: .35; transform: scale(.75); } }
+@keyframes spin { to { transform: rotate(360deg); } }
+
+/* ---------- shelf of apps ---------- */
+.shelf {
+ flex: 1; overflow-y: auto; padding: 22px 26px 40px;
+ display: grid; grid-template-columns: repeat(auto-fill, minmax(148px, 1fr)); align-content: start; gap: 10px;
+}
+.tile {
+ --glow: 80, 120, 255; --rx: 0deg; --ry: 0deg;
+ position: relative; display: flex; flex-direction: column; align-items: center; gap: 3px;
+ padding: 22px 10px 16px; border: 1px solid transparent; border-radius: var(--r-lg);
+ background: transparent; text-align: center; outline-offset: -2px;
+ transition: background .25s, border-color .25s;
+ animation: tile-in .7s var(--ease-out) both; animation-delay: calc(var(--i, 0) * 55ms);
+}
+.tile::before { /* the icon's own colour, softly lighting the card */
+ content: ""; position: absolute; left: 50%; top: 44px; width: 150px; height: 110px; transform: translateX(-50%);
+ border-radius: 50%; background: radial-gradient(ellipse, rgba(var(--glow), .55), transparent 68%);
+ filter: blur(20px); opacity: .55; transition: opacity .35s, transform .35s var(--ease-out); pointer-events: none;
+}
+.tile:hover { background: var(--hover); border-color: var(--line); }
+.tile:hover::before { opacity: 1; transform: translateX(-50%) scale(1.15); }
+@keyframes tile-in { from { opacity: 0; transform: translateY(16px) scale(.92); filter: blur(4px); } }
+.tile-icon {
+ position: relative; width: 92px; height: 92px; margin-bottom: 12px; display: grid; place-items: center;
+ transform: perspective(500px) rotateX(var(--rx)) rotateY(var(--ry));
+ transition: transform .5s var(--ease-out);
+}
+.tile:hover .tile-icon { transform: perspective(500px) rotateX(var(--rx)) rotateY(var(--ry)) translateY(-5px) scale(1.05); transition: transform .15s ease-out; }
+.tile-icon img, .fallback-icon { width: 92px; height: 92px; object-fit: contain; filter: drop-shadow(0 8px 12px rgba(0,0,0,.18)); transition: filter .35s; }
+.tile:hover .tile-icon img { filter: drop-shadow(0 18px 20px rgba(0,0,0,.26)); }
+.tile:active .tile-icon { transform: scale(.9); transition: transform .1s; }
+.tile-name { position: relative; font-weight: 600; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.tile-note { position: relative; font-size: var(--t-sm); color: var(--ink-3); min-height: 18px; transition: color .3s; }
+
+/* launching: squash, bounce and a ripple, the way a Dock icon jumps */
+.tile[data-busy] .tile-icon img { animation: hop 1.15s var(--ease) infinite; }
+.tile[data-busy] .tile-icon::after {
+ content: ""; position: absolute; inset: 4px; border-radius: 24px; border: 2px solid rgba(var(--glow), .9);
+ animation: ripple 1.15s var(--ease-out) infinite; pointer-events: none;
+}
+.tile[data-busy] .tile-note { color: var(--accent); }
+@keyframes hop {
+ 0%, 100% { transform: translateY(0) scale(1, 1); }
+ 12% { transform: translateY(2px) scale(1.06, .92); }
+ 40% { transform: translateY(-16px) scale(.97, 1.04); }
+ 62% { transform: translateY(0) scale(1.04, .96); }
+ 76% { transform: translateY(-3px) scale(1, 1); }
+}
+@keyframes ripple { from { opacity: .8; transform: scale(.85); } to { opacity: 0; transform: scale(1.45); } }
+
+/* running: a small light under the icon, like the macOS Dock */
+.tile .run-dot { position: absolute; left: 50%; bottom: -8px; width: 5px; height: 5px; margin-left: -2.5px; border-radius: 50%; background: var(--ink-2); opacity: 0; transform: scale(0); transition: opacity .3s, transform .4s var(--spring); }
+.tile[data-running] .run-dot { opacity: 1; transform: none; }
+
+/* installing: a frosted placeholder with an iPhone-style progress ring */
+.tile.installing { --p: 0; cursor: default; }
+.ring-box {
+ position: relative; width: 92px; height: 92px; border-radius: 22px; display: grid; place-items: center;
+ background: linear-gradient(145deg, color-mix(in srgb, var(--brand-1) 78%, #000 0%), var(--brand-2));
+ border: 1px solid var(--line-strong); box-shadow: var(--shadow); overflow: hidden;
+}
+.ring-box::before { /* shimmer while working */
+ content: ""; position: absolute; inset: 0; transform: translateX(-100%);
+ background: linear-gradient(110deg, transparent 35%, rgba(255,255,255,.35) 50%, transparent 65%);
+ animation: sweep 2.4s ease-in-out infinite;
+}
+.ring {
+ width: 54px; height: 54px; border-radius: 50%;
+ background: conic-gradient(#fff calc(var(--p) * 1%), rgba(255,255,255,.28) 0);
+ -webkit-mask: radial-gradient(circle, transparent 20px, #000 21px);
+ mask: radial-gradient(circle, transparent 20px, #000 21px);
+ transition: --p .6s; filter: drop-shadow(0 2px 6px rgba(0,0,0,.2));
+}
+.tile.installing .tile-note { color: var(--accent); }
+.tile.pop .tile-icon { animation: pop-in .8s var(--spring) both; }
+@keyframes pop-in { 0% { transform: scale(.4); opacity: 0; } 60% { opacity: 1; } 100% { transform: scale(1); } }
+
+/* ---------- empty state ---------- */
+.empty { margin: auto; max-width: 460px; text-align: center; padding: 0 24px 9vh; animation: tile-in .8s var(--ease-out) both; }
+.stack { position: relative; width: 210px; height: 140px; margin: 0 auto 26px; }
+.stack span {
+ position: absolute; width: 76px; height: 76px; border-radius: 20px; border: 1px solid var(--line-strong);
+ background: linear-gradient(150deg, var(--glass-strong), var(--glass)); box-shadow: var(--shadow);
+ backdrop-filter: blur(10px);
+}
+.stack span:nth-child(1) { left: 12px; top: 40px; transform: rotate(-12deg); animation: bob 5s ease-in-out infinite; }
+.stack span:nth-child(2) { left: 67px; top: 12px; z-index: 2; background: linear-gradient(145deg, var(--brand-1), var(--brand-2)); border: 0; animation: bob 5s ease-in-out -1.6s infinite; display: grid; place-items: center; }
+.stack span:nth-child(3) { right: 12px; top: 44px; transform: rotate(11deg); animation: bob 5s ease-in-out -3.2s infinite; }
+.stack span:nth-child(2) svg { width: 34px; height: 34px; stroke: #fff; stroke-width: 2.2; }
+@keyframes bob { 50% { translate: 0 -8px; } }
+.empty h2 { margin: 0 0 8px; font: 650 var(--t-lg)/1.25 var(--display); letter-spacing: -0.01em; }
+.empty p { margin: 0 0 22px; color: var(--ink-2); line-height: 1.55; }
+.empty kbd { font: 600 var(--t-sm)/1 var(--text); padding: 3px 6px; border-radius: 6px; background: var(--hover); border: 1px solid var(--line); }
+
+/* ---------- drop overlay ---------- */
+.drop {
+ position: fixed; inset: 10px; z-index: 50; border-radius: var(--r-xl); display: grid; place-items: center;
+ background: color-mix(in srgb, var(--brand-1) 14%, var(--well)); backdrop-filter: blur(14px);
+ opacity: 0; pointer-events: none; transition: opacity .25s;
+}
+.drop::before { content: ""; position: absolute; inset: 18px; border-radius: calc(var(--r-xl) - 6px); border: 2.5px dashed color-mix(in srgb, var(--accent) 70%, transparent); animation: march 1s linear infinite paused; }
+body.dropping .drop { opacity: 1; }
+body.dropping .drop::before { animation-play-state: running; }
+.drop-card { text-align: center; transform: scale(.94); transition: transform .4s var(--spring); }
+body.dropping .drop-card { transform: none; }
+.drop-card .arrow { width: 84px; height: 84px; margin: 0 auto 16px; border-radius: 26px; display: grid; place-items: center; background: linear-gradient(145deg, var(--brand-1), var(--brand-2)); box-shadow: 0 16px 40px color-mix(in srgb, var(--brand-1) 45%, transparent); animation: nudge 1.2s var(--ease) infinite; }
+.drop-card .arrow svg { width: 38px; height: 38px; stroke: #fff; stroke-width: 2.4; }
+.drop-card b { display: block; font: 650 var(--t-lg)/1.2 var(--display); }
+.drop-card span { color: var(--ink-2); }
+@keyframes nudge { 50% { transform: translateY(8px); } }
+@keyframes march { to { stroke-dashoffset: 0; } }
+
+/* ---------- settings sheet ---------- */
+.scrim { position: fixed; inset: 0; background: rgba(6, 10, 24, .28); backdrop-filter: blur(3px); opacity: 0; transition: opacity .35s; z-index: 30; }
+.scrim.show { opacity: 1; }
+.settings {
+ position: fixed; top: 10px; right: 10px; bottom: 10px; width: min(460px, 92vw); z-index: 31;
+ background: var(--glass-strong); backdrop-filter: blur(30px) saturate(1.4);
+ border: 1px solid var(--line-strong); border-radius: var(--r-xl); box-shadow: var(--shadow-lift);
+ transform: translateX(calc(100% + 30px)) scale(.98); transition: transform .5s var(--ease-out);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+.settings.open { transform: none; }
+.settings.open .group { animation: tile-in .55s var(--ease-out) both; }
+.settings.open .group:nth-child(2) { animation-delay: 60ms; }
+.settings.open .group:nth-child(3) { animation-delay: 120ms; }
+.settings.open .group:nth-child(4) { animation-delay: 180ms; }
+.settings-head { display: flex; align-items: center; justify-content: space-between; padding: 22px 18px 6px 28px; }
+.settings-head h2 { margin: 0; font: 650 var(--t-lg)/1.2 var(--display); }
+.settings-body { overflow-y: auto; padding: 0 22px 28px; }
+.group { margin-top: 22px; }
+.group h3 { margin: 0 0 8px 6px; font: 600 var(--t-sm)/1.3 var(--text); color: var(--ink-3); text-transform: uppercase; letter-spacing: .08em; }
+.group-card { border-radius: var(--r-lg); background: var(--hover); border: 1px solid var(--line); overflow: hidden; }
+.row { display: flex; align-items: center; justify-content: space-between; gap: 18px; padding: 14px 16px; }
+.row + .row { border-top: 1px solid var(--line); }
+.row-title { font-weight: 600; }
+.row-sub { color: var(--ink-2); font-size: var(--t-sm); margin-top: 2px; max-width: 36ch; }
+.meter { height: 6px; border-radius: 999px; background: var(--hover); margin-top: 8px; overflow: hidden; width: 220px; }
+.meter i { display: block; height: 100%; width: 0; border-radius: 999px; background: linear-gradient(90deg, var(--brand-1), var(--brand-2)); transition: width .8s var(--ease-out); }
+.segmented { display: inline-flex; padding: 3px; border-radius: 999px; background: var(--hover); border: 1px solid var(--line); }
+.seg { border: 0; background: transparent; padding: 5px 16px; border-radius: 999px; color: var(--ink-2); transition: background .25s, color .25s; }
+.seg.on { background: var(--solid); color: var(--ink); font-weight: 600; box-shadow: 0 1px 3px rgba(0,0,0,.14); }
+.seg[disabled] { opacity: .5; }
+.about { margin: 28px 6px 0; color: var(--ink-3); font-size: var(--t-sm); display: flex; align-items: center; gap: 10px; }
+.about img { width: 22px; height: 22px; }
+
+/* ---------- menu & toast ---------- */
+.menu {
+ position: fixed; z-index: 40; min-width: 200px; padding: 6px; border-radius: var(--r-md); transform-origin: top left;
+ background: var(--glass-strong); backdrop-filter: blur(24px); border: 1px solid var(--line-strong); box-shadow: var(--shadow-lift);
+ animation: pop .22s var(--spring);
+}
+.menu button { display: flex; align-items: center; gap: 10px; width: 100%; text-align: left; padding: 8px 12px; border: 0; background: none; border-radius: var(--r-sm); }
+.menu button:hover { background: var(--hover); }
+.menu .danger { color: var(--bad); }
+.menu svg { width: 15px; height: 15px; }
+.toast {
+ position: fixed; left: 50%; bottom: 26px; z-index: 60; transform: translateX(-50%);
+ display: flex; align-items: center; gap: 12px;
+ max-width: min(600px, 90vw); padding: 11px 20px 11px 14px; border-radius: 999px;
+ background: var(--glass-strong); backdrop-filter: blur(24px); border: 1px solid var(--line-strong);
+ box-shadow: var(--shadow-lift); animation: rise .45s var(--spring);
+}
+.toast::before { content: ""; width: 10px; height: 10px; border-radius: 50%; flex: none; background: linear-gradient(135deg, var(--brand-1), var(--brand-2)); box-shadow: 0 0 0 4px var(--accent-soft); }
+.toast[data-tone="bad"]::before { background: var(--bad); box-shadow: 0 0 0 4px color-mix(in srgb, var(--bad) 18%, transparent); }
+.toast[data-tone="ok"]::before { background: var(--ok); box-shadow: 0 0 0 4px color-mix(in srgb, var(--ok) 18%, transparent); }
+@keyframes pop { from { opacity: 0; transform: scale(.9); } }
+@keyframes rise { from { opacity: 0; transform: translate(-50%, 14px) scale(.96); } }
+
+/* ---------- setup wizard ---------- */
+.wizard { position: absolute; inset: 10px; display: grid; grid-template-columns: minmax(270px, 30%) 1fr; gap: 10px; }
+.rail { position: relative; padding: 34px 26px; display: flex; flex-direction: column; animation: well-in .7s var(--ease-out) both; }
+.rail .brand-mark { width: 46px; height: 46px; margin-bottom: 18px; }
+.rail h1 { margin: 0 0 4px; font: 650 var(--t-lg)/1.2 var(--display); letter-spacing: -0.01em; }
+.rail p { margin: 0; color: var(--ink-2); }
+.steps { position: relative; list-style: none; margin: 38px 0 0; padding: 0; display: grid; gap: 6px; }
+.steps::before, .steps::after { content: ""; position: absolute; left: 22px; top: 22px; width: 2px; border-radius: 2px; }
+.steps::before { bottom: 22px; background: var(--line-strong); }
+.steps::after { height: var(--fill, 0px); background: linear-gradient(var(--brand-1), var(--brand-2)); transition: height .7s var(--ease-out); }
+.steps li { position: relative; z-index: 1; display: flex; align-items: center; gap: 14px; padding: 9px 12px; border-radius: 999px; color: var(--ink-3); transition: color .35s, background .35s; }
+.steps .mark {
+ width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; flex: none;
+ font-size: 11px; font-weight: 700; background: var(--solid); border: 1.5px solid var(--line-strong);
+ transition: background .35s, border-color .35s, color .35s, transform .45s var(--spring), box-shadow .35s;
+}
+.steps .mark svg { width: 12px; height: 12px; stroke-width: 3; display: none; }
+.steps li[aria-current="step"] { color: var(--ink); font-weight: 600; background: var(--hover); }
+.steps li[aria-current="step"] .mark { border-color: var(--accent); color: var(--accent); transform: scale(1.12); box-shadow: 0 0 0 5px var(--accent-soft); }
+.steps li.done { color: var(--ink-2); }
+.steps li.done .mark { background: linear-gradient(135deg, var(--brand-1), var(--brand-2)); border-color: transparent; color: #fff; }
+.steps li.done .mark span { display: none; }
+.steps li.done .mark svg { display: block; animation: draw .4s var(--ease-out) both; stroke-dasharray: 20; }
+@keyframes draw { from { stroke-dashoffset: 20; } to { stroke-dashoffset: 0; } }
+.rail-foot { margin-top: auto; color: var(--ink-3); font-size: var(--t-sm); }
+
+.pane { position: relative; padding: 64px 64px 40px; display: flex; flex-direction: column; overflow-y: auto; overflow-x: hidden; }
+.pane.in > * { animation: step-in .6s var(--ease-out) both; }
+.pane.in > *:nth-child(2) { animation-delay: 50ms; } .pane.in > *:nth-child(3) { animation-delay: 100ms; }
+.pane.in > *:nth-child(4) { animation-delay: 150ms; } .pane.in > *:nth-child(5) { animation-delay: 200ms; } .pane.in > *:nth-child(6) { animation-delay: 250ms; }
+.pane.out > * { animation: step-out .22s var(--ease) both; }
+@keyframes step-in { from { opacity: 0; transform: translateX(26px); filter: blur(3px); } }
+@keyframes step-out { to { opacity: 0; transform: translateX(-18px); } }
+.pane h2 { margin: 0 0 12px; font: 650 var(--t-xl)/1.12 var(--display); letter-spacing: -0.022em; max-width: 22ch; text-wrap: balance; }
+.pane .lede { margin: 0 0 26px; color: var(--ink-2); font-size: var(--t-md); line-height: 1.55; max-width: 54ch; }
+
+/* welcome hero: the WSM mark in orbit */
+.hero { position: relative; width: 190px; height: 190px; margin: -8px 0 26px; display: grid; place-items: center; }
+.hero img { width: 116px; height: 116px; z-index: 2; filter: drop-shadow(0 18px 30px color-mix(in srgb, var(--brand-1) 45%, transparent)); animation: float 6s ease-in-out infinite; }
+.hero .glow { position: absolute; inset: 22px; border-radius: 50%; background: radial-gradient(circle, color-mix(in srgb, var(--brand-2) 45%, transparent), transparent 70%); filter: blur(14px); animation: breathe 5s ease-in-out infinite; }
+.hero .orbit { position: absolute; inset: 0; border-radius: 50%; border: 1.5px dashed color-mix(in srgb, var(--accent) 35%, transparent); animation: spin 26s linear infinite; }
+.hero .orbit.two { inset: 18px; border-style: solid; border-color: color-mix(in srgb, var(--brand-2) 22%, transparent); animation-duration: 18s; animation-direction: reverse; }
+.hero .orbit i { position: absolute; width: 10px; height: 10px; border-radius: 50%; top: -5px; left: 50%; margin-left: -5px; background: linear-gradient(135deg, var(--brand-1), var(--brand-2)); box-shadow: 0 0 12px var(--brand-2); }
+.hero .orbit.two i { top: auto; bottom: -4px; width: 7px; height: 7px; }
+@keyframes breathe { 50% { transform: scale(1.12); opacity: .7; } }
+.features { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; max-width: 640px; margin-bottom: 8px; }
+.feature { padding: 16px; border-radius: var(--r-lg); background: var(--hover); border: 1px solid var(--line); transition: transform .35s var(--spring), border-color .3s, background .3s; }
+.feature:hover { transform: translateY(-3px); border-color: var(--line-strong); }
+.feature .fi { width: 34px; height: 34px; border-radius: 11px; display: grid; place-items: center; margin-bottom: 10px; color: #fff; background: linear-gradient(135deg, var(--brand-1), var(--brand-2)); box-shadow: 0 6px 14px color-mix(in srgb, var(--brand-1) 30%, transparent); }
+.feature .fi svg { width: 18px; height: 18px; stroke-width: 2; }
+.feature b { display: block; margin-bottom: 3px; }
+.feature span { color: var(--ink-2); font-size: var(--t-sm); line-height: 1.45; }
+
+.choices { display: grid; gap: 10px; max-width: 580px; }
+.choice {
+ position: relative; display: flex; gap: 14px; align-items: flex-start; text-align: left; padding: 18px 20px;
+ border: 1px solid var(--line-strong); border-radius: var(--r-lg); background: var(--glass);
+ transition: border-color .25s, box-shadow .3s, transform .3s var(--spring), background .25s;
+}
+.choice:hover { transform: translateY(-2px); border-color: color-mix(in srgb, var(--accent) 45%, var(--line)); }
+.choice:active { transform: scale(.99); }
+.choice[aria-checked="true"] { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft), var(--shadow); background: var(--glass-strong); }
+.choice[disabled] { opacity: .55; pointer-events: none; }
+.choice .dot { width: 20px; height: 20px; border-radius: 50%; border: 1.5px solid var(--ink-3); margin-top: 1px; flex: none; transition: border .3s var(--spring), border-color .25s; }
+.choice[aria-checked="true"] .dot { border: 6px solid var(--accent); }
+.choice b { display: block; margin-bottom: 3px; font-size: var(--t-md); }
+.choice span { color: var(--ink-2); font-size: var(--t-sm); line-height: 1.5; }
+.tag { display: inline-block; margin-left: 8px; padding: 2px 8px; border-radius: 999px; font: 600 var(--t-xs)/1.5 var(--text); color: var(--accent); background: var(--accent-soft); vertical-align: 2px; }
+
+.license { max-width: 640px; height: 230px; overflow-y: auto; padding: 18px 20px; border: 1px solid var(--line-strong); border-radius: var(--r-lg); background: var(--glass); color: var(--ink-2); font-size: var(--t-sm); line-height: 1.6; user-select: text; }
+.check { display: flex; gap: 12px; align-items: center; margin-top: 18px; max-width: 640px; }
+.check input { appearance: none; width: 20px; height: 20px; margin: 0; flex: none; border-radius: 6px; border: 1.5px solid var(--ink-3); display: grid; place-items: center; transition: background .2s, border-color .2s, transform .3s var(--spring); }
+.check input:checked { background: linear-gradient(135deg, var(--brand-1), var(--brand-2)); border-color: transparent; transform: scale(1.06); }
+.check input:checked::after { content: ""; width: 10px; height: 5px; border: 2.2px solid #fff; border-top: 0; border-right: 0; transform: translateY(-1px) rotate(-45deg); }
+
+.facts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; max-width: 600px; margin: 0 0 22px; }
+.fact { padding: 14px 16px; border-radius: var(--r-md); background: var(--hover); border: 1px solid var(--line); }
+.fact dt { color: var(--ink-3); font-size: var(--t-sm); margin-bottom: 2px; }
+.fact dd { margin: 0; font: 650 var(--t-md)/1.3 var(--display); }
+
+/* install: a big ring that fills, and a checklist that ticks off */
+.install { display: flex; align-items: center; gap: 44px; flex-wrap: wrap; margin-top: 8px; }
+.big-ring { position: relative; width: 184px; height: 184px; flex: none; }
+.big-ring svg { width: 184px; height: 184px; transform: rotate(-90deg); overflow: visible; }
+.big-ring circle { fill: none; stroke-width: 12; }
+.big-ring .track { stroke: var(--hover); }
+.big-ring .fill { stroke: url(#ring-grad); stroke-dasharray: 534; stroke-dashoffset: 534; transition: stroke-dashoffset 1s var(--ease-out); filter: drop-shadow(0 4px 10px color-mix(in srgb, var(--brand-1) 45%, transparent)); }
+.big-ring .num { position: absolute; inset: 0; display: grid; place-items: center; text-align: center; }
+.big-ring .num b { font: 650 40px/1 var(--display); letter-spacing: -0.03em; font-variant-numeric: tabular-nums; }
+.big-ring .num small { display: block; color: var(--ink-3); font-size: var(--t-sm); margin-top: 4px; }
+.big-ring::after { content: ""; position: absolute; inset: -14px; border-radius: 50%; background: radial-gradient(circle, color-mix(in srgb, var(--brand-2) 22%, transparent), transparent 65%); z-index: -1; animation: breathe 4s ease-in-out infinite; }
+.phases { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; min-width: 260px; }
+.phases li { display: flex; align-items: center; gap: 12px; color: var(--ink-3); transition: color .4s; }
+.phases .pi { width: 24px; height: 24px; border-radius: 50%; border: 1.5px solid var(--line-strong); display: grid; place-items: center; flex: none; transition: background .4s, border-color .4s; }
+.phases .pi svg { width: 12px; height: 12px; stroke: #fff; stroke-width: 3; opacity: 0; stroke-dasharray: 20; stroke-dashoffset: 20; }
+.phases li.now { color: var(--ink); font-weight: 600; }
+.phases li.now .pi { border-color: var(--accent) transparent var(--accent) var(--accent); animation: spin 1s linear infinite; }
+.phases li.done { color: var(--ink-2); }
+.phases li.done .pi { background: linear-gradient(135deg, var(--brand-1), var(--brand-2)); border-color: transparent; }
+.phases li.done .pi svg { opacity: 1; animation: draw .45s var(--ease-out) forwards; }
+.detail { margin-top: 22px; color: var(--ink-2); min-height: 20px; }
+
+/* done: a check that draws itself and a little burst */
+.done-mark { position: relative; width: 120px; height: 120px; margin: 0 0 26px; }
+.done-mark .disc { position: absolute; inset: 0; border-radius: 50%; background: linear-gradient(135deg, var(--brand-1), var(--brand-2)); box-shadow: 0 18px 40px color-mix(in srgb, var(--brand-1) 45%, transparent); animation: pop-in .8s var(--spring) both; }
+.done-mark svg { position: absolute; inset: 0; width: 120px; height: 120px; stroke: #fff; stroke-width: 7; stroke-dasharray: 80; stroke-dashoffset: 80; animation: draw-80 .6s var(--ease-out) .35s forwards; }
+@keyframes draw-80 { to { stroke-dashoffset: 0; } }
+.burst i { position: absolute; left: 50%; top: 50%; width: 8px; height: 8px; margin: -4px; border-radius: 2px; background: var(--c); opacity: 0; animation: burst 1s var(--ease-out) .3s forwards; }
+@keyframes burst { 0% { opacity: 1; transform: rotate(var(--a)) translateY(0) scale(1); } 100% { opacity: 0; transform: rotate(var(--a)) translateY(-96px) scale(.4) rotate(160deg); } }
+
+.foot { margin-top: 30px; display: flex; gap: 8px; align-items: center; }
+.err { margin-top: 20px; padding: 14px 16px; border-radius: var(--r-lg); background: color-mix(in srgb, var(--bad) 12%, transparent); border: 1px solid color-mix(in srgb, var(--bad) 30%, transparent); color: var(--bad); max-width: 560px; animation: shake .45s var(--ease); }
+@keyframes shake { 20%, 60% { transform: translateX(-6px); } 40%, 80% { transform: translateX(6px); } }
+
+/* ---------- small windows ---------- */
+@media (max-width: 760px) {
+ .wizard { grid-template-columns: 1fr; inset: 0; }
+ .rail { display: none; }
+ .pane { padding: 32px 22px; border-radius: 0; }
+ .features, .facts { grid-template-columns: 1fr; }
+}
+@media (max-width: 640px) {
+ .well { inset: 0; border-radius: 0; }
+ .lib-head { flex-direction: column; align-items: flex-start; padding: 20px 18px 4px; }
+ .shelf { padding: 16px 10px 32px; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); }
+ .brand h1 { font-size: var(--t-lg); }
+}
+@media (prefers-reduced-motion: reduce) {
+ *, *::before, *::after { animation: none !important; transition: none !important; }
+}
+
+/* Thin overlay scrollbars, like Windows 11's own. */
+::-webkit-scrollbar { width: 10px; height: 10px; }
+::-webkit-scrollbar-track { background: transparent; }
+::-webkit-scrollbar-thumb { background: transparent; border: 3px solid transparent; border-radius: 999px; background-clip: padding-box; }
+:hover::-webkit-scrollbar-thumb { background-color: color-mix(in srgb, var(--ink) 22%, transparent); }
+::-webkit-scrollbar-button { display: none; }
+
+/* glass card used by the setup wizard's two panes */
+.glass-pane { border-radius: var(--r-xl); background: var(--well); border: 1px solid var(--line); backdrop-filter: blur(24px) saturate(1.3); box-shadow: 0 1px 0 rgba(255,255,255,.4) inset; }
+.pane.glass-pane { animation: well-in .7s var(--ease-out) .08s both; }
+
+.fallback-icon { display: grid; place-items: center; border-radius: 22px; color: #fff; font: 650 36px/1 var(--display); background: linear-gradient(145deg, var(--brand-1), var(--brand-2)); }
+
+/* the last tile invites the next install */
+.tile.add-tile { color: var(--ink-3); }
+.add-tile .add-box {
+ width: 92px; height: 92px; border-radius: 22px; display: grid; place-items: center;
+ border: 2px dashed var(--line-strong); transition: border-color .3s, color .3s, background .3s, transform .4s var(--spring);
+}
+.add-tile .add-box svg { width: 30px; height: 30px; stroke-width: 2; transition: transform .5s var(--spring); }
+.add-tile:hover { color: var(--accent); }
+.add-tile:hover .add-box { border-color: var(--accent); background: var(--accent-soft); transform: translateY(-4px); }
+.add-tile:hover .add-box svg { transform: rotate(90deg); }
+.add-tile::before { display: none; }
+
+/* Apps that ship with macOS, offered in the shelf until added. */
+.builtin-icon { width: 92px; height: 92px; filter: drop-shadow(0 8px 12px rgba(0,0,0,.18)) saturate(.85); opacity: .9; transition: opacity .3s, filter .3s, transform .5s var(--spring); }
+.suggest-tile .tile-note { color: var(--ink-3); }
+.suggest-tile:hover .builtin-icon { opacity: 1; filter: drop-shadow(0 10px 16px rgba(0,0,0,.22)); transform: translateY(-4px); }
+.suggest-tile:hover .tile-note { color: var(--accent); }
+
+/* Setup: the license notice right above Install (pressing Install is the acceptance). */
+.pane .fine { margin: -10px 0 0; color: var(--ink-3); font-size: var(--t-sm, 12.5px); line-height: 1.5; max-width: 60ch; }
+.pane .fine a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }
+.pane .fine a:hover { color: var(--accent); }
diff --git a/src/wsm-manager/wsm.png b/src/wsm-manager/wsm.png
new file mode 100644
index 0000000..4c32998
Binary files /dev/null and b/src/wsm-manager/wsm.png differ
diff --git a/src/wsm-proto/CMakeLists.txt b/src/wsm-proto/CMakeLists.txt
new file mode 100644
index 0000000..05cace6
--- /dev/null
+++ b/src/wsm-proto/CMakeLists.txt
@@ -0,0 +1,4 @@
+add_library(wsm-proto INTERFACE)
+target_include_directories(wsm-proto INTERFACE
+ "${CMAKE_CURRENT_SOURCE_DIR}/include"
+)
diff --git a/src/wsm-proto/include/wsm/protocol.hpp b/src/wsm-proto/include/wsm/protocol.hpp
new file mode 100644
index 0000000..5b85888
--- /dev/null
+++ b/src/wsm-proto/include/wsm/protocol.hpp
@@ -0,0 +1,187 @@
+#pragma once
+#include <cstdint>
+#include <cstddef>
+#include <string>
+#include <vector>
+
+namespace wsm::proto {
+
+constexpr uint32_t WSM_MAGIC = 0x57534D31; // "WSM1"
+constexpr uint16_t WSM_PROTO_VERSION = 1;
+
+// Channel identifiers over virtio-serial / vsock / TCP bridge
+enum class Channel : uint16_t {
+ Control = 1, // Lifecycle, heartbeat, guest info, process launch/kill
+ Window = 2, // Rootless window metadata, geometry, framebuffers, input events
+ Clipboard = 3, // Bidirectional text/HTML/RTF/image/file clipboard sync
+ Audio = 4, // CoreAudio <-> WASAPI low-latency PCM frames
+ GpuControl = 5, // Paravirtualized GPU surface / IOSurface handle sharing
+ FileSync = 6, // Shared folder notifications & file association open requests
+};
+
+enum class MsgType : uint16_t {
+ // Control channel
+ Hello = 0x0001,
+ HelloAck = 0x0002,
+ Ping = 0x0003,
+ Pong = 0x0004,
+ LaunchApp = 0x0010,
+ LaunchAppReply = 0x0011,
+ TerminateApp = 0x0012,
+ ListApps = 0x0013,
+ ListAppsReply = 0x0014,
+ ProcessExited = 0x0015,
+ GuestShutdown = 0x0016,
+ GuestStats = 0x0017,
+
+ // Window channel (guest -> host)
+ WindowCreated = 0x0100,
+ WindowDestroyed = 0x0101,
+ WindowUpdated = 0x0102, // title, bounds, flags, z-order, icon
+ WindowFrame = 0x0103, // BGRA32 or shared handle frame update
+ WindowIcon = 0x0104,
+ MenuUpdated = 0x0105,
+
+ // Window channel (host -> guest)
+ InputKey = 0x0120,
+ InputMouseMove = 0x0121,
+ InputMouseButton = 0x0122,
+ InputScroll = 0x0123,
+ InputText = 0x0124,
+ WindowAction = 0x0125, // move, resize, focus, minimize, maximize, close
+
+ // Clipboard channel
+ ClipboardOffer = 0x0200,
+ ClipboardData = 0x0201,
+ ClipboardRequest = 0x0202,
+
+ // Audio channel
+ AudioConfig = 0x0300,
+ AudioPcmOut = 0x0301,
+ AudioPcmIn = 0x0302,
+ AudioVolume = 0x0303,
+
+ // Error / Diagnostics
+ Error = 0xFFFF,
+};
+
+#pragma pack(push, 1)
+struct FrameHeader {
+ uint32_t magic = WSM_MAGIC;
+ uint16_t version = WSM_PROTO_VERSION;
+ uint16_t channel = 0;
+ uint16_t type = 0;
+ uint16_t flags = 0;
+ uint32_t seq = 0;
+ uint32_t payload_size = 0;
+};
+
+struct WindowRect {
+ int32_t x = 0;
+ int32_t y = 0;
+ int32_t width = 0;
+ int32_t height = 0;
+};
+
+struct WindowDescriptor {
+ uint64_t window_id = 0;
+ uint64_t parent_window_id = 0;
+ uint32_t pid = 0;
+ uint32_t style_flags = 0; // bit0=resizable, bit1=closable, bit2=minimizable, bit3=popup, bit4=modal, bit5=transparent
+ WindowRect bounds{};
+ float scale_factor = 1.0f;
+ uint8_t visible = 1;
+ uint8_t focused = 0;
+ uint16_t title_len = 0;
+ // Followed by UTF-8 title bytes of length title_len
+};
+
+struct WindowFrameHeader {
+ uint64_t window_id = 0;
+ uint32_t width = 0;
+ uint32_t height = 0;
+ uint32_t stride = 0;
+ uint32_t pixel_format = 0; // 0 = BGRA8888, 1 = RGBA8888, 2 = SharedNtHandle
+ uint32_t dirty_x = 0;
+ uint32_t dirty_y = 0;
+ uint32_t dirty_w = 0;
+ uint32_t dirty_h = 0;
+ uint64_t iosurface_id = 0;
+ uint64_t timestamp_us = 0;
+ // Followed by pixel bytes or 64-bit shared handle info
+};
+
+struct InputKeyEvent {
+ uint64_t window_id = 0;
+ uint32_t vk_code = 0;
+ uint32_t mac_keycode = 0;
+ uint32_t modifiers = 0; // bit0=Shift, bit1=Ctrl, bit2=Alt/Opt, bit3=Cmd/Win
+ uint8_t pressed = 0;
+ uint8_t repeat = 0;
+ uint16_t reserved = 0;
+};
+
+struct InputMouseMoveEvent {
+ uint64_t window_id = 0;
+ int32_t x = 0;
+ int32_t y = 0;
+ uint32_t modifiers = 0;
+};
+
+struct InputMouseButtonEvent {
+ uint64_t window_id = 0;
+ int32_t x = 0;
+ int32_t y = 0;
+ uint8_t button = 0; // 0=left, 1=right, 2=middle, 3=x1, 4=x2
+ uint8_t pressed = 0;
+ uint16_t clicks = 1;
+ uint32_t modifiers = 0;
+};
+
+struct InputScrollEvent {
+ uint64_t window_id = 0;
+ int32_t x = 0;
+ int32_t y = 0;
+ float delta_x = 0.0f;
+ float delta_y = 0.0f;
+ uint32_t modifiers = 0;
+};
+
+enum class WindowActionKind : uint32_t {
+ Move = 1,
+ Resize = 2,
+ Focus = 3,
+ Minimize = 4,
+ Maximize = 5,
+ Restore = 6,
+ Close = 7,
+};
+
+struct WindowActionEvent {
+ uint64_t window_id = 0;
+ uint32_t action = 0;
+ int32_t arg1 = 0;
+ int32_t arg2 = 0;
+ int32_t arg3 = 0;
+ int32_t arg4 = 0;
+};
+
+struct AudioPcmHeader {
+ uint32_t sample_rate = 48000;
+ uint16_t channels = 2;
+ uint16_t bits_per_sample = 32; // float32
+ uint32_t frame_count = 0;
+ uint64_t timestamp_us = 0;
+};
+#pragma pack(pop)
+
+// Max single frame payload: 64 MiB (bounds checking against untrusted guest input)
+constexpr uint32_t WSM_MAX_PAYLOAD_SIZE = 64u * 1024u * 1024u;
+
+inline bool validate_header(const FrameHeader& hdr) noexcept {
+ return hdr.magic == WSM_MAGIC &&
+ hdr.version == WSM_PROTO_VERSION &&
+ hdr.payload_size <= WSM_MAX_PAYLOAD_SIZE;
+}
+
+} // namespace wsm::proto
diff --git a/src/wsm-runtime/CMakeLists.txt b/src/wsm-runtime/CMakeLists.txt
new file mode 100644
index 0000000..205efd6
--- /dev/null
+++ b/src/wsm-runtime/CMakeLists.txt
@@ -0,0 +1,69 @@
+add_library(wsm-appman STATIC
+ src/app_registry.cpp
+ src/guest_bridge.cpp
+ src/shell_integration.cpp
+ src/provisioner.cpp
+ src/runtime_host.cpp
+ src/window_streamer.cpp
+ src/app_installer.cpp
+ src/webdav_server.cpp
+)
+target_include_directories(wsm-appman PUBLIC
+ "${CMAKE_CURRENT_SOURCE_DIR}/include"
+)
+target_link_libraries(wsm-appman PUBLIC
+ wsm-core
+ wsm-compositor
+ wsm-services
+ ws2_32
+ ole32
+ shell32
+ advapi32
+ psapi
+)
+
+add_executable(wsm src/wsm_cli.cpp)
+target_link_libraries(wsm PRIVATE
+ wsm-core
+ wsm-compositor
+ wsm-services
+ wsm-appman
+)
+
+add_executable(wsmd src/wsmd.cpp)
+target_link_libraries(wsmd PRIVATE
+ wsm-core
+ wsm-compositor
+ wsm-services
+ wsm-appman
+ ws2_32
+)
+
+add_executable(WsmManager WIN32 src/wsm_manager_launcher.cpp)
+target_include_directories(WsmManager PRIVATE
+ "F:/WSM/third_party/webview2/build/native/include"
+)
+target_link_libraries(WsmManager PRIVATE
+ wsm-core
+ "F:/WSM/third_party/webview2/build/native/x64/WebView2LoaderStatic.lib"
+ dwmapi
+ ole32
+ ws2_32
+ shell32
+)
+
+# Target of every Mac app's Start menu / Desktop shortcut (GUI subsystem: no console flash).
+add_executable(wsmlaunch WIN32 src/wsm_app_launcher.cpp)
+target_link_libraries(wsmlaunch PRIVATE ws2_32 shell32)
+
+# App icon: compiled with rc.exe directly (the Ninja RC rule passes "-I dir", which this rc rejects).
+set(WSM_RES "${CMAKE_CURRENT_BINARY_DIR}/wsm.res")
+add_custom_command(OUTPUT "${WSM_RES}"
+ COMMAND "${CMAKE_RC_COMPILER}" /nologo /fo "${WSM_RES}" "${CMAKE_CURRENT_SOURCE_DIR}/wsm.rc"
+ DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/wsm.rc" "${CMAKE_SOURCE_DIR}/assets/brand/wsm.ico"
+ WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
+add_custom_target(wsm_icon_res DEPENDS "${WSM_RES}")
+foreach(t wsm wsmd WsmManager wsmlaunch)
+ add_dependencies(${t} wsm_icon_res)
+ target_link_options(${t} PRIVATE "${WSM_RES}")
+endforeach()
diff --git a/src/wsm-runtime/include/wsm/app_installer.hpp b/src/wsm-runtime/include/wsm/app_installer.hpp
new file mode 100644
index 0000000..7c41310
--- /dev/null
+++ b/src/wsm-runtime/include/wsm/app_installer.hpp
@@ -0,0 +1,74 @@
+#pragma once
+// AppInstaller — "drop a Mac app on WSM and it's installed".
+//
+// Takes any .dmg, .pkg/.mpkg, .zip, .tar(.gz) or .app on Windows and:
+// 1. wakes the macOS runtime (boot, or resume when paused),
+// 2. copies the file into it over SSH,
+// 3. installs it *inside* macOS (wsm-install.sh: hdiutil/ditto/installer), which keeps code
+// signatures, symlinks and extended attributes intact,
+// 4. fetches each installed app's icon as Finder renders it and converts it to .ico,
+// 5. records the app, puts it on the Start menu and Desktop, and opens it.
+// One job runs at a time; status() reports its stage for the UI and the Explorer handler.
+#include "wsm/app_registry.hpp"
+#include "wsm/runtime_host.hpp"
+#include "wsm/window_streamer.hpp"
+
+#include <atomic>
+#include <cstdint>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <vector>
+
+namespace wsm::runtime {
+
+struct InstallStatus {
+ uint64_t job = 0;
+ bool running = false;
+ bool done = false;
+ bool ok = false;
+ bool opens = true; // the app is opened afterwards (false: added quietly)
+ int percent = 0;
+ std::string stage; // user-facing, e.g. "Installing CotEditor"
+ std::string error; // user-facing on failure
+ std::string file; // what is being installed
+ std::vector<std::string> app_ids, app_names;
+};
+
+class AppInstaller {
+public:
+ AppInstaller(std::string wsm_root, RuntimeHost& runtime, WindowStreamer& streamer,
+ AppRegistry& registry, std::mutex& registry_mu);
+ ~AppInstaller();
+
+ // Starts installing `path`. Returns the job id, or 0 when another install is running.
+ uint64_t start(const std::string& path, bool open_after = true);
+ // Adds an app that ships with macOS (e.g. "/Applications/Safari.app") to the library:
+ // nothing is copied, only its icon, Start menu entry and Desktop shortcut are made.
+ uint64_t start_builtin(const std::string& guest_app_path, bool open_after = true);
+ InstallStatus status() const;
+ bool busy() const { return busy_.load(); }
+ std::string status_json() const;
+
+private:
+ void run(uint64_t job, std::string path, bool open_after, bool builtin);
+ void set(int percent, const std::string& stage);
+ void fail(const std::string& error);
+
+ std::string root_;
+ RuntimeHost& runtime_;
+ WindowStreamer& streamer_;
+ AppRegistry& registry_;
+ std::mutex& registry_mu_;
+
+ mutable std::mutex mu_;
+ InstallStatus st_;
+ std::atomic<bool> busy_{false};
+ std::atomic<uint64_t> next_job_{1};
+ std::thread worker_;
+};
+
+// Writes a Windows .ico holding one 256x256 PNG (the format Explorer uses for large icons).
+bool png_to_ico(const std::string& png_path, const std::string& ico_path);
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/include/wsm/app_registry.hpp b/src/wsm-runtime/include/wsm/app_registry.hpp
new file mode 100644
index 0000000..6dafef2
--- /dev/null
+++ b/src/wsm-runtime/include/wsm/app_registry.hpp
@@ -0,0 +1,54 @@
+#pragma once
+#include "wsm/paths.hpp"
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace wsm::runtime {
+
+enum class BinaryArch {
+ Unknown,
+ X86_64,
+ Arm64,
+ Universal,
+};
+
+struct AppBundleInfo {
+ std::string id; // CFBundleIdentifier or derived slug
+ std::string name; // CFBundleDisplayName / CFBundleName
+ std::string version; // CFBundleShortVersionString
+ std::string min_macos; // LSMinimumSystemVersion
+ std::string bundle_path; // Path to .app or Mach-O binary
+ std::string executable_path; // Resolved Contents/MacOS/<exec>
+ std::string icon_path; // Resolved Contents/Resources/<icon>.icns
+ BinaryArch arch = BinaryArch::Unknown;
+ bool requires_arm64_translation = false;
+};
+
+// Parses Mach-O thin (MH_MAGIC_64) and fat (FAT_MAGIC / FAT_CIGAM) headers
+BinaryArch inspect_macho_architecture(const std::string& file_path);
+std::string arch_to_string(BinaryArch a);
+
+// Inspects a macOS .app bundle (Info.plist + Mach-O binary) or standalone Mach-O executable
+bool inspect_macos_app(const std::string& path, AppBundleInfo& out, std::string& err);
+
+class AppRegistry {
+public:
+ explicit AppRegistry(std::string storage_file = wsm::core::resolve_wsm_root() + "\\runtime\\config\\apps.json");
+
+ bool load();
+ bool save() const;
+
+ bool register_app(const std::string& path, AppBundleInfo& out, std::string& err);
+ bool remove_app(const std::string& id);
+ void upsert(const AppBundleInfo& info); // add or replace by id (call save() after)
+ std::vector<AppBundleInfo> list() const;
+ bool find(const std::string& id, AppBundleInfo& out) const;
+ std::string to_json() const;
+
+private:
+ std::string storage_file_;
+ std::vector<AppBundleInfo> apps_;
+};
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/include/wsm/guest_bridge.hpp b/src/wsm-runtime/include/wsm/guest_bridge.hpp
new file mode 100644
index 0000000..d06233e
--- /dev/null
+++ b/src/wsm-runtime/include/wsm/guest_bridge.hpp
@@ -0,0 +1,56 @@
+#pragma once
+#include "wsm/protocol.hpp"
+#include "wsm/compositor.hpp"
+#include "wsm/services.hpp"
+
+#include <atomic>
+#include <cstdint>
+#include <mutex>
+#include <string>
+#include <thread>
+
+namespace wsm::runtime {
+
+// Connects Windows host wsmd.exe to macOS guest wsm-guest-agent over TCP (virtio-net/vsock).
+// Dispatches guest WindowUpdated/WindowFrame/Clipboard/Audio frames to host subsystems
+// and forwards host input/clipboard events back to the guest.
+class GuestBridge {
+public:
+ GuestBridge(compositor::RootlessCompositor& compositor,
+ services::ClipboardBridge& clipboard,
+ services::WasapiAudioBridge& audio);
+ ~GuestBridge();
+
+ GuestBridge(const GuestBridge&) = delete;
+ GuestBridge& operator=(const GuestBridge&) = delete;
+
+ void start(const std::string& host = "127.0.0.1", uint16_t port = 4445);
+ void stop();
+
+ bool is_connected() const noexcept { return connected_.load(); }
+ uint64_t frames_received() const noexcept { return frames_rx_.load(); }
+ uint64_t events_sent() const noexcept { return events_tx_.load(); }
+
+ bool send_frame(proto::Channel ch, proto::MsgType type, const void* payload, uint32_t size);
+
+private:
+ void io_loop();
+
+ compositor::RootlessCompositor& compositor_;
+ services::ClipboardBridge& clipboard_;
+ services::WasapiAudioBridge& audio_;
+
+ std::string host_ = "127.0.0.1";
+ uint16_t port_ = 4445;
+ std::atomic<bool> running_{false};
+ std::atomic<bool> connected_{false};
+ std::atomic<uint64_t> frames_rx_{0};
+ std::atomic<uint64_t> events_tx_{0};
+ std::atomic<uint32_t> seq_{1};
+
+ std::mutex send_mutex_;
+ uintptr_t sock_ = static_cast<uintptr_t>(~0ULL);
+ std::thread thread_;
+};
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/include/wsm/provisioner.hpp b/src/wsm-runtime/include/wsm/provisioner.hpp
new file mode 100644
index 0000000..aa041f0
--- /dev/null
+++ b/src/wsm-runtime/include/wsm/provisioner.hpp
@@ -0,0 +1,103 @@
+#pragma once
+// Automated, invisible macOS provisioning for WSM.
+//
+// Apple offers no unattended install for non-Apple hardware, so the provisioner drives macOS
+// Recovery itself over QMP (keyboard + screendump) inside a runtime whose window is parked
+// off-screen. The user only ever sees the setup wizard's progress.
+//
+// Install target selection is by device identity, never by path guessing: the system disk is
+// erased by identifier with a fixed volume name, and `installer`/`startosinstall` only run
+// after `diskutil info` confirms that name is a mounted, writable volume. (Guessing
+// /Volumes/Untitled is what made the old script install "at base path /" and fail with
+// "can't create the folder //Install.XXXX".)
+#include <atomic>
+#include <cstdint>
+#include <functional>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <vector>
+
+namespace wsm::runtime {
+
+enum class ProvState {
+ Idle, Preparing, Downloading, CreatingRuntime, BootingRecovery, PreparingDisk,
+ CopyingInstaller, Installing, FirstBoot, Finishing, Ready, Failed
+};
+
+struct ProvSnapshot {
+ ProvState state = ProvState::Idle;
+ double percent = 0;
+ std::string title, detail, error;
+};
+
+struct ProvPlan {
+ bool reuse_installer = false;
+ std::string installer_path, macos_name = "macOS Tahoe";
+ uint64_t download_bytes = 0, disk_needed_bytes = 0, free_bytes = 0;
+ std::string drive;
+ int minutes = 45;
+};
+
+class Provisioner {
+public:
+ explicit Provisioner(std::string wsm_root);
+ ~Provisioner();
+
+ ProvPlan plan() const; // discovery: reusable installers, space, sizes
+ bool begin(bool license_accepted, std::string& err);
+ ProvSnapshot snapshot() const;
+ std::string to_json() const;
+ bool busy() const { return running_.load(); }
+ // Runs only the first-boot setup (WSM's user, SSH key, auto-login, sudo) against an installed
+ // runtime, in the background: repairs a runtime WSM can't log in to, and tests the step on a
+ // copy (vm/ssh_port of that copy). Progress and result come through snapshot().
+ bool repair_first_boot(const std::string& vm, int ssh_port, std::string& err);
+
+private:
+ void run();
+ void set(ProvState s, double pct, const std::string& title, const std::string& detail = {});
+ void fail(const std::string& why);
+ bool step_create_runtime();
+ bool step_boot_recovery();
+ bool step_install();
+ bool step_wait_first_boot();
+ bool step_first_boot_setup(); // user, SSH, auto-login, sudo: from the disk's own Recovery
+ bool step_finish();
+
+ // first-boot setup helpers
+ bool make_payload(std::string& dir, std::string& err);
+ bool boot_into_recovery(); // OpenCore Cmd+R hotkey, then Terminal (Shift+Cmd+T)
+ bool restart_vm(); // power off, wait for QEMU to be gone, start (retried)
+ struct SetupLock { // runtime\config\setup-running while setup drives the VM
+ explicit SetupLock(const std::string& root);
+ ~SetupLock();
+ std::string path_;
+ };
+ bool ssh_ok(uint32_t timeout_ms) const;
+ bool click_blue_button(); // Apple's first-run "Get Started"/"Continue", if on screen
+
+ // helpers
+ int reims(const std::string& args, std::string* out = nullptr) const;
+ bool vm_running() const;
+ bool screen_dump(std::vector<uint8_t>& rgb, int& w, int& h) const;
+ double screen_fraction_nonblack() const;
+ bool open_recovery_terminal();
+ bool terminal_visible() const; // Terminal's window is on the guest screen
+ bool guest_shell(const std::string& cmd); // types into Recovery Terminal
+ bool wait_for_marker(const std::string& marker_file, int timeout_s, const std::function<void(int)>& tick);
+ uint64_t disk_bytes() const;
+ void log(const std::string& line) const;
+
+ std::string root_, vm_dir_, reims_ctl_, qemu_img_, share_dir_;
+ std::string vm_ = "wsm-default";
+ int ssh_port_ = 2222;
+ mutable std::mutex mu_;
+ mutable ProvSnapshot snap_;
+ std::atomic<bool> running_{false};
+ std::thread worker_;
+};
+
+const char* prov_state_name(ProvState s);
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/include/wsm/runtime_host.hpp b/src/wsm-runtime/include/wsm/runtime_host.hpp
new file mode 100644
index 0000000..afe0c32
--- /dev/null
+++ b/src/wsm-runtime/include/wsm/runtime_host.hpp
@@ -0,0 +1,62 @@
+#pragma once
+// RuntimeHost — the single owner of the macOS runtime's lifecycle.
+//
+// Every start and stop goes through reims-ctl, so there is exactly one definition of the
+// runtime (vm.toml) and one QEMU command line. (The older VmManager built a second, different
+// command line; two launch paths let a second runtime start on the same disk.)
+//
+// Fast app start. A full RAM snapshot (QMP savevm/loadvm) is not available: the GPU device,
+// reims-graphics-pci, registers a migration blocker because its state lives in the host GPU.
+// So WSM keeps the runtime warm instead:
+// - Running: an app is open.
+// - Paused (QMP "stop"): no app open; vCPUs stop, so no CPU is used. Resume is instant.
+// - Off: after a longer idle period, the runtime shuts down cleanly and its memory is freed.
+// The next app start boots macOS (cold start).
+#include <cstdint>
+#include <mutex>
+#include <string>
+
+namespace wsm::runtime {
+
+enum class RtState { NotInstalled, Off, Starting, Running, Paused, Stopping };
+
+struct RtStatus {
+ RtState state = RtState::Off;
+ uint32_t pid = 0;
+ uint64_t working_set_mb = 0;
+};
+
+class RuntimeHost {
+public:
+ explicit RuntimeHost(std::string wsm_root, std::string vm = "wsm-default");
+
+ RtStatus status() const;
+ // Running afterwards (resumes a paused runtime or boots one). Returns ms taken.
+ bool ensure_running(std::string& err, uint64_t* took_ms = nullptr);
+ bool pause(std::string& err);
+ bool resume(std::string& err);
+ bool shutdown(std::string& err); // graceful, falls back to power-off after timeout
+ // Runtime stopped: rewrites its disk image without the free space (and compressed), which
+ // takes a 128 GB-sized image of ~25 GB of data down to roughly 10 GB. Minutes; keeps the
+ // old file until the new one is complete and checked.
+ bool compact(std::string& err, uint64_t* before_bytes = nullptr, uint64_t* after_bytes = nullptr);
+ // WSM's QEMU profile for this runtime ("1", "2-trial", "2", "2-ahci"; see apply_profile).
+ std::string profile_state() const;
+ // After a boot on a trial profile: keep it when macOS came up, else go back to SATA.
+ void confirm_disk_profile(bool came_up);
+ bool qmp(const std::string& json, std::string& resp, uint32_t timeout_ms = 3000) const;
+ std::string vm_dir() const { return vm_dir_; }
+ std::string qmp_socket() const { return vm_dir_ + "\\qmp.sock"; }
+
+private:
+ int reims(const std::string& args, std::string* out = nullptr) const;
+ void apply_profile(); // once per runtime: WSM's QEMU options (VNC frames, zero detection)
+ uint32_t pid() const;
+
+ std::string root_, vm_, vm_dir_, reims_ctl_;
+ mutable std::mutex mu_;
+};
+
+const char* rt_state_name(RtState s);
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/include/wsm/shell_integration.hpp b/src/wsm-runtime/include/wsm/shell_integration.hpp
new file mode 100644
index 0000000..819348e
--- /dev/null
+++ b/src/wsm-runtime/include/wsm/shell_integration.hpp
@@ -0,0 +1,24 @@
+#pragma once
+#include <string>
+
+namespace wsm::runtime {
+
+// Extracts the highest-resolution PNG chunk (ic10/ic09/ic08/ic07) from an Apple .icns file
+// and writes a valid Windows .ico file (PNG-in-ICO format supported since Windows Vista).
+bool convert_icns_to_ico(const std::string& icns_path, const std::string& ico_out_path);
+
+// Adds an installed Mac app to the Start menu (top level) and the Desktop with its own icon and
+// taskbar identity. The shortcuts run wsmlaunch.exe <bundle_id>, which wakes the runtime if needed.
+bool create_app_start_menu_shortcut(const std::string& app_name,
+ const std::string& bundle_id,
+ const std::string& ico_path,
+ std::string& out_lnk_path);
+
+// Registers HKCU\Software\Classes file associations for .dmg, .pkg, and .app
+// so double-clicking them in Windows Explorer invokes `wsm.exe open "%1"` (no admin required).
+// Removes the Start menu and Desktop shortcuts of an app.
+void remove_app_shortcuts(const std::string& app_name);
+
+bool register_windows_shell_associations(const std::string& wsm_exe_path, std::string& err);
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/include/wsm/webdav_server.hpp b/src/wsm-runtime/include/wsm/webdav_server.hpp
new file mode 100644
index 0000000..6523843
--- /dev/null
+++ b/src/wsm-runtime/include/wsm/webdav_server.hpp
@@ -0,0 +1,40 @@
+#pragma once
+// WebDavServer — the Windows drives, shared with the macOS runtime (like WSL's /mnt/c).
+//
+// A small WebDAV (class 1+2) server on 127.0.0.1. Inside the runtime QEMU's user network reaches
+// the host's loopback at 10.0.2.2, and macOS mounts the share with its own mount_webdav at
+// ~/Windows: ~/Windows/C is C:\, ~/Windows/D is D:\ ... Every request must carry a random token
+// as the first path segment; nothing else on the PC can guess it. macOS's AppleDouble ("._*")
+// and .DS_Store files are accepted and dropped, so they never litter the Windows drives.
+#include <atomic>
+#include <cstdint>
+#include <string>
+#include <thread>
+
+namespace wsm::runtime {
+
+class WebDavServer {
+public:
+ WebDavServer(uint16_t port, std::string token);
+ ~WebDavServer();
+
+ bool start(std::string& err);
+ void stop();
+ void set_enabled(bool on) { enabled_.store(on); } // off: every request gets 403
+ bool enabled() const { return enabled_.load(); }
+ // What macOS mounts.
+ std::string guest_url() const { return "http://10.0.2.2:" + std::to_string(port_) + "/" + token_ + "/"; }
+
+private:
+ void accept_loop();
+ void serve(uintptr_t sock);
+
+ uint16_t port_;
+ std::string token_;
+ uintptr_t listen_ = ~static_cast<uintptr_t>(0);
+ std::atomic<bool> running_{false}, enabled_{true};
+ std::atomic<int> clients_{0};
+ std::thread acceptor_;
+};
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/include/wsm/window_streamer.hpp b/src/wsm-runtime/include/wsm/window_streamer.hpp
new file mode 100644
index 0000000..0804579
--- /dev/null
+++ b/src/wsm-runtime/include/wsm/window_streamer.hpp
@@ -0,0 +1,188 @@
+#pragma once
+// WindowStreamer — puts each macOS app window on the Windows desktop as its own window.
+//
+// macOS runs as a hidden runtime. Nothing is compiled or installed inside it for this:
+// - Window list: one long-lived SSH session runs a small JXA script in the runtime that
+// reports on-screen app windows (CGWindowListCopyWindowInfo: bounds need no TCC grant).
+// - Pixels: the runtime's framebuffer is read over QMP (screendump) and each window's
+// rectangle is cropped out and presented in its own DirectComposition window.
+// - Input: Windows mouse/keyboard events on those windows are mapped back to runtime
+// screen coordinates and injected over QMP (input-send-event), so the app receives them
+// as normal HID input. Windows Ctrl is sent as Command, so Ctrl+C/V/S work as expected.
+// Limits (honest): frame rate is bounded by screendump (~5-10 fps); windows that overlap
+// inside the runtime show whatever is on top there; the macOS menu bar is not mirrored yet.
+#include "wsm/compositor.hpp"
+#include "wsm/protocol.hpp"
+
+#include <atomic>
+#include <condition_variable>
+#include <cstdint>
+#include <deque>
+#include <functional>
+#include <map>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <vector>
+
+namespace wsm::runtime {
+
+class WindowStreamer {
+public:
+ WindowStreamer(compositor::RootlessCompositor& compositor, std::string wsm_root);
+ ~WindowStreamer();
+
+ void start();
+ void stop();
+
+ // Returns true when the event belonged to a streamed window (and was forwarded).
+ bool on_mouse_move(const proto::InputMouseMoveEvent& ev);
+ bool on_mouse_button(const proto::InputMouseButtonEvent& ev);
+ bool on_scroll(const proto::InputScrollEvent& ev);
+ bool on_key(const proto::InputKeyEvent& ev);
+ void debug_key(const std::string& qcode); // diagnostics: a key press through the real input path
+ bool on_window_action(const proto::WindowActionEvent& ev);
+ // Empty title-bar area (uniform pixels near the top) drags natively on Windows.
+ int hit_caption(uint64_t window_id, int x, int y);
+
+ // Opens an app inside the runtime by bundle identifier (falls back to a path/name).
+ bool launch_app(const std::string& bundle_id_or_path, std::string& err);
+ // Runs a shell command inside the runtime as the runtime user. Returns exit code.
+ int guest_exec(const std::string& command, std::string* out = nullptr, uint32_t timeout_ms = 60000,
+ const std::function<void(const std::string&)>& on_line = {}) const;
+ // Runs a short command over the persistent shell session (fast path). Returns exit code.
+ int quick(const std::string& command, std::string* out = nullptr, uint32_t timeout_ms = 15000);
+ // Copies a file into / out of the runtime user's home (remote paths relative to $HOME).
+ bool copy_to_guest(const std::string& local, const std::string& remote_rel) const;
+ bool copy_from_guest(const std::string& remote, const std::string& local) const;
+ // Shared clipboard (text). on_guest_clipboard is called when a Mac app copies text;
+ // set_guest_clipboard puts Windows' clipboard text on the Mac pasteboard.
+ void set_on_guest_clipboard(std::function<void(const std::string&)> f) { on_guest_clipboard_ = std::move(f); }
+ void set_guest_clipboard(const std::string& text);
+ // The Windows drives in macOS at ~/Windows (WebDavServer's URL); mounted each time the runtime
+ // comes up, unmounted when switched off. Safe to call any time.
+ void set_share(const std::string& url, bool on);
+ void mount_share();
+ // Reconnects the window watcher now (after the runtime resumes).
+ void kick();
+
+ bool watching() const noexcept { return watching_.load(); }
+ // Monotonic ms (steady_clock) of the last command, copy or input sent to the runtime.
+ int64_t last_activity_ms() const noexcept { return last_activity_ms_.load(); }
+ size_t window_count() const;
+ std::string debug_json() const; // runtime windows as the streamer sees them (diagnostics)
+ bool debug_dump_frame(uint32_t wid, const std::string& path); // last presented frame, .bmp
+ uint64_t frames_presented() const noexcept { return frames_.load(); }
+
+ static constexpr uint64_t kIdBase = 1ull << 40;
+ // QEMU's VNC server for the runtime's screen (localhost only): -vnc 127.0.0.1:15
+ static constexpr uint16_t kVncPort = 5915;
+ bool vnc_live() const noexcept { return vnc_live_.load(); }
+
+private:
+ struct GuestWin {
+ uint32_t wid = 0;
+ uint32_t pid = 0;
+ int layer = 0;
+ int x = 0, y = 0, w = 0, h = 0; // runtime screen points
+ std::string owner, bundle;
+ uint64_t last_hash = 0;
+ int64_t changed_ms = 0; // last geometry change in the runtime
+ int z = 0; // stacking order in the runtime (higher = in front)
+ int min_x = 49, min_y = 26; // macOS minimize ("yellow") button centre, client px
+ int zoom_x = 72, zoom_y = 26; // zoom ("green") button centre
+ bool created = false;
+ int missing = 0;
+ int covered_rects = -1; // diagnostics: rects masked in its last rendered frame // consecutive window lists without it (activation blips)
+ };
+
+ void watch_loop();
+ void capture_loop();
+ void vnc_loop();
+ void input_loop();
+ void apply_window_list(const std::string& line);
+ void sync_host_window(GuestWin& g);
+ bool lookup(uint64_t host_id, GuestWin& out) const;
+ void queue_events(const std::string& events_json);
+ void queue_abs(int gx, int gy);
+ std::string ssh_base() const;
+ int scp(const std::string& from, const std::string& to, uint32_t timeout_ms) const;
+
+ compositor::RootlessCompositor& compositor_;
+ std::string root_;
+ std::string ppm_path_;
+
+ std::atomic<bool> running_{false};
+ std::atomic<bool> watching_{false};
+ std::atomic<uint64_t> frames_{0};
+ std::atomic<int64_t> last_input_ms_{0};
+ // Diagnostics (ms): last screendump's duration, and input -> first presented change.
+ std::atomic<int64_t> diag_dump_ms_{0}, diag_lat_ms_{0}, diag_cycle_ms_{0};
+ std::atomic<bool> diag_wait_{false};
+public:
+ std::string latency_json() const {
+ return "{\"dump_ms\":" + std::to_string(diag_dump_ms_.load()) + ",\"input_to_frame_ms\":" + std::to_string(diag_lat_ms_.load()) + ",\"cycle_ms\":" + std::to_string(diag_cycle_ms_.load()) + "}";
+ }
+private:
+ mutable std::atomic<int64_t> last_activity_ms_{0};
+
+ mutable std::mutex mu_;
+ std::map<uint32_t, GuestWin> wins_;
+ std::map<uint32_t, std::pair<int, int>> pid_offset_; // host = runtime + offset
+ std::map<uint32_t, int64_t> pid_empty_since_; // app lost its last window at
+ std::atomic<bool> kick_watch_{false};
+ std::atomic<int64_t> stack_changed_ms_{0}; // last change of which windows are where in the stack
+ std::string stack_sig_; // (guarded by mu_)
+ std::string trim_report_; // last output of the runtime profile script
+ // Once, after setup: macOS is up and answering, so the installer is no longer needed.
+ // Deletes its leftovers inside macOS and the installer images on Windows (~19 GB).
+ void post_setup_cleanup();
+ // Instant start: recently used apps are read into macOS's memory, and the most recent one
+ // is started hidden, so opening it only has to show a window that already exists.
+ void prewarm_apps();
+ void remember_recent(const std::string& bundle_id);
+ std::mutex recent_mu_;
+ std::string hidden_bundle_; // started hidden by prewarm_apps; its windows stay
+ int64_t hidden_until_ms_ = 0; // off Windows until the user opens it (guarded by mu_)
+ std::function<void(const std::string&)> on_guest_clipboard_;
+ std::mutex share_mu_;
+ std::string share_url_;
+ bool share_on_ = false;
+ std::mutex clip_mu_;
+ std::string last_clip_;
+ std::mutex sh_mu_;
+ void* sh_proc_ = nullptr; // persistent ssh + zsh -s
+ void* sh_in_ = nullptr;
+ void* sh_out_ = nullptr;
+ std::atomic<int64_t> last_raise_ms_{0};
+ std::atomic<uint32_t> last_raise_pid_{0};
+ int screen_w_ = 1920, screen_h_ = 1080; // runtime screen, points
+
+ struct Frame { int w = 0, h = 0; std::vector<uint8_t> px; };
+ std::mutex frame_mu_;
+ std::map<uint32_t, Frame> frames_by_win_; // last presented pixels (BGRA) per window
+
+ // VNC framebuffer (BGRX) and the area changed since the capture loop last looked.
+ std::atomic<bool> vnc_live_{false};
+ uintptr_t vnc_sock_ = static_cast<uintptr_t>(~0ULL);
+ std::mutex fb_mu_;
+ // Writes to the VNC socket come from two threads (update requests, input pokes).
+ std::mutex vnc_write_mu_;
+ std::vector<uint8_t> fb_;
+ int fb_w_ = 0, fb_h_ = 0;
+ int dirty_x0_ = 0x7fffffff, dirty_y0_ = 0x7fffffff, dirty_x1_ = 0, dirty_y1_ = 0;
+ std::thread vnc_thread_;
+
+ std::mutex cap_mu_;
+ std::condition_variable cap_cv_;
+ std::atomic<bool> cap_kick_{false};
+
+ std::mutex in_mu_;
+ std::condition_variable in_cv_;
+ std::deque<std::string> in_q_;
+
+ void* watch_proc_ = nullptr; // HANDLE of the ssh process
+ std::thread watch_thread_, capture_thread_, input_thread_;
+};
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/src/app_installer.cpp b/src/wsm-runtime/src/app_installer.cpp
new file mode 100644
index 0000000..d5ed4cf
--- /dev/null
+++ b/src/wsm-runtime/src/app_installer.cpp
@@ -0,0 +1,297 @@
+#include "wsm/app_installer.hpp"
+#include "wsm/shell_integration.hpp"
+
+#include <windows.h>
+
+#include <cctype>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <sstream>
+
+namespace wsm::runtime {
+
+namespace fs = std::filesystem;
+
+namespace {
+
+std::string jesc(const std::string& s) {
+ std::string o;
+ for (char c : s) {
+ switch (c) {
+ case '"': o += "\\\""; break;
+ case '\\': o += "\\\\"; break;
+ case '\n': o += "\\n"; break;
+ case '\r': break;
+ case '\t': o += "\\t"; break;
+ default:
+ if (static_cast<unsigned char>(c) < 0x20) break;
+ o += c;
+ }
+ }
+ return o;
+}
+
+std::string lower(std::string s) {
+ for (auto& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
+ return s;
+}
+
+// A file name that's safe on the remote command line; keeps compound extensions (.tar.gz).
+std::string safe_remote_name(const std::string& name) {
+ std::string o;
+ for (char c : name) o += (std::isalnum(static_cast<unsigned char>(c)) || c == '.' || c == '-' || c == '_') ? c : '_';
+ return o.empty() ? std::string("package") : o;
+}
+
+std::vector<std::string> split(const std::string& s, char d) {
+ std::vector<std::string> out;
+ std::string cur;
+ for (char c : s) {
+ if (c == d) { out.push_back(cur); cur.clear(); }
+ else cur += c;
+ }
+ out.push_back(cur);
+ return out;
+}
+
+int run_hidden(const std::string& cmdline, DWORD timeout_ms) {
+ STARTUPINFOA si{}; si.cb = sizeof(si);
+ si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;
+ PROCESS_INFORMATION pi{};
+ std::string cl = cmdline;
+ if (!CreateProcessA(nullptr, cl.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) return -1;
+ WaitForSingleObject(pi.hProcess, timeout_ms);
+ DWORD code = 255;
+ GetExitCodeProcess(pi.hProcess, &code);
+ CloseHandle(pi.hThread); CloseHandle(pi.hProcess);
+ return static_cast<int>(code);
+}
+
+} // namespace
+
+bool png_to_ico(const std::string& png_path, const std::string& ico_path) {
+ std::ifstream in(png_path, std::ios::binary);
+ if (!in) return false;
+ std::string png((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
+ if (png.size() < 24 || png.compare(1, 3, "PNG") != 0) return false;
+ auto u32 = [](uint32_t v, std::string& o) { for (int i = 0; i < 4; ++i) o += static_cast<char>((v >> (8 * i)) & 0xFF); };
+ auto u16 = [](uint16_t v, std::string& o) { o += static_cast<char>(v & 0xFF); o += static_cast<char>(v >> 8); };
+ std::string ico;
+ u16(0, ico); u16(1, ico); u16(1, ico); // ICONDIR: reserved, type=icon, count
+ ico += '\0'; ico += '\0'; ico += '\0'; ico += '\0'; // 256x256 (0 = 256), no palette, reserved
+ u16(1, ico); u16(32, ico); // planes, bpp
+ u32(static_cast<uint32_t>(png.size()), ico);
+ u32(22, ico); // data offset
+ ico += png;
+ fs::create_directories(fs::path(ico_path).parent_path());
+ std::ofstream out(ico_path, std::ios::binary | std::ios::trunc);
+ out.write(ico.data(), static_cast<std::streamsize>(ico.size()));
+ return static_cast<bool>(out);
+}
+
+AppInstaller::AppInstaller(std::string wsm_root, RuntimeHost& runtime, WindowStreamer& streamer,
+ AppRegistry& registry, std::mutex& registry_mu)
+ : root_(std::move(wsm_root)), runtime_(runtime), streamer_(streamer), registry_(registry), registry_mu_(registry_mu) {}
+
+AppInstaller::~AppInstaller() {
+ if (worker_.joinable()) worker_.join();
+}
+
+uint64_t AppInstaller::start(const std::string& raw, bool open_after) {
+ if (busy_.exchange(true)) return 0;
+ std::string path = raw;
+ while (!path.empty() && (path.back() == '\r' || path.back() == '\n' || path.back() == ' ' || path.back() == '"')) path.pop_back();
+ while (!path.empty() && (path.front() == '"' || path.front() == ' ')) path.erase(0, 1);
+ uint64_t job = next_job_.fetch_add(1);
+ {
+ std::lock_guard<std::mutex> lk(mu_);
+ st_ = InstallStatus{};
+ st_.job = job;
+ st_.running = true;
+ st_.file = fs::path(path).filename().string();
+ st_.stage = "Getting ready";
+ st_.opens = open_after;
+ }
+ if (worker_.joinable()) worker_.join();
+ worker_ = std::thread(&AppInstaller::run, this, job, path, open_after, false);
+ return job;
+}
+
+uint64_t AppInstaller::start_builtin(const std::string& a, bool open_after) {
+ // Only plain paths of apps that ship with macOS; it ends up inside a quoted shell command.
+ bool ok = a.size() > 18 && a.compare(a.size() - 4, 4, ".app") == 0 && a.find("..") == std::string::npos &&
+ (a.rfind("/Applications/", 0) == 0 || a.rfind("/System/Applications/", 0) == 0);
+ for (char c : a)
+ // Inside a single-quoted shell argument: anything but a quote or a control character is
+ // literal there; App Store names use + & ( ) , too.
+ if (!(std::isalnum(static_cast<unsigned char>(c)) || std::strchr("/ .-_+&(),", c)) || c == 0) ok = false;
+ if (!ok || busy_.exchange(true)) return 0;
+ uint64_t job = next_job_.fetch_add(1);
+ {
+ std::lock_guard<std::mutex> lk(mu_);
+ st_ = InstallStatus{};
+ st_.job = job;
+ st_.running = true;
+ st_.file = fs::path(a).filename().string();
+ st_.stage = "Getting ready";
+ st_.opens = open_after;
+ }
+ if (worker_.joinable()) worker_.join();
+ worker_ = std::thread(&AppInstaller::run, this, job, a, open_after, true);
+ return job;
+}
+
+InstallStatus AppInstaller::status() const {
+ std::lock_guard<std::mutex> lk(mu_);
+ return st_;
+}
+
+std::string AppInstaller::status_json() const {
+ InstallStatus s = status();
+ std::ostringstream o;
+ o << "{\"job\":" << s.job << ",\"running\":" << (s.running ? "true" : "false")
+ << ",\"done\":" << (s.done ? "true" : "false") << ",\"ok\":" << (s.ok ? "true" : "false")
+ << ",\"percent\":" << s.percent << ",\"stage\":\"" << jesc(s.stage) << "\",\"error\":\"" << jesc(s.error)
+ << "\",\"file\":\"" << jesc(s.file) << "\",\"opens\":" << (s.opens ? "true" : "false") << ",\"apps\":[";
+ for (size_t i = 0; i < s.app_ids.size(); ++i)
+ o << (i ? "," : "") << "{\"id\":\"" << jesc(s.app_ids[i]) << "\",\"name\":\"" << jesc(s.app_names[i]) << "\"}";
+ o << "]}";
+ return o.str();
+}
+
+void AppInstaller::set(int percent, const std::string& stage) {
+ std::lock_guard<std::mutex> lk(mu_);
+ st_.percent = percent;
+ st_.stage = stage;
+}
+
+void AppInstaller::fail(const std::string& error) {
+ std::lock_guard<std::mutex> lk(mu_);
+ st_.running = false;
+ st_.done = true;
+ st_.ok = false;
+ st_.error = error;
+}
+
+void AppInstaller::run(uint64_t, std::string path, bool open_after, bool builtin) {
+ struct Release { std::atomic<bool>& b; ~Release() { b.store(false); } } release{busy_};
+ std::error_code ec;
+ if (!builtin && (path.empty() || !fs::exists(path, ec))) { fail("That file couldn't be found. It may have been moved."); return; }
+
+ // 1. Runtime awake and reachable.
+ set(5, "Starting the macOS runtime");
+ std::string err;
+ const bool was_running = runtime_.status().state == RtState::Running;
+ if (!runtime_.ensure_running(err)) { fail("The macOS runtime couldn't start: " + err); return; }
+ if (!was_running || !streamer_.watching()) streamer_.kick();
+ bool up = false;
+ for (int i = 0; i < 120 && !up; ++i) {
+ up = streamer_.guest_exec("true", nullptr, 15000) == 0;
+ if (!up) Sleep(2000);
+ }
+ if (!up) { fail("The macOS runtime didn't respond. Try again in a minute."); return; }
+
+ const std::string inbox = "Library/Caches/WSM/inbox";
+ streamer_.guest_exec("mkdir -p ~/" + inbox + " ~/Library/Caches/WSM/icons", nullptr, 20000);
+ if (!streamer_.copy_to_guest(root_ + "\\src\\wsm-guest\\agent\\wsm-install.sh", "Library/Caches/WSM/wsm-install.sh")) {
+ fail("The installer couldn't be copied into the macOS runtime."); return;
+ }
+ std::string install_cmd;
+ if (builtin) {
+ // Ships with macOS: nothing to copy, the script only reports it (path vetted in start_builtin).
+ set(45, "Adding " + fs::path(path).stem().string());
+ install_cmd = "zsh ~/Library/Caches/WSM/wsm-install.sh --builtin '" + path + "' ~/Library/Caches/WSM/icons";
+ } else {
+ // 2. Copy in. A folder (.app on Windows) is packed first; it can't be copied as one file.
+ set(20, "Copying " + fs::path(path).filename().string());
+ std::string local = path, remote_name;
+ std::string tmp_pack;
+ if (fs::is_directory(path, ec)) {
+ fs::path p(path);
+ tmp_pack = root_ + "\\cache\\tmp\\wsm-pack-" + std::to_string(GetTickCount64()) + ".tar";
+ std::string cmd = "C:\\Windows\\System32\\tar.exe -cf \"" + tmp_pack + "\" -C \"" + p.parent_path().string() +
+ "\" \"" + p.filename().string() + "\"";
+ if (run_hidden(cmd, 10 * 60 * 1000) != 0) { fail("The app folder couldn't be packed for copying."); return; }
+ local = tmp_pack;
+ remote_name = safe_remote_name(p.filename().string()) + ".tar";
+ } else {
+ remote_name = safe_remote_name(fs::path(path).filename().string());
+ }
+ bool copied = streamer_.copy_to_guest(local, inbox + "/" + remote_name);
+ if (!tmp_pack.empty()) fs::remove(tmp_pack, ec);
+ if (!copied) { fail("The file couldn't be copied into the macOS runtime."); return; }
+
+ // 3. Install inside macOS.
+ set(45, "Installing");
+ install_cmd = "zsh ~/Library/Caches/WSM/wsm-install.sh ~/" + inbox + "/" + remote_name + " ~/Library/Caches/WSM/icons; "
+ "rc=$?; rm -f ~/" + inbox + "/" + remote_name + "; exit $rc";
+ }
+ struct Found { std::string id, name, ver, app, png; };
+ std::vector<Found> found;
+ std::string last_error;
+ int rc = streamer_.guest_exec(
+ install_cmd,
+ nullptr, 30 * 60 * 1000,
+ [&](const std::string& line) {
+ if (line.rfind("STAGE ", 0) == 0) set(60, line.substr(6));
+ else if (line.rfind("ERROR ", 0) == 0) last_error = line.substr(6);
+ else if (line.rfind("APP ", 0) == 0) {
+ auto f = split(line.substr(4), '\t');
+ if (f.size() >= 5 && !f[0].empty()) found.push_back({f[0], f[1], f[2], f[3], f[4]});
+ }
+ });
+ if (rc != 0 || found.empty()) {
+ std::string why = last_error.empty() ? "the installer stopped unexpectedly" : last_error;
+ fail(std::string(builtin ? "Couldn't add " : "Couldn't install ") + fs::path(path).stem().string() + ": " + why + ".");
+ return;
+ }
+
+ // 4. Icons, registry, shortcuts.
+ set(85, "Adding to Start menu and Desktop");
+ std::vector<std::string> ids, names;
+ for (auto& a : found) {
+ std::string png = root_ + "\\runtime\\apps\\icons\\" + a.id + ".png";
+ std::string ico = root_ + "\\runtime\\apps\\icons\\" + a.id + ".ico";
+ fs::create_directories(root_ + "\\runtime\\apps\\icons", ec);
+ if (streamer_.copy_from_guest(a.png, png)) png_to_ico(png, ico);
+
+ AppBundleInfo info;
+ info.id = a.id;
+ info.name = a.name;
+ info.version = a.ver;
+ info.bundle_path = a.app; // path inside the runtime
+ info.executable_path = a.app;
+ info.icon_path = fs::exists(png, ec) ? png : std::string();
+ info.arch = BinaryArch::Universal;
+ {
+ std::lock_guard<std::mutex> lk(registry_mu_);
+ registry_.upsert(info);
+ registry_.save();
+ }
+ std::string lnk;
+ create_app_start_menu_shortcut(a.name, a.id, fs::exists(ico, ec) ? ico : std::string(), lnk);
+ ids.push_back(a.id);
+ names.push_back(a.name);
+ }
+ {
+ std::lock_guard<std::mutex> lk(mu_);
+ st_.app_ids = ids;
+ st_.app_names = names;
+ }
+
+ // 5. Open it.
+ if (open_after) {
+ set(95, "Opening " + names.front());
+ std::string lerr;
+ streamer_.launch_app(ids.front(), lerr);
+ }
+ std::lock_guard<std::mutex> lk(mu_);
+ st_.percent = 100;
+ st_.stage = names.size() == 1 ? (names.front() + (builtin ? " is ready" : " is installed")) : (std::to_string(names.size()) + " apps installed");
+ st_.running = false;
+ st_.done = true;
+ st_.ok = true;
+}
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/src/app_registry.cpp b/src/wsm-runtime/src/app_registry.cpp
new file mode 100644
index 0000000..076bc68
--- /dev/null
+++ b/src/wsm-runtime/src/app_registry.cpp
@@ -0,0 +1,449 @@
+#include "wsm/paths.hpp"
+#include "wsm/app_registry.hpp"
+
+#include <windows.h>
+
+#include <algorithm>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <sstream>
+
+namespace wsm::runtime {
+
+namespace {
+
+uint32_t bswap32(uint32_t v) noexcept {
+ return ((v & 0x000000FFu) << 24) |
+ ((v & 0x0000FF00u) << 8) |
+ ((v & 0x00FF0000u) >> 8) |
+ ((v & 0xFF000000u) >> 24);
+}
+
+std::string json_escape(const std::string& s) {
+ std::string out;
+ out.reserve(s.size() + 8);
+ for (char c : s) {
+ switch (c) {
+ case '"': out += "\\\""; break;
+ case '\\': out += "\\\\"; break;
+ case '\n': out += "\\n"; break;
+ case '\r': out += "\\r"; break;
+ default: out.push_back(c); break;
+ }
+ }
+ return out;
+}
+
+// Lightweight XML Info.plist <key>K</key><string>V</string> extractor
+std::string extract_plist_string(const std::string& xml, const std::string& key) {
+ std::string needle = "<key>" + key + "</key>";
+ auto pos = xml.find(needle);
+ if (pos == std::string::npos) return {};
+ auto s_open = xml.find("<string>", pos + needle.size());
+ if (s_open == std::string::npos) return {};
+ auto s_close = xml.find("</string>", s_open + 8);
+ if (s_close == std::string::npos) return {};
+ return xml.substr(s_open + 8, s_close - (s_open + 8));
+}
+
+} // namespace
+
+BinaryArch inspect_macho_architecture(const std::string& file_path) {
+ std::ifstream f(file_path, std::ios::binary);
+ if (!f) return BinaryArch::Unknown;
+
+ uint32_t magic = 0;
+ f.read(reinterpret_cast<char*>(&magic), sizeof(magic));
+ if (!f) return BinaryArch::Unknown;
+
+ constexpr uint32_t CPU_TYPE_X86_64 = 0x01000007u;
+ constexpr uint32_t CPU_TYPE_ARM64 = 0x0100000Cu;
+
+ // MH_MAGIC_64 (little-endian on x86_64/arm64)
+ if (magic == 0xFEEDFACFu) {
+ uint32_t cputype = 0;
+ f.read(reinterpret_cast<char*>(&cputype), sizeof(cputype));
+ if (cputype == CPU_TYPE_X86_64) return BinaryArch::X86_64;
+ if (cputype == CPU_TYPE_ARM64) return BinaryArch::Arm64;
+ return BinaryArch::Unknown;
+ }
+
+ // FAT_MAGIC / FAT_CIGAM (Universal binary)
+ if (magic == 0xCAFEBABEu || magic == 0xBEBAFECA) {
+ bool swap = (magic == 0xBEBAFECA);
+ uint32_t nfat = 0;
+ f.read(reinterpret_cast<char*>(&nfat), sizeof(nfat));
+ if (swap) nfat = bswap32(nfat);
+ if (nfat > 16) return BinaryArch::Unknown;
+
+ bool has_x64 = false;
+ bool has_arm64 = false;
+ for (uint32_t i = 0; i < nfat; ++i) {
+ uint32_t arch_hdr[5] = {};
+ f.read(reinterpret_cast<char*>(arch_hdr), sizeof(arch_hdr));
+ if (!f) break;
+ uint32_t cputype = swap ? bswap32(arch_hdr[0]) : arch_hdr[0];
+ if (cputype == CPU_TYPE_X86_64) has_x64 = true;
+ if (cputype == CPU_TYPE_ARM64) has_arm64 = true;
+ }
+ if (has_x64 && has_arm64) return BinaryArch::Universal;
+ if (has_x64) return BinaryArch::X86_64;
+ if (has_arm64) return BinaryArch::Arm64;
+ }
+ return BinaryArch::Unknown;
+}
+
+std::string arch_to_string(BinaryArch a) {
+ switch (a) {
+ case BinaryArch::X86_64: return "x86_64";
+ case BinaryArch::Arm64: return "arm64";
+ case BinaryArch::Universal: return "universal (x86_64+arm64)";
+ default: return "unknown";
+ }
+}
+
+bool inspect_macos_app(const std::string& path, AppBundleInfo& out, std::string& err) {
+ namespace fs = std::filesystem;
+ if (!fs::exists(path)) {
+ err = "Path does not exist: " + path;
+ return false;
+ }
+
+ out = AppBundleInfo{};
+ out.bundle_path = fs::weakly_canonical(path).string();
+
+ if (fs::is_directory(path)) {
+ fs::path plist = fs::path(path) / "Contents" / "Info.plist";
+ if (!fs::exists(plist)) {
+ err = "Not a valid .app bundle (missing Contents/Info.plist)";
+ return false;
+ }
+ std::ifstream pf(plist, std::ios::binary);
+ std::ostringstream ss;
+ ss << pf.rdbuf();
+ std::string xml = ss.str();
+
+ out.id = extract_plist_string(xml, "CFBundleIdentifier");
+ out.name = extract_plist_string(xml, "CFBundleDisplayName");
+ if (out.name.empty()) out.name = extract_plist_string(xml, "CFBundleName");
+ if (out.name.empty()) out.name = fs::path(path).stem().string();
+ if (out.id.empty()) out.id = "local.wsm." + out.name;
+
+ out.version = extract_plist_string(xml, "CFBundleShortVersionString");
+ out.min_macos = extract_plist_string(xml, "LSMinimumSystemVersion");
+
+ std::string exec_name = extract_plist_string(xml, "CFBundleExecutable");
+ if (!exec_name.empty()) {
+ fs::path exec_p = fs::path(path) / "Contents" / "MacOS" / exec_name;
+ out.executable_path = exec_p.string();
+ out.arch = inspect_macho_architecture(out.executable_path);
+ }
+
+ // Fallback for binary Info.plist (bplist00, used by Safari & Apple system apps):
+ // scan Contents/MacOS/* directly for the primary Mach-O executable and Contents/Resources/*.icns for icon
+ if (out.executable_path.empty() || out.arch == BinaryArch::Unknown) {
+ std::error_code ec;
+ fs::path macos_dir = fs::path(path) / "Contents" / "MacOS";
+ if (fs::is_directory(macos_dir, ec)) {
+ for (const auto& entry : fs::directory_iterator(macos_dir, ec)) {
+ if (!entry.is_regular_file(ec)) continue;
+ BinaryArch a = inspect_macho_architecture(entry.path().string());
+ if (a != BinaryArch::Unknown) {
+ out.executable_path = entry.path().string();
+ out.arch = a;
+ break;
+ }
+ }
+ }
+ }
+
+ std::string icon_name = extract_plist_string(xml, "CFBundleIconFile");
+ if (!icon_name.empty()) {
+ if (icon_name.find('.') == std::string::npos) icon_name += ".icns";
+ fs::path icon_p = fs::path(path) / "Contents" / "Resources" / icon_name;
+ if (fs::exists(icon_p)) out.icon_path = icon_p.string();
+ }
+ if (out.icon_path.empty()) {
+ std::error_code ec;
+ fs::path res_dir = fs::path(path) / "Contents" / "Resources";
+ if (fs::is_directory(res_dir, ec)) {
+ for (const auto& entry : fs::directory_iterator(res_dir, ec)) {
+ if (entry.is_regular_file(ec) && entry.path().extension() == ".icns") {
+ out.icon_path = entry.path().string();
+ break;
+ }
+ }
+ }
+ }
+ } else {
+ out.name = fs::path(path).filename().string();
+ out.id = "local.macho." + out.name;
+ out.executable_path = out.bundle_path;
+ out.arch = inspect_macho_architecture(out.executable_path);
+ if (out.arch == BinaryArch::Unknown) {
+ err = "File is not a recognized Mach-O executable or .app bundle.";
+ return false;
+ }
+ }
+
+ out.requires_arm64_translation = (out.arch == BinaryArch::Arm64);
+ return true;
+}
+
+AppRegistry::AppRegistry(std::string storage_file) : storage_file_(std::move(storage_file)) {}
+
+bool AppRegistry::load() {
+ apps_.clear();
+ std::ifstream f(storage_file_);
+ if (!f) return true;
+ // Simple line-oriented reload for our structured JSON entries
+ std::string line;
+ AppBundleInfo cur{};
+ bool in_obj = false;
+ auto extract_val = [](const std::string& l) -> std::string {
+ auto colon = l.find(':');
+ if (colon == std::string::npos) return {};
+ auto q1 = l.find('"', colon + 1);
+ if (q1 == std::string::npos) return {};
+ auto q2 = l.rfind('"');
+ if (q2 == std::string::npos || q2 <= q1) return {};
+ return l.substr(q1 + 1, q2 - q1 - 1);
+ };
+ while (std::getline(f, line)) {
+ if (line.find('{') != std::string::npos) { cur = AppBundleInfo{}; in_obj = true; }
+ else if (line.find('}') != std::string::npos && in_obj) {
+ if (!cur.id.empty()) apps_.push_back(cur);
+ in_obj = false;
+ } else if (in_obj) {
+ if (line.find("\"id\"") != std::string::npos) cur.id = extract_val(line);
+ else if (line.find("\"name\"") != std::string::npos) cur.name = extract_val(line);
+ else if (line.find("\"version\"") != std::string::npos) cur.version = extract_val(line);
+ else if (line.find("\"min_macos\"") != std::string::npos) cur.min_macos = extract_val(line);
+ else if (line.find("\"bundle_path\"") != std::string::npos) cur.bundle_path = extract_val(line);
+ else if (line.find("\"executable_path\"") != std::string::npos) cur.executable_path = extract_val(line);
+ else if (line.find("\"arch\"") != std::string::npos) {
+ std::string a = extract_val(line);
+ if (a == "x86_64") cur.arch = BinaryArch::X86_64;
+ else if (a == "arm64") cur.arch = BinaryArch::Arm64;
+ else if (a.find("universal") != std::string::npos) cur.arch = BinaryArch::Universal;
+ cur.requires_arm64_translation = (cur.arch == BinaryArch::Arm64);
+ }
+ }
+ }
+ return true;
+}
+
+bool AppRegistry::save() const {
+ std::filesystem::create_directories(std::filesystem::path(storage_file_).parent_path());
+ std::ofstream f(storage_file_, std::ios::trunc);
+ if (!f) return false;
+ f << to_json();
+ return true;
+}
+
+bool AppRegistry::register_app(const std::string& raw_path, AppBundleInfo& out, std::string& err) {
+ namespace fs = std::filesystem;
+ // Trim whitespace and optional surrounding quotes from pasted Windows Explorer paths
+ std::string path = raw_path;
+ while (!path.empty() && (path.front() == ' ' || path.front() == '"' || path.front() == '\r' || path.front() == '\n')) path.erase(path.begin());
+ while (!path.empty() && (path.back() == ' ' || path.back() == '"' || path.back() == '\r' || path.back() == '\n')) path.pop_back();
+
+ if (!fs::exists(path)) {
+ err = "File or directory does not exist: " + path;
+ return false;
+ }
+
+ std::string target_path = path;
+
+ auto run_7z = [](const std::string& archive, const fs::path& out_dir) -> int {
+ std::error_code ec;
+ fs::create_directories(out_dir, ec);
+ // Use CreateProcessA directly (never std::system / cmd.exe quote mangling!)
+ std::string cmd = "\"C:\\Program Files\\7-Zip\\7z.exe\" x -y -o\"" + out_dir.string() + "\" \"" + archive + "\"";
+ STARTUPINFOA si{};
+ si.cb = sizeof(si);
+ PROCESS_INFORMATION pi{};
+ if (!CreateProcessA("C:\\Program Files\\7-Zip\\7z.exe", cmd.data(),
+ nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) {
+ return 99;
+ }
+ WaitForSingleObject(pi.hProcess, 120000);
+ DWORD exit_code = 0;
+ GetExitCodeProcess(pi.hProcess, &exit_code);
+ CloseHandle(pi.hThread);
+ CloseHandle(pi.hProcess);
+ return static_cast<int>(exit_code);
+ };
+
+ // Finds a genuine top-level .app bundle (valid Info.plist + MacOS executable, ignoring nested Frameworks/*.app helpers and __MACOSX)
+ auto find_best_app_bundle = [](const fs::path& root, std::string& found_path) -> bool {
+ std::error_code ec;
+ size_t best_depth = 9999;
+ bool found = false;
+ for (const auto& entry : fs::recursive_directory_iterator(root, fs::directory_options::skip_permission_denied, ec)) {
+ if (!entry.is_directory(ec)) continue;
+ if (entry.path().extension() != ".app") continue;
+ std::string s = entry.path().string();
+ if (s.find("__MACOSX") != std::string::npos) continue;
+ if (s.find("\\Contents\\Frameworks\\") != std::string::npos) continue;
+ if (s.find("\\Contents\\Library\\") != std::string::npos) continue;
+ if (!fs::exists(entry.path() / "Contents" / "Info.plist", ec)) continue;
+ if (!fs::exists(entry.path() / "Contents" / "MacOS", ec)) continue;
+
+ // Prefer shallowest genuine .app bundle
+ size_t depth = std::distance(entry.path().begin(), entry.path().end());
+ if (depth < best_depth) {
+ best_depth = depth;
+ found_path = s;
+ found = true;
+ }
+ }
+ return found;
+ };
+
+ // Content-based + extension-based detection of extractable containers
+ auto is_nested_container = [](const fs::path& p) -> bool {
+ std::string name = p.filename().string();
+ std::string ext = p.extension().string();
+ std::transform(ext.begin(), ext.end(), ext.begin(),
+ [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
+ if (name == "Payload" || name == "Payload~") return true;
+ if (ext == ".apfs" || ext == ".hfs" || ext == ".hfsx" || ext == ".dmg" ||
+ ext == ".pkg" || ext == ".mpkg" || ext == ".xar" || ext == ".cpio" ||
+ ext == ".zip" || ext == ".tar" || ext == ".gz" || ext == ".tgz" ||
+ ext == ".xz" || ext == ".bz2" || ext == ".img" || ext == ".iso") {
+ return true;
+ }
+ // Sniff magic bytes for extensionless containers (e.g. XAR, GZIP, ZIP, APFS/HFS)
+ std::ifstream f(p, std::ios::binary);
+ if (!f) return false;
+ uint8_t mag[8] = {};
+ f.read(reinterpret_cast<char*>(mag), sizeof(mag));
+ if (f.gcount() >= 4) {
+ if (std::memcmp(mag, "xar!", 4) == 0) return true;
+ if (mag[0] == 0x1F && mag[1] == 0x8B) return true; // gzip
+ if (mag[0] == 'P' && mag[1] == 'K' && mag[2] == 0x03 && mag[3] == 0x04) return true; // zip
+ if (std::memcmp(mag, "070701", 6) == 0 || std::memcmp(mag, "070707", 6) == 0) return true; // cpio
+ }
+ return false;
+ };
+
+ if (fs::is_regular_file(path)) {
+ // Also stage original package into W:\Applications (F:\WSM\fs\Applications) for native guest-side installation
+ std::error_code copy_ec;
+ fs::create_directories(wsm::core::resolve_wsm_root() + "\\fs\\Applications", copy_ec);
+ fs::copy_file(path, fs::path(wsm::core::resolve_wsm_root() + "\\fs\\Applications") / fs::path(path).filename(),
+ fs::copy_options::overwrite_existing, copy_ec);
+
+ if (is_nested_container(path)) {
+ std::string stem = fs::path(path).stem().string();
+ fs::path extract_dir = fs::path(wsm::core::resolve_wsm_root() + "\\runtime\\apps\\extracted") / stem;
+ std::error_code ec;
+ fs::remove_all(extract_dir, ec);
+
+ // Stage 0: outer container (.dmg, .pkg, .zip, .tar.gz, etc.)
+ // Note: 7-Zip returns code 2 if macOS symlinks inside APFS/HFS cannot be created without Developer Mode,
+ // even though all regular files and Info.plist/Mach-O binaries extracted cleanly.
+ int rc = run_7z(path, extract_dir);
+ if (rc == 99) {
+ err = "7-Zip executable not found at C:\\Program Files\\7-Zip\\7z.exe";
+ return false;
+ }
+ if (rc >= 2 && fs::is_empty(extract_dir, ec)) {
+ err = "Failed to extract archive with 7-Zip (code " + std::to_string(rc) + ")";
+ return false;
+ }
+
+ bool found_app = find_best_app_bundle(extract_dir, target_path);
+
+ // Multi-stage recursive unpacking (handles UDIF DMG -> 4.apfs / HFS+ -> .app,
+ // DMG -> .pkg -> Payload -> gzip -> cpio -> .app, and .tar.gz -> .tar -> .app)
+ std::vector<fs::path> processed;
+ for (int depth = 0; depth < 4 && !found_app; ++depth) {
+ std::vector<fs::path> next_containers;
+ for (const auto& entry : fs::recursive_directory_iterator(extract_dir, fs::directory_options::skip_permission_denied, ec)) {
+ if (!entry.is_regular_file(ec)) continue;
+ if (std::find(processed.begin(), processed.end(), entry.path()) != processed.end()) continue;
+ if (is_nested_container(entry.path())) {
+ next_containers.push_back(entry.path());
+ }
+ }
+ if (next_containers.empty()) break;
+
+ for (size_t i = 0; i < next_containers.size() && !found_app; ++i) {
+ processed.push_back(next_containers[i]);
+ fs::path stage_dir = extract_dir / ("_stage_" + std::to_string(depth) + "_" + std::to_string(i));
+ run_7z(next_containers[i].string(), stage_dir);
+ if (find_best_app_bundle(stage_dir, target_path)) {
+ found_app = true;
+ break;
+ }
+ }
+ }
+
+ if (!found_app) {
+ err = "No valid macOS .app bundle found inside extracted package (staged original in W:\\Applications for native macOS installation).";
+ return false;
+ }
+ }
+ }
+
+ if (!inspect_macos_app(target_path, out, err)) return false;
+ apps_.erase(std::remove_if(apps_.begin(), apps_.end(),
+ [&](const AppBundleInfo& a) { return a.id == out.id; }),
+ apps_.end());
+ apps_.push_back(out);
+ return save();
+}
+
+bool AppRegistry::remove_app(const std::string& id) {
+ auto prev = apps_.size();
+ apps_.erase(std::remove_if(apps_.begin(), apps_.end(),
+ [&](const AppBundleInfo& a) { return a.id == id; }),
+ apps_.end());
+ if (apps_.size() == prev) return false;
+ return save();
+}
+
+std::vector<AppBundleInfo> AppRegistry::list() const { return apps_; }
+
+bool AppRegistry::find(const std::string& id, AppBundleInfo& out) const {
+ for (const auto& a : apps_) {
+ if (a.id == id) { out = a; return true; }
+ }
+ return false;
+}
+
+std::string AppRegistry::to_json() const {
+ std::ostringstream oss;
+ oss << "[\n";
+ for (size_t i = 0; i < apps_.size(); ++i) {
+ const auto& a = apps_[i];
+ oss << " {\n"
+ << " \"id\": \"" << json_escape(a.id) << "\",\n"
+ << " \"name\": \"" << json_escape(a.name) << "\",\n"
+ << " \"version\": \"" << json_escape(a.version) << "\",\n"
+ << " \"min_macos\": \"" << json_escape(a.min_macos) << "\",\n"
+ << " \"bundle_path\": \"" << json_escape(a.bundle_path) << "\",\n"
+ << " \"executable_path\": \"" << json_escape(a.executable_path) << "\",\n"
+ << " \"arch\": \"" << arch_to_string(a.arch) << "\",\n"
+ << " \"requires_arm64_translation\": " << (a.requires_arm64_translation ? "true" : "false") << "\n"
+ << " }" << (i + 1 < apps_.size() ? "," : "") << "\n";
+ }
+ oss << "]\n";
+ return oss.str();
+}
+
+} // namespace wsm::runtime
+
+namespace wsm::runtime {
+
+void AppRegistry::upsert(const AppBundleInfo& info) {
+ for (auto& a : apps_) {
+ if (a.id == info.id) { a = info; return; }
+ }
+ apps_.push_back(info);
+}
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/src/guest_bridge.cpp b/src/wsm-runtime/src/guest_bridge.cpp
new file mode 100644
index 0000000..6b388f5
--- /dev/null
+++ b/src/wsm-runtime/src/guest_bridge.cpp
@@ -0,0 +1,185 @@
+#include "wsm/guest_bridge.hpp"
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+
+#include <cstring>
+#include <vector>
+
+#pragma comment(lib, "ws2_32.lib")
+
+namespace wsm::runtime {
+
+namespace {
+
+bool recv_exact(SOCKET s, void* buf, size_t len) {
+ auto* p = static_cast<uint8_t*>(buf);
+ while (len > 0) {
+ int n = recv(s, reinterpret_cast<char*>(p), static_cast<int>(len), 0);
+ if (n <= 0) return false;
+ p += n;
+ len -= static_cast<size_t>(n);
+ }
+ return true;
+}
+
+bool send_exact(SOCKET s, const void* buf, size_t len) {
+ const auto* p = static_cast<const uint8_t*>(buf);
+ while (len > 0) {
+ int n = send(s, reinterpret_cast<const char*>(p), static_cast<int>(len), 0);
+ if (n <= 0) return false;
+ p += n;
+ len -= static_cast<size_t>(n);
+ }
+ return true;
+}
+
+} // namespace
+
+GuestBridge::GuestBridge(compositor::RootlessCompositor& compositor,
+ services::ClipboardBridge& clipboard,
+ services::WasapiAudioBridge& audio)
+ : compositor_(compositor), clipboard_(clipboard), audio_(audio) {}
+
+GuestBridge::~GuestBridge() {
+ stop();
+}
+
+void GuestBridge::start(const std::string& host, uint16_t port) {
+ if (running_.exchange(true)) return;
+ host_ = host;
+ port_ = port;
+ thread_ = std::thread(&GuestBridge::io_loop, this);
+}
+
+void GuestBridge::stop() {
+ if (!running_.exchange(false)) return;
+ {
+ std::lock_guard<std::mutex> lock(send_mutex_);
+ if (sock_ != INVALID_SOCKET) {
+ closesocket(static_cast<SOCKET>(sock_));
+ sock_ = INVALID_SOCKET;
+ }
+ }
+ if (thread_.joinable()) thread_.join();
+ connected_.store(false);
+}
+
+bool GuestBridge::send_frame(proto::Channel ch, proto::MsgType type, const void* payload, uint32_t size) {
+ if (!connected_.load()) return false;
+ std::lock_guard<std::mutex> lock(send_mutex_);
+ if (sock_ == INVALID_SOCKET) return false;
+
+ proto::FrameHeader hdr{};
+ hdr.channel = static_cast<uint16_t>(ch);
+ hdr.type = static_cast<uint16_t>(type);
+ hdr.seq = seq_.fetch_add(1);
+ hdr.payload_size = size;
+
+ SOCKET s = static_cast<SOCKET>(sock_);
+ if (!send_exact(s, &hdr, sizeof(hdr))) return false;
+ if (size > 0 && payload) {
+ if (!send_exact(s, payload, size)) return false;
+ }
+ events_tx_.fetch_add(1);
+ return true;
+}
+
+void GuestBridge::io_loop() {
+ std::vector<uint8_t> payload;
+
+ while (running_.load()) {
+ SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (s == INVALID_SOCKET) {
+ Sleep(500);
+ continue;
+ }
+
+ sockaddr_in addr{};
+ addr.sin_family = AF_INET;
+ addr.sin_port = htons(port_);
+ inet_pton(AF_INET, host_.c_str(), &addr.sin_addr);
+
+ if (connect(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
+ closesocket(s);
+ Sleep(500);
+ continue;
+ }
+
+ {
+ std::lock_guard<std::mutex> lock(send_mutex_);
+ sock_ = static_cast<uintptr_t>(s);
+ }
+ connected_.store(true);
+
+ while (running_.load()) {
+ proto::FrameHeader hdr{};
+ if (!recv_exact(s, &hdr, sizeof(hdr))) break;
+ if (!proto::validate_header(hdr)) break;
+
+ payload.resize(hdr.payload_size);
+ if (hdr.payload_size > 0 && !recv_exact(s, payload.data(), hdr.payload_size)) {
+ break;
+ }
+ frames_rx_.fetch_add(1);
+
+ auto msg_type = static_cast<proto::MsgType>(hdr.type);
+ if (msg_type == proto::MsgType::WindowCreated || msg_type == proto::MsgType::WindowUpdated) {
+ if (payload.size() >= sizeof(proto::WindowDescriptor)) {
+ proto::WindowDescriptor desc{};
+ std::memcpy(&desc, payload.data(), sizeof(desc));
+ size_t max_title = payload.size() - sizeof(desc);
+ size_t tlen = (desc.title_len < max_title) ? desc.title_len : max_title;
+ std::string title(reinterpret_cast<const char*>(payload.data() + sizeof(desc)), tlen);
+ compositor_.create_or_update_window(desc, title);
+ }
+ } else if (msg_type == proto::MsgType::WindowDestroyed) {
+ if (payload.size() >= sizeof(uint64_t)) {
+ uint64_t wid = 0;
+ std::memcpy(&wid, payload.data(), sizeof(wid));
+ compositor_.destroy_window(wid);
+ }
+ } else if (msg_type == proto::MsgType::WindowFrame) {
+ if (payload.size() > sizeof(proto::WindowFrameHeader)) {
+ proto::WindowFrameHeader fh{};
+ std::memcpy(&fh, payload.data(), sizeof(fh));
+ const uint8_t* pixels = payload.data() + sizeof(fh);
+ size_t avail = payload.size() - sizeof(fh);
+ size_t needed = static_cast<size_t>(fh.stride) * fh.height;
+ if (fh.pixel_format == 0 && needed > 0 && needed <= avail) {
+ compositor_.present_bgra_frame(fh.window_id, fh.width, fh.height, fh.stride, pixels,
+ fh.dirty_x, fh.dirty_y, fh.dirty_w, fh.dirty_h);
+ }
+ }
+ } else if (msg_type == proto::MsgType::ClipboardData) {
+ if (!payload.empty()) {
+ std::string text(reinterpret_cast<const char*>(payload.data()), payload.size());
+ clipboard_.set_host_text(text);
+ }
+ } else if (msg_type == proto::MsgType::AudioPcmOut) {
+ if (payload.size() > sizeof(proto::AudioPcmHeader)) {
+ proto::AudioPcmHeader ah{};
+ std::memcpy(&ah, payload.data(), sizeof(ah));
+ const float* samples = reinterpret_cast<const float*>(payload.data() + sizeof(ah));
+ size_t avail_bytes = payload.size() - sizeof(ah);
+ size_t needed_bytes = static_cast<size_t>(ah.frame_count) * ah.channels * sizeof(float);
+ if (needed_bytes > 0 && needed_bytes <= avail_bytes) {
+ audio_.write_float_pcm(samples, ah.frame_count);
+ }
+ }
+ }
+ }
+
+ connected_.store(false);
+ {
+ std::lock_guard<std::mutex> lock(send_mutex_);
+ if (sock_ != INVALID_SOCKET) {
+ closesocket(static_cast<SOCKET>(sock_));
+ sock_ = INVALID_SOCKET;
+ }
+ }
+ }
+}
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/src/provisioner.cpp b/src/wsm-runtime/src/provisioner.cpp
new file mode 100644
index 0000000..52021e5
--- /dev/null
+++ b/src/wsm-runtime/src/provisioner.cpp
@@ -0,0 +1,739 @@
+#include "wsm/provisioner.hpp"
+#include "wsm/qmp_unix.hpp"
+
+#include <windows.h>
+
+#include <chrono>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <initializer_list>
+#include <iterator>
+#include <random>
+#include <sstream>
+
+namespace fs = std::filesystem;
+
+namespace wsm::runtime {
+namespace {
+
+std::string esc(const std::string& s) {
+ std::string o;
+ for (char c : s) {
+ if (c == '"' || c == '\\') { o.push_back('\\'); o.push_back(c); }
+ else if (c == '\n') o += "\\n";
+ else if (static_cast<unsigned char>(c) >= 0x20) o.push_back(c);
+ }
+ return o;
+}
+
+// Colour-coded result channel. Recovery has no network and no shared disk, so a command's
+// outcome is reported by painting Terminal's window green (success) or red (failure), which
+// the host reads from a QMP screendump. Robust across fonts, languages and resolutions.
+constexpr const char* kColourFns =
+ "G(){ printf '\\033[42m'; printf '\\033[2J\\033[3J\\033[H'; i=0; while [ $i -lt 40 ]; do printf '%130s\\n' ''; i=$((i+1)); done; printf '\\033[0m'; };"
+ "R(){ printf '\\033[41m'; printf '\\033[2J\\033[3J\\033[H'; i=0; while [ $i -lt 40 ]; do printf '%130s\\n' ''; i=$((i+1)); done; printf '\\033[0m'; };";
+
+enum class Verdict { None, Green, Red };
+
+} // namespace
+
+const char* prov_state_name(ProvState s) {
+ switch (s) {
+ case ProvState::Idle: return "idle";
+ case ProvState::Preparing: return "preparing";
+ case ProvState::Downloading: return "downloading";
+ case ProvState::CreatingRuntime: return "creating";
+ case ProvState::BootingRecovery: return "booting";
+ case ProvState::PreparingDisk: return "disk";
+ case ProvState::CopyingInstaller: return "copying";
+ case ProvState::Installing: return "installing";
+ case ProvState::FirstBoot: return "first_boot";
+ case ProvState::Finishing: return "finishing";
+ case ProvState::Ready: return "ready";
+ case ProvState::Failed: return "failed";
+ }
+ return "unknown";
+}
+
+Provisioner::Provisioner(std::string root) : root_(std::move(root)) {
+ vm_dir_ = root_ + "\\runtime\\reims-ctl\\vms\\wsm-default";
+ reims_ctl_ = root_ + "\\cache\\cargo\\bin\\reims-ctl.exe";
+ qemu_img_ = root_ + "\\runtime\\reims-ctl\\qemu\\current\\bin\\qemu-img.exe";
+ share_dir_ = root_ + "\\fs";
+ if (fs::exists(root_ + "\\runtime\\config\\runtime-ready.json")) {
+ snap_.state = ProvState::Ready; snap_.percent = 100; snap_.title = "macOS is ready";
+ }
+}
+
+Provisioner::~Provisioner() { if (worker_.joinable()) worker_.detach(); }
+
+void Provisioner::log(const std::string& line) const {
+ fs::create_directories(root_ + "\\logs");
+ std::ofstream f(root_ + "\\logs\\provision.log", std::ios::app);
+ SYSTEMTIME st; GetLocalTime(&st);
+ char ts[32]; snprintf(ts, sizeof(ts), "%02d:%02d:%02d ", st.wHour, st.wMinute, st.wSecond);
+ f << ts << line << "\n";
+}
+
+void Provisioner::set(ProvState s, double pct, const std::string& title, const std::string& detail) {
+ std::lock_guard<std::mutex> l(mu_);
+ snap_.state = s; snap_.percent = pct; snap_.title = title; snap_.detail = detail;
+ log(std::string("[") + prov_state_name(s) + "] " + title + (detail.empty() ? "" : " — " + detail));
+}
+
+void Provisioner::fail(const std::string& why) {
+ {
+ std::lock_guard<std::mutex> l(mu_);
+ snap_.state = ProvState::Failed; snap_.error = why;
+ }
+ log("[failed] " + why);
+}
+
+ProvSnapshot Provisioner::snapshot() const { std::lock_guard<std::mutex> l(mu_); return snap_; }
+
+std::string Provisioner::to_json() const {
+ auto s = snapshot();
+ std::ostringstream o;
+ o << "{\"state\":\"" << prov_state_name(s.state) << "\",\"percent\":" << s.percent
+ << ",\"title\":\"" << esc(s.title) << "\",\"detail\":\"" << esc(s.detail)
+ << "\",\"error\":\"" << esc(s.error) << "\",\"busy\":" << (running_ ? "true" : "false") << "}";
+ return o.str();
+}
+
+// ---------------------------------------------------------------- discovery
+
+ProvPlan Provisioner::plan() const {
+ ProvPlan p;
+ std::error_code ec;
+ fs::path inst = fs::path(root_) / "runtime" / "reims-ctl" / "installers";
+ for (auto& e : fs::directory_iterator(inst, ec)) {
+ auto n = e.path().filename().string();
+ // A complete offline installer image is 13-20 GB; a partial download ends in .part.
+ if (n.find("-offline-installer.img") != std::string::npos && n.find(".part") == std::string::npos &&
+ e.file_size(ec) > 10ull * 1000 * 1000 * 1000) {
+ p.reuse_installer = true; p.installer_path = e.path().string();
+ if (n.rfind("macOS-", 0) == 0) {
+ auto rest = n.substr(6);
+ auto dash = rest.find('-');
+ p.macos_name = "macOS " + rest.substr(0, dash) + " " + rest.substr(dash + 1, rest.find('-', dash + 1) - dash - 1);
+ }
+ }
+ }
+ p.download_bytes = p.reuse_installer ? 0 : 19700000000ull;
+ p.disk_needed_bytes = (p.reuse_installer ? 0 : 19700000000ull) + 40000000000ull;
+ p.drive = root_.substr(0, 2);
+ ULARGE_INTEGER freeb{};
+ if (GetDiskFreeSpaceExA((root_ + "\\").c_str(), &freeb, nullptr, nullptr)) p.free_bytes = freeb.QuadPart;
+ p.minutes = p.reuse_installer ? 45 : 75;
+ return p;
+}
+
+// ---------------------------------------------------------------- process helpers
+
+int Provisioner::reims(const std::string& args, std::string* out) const {
+ std::string cmd = "\"" + reims_ctl_ + "\" " + args;
+ SECURITY_ATTRIBUTES sa{sizeof(sa), nullptr, TRUE};
+ HANDLE rd = nullptr, wr = nullptr;
+ CreatePipe(&rd, &wr, &sa, 0);
+ SetHandleInformation(rd, HANDLE_FLAG_INHERIT, 0);
+ STARTUPINFOA si{}; si.cb = sizeof(si);
+ si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;
+ // An empty input: with wsmd's own (a background service has none worth reading) the macOS
+ // download in `reims-ctl create` waited on it forever and setup stuck at 2 %.
+ HANDLE nul = CreateFileA("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, nullptr);
+ si.hStdOutput = wr; si.hStdError = wr; si.hStdInput = nul;
+ PROCESS_INFORMATION pi{};
+ // reims-ctl keeps its VMs and downloads under XDG_DATA_HOME; QEMU must never open a visible window.
+ std::string env_data = root_ + "\\runtime", env_cache = root_ + "\\cache";
+ SetEnvironmentVariableA("XDG_DATA_HOME", env_data.c_str());
+ SetEnvironmentVariableA("XDG_CACHE_HOME", env_cache.c_str());
+ std::vector<char> buf(cmd.begin(), cmd.end()); buf.push_back(0);
+ BOOL started = CreateProcessA(nullptr, buf.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW, nullptr, root_.c_str(), &si, &pi);
+ if (nul != INVALID_HANDLE_VALUE) CloseHandle(nul);
+ if (!started) {
+ CloseHandle(rd); CloseHandle(wr);
+ log("could not start reims-ctl: " + std::to_string(GetLastError()));
+ return -1;
+ }
+ CloseHandle(wr);
+ std::string acc; char chunk[4096]; DWORD n = 0;
+ while (ReadFile(rd, chunk, sizeof(chunk), &n, nullptr) && n) {
+ acc.append(chunk, n);
+ // Surface download progress lines ("... 41% ...") to the wizard.
+ auto pct = acc.rfind('%');
+ if (pct != std::string::npos && pct >= 2) {
+ size_t b = pct; while (b > 0 && (isdigit(static_cast<unsigned char>(acc[b - 1])) || acc[b - 1] == '.')) --b;
+ if (b < pct) {
+ double v = atof(acc.substr(b, pct - b).c_str());
+ std::lock_guard<std::mutex> l(mu_);
+ if (snap_.state == ProvState::Downloading) snap_.percent = 2 + v * 0.38;
+ }
+ }
+ }
+ CloseHandle(rd);
+ WaitForSingleObject(pi.hProcess, INFINITE);
+ DWORD code = 1; GetExitCodeProcess(pi.hProcess, &code);
+ CloseHandle(pi.hProcess); CloseHandle(pi.hThread);
+ log("reims-ctl " + args + " -> " + std::to_string(code) + "\n" + acc.substr(acc.size() > 4000 ? acc.size() - 4000 : 0));
+ if (out) *out = acc;
+ return static_cast<int>(code);
+}
+
+bool Provisioner::vm_running() const {
+ std::string resp;
+ return wsm::core::QmpUnixClient(vm_dir_ + "\\qmp.sock").execute("{\"execute\":\"query-status\"}", resp, 1500);
+}
+
+uint64_t Provisioner::disk_bytes() const {
+ std::error_code ec; auto s = fs::file_size(vm_dir_ + "\\disk.qcow2", ec); return ec ? 0 : s;
+}
+
+bool Provisioner::screen_dump(std::vector<uint8_t>& rgb, int& w, int& h) const {
+ std::string ppm = root_ + "\\cache\\tmp\\prov_screen.ppm", err;
+ fs::create_directories(root_ + "\\cache\\tmp");
+ if (!wsm::core::QmpUnixClient(vm_dir_ + "\\qmp.sock").capture_screendump_ppm(ppm, err)) return false;
+ std::ifstream f(ppm, std::ios::binary);
+ std::string magic; int maxv = 0;
+ f >> magic >> w >> h >> maxv; f.get();
+ if (magic != "P6" || w <= 0 || h <= 0) return false;
+ rgb.resize(static_cast<size_t>(w) * h * 3);
+ f.read(reinterpret_cast<char*>(rgb.data()), rgb.size());
+ return static_cast<size_t>(f.gcount()) == rgb.size();
+}
+
+double Provisioner::screen_fraction_nonblack() const {
+ std::vector<uint8_t> px; int w = 0, h = 0;
+ if (!screen_dump(px, w, h)) return -1;
+ size_t lit = 0, total = static_cast<size_t>(w) * h;
+ for (size_t i = 0; i < total; i += 7) if (px[i * 3] + px[i * 3 + 1] + px[i * 3 + 2] > 60) ++lit;
+ return static_cast<double>(lit) / (total / 7.0);
+}
+
+static Verdict read_verdict(const std::vector<uint8_t>& px, int w, int h) {
+ size_t green = 0, red = 0, total = static_cast<size_t>(w) * h;
+ for (size_t i = 0; i < total; i += 3) {
+ int r = px[i * 3], g = px[i * 3 + 1], b = px[i * 3 + 2];
+ // Relative, so any Terminal theme works (Tahoe's Recovery paints a muted 108,170,113).
+ if (g > 120 && g > r + 40 && g > b + 40) ++green;
+ else if (r > 140 && r > g + 50 && r > b + 50) ++red;
+ }
+ double gf = green / (total / 3.0), rf = red / (total / 3.0);
+ if (gf > 0.04 && gf > rf) return Verdict::Green;
+ if (rf > 0.04) return Verdict::Red;
+ return Verdict::None;
+}
+
+bool Provisioner::guest_shell(const std::string& cmd) {
+ wsm::core::QmpUnixClient q(vm_dir_ + "\\qmp.sock");
+ // Paint neutral first so a stale green from a previous command can't be misread.
+ std::string line = std::string(kColourFns) + " printf '\\033[0m'; printf '\\033[2J\\033[3J\\033[H'; ( " + cmd + " ) && G || R";
+ log("guest$ " + cmd);
+ // Keystrokes reach the guest after type_ascii_text returns, so the previous command's green
+ // could still be on screen when the next verdict is read, and pass a command that hadn't
+ // even run yet. Clear to neutral first and wait until the screen really shows no verdict.
+ // (The leading empty line also absorbs a keystroke lost while Terminal's window comes up.)
+ q.type_ascii_text("\nprintf '\\033[0m\\033[2J\\033[3J\\033[H'\n");
+ for (int i = 0; i < 60; ++i) {
+ std::vector<uint8_t> px; int w = 0, h = 0;
+ if (screen_dump(px, w, h) && read_verdict(px, w, h) == Verdict::None) break;
+ Sleep(1000);
+ }
+ return q.type_ascii_text(line + "\n");
+}
+
+// Waits for the colour verdict of the last guest_shell command.
+static Verdict wait_verdict(Provisioner* self, const std::function<bool(std::vector<uint8_t>&, int&, int&)>& dump,
+ int timeout_s, const std::function<void(int)>& tick) {
+ for (int t = 0; t < timeout_s; t += 3) {
+ std::vector<uint8_t> px; int w = 0, h = 0;
+ if (dump(px, w, h)) { auto v = read_verdict(px, w, h); if (v != Verdict::None) return v; }
+ if (tick) tick(t);
+ Sleep(3000);
+ }
+ (void)self;
+ return Verdict::None;
+}
+
+bool Provisioner::wait_for_marker(const std::string&, int, const std::function<void(int)>&) { return false; }
+
+// Recovery's menu bar is at the top; Utilities > Terminal is the third item of the Utilities menu.
+// Positions are fractions of the guest display, so they hold at any resolution. Each attempt is
+// verified through the colour channel before anything destructive runs.
+// Terminal's window: its slate background (about 38,44,56) over a real part of the screen.
+// Recovery itself is neutral grey and Apple's setup screens don't use this colour, so nothing is
+// ever typed into the installer's or Recovery's own windows.
+bool Provisioner::terminal_visible() const {
+ std::vector<uint8_t> px; int w = 0, h = 0;
+ if (!screen_dump(px, w, h)) return false;
+ size_t hit = 0, n = 0;
+ for (int y = 0; y < h; y += 6)
+ for (int x = 0; x < w; x += 6, ++n) {
+ const uint8_t* p = &px[(static_cast<size_t>(y) * w + x) * 3];
+ if (std::abs(p[0] - 38) <= 9 && std::abs(p[1] - 44) <= 9 && std::abs(p[2] - 56) <= 9 && p[2] >= p[0] + 10) ++hit;
+ }
+ return n && hit * 20 > n; // > 5 % of the screen
+}
+
+// Recovery (the installer's, or the installed disk's): Utilities > Terminal by its shortcut
+// (Shift+Cmd+T, any resolution), else through the menu. Verified twice: Terminal's window on
+// screen before anything is typed, then a command's green verdict.
+bool Provisioner::open_recovery_terminal() {
+ wsm::core::QmpUnixClient q(vm_dir_ + "\\qmp.sock");
+ auto dump = [this](std::vector<uint8_t>& p, int& w, int& h) { return screen_dump(p, w, h); };
+ for (int attempt = 0; attempt < 4; ++attempt) {
+ q.send_key_qcode("esc");
+ Sleep(800);
+ std::string r;
+ q.execute("{\"execute\":\"send-key\",\"arguments\":{\"keys\":[{\"type\":\"qcode\",\"data\":\"shift\"},"
+ "{\"type\":\"qcode\",\"data\":\"meta_l\"},{\"type\":\"qcode\",\"data\":\"t\"}]}}", r, 2000);
+ Sleep(6000);
+ if (!terminal_visible()) {
+ q.send_mouse_click(static_cast<int>(122.0 / 872 * 32767), static_cast<int>(7.0 / 492 * 32767));
+ Sleep(1200);
+ q.send_mouse_click(static_cast<int>(125.0 / 872 * 32767), static_cast<int>(48.0 / 492 * 32767));
+ Sleep(5000);
+ }
+ if (terminal_visible()) {
+ Sleep(3000);
+ guest_shell("true");
+ if (wait_verdict(this, dump, 30, nullptr) == Verdict::Green) return true;
+ }
+ log("Terminal not confirmed, retrying");
+ q.send_key_qcode("esc");
+ Sleep(5000);
+ }
+ return false;
+}
+
+// ---------------------------------------------------------------- steps
+
+bool Provisioner::step_create_runtime() {
+ if (fs::exists(vm_dir_ + "\\vm.toml")) { log("reusing existing runtime definition"); return true; }
+ auto p = plan();
+ set(p.reuse_installer ? ProvState::CreatingRuntime : ProvState::Downloading, 2,
+ p.reuse_installer ? "Preparing macOS" : "Downloading macOS from Apple",
+ p.reuse_installer ? "Using the installer already on this PC" : "About 19.7 GB");
+ // reims-util reuses a complete installer image in the downloads folder and resumes a partial one.
+ int rc = reims("create wsm-default --macos tahoe --offline --memory 5G --cpus 4 --ssh-port 2222 --network false");
+ if (rc != 0) { fail("macOS couldn't be prepared. Check the internet connection and free space, then try again."); return false; }
+ reims("set wsm-default --env REIMS_VGPU_WINDOW=1");
+ return true;
+}
+
+bool Provisioner::step_boot_recovery() {
+ set(ProvState::BootingRecovery, 42, "Starting the macOS installer");
+ if (!vm_running() && reims("start wsm-default") != 0) { fail("The macOS installer didn't start."); return false; }
+ // Recovery's desktop is a mostly-dark full-screen picture; wait until it has drawn and settled.
+ for (int t = 0; t < 600; t += 5) {
+ double lit = screen_fraction_nonblack();
+ if (lit > 0.02) { Sleep(15000); break; }
+ Sleep(5000);
+ if (t >= 595) { fail("The macOS installer didn't finish starting within 10 minutes."); return false; }
+ }
+ if (!open_recovery_terminal()) { fail("WSM couldn't take control of the macOS installer."); return false; }
+ return true;
+}
+
+bool Provisioner::step_install() {
+ auto dump = [this](std::vector<uint8_t>& p, int& w, int& h) { return screen_dump(p, w, h); };
+ set(ProvState::PreparingDisk, 46, "Preparing the disk");
+ // The system disk is the internal physical disk that holds neither OpenCore nor the installer.
+ // If it already carries "Macintosh HD" with the Install app (an interrupted earlier run), keep it.
+ guest_shell(
+ "if [ -d '/Volumes/Macintosh HD/Applications' ] || [ -d /Volumes/MacintoshHD/Applications ]; then true; else "
+ "T=; for d in $(diskutil list internal physical | grep '^/dev/disk' | cut -d' ' -f1); do "
+ "diskutil list $d | grep -qE 'OPENCORE|Installer|RECOVERY' || T=$d; done; "
+ "[ -n \"$T\" ] && diskutil eraseDisk APFS 'Macintosh HD' GPT $T; fi");
+ if (wait_verdict(this, dump, 180, nullptr) != Verdict::Green) { fail("The disk for macOS couldn't be prepared."); return false; }
+
+ // Resolve the verified target: a mounted, writable volume (never a bare directory on the
+ // read-only Recovery root, which is what made the old script fail with //Install.XXXX).
+ const std::string pick_target =
+ "V=; for c in '/Volumes/Macintosh HD' /Volumes/MacintoshHD; do "
+ "diskutil info \"$c\" 2>/dev/null | grep -q 'Read-Only Volume: *No' && V=$c; done; [ -n \"$V\" ]";
+ guest_shell(pick_target);
+ if (wait_verdict(this, dump, 60, nullptr) != Verdict::Green) { fail("The prepared disk wasn't available to the installer."); return false; }
+
+ set(ProvState::CopyingInstaller, 50, "Copying the installer", "This takes a few minutes");
+ guest_shell(pick_target + " && A=$(ls -d \"$V\"/Applications/Install\\ macOS*.app 2>/dev/null | head -1); "
+ "if [ -z \"$A\" ]; then L=\"${V}Applications\"; mkdir -p \"$V/Applications\"; ln -sfn \"$V/Applications\" \"$L\"; "
+ "CM_BUILD=CM_BUILD installer -pkg /Volumes/Installer/InstallAssistant.pkg -target \"$V\"; rm -f \"$L\"; "
+ "A=$(ls -d \"$V\"/Applications/Install\\ macOS*.app | head -1); fi; "
+ "[ -f \"$A/Contents/SharedSupport/SharedSupport.dmg\" ] || { mkdir -p \"$A/Contents/SharedSupport\"; "
+ "cp /Volumes/Installer/InstallAssistant.pkg \"$A/Contents/SharedSupport/SharedSupport.dmg\"; }; "
+ "chmod -R 755 \"$A\" && [ -x \"$A/Contents/Resources/startosinstall\" ]");
+ if (wait_verdict(this, dump, 1800, [this](int t) {
+ std::lock_guard<std::mutex> l(mu_); snap_.percent = 50 + std::min(8.0, t / 60.0); }) != Verdict::Green) {
+ fail("The macOS installer couldn't be copied to the disk."); return false;
+ }
+
+ // License acceptance was given explicitly by the user in the setup wizard (recorded in
+ // runtime\config\license-acceptance.json) before begin() could be called.
+ set(ProvState::Installing, 58, "Installing macOS", "Your PC can be used normally meanwhile");
+ guest_shell(pick_target + " && A=$(ls -d \"$V\"/Applications/Install\\ macOS*.app | head -1) && "
+ "\"$A/Contents/Resources/startosinstall\" --agreetolicense --volume \"$V\"");
+ return true;
+}
+
+bool Provisioner::step_wait_first_boot() {
+ // startosinstall prepares, then restarts into the installer, which restarts several more
+ // times. Progress is tracked by the disk's growth; completion is the first macOS boot that
+ // stays up with the disk quiet.
+ uint64_t start = disk_bytes(), last = start;
+ auto quiet_since = std::chrono::steady_clock::now();
+ for (int t = 0; t < 4 * 3600; t += 20) {
+ Sleep(20000);
+ if (!vm_running()) { // the guest powered off rather than restarting: start it again
+ log("runtime stopped during install; starting it again");
+ reims("start wsm-default");
+ continue;
+ }
+ uint64_t now = disk_bytes();
+ double grown = static_cast<double>(now - start) / (14.0 * 1024 * 1024 * 1024);
+ {
+ std::lock_guard<std::mutex> l(mu_);
+ snap_.percent = std::max(snap_.percent, std::min(92.0, 58 + grown * 34));
+ }
+ if (now != last) { last = now; quiet_since = std::chrono::steady_clock::now(); }
+ auto quiet = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - quiet_since).count();
+ if (now - start > 6ull * 1024 * 1024 * 1024 && quiet > 240 && screen_fraction_nonblack() > 0.05) return true;
+ }
+ fail("Installing macOS took longer than 4 hours and was stopped.");
+ return false;
+}
+
+// ---------------------------------------------------------------- first-boot setup
+//
+// After the install, macOS would stop at Setup Assistant with no account WSM can use. The
+// fix runs offline, from the installed disk's own Recovery (no installer image needed, so it
+// also works after the installer was cleaned up):
+// payload folder on Windows -> QEMU virtual FAT USB stick "WSMPAYLOAD"
+// reboot holding Cmd+R (tapped: OpenCore's KeySupport forgets keys that don't repeat)
+// Terminal via Shift+Cmd+T -> sh wsm-offline-setup.sh -> green/red verdict
+// normal boot -> auto-login -> SSH with the new key proves it.
+
+namespace {
+
+int run_quiet(const std::string& cmdline, DWORD timeout_ms) {
+ STARTUPINFOA si{}; si.cb = sizeof(si);
+ si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;
+ PROCESS_INFORMATION pi{};
+ std::string cl = cmdline;
+ if (!CreateProcessA(nullptr, cl.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) return -1;
+ if (WaitForSingleObject(pi.hProcess, timeout_ms) != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 255);
+ DWORD code = 255;
+ GetExitCodeProcess(pi.hProcess, &code);
+ CloseHandle(pi.hThread); CloseHandle(pi.hProcess);
+ return static_cast<int>(code);
+}
+
+std::string read_all(const std::string& path) {
+ std::ifstream f(path, std::ios::binary);
+ return std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+}
+
+// /etc/kcpassword: the auto-login password, NUL-terminated, padded to 12 bytes, XORed with
+// Apple's fixed key.
+std::string kcpassword(const std::string& pw) {
+ static const unsigned char key[] = {0x7D, 0x89, 0x52, 0x23, 0xD2, 0xBC, 0xDD, 0xEA, 0xA3, 0xB9, 0x1F};
+ std::string b = pw + '\0';
+ while (b.size() % 12) b.push_back('\0');
+ for (size_t i = 0; i < b.size(); ++i) b[i] = static_cast<char>(static_cast<unsigned char>(b[i]) ^ key[i % sizeof(key)]);
+ return b;
+}
+
+} // namespace
+
+bool Provisioner::make_payload(std::string& dir, std::string& err) {
+ const std::string guest = root_ + "\\runtime\\config\\guest";
+ const std::string key = guest + "\\id_ed25519", pwfile = guest + "\\password";
+ std::error_code ec;
+ fs::create_directories(guest, ec);
+ // The runtime's SSH key: made once, on this PC, never shipped.
+ if (!fs::exists(key, ec)) {
+ int rc = run_quiet("\"C:\\Windows\\System32\\OpenSSH\\ssh-keygen.exe\" -q -t ed25519 -N \"\" -C wsm-runtime -f \"" + key + "\"", 60000);
+ if (rc != 0 || !fs::exists(key + ".pub", ec)) { err = "Windows' OpenSSH client (ssh-keygen) isn't available."; return false; }
+ }
+ // OpenSSH refuses a private key other accounts can read.
+ run_quiet("cmd.exe /c icacls.exe \"" + key + "\" /inheritance:r /grant:r \"%USERNAME%:F\"", 15000);
+ // The runtime account's password (only for auto-login; WSM itself logs in with the key).
+ std::string pw = read_all(pwfile);
+ while (!pw.empty() && (pw.back() == '\n' || pw.back() == '\r' || pw.back() == ' ')) pw.pop_back();
+ if (pw.empty()) {
+ static const char cs[] = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789";
+ std::random_device rd; // MSVC: rand_s, a CSPRNG
+ for (int i = 0; i < 20; ++i) pw.push_back(cs[rd() % (sizeof(cs) - 1)]);
+ std::ofstream(pwfile, std::ios::binary | std::ios::trunc) << pw;
+ }
+ dir = root_ + "\\cache\\tmp\\wsm-payload";
+ fs::remove_all(dir, ec);
+ fs::create_directories(dir, ec);
+ std::ofstream(dir + "\\authorized_keys", std::ios::binary) << read_all(key + ".pub");
+ std::ofstream(dir + "\\password", std::ios::binary) << pw;
+ std::string kc = kcpassword(pw);
+ std::ofstream(dir + "\\kcpassword", std::ios::binary).write(kc.data(), static_cast<std::streamsize>(kc.size()));
+ fs::copy_file(root_ + "\\src\\wsm-guest\\provision\\wsm-offline-setup.sh", dir + "\\wsm-offline-setup.sh",
+ fs::copy_options::overwrite_existing, ec);
+ if (ec) { err = "WSM's setup files are missing. Reinstall WSM."; return false; }
+ return true;
+}
+
+// While setup drives the runtime, nothing else may start it (RuntimeHost checks this file).
+Provisioner::SetupLock::SetupLock(const std::string& root) : path_(root + "\\runtime\\config\\setup-running") {
+ std::error_code ec;
+ fs::create_directories(fs::path(path_).parent_path(), ec);
+ std::ofstream(path_) << "setup\n";
+}
+Provisioner::SetupLock::~SetupLock() { std::error_code ec; fs::remove(path_, ec); }
+
+// Power off, wait until that QEMU is really gone (it holds the SSH port and the disk for a
+// moment after the stop), then start; a start that fails is retried.
+bool Provisioner::restart_vm() {
+ reims("stop " + vm_ + " --force");
+ for (int i = 0; i < 30 && vm_running(); ++i) Sleep(1000);
+ Sleep(3000);
+ for (int t = 0; t < 4; ++t) {
+ if (reims("start " + vm_) == 0) return true;
+ log("start failed, retrying");
+ reims("stop " + vm_ + " --force");
+ Sleep(5000);
+ }
+ return false;
+}
+
+bool Provisioner::boot_into_recovery() {
+ wsm::core::QmpUnixClient q(vm_dir_ + "\\qmp.sock");
+ auto key_events = [&](bool down, std::initializer_list<const char*> keys) {
+ std::string ev;
+ for (const char* k : keys)
+ ev += std::string(ev.empty() ? "" : ",") + "{\"type\":\"key\",\"data\":{\"down\":" + (down ? "true" : "false") +
+ ",\"key\":{\"type\":\"qcode\",\"data\":\"" + k + "\"}}}";
+ std::string r;
+ q.execute("{\"execute\":\"input-send-event\",\"arguments\":{\"events\":[" + ev + "]}}", r, 1000);
+ };
+ auto dump = [this](std::vector<uint8_t>& p, int& w, int& h) { return screen_dump(p, w, h); };
+ for (int attempt = 0; attempt < 4; ++attempt) { // the Cmd+R tap misses about half the time
+ if (!restart_vm()) return false;
+ // QEMU's socket is up within a second; tap Cmd+R through OpenCore's start (25 s).
+ for (int i = 0; i < 50; ++i) { std::string r; if (q.execute("{\"execute\":\"query-status\"}", r, 500)) break; Sleep(200); }
+ auto t0 = std::chrono::steady_clock::now();
+ while (std::chrono::steady_clock::now() - t0 < std::chrono::seconds(25)) {
+ key_events(true, {"meta_l", "r"});
+ Sleep(40);
+ key_events(false, {"r"});
+ Sleep(40);
+ }
+ key_events(false, {"meta_l"});
+ // Recovery takes ~60-100 s. Wait until the screen is lit and has stopped changing (the
+ // boot progress bar moves; Recovery's options window sits still), then open Terminal by
+ // its shortcut. Nothing is typed until a window has visibly appeared, so keystrokes can
+ // never land in Recovery's options window (Enter there would start a restore flow).
+ auto signature = [&](uint64_t& sig) {
+ std::vector<uint8_t> px; int w = 0, h = 0;
+ if (!screen_dump(px, w, h)) return false;
+ uint64_t s = 1469598103934665603ull; size_t lit = 0, n = 0;
+ std::vector<bool> seen(4096, false);
+ int colours = 0;
+ for (int y = 0; y < h; y += 8)
+ for (int x = 0; x < w; x += 8, ++n) {
+ const uint8_t* p = &px[(static_cast<size_t>(y) * w + x) * 3];
+ s = (s ^ (p[0] >> 3) ^ ((p[1] >> 3) << 5) ^ ((p[2] >> 3) << 10)) * 1099511628211ull;
+ if (p[0] + p[1] + p[2] > 60) ++lit;
+ int q = (p[0] >> 4) << 8 | (p[1] >> 4) << 4 | (p[2] >> 4);
+ if (!seen[q]) { seen[q] = true; ++colours; }
+ }
+ // 0 = not a UI yet: mostly black (Apple logo), or a plain screen (the firmware's grey
+ // one right after the Cmd+R start). Recovery has a gradient, a window and icons.
+ sig = (n && lit * 20 > n && colours >= 24) ? s : 0;
+ return true;
+ };
+ uint64_t prev = 0;
+ int settled = 0;
+ bool opened = false;
+ for (int t = 0; t < 300 && !opened; t += 5) {
+ Sleep(5000);
+ uint64_t sig = 0;
+ bool got = signature(sig);
+ log("recovery wait " + std::to_string(t) + " s: " + (!got ? "no screen" : sig == 0 ? "not a UI yet" : "UI") +
+ ", still " + std::to_string(sig != 0 && sig == prev ? settled + 1 : 0));
+ if (!got || sig == 0) { settled = 0; prev = 0; continue; }
+ settled = (sig == prev) ? settled + 1 : 0;
+ prev = sig;
+ if (settled < 3) continue; // unchanged for 15 s
+ for (int tries = 0; tries < 3 && !opened; ++tries) {
+ uint64_t before = sig, after = 0;
+ q.send_key_qcode("esc");
+ Sleep(800);
+ std::string r;
+ q.execute("{\"execute\":\"send-key\",\"arguments\":{\"keys\":[{\"type\":\"qcode\",\"data\":\"shift\"},"
+ "{\"type\":\"qcode\",\"data\":\"meta_l\"},{\"type\":\"qcode\",\"data\":\"t\"}]}}", r, 2000);
+ Sleep(6000);
+ signature(after);
+ bool term = terminal_visible();
+ log(std::string("terminal shortcut: screen ") + (after != before ? "changed" : "unchanged") + ", terminal " + (term ? "seen" : "not seen"));
+ if (after != 0 && after != before && term) opened = true;
+ }
+ if (!opened) { settled = 0; prev = 0; }
+ }
+ if (opened) {
+ Sleep(3000); // let Terminal finish opening before typing
+ // Only Recovery has the payload stick next to a writable Data volume; normal macOS
+ // has no root Terminal here at all, so this can't succeed by accident.
+ guest_shell("ls /Volumes/*/wsm-offline-setup.sh >/dev/null");
+ if (wait_verdict(this, dump, 60, nullptr) == Verdict::Green) return true;
+ }
+ log("Recovery Terminal not confirmed (attempt " + std::to_string(attempt + 1) + ")");
+ }
+ return false;
+}
+
+bool Provisioner::ssh_ok(uint32_t timeout_ms) const {
+ std::string cmd = "\"C:\\Windows\\System32\\OpenSSH\\ssh.exe\" -i \"" + root_ + "\\runtime\\config\\guest\\id_ed25519\"" +
+ " -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=NUL -o LogLevel=ERROR"
+ " -o ConnectTimeout=8 -p " + std::to_string(ssh_port_) +
+ // sshd answers before anyone is signed in: ready means WSM's account owns the
+ // desktop (auto-login got past any first-run screen) and sudo needs no password.
+ " [email protected] \"sudo -n true && [ \\\"$(stat -f %Su /dev/console)\\\" = wsm ]\"";
+ return run_quiet(cmd, timeout_ms) == 0;
+}
+
+// Apple's first-run screens put their action ("Get Started", "Continue") in a filled blue
+// button in the lower half. Click the centre of the largest such area, if there is one.
+bool Provisioner::click_blue_button() {
+ std::vector<uint8_t> px; int w = 0, h = 0;
+ if (!screen_dump(px, w, h)) return false;
+ long sx = 0, sy = 0, n = 0;
+ for (int y = h / 2; y < h; y += 2)
+ for (int x = w / 4; x < w * 3 / 4; x += 2) {
+ const uint8_t* p = &px[(static_cast<size_t>(y) * w + x) * 3];
+ if (p[2] > 190 && p[0] < 60 && p[1] > 90 && p[1] < 170) { sx += x; sy += y; ++n; }
+ }
+ if (n < 150) return false; // nothing button-sized
+ int cx = static_cast<int>(sx / n), cy = static_cast<int>(sy / n);
+ log("clicking the blue button at " + std::to_string(cx) + "," + std::to_string(cy));
+ wsm::core::QmpUnixClient(vm_dir_ + "\\qmp.sock").send_mouse_click(cx * 32767 / w, cy * 32767 / h);
+ return true;
+}
+
+bool Provisioner::step_first_boot_setup() {
+ set(ProvState::FirstBoot, 93, "Setting up macOS for WSM", "Creating the runtime's account");
+ if (ssh_ok(30000)) { log("first-boot setup: already reachable"); return true; }
+ std::string dir, err;
+ if (!make_payload(dir, err)) { fail(err); return false; }
+
+ // The payload as a read-only FAT stick, only for this boot.
+ std::string fwd = dir;
+ for (auto& c : fwd) if (c == '\\') c = '/';
+ reims("stop " + vm_);
+ reims("set " + vm_ + " --extra-args \"-drive if=none,id=wsmpayload,driver=vvfat,dir=" + fwd +
+ ",fat-type=16,label=WSMPAYLOAD,read-only=on -device usb-storage,bus=xhci.0,drive=wsmpayload,removable=on\"");
+ bool ok = boot_into_recovery();
+ if (ok) {
+ set(ProvState::FirstBoot, 95, "Setting up macOS for WSM", "Account, sign-in and remote access");
+ auto dump = [this](std::vector<uint8_t>& p, int& w, int& h) { return screen_dump(p, w, h); };
+ guest_shell("P=$(dirname \"$(ls /Volumes/*/wsm-offline-setup.sh | head -1)\") && sh \"$P/wsm-offline-setup.sh\" \"$P\"");
+ ok = wait_verdict(this, dump, 300, nullptr) == Verdict::Green;
+ if (!ok) err = "macOS couldn't be set up for WSM.";
+ } else {
+ err = "WSM couldn't start macOS's recovery system to finish the setup.";
+ }
+ // Shut Recovery down from the inside, so what the script wrote is on the disk (a forced
+ // power-off right after it lost the new key and auto-login), then a normal start without
+ // the stick (RuntimeHost adds WSM's own options later).
+ if (ok) {
+ // macOS's sync only queues the writes; give them time, then let QEMU flush its image
+ // (stop) and exit cleanly (quit). Killing QEMU loses the qcow2 index entries it still
+ // holds in memory, and with them everything the script wrote.
+ guest_shell("sync; sync");
+ Sleep(10000);
+ wsm::core::QmpUnixClient q(vm_dir_ + "\\qmp.sock");
+ std::string r;
+ q.execute("{\"execute\":\"stop\"}", r, 30000);
+ q.execute("{\"execute\":\"quit\"}", r, 30000);
+ for (int i = 0; i < 60 && vm_running(); ++i) Sleep(1000);
+ }
+ reims("stop " + vm_ + " --force"); // only if it's somehow still there
+ reims("set " + vm_ + " --extra-args \"\"");
+ std::error_code ec;
+ fs::remove_all(dir, ec); // holds the password in clear text
+ if (!ok) { fail(err); return false; }
+
+ set(ProvState::FirstBoot, 96, "Starting macOS", "First sign-in");
+ if (!restart_vm()) { fail("macOS didn't start after setup."); return false; }
+ // Signed in when WSM's key works (and sudo needs no password). Apple's first-run screen may
+ // still want one "Get Started" click; press it when it shows.
+ for (int t = 0; t < 20 * 60; t += 20) {
+ if (ssh_ok(20000)) { log("first-boot setup: runtime reachable after " + std::to_string(t) + " s"); return true; }
+ if (t >= 120) click_blue_button();
+ Sleep(20000);
+ }
+ fail("macOS started, but WSM couldn't sign in to it.");
+ return false;
+}
+
+bool Provisioner::repair_first_boot(const std::string& vm, int ssh_port, std::string& err) {
+ if (running_.exchange(true)) { err = "Setup is already running."; return false; }
+ vm_ = vm;
+ ssh_port_ = ssh_port;
+ vm_dir_ = root_ + "\\runtime\\reims-ctl\\vms\\" + vm;
+ { std::lock_guard<std::mutex> l(mu_); snap_ = {}; }
+ if (worker_.joinable()) worker_.join();
+ worker_ = std::thread([this] {
+ SetupLock lock(root_);
+ if (step_first_boot_setup()) {
+ // The main runtime, not yet marked ready (a reset or a just-installed macOS): finish
+ // exactly like setup does.
+ if (vm_ == "wsm-default" && !fs::exists(root_ + "\\runtime\\config\\runtime-ready.json")) step_finish();
+ else set(ProvState::Ready, 100, "macOS is set up for WSM");
+ }
+ vm_ = "wsm-default";
+ ssh_port_ = 2222;
+ vm_dir_ = root_ + "\\runtime\\reims-ctl\\vms\\wsm-default";
+ running_ = false;
+ });
+ return true;
+}
+
+bool Provisioner::step_finish() {
+ set(ProvState::Finishing, 94, "Finishing up");
+ reims("eject wsm-default");
+ reims("set wsm-default --network true");
+ // The install ran with macOS's screen in a window (REIMS_VGPU_WINDOW=1). From now on macOS is
+ // never shown: no window at all, so no Apple logo or progress bar at boot.
+ reims("set wsm-default --env REIMS_VGPU_WINDOW=0");
+ fs::create_directories(root_ + "\\runtime\\config");
+ std::ofstream(root_ + "\\runtime\\config\\runtime-ready.json") << "{\"runtime\":\"full\",\"vm\":\"wsm-default\"}\n";
+ set(ProvState::Ready, 100, "macOS is ready");
+ return true;
+}
+
+// ---------------------------------------------------------------- driver
+
+bool Provisioner::begin(bool license_accepted, std::string& err) {
+ if (!license_accepted) { err = "Apple's license must be accepted before macOS can be installed."; return false; }
+ if (running_.exchange(true)) { err = "Setup is already running."; return false; }
+ fs::create_directories(root_ + "\\runtime\\config");
+ SYSTEMTIME st; GetLocalTime(&st);
+ char ts[40]; snprintf(ts, sizeof(ts), "%04d-%02d-%02dT%02d:%02d:%02d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
+ std::ofstream(root_ + "\\runtime\\config\\license-acceptance.json")
+ << "{\"license\":\"Apple macOS Software License Agreement\",\"accepted\":true,\"accepted_at\":\"" << ts
+ << "\",\"accepted_via\":\"Install in WSM setup, with the license notice and link shown above it\"}\n";
+ { std::lock_guard<std::mutex> l(mu_); snap_ = {}; }
+ if (worker_.joinable()) worker_.join();
+ worker_ = std::thread([this] { SetupLock lock(root_); run(); running_ = false; });
+ return true;
+}
+
+void Provisioner::run() {
+ set(ProvState::Preparing, 1, "Checking this PC");
+ if (!fs::exists(reims_ctl_)) { fail("WSM's runtime components are missing. Reinstall WSM."); return; }
+ if (!step_create_runtime()) return;
+ if (!step_boot_recovery()) return;
+ if (!step_install()) return;
+ if (!step_wait_first_boot()) return;
+ if (!step_first_boot_setup()) return;
+ step_finish();
+}
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/src/runtime_host.cpp b/src/wsm-runtime/src/runtime_host.cpp
new file mode 100644
index 0000000..e96ccad
--- /dev/null
+++ b/src/wsm-runtime/src/runtime_host.cpp
@@ -0,0 +1,253 @@
+#include "wsm/runtime_host.hpp"
+#include "wsm/qmp_unix.hpp"
+
+#include <windows.h>
+#include <psapi.h>
+
+#include <chrono>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <vector>
+
+namespace fs = std::filesystem;
+
+namespace wsm::runtime {
+
+const char* rt_state_name(RtState s) {
+ switch (s) {
+ case RtState::NotInstalled: return "not_installed";
+ case RtState::Off: return "stopped";
+ case RtState::Starting: return "starting";
+ case RtState::Running: return "ready";
+ case RtState::Paused: return "paused";
+ case RtState::Stopping: return "stopping";
+ }
+ return "unknown";
+}
+
+RuntimeHost::RuntimeHost(std::string root, std::string vm) : root_(std::move(root)), vm_(std::move(vm)) {
+ vm_dir_ = root_ + "\\runtime\\reims-ctl\\vms\\" + vm_;
+ reims_ctl_ = root_ + "\\cache\\cargo\\bin\\reims-ctl.exe";
+}
+
+int RuntimeHost::reims(const std::string& args, std::string* out) const {
+ SetEnvironmentVariableA("XDG_DATA_HOME", (root_ + "\\runtime").c_str());
+ SetEnvironmentVariableA("XDG_CACHE_HOME", (root_ + "\\cache").c_str());
+ std::string cmd = "\"" + reims_ctl_ + "\" " + args;
+ SECURITY_ATTRIBUTES sa{sizeof(sa), nullptr, TRUE};
+ HANDLE rd = nullptr, wr = nullptr;
+ CreatePipe(&rd, &wr, &sa, 0);
+ SetHandleInformation(rd, HANDLE_FLAG_INHERIT, 0);
+ STARTUPINFOA si{}; si.cb = sizeof(si);
+ si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;
+ HANDLE nul = CreateFileA("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, nullptr);
+ si.hStdOutput = wr; si.hStdError = wr; si.hStdInput = nul; // never wait on an input nobody gives
+ PROCESS_INFORMATION pi{};
+ std::vector<char> buf(cmd.begin(), cmd.end()); buf.push_back(0);
+ BOOL started = CreateProcessA(nullptr, buf.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW, nullptr, root_.c_str(), &si, &pi);
+ if (nul != INVALID_HANDLE_VALUE) CloseHandle(nul);
+ if (!started) {
+ CloseHandle(rd); CloseHandle(wr); return -1;
+ }
+ CloseHandle(wr);
+ std::string acc; char chunk[2048]; DWORD n = 0;
+ while (ReadFile(rd, chunk, sizeof(chunk), &n, nullptr) && n) acc.append(chunk, n);
+ CloseHandle(rd);
+ WaitForSingleObject(pi.hProcess, INFINITE);
+ DWORD code = 1; GetExitCodeProcess(pi.hProcess, &code);
+ CloseHandle(pi.hProcess); CloseHandle(pi.hThread);
+ std::ofstream(root_ + "\\logs\\runtime.log", std::ios::app) << "reims-ctl " << args << " -> " << code << "\n" << acc << "\n";
+ if (out) *out = acc;
+ return static_cast<int>(code);
+}
+
+uint32_t RuntimeHost::pid() const {
+ std::ifstream f(vm_dir_ + "\\qemu.pid");
+ uint32_t p = 0;
+ if (!(f >> p) || !p) return 0;
+ HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, p);
+ if (!h) return 0;
+ DWORD code = 0;
+ bool alive = GetExitCodeProcess(h, &code) && code == STILL_ACTIVE;
+ CloseHandle(h);
+ return alive ? p : 0;
+}
+
+bool RuntimeHost::qmp(const std::string& json, std::string& resp, uint32_t timeout_ms) const {
+ return wsm::core::QmpUnixClient(qmp_socket()).execute(json, resp, timeout_ms);
+}
+
+RtStatus RuntimeHost::status() const {
+ RtStatus s;
+ if (!fs::exists(vm_dir_ + "\\vm.toml")) { s.state = RtState::NotInstalled; return s; }
+ s.pid = pid();
+ if (!s.pid) { s.state = RtState::Off; return s; }
+ std::string r;
+ if (!qmp("{\"execute\":\"query-status\"}", r, 1500)) s.state = RtState::Starting;
+ else if (r.find("\"running\": true") != std::string::npos || r.find("\"running\":true") != std::string::npos) s.state = RtState::Running;
+ else if (r.find("\"paused\"") != std::string::npos) s.state = RtState::Paused;
+ else if (r.find("shutdown") != std::string::npos) s.state = RtState::Stopping;
+ else s.state = RtState::Starting;
+ HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, s.pid);
+ if (h) {
+ PROCESS_MEMORY_COUNTERS pmc{}; pmc.cb = sizeof(pmc);
+ if (GetProcessMemoryInfo(h, &pmc, sizeof(pmc))) s.working_set_mb = pmc.WorkingSetSize >> 20;
+ CloseHandle(h);
+ }
+ return s;
+}
+
+bool RuntimeHost::pause(std::string& err) {
+ std::lock_guard<std::mutex> l(mu_);
+ std::string r;
+ if (!qmp("{\"execute\":\"stop\"}", r)) { err = "The runtime isn't running."; return false; }
+ return true;
+}
+
+bool RuntimeHost::resume(std::string& err) {
+ std::lock_guard<std::mutex> l(mu_);
+ std::string r;
+ if (!qmp("{\"execute\":\"cont\"}", r)) { err = "The runtime isn't running."; return false; }
+ return true;
+}
+
+bool RuntimeHost::ensure_running(std::string& err, uint64_t* took_ms) {
+ auto t0 = std::chrono::steady_clock::now();
+ auto done = [&] {
+ if (took_ms) *took_ms = static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - t0).count());
+ return true;
+ };
+ auto st = status();
+ if (st.state == RtState::NotInstalled) { err = "The macOS runtime isn't installed."; return false; }
+ // Setup drives the runtime itself (stops, boots Recovery, restarts): never start it alongside
+ // (two QEMUs on one disk) or change its options meanwhile.
+ if (std::filesystem::exists(root_ + "\\runtime\\config\\setup-running")) { err = "macOS is still being set up."; return false; }
+ if (st.state == RtState::Running || st.state == RtState::Starting) return done();
+ if (st.state == RtState::Paused) { if (!resume(err)) return false; return done(); }
+ std::lock_guard<std::mutex> l(mu_);
+ apply_profile();
+ std::string out;
+ if (reims("start " + vm_, &out) != 0) { err = "The macOS runtime didn't start."; return false; }
+ return done();
+}
+
+void RuntimeHost::apply_profile() {
+ // v1: frames pushed by QEMU's VNC server (key -> pixel ~46 ms instead of ~580 ms with
+ // screendumps), and zero writes stored as nothing (so the image can shrink). Before this was
+ // set here it existed only on the machine it was measured on.
+ // v2: the installed system disk on virtio-blk instead of emulated SATA (AHCI is slow under
+ // WHPX; boot 60 s -> 47 s). Tried once: "2-trial" until macOS is seen up on it
+ // (confirm_disk_profile), "2-ahci" when it wasn't and SATA was put back.
+ const std::string mark = vm_dir_ + "\\wsm-profile";
+ std::string all;
+ {
+ std::ifstream toml(vm_dir_ + "\\vm.toml"); // closed before reims-ctl rewrites it
+ all.assign(std::istreambuf_iterator<char>(toml), std::istreambuf_iterator<char>());
+ }
+ // Always, once installed: no window for macOS's screen (setup leaves it on; it showed the
+ // Apple logo and progress bar at every boot).
+ if (std::filesystem::exists(root_ + "\\runtime\\config\\runtime-ready.json") &&
+ all.find("REIMS_VGPU_WINDOW = \"0\"") == std::string::npos)
+ reims("set " + vm_ + " --env REIMS_VGPU_WINDOW=0");
+ // WSM's QEMU options, checked against vm.toml itself (setup replaces the extra args, so a
+ // marker file could claim options that are gone): frames pushed by QEMU's VNC server, zero
+ // writes stored as nothing (so the image can shrink), and two QMP sockets of WSM's own,
+ // held open for input and frame capture (QEMU serves one client per QMP socket).
+ if (all.find("wsm-cap.sock") == std::string::npos) {
+ std::string d = vm_dir_;
+ for (auto& c : d) if (c == '\\') c = '/';
+ reims("set " + vm_ + " --extra-args \"-vnc 127.0.0.1:15,display=gfx -set drive.disk.detect-zeroes=on"
+ " -qmp unix:" + d + "/wsm-in.sock,server=on,wait=off -qmp unix:" + d + "/wsm-cap.sock,server=on,wait=off\"");
+ }
+ std::string v = profile_state();
+ if (v.empty() || v == "0") {
+ v = "1";
+ std::ofstream(mark, std::ios::trunc) << v << "\n";
+ }
+ // Only once macOS is installed (setup ejects the installer first, as reims-ctl requires).
+ if (v == "1" && std::filesystem::exists(root_ + "\\runtime\\config\\runtime-ready.json") &&
+ reims("set " + vm_ + " --disk-controller virtio") == 0)
+ std::ofstream(mark, std::ios::trunc) << "2-trial\n";
+}
+
+std::string RuntimeHost::profile_state() const {
+ std::ifstream in(vm_dir_ + "\\wsm-profile");
+ std::string v;
+ std::getline(in, v);
+ while (!v.empty() && (v.back() == '\r' || v.back() == ' ')) v.pop_back();
+ return v;
+}
+
+void RuntimeHost::confirm_disk_profile(bool came_up) {
+ if (profile_state() != "2-trial") return;
+ const std::string mark = vm_dir_ + "\\wsm-profile";
+ if (came_up) { std::ofstream(mark, std::ios::trunc) << "2\n"; return; }
+ // macOS didn't come up on virtio: back to SATA for good, and start again.
+ std::string e;
+ {
+ std::lock_guard<std::mutex> l(mu_);
+ reims("stop " + vm_ + " --force");
+ reims("set " + vm_ + " --disk-controller ahci");
+ std::ofstream(mark, std::ios::trunc) << "2-ahci\n";
+ }
+ ensure_running(e);
+}
+
+bool RuntimeHost::compact(std::string& err, uint64_t* before_bytes, uint64_t* after_bytes) {
+ namespace fs = std::filesystem;
+ std::lock_guard<std::mutex> l(mu_);
+ if (pid()) { err = "The runtime must be stopped first."; return false; }
+ const std::string bin = root_ + "\\runtime\\reims-ctl\\qemu\\current\\bin\\qemu-img.exe";
+ const std::string disk = vm_dir_ + "\\disk.qcow2", tmp = vm_dir_ + "\\disk.compact.qcow2", old = vm_dir_ + "\\disk.old.qcow2";
+ std::error_code ec;
+ // Follow a link: the runtime's folder may live on another drive.
+ uint64_t before = fs::file_size(disk, ec);
+ if (ec) { err = "The runtime's disk wasn't found."; return false; }
+ // Enough room for the new file next to the old one (it ends up far smaller than this).
+ auto space = fs::space(vm_dir_, ec);
+ if (!ec && space.available < before / 2) { err = "Not enough free space to compact the runtime."; return false; }
+ fs::remove(tmp, ec);
+ auto run = [](const std::string& cmdline, DWORD timeout_ms) {
+ STARTUPINFOA si{}; si.cb = sizeof(si);
+ si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;
+ PROCESS_INFORMATION pi{};
+ std::string cl = cmdline;
+ if (!CreateProcessA(nullptr, cl.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW | BELOW_NORMAL_PRIORITY_CLASS,
+ nullptr, nullptr, &si, &pi)) return -1;
+ DWORD w = WaitForSingleObject(pi.hProcess, timeout_ms);
+ if (w != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 1);
+ DWORD code = 1;
+ GetExitCodeProcess(pi.hProcess, &code);
+ CloseHandle(pi.hThread); CloseHandle(pi.hProcess);
+ return static_cast<int>(code);
+ };
+ // Flattens any backing chain, skips unused and zero clusters, compresses the rest (zstd).
+ int rc = run("\"" + bin + "\" convert -c -m 8 -W -O qcow2 -o compression_type=zstd \"" + disk + "\" \"" + tmp + "\"",
+ 3 * 60 * 60 * 1000);
+ if (rc != 0 || run("\"" + bin + "\" check -q \"" + tmp + "\"", 30 * 60 * 1000) != 0) {
+ fs::remove(tmp, ec);
+ err = "The runtime's disk couldn't be compacted.";
+ return false;
+ }
+ fs::remove(old, ec);
+ fs::rename(disk, old, ec);
+ if (ec) { fs::remove(tmp, ec); err = "The runtime's disk is in use."; return false; }
+ fs::rename(tmp, disk, ec);
+ if (ec) { std::error_code e2; fs::rename(old, disk, e2); err = "The compacted disk couldn't be put in place."; return false; }
+ fs::remove(old, ec);
+ if (before_bytes) *before_bytes = before;
+ if (after_bytes) *after_bytes = fs::file_size(disk, ec);
+ return true;
+}
+
+bool RuntimeHost::shutdown(std::string& err) {
+ std::lock_guard<std::mutex> l(mu_);
+ if (!pid()) return true;
+ std::string r;
+ qmp("{\"execute\":\"cont\"}", r); // a paused guest can't hear the power button
+ if (reims("stop " + vm_) != 0) { err = "The runtime didn't shut down cleanly."; return false; }
+ return true;
+}
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/src/shell_integration.cpp b/src/wsm-runtime/src/shell_integration.cpp
new file mode 100644
index 0000000..26cd933
--- /dev/null
+++ b/src/wsm-runtime/src/shell_integration.cpp
@@ -0,0 +1,225 @@
+#include "wsm/shell_integration.hpp"
+
+#include <windows.h>
+#include <shlobj.h>
+#include <objbase.h>
+#include <wrl/client.h>
+#include <propkey.h>
+#include <propvarutil.h>
+
+#include <cstdint>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <thread>
+#include <vector>
+
+#pragma comment(lib, "ole32.lib")
+#pragma comment(lib, "shell32.lib")
+#pragma comment(lib, "advapi32.lib")
+#pragma comment(lib, "propsys.lib")
+
+namespace wsm::runtime {
+
+namespace {
+
+uint32_t read_be32(const uint8_t* p) noexcept {
+ return (static_cast<uint32_t>(p[0]) << 24) |
+ (static_cast<uint32_t>(p[1]) << 16) |
+ (static_cast<uint32_t>(p[2]) << 8) |
+ static_cast<uint32_t>(p[3]);
+}
+
+std::wstring utf8_to_wide(const std::string& s) {
+ if (s.empty()) return {};
+ int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), static_cast<int>(s.size()), nullptr, 0);
+ if (len <= 0) return {};
+ std::wstring out(static_cast<size_t>(len), L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), static_cast<int>(s.size()), out.data(), len);
+ return out;
+}
+
+bool set_hkcu_string(const std::string& subkey, const std::string& val_name, const std::string& data) {
+ HKEY hKey = nullptr;
+ if (RegCreateKeyExA(HKEY_CURRENT_USER, subkey.c_str(), 0, nullptr, 0, KEY_WRITE, nullptr, &hKey, nullptr) != ERROR_SUCCESS) {
+ return false;
+ }
+ LONG rc = RegSetValueExA(hKey, val_name.empty() ? nullptr : val_name.c_str(), 0, REG_SZ,
+ reinterpret_cast<const BYTE*>(data.c_str()),
+ static_cast<DWORD>(data.size() + 1));
+ RegCloseKey(hKey);
+ return rc == ERROR_SUCCESS;
+}
+
+} // namespace
+
+bool convert_icns_to_ico(const std::string& icns_path, const std::string& ico_out_path) {
+ std::ifstream f(icns_path, std::ios::binary);
+ if (!f) return false;
+ std::vector<uint8_t> data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ if (data.size() < 8 || std::memcmp(data.data(), "icns", 4) != 0) return false;
+
+ // Look for PNG-bearing icon chunks in descending resolution preference
+ // ic08 (256x256), ic09 (512x512), ic10 (1024x1024), ic07 (128x128)
+ const uint8_t png_sig[8] = {0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A};
+ std::vector<uint8_t> best_png;
+ int best_rank = -1;
+
+ size_t pos = 8;
+ while (pos + 8 <= data.size()) {
+ const char* tag = reinterpret_cast<const char*>(data.data() + pos);
+ uint32_t len = read_be32(data.data() + pos + 4);
+ if (len < 8 || pos + len > data.size()) break;
+
+ size_t payload_len = len - 8;
+ const uint8_t* payload = data.data() + pos + 8;
+ if (payload_len > 8 && std::memcmp(payload, png_sig, 8) == 0) {
+ int rank = 0;
+ if (std::memcmp(tag, "ic08", 4) == 0) rank = 4; // 256x256 ideal for Windows ICO
+ else if (std::memcmp(tag, "ic09", 4) == 0) rank = 3; // 512x512
+ else if (std::memcmp(tag, "ic07", 4) == 0) rank = 2; // 128x128
+ else if (std::memcmp(tag, "ic10", 4) == 0) rank = 1; // 1024x1024
+ if (rank > best_rank) {
+ best_rank = rank;
+ best_png.assign(payload, payload + payload_len);
+ }
+ }
+ pos += len;
+ }
+
+ if (best_png.empty()) return false;
+
+ std::filesystem::create_directories(std::filesystem::path(ico_out_path).parent_path());
+ std::ofstream out(ico_out_path, std::ios::binary | std::ios::trunc);
+ if (!out) return false;
+
+ // ICONDIR (6 bytes) + ICONDIRENTRY (16 bytes) + PNG payload
+ uint8_t hdr[22] = {};
+ hdr[2] = 1; // type = 1 (ICO)
+ hdr[4] = 1; // count = 1 image
+ hdr[6] = 0; // width = 256 (0 encodes 256 in ICO)
+ hdr[7] = 0; // height = 256
+ hdr[10] = 1; // planes
+ hdr[12] = 32; // bpp
+ uint32_t png_sz = static_cast<uint32_t>(best_png.size());
+ uint32_t offset = 22;
+ std::memcpy(hdr + 14, &png_sz, 4);
+ std::memcpy(hdr + 18, &offset, 4);
+
+ out.write(reinterpret_cast<const char*>(hdr), sizeof(hdr));
+ out.write(reinterpret_cast<const char*>(best_png.data()), best_png.size());
+ return out.good();
+}
+
+namespace {
+
+std::wstring launcher_exe_path() {
+ wchar_t buf[MAX_PATH]{};
+ GetModuleFileNameW(nullptr, buf, MAX_PATH);
+ return (std::filesystem::path(buf).parent_path() / L"wsmlaunch.exe").wstring();
+}
+
+// Windows forbids these in file names; a Mac app name can contain them (e.g. "Foo: Bar").
+std::wstring safe_file_name(const std::string& name) {
+ std::wstring w = utf8_to_wide(name);
+ for (auto& c : w) if (wcschr(L"<>:\"/\\|?*", c) || c < 32) c = L' ';
+ while (!w.empty() && (w.back() == L' ' || w.back() == L'.')) w.pop_back();
+ return w.empty() ? L"Mac app" : w;
+}
+
+std::filesystem::path known_folder(REFKNOWNFOLDERID id) {
+ PWSTR p = nullptr;
+ std::filesystem::path out;
+ if (SUCCEEDED(SHGetKnownFolderPath(id, 0, nullptr, &p))) out = p;
+ CoTaskMemFree(p);
+ return out;
+}
+
+bool write_link(const std::filesystem::path& lnk, const std::string& app_name, const std::string& bundle_id,
+ const std::string& ico_path) {
+ Microsoft::WRL::ComPtr<IShellLinkW> link;
+ if (FAILED(CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&link)))) return false;
+ std::wstring exe = launcher_exe_path();
+ link->SetPath(exe.c_str());
+ link->SetWorkingDirectory(std::filesystem::path(exe).parent_path().wstring().c_str());
+ link->SetArguments(utf8_to_wide("\"" + bundle_id + "\"").c_str());
+ link->SetDescription(utf8_to_wide(app_name).c_str());
+ if (!ico_path.empty() && std::filesystem::exists(ico_path)) link->SetIconLocation(utf8_to_wide(ico_path).c_str(), 0);
+ // Each Mac app gets its own taskbar identity, so it groups and pins as itself, not as WSM.
+ Microsoft::WRL::ComPtr<IPropertyStore> props;
+ if (SUCCEEDED(link.As(&props))) {
+ PROPVARIANT pv;
+ std::wstring aumid = utf8_to_wide("WSM.App." + bundle_id);
+ if (SUCCEEDED(InitPropVariantFromString(aumid.c_str(), &pv))) {
+ props->SetValue(PKEY_AppUserModel_ID, pv);
+ PropVariantClear(&pv);
+ props->Commit();
+ }
+ }
+ Microsoft::WRL::ComPtr<IPersistFile> persist;
+ return SUCCEEDED(link.As(&persist)) && SUCCEEDED(persist->Save(lnk.wstring().c_str(), TRUE));
+}
+
+template <typename F> void on_sta(F&& f) {
+ // COM shell objects need an STA; wsmd's request thread may be MTA.
+ std::thread t([&] {
+ HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
+ f();
+ if (SUCCEEDED(hr)) CoUninitialize();
+ });
+ t.join();
+}
+
+} // namespace
+
+bool create_app_start_menu_shortcut(const std::string& app_name,
+ const std::string& bundle_id,
+ const std::string& ico_path,
+ std::string& out_lnk_path) {
+ // Installed Mac apps appear exactly like Windows apps: their own entry at the top level of the
+ // Start menu and an icon on the Desktop, both with the app's real icon.
+ bool ok = false;
+ on_sta([&] {
+ std::wstring file = safe_file_name(app_name) + L".lnk";
+ auto start = known_folder(FOLDERID_Programs) / file;
+ auto desk = known_folder(FOLDERID_Desktop) / file;
+ ok = write_link(start, app_name, bundle_id, ico_path);
+ write_link(desk, app_name, bundle_id, ico_path);
+ out_lnk_path = start.string();
+ });
+ SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nullptr, nullptr);
+ return ok;
+}
+
+void remove_app_shortcuts(const std::string& app_name) {
+ std::wstring file = safe_file_name(app_name) + L".lnk";
+ std::error_code ec;
+ std::filesystem::remove(known_folder(FOLDERID_Programs) / file, ec);
+ std::filesystem::remove(known_folder(FOLDERID_Desktop) / file, ec);
+ std::filesystem::remove(known_folder(FOLDERID_Programs) / L"WSM Apps" / file, ec); // pre-0.2 location
+ SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nullptr, nullptr);
+}
+
+bool register_windows_shell_associations(const std::string& wsm_exe_path, std::string& err) {
+ struct Assoc { const char* ext; const char* prog_id; const char* desc; };
+ const Assoc list[] = {
+ {".dmg", "WSM.MacDiskImage", "macOS Disk Image (WSM)"},
+ {".pkg", "WSM.MacPackage", "macOS Installer Package (WSM)"},
+ {".app", "WSM.MacAppBundle", "macOS Application Bundle (WSM)"},
+ };
+
+ for (const auto& a : list) {
+ if (!set_hkcu_string(std::string("Software\\Classes\\") + a.ext, "", a.prog_id) ||
+ !set_hkcu_string(std::string("Software\\Classes\\") + a.prog_id, "", a.desc) ||
+ !set_hkcu_string(std::string("Software\\Classes\\") + a.prog_id + "\\shell\\open\\command",
+ "", "\"" + wsm_exe_path + "\" --install \"%1\"") ||
+ !set_hkcu_string(std::string("Software\\Classes\\") + a.prog_id + "\\DefaultIcon", "", "\"" + wsm_exe_path + "\",0")) {
+ err = std::string("Failed to write HKCU shell association for ") + a.ext;
+ return false;
+ }
+ }
+ SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nullptr, nullptr);
+ return true;
+}
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/src/webdav_server.cpp b/src/wsm-runtime/src/webdav_server.cpp
new file mode 100644
index 0000000..9a41706
--- /dev/null
+++ b/src/wsm-runtime/src/webdav_server.cpp
@@ -0,0 +1,622 @@
+#include "wsm/webdav_server.hpp"
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+
+#include <algorithm>
+#include <cctype>
+#include <cwctype>
+#include <cstdlib>
+#include <cstring>
+#include <ctime>
+#include <filesystem>
+#include <fstream>
+#include <map>
+#include <mutex>
+#include <sstream>
+#include <vector>
+
+namespace wsm::runtime {
+namespace fs = std::filesystem;
+
+namespace {
+
+// ---------------------------------------------------------------- text helpers
+
+std::wstring widen(const std::string& s) {
+ if (s.empty()) return {};
+ int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), static_cast<int>(s.size()), nullptr, 0);
+ std::wstring w(static_cast<size_t>(n), L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.data(), static_cast<int>(s.size()), w.data(), n);
+ return w;
+}
+
+std::string narrow(const std::wstring& w) {
+ if (w.empty()) return {};
+ int n = WideCharToMultiByte(CP_UTF8, 0, w.data(), static_cast<int>(w.size()), nullptr, 0, nullptr, nullptr);
+ std::string s(static_cast<size_t>(n), '\0');
+ WideCharToMultiByte(CP_UTF8, 0, w.data(), static_cast<int>(w.size()), s.data(), n, nullptr, nullptr);
+ return s;
+}
+
+std::string lower(std::string s) {
+ for (auto& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
+ return s;
+}
+
+std::string url_decode(const std::string& s) {
+ std::string o;
+ for (size_t i = 0; i < s.size(); ++i) {
+ if (s[i] == '%' && i + 2 < s.size() && std::isxdigit(static_cast<unsigned char>(s[i + 1])) &&
+ std::isxdigit(static_cast<unsigned char>(s[i + 2]))) {
+ o.push_back(static_cast<char>(std::stoi(s.substr(i + 1, 2), nullptr, 16)));
+ i += 2;
+ } else {
+ o.push_back(s[i]);
+ }
+ }
+ return o;
+}
+
+std::string url_encode_segment(const std::string& s) {
+ static const char* hex = "0123456789ABCDEF";
+ std::string o;
+ for (unsigned char c : s) {
+ if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') o.push_back(static_cast<char>(c));
+ else { o.push_back('%'); o.push_back(hex[c >> 4]); o.push_back(hex[c & 15]); }
+ }
+ return o;
+}
+
+std::string xml_escape(const std::string& s) {
+ std::string o;
+ for (char c : s) {
+ switch (c) {
+ case '&': o += "&amp;"; break;
+ case '<': o += "&lt;"; break;
+ case '>': o += "&gt;"; break;
+ case '"': o += "&quot;"; break;
+ default: o.push_back(c);
+ }
+ }
+ return o;
+}
+
+std::string http_date(std::time_t t) {
+ std::tm g{};
+ gmtime_s(&g, &t);
+ char b[64];
+ std::strftime(b, sizeof(b), "%a, %d %b %Y %H:%M:%S GMT", &g);
+ return b;
+}
+
+std::string iso_date(std::time_t t) {
+ std::tm g{};
+ gmtime_s(&g, &t);
+ char b[64];
+ std::strftime(b, sizeof(b), "%Y-%m-%dT%H:%M:%SZ", &g);
+ return b;
+}
+
+std::time_t to_time_t(fs::file_time_type ft) {
+ using namespace std::chrono;
+ auto sys = time_point_cast<system_clock::duration>(ft - fs::file_time_type::clock::now() + system_clock::now());
+ return system_clock::to_time_t(sys);
+}
+
+// macOS writes these next to every file on a network volume; they never reach Windows.
+bool is_mac_litter(const std::string& name) {
+ return name.rfind("._", 0) == 0 || name == ".DS_Store" || name == ".localized" || name == ".metadata_never_index" ||
+ name == ".Spotlight-V100" || name == ".Trashes" || name == ".fseventsd" || name == ".hidden";
+}
+
+// Windows files nobody can open, or that only confuse a Mac app.
+bool is_windows_system(const std::wstring& name) {
+ static const wchar_t* skip[] = {L"$recycle.bin", L"system volume information", L"pagefile.sys", L"hiberfil.sys",
+ L"swapfile.sys", L"dumpstack.log.tmp", L"dumpstack.log", L"$winreagent", L"config.msi",
+ L"recovery", L"$windows.~ws", L"$windows.~bt", L"$sysreset"};
+ std::wstring l = name;
+ for (auto& c : l) c = static_cast<wchar_t>(std::towlower(c));
+ for (auto* s : skip) if (l == s) return true;
+ return false;
+}
+
+// ---------------------------------------------------------------- socket helpers
+
+bool send_all(SOCKET s, const char* p, size_t n) {
+ while (n) {
+ int k = send(s, p, static_cast<int>(std::min<size_t>(n, 1 << 20)), 0);
+ if (k <= 0) return false;
+ p += k; n -= static_cast<size_t>(k);
+ }
+ return true;
+}
+bool send_all(SOCKET s, const std::string& d) { return send_all(s, d.data(), d.size()); }
+
+struct Conn {
+ SOCKET s;
+ std::string buf; // bytes received but not consumed yet
+ bool fill() {
+ char tmp[65536];
+ int k = recv(s, tmp, sizeof(tmp), 0);
+ if (k <= 0) return false;
+ buf.append(tmp, static_cast<size_t>(k));
+ return true;
+ }
+ bool read_line(std::string& line) {
+ for (;;) {
+ size_t nl = buf.find("\r\n");
+ if (nl != std::string::npos) { line = buf.substr(0, nl); buf.erase(0, nl + 2); return true; }
+ if (buf.size() > 65536 || !fill()) return false;
+ }
+ }
+ // Calls sink(data, n) for exactly n bytes of body.
+ template <class F> bool read_body(uint64_t n, F&& sink) {
+ while (n) {
+ if (buf.empty() && !fill()) return false;
+ size_t k = static_cast<size_t>(std::min<uint64_t>(n, buf.size()));
+ if (!sink(buf.data(), k)) return false;
+ buf.erase(0, k);
+ n -= k;
+ }
+ return true;
+ }
+ template <class F> bool read_chunked(F&& sink) {
+ for (;;) {
+ std::string line;
+ if (!read_line(line)) return false;
+ uint64_t n = std::strtoull(line.c_str(), nullptr, 16);
+ if (n == 0) { std::string t; while (read_line(t) && !t.empty()) {} return true; }
+ if (!read_body(n, sink)) return false;
+ std::string crlf;
+ if (!read_line(crlf)) return false;
+ }
+ }
+};
+
+struct Request {
+ std::string method, path, version;
+ std::map<std::string, std::string> h; // lower-case names
+ std::string header(const std::string& k) const { auto it = h.find(k); return it == h.end() ? std::string() : it->second; }
+};
+
+std::string response(int code, const char* reason, const std::string& body = {}, const std::string& type = {},
+ const std::string& extra = {}) {
+ std::ostringstream o;
+ o << "HTTP/1.1 " << code << " " << reason << "\r\n"
+ << "Server: WSM\r\nDAV: 1,2\r\nMS-Author-Via: DAV\r\n"
+ << "Content-Length: " << body.size() << "\r\n";
+ if (!type.empty()) o << "Content-Type: " << type << "\r\n";
+ o << extra << "\r\n" << body;
+ return o.str();
+}
+
+// ---------------------------------------------------------------- path mapping
+
+// "/C/Users/x" (decoded, after the token) -> C:\Users\x. Empty path = the drive list.
+struct Target {
+ bool root = false; // the list of drives
+ bool litter = false; // a macOS AppleDouble/.DS_Store name: accepted, never stored
+ fs::path path; // otherwise the Windows path
+ std::vector<std::string> segs;
+};
+
+bool map_path(const std::string& rel, Target& t) {
+ std::vector<std::string> segs;
+ std::string cur;
+ for (char c : rel + "/") {
+ if (c == '/') { if (!cur.empty()) segs.push_back(cur); cur.clear(); }
+ else cur.push_back(c);
+ }
+ for (auto& s : segs) {
+ if (s == "." || s == "..") return false;
+ for (unsigned char c : s) if (c < 0x20 || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') return false;
+ }
+ t.segs = segs;
+ if (segs.empty()) { t.root = true; return true; }
+ if (segs[0].size() != 1 || !std::isalpha(static_cast<unsigned char>(segs[0][0]))) return false;
+ std::wstring p = widen(std::string(1, static_cast<char>(std::toupper(static_cast<unsigned char>(segs[0][0])))) + ":\\");
+ for (size_t i = 1; i < segs.size(); ++i) {
+ p += widen(segs[i]);
+ if (i + 1 < segs.size()) p += L"\\";
+ }
+ t.path = fs::path(p);
+ t.litter = segs.size() > 1 && is_mac_litter(segs.back());
+ return true;
+}
+
+std::vector<std::string> drives() {
+ std::vector<std::string> d;
+ DWORD mask = GetLogicalDrives();
+ for (int i = 0; i < 26; ++i) {
+ if (!(mask & (1u << i))) continue;
+ wchar_t root[4] = {static_cast<wchar_t>(L'A' + i), L':', L'\\', 0};
+ UINT type = GetDriveTypeW(root);
+ if (type == DRIVE_FIXED || type == DRIVE_REMOVABLE) d.push_back(std::string(1, static_cast<char>('A' + i)));
+ }
+ return d;
+}
+
+std::string mime_of(const fs::path& p) {
+ std::string e = lower(narrow(p.extension().wstring()));
+ static const std::map<std::string, std::string> m = {
+ {".txt", "text/plain"}, {".html", "text/html"}, {".htm", "text/html"}, {".css", "text/css"},
+ {".js", "text/javascript"}, {".json", "application/json"}, {".png", "image/png"}, {".jpg", "image/jpeg"},
+ {".jpeg", "image/jpeg"}, {".gif", "image/gif"}, {".pdf", "application/pdf"}, {".mp4", "video/mp4"},
+ {".mov", "video/quicktime"}, {".mp3", "audio/mpeg"}, {".zip", "application/zip"}, {".svg", "image/svg+xml"}};
+ auto it = m.find(e);
+ return it == m.end() ? "application/octet-stream" : it->second;
+}
+
+// One <D:response> of a PROPFIND.
+std::string prop_entry(const std::string& href, const std::string& name, bool dir, uint64_t size, std::time_t mtime,
+ uint64_t quota_free = 0, uint64_t quota_used = 0, bool quota = false, const std::string& type = {}) {
+ std::ostringstream o;
+ o << "<D:response><D:href>" << xml_escape(href) << "</D:href><D:propstat><D:prop>"
+ << "<D:displayname>" << xml_escape(name) << "</D:displayname>"
+ << (dir ? "<D:resourcetype><D:collection/></D:resourcetype>" : "<D:resourcetype/>")
+ << "<D:getlastmodified>" << http_date(mtime) << "</D:getlastmodified>"
+ << "<D:creationdate>" << iso_date(mtime) << "</D:creationdate>";
+ if (!dir) {
+ o << "<D:getcontentlength>" << size << "</D:getcontentlength>"
+ << "<D:getcontenttype>" << type << "</D:getcontenttype>"
+ << "<D:getetag>\"" << std::hex << (static_cast<uint64_t>(mtime) ^ (size << 20)) << std::dec << "\"</D:getetag>";
+ }
+ if (quota) o << "<D:quota-available-bytes>" << quota_free << "</D:quota-available-bytes><D:quota-used-bytes>" << quota_used << "</D:quota-used-bytes>";
+ o << "<D:supportedlock><D:lockentry><D:lockscope><D:exclusive/></D:lockscope><D:locktype><D:write/></D:locktype></D:lockentry></D:supportedlock>"
+ << "<D:lockdiscovery/></D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>";
+ return o.str();
+}
+
+// AppleDouble / Finder files, by lower-case Windows path (one server per process).
+std::map<std::string, std::string>& litter_store() { static std::map<std::string, std::string> m; return m; }
+std::mutex& litter_mu() { static std::mutex m; return m; }
+
+bool dest_target(const Request& r, const std::string& token, Target& t) {
+ std::string d = r.header("destination");
+ size_t scheme = d.find("://");
+ if (scheme != std::string::npos) {
+ size_t slash = d.find('/', scheme + 3);
+ d = slash == std::string::npos ? "/" : d.substr(slash);
+ }
+ d = url_decode(d);
+ const std::string pre = "/" + token;
+ if (d.rfind(pre, 0) != 0) return false;
+ return map_path(d.substr(pre.size()), t);
+}
+
+} // namespace
+
+WebDavServer::WebDavServer(uint16_t port, std::string token) : port_(port), token_(std::move(token)) {}
+WebDavServer::~WebDavServer() { stop(); }
+
+bool WebDavServer::start(std::string& err) {
+ if (running_.load()) return true;
+ WSADATA w{};
+ WSAStartup(MAKEWORD(2, 2), &w);
+ SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (s == INVALID_SOCKET) { err = "socket"; return false; }
+ BOOL excl = TRUE;
+ setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast<const char*>(&excl), sizeof(excl));
+ sockaddr_in a{};
+ a.sin_family = AF_INET;
+ a.sin_port = htons(port_);
+ a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // only this PC (and the runtime through QEMU)
+ if (bind(s, reinterpret_cast<sockaddr*>(&a), sizeof(a)) != 0 || listen(s, 16) != 0) {
+ err = "port " + std::to_string(port_) + " is in use";
+ closesocket(s);
+ return false;
+ }
+ listen_ = static_cast<uintptr_t>(s);
+ running_.store(true);
+ acceptor_ = std::thread(&WebDavServer::accept_loop, this);
+ return true;
+}
+
+void WebDavServer::stop() {
+ if (!running_.exchange(false)) return;
+ closesocket(static_cast<SOCKET>(listen_));
+ if (acceptor_.joinable()) acceptor_.join();
+}
+
+void WebDavServer::accept_loop() {
+ while (running_.load()) {
+ SOCKET c = accept(static_cast<SOCKET>(listen_), nullptr, nullptr);
+ if (c == INVALID_SOCKET) { if (!running_.load()) break; Sleep(50); continue; }
+ if (clients_.load() >= 32) { closesocket(c); continue; }
+ clients_.fetch_add(1);
+ std::thread([this, c] { serve(static_cast<uintptr_t>(c)); clients_.fetch_sub(1); }).detach();
+ }
+}
+
+void WebDavServer::serve(uintptr_t sock) {
+ SOCKET s = static_cast<SOCKET>(sock);
+ DWORD to = 120000;
+ setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&to), sizeof(to));
+ Conn c{s, {}};
+ const std::string pre = "/" + token_;
+
+ for (;;) {
+ // ---- request line and headers
+ Request r;
+ std::string line;
+ if (!c.read_line(line)) break;
+ if (line.empty()) continue;
+ {
+ std::istringstream rl(line);
+ rl >> r.method >> r.path >> r.version;
+ }
+ bool bad = false;
+ while (c.read_line(line) && !line.empty()) {
+ size_t colon = line.find(':');
+ if (colon == std::string::npos) { bad = true; continue; }
+ std::string v = line.substr(colon + 1);
+ while (!v.empty() && v.front() == ' ') v.erase(0, 1);
+ r.h[lower(line.substr(0, colon))] = v;
+ }
+ if (bad || r.method.empty()) break;
+ const bool close_after = lower(r.header("connection")) == "close";
+ const bool chunked = lower(r.header("transfer-encoding")).find("chunked") != std::string::npos;
+ const uint64_t clen = std::strtoull(r.header("content-length").c_str(), nullptr, 10);
+
+ // Reads (or skips) the body before answering, so the connection stays in step.
+ std::string small_body;
+ auto collect = [&](const char* p, size_t n) { if (small_body.size() < (1 << 20)) small_body.append(p, n); return true; };
+ auto drain = [&] { return chunked ? c.read_chunked(collect) : c.read_body(clen, collect); };
+
+ std::string path = r.path;
+ size_t q = path.find('?');
+ if (q != std::string::npos) path.erase(q);
+ path = url_decode(path);
+ Target t;
+ bool ok_path = path.rfind(pre, 0) == 0 && (path.size() == pre.size() || path[pre.size()] == '/') &&
+ map_path(path.substr(pre.size()), t);
+ std::string out;
+
+ if (!enabled_.load() || !ok_path) {
+ drain();
+ out = response(!enabled_.load() ? 403 : 404, !enabled_.load() ? "Forbidden" : "Not Found");
+ send_all(s, out);
+ break;
+ }
+ // href of the target, as the client should see it.
+ std::string href = pre + "/";
+ for (size_t i = 0; i < t.segs.size(); ++i) href += url_encode_segment(t.segs[i]) + (i + 1 < t.segs.size() ? "/" : "");
+ std::error_code ec;
+
+ // macOS's AppleDouble ("._name") and Finder files: kept in memory, never on the Windows
+ // drive. macOS writes one next to a file before opening it and reads it back; when that
+ // read failed it reported the file itself as "no permission".
+ if (t.litter) {
+ const std::string key = lower(narrow(t.path.wstring()));
+ auto& store = litter_store();
+ std::unique_lock<std::mutex> lk(litter_mu());
+ auto it = store.find(key);
+ if (r.method == "PUT") {
+ std::string data;
+ lk.unlock();
+ auto keep = [&](const char* p, size_t n) { if (data.size() < (1u << 20)) data.append(p, n); return true; };
+ if (!(chunked ? c.read_chunked(keep) : c.read_body(clen, keep))) break;
+ lk.lock();
+ bool existed = store.count(key) != 0;
+ if (store.size() < 20000) store[key] = std::move(data);
+ out = existed ? response(204, "No Content") : response(201, "Created");
+ } else {
+ drain();
+ if (r.method == "DELETE") { if (it != store.end()) store.erase(it); out = response(204, "No Content"); }
+ else if (r.method == "LOCK" || r.method == "UNLOCK" || r.method == "PROPPATCH" || r.method == "OPTIONS")
+ out = r.method == "UNLOCK" ? response(204, "No Content") : response(200, "OK", {}, {},
+ r.method == "LOCK" ? "Lock-Token: <opaquelocktoken:wsm-litter>\r\n" : "");
+ else if (it == store.end()) out = response(404, "Not Found");
+ else if (r.method == "PROPFIND")
+ out = response(207, "Multi-Status", "<?xml version=\"1.0\" encoding=\"utf-8\"?><D:multistatus xmlns:D=\"DAV:\">" +
+ prop_entry(href, t.segs.back(), false, it->second.size(), std::time(nullptr), 0, 0, false,
+ "application/octet-stream") + "</D:multistatus>", "application/xml; charset=utf-8");
+ else if (r.method == "GET" || r.method == "HEAD")
+ out = response(200, "OK", r.method == "GET" ? it->second : std::string(), "application/octet-stream");
+ else if (r.method == "MOVE" || r.method == "COPY") {
+ Target d;
+ if (dest_target(r, token_, d) && d.litter) {
+ std::string v = it->second;
+ if (r.method == "MOVE") store.erase(it);
+ store[lower(narrow(d.path.wstring()))] = std::move(v);
+ }
+ out = response(201, "Created");
+ } else out = response(405, "Method Not Allowed");
+ }
+ if (!send_all(s, out) || close_after) break;
+ continue;
+ }
+
+ const bool exists = t.root || fs::exists(t.path, ec);
+ const bool is_dir = t.root || (exists && fs::is_directory(t.path, ec));
+
+ if (r.method == "OPTIONS") {
+ drain();
+ out = response(200, "OK", {}, {}, "Allow: OPTIONS, GET, HEAD, PUT, DELETE, MKCOL, COPY, MOVE, PROPFIND, PROPPATCH, LOCK, UNLOCK\r\n");
+ } else if (r.method == "PROPFIND") {
+ drain();
+ if (!exists) {
+ out = response(404, "Not Found");
+ } else {
+ std::string depth = r.header("depth");
+ bool children = is_dir && depth != "0";
+ std::string body = "<?xml version=\"1.0\" encoding=\"utf-8\"?><D:multistatus xmlns:D=\"DAV:\">";
+ if (t.root) {
+ body += prop_entry(pre + "/", "Windows", true, 0, std::time(nullptr));
+ if (children)
+ for (auto& d : drives()) {
+ ULARGE_INTEGER fr{}, tot{};
+ GetDiskFreeSpaceExW(widen(d + ":\\").c_str(), &fr, &tot, nullptr);
+ body += prop_entry(pre + "/" + d + "/", d, true, 0, std::time(nullptr), fr.QuadPart,
+ tot.QuadPart - fr.QuadPart, true);
+ }
+ } else {
+ std::string self_href = href + (is_dir ? "/" : "");
+ std::string name = t.segs.size() == 1 ? t.segs[0] : t.segs.back();
+ uint64_t sz = is_dir ? 0 : fs::file_size(t.path, ec);
+ std::time_t mt = to_time_t(fs::last_write_time(t.path, ec));
+ if (t.segs.size() == 1) {
+ ULARGE_INTEGER fr{}, tot{};
+ GetDiskFreeSpaceExW(t.path.wstring().c_str(), &fr, &tot, nullptr);
+ body += prop_entry(self_href, name, true, 0, mt, fr.QuadPart, tot.QuadPart - fr.QuadPart, true);
+ } else {
+ body += prop_entry(self_href, name, is_dir, sz, mt, 0, 0, false, mime_of(t.path));
+ }
+ if (children) {
+ for (auto it = fs::directory_iterator(t.path, fs::directory_options::skip_permission_denied, ec);
+ !ec && it != fs::directory_iterator(); it.increment(ec)) {
+ std::wstring wn = it->path().filename().wstring();
+ if (is_windows_system(wn)) continue;
+ std::string n = narrow(wn);
+ if (is_mac_litter(n)) continue;
+ std::error_code e2;
+ bool d = it->is_directory(e2);
+ if (e2) continue;
+ uint64_t fsz = d ? 0 : it->file_size(e2);
+ if (e2) continue;
+ std::time_t m = to_time_t(it->last_write_time(e2));
+ body += prop_entry(href + "/" + url_encode_segment(n) + (d ? "/" : ""), n, d, fsz, m, 0, 0, false,
+ d ? std::string() : mime_of(it->path()));
+ }
+ }
+ }
+ body += "</D:multistatus>";
+ out = response(207, "Multi-Status", body, "application/xml; charset=utf-8");
+ }
+ } else if (r.method == "GET" || r.method == "HEAD") {
+ drain();
+ if (!exists) {
+ out = response(404, "Not Found");
+ } else if (is_dir) {
+ out = response(200, "OK", "<html><body>WSM: Windows drives for macOS.</body></html>", "text/html");
+ } else {
+ uint64_t size = fs::file_size(t.path, ec);
+ uint64_t from = 0, to_ = size ? size - 1 : 0;
+ bool ranged = false;
+ std::string range = r.header("range");
+ if (range.rfind("bytes=", 0) == 0 && size) {
+ std::string spec = range.substr(6);
+ size_t dash = spec.find('-');
+ if (dash != std::string::npos) {
+ std::string a = spec.substr(0, dash), b = spec.substr(dash + 1);
+ if (a.empty()) { uint64_t n = std::strtoull(b.c_str(), nullptr, 10); from = n >= size ? 0 : size - n; }
+ else { from = std::strtoull(a.c_str(), nullptr, 10); if (!b.empty()) to_ = std::min<uint64_t>(std::strtoull(b.c_str(), nullptr, 10), size - 1); }
+ ranged = from <= to_ && from < size;
+ }
+ }
+ uint64_t len = size ? (to_ - from + 1) : 0;
+ std::ostringstream hd;
+ hd << "HTTP/1.1 " << (ranged ? "206 Partial Content" : "200 OK") << "\r\nServer: WSM\r\nAccept-Ranges: bytes\r\n"
+ << "Content-Type: " << mime_of(t.path) << "\r\nContent-Length: " << len << "\r\n"
+ << "Last-Modified: " << http_date(to_time_t(fs::last_write_time(t.path, ec))) << "\r\n";
+ if (ranged) hd << "Content-Range: bytes " << from << "-" << to_ << "/" << size << "\r\n";
+ hd << "\r\n";
+ if (!send_all(s, hd.str())) break;
+ if (r.method == "GET" && len) {
+ std::ifstream f(t.path, std::ios::binary);
+ f.seekg(static_cast<std::streamoff>(from));
+ std::vector<char> b(1 << 20);
+ uint64_t left = len;
+ bool okw = true;
+ while (left && f && okw) {
+ f.read(b.data(), static_cast<std::streamsize>(std::min<uint64_t>(left, b.size())));
+ std::streamsize got = f.gcount();
+ if (got <= 0) break;
+ okw = send_all(s, b.data(), static_cast<size_t>(got));
+ left -= static_cast<uint64_t>(got);
+ }
+ if (!okw || left) break; // the client can't trust this connection any more
+ }
+ if (close_after) break;
+ continue;
+ }
+ } else if (r.method == "PUT") {
+ if (t.root || t.segs.size() < 2) {
+ drain(); out = response(403, "Forbidden");
+ } else if (t.litter) {
+ if (!(chunked ? c.read_chunked([](const char*, size_t) { return true; })
+ : c.read_body(clen, [](const char*, size_t) { return true; }))) break;
+ out = response(201, "Created");
+ } else if (!fs::is_directory(t.path.parent_path(), ec)) {
+ drain(); out = response(409, "Conflict");
+ } else {
+ const bool existed = exists;
+ std::ofstream f(t.path, std::ios::binary | std::ios::trunc);
+ auto write = [&](const char* p, size_t n) { f.write(p, static_cast<std::streamsize>(n)); return true; };
+ bool got = chunked ? c.read_chunked(write) : c.read_body(clen, write);
+ bool wrote = static_cast<bool>(f);
+ f.close();
+ if (!got) break;
+ out = !wrote ? response(403, "Forbidden") : existed ? response(204, "No Content") : response(201, "Created");
+ }
+ } else if (r.method == "DELETE") {
+ drain();
+ if (t.root || t.segs.size() < 2) out = response(403, "Forbidden");
+ else if (t.litter) out = response(204, "No Content");
+ else if (!exists) out = response(404, "Not Found");
+ else { fs::remove_all(t.path, ec); out = ec ? response(403, "Forbidden") : response(204, "No Content"); }
+ } else if (r.method == "MKCOL") {
+ drain();
+ if (t.root || t.segs.size() < 2 || t.litter) out = response(403, "Forbidden");
+ else if (exists) out = response(405, "Method Not Allowed");
+ else if (!fs::is_directory(t.path.parent_path(), ec)) out = response(409, "Conflict");
+ else out = fs::create_directory(t.path, ec) ? response(201, "Created") : response(403, "Forbidden");
+ } else if (r.method == "MOVE" || r.method == "COPY") {
+ drain();
+ Target d;
+ bool overwrite = lower(r.header("overwrite")) != "f";
+ if (t.root || t.segs.size() < 2 || !dest_target(r, token_, d) || d.root || d.segs.size() < 2) {
+ out = response(403, "Forbidden");
+ } else if (t.litter || d.litter) {
+ out = response(201, "Created");
+ } else if (!exists) {
+ out = response(404, "Not Found");
+ } else {
+ bool dest_existed = fs::exists(d.path, ec);
+ if (dest_existed && !overwrite) {
+ out = response(412, "Precondition Failed");
+ } else {
+ if (dest_existed) fs::remove_all(d.path, ec);
+ ec.clear();
+ if (r.method == "MOVE") fs::rename(t.path, d.path, ec);
+ else fs::copy(t.path, d.path, fs::copy_options::recursive | fs::copy_options::overwrite_existing, ec);
+ out = ec ? response(409, "Conflict") : dest_existed ? response(204, "No Content") : response(201, "Created");
+ }
+ }
+ } else if (r.method == "PROPPATCH") {
+ drain();
+ std::string body = "<?xml version=\"1.0\" encoding=\"utf-8\"?><D:multistatus xmlns:D=\"DAV:\"><D:response><D:href>" +
+ xml_escape(href) + "</D:href><D:propstat><D:prop/><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response></D:multistatus>";
+ out = response(207, "Multi-Status", body, "application/xml; charset=utf-8");
+ } else if (r.method == "LOCK") {
+ drain();
+ // Locks are advisory only (one user, one Mac); macOS needs class 2 to mount read-write.
+ char tok[64];
+ snprintf(tok, sizeof(tok), "opaquelocktoken:wsm-%08lx-%08lx", static_cast<unsigned long>(GetTickCount()),
+ static_cast<unsigned long>(reinterpret_cast<uintptr_t>(&c) & 0xffffffff));
+ std::string body = std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?><D:prop xmlns:D=\"DAV:\"><D:lockdiscovery><D:activelock>") +
+ "<D:locktype><D:write/></D:locktype><D:lockscope><D:exclusive/></D:lockscope><D:depth>0</D:depth>" +
+ "<D:timeout>Second-3600</D:timeout><D:locktoken><D:href>" + tok + "</D:href></D:locktoken>" +
+ "</D:activelock></D:lockdiscovery></D:prop>";
+ if (!exists && !t.root && !t.litter && t.segs.size() >= 2 && fs::is_directory(t.path.parent_path(), ec))
+ std::ofstream(t.path, std::ios::binary | std::ios::app); // LOCK on a new name creates it
+ out = response(200, "OK", body, "application/xml; charset=utf-8", std::string("Lock-Token: <") + tok + ">\r\n");
+ } else if (r.method == "UNLOCK") {
+ drain();
+ out = response(204, "No Content");
+ } else {
+ drain();
+ out = response(405, "Method Not Allowed");
+ }
+ if (const char* lg = std::getenv("WSM_SHARE_LOG")) { // diagnostics: one line per request
+ std::ofstream(lg, std::ios::app) << r.method << " " << path.substr(pre.size()) << " -> " << out.substr(9, 3)
+ << " depth=" << r.header("depth") << "\n";
+ }
+ if (!send_all(s, out) || close_after) break;
+ }
+ closesocket(s);
+}
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/src/window_streamer.cpp b/src/wsm-runtime/src/window_streamer.cpp
new file mode 100644
index 0000000..c4ff826
--- /dev/null
+++ b/src/wsm-runtime/src/window_streamer.cpp
@@ -0,0 +1,1377 @@
+#include "wsm/window_streamer.hpp"
+#include "wsm/qmp_unix.hpp"
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#include <tlhelp32.h>
+
+#include <chrono>
+#include <cstdio>
+#include <cstring>
+#include <fstream>
+#include <sstream>
+#include <filesystem>
+#include <algorithm>
+#include <climits>
+#include <tuple>
+#include <cstdlib>
+#include <cctype>
+#include <set>
+
+namespace wsm::runtime {
+
+namespace {
+
+std::string b64_decode(const std::string& in) {
+ static int T[256]; static bool init = false;
+ if (!init) {
+ for (int& v : T) v = -1;
+ const char* a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ for (int i = 0; i < 64; ++i) T[static_cast<unsigned char>(a[i])] = i;
+ init = true;
+ }
+ std::string out; int val = 0, bits = -8;
+ for (unsigned char c : in) {
+ if (T[c] < 0) continue;
+ val = (val << 6) + T[c]; bits += 6;
+ if (bits >= 0) { out.push_back(static_cast<char>((val >> bits) & 0xFF)); bits -= 8; }
+ }
+ return out;
+}
+
+std::string b64_encode(const std::string& in) {
+ const char* a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ std::string out; int val = 0, bits = -6;
+ for (unsigned char c : in) {
+ val = (val << 8) + c; bits += 8;
+ while (bits >= 0) { out.push_back(a[(val >> bits) & 0x3F]); bits -= 6; }
+ }
+ if (bits > -6) out.push_back(a[((val << 8) >> (bits + 8)) & 0x3F]);
+ while (out.size() % 4) out.push_back('=');
+ return out;
+}
+
+const char* const kDisconnected = "\x01"; // apply_window_list: watcher lost the runtime
+
+int64_t now_ms() {
+ return std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+
+// Runtime-side window reporter. Prints "S <w> <h>" once, then "W <list>" whenever the set of
+// windows or their geometry changes ("K" as a keepalive otherwise). Entries are
+// wid|pid|layer|x|y|w|h|owner|bundle, separated by ';'. Runs until the SSH session closes.
+const char* kWindowScript = R"JXA(
+ObjC.import('CoreGraphics'); ObjC.import('AppKit');
+var so = $.NSFileHandle.fileHandleWithStandardOutput;
+function out(s) { so.writeData($(s + "\n").dataUsingEncoding($.NSUTF8StringEncoding)); }
+// The runtime's desktop is one flat colour. Nothing else is ever shown, and the host turns
+// that colour transparent where it shows through a window's rounded corners.
+try {
+ var dir = "/Users/wsm/Library/Application Support/WSM", png = dir + "/backdrop.png";
+ var fm = $.NSFileManager.defaultManager;
+ fm.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(dir, true, $(), null);
+ if (!fm.fileExistsAtPath(png)) {
+ var rep = $.NSBitmapImageRep.alloc.initWithBitmapDataPlanesPixelsWidePixelsHighBitsPerSampleSamplesPerPixelHasAlphaIsPlanarColorSpaceNameBytesPerRowBitsPerPixel(
+ null, 8, 8, 8, 3, false, false, "NSDeviceRGBColorSpace", 0, 0);
+ var c = $.NSColor.colorWithDeviceRedGreenBlueAlpha(18/255, 20/255, 22/255, 1);
+ for (var y = 0; y < 8; y++) for (var x = 0; x < 8; x++) rep.setColorAtXY(c, x, y);
+ rep.representationUsingTypeProperties(4 /* PNG */, $()).writeToFileAtomically(png, true);
+ }
+ var u = $.NSURL.fileURLWithPath(png), ws = $.NSWorkspace.sharedWorkspace, sc = $.NSScreen.mainScreen;
+ var cur = ws.desktopImageURLForScreen(sc);
+ if (!cur || cur.isNil() || ObjC.unwrap(cur.path) != png) ws.setDesktopImageURLForScreenOptionsError(u, sc, $(), null);
+} catch (e) {}
+var f = $.NSScreen.mainScreen.frame;
+out("S " + Math.round(f.size.width) + " " + Math.round(f.size.height));
+var skip = {"Window Server":1,"Dock":1,"SystemUIServer":1,"Control Center":1,"Spotlight":1,
+ "Notification Center":1,"NotificationCenter":1,"WindowManager":1,"Wallpaper":1,"loginwindow":1,
+ "TextInputMenuAgent":1,"TextInputSwitcher":1,"universalAccessAuthWarn":1,"CursorUIViewService":1,
+ "Finder":1,"KeyboardSetupAssistant":1,"Installer Progress":1,"Setup Assistant":1,"SetupAssistantSpringboard":1};
+var bundles = {};
+function bid(pid) {
+ if (bundles[pid] !== undefined) return bundles[pid];
+ var a = $.NSRunningApplication.runningApplicationWithProcessIdentifier(pid);
+ var b = (a && a.bundleIdentifier && !a.bundleIdentifier.isNil()) ? ObjC.unwrap(a.bundleIdentifier) : "";
+ bundles[pid] = b; return b;
+}
+var last = "", n = 0;
+var pb = $.NSPasteboard.generalPasteboard, pbCount = pb.changeCount;
+while (true) {
+ if (pb.changeCount != pbCount) { // the app copied something: send it to Windows
+ pbCount = pb.changeCount;
+ var t = pb.stringForType("public.utf8-plain-text");
+ if (t && !t.isNil() && t.length < 1000000)
+ out("C " + ObjC.unwrap(t.dataUsingEncoding($.NSUTF8StringEncoding).base64EncodedStringWithOptions(0)));
+ }
+ var l = ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo(1 | 16, 0))) || [];
+ var r = [];
+ for (var i = l.length - 1; i >= 0; i--) { // back to front
+ var w = l[i], L = w.kCGWindowLayer, o = w.kCGWindowOwnerName || "";
+ // App windows, panels and menus (up to 101); never macOS's own overlays above that (the
+ // first-login "Installer Progress" Apple logo is at 993-996 and covers the whole screen).
+ if (L < 0 || L >= 500 || L == 20 || L == 24 || L == 25) continue;
+ if (skip[o] || w.kCGWindowAlpha === 0) continue;
+ var b = w.kCGWindowBounds;
+ if (b.Width < 24 || b.Height < 16) continue;
+ if (b.Width > 2 * f.size.width || b.Height > 2 * f.size.height) continue; // backdrops, not windows
+ r.push([w.kCGWindowNumber, w.kCGWindowOwnerPID, L, Math.round(b.X), Math.round(b.Y),
+ Math.round(b.Width), Math.round(b.Height), o.replace(/[|;]/g, " "), bid(w.kCGWindowOwnerPID)].join("|"));
+ }
+ var s = r.join(";");
+ if (s != last || ++n % 40 == 0) { out("W " + s); last = s; } else out("K");
+ delay(0.1);
+}
+)JXA";
+
+std::string vk_to_qcode(uint32_t vk) {
+ if (vk >= 'A' && vk <= 'Z') return std::string(1, static_cast<char>(vk - 'A' + 'a'));
+ if (vk >= '0' && vk <= '9') return std::string(1, static_cast<char>(vk));
+ if (vk >= VK_F1 && vk <= VK_F12) return "f" + std::to_string(vk - VK_F1 + 1);
+ if (vk >= VK_NUMPAD0 && vk <= VK_NUMPAD9) return "kp_" + std::to_string(vk - VK_NUMPAD0);
+ switch (vk) {
+ case VK_RETURN: return "ret"; case VK_TAB: return "tab";
+ case VK_SPACE: return "spc"; case VK_BACK: return "backspace";
+ case VK_ESCAPE: return "esc"; case VK_DELETE: return "delete";
+ case VK_INSERT: return "insert"; case VK_HOME: return "home";
+ case VK_END: return "end"; case VK_PRIOR: return "pgup";
+ case VK_NEXT: return "pgdn"; case VK_LEFT: return "left";
+ case VK_RIGHT: return "right"; case VK_UP: return "up";
+ case VK_DOWN: return "down"; case VK_CAPITAL: return "caps_lock";
+ // Windows Ctrl acts as Command and the Windows key as Control, so the usual
+ // shortcuts (Ctrl+C, Ctrl+S, Ctrl+Z ...) do what a Windows user expects.
+ case VK_CONTROL: case VK_LCONTROL: return "meta_l";
+ case VK_RCONTROL: return "meta_r";
+ case VK_LWIN: return "ctrl"; case VK_RWIN: return "ctrl_r";
+ case VK_SHIFT: case VK_LSHIFT: return "shift";
+ case VK_RSHIFT: return "shift_r";
+ case VK_MENU: case VK_LMENU: return "alt";
+ case VK_RMENU: return "alt_r";
+ case VK_OEM_1: return "semicolon"; case VK_OEM_PLUS: return "equal";
+ case VK_OEM_COMMA: return "comma"; case VK_OEM_MINUS: return "minus";
+ case VK_OEM_PERIOD: return "dot"; case VK_OEM_2: return "slash";
+ case VK_OEM_3: return "grave_accent"; case VK_OEM_4: return "bracket_left";
+ case VK_OEM_5: return "backslash"; case VK_OEM_6: return "bracket_right";
+ case VK_OEM_7: return "apostrophe"; case VK_OEM_102: return "less";
+ case VK_MULTIPLY: return "kp_multiply"; case VK_ADD: return "kp_add";
+ case VK_SUBTRACT: return "kp_subtract"; case VK_DECIMAL: return "kp_decimal";
+ case VK_DIVIDE: return "kp_divide";
+ default: return {};
+ }
+}
+
+std::string quote_arg(const std::string& s) {
+ std::string o = "\"";
+ for (char c : s) {
+ if (c == '"') o += "\\\"";
+ else o += c;
+ }
+ return o + "\"";
+}
+
+struct Proc {
+ HANDLE process = nullptr;
+ HANDLE in_w = nullptr; // our end of child's stdin
+ HANDLE out_r = nullptr; // our end of child's stdout
+};
+
+bool spawn(const std::string& cmdline, Proc& p) {
+ SECURITY_ATTRIBUTES sa{sizeof(sa), nullptr, TRUE};
+ HANDLE in_r = nullptr, out_w = nullptr;
+ if (!CreatePipe(&in_r, &p.in_w, &sa, 0)) return false;
+ if (!CreatePipe(&p.out_r, &out_w, &sa, 0)) return false;
+ SetHandleInformation(p.in_w, HANDLE_FLAG_INHERIT, 0);
+ SetHandleInformation(p.out_r, HANDLE_FLAG_INHERIT, 0);
+ STARTUPINFOA si{};
+ si.cb = sizeof(si);
+ si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
+ si.wShowWindow = SW_HIDE;
+ si.hStdInput = in_r;
+ si.hStdOutput = out_w;
+ si.hStdError = out_w;
+ PROCESS_INFORMATION pi{};
+ std::string cl = cmdline;
+ BOOL ok = CreateProcessA(nullptr, cl.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi);
+ CloseHandle(in_r);
+ CloseHandle(out_w);
+ if (!ok) {
+ CloseHandle(p.in_w); CloseHandle(p.out_r);
+ p = {};
+ return false;
+ }
+ CloseHandle(pi.hThread);
+ p.process = pi.hProcess;
+ return true;
+}
+
+void close_proc(Proc& p) {
+ if (p.in_w) CloseHandle(p.in_w);
+ if (p.out_r) CloseHandle(p.out_r);
+ if (p.process) CloseHandle(p.process);
+ p = {};
+}
+
+uint64_t fnv1a(const uint8_t* d, size_t n, uint64_t h = 1469598103934665603ull) {
+ // Sampled hash: every 7th byte is enough to notice a changed frame and keeps it cheap.
+ for (size_t i = 0; i < n; i += 7) { h ^= d[i]; h *= 1099511628211ull; }
+ return h;
+}
+
+} // namespace
+
+WindowStreamer::WindowStreamer(compositor::RootlessCompositor& compositor, std::string wsm_root)
+ : compositor_(compositor), root_(std::move(wsm_root)) {
+ // The per-frame screendump goes to %TEMP% (normally the system SSD), never to the drive
+ // holding the runtime, so frame captures don't compete with macOS's own disk reads.
+ char tmp[MAX_PATH] = {};
+ DWORD n = GetTempPathA(MAX_PATH, tmp);
+ ppm_path_ = (n > 0 && n < MAX_PATH ? std::string(tmp) : root_ + "\\cache\\tmp\\") + "wsm_stream_frame.ppm";
+}
+
+WindowStreamer::~WindowStreamer() { stop(); }
+
+std::string WindowStreamer::ssh_base() const {
+ return "C:\\Windows\\System32\\OpenSSH\\ssh.exe -i " + quote_arg(root_ + "\\runtime\\config\\guest\\id_ed25519") +
+ " -p 2222 -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=NUL -o LogLevel=ERROR"
+ " -o ConnectTimeout=10 -o ServerAliveInterval=10 -o ServerAliveCountMax=3 [email protected] ";
+}
+
+int WindowStreamer::guest_exec(const std::string& command, std::string* out, uint32_t timeout_ms,
+ const std::function<void(const std::string&)>& on_line) const {
+ last_activity_ms_.store(now_ms());
+ struct Touch { std::atomic<int64_t>& t; ~Touch() { t.store(now_ms()); } } touch{last_activity_ms_};
+ Proc p;
+ if (!spawn(ssh_base() + quote_arg(command), p)) return -1;
+ size_t fed = 0;
+ auto feed = [&](std::string& b) {
+ if (!on_line) return;
+ size_t pos;
+ while ((pos = b.find('\n', fed)) != std::string::npos) {
+ std::string line = b.substr(fed, pos - fed);
+ if (!line.empty() && line.back() == '\r') line.pop_back();
+ on_line(line);
+ fed = pos + 1;
+ }
+ };
+ CloseHandle(p.in_w); p.in_w = nullptr;
+ std::string buf;
+ char tmp[4096];
+ DWORD n = 0;
+ int64_t deadline = now_ms() + timeout_ms;
+ for (;;) {
+ DWORD avail = 0;
+ if (PeekNamedPipe(p.out_r, nullptr, 0, nullptr, &avail, nullptr) && avail > 0) {
+ if (ReadFile(p.out_r, tmp, sizeof(tmp), &n, nullptr) && n > 0) { buf.append(tmp, n); feed(buf); }
+ continue;
+ }
+ if (WaitForSingleObject(p.process, 30) == WAIT_OBJECT_0) {
+ while (PeekNamedPipe(p.out_r, nullptr, 0, nullptr, &avail, nullptr) && avail > 0 &&
+ ReadFile(p.out_r, tmp, sizeof(tmp), &n, nullptr) && n > 0) buf.append(tmp, n);
+ buf += "\n";
+ feed(buf);
+ buf.pop_back();
+ break;
+ }
+ if (now_ms() > deadline) { TerminateProcess(p.process, 255); break; }
+ }
+ DWORD code = 255;
+ GetExitCodeProcess(p.process, &code);
+ close_proc(p);
+ if (out) *out = buf;
+ return static_cast<int>(code);
+}
+
+int WindowStreamer::scp(const std::string& from, const std::string& to, uint32_t timeout_ms) const {
+ std::string cmd = "C:\\Windows\\System32\\OpenSSH\\scp.exe -q -i " +
+ quote_arg(root_ + "\\runtime\\config\\guest\\id_ed25519") +
+ " -P 2222 -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=NUL"
+ " -o LogLevel=ERROR -o ConnectTimeout=10 " + quote_arg(from) + " " + quote_arg(to);
+ Proc p;
+ if (!spawn(cmd, p)) return -1;
+ CloseHandle(p.in_w); p.in_w = nullptr;
+ char tmp[1024]; DWORD n = 0, avail = 0;
+ int64_t deadline = now_ms() + timeout_ms;
+ while (WaitForSingleObject(p.process, 50) != WAIT_OBJECT_0) {
+ while (PeekNamedPipe(p.out_r, nullptr, 0, nullptr, &avail, nullptr) && avail > 0 &&
+ ReadFile(p.out_r, tmp, sizeof(tmp), &n, nullptr) && n > 0) {}
+ if (now_ms() > deadline) { TerminateProcess(p.process, 255); break; }
+ }
+ DWORD code = 255;
+ GetExitCodeProcess(p.process, &code);
+ close_proc(p);
+ return static_cast<int>(code);
+}
+
+bool WindowStreamer::copy_to_guest(const std::string& local, const std::string& remote_rel) const {
+ return scp(local, "[email protected]:" + remote_rel, 30 * 60 * 1000) == 0;
+}
+
+bool WindowStreamer::copy_from_guest(const std::string& remote, const std::string& local) const {
+ return scp("[email protected]:" + remote, local, 120000) == 0;
+}
+
+void WindowStreamer::kick() {
+ kick_watch_.store(true);
+ if (watch_proc_) TerminateProcess(static_cast<HANDLE>(watch_proc_), 0);
+}
+
+// One SSH session kept open with a shell on the other end: commands run in milliseconds
+// instead of paying for a new SSH connection (~1 s) each time.
+int WindowStreamer::quick(const std::string& command, std::string* out, uint32_t timeout_ms) {
+ last_activity_ms_.store(now_ms());
+ std::lock_guard<std::mutex> lk(sh_mu_);
+ for (int attempt = 0; attempt < 2; ++attempt) {
+ if (!sh_proc_ || WaitForSingleObject(static_cast<HANDLE>(sh_proc_), 0) == WAIT_OBJECT_0) {
+ if (sh_proc_) { CloseHandle(static_cast<HANDLE>(sh_in_)); CloseHandle(static_cast<HANDLE>(sh_out_)); CloseHandle(static_cast<HANDLE>(sh_proc_)); }
+ sh_proc_ = sh_in_ = sh_out_ = nullptr;
+ Proc p;
+ if (!spawn(ssh_base() + quote_arg("exec /bin/zsh -s"), p)) return -1;
+ sh_proc_ = p.process; sh_in_ = p.in_w; sh_out_ = p.out_r;
+ }
+ std::string line = command + " 2>&1; echo \"__WSM_RC__ $?\"\n";
+ DWORD wr = 0;
+ if (!WriteFile(static_cast<HANDLE>(sh_in_), line.data(), static_cast<DWORD>(line.size()), &wr, nullptr)) {
+ TerminateProcess(static_cast<HANDLE>(sh_proc_), 0);
+ continue;
+ }
+ std::string buf;
+ char tmp[4096]; DWORD n = 0, avail = 0;
+ int64_t deadline = now_ms() + timeout_ms;
+ for (;;) {
+ size_t m = buf.find("__WSM_RC__ ");
+ if (m != std::string::npos && buf.find('\n', m) != std::string::npos) {
+ int rc = std::atoi(buf.c_str() + m + 11);
+ if (out) *out = buf.substr(0, m);
+ last_activity_ms_.store(now_ms());
+ return rc;
+ }
+ if (PeekNamedPipe(static_cast<HANDLE>(sh_out_), nullptr, 0, nullptr, &avail, nullptr) && avail > 0) {
+ if (ReadFile(static_cast<HANDLE>(sh_out_), tmp, sizeof(tmp), &n, nullptr) && n > 0) buf.append(tmp, n);
+ continue;
+ }
+ if (WaitForSingleObject(static_cast<HANDLE>(sh_proc_), 5) == WAIT_OBJECT_0) break; // shell died
+ if (now_ms() > deadline) { // stuck: start over
+ TerminateProcess(static_cast<HANDLE>(sh_proc_), 0);
+ return -1;
+ }
+ }
+ }
+ return -1;
+}
+
+void WindowStreamer::set_guest_clipboard(const std::string& text) {
+ if (text.empty() || text.size() > 1000000 || !watching_.load()) return;
+ {
+ std::lock_guard<std::mutex> lk(clip_mu_);
+ if (text == last_clip_) return; // came from the guest
+ last_clip_ = text;
+ }
+ std::thread([this, text] {
+ quick("printf %s '" + b64_encode(text) + "' | base64 -D | LANG=en_US.UTF-8 pbcopy", nullptr, 15000);
+ }).detach();
+}
+
+bool WindowStreamer::launch_app(const std::string& app, std::string& err) {
+ std::string cmd;
+ if (app.find('/') != std::string::npos) cmd = "open " + quote_arg(app);
+ else if (app.find('.') != std::string::npos) cmd = "open -b " + quote_arg(app);
+ else cmd = "open -a " + quote_arg(app);
+ {
+ // The user asked for it: its windows may show now (also when it was started hidden).
+ std::lock_guard<std::mutex> lk(mu_);
+ if (hidden_bundle_ == app) hidden_bundle_.clear();
+ }
+ std::string out;
+ int rc = quick(cmd, &out, 30000);
+ if (rc != 0) { err = out.empty() ? ("exit " + std::to_string(rc)) : out; return false; }
+ last_input_ms_.store(now_ms());
+ if (app.find('/') == std::string::npos && app.find('.') != std::string::npos) remember_recent(app);
+ return true;
+}
+
+void WindowStreamer::remember_recent(const std::string& id) {
+ std::lock_guard<std::mutex> lk(recent_mu_);
+ const std::string path = root_ + "\\runtime\\config\\recent-apps.txt";
+ std::vector<std::string> ids{id};
+ std::ifstream in(path);
+ for (std::string l; std::getline(in, l) && ids.size() < 6;)
+ if (!l.empty() && l != id) ids.push_back(l);
+ in.close();
+ std::ofstream o(path, std::ios::trunc);
+ for (auto& x : ids) o << x << "\n";
+}
+
+void WindowStreamer::set_share(const std::string& url, bool on) {
+ {
+ std::lock_guard<std::mutex> lk(share_mu_);
+ share_url_ = url;
+ share_on_ = on;
+ }
+ if (watching_.load()) std::thread([this] { mount_share(); }).detach();
+}
+
+void WindowStreamer::mount_share() {
+ std::string url;
+ bool on;
+ {
+ std::lock_guard<std::mutex> lk(share_mu_);
+ url = share_url_;
+ on = share_on_;
+ }
+ if (url.empty()) return;
+ for (char c : url) if (c == '\'' || c == '"' || c == '\\') return;
+ // macOS's own WebDAV client; -S: never show a dialog. Read-write because the server speaks
+ // WebDAV class 2 (locks).
+ if (on)
+ quick("mkdir -p ~/Windows; mount | grep -q \" on $HOME/Windows \" || /sbin/mount_webdav -S -v Windows '" + url +
+ "' ~/Windows", nullptr, 30000);
+ else
+ quick("mount | grep -q \" on $HOME/Windows \" && umount ~/Windows; true", nullptr, 30000);
+}
+
+void WindowStreamer::prewarm_apps() {
+ std::vector<std::string> ids;
+ {
+ std::lock_guard<std::mutex> lk(recent_mu_);
+ std::ifstream in(root_ + "\\runtime\\config\\recent-apps.txt");
+ for (std::string l; std::getline(in, l) && ids.size() < 3;) {
+ bool ok = !l.empty() && l.size() < 200;
+ for (char c : l) if (!(std::isalnum(static_cast<unsigned char>(c)) || c == '.' || c == '-' || c == '_')) ok = false;
+ if (ok) ids.push_back(l);
+ }
+ }
+ if (ids.empty()) return;
+ // 1. The most recent app, started hidden and in the background (-g -j) unless it already
+ // runs (then it may have windows the user is looking at). Its windows are kept off the
+ // Windows desktop until the user opens it (see apply_window_list).
+ std::string first = ids.front(), out;
+ quick("(p=$(osascript -l JavaScript -e \"ObjC.import('AppKit'); $.NSWorkspace.sharedWorkspace.URLForApplicationWithBundleIdentifier('" +
+ first + "').path.js\" 2>/dev/null); if [[ -z $p ]]; then echo MISSING; else "
+ "pgrep -qf \"$p/Contents/MacOS/\" && echo RUNNING || open -g -j -b " + quote_arg(first) + "; fi)", &out, 20000);
+ if (out.find("RUNNING") == std::string::npos && out.find("MISSING") == std::string::npos) {
+ std::lock_guard<std::mutex> lk(mu_);
+ hidden_bundle_ = first;
+ hidden_until_ms_ = now_ms() + 10 * 60 * 1000;
+ }
+ // 2. Every recent app's files into memory, at background I/O priority, so a launch reads
+ // nothing from disk.
+ std::string list;
+ for (auto& id : ids) list += " " + id;
+ std::thread([this, list] {
+ // Own subshell, detached inside it: nothing is left running in the shared shell.
+ quick("( ( for id in" + list + "; do "
+ "p=$(osascript -l JavaScript -e \"ObjC.import('AppKit'); $.NSWorkspace.sharedWorkspace.URLForApplicationWithBundleIdentifier('$id').path.js\" 2>/dev/null); "
+ "[[ -n $p ]] && taskpolicy -b find \"$p/\" -type f -size -96M -exec cat {} + >/dev/null 2>&1; "
+ "done ) </dev/null &>/dev/null & )", nullptr, 15000);
+ }).detach();
+}
+
+void WindowStreamer::start() {
+ if (running_.exchange(true)) return;
+ std::filesystem::create_directories(root_ + "\\cache\\tmp");
+ // Windows OpenSSH ignores a private key that other accounts can read.
+ {
+ std::string key = root_ + "\\runtime\\config\\guest\\id_ed25519";
+ std::string cmd = "icacls.exe " + quote_arg(key) + " /inheritance:r /grant:r \"%USERNAME%:F\"";
+ Proc p;
+ if (spawn("cmd.exe /c " + cmd, p)) { WaitForSingleObject(p.process, 10000); close_proc(p); }
+ }
+ watch_thread_ = std::thread(&WindowStreamer::watch_loop, this);
+ capture_thread_ = std::thread(&WindowStreamer::capture_loop, this);
+ vnc_thread_ = std::thread(&WindowStreamer::vnc_loop, this);
+ input_thread_ = std::thread(&WindowStreamer::input_loop, this);
+}
+
+void WindowStreamer::stop() {
+ if (!running_.exchange(false)) return;
+ if (watch_proc_) TerminateProcess(static_cast<HANDLE>(watch_proc_), 0);
+ in_cv_.notify_all();
+ if (vnc_sock_ != static_cast<uintptr_t>(INVALID_SOCKET)) closesocket(static_cast<SOCKET>(vnc_sock_));
+ if (sh_proc_) TerminateProcess(static_cast<HANDLE>(sh_proc_), 0);
+ if (vnc_thread_.joinable()) vnc_thread_.join();
+ if (watch_thread_.joinable()) watch_thread_.join();
+ if (capture_thread_.joinable()) capture_thread_.join();
+ if (input_thread_.joinable()) input_thread_.join();
+}
+
+std::string WindowStreamer::debug_json() const {
+ std::lock_guard<std::mutex> lk(mu_);
+ std::ostringstream o;
+ o << "[";
+ bool first = true;
+ for (auto& [wid, g] : wins_) {
+ o << (first ? "" : ",") << "{\"wid\":" << wid << ",\"pid\":" << g.pid << ",\"layer\":" << g.layer << ",\"z\":" << g.z
+ << ",\"x\":" << g.x << ",\"y\":" << g.y << ",\"w\":" << g.w << ",\"h\":" << g.h << ",\"missing\":" << g.missing << ",\"covered\":" << g.covered_rects << "}";
+ first = false;
+ }
+ o << "]";
+ return o.str();
+}
+
+bool WindowStreamer::debug_dump_frame(uint32_t wid, const std::string& path) {
+ std::lock_guard<std::mutex> lk(frame_mu_);
+ auto it = frames_by_win_.find(wid);
+ if (it == frames_by_win_.end() || it->second.px.empty()) return false;
+ const Frame& f = it->second;
+ BITMAPFILEHEADER bf{}; BITMAPINFOHEADER bi{};
+ bi.biSize = sizeof(bi); bi.biWidth = f.w; bi.biHeight = -f.h; bi.biPlanes = 1; bi.biBitCount = 32;
+ bf.bfType = 0x4D42; bf.bfOffBits = sizeof(bf) + sizeof(bi);
+ bf.bfSize = bf.bfOffBits + static_cast<DWORD>(f.px.size());
+ std::ofstream o(path, std::ios::binary | std::ios::trunc);
+ o.write(reinterpret_cast<const char*>(&bf), sizeof(bf));
+ o.write(reinterpret_cast<const char*>(&bi), sizeof(bi));
+ o.write(reinterpret_cast<const char*>(f.px.data()), static_cast<std::streamsize>(f.px.size()));
+ return static_cast<bool>(o);
+}
+
+size_t WindowStreamer::window_count() const {
+ std::lock_guard<std::mutex> lk(mu_);
+ return wins_.size();
+}
+
+void WindowStreamer::watch_loop() {
+ while (running_.load()) {
+ Proc p;
+ if (!spawn(ssh_base() + quote_arg("osascript -l JavaScript -"), p)) { Sleep(2000); continue; }
+ watch_proc_ = p.process;
+ DWORD wr = 0;
+ WriteFile(p.in_w, kWindowScript, static_cast<DWORD>(std::strlen(kWindowScript)), &wr, nullptr);
+ CloseHandle(p.in_w); p.in_w = nullptr;
+
+ std::string acc, last_list;
+ char buf[8192];
+ DWORD n = 0;
+ while (running_.load() && ReadFile(p.out_r, buf, sizeof(buf), &n, nullptr) && n > 0) {
+ acc.append(buf, n);
+ size_t pos;
+ while ((pos = acc.find('\n')) != std::string::npos) {
+ std::string line = acc.substr(0, pos);
+ acc.erase(0, pos + 1);
+ if (!line.empty() && line.back() == '\r') line.pop_back();
+ if (line.rfind("S ", 0) == 0) {
+ int w = 0, h = 0;
+ if (std::sscanf(line.c_str() + 2, "%d %d", &w, &h) == 2 && w > 0 && h > 0) {
+ std::lock_guard<std::mutex> lk(mu_);
+ screen_w_ = w; screen_h_ = h;
+ }
+ if (!watching_.exchange(true)) {
+ std::thread([this] {
+ // scp doesn't create folders, and cache cleanup inside macOS can remove it.
+ quick("mkdir -p ~/Library/Caches/WSM/icons ~/Library/Caches/WSM/inbox", nullptr, 15000);
+ if (copy_to_guest(root_ + "\\src\\wsm-guest\\agent\\wsm-trim.sh", "Library/Caches/WSM/wsm-trim.sh")) {
+ std::string out;
+ int trc = guest_exec("zsh ~/Library/Caches/WSM/wsm-trim.sh", &out, 120000);
+ trim_report_ = out;
+ if (trc == 0) post_setup_cleanup();
+ prewarm_apps();
+ mount_share();
+ }
+ }).detach();
+ }
+ } else if (line.rfind("C ", 0) == 0) {
+ std::string text = b64_decode(line.substr(2));
+ {
+ std::lock_guard<std::mutex> lk(clip_mu_);
+ if (text == last_clip_) continue; // our own paste coming back
+ last_clip_ = text;
+ }
+ if (on_guest_clipboard_) on_guest_clipboard_(text);
+ } else if (line.rfind("W", 0) == 0) {
+ last_list = line.size() > 2 ? line.substr(2) : std::string();
+ apply_window_list(last_list);
+ } else if (line == "K") {
+ // Unchanged: apply it again so windows missing from it finish closing.
+ apply_window_list(last_list);
+ }
+ }
+ }
+ watching_.store(false);
+ watch_proc_ = nullptr;
+ TerminateProcess(p.process, 0);
+ close_proc(p);
+ // Runtime gone (paused/stopped/booting): drop its windows, retry shortly.
+ apply_window_list(kDisconnected); // disconnected: drop windows, quit nothing
+ for (int i = 0; i < 30 && running_.load() && !kick_watch_.exchange(false); ++i) Sleep(100);
+ }
+}
+
+void WindowStreamer::post_setup_cleanup() {
+ namespace fs = std::filesystem;
+ std::error_code ec;
+ const std::string cfg = root_ + "\\runtime\\config\\";
+ if (!fs::exists(cfg + "runtime-ready.json", ec) || fs::exists(cfg + "setup-cleaned", ec)) return;
+ // Confirmed working: we got here because macOS booted, logged in, answers over SSH and its
+ // window watcher runs. Inside macOS: the installer's own 17 GB copy ("Previous Content").
+ std::string out;
+ if (!copy_to_guest(root_ + "\\src\\wsm-guest\\agent\\wsm-shrink.sh", "Library/Caches/WSM/wsm-shrink.sh") ||
+ guest_exec("zsh ~/Library/Caches/WSM/wsm-shrink.sh --leftovers-only", &out, 15 * 60 * 1000) != 0)
+ return; // try again next start
+ // On Windows: the downloaded installer / recovery images. Only finished ones: a .part is a
+ // download in progress (deleting it killed one), and nothing while a download holds the lock.
+ uint64_t freed = 0;
+ const std::string inst = root_ + "\\runtime\\reims-ctl\\installers";
+ {
+ HANDLE lk = CreateFileA((inst + "\\.lock").c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr);
+ if (lk == INVALID_HANDLE_VALUE && GetLastError() == ERROR_SHARING_VIOLATION) return; // try again next start
+ if (lk != INVALID_HANDLE_VALUE) CloseHandle(lk);
+ HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
+ bool downloading = false;
+ PROCESSENTRY32W pe{}; pe.dwSize = sizeof(pe);
+ if (snap != INVALID_HANDLE_VALUE && Process32FirstW(snap, &pe))
+ do { downloading |= _wcsicmp(pe.szExeFile, L"reims-util.exe") == 0; } while (Process32NextW(snap, &pe));
+ if (snap != INVALID_HANDLE_VALUE) CloseHandle(snap);
+ if (downloading) return; // try again next start
+ }
+ for (auto& e : fs::directory_iterator(inst, ec)) {
+ auto ext = e.path().extension().string();
+ for (auto& ch : ext) ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
+ if (!e.is_regular_file(ec) || (ext != ".img" && ext != ".dmg" && ext != ".pkg")) continue;
+ uint64_t sz = e.file_size(ec);
+ if (fs::remove(e.path(), ec)) freed += sz;
+ }
+ std::ofstream(cfg + "setup-cleaned") << "installer images removed: " << (freed >> 20) << " MB\n" << out;
+ // The disk image only gives the freed space back when it's rewritten offline; wsmd does
+ // that the next time the runtime is idle.
+ std::ofstream(cfg + "compact-pending") << "after setup\n";
+}
+
+void WindowStreamer::apply_window_list(const std::string& list) {
+ std::map<uint32_t, GuestWin> seen;
+ std::stringstream ss(list);
+ std::string item;
+ while (std::getline(ss, item, ';')) {
+ std::vector<std::string> f;
+ std::stringstream is(item);
+ std::string part;
+ while (std::getline(is, part, '|')) f.push_back(part);
+ if (f.size() < 9) continue;
+ GuestWin g;
+ g.wid = static_cast<uint32_t>(std::stoul(f[0]));
+ g.pid = static_cast<uint32_t>(std::stoul(f[1]));
+ g.layer = std::stoi(f[2]);
+ g.x = std::stoi(f[3]); g.y = std::stoi(f[4]);
+ g.w = std::stoi(f[5]); g.h = std::stoi(f[6]);
+ g.owner = f[7]; g.bundle = f[8];
+ g.z = static_cast<int>(seen.size()); // list is back to front
+ {
+ // Started hidden by prewarm_apps and not opened yet: not on the Windows desktop.
+ std::lock_guard<std::mutex> lk(mu_);
+ if (!hidden_bundle_.empty() && g.bundle == hidden_bundle_ && now_ms() < hidden_until_ms_) continue;
+ }
+ seen[g.wid] = g;
+ }
+
+ std::vector<uint32_t> gone;
+ std::lock_guard<std::mutex> lk(mu_);
+ {
+ // Stacking (and bounds) signature: while it just changed, the screen may already show
+ // the new order while this list doesn't yet (see capture_loop's clean frames).
+ std::string sig;
+ for (auto& [wid, g] : seen)
+ sig += std::to_string(wid) + ":" + std::to_string(g.z) + ":" + std::to_string(g.x) + "," + std::to_string(g.y) + "," +
+ std::to_string(g.w) + "," + std::to_string(g.h) + ";";
+ if (sig != stack_sig_ && list != kDisconnected) { stack_sig_ = sig; stack_changed_ms_.store(now_ms()); }
+ }
+ // Windows behaviour: closing an app's last window quits the app. Only apps that had a
+ // window streamed (so a launching app with no window yet is left alone), after a short grace.
+ {
+ std::map<uint32_t, int> now_count;
+ for (auto& [wid, g] : seen) if (g.layer == 0) now_count[g.pid]++;
+ int64_t t = now_ms();
+ for (auto& [wid, g] : wins_)
+ if (g.layer == 0 && !now_count.count(g.pid) && list != kDisconnected) pid_empty_since_.emplace(g.pid, t);
+ for (auto it = pid_empty_since_.begin(); it != pid_empty_since_.end();) {
+ if (now_count.count(it->first)) { it = pid_empty_since_.erase(it); continue; }
+ if (t - it->second > 2500) {
+ uint32_t pid = it->first;
+ std::thread([this, pid] { quick("kill -TERM " + std::to_string(pid), nullptr, 15000); }).detach();
+ pid_offset_.erase(pid);
+ it = pid_empty_since_.erase(it);
+ continue;
+ }
+ ++it;
+ }
+ }
+ // While macOS switches the active app it can report no windows (or not all) for ~100 ms.
+ // Closing on that blip destroyed and re-created every window on each app switch (flicker),
+ // so a window is gone only after 3 lists in a row without it (~300 ms), or on disconnect.
+ const bool disconnected = list == kDisconnected;
+ for (auto& [wid, g] : wins_) {
+ if (seen.count(wid)) { g.missing = 0; continue; }
+ if (disconnected || ++g.missing >= 3) gone.push_back(wid);
+ }
+ for (uint32_t wid : gone) {
+ compositor_.destroy_window(kIdBase | wid);
+ wins_.erase(wid);
+ }
+ for (auto& [wid, s] : seen) {
+ auto it = wins_.find(wid);
+ if (it == wins_.end()) {
+ wins_[wid] = s;
+ sync_host_window(wins_[wid]);
+ } else {
+ GuestWin& g = it->second;
+ bool moved = g.x != s.x || g.y != s.y || g.w != s.w || g.h != s.h;
+ g.x = s.x; g.y = s.y; g.w = s.w; g.h = s.h; g.layer = s.layer; g.z = s.z;
+ if (moved) { g.last_hash = 0; g.changed_ms = now_ms(); sync_host_window(g); }
+ }
+ }
+}
+
+// Caller holds mu_.
+void WindowStreamer::sync_host_window(GuestWin& g) {
+ auto off = pid_offset_.find(g.pid);
+ if (off == pid_offset_.end()) {
+ // First window of this app: place it where it is in the runtime, kept inside the
+ // primary monitor's work area. Later windows of the app keep the same offset so menus
+ // and sheets line up with their parent.
+ RECT wa{};
+ SystemParametersInfoW(SPI_GETWORKAREA, 0, &wa, 0);
+ int ox = 0, oy = 0;
+ if (g.x + g.w > wa.right) ox = wa.right - (g.x + g.w);
+ if (g.y + g.h > wa.bottom) oy = wa.bottom - (g.y + g.h);
+ if (g.x + ox < wa.left) ox = wa.left - g.x;
+ if (g.y + oy < wa.top) oy = wa.top - g.y;
+ off = pid_offset_.emplace(g.pid, std::make_pair(ox, oy)).first;
+ }
+ proto::WindowDescriptor d{};
+ d.window_id = kIdBase | g.wid;
+ d.pid = g.pid;
+ d.style_flags = (1u << 3) | (g.layer != 0 ? (1u << 6) : 0u);
+ d.bounds = {g.x + off->second.first, g.y + off->second.second, g.w, g.h};
+ d.visible = 1;
+ compositor_.create_or_update_window(d, g.owner);
+ if (!g.created) {
+ g.created = true;
+ std::string bundle = g.bundle, owner = g.owner, icon = root_ + "\\runtime\\apps\\icons\\" + g.bundle + ".ico";
+ uint64_t id = d.window_id;
+ // The HWND is created asynchronously on the compositor thread.
+ std::thread([this, id, bundle, icon] {
+ for (int i = 0; i < 20; ++i) {
+ Sleep(50);
+ if (compositor_.set_window_identity(id, bundle.empty() ? "" : "WSM.App." + bundle,
+ std::filesystem::exists(icon) ? icon : "")) break;
+ }
+ }).detach();
+ }
+}
+
+bool WindowStreamer::lookup(uint64_t host_id, GuestWin& out) const {
+ if ((host_id & kIdBase) == 0) return false;
+ std::lock_guard<std::mutex> lk(mu_);
+ auto it = wins_.find(static_cast<uint32_t>(host_id & 0xFFFFFFFFu));
+ if (it == wins_.end()) return false;
+ out = it->second;
+ return true;
+}
+
+namespace {
+
+// Makes the runtime's flat desktop colour transparent inside a window's corner squares and
+// un-blends the anti-aliased edge, so the window keeps macOS's exact rounded shape on Windows.
+// Writes premultiplied BGRA (the swap chain is DXGI_ALPHA_MODE_PREMULTIPLIED).
+void cut_corners(uint8_t* px, int w, int h, const uint8_t key[3]) {
+ int R = std::min(40, std::min(w, h) / 3);
+ if (R < 4) return;
+ auto dist = [](const uint8_t* a, const uint8_t* k) {
+ int d0 = std::abs(a[0] - k[0]), d1 = std::abs(a[1] - k[1]), d2 = std::abs(a[2] - k[2]);
+ return std::max(d0, std::max(d1, d2));
+ };
+ const int cx[4] = {0, w - R, 0, w - R}, cy[4] = {0, 0, h - R, h - R};
+ for (int c = 0; c < 4; ++c) {
+ // Reference: the window's own colour just inside this corner.
+ int rx = (c & 1) ? w - R - 1 : R, ry = (c & 2) ? h - R - 1 : R;
+ const uint8_t* ref = px + (static_cast<size_t>(ry) * w + rx) * 4;
+ int D = dist(ref, key);
+ for (int y = cy[c]; y < cy[c] + R; ++y) {
+ uint8_t* p = px + (static_cast<size_t>(y) * w + cx[c]) * 4;
+ for (int x = 0; x < R; ++x, p += 4) {
+ int d = dist(p, key);
+ if (d >= D && D > 0) continue; // window pixel
+ if (D < 24) { if (d <= 3) { p[0] = p[1] = p[2] = p[3] = 0; } continue; }
+ double a = static_cast<double>(d) / D; // coverage of the window
+ if (a < 0.02) { p[0] = p[1] = p[2] = p[3] = 0; continue; }
+ for (int k = 0; k < 3; ++k) {
+ double v = p[k] - (1.0 - a) * key[k];
+ p[k] = static_cast<uint8_t>(v < 0 ? 0 : (v > 255 ? 255 : v));
+ }
+ p[3] = static_cast<uint8_t>(a * 255.0 + 0.5);
+ }
+ }
+ }
+}
+
+} // namespace
+
+namespace {
+
+bool sock_read(SOCKET s, void* buf, size_t len) {
+ auto* p = static_cast<char*>(buf);
+ while (len) {
+ int n = recv(s, p, static_cast<int>(len > (1 << 20) ? (1 << 20) : len), 0);
+ if (n <= 0) return false;
+ p += n; len -= static_cast<size_t>(n);
+ }
+ return true;
+}
+bool sock_write(SOCKET s, const void* buf, size_t len) {
+ auto* p = static_cast<const char*>(buf);
+ while (len) {
+ int n = send(s, p, static_cast<int>(len), 0);
+ if (n <= 0) return false;
+ p += n; len -= static_cast<size_t>(n);
+ }
+ return true;
+}
+uint16_t be16(const uint8_t* p) { return static_cast<uint16_t>((p[0] << 8) | p[1]); }
+uint32_t be32(const uint8_t* p) { return (uint32_t(p[0]) << 24) | (uint32_t(p[1]) << 16) | (uint32_t(p[2]) << 8) | p[3]; }
+
+} // namespace
+
+// Frames from QEMU's VNC server on 127.0.0.1 (the runtime is started with -vnc). QEMU tracks
+// which parts of the screen changed and sends only those, so a blinking caret costs a few
+// hundred bytes instead of a 6 MB screen capture. Pixels land straight in fb_ (BGRX).
+void WindowStreamer::vnc_loop() {
+ WSADATA wsa{};
+ WSAStartup(MAKEWORD(2, 2), &wsa);
+ while (running_.load()) {
+ if (!watching_.load()) { vnc_live_.store(false); Sleep(500); continue; }
+ SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ sockaddr_in a{}; a.sin_family = AF_INET; a.sin_port = htons(kVncPort);
+ inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);
+ if (s == INVALID_SOCKET || connect(s, reinterpret_cast<sockaddr*>(&a), sizeof(a)) != 0) {
+ if (s != INVALID_SOCKET) closesocket(s);
+ vnc_live_.store(false);
+ for (int i = 0; i < 30 && running_.load(); ++i) Sleep(100);
+ continue;
+ }
+ BOOL nd = TRUE;
+ setsockopt(s, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char*>(&nd), sizeof(nd));
+ int rcv = 8 << 20;
+ setsockopt(s, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<const char*>(&rcv), sizeof(rcv));
+ vnc_sock_ = static_cast<uintptr_t>(s);
+
+ bool ok = true;
+ uint8_t b[64];
+ // Handshake: RFB 3.8, no authentication (the server listens on localhost only).
+ ok = ok && sock_read(s, b, 12) && std::memcmp(b, "RFB ", 4) == 0 && sock_write(s, "RFB 003.008\n", 12);
+ uint8_t ntypes = 0;
+ ok = ok && sock_read(s, &ntypes, 1) && ntypes > 0 && sock_read(s, b, ntypes);
+ uint8_t none = 1;
+ ok = ok && sock_write(s, &none, 1) && sock_read(s, b, 4) && be32(b) == 0;
+ uint8_t shared = 1;
+ ok = ok && sock_write(s, &shared, 1) && sock_read(s, b, 24);
+ int w = ok ? be16(b) : 0, h = ok ? be16(b + 2) : 0;
+ uint32_t name_len = ok ? be32(b + 20) : 0;
+ std::vector<uint8_t> name(name_len);
+ ok = ok && (name_len == 0 || sock_read(s, name.data(), name_len));
+ // 32-bit little-endian true colour with red at bit 16: bytes arrive as B,G,R,X.
+ const uint8_t setfmt[20] = {0, 0, 0, 0, 32, 24, 0, 1, 0, 255, 0, 255, 0, 255, 16, 8, 0, 0, 0, 0};
+ ok = ok && sock_write(s, setfmt, sizeof(setfmt));
+ const uint8_t setenc[12] = {2, 0, 0, 2, 0, 0, 0, 0 /*raw*/, 0xFF, 0xFF, 0xFF, 0x21 /*DesktopSize*/};
+ ok = ok && sock_write(s, setenc, sizeof(setenc));
+ auto request = [&](bool incremental) {
+ uint8_t r[10] = {3, static_cast<uint8_t>(incremental ? 1 : 0), 0, 0, 0, 0,
+ static_cast<uint8_t>(w >> 8), static_cast<uint8_t>(w), static_cast<uint8_t>(h >> 8), static_cast<uint8_t>(h)};
+ std::lock_guard<std::mutex> lw(vnc_write_mu_);
+ return sock_write(s, r, sizeof(r));
+ };
+ if (ok) {
+ std::lock_guard<std::mutex> lk(fb_mu_);
+ fb_w_ = w; fb_h_ = h;
+ fb_.assign(static_cast<size_t>(w) * h * 4, 0);
+ }
+ ok = ok && request(false);
+ if (ok) vnc_live_.store(true);
+
+ std::vector<uint8_t> row;
+ DWORD rto = 3000;
+ setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&rto), sizeof(rto));
+ while (ok && running_.load()) {
+ uint8_t type = 0;
+ if (!watching_.load()) break;
+ if (!sock_read(s, &type, 1)) {
+ if (WSAGetLastError() == WSAETIMEDOUT && watching_.load()) continue; // nothing changed
+ break;
+ }
+ if (type == 0) { // FramebufferUpdate
+ if (!sock_read(s, b, 3)) break;
+ int n = be16(b + 1);
+ int dx0 = INT_MAX, dy0 = INT_MAX, dx1 = 0, dy1 = 0;
+ for (int i = 0; i < n && ok; ++i) {
+ if (!sock_read(s, b, 12)) { ok = false; break; }
+ int rx = be16(b), ry = be16(b + 2), rw = be16(b + 4), rh = be16(b + 6);
+ int32_t enc = static_cast<int32_t>(be32(b + 8));
+ if (enc == 0) {
+ row.resize(static_cast<size_t>(rw) * 4);
+ for (int y = 0; y < rh; ++y) {
+ if (!sock_read(s, row.data(), row.size())) { ok = false; break; }
+ std::lock_guard<std::mutex> lk(fb_mu_);
+ if (ry + y < fb_h_ && rx + rw <= fb_w_)
+ std::memcpy(&fb_[(static_cast<size_t>(ry + y) * fb_w_ + rx) * 4], row.data(), row.size());
+ }
+ dx0 = std::min(dx0, rx); dy0 = std::min(dy0, ry);
+ dx1 = std::max(dx1, rx + rw); dy1 = std::max(dy1, ry + rh);
+ } else if (enc == -223) { // DesktopSize: the screen was resized
+ w = rw; h = rh;
+ std::lock_guard<std::mutex> lk(fb_mu_);
+ fb_w_ = w; fb_h_ = h;
+ fb_.assign(static_cast<size_t>(w) * h * 4, 0);
+ dx0 = 0; dy0 = 0; dx1 = w; dy1 = h;
+ } else { ok = false; } // never asked for anything else
+ }
+ if (!ok) break;
+ if (dx1 > dx0) {
+ std::lock_guard<std::mutex> lk(fb_mu_);
+ dirty_x0_ = std::min(dirty_x0_, dx0); dirty_y0_ = std::min(dirty_y0_, dy0);
+ dirty_x1_ = std::max(dirty_x1_, dx1); dirty_y1_ = std::max(dirty_y1_, dy1);
+ }
+ cap_kick_.store(true);
+ cap_cv_.notify_one();
+ ok = request(true);
+ } else if (type == 1) { // SetColourMapEntries (unused)
+ if (!sock_read(s, b, 5)) break;
+ std::vector<uint8_t> skip(static_cast<size_t>(be16(b + 3)) * 6);
+ if (!sock_read(s, skip.data(), skip.size())) break;
+ } else if (type == 2) { // Bell
+ } else if (type == 3) { // ServerCutText
+ if (!sock_read(s, b, 7)) break;
+ std::vector<uint8_t> skip(be32(b + 3));
+ if (!skip.empty() && !sock_read(s, skip.data(), skip.size())) break;
+ } else break;
+ }
+ vnc_live_.store(false);
+ vnc_sock_ = static_cast<uintptr_t>(INVALID_SOCKET);
+ closesocket(s);
+ for (int i = 0; i < 10 && running_.load(); ++i) Sleep(100);
+ }
+}
+
+void WindowStreamer::capture_loop() {
+ // Its own QMP connection, kept open (a new one per screendump cost a handshake per frame).
+ const std::string vmd = root_ + "\\runtime\\reims-ctl\\vms\\wsm-default";
+ wsm::core::QmpSession qmp(vmd + "\\wsm-cap.sock", vmd + "\\qmp.sock");
+ std::vector<uint8_t> shot, crop; // shot: screendump pixels (RGB)
+ std::map<uint32_t, std::vector<uint8_t>> prev; // last presented pixels per window
+ std::map<uint32_t, std::tuple<int, int, int, int>> prev_geom;
+ // Per window: pixels known to be its own (taken only while the stack was settled). Covered
+ // parts are filled from here, so another app's pixels can never get stuck in a window.
+ std::map<uint32_t, std::vector<uint8_t>> clean;
+ std::set<uint32_t> redo; // shown while unsettled: render again once settled
+ uint8_t key[3] = {22, 20, 18}; // BGR of the backdrop colour
+ int64_t last_full = 0;
+ while (running_.load()) {
+ std::vector<GuestWin> list;
+ {
+ std::lock_guard<std::mutex> lk(mu_);
+ for (auto& [wid, g] : wins_) list.push_back(g);
+ }
+ auto alive = [&](uint32_t wid) { for (auto& g : list) if (g.wid == wid) return true; return false; };
+ for (auto it = prev.begin(); it != prev.end();) it = alive(it->first) ? std::next(it) : prev.erase(it);
+ for (auto it = prev_geom.begin(); it != prev_geom.end();) it = alive(it->first) ? std::next(it) : prev_geom.erase(it);
+ for (auto it = clean.begin(); it != clean.end();) it = alive(it->first) ? std::next(it) : clean.erase(it);
+ const bool settled = now_ms() - stack_changed_ms_.load() > 250;
+ {
+ std::lock_guard<std::mutex> lk(frame_mu_);
+ for (auto it = frames_by_win_.begin(); it != frames_by_win_.end();)
+ it = alive(it->first) ? std::next(it) : frames_by_win_.erase(it);
+ }
+ if (list.empty()) {
+ std::unique_lock<std::mutex> lk(cap_mu_);
+ cap_cv_.wait_for(lk, std::chrono::milliseconds(150));
+ continue;
+ }
+ int64_t t0 = now_ms();
+ // QEMU's VNC server checks the screen less often while it's quiet (up to seconds), so
+ // right after input the frames come from screendumps, which are always fresh; changes
+ // the app makes by itself (animations, new messages) come through VNC.
+ const bool typing = now_ms() - last_input_ms_.load() < 1500;
+ // (Tried: VNC only, with QEMU's refresh forced back to 30 ms after each input. Measured
+ // slower than screendumps here: median 106 vs 68 ms key -> pixel in Safari.)
+ const bool vnc = vnc_live_.load() && !typing;
+ int bpp = 4; // VNC: B,G,R,X screendump: R,G,B
+
+ // The frame to crop from: QEMU's VNC framebuffer (only what changed), or a screendump.
+ std::unique_lock<std::mutex> fb_lock(fb_mu_, std::defer_lock);
+ const uint8_t* src = nullptr;
+ int fw = 0, fh = 0;
+ int dx0 = 0, dy0 = 0, dx1 = 0, dy1 = 0; // changed area this round
+ if (vnc) {
+ fb_lock.lock();
+ src = fb_.data(); fw = fb_w_; fh = fb_h_;
+ dx0 = dirty_x0_; dy0 = dirty_y0_; dx1 = dirty_x1_; dy1 = dirty_y1_;
+ dirty_x0_ = dirty_y0_ = INT_MAX; dirty_x1_ = dirty_y1_ = 0;
+ if (fw <= 0 || fh <= 0) { fb_lock.unlock(); Sleep(50); continue; }
+ if (now_ms() - last_full > 2000) { dx0 = 0; dy0 = 0; dx1 = fw; dy1 = fh; last_full = now_ms(); }
+ } else {
+ std::string err;
+ int64_t td = now_ms();
+ if (!qmp.capture_screendump_ppm(ppm_path_, err)) { Sleep(300); continue; }
+ diag_dump_ms_.store(now_ms() - td);
+ std::ifstream f(ppm_path_, std::ios::binary);
+ if (!f) { Sleep(100); continue; }
+ std::string magic; int maxv = 0;
+ f >> magic >> fw >> fh >> maxv;
+ f.get();
+ if (magic != "P6" || fw <= 0 || fh <= 0) { Sleep(100); continue; }
+ shot.resize(static_cast<size_t>(fw) * fh * 3);
+ f.read(reinterpret_cast<char*>(shot.data()), static_cast<std::streamsize>(shot.size()));
+ if (!f) { Sleep(50); continue; }
+ src = shot.data();
+ bpp = 3;
+ dx0 = 0; dy0 = 0; dx1 = fw; dy1 = fh;
+ }
+
+ int sw, sh;
+ { std::lock_guard<std::mutex> lk(mu_); sw = screen_w_; sh = screen_h_; }
+ double sx = static_cast<double>(fw) / sw, sy = static_cast<double>(fh) / sh;
+
+ // Desktop colour, read where no window is (screen corners below the menu bar).
+ {
+ const int pts[4][2] = {{4, 40}, {sw - 5, 40}, {4, sh - 5}, {sw - 5, sh - 5}};
+ for (auto& pt : pts) {
+ bool covered = false;
+ for (auto& g : list)
+ covered |= pt[0] >= g.x && pt[0] < g.x + g.w && pt[1] >= g.y && pt[1] < g.y + g.h;
+ if (covered) continue;
+ const uint8_t* s = src + (static_cast<size_t>(pt[1] * sy) * fw + static_cast<size_t>(pt[0] * sx)) * bpp;
+ if (bpp == 4) { key[0] = s[0]; key[1] = s[1]; key[2] = s[2]; }
+ else { key[0] = s[2]; key[1] = s[1]; key[2] = s[0]; }
+ break;
+ }
+ }
+
+ struct Out { uint32_t wid; int pw, ph, y0, y1; bool full; std::vector<uint8_t> px; };
+ std::vector<Out> outs;
+ for (const GuestWin& g : list) {
+ int px = static_cast<int>(g.x * sx), py = static_cast<int>(g.y * sy);
+ int pw = static_cast<int>(g.w * sx), ph = static_cast<int>(g.h * sy);
+ if (px < 0) { pw += px; px = 0; }
+ if (py < 0) { ph += py; py = 0; }
+ if (px + pw > fw) pw = fw - px;
+ if (py + ph > fh) ph = fh - py;
+ if (pw <= 0 || ph <= 0) continue;
+ // While a window is moving inside the runtime, its reported bounds trail the pixels;
+ // presenting then would show the wrong area (flicker). Wait until it settles.
+ if (now_ms() - g.changed_ms < 120) continue;
+ auto geom = std::make_tuple(px, py, pw, ph);
+ bool geom_changed = prev_geom[g.wid] != geom;
+ // Nothing changed inside this window: no work at all.
+ const bool must_redo = settled && redo.count(g.wid);
+ if (!must_redo && !geom_changed && prev.count(g.wid) && !(dx0 < px + pw && px < dx1 && dy0 < py + ph && py < dy1)) continue;
+ if (settled) redo.erase(g.wid); else redo.insert(g.wid);
+ // Parts covered by other windows inside the runtime (crop-relative pixel rects).
+ // Those pixels belong to the other app; they're masked below.
+ struct Rc { int x0, y0, x1, y1; };
+ std::vector<Rc> cover;
+ for (const GuestWin& w2 : list) {
+ if (w2.wid == g.wid || w2.z <= g.z) continue;
+ // The app's own dropdowns, popovers, sheets and menus: nothing foreign to hide
+ // (their own Windows window covers that spot), and masking them froze the parent
+ // around them, e.g. Safari's address bar above its Favorites dropdown.
+ if (w2.pid == g.pid) continue;
+ // Plus its shadow, which macOS draws outside the window's bounds (deeper below).
+ const int sh_side = w2.layer == 0 ? 28 : 12, sh_below = w2.layer == 0 ? 44 : 16;
+ int ox0 = static_cast<int>((w2.x - sh_side) * sx) - px, oy0 = static_cast<int>((w2.y - sh_side) * sy) - py;
+ int ox1 = static_cast<int>((w2.x + w2.w + sh_side) * sx) - px, oy1 = static_cast<int>((w2.y + w2.h + sh_below) * sy) - py;
+ ox0 = std::max(ox0, 0); oy0 = std::max(oy0, 0); ox1 = std::min(ox1, pw); oy1 = std::min(oy1, ph);
+ if (ox0 < ox1 && oy0 < oy1) cover.push_back({ox0, oy0, ox1, oy1});
+ }
+ {
+ std::lock_guard<std::mutex> lk(mu_);
+ if (auto wi = wins_.find(g.wid); wi != wins_.end()) wi->second.covered_rects = static_cast<int>(cover.size());
+ }
+ Out o{g.wid, pw, ph, 0, ph - 1, true, {}};
+ o.px.resize(static_cast<size_t>(pw) * ph * 4);
+ const size_t stride = static_cast<size_t>(pw) * 4;
+ for (int row = 0; row < ph; ++row) {
+ const uint8_t* r = src + (static_cast<size_t>(py + row) * fw + px) * bpp;
+ if (bpp == 4) { std::memcpy(&o.px[row * stride], r, stride); continue; }
+ uint8_t* d = &o.px[row * stride];
+ for (int c = 0; c < pw; ++c, r += 3, d += 4) { d[0] = r[2]; d[1] = r[1]; d[2] = r[0]; }
+ }
+ if (!cover.empty()) {
+ // Keep this window's own last pixels there; never seen yet: its own background
+ // (most common colour of a row through its uncovered content).
+ auto pit = clean.find(g.wid);
+ const bool have_prev = pit != clean.end() && pit->second.size() == o.px.size();
+ uint8_t fill[4] = {236, 236, 236, 255};
+ if (!have_prev) {
+ std::map<uint32_t, int> hist;
+ for (int row = std::min(ph - 1, 60); row < ph; row += std::max(1, ph / 16))
+ for (int c = 0; c < pw; c += 3) {
+ bool hid = false;
+ for (auto& rc : cover) hid |= c >= rc.x0 && c < rc.x1 && row >= rc.y0 && row < rc.y1;
+ if (hid) continue;
+ const uint8_t* q = &o.px[(static_cast<size_t>(row) * pw + c) * 4];
+ hist[q[0] | (q[1] << 8) | (q[2] << 16)]++;
+ }
+ int best = 0;
+ for (auto& [k, n] : hist)
+ if (n > best) { best = n; fill[0] = k & 255; fill[1] = (k >> 8) & 255; fill[2] = (k >> 16) & 255; }
+ }
+ for (auto& rc : cover)
+ for (int row = rc.y0; row < rc.y1; ++row) {
+ uint8_t* d = &o.px[(static_cast<size_t>(row) * pw + rc.x0) * 4];
+ const size_t n = static_cast<size_t>(rc.x1 - rc.x0) * 4;
+ if (have_prev) std::memcpy(d, &pit->second[(static_cast<size_t>(row) * pw + rc.x0) * 4], n);
+ else for (size_t i = 0; i < n; i += 4) std::memcpy(d + i, fill, 4);
+ }
+ }
+ if (settled) clean[g.wid] = o.px; // the stack is settled: these pixels are its own
+ else if (auto ci = clean.find(g.wid); ci != clean.end() && ci->second.size() != o.px.size()) clean.erase(ci);
+ prev_geom[g.wid] = geom;
+ outs.push_back(std::move(o));
+ }
+ if (fb_lock.owns_lock()) fb_lock.unlock(); // the VNC thread may write again
+
+ for (Out& o : outs) {
+ const size_t stride = static_cast<size_t>(o.pw) * 4;
+ for (size_t i = 3; i < o.px.size(); i += 4) o.px[i] = 255;
+ cut_corners(o.px.data(), o.pw, o.ph, key);
+ // Only upload the rows that changed since the last frame of this window.
+ auto& last = prev[o.wid];
+ o.full = last.size() != o.px.size();
+ if (!o.full) {
+ while (o.y0 < o.ph && std::memcmp(&last[o.y0 * stride], &o.px[o.y0 * stride], stride) == 0) ++o.y0;
+ if (o.y0 == o.ph) continue; // unchanged
+ while (o.y1 > o.y0 && std::memcmp(&last[o.y1 * stride], &o.px[o.y1 * stride], stride) == 0) --o.y1;
+ }
+ bool ok = o.full ? compositor_.present_bgra_frame(kIdBase | o.wid, o.pw, o.ph, o.pw * 4, o.px.data())
+ : compositor_.present_bgra_frame(kIdBase | o.wid, o.pw, o.ph, o.pw * 4, o.px.data(),
+ 0, o.y0, o.pw, o.y1 - o.y0 + 1);
+ if (!ok) continue;
+ frames_.fetch_add(1);
+ if (diag_wait_.exchange(false)) diag_lat_ms_.store(now_ms() - last_input_ms_.load());
+ // Find the yellow/green title-bar buttons (BGRA) in the top-left corner.
+ if (o.full || o.y0 < 56) {
+ long yx = 0, yy = 0, yn = 0, gx = 0, gy = 0, gn = 0;
+ for (int ry = 0; ry < std::min(o.ph, 56); ++ry)
+ for (int rx = 0; rx < std::min(o.pw, 110); ++rx) {
+ const uint8_t* q = &o.px[(static_cast<size_t>(ry) * o.pw + rx) * 4];
+ if (q[3] < 200) continue;
+ if (q[2] > 220 && q[1] > 150 && q[1] < 215 && q[0] < 110) { yx += rx; yy += ry; ++yn; }
+ else if (q[1] > 160 && q[2] < 130 && q[0] < 130) { gx += rx; gy += ry; ++gn; }
+ }
+ std::lock_guard<std::mutex> lk2(mu_);
+ auto w = wins_.find(o.wid);
+ if (w != wins_.end()) {
+ if (yn > 30) { w->second.min_x = static_cast<int>(yx / yn); w->second.min_y = static_cast<int>(yy / yn); }
+ if (gn > 30) { w->second.zoom_x = static_cast<int>(gx / gn); w->second.zoom_y = static_cast<int>(gy / gn); }
+ }
+ }
+ {
+ std::lock_guard<std::mutex> lk(frame_mu_);
+ Frame& fr = frames_by_win_[o.wid];
+ fr.w = o.pw; fr.h = o.ph; fr.px = o.px;
+ }
+ last = std::move(o.px);
+ }
+
+ if (vnc) {
+ // Event driven: wake when QEMU sends changed pixels or the window list changes.
+ std::unique_lock<std::mutex> lk(cap_mu_);
+ cap_cv_.wait_for(lk, std::chrono::milliseconds(250), [&] { return cap_kick_.exchange(false); });
+ } else {
+ // Screendumps: as fast as they come while the user types or clicks; ~6 fps otherwise
+ // (only when VNC isn't available).
+ int64_t budget = typing ? 8 : 160;
+ int64_t spent = now_ms() - t0;
+ if (typing) diag_cycle_ms_.store(spent);
+ if (spent < budget) {
+ std::unique_lock<std::mutex> lk(cap_mu_);
+ cap_cv_.wait_for(lk, std::chrono::milliseconds(budget - spent), [&] { return cap_kick_.exchange(false); });
+ }
+ }
+ }
+}
+
+void WindowStreamer::queue_events(const std::string& events_json) {
+ last_input_ms_.store(now_ms());
+ diag_wait_.store(true);
+ last_activity_ms_.store(now_ms());
+ cap_kick_.store(true);
+ cap_cv_.notify_one();
+ {
+ std::lock_guard<std::mutex> lk(in_mu_);
+ in_q_.push_back(events_json);
+ }
+ in_cv_.notify_one();
+}
+
+void WindowStreamer::queue_abs(int gx, int gy) {
+ int sw, sh;
+ { std::lock_guard<std::mutex> lk(mu_); sw = screen_w_; sh = screen_h_; }
+ if (gx < 0) gx = 0;
+ if (gy < 0) gy = 0;
+ if (gx >= sw) gx = sw - 1;
+ if (gy >= sh) gy = sh - 1;
+ long ax = static_cast<long>(gx) * 32767 / (sw - 1);
+ long ay = static_cast<long>(gy) * 32767 / (sh - 1);
+ queue_events("M{\"type\":\"abs\",\"data\":{\"axis\":\"x\",\"value\":" + std::to_string(ax) +
+ "}},{\"type\":\"abs\",\"data\":{\"axis\":\"y\",\"value\":" + std::to_string(ay) + "}}");
+}
+
+void WindowStreamer::input_loop() {
+ // Its own QMP connection, kept open: every key and click paid a connect and handshake.
+ const std::string vmd = root_ + "\\runtime\\reims-ctl\\vms\\wsm-default";
+ wsm::core::QmpSession qmp(vmd + "\\wsm-in.sock", vmd + "\\qmp.sock");
+ while (running_.load()) {
+ std::deque<std::string> batch;
+ {
+ std::unique_lock<std::mutex> lk(in_mu_);
+ in_cv_.wait_for(lk, std::chrono::milliseconds(200), [&] { return !in_q_.empty() || !running_.load(); });
+ batch.swap(in_q_);
+ }
+ if (batch.empty()) continue;
+ // Collapse runs of pointer moves (prefix 'M') to the last one; keep everything else in order.
+ std::string events;
+ for (size_t i = 0; i < batch.size(); ++i) {
+ const std::string& e = batch[i];
+ if (e[0] == 'M' && i + 1 < batch.size() && batch[i + 1][0] == 'M') continue;
+ if (!events.empty()) events += ",";
+ events += (e[0] == 'M' || e[0] == 'E') ? e.substr(1) : e;
+ }
+ std::string resp;
+ qmp.execute("{\"execute\":\"input-send-event\",\"arguments\":{\"events\":[" + events + "]}}", resp, 1000);
+ }
+}
+
+bool WindowStreamer::on_mouse_move(const proto::InputMouseMoveEvent& ev) {
+ GuestWin g;
+ if (!lookup(ev.window_id, g)) return false;
+ queue_abs(g.x + ev.x, g.y + ev.y);
+ return true;
+}
+
+bool WindowStreamer::on_mouse_button(const proto::InputMouseButtonEvent& ev) {
+ GuestWin g;
+ if (!lookup(ev.window_id, g)) return false;
+ queue_abs(g.x + ev.x, g.y + ev.y);
+ const char* b = ev.button == 1 ? "right" : ev.button == 2 ? "middle" : "left";
+ queue_events(std::string("E{\"type\":\"btn\",\"data\":{\"down\":") + (ev.pressed ? "true" : "false") +
+ ",\"button\":\"" + b + "\"}}");
+ return true;
+}
+
+bool WindowStreamer::on_scroll(const proto::InputScrollEvent& ev) {
+ GuestWin g;
+ if (!lookup(ev.window_id, g)) return false;
+ int steps = static_cast<int>(ev.delta_y >= 0 ? ev.delta_y + 0.5f : -ev.delta_y + 0.5f);
+ if (steps < 1) steps = 1;
+ const char* b = ev.delta_y > 0 ? "wheel-up" : "wheel-down";
+ for (int i = 0; i < steps * 3; ++i) {
+ queue_events(std::string("E{\"type\":\"btn\",\"data\":{\"down\":true,\"button\":\"") + b +
+ "\"}},{\"type\":\"btn\",\"data\":{\"down\":false,\"button\":\"" + b + "\"}}");
+ }
+ return true;
+}
+
+bool WindowStreamer::on_key(const proto::InputKeyEvent& ev) {
+ if ((ev.window_id & kIdBase) == 0) return false;
+ std::string q = vk_to_qcode(ev.vk_code);
+ if (q.empty()) return true;
+ queue_events(std::string("E{\"type\":\"key\",\"data\":{\"down\":") + (ev.pressed ? "true" : "false") +
+ ",\"key\":{\"type\":\"qcode\",\"data\":\"" + q + "\"}}}");
+ return true;
+}
+
+void WindowStreamer::debug_key(const std::string& q) {
+ for (char c : q) if (!(std::isalnum(static_cast<unsigned char>(c)) || c == '_')) return;
+ queue_events("E{\"type\":\"key\",\"data\":{\"down\":true,\"key\":{\"type\":\"qcode\",\"data\":\"" + q + "\"}}}");
+ queue_events("E{\"type\":\"key\",\"data\":{\"down\":false,\"key\":{\"type\":\"qcode\",\"data\":\"" + q + "\"}}}");
+}
+
+int WindowStreamer::hit_caption(uint64_t window_id, int x, int y) {
+ GuestWin g;
+ if (!lookup(window_id, g) || g.layer != 0) return 0;
+ // macOS's yellow button minimizes the Windows window (in the runtime it would hide the
+ // window in the Dock, which nobody can see); green does nothing (fullscreen there would
+ // cover the hidden desktop). Red goes to the app, which closes the window properly.
+ auto close_to = [&](int cx, int cy) { return (x - cx) * (x - cx) + (y - cy) * (y - cy) <= 81; };
+ if (close_to(g.min_x, g.min_y)) return 8; // HTMINBUTTON
+ if (close_to(g.zoom_x, g.zoom_y)) return 9; // HTMAXBUTTON (ignored by the compositor)
+ if (y < 0 || y >= 52 || x < 80) return 0; // title band; traffic lights excluded
+ std::lock_guard<std::mutex> lk(frame_mu_);
+ auto it = frames_by_win_.find(g.wid);
+ if (it == frames_by_win_.end()) return 0;
+ const Frame& f = it->second;
+ if (x >= f.w - 8 || y >= f.h) return 0;
+ // The bar can be grabbed wherever nothing sharp is drawn: plain title bar, Safari's glass
+ // toolbar with a gradient behind it, or the title text. A click there that doesn't move the
+ // window is handed to the app (compositor), so buttons and fields on the bar still work.
+ const uint8_t* c = &f.px[(static_cast<size_t>(y) * f.w + x) * 4];
+ auto px_at = [&](int xx, int yy) { return &f.px[(static_cast<size_t>(yy) * f.w + xx) * 4]; };
+ auto diff = [](const uint8_t* a, const uint8_t* b) {
+ return std::max(std::abs(a[0] - b[0]), std::max(std::abs(a[1] - b[1]), std::abs(a[2] - b[2])));
+ };
+ // 1. Smooth: no edge between neighbouring pixels (icons, glyphs and outlines have edges).
+ bool smooth = true;
+ for (int dy = -5; dy <= 5 && smooth; ++dy) {
+ int yy = y + dy;
+ if (yy < 0 || yy + 1 >= f.h) continue;
+ for (int dx = -7; dx <= 7; ++dx) {
+ int xx = x + dx;
+ if (xx < 0 || xx + 1 >= f.w) continue;
+ const uint8_t* q = px_at(xx, yy);
+ if (diff(q, px_at(xx + 1, yy)) > 8 || diff(q, px_at(xx, yy + 1)) > 8) { smooth = false; break; }
+ }
+ }
+ if (smooth) return 2; // HTCAPTION
+ // 2. The window's title: grey anti-aliased text on mostly plain bar.
+ int plain = 0, total = 0;
+ for (int dy = -5; dy <= 5; ++dy) {
+ int yy = y + dy;
+ if (yy < 0 || yy >= f.h) continue;
+ for (int dx = -7; dx <= 7; ++dx) {
+ int xx = x + dx;
+ if (xx < 0 || xx >= f.w) continue;
+ const uint8_t* q = px_at(xx, yy);
+ ++total;
+ if (diff(q, c) <= 6) { ++plain; continue; }
+ bool grey = std::abs(q[0] - q[1]) <= 10 && std::abs(q[1] - q[2]) <= 10;
+ if (!grey) return 0;
+ }
+ }
+ if (total == 0 || plain * 2 < total) return 0; // mostly bar, at most some text
+ return 2; // HTCAPTION
+}
+
+bool WindowStreamer::on_window_action(const proto::WindowActionEvent& ev) {
+ GuestWin g;
+ if (!lookup(ev.window_id, g)) return (ev.window_id & kIdBase) != 0;
+ if (ev.action == static_cast<uint32_t>(proto::WindowActionKind::Focus) && g.layer == 0 && !g.bundle.empty()) {
+ // Bring the app to the front inside the runtime too, so its window is the live one.
+ int64_t t = now_ms();
+ if (t - last_raise_ms_.load() > 300 || last_raise_pid_.load() != g.pid) {
+ last_raise_ms_.store(t);
+ last_raise_pid_.store(g.pid);
+ std::string b = g.bundle;
+ std::thread([this, b] { quick("open -b " + quote_arg(b), nullptr, 15000); }).detach();
+ }
+ return true;
+ }
+ if (ev.action == static_cast<uint32_t>(proto::WindowActionKind::Move)) {
+ // Moved natively on Windows: the runtime window stays put; remember the new offset
+ // so later geometry updates from the runtime keep the Windows position.
+ if (g.layer == 0) {
+ std::lock_guard<std::mutex> lk(mu_);
+ pid_offset_[g.pid] = {ev.arg1 - g.x, ev.arg2 - g.y};
+ }
+ return true;
+ }
+ if (ev.action == static_cast<uint32_t>(proto::WindowActionKind::Close)) {
+ // Focus the window in the runtime (click its title bar), then Command+W.
+ queue_abs(g.x + g.w / 2, g.y + 8);
+ queue_events("E{\"type\":\"btn\",\"data\":{\"down\":true,\"button\":\"left\"}}");
+ queue_events("E{\"type\":\"btn\",\"data\":{\"down\":false,\"button\":\"left\"}}");
+ queue_events("E{\"type\":\"key\",\"data\":{\"down\":true,\"key\":{\"type\":\"qcode\",\"data\":\"meta_l\"}}}");
+ queue_events("E{\"type\":\"key\",\"data\":{\"down\":true,\"key\":{\"type\":\"qcode\",\"data\":\"w\"}}}");
+ queue_events("E{\"type\":\"key\",\"data\":{\"down\":false,\"key\":{\"type\":\"qcode\",\"data\":\"w\"}}}");
+ queue_events("E{\"type\":\"key\",\"data\":{\"down\":false,\"key\":{\"type\":\"qcode\",\"data\":\"meta_l\"}}}");
+ }
+ return true;
+}
+
+} // namespace wsm::runtime
diff --git a/src/wsm-runtime/src/wsm_app_launcher.cpp b/src/wsm-runtime/src/wsm_app_launcher.cpp
new file mode 100644
index 0000000..3120c02
--- /dev/null
+++ b/src/wsm-runtime/src/wsm_app_launcher.cpp
@@ -0,0 +1,211 @@
+// wsmlaunch.exe — the target of every Mac app's Start menu and Desktop shortcut.
+//
+// A GUI-subsystem executable, so clicking a shortcut never flashes a console. It makes sure the
+// WSM service is running, asks it to open the app (the service wakes the macOS runtime when it
+// is asleep), and returns. If something goes wrong it says so in a normal Windows dialog.
+//
+// wsmlaunch.exe <bundle-id> open an installed Mac app
+// wsmlaunch.exe --install <file> install a .dmg/.pkg/.zip/.app (Explorer double-click)
+// wsmlaunch.exe --background start WSM's service at sign-in (warms the runtime)
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#include <shellapi.h>
+#include <commctrl.h>
+
+#include <filesystem>
+#include <string>
+
+#pragma comment(lib, "ws2_32.lib")
+#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
+
+namespace {
+
+std::wstring exe_dir() {
+ wchar_t buf[MAX_PATH]{};
+ GetModuleFileNameW(nullptr, buf, MAX_PATH);
+ return std::filesystem::path(buf).parent_path().wstring();
+}
+
+SOCKET connect_wsmd() {
+ SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (s == INVALID_SOCKET) return s;
+ sockaddr_in a{}; a.sin_family = AF_INET; a.sin_port = htons(17421);
+ inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);
+ if (connect(s, reinterpret_cast<sockaddr*>(&a), sizeof(a)) != 0) { closesocket(s); return INVALID_SOCKET; }
+ return s;
+}
+
+bool ensure_service() {
+ SOCKET s = connect_wsmd();
+ if (s != INVALID_SOCKET) { closesocket(s); return true; }
+ std::wstring path = exe_dir() + L"\\wsmd.exe";
+ STARTUPINFOW si{}; si.cb = sizeof(si);
+ PROCESS_INFORMATION pi{};
+ if (!CreateProcessW(path.c_str(), nullptr, nullptr, nullptr, FALSE, CREATE_NO_WINDOW | DETACHED_PROCESS,
+ nullptr, exe_dir().c_str(), &si, &pi)) return false;
+ CloseHandle(pi.hThread); CloseHandle(pi.hProcess);
+ for (int i = 0; i < 100; ++i) {
+ Sleep(100);
+ s = connect_wsmd();
+ if (s != INVALID_SOCKET) { closesocket(s); return true; }
+ }
+ return false;
+}
+
+std::string post(const std::string& path, const std::string& body) {
+ SOCKET s = connect_wsmd();
+ if (s == INVALID_SOCKET) return {};
+ DWORD to = 60000;
+ setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&to), sizeof(to));
+ std::string req = "POST " + path + " HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: text/plain\r\nContent-Length: " +
+ std::to_string(body.size()) + "\r\nConnection: close\r\n\r\n" + body;
+ send(s, req.data(), static_cast<int>(req.size()), 0);
+ std::string resp; char buf[4096]; int n;
+ while ((n = recv(s, buf, sizeof(buf), 0)) > 0) resp.append(buf, n);
+ closesocket(s);
+ auto p = resp.find("\r\n\r\n");
+ return p == std::string::npos ? resp : resp.substr(p + 4);
+}
+
+std::string json_field(const std::string& json, const std::string& key) {
+ auto k = json.find("\"" + key + "\":\"");
+ if (k == std::string::npos) return {};
+ k += key.size() + 4;
+ auto e = json.find('"', k);
+ return e == std::string::npos ? std::string{} : json.substr(k, e - k);
+}
+
+void error_box(const std::wstring& msg) {
+ MessageBoxW(nullptr, msg.c_str(), L"WSM", MB_OK | MB_ICONWARNING | MB_SETFOREGROUND);
+}
+
+std::wstring widen(const std::string& s) {
+ int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0);
+ std::wstring w(n > 0 ? n - 1 : 0, L'\0');
+ if (n > 0) MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, w.data(), n);
+ return w;
+}
+
+} // namespace
+
+std::string get(const std::string& path) {
+ SOCKET s = connect_wsmd();
+ if (s == INVALID_SOCKET) return {};
+ DWORD to = 10000;
+ setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&to), sizeof(to));
+ std::string req = "GET " + path + " HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n";
+ send(s, req.data(), static_cast<int>(req.size()), 0);
+ std::string resp; char buf[4096]; int n;
+ while ((n = recv(s, buf, sizeof(buf), 0)) > 0) resp.append(buf, n);
+ closesocket(s);
+ auto p = resp.find("\r\n\r\n");
+ return p == std::string::npos ? resp : resp.substr(p + 4);
+}
+
+int json_int(const std::string& json, const std::string& key) {
+ auto k = json.find("\"" + key + "\":");
+ return k == std::string::npos ? 0 : std::atoi(json.c_str() + k + key.size() + 3);
+}
+
+std::string utf8(const std::wstring& w) {
+ int n = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, nullptr, 0, nullptr, nullptr);
+ std::string s(n > 0 ? n - 1 : 0, '\0');
+ if (n > 0) WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, s.data(), n, nullptr, nullptr);
+ return s;
+}
+
+// Progress dialog for an install started from Explorer. The service does the work; this
+// polls its status and closes when the app is installed (the app then opens by itself).
+struct InstallUi { std::string result; std::wstring title; };
+
+HRESULT CALLBACK install_cb(HWND h, UINT msg, WPARAM, LPARAM, LONG_PTR ref) {
+ auto* ui = reinterpret_cast<InstallUi*>(ref);
+ if (msg == TDN_CREATED) {
+ SendMessageW(h, TDM_SET_PROGRESS_BAR_RANGE, 0, MAKELPARAM(0, 100));
+ } else if (msg == TDN_TIMER) {
+ std::string st = get("/api/apps/install/status");
+ if (st.empty()) return S_OK;
+ SendMessageW(h, TDM_SET_PROGRESS_BAR_POS, json_int(st, "percent"), 0);
+ std::wstring stage = widen(json_field(st, "stage"));
+ SendMessageW(h, TDM_SET_ELEMENT_TEXT, TDE_CONTENT, reinterpret_cast<LPARAM>(stage.c_str()));
+ if (st.find("\"done\":true") != std::string::npos) {
+ ui->result = st;
+ SendMessageW(h, TDM_CLICK_BUTTON, IDOK, 0);
+ }
+ }
+ return S_OK;
+}
+
+int install(const std::wstring& file) {
+ std::wstring name = std::filesystem::path(file).filename().wstring();
+ std::string r = post("/api/apps/install", utf8(file));
+ if (r.empty()) { error_box(L"WSM's service didn't respond."); return 1; }
+ if (r.find("\"ok\":false") != std::string::npos) { error_box(widen(json_field(r, "error"))); return 1; }
+
+ InstallUi ui;
+ TASKDIALOGCONFIG c{};
+ c.cbSize = sizeof(c);
+ c.dwFlags = TDF_SHOW_PROGRESS_BAR | TDF_CALLBACK_TIMER | TDF_ALLOW_DIALOG_CANCELLATION | TDF_POSITION_RELATIVE_TO_WINDOW;
+ c.dwCommonButtons = TDCBF_CLOSE_BUTTON;
+ c.pszWindowTitle = L"WSM";
+ std::wstring head = L"Installing " + name;
+ c.pszMainInstruction = head.c_str();
+ c.pszContent = L"Getting ready";
+ c.pszFooter = L"You can close this window. The app opens when it's ready.";
+ c.pfCallback = install_cb;
+ c.lpCallbackData = reinterpret_cast<LONG_PTR>(&ui);
+ using TdiFn = HRESULT(WINAPI*)(const TASKDIALOGCONFIG*, int*, int*, BOOL*);
+ HMODULE cc = LoadLibraryW(L"comctl32.dll");
+ auto tdi = cc ? reinterpret_cast<TdiFn>(GetProcAddress(cc, "TaskDialogIndirect")) : nullptr;
+ if (tdi) {
+ tdi(&c, nullptr, nullptr, nullptr);
+ } else {
+ for (int i = 0; i < 3600 && ui.result.empty(); ++i) {
+ Sleep(1000);
+ std::string st = get("/api/apps/install/status");
+ if (st.find("\"done\":true") != std::string::npos) ui.result = st;
+ }
+ }
+ if (!ui.result.empty() && ui.result.find("\"ok\":false") != std::string::npos) {
+ error_box(widen(json_field(ui.result, "error")));
+ return 1;
+ }
+ return 0;
+}
+
+int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) {
+ int argc = 0;
+ wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc);
+ if (argc < 2) { error_box(L"This shortcut doesn't name an app. Remove it and add the app again in WSM."); return 2; }
+ if (std::wstring(argv[1]) == L"--background") {
+ WSADATA w{}; WSAStartup(MAKEWORD(2, 2), &w);
+ ensure_service();
+ return 0;
+ }
+ if (std::wstring(argv[1]) == L"--install" || std::wstring(argv[1]) == L"open") {
+ if (argc < 3) return 2;
+ WSADATA w{}; WSAStartup(MAKEWORD(2, 2), &w);
+ if (!ensure_service()) { error_box(L"WSM's service couldn't start."); return 1; }
+ AllowSetForegroundWindow(ASFW_ANY);
+ return install(argv[2]);
+ }
+ std::wstring wid = argv[1];
+ std::string id(wid.begin(), wid.end());
+
+ WSADATA wsa{};
+ WSAStartup(MAKEWORD(2, 2), &wsa);
+ if (!ensure_service()) { error_box(L"The macOS runtime couldn't start. Open WSM to see what's wrong."); return 1; }
+
+ // Let the service bring the app's window to the front (the user just clicked its shortcut).
+ AllowSetForegroundWindow(ASFW_ANY);
+ std::string r = post("/api/apps/launch", id);
+ WSACleanup();
+ if (r.empty()) { error_box(L"The macOS runtime didn't respond. Open WSM to see what's wrong."); return 1; }
+ if (r.find("\"ok\":false") != std::string::npos) {
+ std::string e = json_field(r, "error");
+ error_box(e.empty() ? L"The app couldn't be opened." : widen(e));
+ return 1;
+ }
+ return 0;
+}
diff --git a/src/wsm-runtime/src/wsm_cli.cpp b/src/wsm-runtime/src/wsm_cli.cpp
new file mode 100644
index 0000000..1d27d61
--- /dev/null
+++ b/src/wsm-runtime/src/wsm_cli.cpp
@@ -0,0 +1,360 @@
+#include "wsm/host_probe.hpp"
+#include "wsm/vm_manager.hpp"
+#include "wsm/qmp_unix.hpp"
+#include "wsm/compositor.hpp"
+#include "wsm/services.hpp"
+#include "wsm/app_registry.hpp"
+#include "wsm/shell_integration.hpp"
+#include "wsm/paths.hpp"
+
+#include <windows.h>
+#include <tlhelp32.h>
+#include <shlobj.h>
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <string>
+#include <vector>
+
+static void print_usage() {
+ std::cout << "WSM — Windows Subsystem for macOS (CLI v0.1.0)\n"
+ << "Usage:\n"
+ << " wsm doctor Probe WHPX, Vulkan/GPU, storage, and host readiness\n"
+ << " wsm vm-cmd Print the configured QEMU WHPX + reims-vgpu command\n"
+ << " wsm inspect <path> Inspect a macOS .app bundle or Mach-O binary\n"
+ << " wsm apps List registered macOS applications\n"
+ << " wsm import <path> Import a macOS .app/.dmg/.pkg and create Start Menu shortcut\n"
+ << " wsm open <path> Handle double-clicked .dmg/.pkg/.app from Windows Explorer\n"
+ << " wsm launch <bundle_id> Auto-start WSM runtime and launch a registered macOS app\n"
+ << " wsm register-shell Register .dmg, .pkg, .app double-click handlers in Windows\n"
+ << " wsm bench Measure real DirectComposition full-frame & dirty-rect latency\n"
+ << " wsm compositor-verify Verify hardware DirectComposition rootless surface\n"
+ << " wsm audio-verify Verify WASAPI low-latency audio endpoint\n";
+}
+
+int main(int argc, char** argv) {
+ if (argc < 2) {
+ print_usage();
+ return 0;
+ }
+
+ std::string cmd = argv[1];
+
+ if (cmd == "snap-manager" && argc >= 3) {
+ // Dev aid: captures the WSM Manager window (including WebView2 content) to a BMP.
+ HWND h = FindWindowW(L"WsmNativeManagerWindow", nullptr);
+ if (!h) { std::cerr << "WSM window not found\n"; return 1; }
+ ShowWindow(h, SW_RESTORE); SetForegroundWindow(h); Sleep(500);
+ RECT r{}; GetWindowRect(h, &r);
+ int w = r.right - r.left, hh = r.bottom - r.top;
+ HDC screen = GetDC(nullptr), mem = CreateCompatibleDC(screen);
+ HBITMAP bmp = CreateCompatibleBitmap(screen, w, hh);
+ SelectObject(mem, bmp);
+ BitBlt(mem, 0, 0, w, hh, screen, r.left, r.top, SRCCOPY);
+ BITMAPINFOHEADER bi{sizeof(bi), w, -hh, 1, 24, BI_RGB};
+ int stride = ((w * 3 + 3) & ~3);
+ std::vector<char> px(static_cast<size_t>(stride) * hh);
+ GetDIBits(mem, bmp, 0, hh, px.data(), reinterpret_cast<BITMAPINFO*>(&bi), DIB_RGB_COLORS);
+ BITMAPFILEHEADER fh{0x4D42, static_cast<DWORD>(sizeof(fh) + sizeof(bi) + px.size()), 0, 0, sizeof(fh) + sizeof(bi)};
+ std::ofstream f(argv[2], std::ios::binary);
+ f.write(reinterpret_cast<char*>(&fh), sizeof(fh)); f.write(reinterpret_cast<char*>(&bi), sizeof(bi)); f.write(px.data(), px.size());
+ DeleteObject(bmp); DeleteDC(mem); ReleaseDC(nullptr, screen);
+ std::cout << w << "x" << hh << "\n";
+ return 0;
+ }
+
+ if (cmd == "qmp" && argc >= 3) {
+ // Dev aid: sends each argument as one raw QMP command on the runtime's socket.
+ wsm::core::QmpUnixClient qmp;
+ int rc = 0;
+ for (int i = 2; i < argc; ++i) {
+ std::string resp;
+ bool ok = qmp.execute(argv[i], resp, 5000);
+ std::cout << resp << "\n";
+ if (!ok) rc = 1;
+ Sleep(60);
+ }
+ return rc;
+ }
+
+ if (cmd == "qmp-reset-hold" && argc >= 4) {
+ // Resets the runtime and keeps a key combination pressed through firmware start, e.g.
+ // "meta_l+r" for OpenCore's Recovery hotkey. Usage: wsm qmp-reset-hold <combo> <seconds>
+ wsm::core::QmpUnixClient qmp;
+ std::string resp;
+ std::string keys;
+ std::string combo = argv[2];
+ size_t start = 0;
+ while (start <= combo.size()) {
+ size_t plus = combo.find('+', start);
+ std::string k = combo.substr(start, plus == std::string::npos ? std::string::npos : plus - start);
+ keys += std::string(keys.empty() ? "" : ",") + "{\"type\":\"qcode\",\"data\":\"" + k + "\"}";
+ if (plus == std::string::npos) break;
+ start = plus + 1;
+ }
+ qmp.execute("{\"execute\":\"system_reset\"}", resp);
+ DWORD until = GetTickCount() + static_cast<DWORD>(atof(argv[3]) * 1000);
+ int sent = 0;
+ while (GetTickCount() < until) {
+ qmp.execute("{\"execute\":\"send-key\",\"arguments\":{\"keys\":[" + keys + "],\"hold-time\":250}}", resp, 1500);
+ ++sent;
+ }
+ std::cout << "reset, held " << combo << " (" << sent << " presses)\n";
+ return 0;
+ }
+
+ if (cmd == "relink-shortcuts") {
+ // Re-creates every installed app's Start menu and Desktop shortcuts (used after upgrades).
+ wsm::runtime::AppRegistry reg;
+ reg.load();
+ for (const auto& a : reg.list()) {
+ wsm::runtime::remove_app_shortcuts(a.name);
+ std::string ico = wsm::core::resolve_wsm_root() + "\\runtime\\apps\\icons\\" + a.id + ".ico";
+ if (!std::filesystem::exists(ico) && !a.icon_path.empty()) wsm::runtime::convert_icns_to_ico(a.icon_path, ico);
+ std::string lnk;
+ bool ok = wsm::runtime::create_app_start_menu_shortcut(a.name, a.id, ico, lnk);
+ std::cout << (ok ? "linked " : "FAILED ") << a.name << " " << lnk << "\n";
+ }
+ std::error_code ec;
+ PWSTR p = nullptr;
+ if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Programs, 0, nullptr, &p))) {
+ std::filesystem::path old = std::filesystem::path(p) / L"WSM Apps";
+ if (std::filesystem::is_empty(old, ec)) std::filesystem::remove(old, ec);
+ }
+ CoTaskMemFree(p);
+ return 0;
+ }
+
+ if (cmd == "hide-runtime-windows") {
+ // The macOS runtime must never be visible to the user: hide any window owned by QEMU.
+ std::vector<DWORD> pids;
+ HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
+ PROCESSENTRY32W pe{}; pe.dwSize = sizeof(pe);
+ if (snap != INVALID_HANDLE_VALUE && Process32FirstW(snap, &pe)) {
+ do { if (_wcsicmp(pe.szExeFile, L"qemu-system-x86_64.exe") == 0) pids.push_back(pe.th32ProcessID); }
+ while (Process32NextW(snap, &pe));
+ }
+ if (snap != INVALID_HANDLE_VALUE) CloseHandle(snap);
+ struct Ctx { std::vector<DWORD>* pids; int n; } ctx{&pids, 0};
+ EnumWindows([](HWND h, LPARAM l) -> BOOL {
+ auto* c = reinterpret_cast<Ctx*>(l);
+ DWORD pid = 0; GetWindowThreadProcessId(h, &pid);
+ // Hiding the window stalls reims-vgpu's presenter (no swapchain -> the guest display stops).
+ // Instead keep it shown but off-screen, out of the taskbar and Alt+Tab, and click-through.
+ for (DWORD p : *c->pids) if (p == pid) {
+ wchar_t cls[64]{}; GetClassNameW(h, cls, 64);
+ if (wcscmp(cls, L"IME") == 0 || wcscmp(cls, L"MSCTFIME UI") == 0) continue;
+ LONG_PTR ex = GetWindowLongPtrW(h, GWL_EXSTYLE);
+ ex = (ex | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_TRANSPARENT) & ~WS_EX_APPWINDOW;
+ SetWindowLongPtrW(h, GWL_EXSTYLE, ex);
+ RECT r{}; GetWindowRect(h, &r);
+ SetWindowPos(h, HWND_BOTTOM, -32000, -32000, r.right - r.left, r.bottom - r.top,
+ SWP_NOACTIVATE | SWP_SHOWWINDOW | SWP_FRAMECHANGED);
+ c->n++;
+ }
+ return TRUE;
+ }, reinterpret_cast<LPARAM>(&ctx));
+ std::cout << "Hidden " << ctx.n << " runtime window(s) across " << pids.size() << " runtime process(es).\n";
+ return 0;
+ }
+
+ if (cmd == "doctor") {
+ auto report = wsm::core::probe_host_system(wsm::core::resolve_wsm_root() + "");
+ std::cout << wsm::core::host_report_to_json(report) << "\n";
+ return (report.whpx.partition_create_verified && report.primary_gpu.vulkan_supported) ? 0 : 1;
+ }
+
+ if (cmd == "vm-cmd") {
+ wsm::core::VmManager vm;
+ wsm::core::VmConfig cfg;
+ std::cout << vm.build_qemu_command(cfg) << "\n";
+ return 0;
+ }
+
+ if (cmd == "inspect" && argc >= 3) {
+ wsm::runtime::AppBundleInfo info;
+ std::string err;
+ if (!wsm::runtime::inspect_macos_app(argv[2], info, err)) {
+ std::cerr << "Error: " << err << "\n";
+ return 1;
+ }
+ std::cout << "Name: " << info.name << "\n"
+ << "Bundle ID: " << info.id << "\n"
+ << "Version: " << info.version << "\n"
+ << "Min macOS: " << info.min_macos << "\n"
+ << "Arch: " << wsm::runtime::arch_to_string(info.arch) << "\n"
+ << "ARM64 JIT: " << (info.requires_arm64_translation ? "required" : "native x86_64") << "\n"
+ << "Executable: " << info.executable_path << "\n";
+ return 0;
+ }
+
+ if (cmd == "apps") {
+ wsm::runtime::AppRegistry reg;
+ reg.load();
+ std::cout << reg.to_json();
+ return 0;
+ }
+
+ if (cmd == "import" && argc >= 3) {
+ wsm::runtime::AppRegistry reg;
+ reg.load();
+ wsm::runtime::AppBundleInfo info;
+ std::string err;
+ if (!reg.register_app(argv[2], info, err)) {
+ std::cerr << "Import failed: " << err << "\n";
+ return 1;
+ }
+ std::string ico_out = wsm::core::resolve_wsm_root() + "\\runtime\\apps\\icons\\" + info.id + ".ico";
+ if (!info.icon_path.empty()) {
+ wsm::runtime::convert_icns_to_ico(info.icon_path, ico_out);
+ }
+ std::string lnk_path;
+ wsm::runtime::create_app_start_menu_shortcut(info.name, info.id, ico_out, lnk_path);
+ std::cout << "Imported: " << info.name << " (" << info.id << ") ["
+ << wsm::runtime::arch_to_string(info.arch) << "]\n"
+ << "Start Menu: " << lnk_path << "\n";
+ return 0;
+ }
+
+ if (cmd == "open" && argc >= 3) {
+ // Double-click handler for .dmg / .pkg / .app from Windows Explorer
+ wsm::runtime::AppRegistry reg;
+ reg.load();
+ wsm::runtime::AppBundleInfo info;
+ std::string err;
+ if (!reg.register_app(argv[2], info, err)) {
+ std::cerr << "Open failed: " << err << "\n";
+ return 1;
+ }
+ std::string ico_out = wsm::core::resolve_wsm_root() + "\\runtime\\apps\\icons\\" + info.id + ".ico";
+ if (!info.icon_path.empty()) wsm::runtime::convert_icns_to_ico(info.icon_path, ico_out);
+ std::string lnk;
+ wsm::runtime::create_app_start_menu_shortcut(info.name, info.id, ico_out, lnk);
+ std::cout << "Registered & ready to launch: " << info.name << " (" << info.id << ")\n";
+ return 0;
+ }
+
+ if (cmd == "register-shell") {
+ std::string err;
+ if (!wsm::runtime::register_windows_shell_associations(wsm::core::resolve_wsm_root() + "\\build\\native\\bin\\wsm.exe", err)) {
+ std::cerr << "Shell registration failed: " << err << "\n";
+ return 1;
+ }
+ std::cout << "Registered Windows Explorer double-click handlers for .dmg, .pkg, and .app (HKCU).\n";
+ return 0;
+ }
+
+ if (cmd == "qmp-status") {
+ wsm::core::QmpUnixClient qmp;
+ std::string resp;
+ if (!qmp.execute("{\"execute\":\"query-status\"}", resp)) {
+ std::cerr << "QMP AF_UNIX query failed: " << resp << "\n";
+ return 1;
+ }
+ std::cout << resp << "\n";
+ return 0;
+ }
+
+ if (cmd == "qmp-type" && argc >= 3) {
+ wsm::core::QmpUnixClient qmp;
+ // Send Ctrl+C first to clear any partial bash line
+ std::string resp;
+ qmp.execute("{\"execute\":\"send-key\",\"arguments\":{\"keys\":[{\"type\":\"qcode\",\"data\":\"ctrl\"},{\"type\":\"qcode\",\"data\":\"c\"}],\"hold-time\":40}}", resp);
+ Sleep(200);
+ qmp.type_ascii_text(std::string(argv[2]) + "\n");
+ std::cout << "Cleared prompt and typed command into guest via AF_UNIX QMP.\n";
+ return 0;
+ }
+
+ if (cmd == "qmp-dump" && argc >= 3) {
+ wsm::core::QmpUnixClient qmp;
+ std::string ppm = wsm::core::resolve_wsm_root() + "\\cache\\tmp\\cli_screendump.ppm";
+ std::string err;
+ if (!qmp.capture_screendump_ppm(ppm, err)) {
+ std::cerr << "QMP screendump failed: " << err << "\n";
+ return 1;
+ }
+ std::vector<uint8_t> bmp;
+ if (!wsm::core::ppm_file_to_bmp_bytes(ppm, bmp)) {
+ std::cerr << "PPM -> BMP conversion failed\n";
+ return 1;
+ }
+ std::ofstream f(argv[2], std::ios::binary | std::ios::trunc);
+ f.write(reinterpret_cast<const char*>(bmp.data()), bmp.size());
+ std::cout << "Captured headless setup frame to " << argv[2] << " (" << bmp.size() << " bytes)\n";
+ return 0;
+ }
+
+ if (cmd == "bench") {
+ wsm::compositor::RootlessCompositor comp;
+ std::string err;
+ if (!comp.start({}, err)) {
+ std::cerr << "Compositor start failed: " << err << "\n";
+ return 1;
+ }
+ std::cout << "Benchmarking DirectComposition on " << comp.gpu_adapter_name() << " (1920x1080, 120 frames)...\n";
+ auto full = comp.benchmark_present(1920, 1080, 120, false);
+ auto dirty = comp.benchmark_present(1920, 1080, 120, true);
+ std::cout << " Full-frame 1080p : avg=" << full.avg_us << " us, p50=" << full.p50_us
+ << " us, p99=" << full.p99_us << " us (" << full.fps << " FPS)\n"
+ << " Dirty-rect 128x64: avg=" << dirty.avg_us << " us, p50=" << dirty.p50_us
+ << " us, p99=" << dirty.p99_us << " us (" << dirty.fps << " FPS)\n";
+ comp.stop();
+ return 0;
+ }
+
+ if (cmd == "compositor-verify") {
+ wsm::compositor::RootlessCompositor comp;
+ std::string err;
+ if (!comp.start({}, err)) {
+ std::cerr << "Compositor start failed: " << err << "\n";
+ return 1;
+ }
+ std::cout << "DirectComposition initialized on GPU: " << comp.gpu_adapter_name() << "\n";
+
+ wsm::proto::WindowDescriptor desc{};
+ desc.window_id = 1001;
+ desc.pid = GetCurrentProcessId();
+ desc.bounds = {120, 120, 640, 360};
+ desc.visible = 1;
+ comp.create_or_update_window(desc, "WSM DirectComposition Hardware Surface Check");
+ Sleep(150);
+
+ std::vector<uint8_t> pixels(640u * 360u * 4u, 0xFF);
+ for (uint32_t y = 0; y < 360; ++y) {
+ for (uint32_t x = 0; x < 640; ++x) {
+ size_t idx = (y * 640u + x) * 4u;
+ pixels[idx + 0] = static_cast<uint8_t>((x * 255) / 640); // B
+ pixels[idx + 1] = static_cast<uint8_t>((y * 255) / 360); // G
+ pixels[idx + 2] = 48; // R
+ pixels[idx + 3] = 255; // A
+ }
+ }
+ bool presented = comp.present_bgra_frame(1001, 640, 360, 640 * 4, pixels.data());
+ auto wins = comp.list_windows();
+ std::cout << "Presented hardware frame: " << (presented ? "OK" : "FAIL")
+ << " | Active windows: " << wins.size() << "\n";
+ Sleep(250);
+ comp.destroy_window(1001);
+ Sleep(100);
+ comp.stop();
+ return presented ? 0 : 1;
+ }
+
+ if (cmd == "audio-verify") {
+ wsm::services::WasapiAudioBridge audio;
+ if (!audio.initialize(48000, 2)) {
+ std::cerr << "WASAPI initialization failed.\n";
+ return 1;
+ }
+ std::cout << "WASAPI initialized on endpoint: " << audio.device_name() << "\n";
+ std::vector<float> silence(480 * 2, 0.0f);
+ bool ok = audio.write_float_pcm(silence.data(), 480);
+ std::cout << "PCM buffer submission: " << (ok ? "OK" : "FAIL") << "\n";
+ audio.shutdown();
+ return ok ? 0 : 1;
+ }
+
+ print_usage();
+ return 1;
+}
diff --git a/src/wsm-runtime/src/wsm_manager_launcher.cpp b/src/wsm-runtime/src/wsm_manager_launcher.cpp
new file mode 100644
index 0000000..64d196e
--- /dev/null
+++ b/src/wsm-runtime/src/wsm_manager_launcher.cpp
@@ -0,0 +1,228 @@
+// WsmManager.exe — True Native Win32 + Windows 11 DWM Dark/Mica + Embedded WebView2 Desktop Application
+// No external Edge browser window, no --app= flag, no browser chrome.
+// Automatically starts wsmd.exe in the background and hosts the WSM Manager interface inside a native HWND.
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#include <dwmapi.h>
+#include <shlobj.h>
+#include <wrl.h>
+#include <WebView2.h>
+
+#include "wsm/paths.hpp"
+
+#include <filesystem>
+#include <string>
+
+#pragma comment(lib, "ws2_32.lib")
+#pragma comment(lib, "dwmapi.lib")
+#pragma comment(lib, "ole32.lib")
+#pragma comment(lib, "user32.lib")
+
+using Microsoft::WRL::Callback;
+using Microsoft::WRL::ComPtr;
+
+namespace {
+
+ComPtr<ICoreWebView2Controller> g_controller;
+ComPtr<ICoreWebView2> g_webview;
+
+std::wstring utf8_to_wide(const std::string& s) {
+ if (s.empty()) return {};
+ int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), static_cast<int>(s.size()), nullptr, 0);
+ if (len <= 0) return {};
+ std::wstring out(static_cast<size_t>(len), L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), static_cast<int>(s.size()), out.data(), len);
+ return out;
+}
+
+bool is_wsmd_listening() {
+ WSADATA wsa{};
+ if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return false;
+ SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ bool ok = false;
+ if (s != INVALID_SOCKET) {
+ sockaddr_in addr{};
+ addr.sin_family = AF_INET;
+ addr.sin_port = htons(17421);
+ inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
+ ok = (connect(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == 0);
+ closesocket(s);
+ }
+ WSACleanup();
+ return ok;
+}
+
+std::wstring exe_dir() {
+ wchar_t buf[MAX_PATH] = {};
+ GetModuleFileNameW(nullptr, buf, MAX_PATH);
+ return std::filesystem::path(buf).parent_path().wstring();
+}
+
+void ensure_wsmd_running() {
+ if (is_wsmd_listening()) return;
+ std::wstring wsmd_path = exe_dir() + L"\\wsmd.exe";
+ STARTUPINFOW si{};
+ si.cb = sizeof(si);
+ PROCESS_INFORMATION pi{};
+ if (CreateProcessW(wsmd_path.c_str(), nullptr, nullptr, nullptr, FALSE,
+ CREATE_NO_WINDOW, nullptr, exe_dir().c_str(), &si, &pi)) {
+ CloseHandle(pi.hThread);
+ CloseHandle(pi.hProcess);
+ for (int i = 0; i < 40; ++i) {
+ Sleep(80);
+ if (is_wsmd_listening()) break;
+ }
+ }
+}
+
+LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
+ switch (msg) {
+ case WM_SIZE:
+ if (g_controller) {
+ RECT bounds{};
+ GetClientRect(hwnd, &bounds);
+ g_controller->put_Bounds(bounds);
+ }
+ return 0;
+ case WM_GETMINMAXINFO: {
+ auto* mmi = reinterpret_cast<MINMAXINFO*>(lParam);
+ mmi->ptMinTrackSize.x = 960;
+ mmi->ptMinTrackSize.y = 640;
+ return 0;
+ }
+ case WM_DESTROY:
+ PostQuitMessage(0);
+ return 0;
+ default:
+ return DefWindowProcW(hwnd, msg, wParam, lParam);
+ }
+}
+
+} // namespace
+
+int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
+
+ ensure_wsmd_running();
+
+ WNDCLASSEXW wc{};
+ wc.cbSize = sizeof(wc);
+ wc.lpfnWndProc = WndProc;
+ wc.hInstance = hInstance;
+ wc.hCursor = LoadCursorW(nullptr, IDC_ARROW);
+ wc.hbrBackground = static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH));
+ wc.lpszClassName = L"WsmNativeManagerWindow";
+ wc.hIcon = LoadIconW(hInstance, MAKEINTRESOURCEW(1));
+ wc.hIconSm = static_cast<HICON>(LoadImageW(hInstance, MAKEINTRESOURCEW(1), IMAGE_ICON, 16, 16, 0));
+ RegisterClassExW(&wc);
+
+ int sw = GetSystemMetrics(SM_CXSCREEN);
+ int sh = GetSystemMetrics(SM_CYSCREEN);
+ int w = 1280, h = 820;
+ int x = (sw - w) / 2, y = (sh - h) / 2;
+
+ HWND hwnd = CreateWindowExW(
+ 0, L"WsmNativeManagerWindow", L"WSM",
+ WS_OVERLAPPEDWINDOW, x, y, w, h,
+ nullptr, nullptr, hInstance, nullptr
+ );
+ if (!hwnd) {
+ CoUninitialize();
+ return 1;
+ }
+
+ // Enable Windows 11 Immersive Dark Titlebar & Mica Backdrop
+ BOOL dark = TRUE;
+ DwmSetWindowAttribute(hwnd, 20 /* DWMWA_USE_IMMERSIVE_DARK_MODE */, &dark, sizeof(dark));
+ DWORD backdrop = 2; /* DWMSBT_MAINWINDOW (Mica) */
+ DwmSetWindowAttribute(hwnd, 38 /* DWMWA_SYSTEMBACKDROP_TYPE */, &backdrop, sizeof(backdrop));
+
+ ShowWindow(hwnd, nCmdShow);
+ UpdateWindow(hwnd);
+
+ std::wstring user_data_dir = utf8_to_wide(wsm::core::resolve_wsm_root() + "\\cache\\webview2");
+ std::filesystem::create_directories(user_data_dir);
+
+ CreateCoreWebView2EnvironmentWithOptions(
+ nullptr, user_data_dir.c_str(), nullptr,
+ Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
+ [hwnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT {
+ if (FAILED(result) || !env) return result;
+ env->CreateCoreWebView2Controller(
+ hwnd,
+ Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
+ [hwnd](HRESULT res, ICoreWebView2Controller* ctrl) -> HRESULT {
+ if (FAILED(res) || !ctrl) return res;
+ g_controller = ctrl;
+ g_controller->get_CoreWebView2(&g_webview);
+
+ ComPtr<ICoreWebView2Settings> settings;
+ if (SUCCEEDED(g_webview->get_Settings(&settings))) {
+ settings->put_AreDefaultContextMenusEnabled(FALSE);
+ settings->put_AreDevToolsEnabled(FALSE);
+ settings->put_IsStatusBarEnabled(FALSE);
+ settings->put_IsZoomControlEnabled(FALSE);
+ }
+
+ RECT bounds{};
+ GetClientRect(hwnd, &bounds);
+ g_controller->put_Bounds(bounds);
+ // Transparent WebView so the window's Mica backdrop shows through.
+ ComPtr<ICoreWebView2Controller2> c2;
+ if (SUCCEEDED(g_controller.As(&c2))) c2->put_DefaultBackgroundColor({0, 0, 0, 0});
+ const bool ready = std::filesystem::exists(wsm::core::resolve_wsm_root() + "\\runtime\\config\\runtime-ready.json");
+ std::wstring url = ready ? L"http://127.0.0.1:17421/" : L"http://127.0.0.1:17421/setup";
+ if (ready && wcsstr(GetCommandLineW(), L"--settings")) url += L"#settings";
+ // Drag and drop: the page posts dropped files ("install"); a web page
+ // can't see file paths, so the host reads them and hands them back.
+ g_webview->add_WebMessageReceived(
+ Callback<ICoreWebView2WebMessageReceivedEventHandler>(
+ [](ICoreWebView2*, ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT {
+ ComPtr<ICoreWebView2WebMessageReceivedEventArgs2> a2;
+ ComPtr<ICoreWebView2ObjectCollectionView> objs;
+ if (FAILED(ComPtr<ICoreWebView2WebMessageReceivedEventArgs>(args).As(&a2)) ||
+ FAILED(a2->get_AdditionalObjects(&objs)) || !objs) return S_OK;
+ UINT32 n = 0;
+ objs->get_Count(&n);
+ for (UINT32 i = 0; i < n; ++i) {
+ ComPtr<IUnknown> o;
+ ComPtr<ICoreWebView2File> file;
+ LPWSTR path = nullptr;
+ if (FAILED(objs->GetValueAtIndex(i, &o)) || FAILED(o.As(&file)) ||
+ FAILED(file->get_Path(&path)) || !path) continue;
+ std::wstring json = L"{\"installPath\":\"";
+ for (const wchar_t* c = path; *c; ++c) {
+ if (*c == L'\\' || *c == L'"') json += L'\\';
+ json += *c;
+ }
+ json += L"\"}";
+ CoTaskMemFree(path);
+ if (g_webview) g_webview->PostWebMessageAsJson(json.c_str());
+ }
+ return S_OK;
+ }).Get(),
+ nullptr);
+ g_webview->Navigate(url.c_str());
+ return S_OK;
+ }
+ ).Get()
+ );
+ return S_OK;
+ }
+ ).Get()
+ );
+
+ MSG msg{};
+ while (GetMessageW(&msg, nullptr, 0, 0) > 0) {
+ TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
+
+ g_webview.Reset();
+ g_controller.Reset();
+ CoUninitialize();
+ return 0;
+}
diff --git a/src/wsm-runtime/src/wsmd.cpp b/src/wsm-runtime/src/wsmd.cpp
new file mode 100644
index 0000000..bce7fdd
--- /dev/null
+++ b/src/wsm-runtime/src/wsmd.cpp
@@ -0,0 +1,1239 @@
+#include "wsm/host_probe.hpp"
+#include "wsm/vm_manager.hpp"
+#include "wsm/paths.hpp"
+#include "wsm/qmp_unix.hpp"
+#include "wsm/compositor.hpp"
+#include "wsm/services.hpp"
+#include "wsm/app_registry.hpp"
+#include "wsm/guest_bridge.hpp"
+#include "wsm/shell_integration.hpp"
+#include "wsm/protocol.hpp"
+#include "wsm/provisioner.hpp"
+#include "wsm/webdav_server.hpp"
+#include "wsm/runtime_host.hpp"
+#include "wsm/window_streamer.hpp"
+#include "wsm/app_installer.hpp"
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#include <winioctl.h>
+#include <commdlg.h>
+#include <shellapi.h>
+#include <tlhelp32.h>
+
+#include <atomic>
+#include <chrono>
+#include <cctype>
+#include <random>
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <mutex>
+#include <set>
+#include <sstream>
+#include <string>
+#include <thread>
+#include <vector>
+
+#pragma comment(lib, "ws2_32.lib")
+#pragma comment(lib, "shell32.lib")
+#pragma comment(lib, "comdlg32.lib")
+
+namespace {
+
+std::string read_file_text(const std::string& path) {
+ std::ifstream f(path, std::ios::binary);
+ if (!f) return {};
+ std::ostringstream ss;
+ ss << f.rdbuf();
+ return ss.str();
+}
+
+std::string read_full_http_request(SOCKET client) {
+ DWORD timeout_ms = 2000;
+ setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&timeout_ms), sizeof(timeout_ms));
+
+ std::string req;
+ char buf[4096];
+ size_t header_end = std::string::npos;
+ size_t content_length = 0;
+
+ while (req.size() < 262144) {
+ int n = recv(client, buf, sizeof(buf), 0);
+ if (n <= 0) break;
+ req.append(buf, static_cast<size_t>(n));
+
+ if (header_end == std::string::npos) {
+ header_end = req.find("\r\n\r\n");
+ if (header_end != std::string::npos) {
+ // Case-insensitive search for Content-Length
+ std::string lower = req.substr(0, header_end);
+ for (char& c : lower) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
+ auto cl_pos = lower.find("content-length:");
+ if (cl_pos != std::string::npos) {
+ size_t val_start = cl_pos + 15;
+ while (val_start < lower.size() && (lower[val_start] == ' ' || lower[val_start] == '\t')) ++val_start;
+ content_length = static_cast<size_t>(std::strtoull(lower.c_str() + val_start, nullptr, 10));
+ }
+ }
+ }
+ if (header_end != std::string::npos) {
+ size_t body_have = req.size() - (header_end + 4);
+ if (body_have >= content_length) break;
+ }
+ }
+ return req;
+}
+
+std::string pick_macos_file_dialog() {
+ std::string out;
+ // Run GetOpenFileNameW on a dedicated STA thread so it never deadlocks wsmd's MTA thread
+ std::thread sta_dlg([&]() {
+ HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
+ wchar_t file_buf[MAX_PATH * 4] = {};
+ HWND owner = FindWindowW(L"WsmNativeManagerWindow", nullptr);
+ if (owner) SetForegroundWindow(owner);
+ OPENFILENAMEW ofn{};
+ ofn.lStructSize = sizeof(ofn);
+ ofn.hwndOwner = owner;
+ ofn.lpstrFilter = L"macOS Apps & Installers (*.dmg;*.pkg;*.zip;*.gz;*.tgz;*.mpkg)\0*.dmg;*.pkg;*.zip;*.gz;*.tgz;*.mpkg\0All Files (*.*)\0*.*\0";
+ ofn.lpstrFile = file_buf;
+ ofn.nMaxFile = MAX_PATH * 4;
+ ofn.lpstrTitle = L"Select a macOS Application (.dmg, .pkg, .zip)";
+ ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR;
+ if (GetOpenFileNameW(&ofn)) {
+ int len = WideCharToMultiByte(CP_UTF8, 0, file_buf, -1, nullptr, 0, nullptr, nullptr);
+ if (len > 1) {
+ out.resize(static_cast<size_t>(len - 1));
+ WideCharToMultiByte(CP_UTF8, 0, file_buf, -1, out.data(), len, nullptr, nullptr);
+ }
+ }
+ if (SUCCEEDED(hr)) CoUninitialize();
+ });
+ sta_dlg.join();
+ return out;
+}
+
+std::string extract_http_body(const std::string& req) {
+ auto pos = req.find("\r\n\r\n");
+ if (pos == std::string::npos) return {};
+ return req.substr(pos + 4);
+}
+
+std::atomic<bool> g_running{true};
+
+BOOL WINAPI console_ctrl_handler(DWORD) {
+ g_running.store(false);
+ return TRUE;
+}
+
+std::string http_response(int code, const std::string& status, const std::string& body,
+ const std::string& content_type = "application/json") {
+ std::ostringstream oss;
+ oss << "HTTP/1.1 " << code << " " << status << "\r\n"
+ << "Content-Type: " << content_type << "\r\n"
+ << "Access-Control-Allow-Origin: *\r\n"
+ << "Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS\r\n"
+ << "Access-Control-Allow-Headers: Content-Type\r\n"
+ << "Content-Length: " << body.size() << "\r\n"
+ << "Connection: close\r\n\r\n"
+ << body;
+ return oss.str();
+}
+
+std::string url_decode(const std::string& s) {
+ std::string out;
+ for (size_t i = 0; i < s.size(); ++i) {
+ if (s[i] == '%' && i + 2 < s.size()) { out.push_back(static_cast<char>(std::stoi(s.substr(i + 1, 2), nullptr, 16))); i += 2; }
+ else if (s[i] == '+') out.push_back(' ');
+ else out.push_back(s[i]);
+ }
+ return out;
+}
+
+// The app's icon as PNG: the PNG payload stored inside the .ico written at import time.
+std::string icon_png_cached(const std::string& root, const wsm::runtime::AppBundleInfo& info) {
+ std::string ico = root + "\\runtime\\apps\\icons\\" + info.id + ".ico";
+ if (!std::filesystem::exists(ico) && !info.icon_path.empty())
+ wsm::runtime::convert_icns_to_ico(info.icon_path, ico);
+ std::ifstream f(ico, std::ios::binary);
+ if (!f) return {};
+ std::string d((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ auto p = d.find("\x89PNG");
+ return p == std::string::npos ? std::string{} : d.substr(p);
+}
+
+// Collects logs into %USERPROFILE%\Desktop\WSM-diagnostics-<time>.txt with the user name redacted.
+bool export_diagnostics(const std::string& root, std::string& out_path) {
+ namespace fs = std::filesystem;
+ char user[256] = {}; DWORD n = sizeof(user); GetUserNameA(user, &n);
+ char prof[MAX_PATH] = {}; GetEnvironmentVariableA("USERPROFILE", prof, MAX_PATH);
+ auto redact = [&](std::string s) {
+ for (const std::string& needle : {std::string(prof), std::string(user)}) {
+ if (needle.size() < 2) continue;
+ for (size_t p; (p = s.find(needle)) != std::string::npos;) s.replace(p, needle.size(), "<redacted>");
+ }
+ return s;
+ };
+ auto tail = [](const fs::path& p, size_t max) {
+ std::ifstream f(p, std::ios::binary);
+ if (!f) return std::string("(missing)\n");
+ std::string d((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ return d.size() > max ? d.substr(d.size() - max) : d;
+ };
+ std::ostringstream r;
+ r << "WSM diagnostic report\n\n";
+ MEMORYSTATUSEX ms{}; ms.dwLength = sizeof(ms); GlobalMemoryStatusEx(&ms);
+ r << "Host RAM: " << (ms.ullTotalPhys >> 20) << " MiB total, " << (ms.ullAvailPhys >> 20) << " MiB free\n";
+ fs::path vmdir = fs::path(root) / "runtime" / "reims-ctl" / "vms" / "wsm-default";
+ r << "\n== vm.toml ==\n" << tail(vmdir / "vm.toml", 8192);
+ r << "\n== runtime log (tail) ==\n" << tail(vmdir / "logs" / "qemu.log", 64 * 1024);
+ r << "\n== daemon runtime log (tail) ==\n" << tail(fs::path(root) / "logs" / "wsm-default-qemu.log", 32 * 1024);
+ r << "\n== serial (tail) ==\n" << tail(fs::path(root) / "logs" / "wsm-default-serial.log", 16 * 1024);
+ r << "\n== apps.json ==\n" << tail(fs::path(root) / "runtime" / "config" / "apps.json", 32 * 1024);
+ char stamp[32]; SYSTEMTIME st; GetLocalTime(&st);
+ snprintf(stamp, sizeof(stamp), "%04d%02d%02d-%02d%02d%02d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
+ fs::path out = fs::path(prof) / "Desktop" / (std::string("WSM-diagnostics-") + stamp + ".txt");
+ std::ofstream o(out, std::ios::binary);
+ if (!o) return false;
+ o << redact(r.str());
+ out_path = out.string();
+ return true;
+}
+
+// The macOS runtime must stay invisible: any top-level window owned by a QEMU process is hidden.
+void hide_runtime_windows_once() {
+ std::vector<DWORD> pids;
+ HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
+ PROCESSENTRY32W pe{}; pe.dwSize = sizeof(pe);
+ if (snap == INVALID_HANDLE_VALUE) return;
+ if (Process32FirstW(snap, &pe)) do {
+ if (_wcsicmp(pe.szExeFile, L"qemu-system-x86_64.exe") == 0) pids.push_back(pe.th32ProcessID);
+ } while (Process32NextW(snap, &pe));
+ CloseHandle(snap);
+ if (pids.empty()) return;
+ EnumWindows([](HWND h, LPARAM l) -> BOOL {
+ auto* v = reinterpret_cast<std::vector<DWORD>*>(l);
+ DWORD pid = 0; GetWindowThreadProcessId(h, &pid);
+ // SW_HIDE would stall reims-vgpu's swapchain and freeze the guest's display, so the window
+ // stays rendered but off-screen, out of the taskbar and Alt+Tab, and click-through.
+ for (DWORD p : *v) if (p == pid) {
+ wchar_t cls[64]{}; GetClassNameW(h, cls, 64);
+ if (wcscmp(cls, L"IME") == 0 || wcscmp(cls, L"MSCTFIME UI") == 0) continue;
+ RECT r{}; GetWindowRect(h, &r);
+ LONG_PTR ex = GetWindowLongPtrW(h, GWL_EXSTYLE);
+ if ((ex & WS_EX_TOOLWINDOW) && r.left <= -30000) continue; // already parked
+ ex = (ex | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_TRANSPARENT) & ~WS_EX_APPWINDOW;
+ SetWindowLongPtrW(h, GWL_EXSTYLE, ex);
+ SetWindowPos(h, HWND_BOTTOM, -32000, -32000, r.right - r.left, r.bottom - r.top,
+ SWP_NOACTIVATE | SWP_SHOWWINDOW | SWP_FRAMECHANGED);
+ }
+ return TRUE;
+ }, reinterpret_cast<LPARAM>(&pids));
+}
+
+std::string json_escape_str(const std::string& s) {
+ std::string out;
+ out.reserve(s.size() + 16);
+ for (unsigned char c : s) {
+ switch (c) {
+ case '"': out += "\\\""; break;
+ case '\\': out += "\\\\"; break;
+ case '\n': out += "\\n"; break;
+ case '\r': break;
+ case '\t': out += "\\t"; break;
+ default:
+ if (c >= 0x20) out.push_back(static_cast<char>(c));
+ break;
+ }
+ }
+ return out;
+}
+
+struct ProvisionState {
+ std::mutex mutex;
+ bool running = false;
+ std::string stage = "idle";
+ int percent = 0;
+ int exit_code = 0;
+ HANDLE proc = nullptr;
+ std::vector<std::string> logs;
+
+ void append_log(const std::string& line) {
+ std::lock_guard<std::mutex> lock(mutex);
+ logs.push_back(line);
+ if (logs.size() > 250) logs.erase(logs.begin());
+
+ // Infer real progress stage from reims-ctl / deploy-agent output
+ if (line.find("download") != std::string::npos || line.find("Download") != std::string::npos || line.find("Fetching") != std::string::npos) {
+ stage = "Downloading macOS installer from Apple...";
+ if (percent < 35) percent = 35;
+ } else if (line.find("OpenCore") != std::string::npos || line.find("opencore") != std::string::npos) {
+ stage = "Configuring OpenCore & reims-vgpu Metal drivers...";
+ if (percent < 65) percent = 65;
+ } else if (line.find("disk") != std::string::npos || line.find("qcow2") != std::string::npos || line.find("Creating") != std::string::npos) {
+ stage = "Allocating APFS virtual disk on " + wsm::core::resolve_wsm_root() + "...";
+ if (percent < 80) percent = 80;
+ } else if (line.find("Starting") != std::string::npos || line.find("QEMU") != std::string::npos) {
+ stage = "Booting WHPX macOS environment...";
+ if (percent < 92) percent = 92;
+ } else if (line.find("Guest agent deployed") != std::string::npos) {
+ stage = "WSM Guest Agent installed and running";
+ percent = 100;
+ }
+ }
+
+ bool start_command(const std::string& cmdline, const std::string& initial_stage) {
+ std::lock_guard<std::mutex> lock(mutex);
+ if (running) return false;
+ logs.clear();
+ running = true;
+ stage = initial_stage;
+ percent = 10;
+ exit_code = 0;
+
+ SECURITY_ATTRIBUTES sa{};
+ sa.nLength = sizeof(sa);
+ sa.bInheritHandle = TRUE;
+ HANDLE hRead = nullptr, hWrite = nullptr;
+ if (!CreatePipe(&hRead, &hWrite, &sa, 0)) {
+ running = false;
+ stage = "Failed to create output pipe";
+ return false;
+ }
+ SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0);
+
+ SetEnvironmentVariableA("XDG_DATA_HOME", (wsm::core::resolve_wsm_root() + "\\runtime").c_str());
+ SetEnvironmentVariableA("XDG_CACHE_HOME", (wsm::core::resolve_wsm_root() + "\\cache").c_str());
+
+ STARTUPINFOA si{};
+ si.cb = sizeof(si);
+ si.dwFlags = STARTF_USESTDHANDLES;
+ si.hStdOutput = hWrite;
+ si.hStdError = hWrite;
+ PROCESS_INFORMATION pi{};
+
+ std::string mutable_cmd = cmdline;
+ BOOL ok = CreateProcessA(nullptr, mutable_cmd.data(), nullptr, nullptr, TRUE,
+ CREATE_NO_WINDOW, nullptr, (wsm::core::resolve_wsm_root() + "\\runtime").c_str(), &si, &pi);
+ CloseHandle(hWrite);
+ if (!ok) {
+ CloseHandle(hRead);
+ running = false;
+ stage = "Failed to launch provisioning process";
+ return false;
+ }
+ CloseHandle(pi.hThread);
+ proc = pi.hProcess;
+
+ std::thread([this, hRead, hProc = pi.hProcess]() {
+ char buf[512];
+ DWORD read = 0;
+ std::string partial;
+ while (ReadFile(hRead, buf, sizeof(buf) - 1, &read, nullptr) && read > 0) {
+ buf[read] = '\0';
+ partial += buf;
+ size_t pos = 0;
+ while ((pos = partial.find('\n')) != std::string::npos) {
+ std::string line = partial.substr(0, pos);
+ if (!line.empty() && line.back() == '\r') line.pop_back();
+ if (!line.empty()) append_log(line);
+ partial.erase(0, pos + 1);
+ }
+ }
+ if (!partial.empty()) append_log(partial);
+ CloseHandle(hRead);
+
+ WaitForSingleObject(hProc, INFINITE);
+ DWORD code = 0;
+ GetExitCodeProcess(hProc, &code);
+ CloseHandle(hProc);
+
+ std::lock_guard<std::mutex> lk(mutex);
+ proc = nullptr;
+ exit_code = static_cast<int>(code);
+ running = false;
+ if (code == 0) {
+ percent = 100;
+ stage = "Completed successfully";
+ } else {
+ stage = "Exited with code " + std::to_string(code);
+ }
+ }).detach();
+ return true;
+ }
+
+ void cancel() {
+ std::lock_guard<std::mutex> lock(mutex);
+ if (proc) {
+ TerminateProcess(proc, 1);
+ }
+ }
+
+ std::string to_json() {
+ std::lock_guard<std::mutex> lock(mutex);
+ std::ostringstream oss;
+ oss << "{\"running\":" << (running ? "true" : "false")
+ << ",\"stage\":\"" << json_escape_str(stage) << "\""
+ << ",\"percent\":" << percent
+ << ",\"exit_code\":" << exit_code
+ << ",\"reims_ctl_ready\":" << (std::filesystem::exists(wsm::core::resolve_wsm_root() + "\\cache\\cargo\\bin\\reims-ctl.exe") ? "true" : "false")
+ << ",\"qemu_ready\":" << (std::filesystem::exists(wsm::core::resolve_wsm_root() + "\\runtime\\reims-ctl\\qemu\\current\\bin\\qemu-system-x86_64.exe") ? "true" : "false")
+ << ",\"vm_exists\":" << (std::filesystem::exists(wsm::core::resolve_wsm_root() + "\\runtime\\reims-ctl\\vms\\wsm-default\\vm.toml") ? "true" : "false")
+ << ",\"logs\":[";
+ for (size_t i = 0; i < logs.size(); ++i) {
+ oss << "\"" << json_escape_str(logs[i]) << "\"" << (i + 1 < logs.size() ? "," : "");
+ }
+ oss << "]}";
+ return oss.str();
+ }
+};
+
+std::string vm_state_to_string(wsm::core::VmState s) {
+ switch (s) {
+ case wsm::core::VmState::NotInstalled: return "not_installed";
+ case wsm::core::VmState::Stopped: return "stopped";
+ case wsm::core::VmState::Starting: return "starting";
+ case wsm::core::VmState::Booting: return "booting";
+ case wsm::core::VmState::WaitingForGuest: return "waiting_for_guest";
+ case wsm::core::VmState::Ready: return "ready";
+ case wsm::core::VmState::Paused: return "paused";
+ case wsm::core::VmState::Stopping: return "stopping";
+ case wsm::core::VmState::Crashed: return "crashed";
+ }
+ return "unknown";
+}
+
+} // namespace
+
+// What kind of drive holds the runtime. macOS reads its disk constantly; on a spinning or USB
+// disk everything (boot, app launch, even drawing) waits on it, so WSM says so.
+struct StorageInfo { std::string bus; bool spinning = false; bool removable = false; };
+StorageInfo probe_storage(const std::string& path) {
+ StorageInfo out;
+ if (path.size() < 2 || path[1] != ':') return out;
+ std::string dev = std::string("\\\\.\\") + path.substr(0, 2);
+ HANDLE h = CreateFileA(dev.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
+ if (h == INVALID_HANDLE_VALUE) return out;
+ DWORD got = 0;
+ STORAGE_PROPERTY_QUERY q{};
+ q.PropertyId = StorageDeviceProperty; q.QueryType = PropertyStandardQuery;
+ std::vector<uint8_t> buf(1024);
+ if (DeviceIoControl(h, IOCTL_STORAGE_QUERY_PROPERTY, &q, sizeof(q), buf.data(), static_cast<DWORD>(buf.size()), &got, nullptr)) {
+ auto* d = reinterpret_cast<STORAGE_DEVICE_DESCRIPTOR*>(buf.data());
+ out.removable = d->RemovableMedia != 0;
+ switch (d->BusType) {
+ case BusTypeUsb: out.bus = "usb"; break;
+ case BusTypeNvme: out.bus = "nvme"; break;
+ case BusTypeSata: case BusTypeAta: out.bus = "sata"; break;
+ default: out.bus = "other"; break;
+ }
+ }
+ q.PropertyId = StorageDeviceSeekPenaltyProperty;
+ DEVICE_SEEK_PENALTY_DESCRIPTOR sp{};
+ if (DeviceIoControl(h, IOCTL_STORAGE_QUERY_PROPERTY, &q, sizeof(q), &sp, sizeof(sp), &got, nullptr))
+ out.spinning = sp.IncursSeekPenalty != 0;
+ CloseHandle(h);
+ return out;
+}
+
+struct WindowStreamerHook { wsm::runtime::WindowStreamer* streamer; wsm::runtime::RuntimeHost* runtime; };
+WindowStreamerHook* g_end_hook = nullptr;
+
+LRESULT CALLBACK end_session_proc(HWND h, UINT msg, WPARAM wp, LPARAM lp) {
+ if (msg == WM_QUERYENDSESSION) {
+ ShutdownBlockReasonCreate(h, L"Closing your Mac apps safely");
+ return TRUE;
+ }
+ if (msg == WM_ENDSESSION && wp && g_end_hook) {
+ auto st = g_end_hook->runtime->status().state;
+ if (st == wsm::runtime::RtState::Paused) { std::string e; g_end_hook->runtime->resume(e); Sleep(1500); }
+ if (st == wsm::runtime::RtState::Running || st == wsm::runtime::RtState::Paused) {
+ g_end_hook->streamer->quick("sync; sudo shutdown -h now", nullptr, 8000);
+ for (int i = 0; i < 90 && g_end_hook->runtime->status().pid; ++i) Sleep(500); // up to 45 s
+ }
+ ShutdownBlockReasonDestroy(h);
+ return 0;
+ }
+ return DefWindowProcW(h, msg, wp, lp);
+}
+
+// cpus and memory (MB) of the runtime, as reims-ctl will start it.
+std::pair<int, int> runtime_size() {
+ int cpus = 4, mem = 4096;
+ std::ifstream f(wsm::core::resolve_wsm_root() + "\\runtime\\reims-ctl\\vms\\wsm-default\\vm.toml");
+ std::string line;
+ while (std::getline(f, line)) {
+ if (line.rfind("cpus = ", 0) == 0) cpus = std::atoi(line.c_str() + 7);
+ else if (line.rfind("memory_mib = ", 0) == 0) mem = std::atoi(line.c_str() + 13);
+ }
+ return {cpus, mem};
+}
+
+int main() {
+ SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
+
+ WSADATA wsa{};
+ if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
+ std::cerr << "[wsmd] WSAStartup failed\n";
+ return 1;
+ }
+
+ const std::string wsm_root = wsm::core::resolve_wsm_root();
+ const std::string ui_dir = std::filesystem::exists(wsm_root + "\\src\\wsm-manager\\index.html")
+ ? (wsm_root + "\\src\\wsm-manager")
+ : (wsm_root + "\\ui");
+
+ wsm::core::VmManager vm;
+ wsm::core::VmConfig vm_cfg;
+ wsm::core::compute_recommended_guest_resources(vm_cfg.vcpus, vm_cfg.ram_mb);
+ vm_cfg.shared_dir = wsm_root + "\\fs";
+ ProvisionState provision;
+ wsm::runtime::Provisioner provisioner(wsm_root);
+ wsm::runtime::RuntimeHost runtime(wsm_root);
+ wsm::compositor::RootlessCompositor compositor;
+ wsm::services::ClipboardBridge clipboard;
+ wsm::services::WasapiAudioBridge audio;
+ wsm::services::SharedFolderManager shared_folders;
+ wsm::runtime::AppRegistry apps(wsm_root + "\\runtime\\config\\apps.json");
+ apps.load();
+
+ wsm::runtime::GuestBridge guest_bridge(compositor, clipboard, audio);
+ // Mac app windows on the Windows desktop (window list over SSH, pixels and input over QMP).
+ wsm::runtime::WindowStreamer streamer(compositor, wsm_root);
+ std::mutex apps_mu; // the registry is shared by HTTP requests and the installer thread
+ wsm::runtime::AppInstaller installer(wsm_root, runtime, streamer, apps, apps_mu);
+
+ wsm::compositor::InputCallbacks input_cbs{};
+ input_cbs.on_key = [&](const wsm::proto::InputKeyEvent& ev) {
+ if (streamer.on_key(ev)) return;
+ guest_bridge.send_frame(wsm::proto::Channel::Window, wsm::proto::MsgType::InputKey, &ev, sizeof(ev));
+ };
+ input_cbs.on_mouse_move = [&](const wsm::proto::InputMouseMoveEvent& ev) {
+ if (streamer.on_mouse_move(ev)) return;
+ guest_bridge.send_frame(wsm::proto::Channel::Window, wsm::proto::MsgType::InputMouseMove, &ev, sizeof(ev));
+ };
+ input_cbs.on_mouse_button = [&](const wsm::proto::InputMouseButtonEvent& ev) {
+ if (streamer.on_mouse_button(ev)) return;
+ guest_bridge.send_frame(wsm::proto::Channel::Window, wsm::proto::MsgType::InputMouseButton, &ev, sizeof(ev));
+ };
+ input_cbs.on_scroll = [&](const wsm::proto::InputScrollEvent& ev) {
+ if (streamer.on_scroll(ev)) return;
+ guest_bridge.send_frame(wsm::proto::Channel::Window, wsm::proto::MsgType::InputScroll, &ev, sizeof(ev));
+ };
+ input_cbs.on_window_action = [&](const wsm::proto::WindowActionEvent& ev) {
+ if (streamer.on_window_action(ev)) return;
+ guest_bridge.send_frame(wsm::proto::Channel::Window, wsm::proto::MsgType::WindowAction, &ev, sizeof(ev));
+ };
+
+ input_cbs.hit_caption = [&](uint64_t id, int x, int y) { return streamer.hit_caption(id, x, y); };
+
+ std::string err;
+ if (compositor.start(input_cbs, err)) {
+ std::cout << "[wsmd] DirectComposition compositor ready on " << compositor.gpu_adapter_name() << "\n";
+ } else {
+ std::cerr << "[wsmd] Compositor warning: " << err << "\n";
+ }
+
+ // Shared clipboard: Windows <-> the Mac apps (text).
+ clipboard.start([&](const std::string& text) { streamer.set_guest_clipboard(text); });
+ streamer.set_on_guest_clipboard([&](const std::string& text) { clipboard.set_host_text(text); });
+
+ // (The old in-guest agent bridge isn't started: windows, input and launching go through the
+ // streamer, and nothing listens on the agent port, so it only spun reconnecting.)
+ streamer.start();
+
+ // The Windows drives in macOS (~/Windows/C, ~/Windows/D ...), like WSL's /mnt/c. A random
+ // token, made once per PC, is the only way in; off when runtime\config\share-off exists.
+ const std::string share_token_file = wsm_root + "\\runtime\\config\\share-token";
+ std::string share_token;
+ {
+ std::ifstream in(share_token_file);
+ std::getline(in, share_token);
+ bool good = share_token.size() == 32;
+ for (char c : share_token) good = good && std::isxdigit(static_cast<unsigned char>(c));
+ if (!good) {
+ std::random_device rd;
+ static const char* hex = "0123456789abcdef";
+ share_token.clear();
+ for (int i = 0; i < 32; ++i) share_token.push_back(hex[rd() % 16]);
+ std::filesystem::create_directories(wsm_root + "\\runtime\\config");
+ std::ofstream(share_token_file, std::ios::trunc) << share_token << "\n";
+ }
+ }
+ wsm::runtime::WebDavServer share(17422, share_token);
+ const std::string share_off_file = wsm_root + "\\runtime\\config\\share-off";
+ {
+ std::string serr;
+ bool on = !std::filesystem::exists(share_off_file);
+ share.set_enabled(on);
+ if (share.start(serr)) streamer.set_share(share.guest_url(), on);
+ else std::fprintf(stderr, "[wsmd] Windows drives not shared: %s\n", serr.c_str());
+ }
+
+ // Explorer: double-clicking a .dmg/.pkg/.app installs it through wsmlaunch (no console);
+ // WSM starts with Windows so the runtime is warm when an app is opened.
+ {
+ wchar_t me[MAX_PATH]{};
+ GetModuleFileNameW(nullptr, me, MAX_PATH);
+ std::string bin = std::filesystem::path(me).parent_path().string();
+ std::string launcher = bin + "\\wsmlaunch.exe";
+ std::string assoc_err;
+ wsm::runtime::register_windows_shell_associations(launcher, assoc_err);
+ HKEY run{};
+ if (RegCreateKeyExA(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, nullptr, 0,
+ KEY_SET_VALUE, nullptr, &run, nullptr) == ERROR_SUCCESS) {
+ std::string v = "\"" + launcher + "\" --background";
+ RegSetValueExA(run, "WSM", 0, REG_SZ, reinterpret_cast<const BYTE*>(v.c_str()), static_cast<DWORD>(v.size() + 1));
+ RegCloseKey(run);
+ }
+ }
+
+ // Keeps the runtime warm, like a phone keeps apps in memory: boot it in the background once
+ // (so the first app opens in seconds, not minutes), and pause it (vCPUs stopped, no CPU use)
+ // after a few minutes with no app window open. Opening an app resumes it instantly.
+ std::thread([&] {
+ Sleep(3000);
+ std::string e;
+ // Only a runtime that finished setup; a half-set-up one belongs to setup.
+ if (runtime.status().state != wsm::runtime::RtState::NotInstalled &&
+ std::filesystem::exists(wsm_root + "\\runtime\\config\\runtime-ready.json"))
+ runtime.ensure_running(e);
+ int64_t idle_since = 0;
+ bool reached = false;
+ for (;;) {
+ Sleep(5000);
+ auto st = runtime.status().state;
+ reached |= streamer.watching();
+ {
+ // A runtime trying the virtio disk profile: keep it once macOS is up on it, or put
+ // SATA back if it isn't up after 12 minutes (a hard disk boot can take 5).
+ static int64_t trial_since = 0;
+ int64_t tnow = static_cast<int64_t>(GetTickCount64());
+ if (st == wsm::runtime::RtState::Running && runtime.profile_state() == "2-trial") {
+ if (trial_since == 0) trial_since = tnow;
+ if (streamer.watching()) { runtime.confirm_disk_profile(true); trial_since = 0; }
+ else if (tnow - trial_since > 12 * 60 * 1000) { runtime.confirm_disk_profile(false); trial_since = 0; }
+ } else {
+ trial_since = 0;
+ }
+ }
+ int64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
+ // Idle = no app window, no install or setup, nothing sent to the runtime for a while
+ // (a launch or install step in flight counts as activity). A file switches it off.
+ bool idle = st == wsm::runtime::RtState::Running && reached && streamer.window_count() == 0 &&
+ !installer.busy() && now - streamer.last_activity_ms() > 3 * 60 * 1000 &&
+ !std::filesystem::exists(wsm_root + "\\runtime\\config\\no-autopause") &&
+ ![&] { std::lock_guard<std::mutex> l(provision.mutex); return provision.running; }();
+ if (!idle) { idle_since = 0; continue; }
+ if (idle_since == 0) idle_since = now;
+ if (now - idle_since > 3 * 60 * 1000) {
+ idle_since = 0;
+ const std::string pending = wsm_root + "\\runtime\\config\\compact-pending";
+ static int compact_tries = 0;
+ if (std::filesystem::exists(pending) && ++compact_tries > 3) {
+ std::error_code rec; // didn't work 3 times: stop trying, keep the runtime as is
+ std::filesystem::remove(pending, rec);
+ }
+ if (std::filesystem::exists(pending)) {
+ // Once (after setup, or when asked): give the disk's free space back. Zero the
+ // free space only when QEMU stores zero writes as nothing (else the image would
+ // grow to its full size), then shut down, rewrite the image, start again.
+ std::string qb;
+ bool zeroes = runtime.qmp("{\"execute\":\"query-block\"}", qb, 5000) &&
+ (qb.find("\"detect_zeroes\": \"on\"") != std::string::npos ||
+ qb.find("\"detect_zeroes\":\"on\"") != std::string::npos);
+ if (zeroes && streamer.copy_to_guest(wsm_root + "\\src\\wsm-guest\\agent\\wsm-shrink.sh",
+ "Library/Caches/WSM/wsm-shrink.sh"))
+ streamer.guest_exec("zsh ~/Library/Caches/WSM/wsm-shrink.sh", nullptr, 40 * 60 * 1000);
+ if (streamer.window_count() == 0 && !installer.busy()) {
+ if (streamer.watching()) streamer.quick("sudo shutdown -h now", nullptr, 5000);
+ runtime.shutdown(e);
+ uint64_t b0 = 0, b1 = 0;
+ if (zeroes && runtime.compact(e, &b0, &b1)) {
+ std::error_code rec;
+ std::filesystem::remove(pending, rec);
+ std::ofstream(wsm_root + "\\runtime\\config\\compact-last")
+ << (b0 >> 20) << " MB -> " << (b1 >> 20) << " MB\n";
+ }
+ runtime.ensure_running(e); // also applies WSM's QEMU options first
+ }
+ continue;
+ }
+ runtime.pause(e);
+ }
+ }
+ }).detach();
+
+ // Apps that appear in macOS without WSM installing them (App Store downloads, an installer
+ // run inside macOS) join the library, Start menu and Desktop by themselves. Apps the user
+ // took off the library (hidden-apps.txt) stay off.
+ std::thread([&] {
+ const std::string hidden_file = wsm_root + "\\runtime\\config\\hidden-apps.txt";
+ for (;;) {
+ Sleep(20000);
+ if (!streamer.watching() || installer.busy() ||
+ !std::filesystem::exists(wsm_root + "\\runtime\\config\\runtime-ready.json"))
+ continue;
+ std::string out;
+ if (streamer.quick("for a in /Applications/*.app /Applications/*/*.app; do [ -L \"$a\" ] && continue; "
+ "i=$(defaults read \"$a/Contents/Info\" CFBundleIdentifier 2>/dev/null) && echo \"APP|$i|$a\"; "
+ "done 2>/dev/null; true", &out, 30000) != 0)
+ continue;
+ std::set<std::string> hidden;
+ {
+ std::ifstream in(hidden_file);
+ for (std::string l; std::getline(in, l);) if (!l.empty()) hidden.insert(l);
+ }
+ {
+ // Hidden entries of apps no longer in macOS (removal finished) are dropped, so a
+ // later App Store download of the same app shows up again. Apple's stay hidden.
+ std::set<std::string> present, keep;
+ std::istringstream ls(out);
+ for (std::string l; std::getline(ls, l);) {
+ size_t bar = l.rfind("APP|", 0) == 0 ? l.find('|', 4) : std::string::npos;
+ if (bar != std::string::npos) present.insert(l.substr(4, bar - 4));
+ }
+ for (auto& h : hidden) if (h.rfind("com.apple.", 0) == 0 || present.count(h)) keep.insert(h);
+ if (keep.size() != hidden.size()) {
+ std::ofstream o(hidden_file, std::ios::trunc);
+ for (auto& h : keep) o << h << "\n";
+ hidden.swap(keep);
+ }
+ }
+ std::istringstream lines(out);
+ for (std::string l; std::getline(lines, l);) {
+ if (!l.empty() && l.back() == '\r') l.pop_back();
+ if (l.rfind("APP|", 0) != 0) continue;
+ size_t bar = l.find('|', 4);
+ if (bar == std::string::npos) continue;
+ std::string id = l.substr(4, bar - 4), path = l.substr(bar + 1);
+ if (id.empty() || hidden.count(id)) continue;
+ wsm::runtime::AppBundleInfo known;
+ bool have;
+ { std::lock_guard<std::mutex> lk(apps_mu); have = apps.find(id, known); }
+ if (have) continue;
+ if (installer.start_builtin(path, false)) break; // one at a time; the rest next round
+ }
+ }
+ }).detach();
+
+ // Keep the macOS runtime invisible: hide any window QEMU or the GPU library opens.
+ // The moment a runtime window is created or shown (an event hook), so macOS's screen never
+ // flashes up while it boots; the poll stays as a safety net.
+ std::thread([] {
+ auto proc = [](HWINEVENTHOOK, DWORD, HWND h, LONG obj, LONG, DWORD, DWORD) {
+ if (obj != OBJID_WINDOW || !h || GetAncestor(h, GA_ROOT) != h) return;
+ DWORD pid = 0;
+ GetWindowThreadProcessId(h, &pid);
+ HANDLE ph = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
+ if (!ph) return;
+ wchar_t img[MAX_PATH] = {};
+ DWORD n = MAX_PATH;
+ bool qemu = QueryFullProcessImageNameW(ph, 0, img, &n) && n > 22 &&
+ _wcsicmp(img + n - 22, L"qemu-system-x86_64.exe") == 0;
+ CloseHandle(ph);
+ if (qemu) hide_runtime_windows_once();
+ };
+ SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_SHOW, nullptr, proc, 0, 0,
+ WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
+ MSG m;
+ while (GetMessageW(&m, nullptr, 0, 0) > 0) DispatchMessageW(&m);
+ }).detach();
+ std::thread([] { for (;;) { hide_runtime_windows_once(); Sleep(400); } }).detach();
+
+ // Windows shutting down or restarting: shut macOS down properly first. Killing it mid-flight
+ // marks its disk dirty, and the next start then spends many minutes checking the disk.
+ std::thread([&] {
+ static WindowStreamerHook hook{&streamer, &runtime};
+ g_end_hook = &hook;
+ WNDCLASSEXW wc{};
+ wc.cbSize = sizeof(wc);
+ wc.lpfnWndProc = end_session_proc;
+ wc.hInstance = GetModuleHandleW(nullptr);
+ wc.lpszClassName = L"WsmSessionWatcher";
+ RegisterClassExW(&wc);
+ // A hidden top-level window: only those receive WM_QUERYENDSESSION.
+ HWND h = CreateWindowExW(WS_EX_TOOLWINDOW, wc.lpszClassName, L"WSM", WS_POPUP, 0, 0, 0, 0,
+ nullptr, nullptr, wc.hInstance, nullptr);
+ (void)h;
+ SetProcessShutdownParameters(0x3FF, 0); // be asked early, while the network is still up
+ MSG m;
+ while (GetMessageW(&m, nullptr, 0, 0) > 0) { TranslateMessage(&m); DispatchMessageW(&m); }
+ }).detach();
+
+ if (audio.initialize(48000, 2)) {
+ std::cout << "[wsmd] WASAPI audio bridge ready on " << audio.device_name() << "\n";
+ }
+
+ {
+ std::string sf_err;
+ shared_folders.add_mapping({"default", wsm::core::resolve_wsm_root() + "\\runtime\\shared", "/Volumes/WSM-Shared", false}, sf_err);
+ }
+
+ SOCKET listen_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (listen_sock == INVALID_SOCKET) {
+ std::cerr << "[wsmd] Failed to create listen socket\n";
+ return 1;
+ }
+
+ // Prevent child processes (QEMU, reims-ctl, 7z) from inheriting the HTTP listen socket!
+ SetHandleInformation(reinterpret_cast<HANDLE>(listen_sock), HANDLE_FLAG_INHERIT, 0);
+ int excl = 1;
+ setsockopt(listen_sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast<const char*>(&excl), sizeof(excl));
+
+ sockaddr_in addr{};
+ addr.sin_family = AF_INET;
+ addr.sin_port = htons(17421);
+ inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
+
+ if (bind(listen_sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0 ||
+ listen(listen_sock, 16) != 0) {
+ std::cerr << "[wsmd] Failed to bind 127.0.0.1:17421\n";
+ closesocket(listen_sock);
+ return 1;
+ }
+
+ std::cout << "[wsmd] WSM Runtime Daemon listening on http://127.0.0.1:17421\n";
+
+ std::mutex api_mutex;
+ while (g_running.load()) {
+ fd_set fds;
+ FD_ZERO(&fds);
+ FD_SET(listen_sock, &fds);
+ timeval tv{0, 250000};
+ if (select(0, &fds, nullptr, nullptr, &tv) <= 0) continue;
+
+ SOCKET client = accept(listen_sock, nullptr, nullptr);
+ if (client == INVALID_SOCKET) continue;
+
+ std::string req = read_full_http_request(client);
+ if (req.empty()) {
+ closesocket(client);
+ continue;
+ }
+ std::istringstream iss(req);
+ std::string method, path, query;
+ iss >> method >> path;
+ std::unique_lock<std::mutex> apps_lock(apps_mu);
+ if (auto q = path.find('?'); q != std::string::npos) { query = path.substr(q + 1); path = path.substr(0, q); }
+
+ std::string resp;
+ std::lock_guard<std::mutex> lock(api_mutex);
+
+ if (method == "OPTIONS") {
+ resp = http_response(204, "No Content", "");
+ } else if (method == "GET" && (path == "/" || path == "/index.html")) {
+ std::string html = read_file_text(ui_dir + "\\index.html");
+ resp = html.empty() ? http_response(404, "Not Found", "UI not found", "text/plain")
+ : http_response(200, "OK", html, "text/html; charset=utf-8");
+ } else if (method == "GET" && (path == "/setup" || path == "/setup.html")) {
+ std::string html = read_file_text(ui_dir + "\\setup.html");
+ resp = html.empty() ? http_response(404, "Not Found", "Setup not found", "text/plain")
+ : http_response(200, "OK", html, "text/html; charset=utf-8");
+ } else if (method == "GET" && path == "/api/setup/plan") {
+ auto p = provisioner.plan();
+ std::ostringstream o;
+ o << "{\"reuse_installer\":" << (p.reuse_installer ? "true" : "false")
+ << ",\"macos_name\":\"" << json_escape_str(p.macos_name) << "\""
+ << ",\"download_bytes\":" << p.download_bytes
+ << ",\"disk_needed_bytes\":" << p.disk_needed_bytes
+ << ",\"free_bytes\":" << p.free_bytes
+ << ",\"drive\":\"" << json_escape_str(p.drive) << "\""
+ << ",\"minutes\":" << p.minutes << "}";
+ resp = http_response(200, "OK", o.str());
+ } else if (method == "GET" && path == "/api/setup/progress") {
+ resp = http_response(200, "OK", provisioner.to_json());
+ } else if (method == "POST" && path == "/api/setup/begin") {
+ std::string body = extract_http_body(req);
+ bool accepted = body.find("\"license_accepted\":true") != std::string::npos;
+ std::string err;
+ if (provisioner.begin(accepted, err)) resp = http_response(200, "OK", "{\"ok\":true}");
+ else resp = http_response(400, "Bad Request", "{\"ok\":false,\"error\":\"" + json_escape_str(err) + "\"}");
+ } else if (method == "POST" && path == "/api/setup/repair") {
+ // Re-runs macOS's first-boot setup for WSM (account, key, auto-login, sudo) on an
+ // installed runtime. Body: "<vm> <ssh port>" (default "wsm-default 2222"); another
+ // VM is for testing the step on a copy. Progress: GET /api/setup/progress.
+ std::string body = extract_http_body(req), vm_name = "wsm-default";
+ int port = 2222;
+ {
+ std::istringstream in(body);
+ std::string v; int p = 0;
+ if (in >> v) vm_name = v;
+ if (in >> p && p > 0 && p < 65536) port = p;
+ }
+ bool safe = !vm_name.empty() && vm_name.size() < 40;
+ for (char c : vm_name) if (!(std::isalnum(static_cast<unsigned char>(c)) || c == '-' || c == '_')) safe = false;
+ std::string err = safe ? "" : "Bad runtime name.";
+ if (safe && provisioner.repair_first_boot(vm_name, port, err)) resp = http_response(200, "OK", "{\"ok\":true}");
+ else resp = http_response(400, "Bad Request", "{\"ok\":false,\"error\":\"" + json_escape_str(err) + "\"}");
+ } else if (method == "GET" && path.rfind("/ui/", 0) == 0 &&
+ path.find("..") == std::string::npos && path.find('\\') == std::string::npos &&
+ std::filesystem::is_regular_file(ui_dir + "\\" + path.substr(4))) {
+ // Any file of the UI folder (styles, scripts, images), typed by extension.
+ std::string name = path.substr(4);
+ std::ifstream f(ui_dir + "\\" + name, std::ios::binary);
+ std::string data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ auto ext = std::filesystem::path(name).extension().string();
+ const char* ct = ext == ".css" ? "text/css; charset=utf-8"
+ : ext == ".js" ? "application/javascript; charset=utf-8"
+ : ext == ".png" ? "image/png"
+ : ext == ".svg" ? "image/svg+xml"
+ : ext == ".webp" ? "image/webp" : "application/octet-stream";
+ resp = http_response(200, "OK", data, ct);
+ } else if (method == "GET" && path == "/ui/setup.js") {
+ resp = http_response(200, "OK", read_file_text(ui_dir + "\\setup.js"), "application/javascript; charset=utf-8");
+ } else if (method == "GET" && path == "/api/apps/icon") {
+ std::string id = query.rfind("id=", 0) == 0 ? url_decode(query.substr(3)) : "";
+ wsm::runtime::AppBundleInfo info;
+ std::string png;
+ if (!id.empty() && apps.find(id, info)) png = icon_png_cached(wsm_root, info);
+ resp = png.empty() ? http_response(404, "Not Found", "", "text/plain")
+ : http_response(200, "OK", png, "image/png");
+ } else if (method == "POST" && path == "/api/diagnostics/export") {
+ std::string out;
+ bool ok = export_diagnostics(wsm_root, out);
+ resp = http_response(200, "OK", std::string("{\"ok\":") + (ok ? "true" : "false") +
+ ",\"path\":\"" + json_escape_str(out) + "\"}");
+ } else if (method == "GET" && path == "/ui/styles.css") {
+ resp = http_response(200, "OK", read_file_text(ui_dir + "\\styles.css"), "text/css; charset=utf-8");
+ } else if (method == "GET" && path == "/ui/app.js") {
+ resp = http_response(200, "OK", read_file_text(ui_dir + "\\app.js"), "application/javascript; charset=utf-8");
+ } else if (method == "GET" && path == "/api/health") {
+ resp = http_response(200, "OK", "{\"status\":\"ok\",\"version\":\"0.1.0\",\"service\":\"wsmd\"}");
+ } else if (method == "GET" && path == "/api/share") {
+ resp = http_response(200, "OK", std::string("{\"enabled\":") + (share.enabled() ? "true" : "false") +
+ ",\"mac_path\":\"~/Windows\"}");
+ } else if (method == "POST" && path == "/api/share") {
+ // Body "on" / "off": the Windows drives in Mac apps.
+ bool on = extract_http_body(req).find("on") != std::string::npos;
+ std::error_code rec;
+ if (on) std::filesystem::remove(share_off_file, rec);
+ else std::ofstream(share_off_file) << "off\n";
+ share.set_enabled(on);
+ streamer.set_share(share.guest_url(), on);
+ resp = http_response(200, "OK", std::string("{\"ok\":true,\"enabled\":") + (on ? "true" : "false") + "}");
+ } else if (method == "GET" && path == "/api/system/storage") {
+ // Follow links: the runtime's disk may live on another drive than WSM itself.
+ std::string where = wsm_root;
+ HANDLE fh = CreateFileA((wsm_root + "\\runtime\\reims-ctl\\vms\\wsm-default\\disk.qcow2").c_str(), 0,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr);
+ if (fh != INVALID_HANDLE_VALUE) {
+ char fin[MAX_PATH * 2] = {};
+ DWORD fl = GetFinalPathNameByHandleA(fh, fin, sizeof(fin), FILE_NAME_NORMALIZED);
+ if (fl > 6 && fl < sizeof(fin)) where = std::string(fin).substr(std::string(fin).rfind("\\?\\", 0) == 0 ? 4 : 0);
+ CloseHandle(fh);
+ }
+ auto st = probe_storage(where);
+ bool slow = st.spinning; // a USB SSD is fine; a spinning disk is what hurts
+ resp = http_response(200, "OK", "{\"drive\":\"" + json_escape_str(where.substr(0, 2)) + "\",\"bus\":\"" + st.bus +
+ "\",\"spinning\":" + (st.spinning ? "true" : "false") + ",\"slow\":" + (slow ? "true" : "false") + "}");
+ } else if (method == "GET" && path == "/api/system") {
+ auto rep = wsm::core::probe_host_system(wsm_root);
+ resp = http_response(200, "OK", wsm::core::host_report_to_json(rep));
+ } else if (method == "GET" && path == "/api/vm/status") {
+ auto st = vm.status(guest_bridge.is_connected());
+ auto rt = runtime.status();
+ std::ostringstream body;
+ // Runtime state comes from the single runtime owner (reims-ctl); "ready" additionally
+ // requires the in-guest helper to be connected.
+ std::string state = wsm::runtime::rt_state_name(rt.state);
+ if (rt.state == wsm::runtime::RtState::Running && !streamer.watching()) state = "waiting_for_guest";
+ body << "{\"state\":\"" << state << "\",\"working_set_mb\":" << rt.working_set_mb
+ << ",\"legacy_state\":\"" << vm_state_to_string(st.state)
+ << "\",\"pid\":" << st.pid
+ << ",\"exit_code\":" << st.last_exit_code
+ << ",\"uptime_ms\":" << st.uptime_ms
+ << ",\"qmp_reachable\":" << (st.qmp_reachable ? "true" : "false")
+ << ",\"guest_connected\":" << (streamer.watching() ? "true" : "false")
+ << ",\"open_windows\":" << streamer.window_count()
+ << ",\"last_error\":\"" << json_escape_str(st.last_error) << "\""
+ << ",\"qemu_log_tail\":\"" << json_escape_str(vm.read_qemu_log_tail(25)) << "\""
+ << ",\"vcpus\":" << runtime_size().first
+ << ",\"ram_mb\":" << runtime_size().second
+ << ",\"headless\":" << (vm_cfg.headless ? "true" : "false")
+ << ",\"reims_vgpu\":" << (vm_cfg.enable_reims_vgpu ? "true" : "false")
+ << ",\"compositor_gpu\":\"" << json_escape_str(compositor.gpu_adapter_name())
+ << "\",\"audio_device\":\"" << json_escape_str(audio.device_name())
+ << "\"}";
+ resp = http_response(200, "OK", body.str());
+ } else if (method == "GET" && path == "/api/vm/log") {
+ resp = http_response(200, "OK", "{\"log\":\"" + json_escape_str(vm.read_qemu_log_tail(100)) + "\"}");
+ } else if (method == "POST" && path == "/api/vm/start") {
+ std::string start_err;
+ uint64_t ms = 0;
+ if (runtime.ensure_running(start_err, &ms)) {
+ resp = http_response(200, "OK", "{\"ok\":true,\"state\":\"" + std::string(wsm::runtime::rt_state_name(runtime.status().state)) + "\",\"ms\":" + std::to_string(ms) + "}");
+ } else {
+ resp = http_response(500, "Internal Server Error",
+ "{\"ok\":false,\"error\":\"" + json_escape_str(start_err) + "\"}");
+ }
+ } else if (method == "POST" && path == "/api/vm/sleep") {
+ // Pause: no CPU use, apps open again in seconds.
+ std::string e; bool ok = runtime.pause(e);
+ resp = http_response(200, "OK", std::string("{\"ok\":") + (ok ? "true" : "false") + "}");
+ } else if (method == "POST" && path == "/api/vm/stop") {
+ // A real OS shutdown first: macOS's normal "quit apps" shutdown waits forever on an
+ // unsaved-document dialog nobody can see, and then the runtime gets powered off.
+ if (streamer.watching()) streamer.quick("sudo shutdown -h now", nullptr, 5000);
+ std::string e; runtime.shutdown(e);
+ resp = http_response(200, "OK", "{\"ok\":true,\"state\":\"stopped\"}");
+ } else if (method == "POST" && path == "/api/vm/compact") {
+ // Settings > Free up space: done the next time no Mac app is open for a few minutes.
+ std::ofstream(wsm_root + "\\runtime\\config\\compact-pending") << "asked\n";
+ resp = http_response(200, "OK", "{\"ok\":true,\"scheduled\":true}");
+ } else if (method == "GET" && path == "/api/vm/cmdline") {
+ std::string cmd = vm.build_qemu_command(vm_cfg);
+ std::string escaped;
+ for (char c : cmd) {
+ if (c == '\\') escaped += "\\\\";
+ else if (c == '"') escaped += "\\\"";
+ else escaped.push_back(c);
+ }
+ resp = http_response(200, "OK", "{\"cmdline\":\"" + escaped + "\"}");
+ } else if (method == "POST" && path == "/api/compositor/test-window") {
+ wsm::proto::WindowDescriptor desc{};
+ desc.window_id = 9001;
+ desc.pid = GetCurrentProcessId();
+ desc.bounds = {160, 140, 560, 340};
+ desc.visible = 1;
+ compositor.create_or_update_window(desc, "WSM Hardware Surface (RTX 3060 Ti)");
+ Sleep(120);
+ std::vector<uint8_t> px(560u * 340u * 4u, 255);
+ for (uint32_t y = 0; y < 340; ++y) {
+ for (uint32_t x = 0; x < 560; ++x) {
+ size_t i = (y * 560u + x) * 4u;
+ px[i + 0] = static_cast<uint8_t>(40 + (x * 160) / 560);
+ px[i + 1] = static_cast<uint8_t>(32 + (y * 140) / 340);
+ px[i + 2] = 28;
+ px[i + 3] = 255;
+ }
+ }
+ bool ok = compositor.present_bgra_frame(9001, 560, 340, 560 * 4, px.data());
+ resp = http_response(200, "OK", std::string("{\"ok\":") + (ok ? "true" : "false") + "}");
+ } else if (method == "POST" && path == "/api/compositor/close-test") {
+ compositor.destroy_window(9001);
+ resp = http_response(200, "OK", "{\"ok\":true}");
+ } else if (method == "GET" && path == "/api/provision/status") {
+ resp = http_response(200, "OK", provision.to_json());
+ } else if (method == "POST" && path == "/api/provision/start") {
+ // Retired: it made a runtime without WSM's setup (no account, no auto-login, no SSH).
+ // Setup is POST /api/setup/begin (the wizard), repairs POST /api/setup/repair.
+ resp = http_response(410, "Gone", "{\"ok\":false,\"error\":\"Use /api/setup/begin.\"}");
+ } else if (method == "POST" && path == "/api/provision/delete") {
+ std::string cmd =
+ "powershell.exe -NoProfile -Command \""
+ "$env:XDG_DATA_HOME='" + wsm_root + "\\runtime'; $env:XDG_CACHE_HOME='" + wsm_root + "\\cache'; "
+ "Get-Process -Name qemu-system-x86_64 -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue; "
+ "Start-Sleep -Milliseconds 400; "
+ "& '" + wsm_root + "\\cache\\cargo\\bin\\reims-ctl.exe' delete wsm-default --yes 2>&1; "
+ "$vmDir='" + wsm_root + "\\runtime\\reims-ctl\\vms\\wsm-default'; "
+ "if (Test-Path $vmDir) { Remove-Item -Recurse -Force $vmDir }; "
+ "Write-Host 'Deleted wsm-default cleanly (cached installers preserved).'\"";
+ bool ok = provision.start_command(cmd, "Stopping QEMU and removing wsm-default via reims-ctl delete...");
+ resp = http_response(200, "OK", std::string("{\"ok\":") + (ok ? "true" : "false") + "}");
+ } else if (method == "GET" && path == "/api/setup/frame") {
+ wsm::core::QmpUnixClient qmp;
+ std::string ppm_path = wsm::core::resolve_wsm_root() + "\\cache\\tmp\\wsm_setup_frame.ppm";
+ std::string qerr;
+ std::vector<uint8_t> bmp;
+ if (qmp.capture_screendump_ppm(ppm_path, qerr) && wsm::core::ppm_file_to_bmp_bytes(ppm_path, bmp)) {
+ std::string body(reinterpret_cast<const char*>(bmp.data()), bmp.size());
+ resp = http_response(200, "OK", body, "image/bmp");
+ } else {
+ resp = http_response(503, "Service Unavailable", "{\"error\":\"" + json_escape_str(qerr) + "\"}");
+ }
+ } else if (method == "POST" && path == "/api/setup/click") {
+ std::string body = extract_http_body(req);
+ int x = 0, y = 0;
+ auto comma = body.find(',');
+ if (comma != std::string::npos) {
+ x = std::atoi(body.substr(0, comma).c_str());
+ y = std::atoi(body.substr(comma + 1).c_str());
+ }
+ wsm::core::QmpUnixClient qmp;
+ bool ok = qmp.send_mouse_click(x, y, "left");
+ resp = http_response(200, "OK", std::string("{\"ok\":") + (ok ? "true" : "false") + "}");
+ } else if (method == "POST" && path == "/api/setup/key") {
+ std::string qcode = extract_http_body(req);
+ wsm::core::QmpUnixClient qmp;
+ bool ok = !qcode.empty() && qmp.send_key_qcode(qcode);
+ resp = http_response(200, "OK", std::string("{\"ok\":") + (ok ? "true" : "false") + "}");
+ } else if (method == "GET" && path == "/api/setup/telemetry") {
+ uint64_t disk_bytes = 0;
+ std::error_code ec;
+ auto disk_p = std::filesystem::path(wsm::core::resolve_wsm_root() + "\\runtime\\reims-ctl\\vms\\wsm-default\\disk.qcow2");
+ if (std::filesystem::exists(disk_p, ec)) disk_bytes = std::filesystem::file_size(disk_p, ec);
+ bool has_template = std::filesystem::exists(wsm::core::resolve_wsm_root() + "\\runtime\\templates\\macos-base.qcow2", ec);
+ MEMORYSTATUSEX ms{}; ms.dwLength = sizeof(ms); GlobalMemoryStatusEx(&ms);
+ std::ostringstream oss;
+ oss << "{\"disk_mb\":" << (disk_bytes / (1024ULL * 1024ULL))
+ << ",\"host_free_ram_mb\":" << (ms.ullAvailPhys / (1024ULL * 1024ULL))
+ << ",\"has_template\":" << (has_template ? "true" : "false") << "}";
+ resp = http_response(200, "OK", oss.str());
+ } else if (method == "POST" && path == "/api/template/save") {
+ std::filesystem::create_directories(wsm::core::resolve_wsm_root() + "\\runtime\\templates");
+ std::string cmd = "powershell.exe -NoProfile -Command \"Copy-Item '" + wsm::core::resolve_wsm_root() + "\\runtime\\reims-ctl\\vms\\wsm-default\\disk.qcow2' '" + wsm::core::resolve_wsm_root() + "\\runtime\\templates\\macos-base.qcow2' -Force; Copy-Item '" + wsm::core::resolve_wsm_root() + "\\runtime\\reims-ctl\\vms\\wsm-default\\OVMF_VARS.fd' '" + wsm::core::resolve_wsm_root() + "\\runtime\\templates\\OVMF_VARS.fd' -Force; Write-Host 'Reusable runtime template saved to " + wsm::core::resolve_wsm_root() + "\\runtime\\templates'\"";
+ bool ok = provision.start_command(cmd, "Saving reusable macOS runtime template to " + wsm::core::resolve_wsm_root() + "\\runtime\\templates...");
+ resp = http_response(200, "OK", std::string("{\"ok\":") + (ok ? "true" : "false") + "}");
+ } else if (method == "POST" && path == "/api/provision/stop") {
+ provision.cancel();
+ resp = http_response(200, "OK", "{\"ok\":true}");
+ } else if (method == "POST" && path == "/api/provision/deploy-agent") {
+ std::string user = extract_http_body(req);
+ if (user.empty()) user = "user";
+ std::string cmd = "powershell.exe -NoProfile -ExecutionPolicy Bypass -File \"" + wsm::core::resolve_wsm_root() + "\\scripts\\provision-guest.ps1\" -DeployAgent -GuestUser \"" + user + "\"";
+ bool ok = provision.start_command(cmd, "Deploying WSM Guest Agent over SSH...");
+ resp = http_response(200, "OK", std::string("{\"ok\":") + (ok ? "true" : "false") + "}");
+ } else if (method == "POST" && path == "/api/fs/open") {
+ // Ensure W:\ drive is mapped to F:\WSM\fs and open in Windows Explorer
+ if (!std::filesystem::exists("W:\\")) {
+ std::system(("subst W: " + wsm::core::resolve_wsm_root() + "\\fs >nul 2>&1").c_str());
+ }
+ std::string target_s = std::filesystem::exists("W:\\") ? std::string("W:\\") : wsm::core::resolve_wsm_root() + "\\fs";
+ const char* target = target_s.c_str();
+ ShellExecuteA(nullptr, "open", "explorer.exe", target, nullptr, SW_SHOWNORMAL);
+ resp = http_response(200, "OK", std::string("{\"ok\":true,\"path\":\"") + json_escape_str(target) + "\"}");
+ } else if (method == "POST" && path == "/api/dialog/pick-app") {
+ std::string picked = pick_macos_file_dialog();
+ if (picked.empty()) {
+ resp = http_response(200, "OK", "{\"ok\":false,\"cancelled\":true}");
+ } else {
+ resp = http_response(200, "OK", "{\"ok\":true,\"path\":\"" + json_escape_str(picked) + "\"}");
+ }
+ } else if (method == "GET" && path == "/api/apps") {
+ resp = http_response(200, "OK", apps.to_json());
+ } else if (method == "POST" && path == "/api/apps/import") {
+ std::string app_path = extract_http_body(req);
+ wsm::runtime::AppBundleInfo info;
+ std::string imp_err;
+ if (apps.register_app(app_path, info, imp_err)) {
+ std::string ico_out = wsm::core::resolve_wsm_root() + "\\runtime\\apps\\icons\\" + info.id + ".ico";
+ if (!info.icon_path.empty()) wsm::runtime::convert_icns_to_ico(info.icon_path, ico_out);
+ std::string lnk;
+ wsm::runtime::create_app_start_menu_shortcut(info.name, info.id, ico_out, lnk);
+ resp = http_response(200, "OK", "{\"ok\":true,\"id\":\"" + json_escape_str(info.id) + "\",\"name\":\"" + json_escape_str(info.name) + "\"}");
+ } else {
+ resp = http_response(400, "Bad Request", "{\"ok\":false,\"error\":\"" + json_escape_str(imp_err) + "\"}");
+ }
+ } else if (method == "POST" && path == "/api/apps/launch") {
+ std::string app_id = extract_http_body(req);
+ wsm::runtime::AppBundleInfo info;
+ if (!apps.find(app_id, info)) {
+ resp = http_response(404, "Not Found", "{\"ok\":false,\"error\":\"App not found\"}");
+ } else {
+ std::string start_err;
+ // Opens the app inside the runtime; its windows then appear on the Windows desktop.
+ // A paused runtime resumes instantly; a cold one boots, and the open is retried
+ // in the background so this request returns at once.
+ auto t0 = GetTickCount64();
+ const bool was_running = runtime.status().state == wsm::runtime::RtState::Running;
+ runtime.ensure_running(start_err);
+ // Reconnect the window watcher only after a resume/boot. Doing it on every launch
+ // dropped and re-created every open window (flicker) and slowed the launch.
+ if (!was_running || !streamer.watching()) streamer.kick();
+ std::string launch_err;
+ bool sent = streamer.launch_app(info.id, launch_err);
+ if (!sent) {
+ std::string id = info.id;
+ std::thread([&streamer, id] {
+ std::string e;
+ for (int i = 0; i < 60 && !streamer.launch_app(id, e); ++i) Sleep(3000);
+ }).detach();
+ }
+ resp = http_response(200, "OK",
+ std::string("{\"ok\":true,\"dispatched\":") + (sent ? "true" : "false") +
+ ",\"ms\":" + std::to_string(GetTickCount64() - t0) +
+ ",\"runtime_state\":\"" + std::string(wsm::runtime::rt_state_name(runtime.status().state)) + "\"}");
+ }
+ } else if (method == "POST" && path == "/api/apps/remove") {
+ std::string app_id = extract_http_body(req);
+ wsm::runtime::AppBundleInfo gone;
+ if (apps.find(app_id, gone)) {
+ wsm::runtime::remove_app_shortcuts(gone.name);
+ // Remove the app from the runtime too (only bundles WSM installed in /Applications).
+ // Apps that ship with macOS (Safari, …) are only taken off the library.
+ if (gone.id.rfind("com.apple.", 0) != 0 &&
+ gone.bundle_path.rfind("/Applications/", 0) == 0 && gone.bundle_path.find("..") == std::string::npos &&
+ gone.bundle_path.size() > 18 && gone.bundle_path.find('\'') == std::string::npos) {
+ std::string b = gone.bundle_path;
+ std::thread([&streamer, b] {
+ streamer.quick("pkill -f '" + b + "/Contents/MacOS/'; sudo rm -rf '" + b + "'", nullptr, 60000);
+ }).detach();
+ }
+ std::error_code rec;
+ std::filesystem::remove(wsm_root + "\\runtime\\apps\\icons\\" + gone.id + ".ico", rec);
+ std::filesystem::remove(wsm_root + "\\runtime\\apps\\icons\\" + gone.id + ".png", rec);
+ }
+ bool removed = apps.remove_app(app_id);
+ // Taken off on purpose: the app sync mustn't bring it back (Apple's apps stay in macOS;
+ // others until their removal there has finished).
+ if (removed) std::ofstream(wsm_root + "\\runtime\\config\\hidden-apps.txt", std::ios::app) << app_id << "\n";
+ resp = http_response(200, "OK", std::string("{\"ok\":") + (removed ? "true" : "false") + "}");
+ } else if (method == "POST" && path == "/api/apps/install") {
+ std::string file = extract_http_body(req);
+ uint64_t job = installer.start(file, true);
+ resp = http_response(job ? 200 : 409, job ? "OK" : "Conflict",
+ job ? "{\"ok\":true,\"job\":" + std::to_string(job) + "}"
+ : std::string("{\"ok\":false,\"error\":\"Another app is being installed. Try again when it finishes.\"}"));
+ } else if (method == "POST" && path == "/api/apps/add-builtin") {
+ // Body: path of an app that ships with macOS, e.g. /Applications/Safari.app.
+ std::string app = extract_http_body(req);
+ while (!app.empty() && (app.back() == '\r' || app.back() == '\n' || app.back() == ' ')) app.pop_back();
+ uint64_t job = installer.start_builtin(app, true);
+ resp = http_response(job ? 200 : 409, job ? "OK" : "Conflict",
+ job ? "{\"ok\":true,\"job\":" + std::to_string(job) + "}"
+ : std::string("{\"ok\":false,\"error\":\"WSM is busy adding another app. Try again when it finishes.\"}"));
+ } else if (method == "GET" && path == "/api/apps/install/status") {
+ resp = http_response(200, "OK", installer.status_json());
+ } else if (method == "GET" && path == "/api/stream/status") {
+ resp = http_response(200, "OK", std::string("{\"watching\":") + (streamer.watching() ? "true" : "false") +
+ ",\"windows\":" + std::to_string(streamer.window_count()) +
+ ",\"frames\":" + std::to_string(streamer.frames_presented()) +
+ ",\"transport\":\"" + (streamer.vnc_live() ? "vnc" : "screendump") + "\"}");
+ } else if (method == "GET" && path == "/api/stream/latency") {
+ resp = http_response(200, "OK", streamer.latency_json());
+ } else if (method == "POST" && path == "/api/stream/key") {
+ // Diagnostics: body = QEMU qcode ("a", "ret"); pressed through the same path as a real key.
+ streamer.debug_key(extract_http_body(req));
+ resp = http_response(200, "OK", "{\"ok\":true}");
+ } else if (method == "GET" && path == "/api/stream/windows") {
+ resp = http_response(200, "OK", streamer.debug_json());
+ } else if (method == "POST" && path == "/api/stream/dump") {
+ // Body: runtime window id. Saves the frame last presented for it (diagnostics).
+ std::string body = extract_http_body(req);
+ std::string out = wsm_root + "\\cache\\tmp\\frame-" + std::to_string(std::strtoul(body.c_str(), nullptr, 10)) + ".bmp";
+ bool ok = streamer.debug_dump_frame(static_cast<uint32_t>(std::strtoul(body.c_str(), nullptr, 10)), out);
+ resp = http_response(ok ? 200 : 404, ok ? "OK" : "Not Found", std::string("{\"ok\":") + (ok ? "true" : "false") + "}");
+ } else if (method == "GET" && path == "/api/windows") {
+ auto wins = compositor.list_windows();
+ std::ostringstream body;
+ body << "[";
+ for (size_t i = 0; i < wins.size(); ++i) {
+ body << "{\"id\":" << wins[i].window_id
+ << ",\"pid\":" << wins[i].pid
+ << ",\"title\":\"" << wins[i].title << "\""
+ << ",\"width\":" << wins[i].width
+ << ",\"height\":" << wins[i].height
+ << ",\"frames\":" << wins[i].frames_presented << "}"
+ << (i + 1 < wins.size() ? "," : "");
+ }
+ body << "]";
+ resp = http_response(200, "OK", body.str());
+ } else {
+ resp = http_response(404, "Not Found", "{\"error\":\"not_found\"}");
+ }
+
+ send(client, resp.c_str(), static_cast<int>(resp.size()), 0);
+ closesocket(client);
+ }
+
+ closesocket(listen_sock);
+ guest_bridge.stop();
+ audio.shutdown();
+ clipboard.stop();
+ compositor.stop();
+ WSACleanup();
+ return 0;
+}
diff --git a/src/wsm-runtime/wsm.rc b/src/wsm-runtime/wsm.rc
new file mode 100644
index 0000000..4af59ce
--- /dev/null
+++ b/src/wsm-runtime/wsm.rc
@@ -0,0 +1,2 @@
+// Application icon (resource 1 is what Explorer, the taskbar and Alt+Tab show).
+1 ICON "../../assets/brand/wsm.ico"
diff --git a/src/wsm-services/CMakeLists.txt b/src/wsm-services/CMakeLists.txt
new file mode 100644
index 0000000..cb3a37e
--- /dev/null
+++ b/src/wsm-services/CMakeLists.txt
@@ -0,0 +1,13 @@
+add_library(wsm-services STATIC
+ src/services.cpp
+)
+
+target_include_directories(wsm-services PUBLIC
+ "${CMAKE_CURRENT_SOURCE_DIR}/include"
+)
+
+target_link_libraries(wsm-services PUBLIC
+ wsm-proto
+ ole32
+ user32
+)
diff --git a/src/wsm-services/include/wsm/services.hpp b/src/wsm-services/include/wsm/services.hpp
new file mode 100644
index 0000000..aec57f2
--- /dev/null
+++ b/src/wsm-services/include/wsm/services.hpp
@@ -0,0 +1,65 @@
+#pragma once
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace wsm::services {
+
+// Bidirectional Windows Clipboard Bridge
+class ClipboardBridge {
+public:
+ ClipboardBridge();
+ ~ClipboardBridge();
+
+ using TextCallback = std::function<void(const std::string& utf8_text)>;
+
+ bool start(TextCallback on_host_clipboard_change);
+ void stop();
+ bool set_host_text(const std::string& utf8_text);
+ std::string get_host_text() const;
+
+private:
+ struct Impl;
+ std::unique_ptr<Impl> impl_;
+};
+
+// Low-Latency WASAPI Audio Output Bridge (CoreAudio PCM -> Windows WASAPI)
+class WasapiAudioBridge {
+public:
+ WasapiAudioBridge();
+ ~WasapiAudioBridge();
+
+ bool initialize(uint32_t sample_rate = 48000, uint16_t channels = 2);
+ void shutdown();
+ bool write_float_pcm(const float* interleaved_samples, uint32_t frame_count);
+ std::string device_name() const;
+ bool is_initialized() const noexcept;
+
+private:
+ struct Impl;
+ std::unique_ptr<Impl> impl_;
+};
+
+// Shared Folder Security & Mapping Manager
+struct SharedFolderMapping {
+ std::string id;
+ std::string host_path;
+ std::string guest_mount; // e.g., /Volumes/WSM-Shared/<id>
+ bool read_only = false;
+};
+
+class SharedFolderManager {
+public:
+ bool add_mapping(const SharedFolderMapping& mapping, std::string& err);
+ bool remove_mapping(const std::string& id);
+ std::vector<SharedFolderMapping> list() const;
+ // Validates that a relative guest path stays strictly inside the mapped host folder
+ bool resolve_safe_host_path(const std::string& mapping_id, const std::string& rel_path, std::string& out_path) const;
+
+private:
+ std::vector<SharedFolderMapping> mappings_;
+};
+
+} // namespace wsm::services
diff --git a/src/wsm-services/src/services.cpp b/src/wsm-services/src/services.cpp
new file mode 100644
index 0000000..ec4be0a
--- /dev/null
+++ b/src/wsm-services/src/services.cpp
@@ -0,0 +1,334 @@
+#include "wsm/services.hpp"
+
+#include <windows.h>
+#include <mmdeviceapi.h>
+#include <audioclient.h>
+#include <functiondiscoverykeys_devpkey.h>
+#include <wrl/client.h>
+
+#include <atomic>
+#include <cstring>
+#include <filesystem>
+#include <mutex>
+#include <thread>
+
+#pragma comment(lib, "ole32.lib")
+#pragma comment(lib, "user32.lib")
+
+namespace wsm::services {
+
+using Microsoft::WRL::ComPtr;
+
+namespace {
+std::string wide_to_utf8(const wchar_t* s) {
+ if (!s || !*s) return {};
+ int len = WideCharToMultiByte(CP_UTF8, 0, s, -1, nullptr, 0, nullptr, nullptr);
+ if (len <= 1) return {};
+ std::string out(static_cast<size_t>(len - 1), '\0');
+ WideCharToMultiByte(CP_UTF8, 0, s, -1, out.data(), len, nullptr, nullptr);
+ return out;
+}
+
+std::wstring utf8_to_wide(const std::string& s) {
+ if (s.empty()) return {};
+ int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), static_cast<int>(s.size()), nullptr, 0);
+ if (len <= 0) return {};
+ std::wstring out(static_cast<size_t>(len), L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), static_cast<int>(s.size()), out.data(), len);
+ return out;
+}
+} // namespace
+
+// ============================================================================
+// ClipboardBridge
+// ============================================================================
+struct ClipboardBridge::Impl {
+ TextCallback on_change;
+ std::atomic<bool> running{false};
+ std::atomic<bool> suppress_next{false};
+ HWND hwnd = nullptr;
+ std::thread thread;
+
+ static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
+ auto* self = reinterpret_cast<Impl*>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
+ if (self && msg == WM_CLIPBOARDUPDATE) {
+ if (self->suppress_next.exchange(false)) return 0;
+ if (self->on_change) {
+ if (OpenClipboard(hwnd)) {
+ HANDLE hData = GetClipboardData(CF_UNICODETEXT);
+ if (hData) {
+ auto* psz = static_cast<const wchar_t*>(GlobalLock(hData));
+ if (psz) {
+ std::string text = wide_to_utf8(psz);
+ GlobalUnlock(hData);
+ CloseClipboard();
+ self->on_change(text);
+ return 0;
+ }
+ }
+ CloseClipboard();
+ }
+ }
+ return 0;
+ }
+ return DefWindowProcW(hwnd, msg, wParam, lParam);
+ }
+};
+
+ClipboardBridge::ClipboardBridge() : impl_(std::make_unique<Impl>()) {}
+ClipboardBridge::~ClipboardBridge() { stop(); }
+
+bool ClipboardBridge::start(TextCallback on_host_clipboard_change) {
+ if (impl_->running.load()) return true;
+ impl_->on_change = std::move(on_host_clipboard_change);
+ std::atomic<bool> ready{false};
+
+ impl_->thread = std::thread([this, &ready]() {
+ WNDCLASSEXW wc{};
+ wc.cbSize = sizeof(wc);
+ wc.lpfnWndProc = Impl::WndProc;
+ wc.hInstance = GetModuleHandleW(nullptr);
+ wc.lpszClassName = L"WsmClipboardMonitorClass";
+ RegisterClassExW(&wc);
+
+ impl_->hwnd = CreateWindowExW(
+ 0, L"WsmClipboardMonitorClass", L"WsmClip", 0,
+ 0, 0, 0, 0, HWND_MESSAGE, nullptr, GetModuleHandleW(nullptr), nullptr
+ );
+ SetWindowLongPtrW(impl_->hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(impl_.get()));
+ AddClipboardFormatListener(impl_->hwnd);
+ impl_->running.store(true);
+ ready.store(true);
+
+ MSG msg{};
+ while (GetMessageW(&msg, nullptr, 0, 0) > 0) {
+ TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
+ if (impl_->hwnd) {
+ RemoveClipboardFormatListener(impl_->hwnd);
+ DestroyWindow(impl_->hwnd);
+ impl_->hwnd = nullptr;
+ }
+ impl_->running.store(false);
+ });
+
+ while (!ready.load()) Sleep(1);
+ return true;
+}
+
+void ClipboardBridge::stop() {
+ if (!impl_->running.load()) return;
+ if (impl_->hwnd) PostMessageW(impl_->hwnd, WM_QUIT, 0, 0);
+ if (impl_->thread.joinable()) impl_->thread.join();
+}
+
+bool ClipboardBridge::set_host_text(const std::string& utf8_text) {
+ std::wstring w = utf8_to_wide(utf8_text);
+ if (!OpenClipboard(impl_->hwnd)) return false;
+ EmptyClipboard();
+ size_t bytes = (w.size() + 1) * sizeof(wchar_t);
+ HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, bytes);
+ if (!hMem) {
+ CloseClipboard();
+ return false;
+ }
+ void* dst = GlobalLock(hMem);
+ std::memcpy(dst, w.c_str(), bytes);
+ GlobalUnlock(hMem);
+ impl_->suppress_next.store(true);
+ SetClipboardData(CF_UNICODETEXT, hMem);
+ CloseClipboard();
+ return true;
+}
+
+std::string ClipboardBridge::get_host_text() const {
+ if (!OpenClipboard(nullptr)) return {};
+ std::string res;
+ HANDLE hData = GetClipboardData(CF_UNICODETEXT);
+ if (hData) {
+ auto* psz = static_cast<const wchar_t*>(GlobalLock(hData));
+ if (psz) {
+ res = wide_to_utf8(psz);
+ GlobalUnlock(hData);
+ }
+ }
+ CloseClipboard();
+ return res;
+}
+
+// ============================================================================
+// WasapiAudioBridge
+// ============================================================================
+struct WasapiAudioBridge::Impl {
+ bool initialized = false;
+ bool com_inited = false;
+ uint32_t sample_rate = 48000;
+ uint16_t channels = 2;
+ uint32_t buffer_frames = 0;
+ std::string device_name;
+
+ ComPtr<IMMDeviceEnumerator> enumerator;
+ ComPtr<IMMDevice> device;
+ ComPtr<IAudioClient> audio_client;
+ ComPtr<IAudioRenderClient> render_client;
+ std::mutex mutex;
+};
+
+WasapiAudioBridge::WasapiAudioBridge() : impl_(std::make_unique<Impl>()) {}
+WasapiAudioBridge::~WasapiAudioBridge() { shutdown(); }
+
+bool WasapiAudioBridge::initialize(uint32_t sample_rate, uint16_t channels) {
+ std::lock_guard<std::mutex> lock(impl_->mutex);
+ if (impl_->initialized) return true;
+
+ HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
+ if (SUCCEEDED(hr)) impl_->com_inited = true;
+
+ hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL,
+ IID_PPV_ARGS(&impl_->enumerator));
+ if (FAILED(hr)) return false;
+
+ hr = impl_->enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &impl_->device);
+ if (FAILED(hr)) return false;
+
+ ComPtr<IPropertyStore> props;
+ if (SUCCEEDED(impl_->device->OpenPropertyStore(STGM_READ, &props))) {
+ PROPVARIANT pv;
+ PropVariantInit(&pv);
+ if (SUCCEEDED(props->GetValue(PKEY_Device_FriendlyName, &pv)) && pv.vt == VT_LPWSTR) {
+ impl_->device_name = wide_to_utf8(pv.pwszVal);
+ }
+ PropVariantClear(&pv);
+ }
+
+ hr = impl_->device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,
+ reinterpret_cast<void**>(impl_->audio_client.GetAddressOf()));
+ if (FAILED(hr)) return false;
+
+ WAVEFORMATEX* mix_fmt = nullptr;
+ hr = impl_->audio_client->GetMixFormat(&mix_fmt);
+ if (FAILED(hr) || !mix_fmt) return false;
+
+ impl_->sample_rate = mix_fmt->nSamplesPerSec;
+ impl_->channels = mix_fmt->nChannels;
+ (void)sample_rate;
+ (void)channels;
+
+ // 20ms low-latency shared-mode buffer
+ REFERENCE_TIME duration = 200000;
+ hr = impl_->audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, duration, 0, mix_fmt, nullptr);
+ CoTaskMemFree(mix_fmt);
+ if (FAILED(hr)) return false;
+
+ impl_->audio_client->GetBufferSize(&impl_->buffer_frames);
+ hr = impl_->audio_client->GetService(IID_PPV_ARGS(&impl_->render_client));
+ if (FAILED(hr)) return false;
+
+ hr = impl_->audio_client->Start();
+ if (FAILED(hr)) return false;
+
+ impl_->initialized = true;
+ return true;
+}
+
+void WasapiAudioBridge::shutdown() {
+ std::lock_guard<std::mutex> lock(impl_->mutex);
+ if (impl_->audio_client) impl_->audio_client->Stop();
+ impl_->render_client.Reset();
+ impl_->audio_client.Reset();
+ impl_->device.Reset();
+ impl_->enumerator.Reset();
+ if (impl_->com_inited) {
+ CoUninitialize();
+ impl_->com_inited = false;
+ }
+ impl_->initialized = false;
+}
+
+bool WasapiAudioBridge::write_float_pcm(const float* interleaved_samples, uint32_t frame_count) {
+ std::lock_guard<std::mutex> lock(impl_->mutex);
+ if (!impl_->initialized || !interleaved_samples || frame_count == 0) return false;
+
+ UINT32 padding = 0;
+ if (FAILED(impl_->audio_client->GetCurrentPadding(&padding))) return false;
+ UINT32 avail = impl_->buffer_frames - padding;
+ if (avail == 0) return false;
+
+ UINT32 to_write = (frame_count < avail) ? frame_count : avail;
+ BYTE* dst = nullptr;
+ if (FAILED(impl_->render_client->GetBuffer(to_write, &dst))) return false;
+ std::memcpy(dst, interleaved_samples, static_cast<size_t>(to_write) * impl_->channels * sizeof(float));
+ impl_->render_client->ReleaseBuffer(to_write, 0);
+ return true;
+}
+
+std::string WasapiAudioBridge::device_name() const { return impl_->device_name; }
+bool WasapiAudioBridge::is_initialized() const noexcept { return impl_->initialized; }
+
+// ============================================================================
+// SharedFolderManager
+// ============================================================================
+bool SharedFolderManager::add_mapping(const SharedFolderMapping& mapping, std::string& err) {
+ if (mapping.id.empty() || mapping.host_path.empty()) {
+ err = "Mapping id and host_path are required.";
+ return false;
+ }
+ std::error_code ec;
+ auto canon = std::filesystem::weakly_canonical(mapping.host_path, ec);
+ if (ec) {
+ err = "Invalid host_path: " + ec.message();
+ return false;
+ }
+ // Security rule: never allow mapping the entire system drive root
+ std::string s = canon.string();
+ if (s == "C:\\" || s == "c:\\") {
+ err = "Mapping the entire C:\\ system drive is disallowed by WSM security policy.";
+ return false;
+ }
+ for (const auto& m : mappings_) {
+ if (m.id == mapping.id) {
+ err = "Duplicate mapping id: " + mapping.id;
+ return false;
+ }
+ }
+ SharedFolderMapping clean = mapping;
+ clean.host_path = s;
+ mappings_.push_back(std::move(clean));
+ return true;
+}
+
+bool SharedFolderManager::remove_mapping(const std::string& id) {
+ for (auto it = mappings_.begin(); it != mappings_.end(); ++it) {
+ if (it->id == id) {
+ mappings_.erase(it);
+ return true;
+ }
+ }
+ return false;
+}
+
+std::vector<SharedFolderMapping> SharedFolderManager::list() const { return mappings_; }
+
+bool SharedFolderManager::resolve_safe_host_path(const std::string& mapping_id,
+ const std::string& rel_path,
+ std::string& out_path) const {
+ for (const auto& m : mappings_) {
+ if (m.id != mapping_id) continue;
+ std::error_code ec;
+ auto base = std::filesystem::weakly_canonical(m.host_path, ec);
+ if (ec) return false;
+ auto combined = std::filesystem::weakly_canonical(base / rel_path, ec);
+ if (ec) return false;
+ std::string b = base.string();
+ std::string c = combined.string();
+ if (c.size() >= b.size() && c.compare(0, b.size(), b) == 0) {
+ out_path = c;
+ return true;
+ }
+ return false; // Path traversal blocked
+ }
+ return false;
+}
+
+} // namespace wsm::services
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
new file mode 100644
index 0000000..8924692
--- /dev/null
+++ b/tests/CMakeLists.txt
@@ -0,0 +1,8 @@
+add_executable(wsm_core_tests wsm_core_tests.cpp)
+target_link_libraries(wsm_core_tests PRIVATE
+ wsm-core
+ wsm-compositor
+ wsm-services
+ wsm-appman
+)
+add_test(NAME wsm_core_tests COMMAND wsm_core_tests)
diff --git a/tests/wsm_core_tests.cpp b/tests/wsm_core_tests.cpp
new file mode 100644
index 0000000..4a481aa
--- /dev/null
+++ b/tests/wsm_core_tests.cpp
@@ -0,0 +1,185 @@
+#include "wsm/host_probe.hpp"
+#include "wsm/protocol.hpp"
+#include "wsm/compositor.hpp"
+#include "wsm/services.hpp"
+#include "wsm/app_registry.hpp"
+#include "wsm/guest_bridge.hpp"
+#include "wsm/shell_integration.hpp"
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+
+#include <cassert>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <thread>
+#include <vector>
+
+#pragma comment(lib, "ws2_32.lib")
+
+#define WSM_CHECK(cond) do { \
+ if (!(cond)) { \
+ std::cerr << "CHECK FAILED at line " << __LINE__ << ": " #cond "\n"; \
+ return 1; \
+ } \
+} while (0)
+
+int main() {
+ std::cout << std::unitbuf;
+ std::cout << "[test] 1. Protocol header validation...\n";
+ wsm::proto::FrameHeader hdr{};
+ hdr.channel = static_cast<uint16_t>(wsm::proto::Channel::Window);
+ hdr.type = static_cast<uint16_t>(wsm::proto::MsgType::WindowFrame);
+ hdr.payload_size = 1024;
+ WSM_CHECK(wsm::proto::validate_header(hdr));
+ hdr.payload_size = wsm::proto::WSM_MAX_PAYLOAD_SIZE + 1;
+ WSM_CHECK(!wsm::proto::validate_header(hdr));
+
+ std::cout << "[test] 2. WHPX live partition verification...\n";
+ auto whpx = wsm::core::probe_whpx(true);
+ WSM_CHECK(whpx.dll_present);
+ WSM_CHECK(whpx.hypervisor_present);
+ WSM_CHECK(whpx.partition_create_verified);
+
+ std::cout << "[test] 3. Vulkan & discrete GPU verification...\n";
+ auto gpu = wsm::core::probe_primary_gpu();
+ WSM_CHECK(gpu.vulkan_supported);
+ WSM_CHECK(gpu.dedicated_vram_bytes > 0);
+ std::cout << " GPU=" << gpu.name
+ << " Vulkan=" << gpu.vulkan_api_major << "." << gpu.vulkan_api_minor << "." << gpu.vulkan_api_patch
+ << " Win32ExtMem=" << gpu.ext_external_memory_win32 << "\n";
+
+ std::cout << "[test] 4. SharedFolderManager path traversal security...\n";
+ wsm::services::SharedFolderManager sfm;
+ std::string err;
+ WSM_CHECK(!sfm.add_mapping({"bad", "C:\\", "/Volumes/C", false}, err)); // Must block C:\ root
+ WSM_CHECK(sfm.add_mapping({"shared", "F:\\WSM\\runtime\\shared", "/Volumes/WSM-Shared", false}, err));
+ std::string resolved;
+ WSM_CHECK(sfm.resolve_safe_host_path("shared", "docs/readme.txt", resolved));
+ WSM_CHECK(!sfm.resolve_safe_host_path("shared", "../../Windows/System32", resolved)); // Must block traversal
+
+ std::cout << "[test] 5. Mach-O x86_64 & ARM64 & Universal header parser...\n";
+ std::filesystem::create_directories("F:\\WSM\\cache\\tmp");
+ auto write_u32s = [](const std::string& p, const std::vector<uint32_t>& words) {
+ std::ofstream f(p, std::ios::binary | std::ios::trunc);
+ f.write(reinterpret_cast<const char*>(words.data()), words.size() * sizeof(uint32_t));
+ };
+ write_u32s("F:\\WSM\\cache\\tmp\\test_x64.macho", {0xFEEDFACFu, 0x01000007u});
+ write_u32s("F:\\WSM\\cache\\tmp\\test_arm64.macho", {0xFEEDFACFu, 0x0100000Cu});
+ WSM_CHECK(wsm::runtime::inspect_macho_architecture("F:\\WSM\\cache\\tmp\\test_x64.macho") == wsm::runtime::BinaryArch::X86_64);
+ WSM_CHECK(wsm::runtime::inspect_macho_architecture("F:\\WSM\\cache\\tmp\\test_arm64.macho") == wsm::runtime::BinaryArch::Arm64);
+
+ std::cout << "[test] 6. VK -> macOS keycode translation...\n";
+ WSM_CHECK(wsm::compositor::vk_to_mac_keycode('A') == 0x00);
+ WSM_CHECK(wsm::compositor::vk_to_mac_keycode(VK_RETURN) == 0x24);
+ WSM_CHECK(wsm::compositor::vk_to_mac_keycode(VK_LWIN) == 0x37);
+
+ std::cout << "[test] 7. End-to-end GuestBridge -> DirectComposition TCP loopback...\n";
+ {
+ WSADATA wsa{};
+ WSM_CHECK(WSAStartup(MAKEWORD(2, 2), &wsa) == 0);
+ SOCKET srv = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ WSM_CHECK(srv != INVALID_SOCKET);
+ sockaddr_in addr{};
+ addr.sin_family = AF_INET;
+ addr.sin_port = htons(17445);
+ inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
+ int opt = 1;
+ setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&opt), sizeof(opt));
+ WSM_CHECK(bind(srv, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == 0);
+ WSM_CHECK(listen(srv, 1) == 0);
+
+ wsm::compositor::RootlessCompositor comp;
+ wsm::services::ClipboardBridge clip;
+ wsm::services::WasapiAudioBridge audio;
+ std::string comp_err;
+ WSM_CHECK(comp.start({}, comp_err));
+
+ wsm::runtime::GuestBridge bridge(comp, clip, audio);
+ bridge.start("127.0.0.1", 17445);
+
+ std::thread mock_guest([srv]() {
+ SOCKET cli = accept(srv, nullptr, nullptr);
+ if (cli == INVALID_SOCKET) return;
+
+ const char* title = "Calculator (Loopback Test)";
+ wsm::proto::WindowDescriptor desc{};
+ desc.window_id = 4242;
+ desc.pid = 777;
+ desc.bounds = {100, 100, 320, 240};
+ desc.visible = 1;
+ desc.title_len = static_cast<uint16_t>(std::strlen(title));
+
+ std::vector<uint8_t> wbuf(sizeof(desc) + desc.title_len);
+ std::memcpy(wbuf.data(), &desc, sizeof(desc));
+ std::memcpy(wbuf.data() + sizeof(desc), title, desc.title_len);
+
+ wsm::proto::FrameHeader hdr{};
+ hdr.channel = static_cast<uint16_t>(wsm::proto::Channel::Window);
+ hdr.type = static_cast<uint16_t>(wsm::proto::MsgType::WindowCreated);
+ hdr.payload_size = static_cast<uint32_t>(wbuf.size());
+ send(cli, reinterpret_cast<const char*>(&hdr), sizeof(hdr), 0);
+ send(cli, reinterpret_cast<const char*>(wbuf.data()), static_cast<int>(wbuf.size()), 0);
+
+ Sleep(200);
+
+ wsm::proto::WindowFrameHeader fh{};
+ fh.window_id = 4242;
+ fh.width = 320;
+ fh.height = 240;
+ fh.stride = 320 * 4;
+ fh.pixel_format = 0;
+
+ std::vector<uint8_t> fbuf(sizeof(fh) + fh.stride * fh.height, 0xCC);
+ std::memcpy(fbuf.data(), &fh, sizeof(fh));
+
+ hdr.type = static_cast<uint16_t>(wsm::proto::MsgType::WindowFrame);
+ hdr.payload_size = static_cast<uint32_t>(fbuf.size());
+ send(cli, reinterpret_cast<const char*>(&hdr), sizeof(hdr), 0);
+ send(cli, reinterpret_cast<const char*>(fbuf.data()), static_cast<int>(fbuf.size()), 0);
+
+ Sleep(300);
+ closesocket(cli);
+ });
+
+ for (int i = 0; i < 60 && bridge.frames_received() < 2; ++i) Sleep(25);
+ Sleep(150);
+ auto wins = comp.list_windows();
+ std::cout << " frames_received=" << bridge.frames_received() << " wins=" << wins.size() << "\n";
+ WSM_CHECK(wins.size() == 1);
+ WSM_CHECK(wins[0].window_id == 4242);
+ WSM_CHECK(wins[0].frames_presented >= 1);
+ std::cout << " Loopback window '" << wins[0].title << "' presented "
+ << wins[0].frames_presented << " hardware frame(s) over TCP!\n";
+
+ bridge.stop();
+ mock_guest.join();
+ closesocket(srv);
+ comp.destroy_window(4242);
+ Sleep(50);
+ comp.stop();
+ WSACleanup();
+ }
+
+ std::cout << "[test] 8. Apple .icns -> Windows .ico converter...\n";
+ {
+ // Construct a minimal valid .icns containing an ic08 PNG chunk
+ std::vector<uint8_t> icns = {
+ 'i','c','n','s', 0,0,0,32,
+ 'i','c','0','8', 0,0,0,24,
+ 0x89,'P','N','G',0x0D,0x0A,0x1A,0x0A,
+ 0,0,0,0, 0,0,0,0
+ };
+ std::ofstream f("F:\\WSM\\cache\\tmp\\test.icns", std::ios::binary | std::ios::trunc);
+ f.write(reinterpret_cast<const char*>(icns.data()), icns.size());
+ f.close();
+ WSM_CHECK(wsm::runtime::convert_icns_to_ico("F:\\WSM\\cache\\tmp\\test.icns", "F:\\WSM\\cache\\tmp\\test.ico"));
+ WSM_CHECK(std::filesystem::file_size("F:\\WSM\\cache\\tmp\\test.ico") == 22 + 16);
+ }
+
+ std::cout << "[test] ALL 8 CORE & INTEGRATION TESTS PASSED!\n";
+ return 0;
+}