Compare commits

...
Author SHA1 Message Date
千川白浪 c70a760603 docs(changelog): align v0.2.6 release notes style with prior releases 2026-11-29 06:04:49 -07:00
千川白浪 6367d17216 release: v0.2.6
Release Reims-Go / release (push) Canceled after 0s
2026-11-29 05:54:23 -07:00
千川白浪 460de66ac4 docs(readme): refresh feature overview, usage guide, and UI screenshots 2026-11-29 05:46:56 -07:00
千川白浪 338a9ee220 feat(ui): track macOS release artwork and redesign installers page 2026-11-29 05:46:56 -07:00
千川白浪 eb2b102bd5 perf(ui): code-split views, isolate VM stats polling, and prune finished tasks 2026-11-29 05:46:56 -07:00
千川白浪 7697374132 perf(backend): bound per-VM resources, stream 4K preview scaling, and cap log tailing 2026-11-29 05:46:05 -07:00
千川白浪 b839242716 feat(tray): redesign system tray menu with per-VM actions, status dots, and notifications 2026-11-29 05:46:05 -07:00
千川白浪 181d952388 fix(storage): account for reims-ctl VM directory and remaining DataRoot usage 2026-11-29 05:45:33 -07:00
千川白浪 7abcc64e6f ci(release): publish zipped Windows binary alongside standalone executable 2026-11-29 05:45:15 -07:00
千川白浪 0934d9d206 ci(runtime): strip runtime executables into detached symbols and trim unused QEMU payloads 2026-11-29 05:45:15 -07:00
千川白浪 003e4a08e7 chore(license): relicense Reims-Go from MIT to Apache-2.0 2026-11-29 05:45:15 -07:00
千川白浪andClaude Opus 5.5 704f68cdce feat(ui): display names for VMs and a side-by-side summary on wide windows
- The VM note now acts as its display name: shown as the page title and in
  the sidebar, renamed in place by clicking the title (or More → Change
  Display Name…). The VM name stays the identifier for folders, CLI and
  reims-ctl; it shows in the title's tooltip and in Technical details.
  Clearing the field or typing the VM name removes the display name.
- When the content column is at least 760 px wide (container query), the
  screen and actions sit on the left and the summary becomes one labelled
  column on the right, so long GPU names are no longer cut off. Narrower
  windows keep the stacked layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:34:53 -07:00
千川白浪andClaude Opus 5.5 ab49d79a71 feat(ui): title-bar menus, hideable sidebar, and a calmer status bar
- Title bar: the logo and name give way to a sidebar toggle and a small
  menu bar (VM / View / Help). Every command lists its shortcut; once a menu
  is open, hovering the next title switches to it. Setup keeps the logo.
- Sidebar hides with Ctrl+B or the toggle (remembered); View menu still
  reaches Installers / Engine / Settings while it is hidden.
- Status bar shows "label value" pairs split by hairlines: memory as
  used / total GB with a bar, the data drive's free space ("D: 816 GB
  free"), running VM count. Exact figures move to tooltips. When WHPX or
  the runtime is not ready it leads with a warning chip that opens the
  Engine page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:19:27 -07:00
千川白浪andClaude Opus 5.5 c0f08be124 feat: per-VM CPU affinity, disk snapshots, SSH helpers and VM window actions
Backend
- Per-VM CPU affinity (vmstart/affinity.go, affinity_flow.go): modes auto /
  all / P-cores / non-LP-E / custom, saved in the VM folder, applied to the
  QEMU process on start (GUI and CLI) and live via SetVMAffinity; copied on
  clone. Start summary logs the resolved mapping. Host report gains CPU
  topology helpers (mask <-> CPU list).
- Offline qcow2 restore points via qemu-img (driver/reims/snapshot.go,
  snapshot_flow.go): list / create / restore / delete.
- SSH helpers (ssh_flow.go): remembered user, open a terminal, write an
  ~/.ssh/config entry, open VS Code Remote-SSH.
- FocusVMWindow brings the QEMU window forward (restoring it if minimized);
  CopyVMScreenshot copies a full-resolution frame to the clipboard.
- DeliverPathsToGuest copies dropped host files into the shared folder;
  main.go enables Wails file drop on elements marked --wails-drop-target.
- VM note (.reims-go-note) and a storage breakdown (extras_flow.go).

Frontend
- VM page: running state's "Show Window" and the screen preview use
  FocusVMWindow; camera button and More-menu item copy a screenshot;
  editable note under the name; SSH row shows the saved user with
  Terminal / config / VS Code actions; restore-point list; install guide
  steps can be ticked off; drop files onto the page to send them.
- Sidebar right-click menu per VM (start, show window, screenshot, stop,
  restart, settings, folders, clone, delete); double-click and Ctrl+Enter
  still run the main action.
- AffinityDialog opened from the VM menu and VM settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:00:48 -07:00
千川白浪andClaude Opus 5.5 dac10a52bc ci(release): build release notes from CHANGELOG.md
- scripts/build-release-notes.ps1 extracts the `## <tag>` section and wraps
  it with download, stable runtime, license and compare links; it fails if
  the section is missing or empty.
- CI checks that CHANGELOG.md has notes for the version in version.go.
- release.yml uses those notes instead of --generate-notes, checks out the
  dispatched tag, fails on gh errors, and backfills notes on an existing
  release whose body is empty or only the auto "Full Changelog" link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:00:37 -07:00
千川白浪andClaude Opus 5.5 b007f6b445 feat(ui): rework VM page around one action per state and plain-language summary
- Running state gets "Show Window" as its primary action (Ctrl+Enter, or
  double-click the VM in the sidebar); stopped keeps "Start". The screen
  preview is a pointer shortcut for the same action; its play button now
  shows on hover only.
- Summary card: disk shows "54 / 128 GB" (controller in tooltip), network
  shows "Shared network" (SSH port only in the SSH row). The separate
  QEMU CPU / host RAM card is folded into live bars under cores and memory.
- Guest Tools is one row with a single status; the install command appears
  as a sub-step only while the disk is attached and macOS is not connected.
- Pending changes read "Memory 8 GB -> 16 GB" instead of raw field names.
- More menu grouped by purpose, destructive items last; adds Copy Screenshot.
- Narrower column and height-aware screen size so Connection stays above
  the fold at 700 px; motion for state changes, meters and screen hover.
- Sidebar VM icons use each VM's last screen; status bar drops the
  parenthetical free-memory text (still in the tooltip).
- FocusVMWindow / CopyVMScreenshot are looked up at run time (wails.ts
  optionalApi) so the UI works with backends that lack them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:40:15 -07:00
89 changed files with 6955 additions and 885 deletions

No files matched your search

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 39 KiB

+4 -2
View File
@@ -196,7 +196,7 @@ jobs:
$ErrorActionPreference = 'Stop'
& ./scripts/check-runtime-alpha.ps1 `
-OutDir (Join-Path $env:RUNNER_TEMP 'releases') `
-Commit $env:RELEASE_ID `
-Commit $env:RELEASE_ID -RequireSlim `
-Zstd (Join-Path '${{ steps.msys2.outputs.msys2-location }}' 'usr\bin\zstd.exe') `
-AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
@@ -220,7 +220,7 @@ jobs:
$c = $env:RELEASE_ID
$short = $env:SHORT_COMMIT
$dir = Join-Path $env:RUNNER_TEMP 'releases'
$assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", 'SHA256SUMS.txt') |
$assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", "reims-runtime-symbols-$c.tar.zst", 'SHA256SUMS.txt') |
ForEach-Object { Join-Path $dir $_ }
$applied = if ($env:APPLIED_PATCHES) { ($env:APPLIED_PATCHES -split ',' | ForEach-Object { "- ``$_``" }) -join "`n" } else { '- (none)' }
$merged = if ($env:MERGED) { "`n`nAlready upstream, skipped (retire from patches/): $env:MERGED" } else { '' }
@@ -232,6 +232,8 @@ jobs:
Local patches applied (sources and patches are in the attached source packages):
$applied$merged
The optional ``reims-runtime-symbols-$c.tar.zst`` contains matching debug files for crash analysis.
Build: $env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID
"@
gh release create "runtime-$c" @assets --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes
+13
View File
@@ -26,6 +26,19 @@ jobs:
cache: pnpm
cache-dependency-path: frontend/pnpm-lock.yaml
- name: Verify CHANGELOG.md matches current version
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$verFile = Get-Content -Raw -LiteralPath 'internal/version/version.go'
if ($verFile -notmatch 'var\s+Version\s*=\s*"(v[^"]+)"') {
throw 'Could not parse Version from internal/version/version.go'
}
$ver = $Matches[1]
$tmp = Join-Path $env:RUNNER_TEMP "release-notes-$ver.md"
& ./scripts/build-release-notes.ps1 -Tag $ver -OutFile $tmp
Write-Host "PASS CHANGELOG.md contains valid release notes for $ver ($((Get-Item -LiteralPath $tmp).Length) bytes)"
- name: Frontend build
shell: pwsh
run: |
+59 -4
View File
@@ -18,6 +18,8 @@ jobs:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || '' }}
- uses: actions/setup-go@v5
with:
@@ -40,6 +42,39 @@ jobs:
if (-not $tag.StartsWith('v')) { throw "Release tag must start with 'v', got: $tag" }
"RELEASE_TAG=$tag" | Out-File -FilePath $env:GITHUB_ENV -Append
- name: Generate release notes from CHANGELOG.md
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$tag = $env:RELEASE_TAG
$runtimeTag = ''
$runtimeTitle = ''
try {
$rels = gh release list -R $env:GITHUB_REPOSITORY --limit 100 --json tagName,name,isPrerelease,isDraft,createdAt | ConvertFrom-Json
$stable = $rels |
Where-Object { $_.tagName -like 'runtime-*' -and -not $_.isPrerelease -and -not $_.isDraft } |
Sort-Object createdAt -Descending |
Select-Object -First 1
if ($stable) {
$runtimeTag = $stable.tagName
$runtimeTitle = if ($stable.name) { $stable.name } else { $stable.tagName }
}
} catch {
Write-Warning "Could not query latest stable runtime release: $_"
}
$notesFile = Join-Path $env:RUNNER_TEMP "release-notes-$tag.md"
& ./scripts/build-release-notes.ps1 `
-Tag $tag `
-ChangelogPath 'CHANGELOG.md' `
-Repo $env:GITHUB_REPOSITORY `
-StableRuntimeTag $runtimeTag `
-StableRuntimeTitle $runtimeTitle `
-OutFile $notesFile
"RELEASE_NOTES_FILE=$notesFile" | Out-File -FilePath $env:GITHUB_ENV -Append
Write-Host "Generated release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $tag"
- name: Build frontend
shell: pwsh
run: |
@@ -67,8 +102,11 @@ jobs:
# One executable: the window without arguments, command-line mode with a command.
$guiOut = Join-Path $dist "reims-go-$tag-windows-amd64.exe"
wails build -s -trimpath -ldflags "-s -w -X $verPkg.Version=$tag" -o "reims-go-$tag-windows-amd64.exe"
if ($LASTEXITCODE) { throw "wails build failed ($LASTEXITCODE)" }
Copy-Item (Join-Path 'build\bin' "reims-go-$tag-windows-amd64.exe") $guiOut
$lines = @(Get-ChildItem -LiteralPath $dist -File | Sort-Object Name | ForEach-Object {
$zipOut = [IO.Path]::ChangeExtension($guiOut, '.zip')
Compress-Archive -LiteralPath $guiOut -DestinationPath $zipOut -CompressionLevel Optimal -Force
$lines = @(Get-Item -LiteralPath $guiOut, $zipOut | ForEach-Object {
$h = (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLowerInvariant()
"$h $($_.Name)"
})
@@ -82,18 +120,35 @@ jobs:
run: |
$ErrorActionPreference = 'Stop'
$tag = $env:RELEASE_TAG
$notesFile = $env:RELEASE_NOTES_FILE
if (-not (Test-Path -LiteralPath $notesFile) -or (Get-Item -LiteralPath $notesFile).Length -eq 0) {
throw "Release notes file is missing or empty: $notesFile"
}
$files = @(Get-ChildItem -LiteralPath 'dist-release' -File | Select-Object -ExpandProperty FullName)
$exists = $true
$existingBody = ''
try {
gh release view $tag *> $null
if ($LASTEXITCODE -ne 0) { $exists = $false }
$relJson = gh release view $tag --json body 2>$null
if ($LASTEXITCODE -ne 0) {
$exists = $false
} else {
$existingBody = (($relJson | ConvertFrom-Json).body | Out-String).Trim()
}
} catch {
$exists = $false
}
if ($exists) {
gh release upload $tag @files --clobber
if ($LASTEXITCODE -ne 0) { throw "gh release upload failed ($LASTEXITCODE)" }
# Backfill notes if the existing release body is empty or only GitHub's auto-generated compare link.
$isAutoOnly = [string]::IsNullOrWhiteSpace($existingBody) -or ($existingBody -match '^\*\*Full Changelog\*\*:\s*https://\S+$')
if ($isAutoOnly) {
gh release edit $tag --notes-file $notesFile
if ($LASTEXITCODE -ne 0) { throw "gh release edit failed ($LASTEXITCODE)" }
}
} else {
gh release create $tag @files `
--title "Reims-Go $tag" `
--generate-notes
--notes-file $notesFile
if ($LASTEXITCODE -ne 0) { throw "gh release create failed ($LASTEXITCODE)" }
}
+1 -1
View File
@@ -30,7 +30,7 @@
## 开源合规边界
- `reims-go` 自身代码(Go 后端 + 前端外壳)采用 **MIT** 协议,见 [`LICENSE`](LICENSE)。
- `reims-go` 自身代码(Go 后端 + 前端外壳)采用 **Apache-2.0** 协议,见 [`LICENSE`](LICENSE)。
- 运行时组件(`qemu-system-x86_64.exe` 为 GPLv2,`reims-ctl` / `reims-vgpu` / `metal2vulkan` 为 `GPL-2.0-or-later OR LGPL-3.0-or-later`,以及 CLANG64/libva 动态库)以**独立子进程与独立运行时压缩包**形态集成。发布二进制时必须同时提供**对应源码包**(含本地补丁,只给上游链接不够)和完整许可证文本(`NOTICE.md` / `licenses/`),见 `docs/portable-runtime-spec.md` 第 7 节。
- 不打包、不托管任何 Apple 系统文件;macOS 恢复镜像一律由用户端运行 `reims-util` 直连 Apple 服务器拉取或本地导入。
- macOS 的软件许可只允许在 Apple 硬件上虚拟化。上游也处在同样的位置,但一键工具公开发布会放大风险。**是否公开发布由人决定**,在此之前 Release 保持私有。
+22
View File
@@ -2,6 +2,28 @@
本文件只记录 Reims-Go 桌面应用的变化。便携运行时(`runtime-*`)的版本另见 [Releases](https://github.com/Nwflower/Reims-Go/releases)。
## v0.2.6 — 2026-11-29
### 新功能
- 可为每台虚拟机单独指定使用的 CPU 核心(自动、全部核心、性能核、避开低功耗核或自定义),运行中修改立即生效。
- 虚拟机停机后可创建、回滚和删除恢复点。
- 新增 SSH 快捷操作:记住用户名,一键打开终端、写入 `~/.ssh/config` 或用 VS Code 远程连接。
- 运行中可一键把虚拟机窗口带到前台,或复制当前全分辨率截图到剪贴板。
- 把文件拖进应用窗口即可直接传到虚拟机的共享文件夹。
- 可在标题处直接给虚拟机起一个显示名称,底层目录和命令名保持不变;宽窗口下预览与配置信息并排显示。
- 新增标题栏菜单和侧栏折叠(`Ctrl+B`),侧栏虚拟机支持右键菜单,底部状态栏更简洁。
- 系统托盘菜单改版:每台虚拟机有独立子菜单和状态圆点,跟随 Windows 浅色/深色主题,截图和后台出错时弹出系统通知。
- 侧栏和未截屏预览按 macOS 大版本显示对应图标;「安装包」页按大版本归组并折叠旧版本,加载失败可直接重试。
### 优化
- 虚拟机页按状态突出主要操作,并把实时负载、磁盘和 Guest Tools 状态收进摘要区。
- 生成 4K 屏幕预览的内存占用大幅下降,删除虚拟机或长时间运行后及时清理后台资源与过期任务。
- 界面各页面和弹窗改为按需加载,减少无谓刷新和显卡开销。
- 修复空间分布统计,正确计入虚拟机文件以及数据目录中的其余数据。
- Reims-Go 本体开源协议由 MIT 变更为 Apache-2.0;发布时同时提供 `.zip` 压缩包和独立 `.exe`。
## v0.2.5 — 2026-11-29
### 新功能
+196 -17
View File
@@ -1,21 +1,200 @@
MIT License
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2026 Reims-Go contributors
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. Definitions.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate acts) or agreed
to in writing, shall any Contributor be liable to You for damages,
including any direct, indirect, special, incidental, or consequential
damages of any character arising as a result of this License or out of
the use or inability to use the Work (including but not limited to damages
for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Reims-Go contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+4 -4
View File
@@ -1,9 +1,9 @@
# Third-Party Notices
`Reims-Go` itself (Go backend and desktop frontend) is licensed under the MIT
License (see `LICENSE`). That license applies to Reims-Go's own code only and
is separate from the portable runtime bundle it invokes as an external child
process.
`Reims-Go` itself (Go backend and desktop frontend) is licensed under the Apache
License, Version 2.0 (see `LICENSE`). That license applies to Reims-Go's own code
only and is separate from the portable runtime bundle it invokes as an external
child process.
The portable runtime bundle (`reims-runtime-win-x64-<commit>.tar.zst`) contains
precompiled binaries built from the following upstream open-source projects.
+58 -23
View File
@@ -20,12 +20,12 @@
<br />
<p align="center">
<img src="./.github/readme/hero.webp" width="100%" alt="Reims-Go 主窗口:浅色外观下的虚拟机详情页与深色外观下的宿主与运行时页" />
<img src="./.github/readme/hero.webp" width="100%" alt="Reims-Go 主窗口:浅色外观下的虚拟机页与深色外观下的内核页" />
</p>
<br />
Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows 桌面应用。环境体检、运行时安装、下载 macOS 到创建并管理虚拟机,都在一个窗口里完成。
Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows 桌面应用。从检查电脑、安装运行时、下载 macOS,到创建和日常使用虚拟机,都在一个窗口里完成。
> 早期迭代中,功能与界面仍在持续打磨。
@@ -33,11 +33,43 @@ Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows
## 特性
- **开箱即用** — 预编译便携运行时一键在线安装,无需配置 MSYS2、Rust 或本地编译。
- **体检与调优** — 一键启用 WHPX、启动前校验提交内存、混合架构智能绑核(P-Core / 避开 LP-E 核),新建默认 NVMe。
- **离线装机** — 宿主机直连 Apple 断点续传下载;内置离线辅助盘与「粘贴为键入」,装机无需手敲长命令。
- **随时调整** — 运行中即可修改配置并标明生效时机,支持一键进出恢复模式;全部数据留在指定目录,不占 C 盘。
- **双端一致** — 浅色 / 深色外观与中英双语,GUI 与命令行共用同一套内核。
### 开箱即用
- **不用编译** — 运行时在应用里一键下载安装,不用装 MSYS2、Rust,也不用自己编译。GitHub 连不上时自动改从 GitCode 国内镜像下载,并沿用 Windows 的系统代理设置。
- **先检查再开工** — 首次打开会检查虚拟化、显卡和内存;虚拟化没开的话可以一键开启。
- **不占 C 盘** — 运行时、安装包、虚拟磁盘和临时文件都放在你选的数据目录里。
### 装机
- **安装包直接从 Apple 下载** — 在 Windows 上下载完整安装包,可以暂停和续传;装机过程不用联网。
- **不用手敲命令** — 装机命令点一下就自动键入到 macOS 的恢复终端,抹盘和安装都会自动完成。
- **按本机配置推荐** — 内存大小按电脑的空闲内存推荐,分辨率按显示器和缩放推荐清晰的 HiDPI 档位。
- **装机界面用中文** — 可以提前选好 macOS 系统语言,恢复模式和设置助理不再只有英文。
- **导入已有磁盘** — 新建时可以直接用现成的 VMDK 或 RAW 磁盘。
### 日常使用
- **和 Windows 互通** — 双向剪贴板(包括图片)和共享文件夹,把文件拖到窗口里就能传进 macOS;还可以把 Windows 磁盘以只读方式共享给 macOS。
- **直接打中文** — 中文、emoji 和 Windows 输入法都能直接输入到虚拟机。
- **一眼看清状态** — 页面上有屏幕预览,以及 CPU、内存、磁盘的实时占用;一键截屏并复制。
- **常驻托盘** — 关掉窗口后剪贴板和共享照常工作,可以从托盘启动或关闭虚拟机,也可以让 macOS 保持唤醒。
- **随时修改设置** — 虚拟机运行时也能改设置,界面会说明改动是立即生效还是下次启动生效;一键进入或退出恢复模式。
- **浅色、深色外观,中英双语**。
### 性能
- **显卡加速** — 用 Windows 上的独立显卡加速 macOS 的图形显示。
- **自动挑选性能核** — 在大小核处理器上,虚拟机自动跑在性能核上,减少卡顿;也可以给每台虚拟机单独指定用哪些核,运行中修改立即生效。
- **启动前检查内存** — 内存不够时会先提示,避免启动到一半失败。
### 进阶
- **秒级派生副本** — 已关机的虚拟机可以秒级派生出一台独立副本,副本只记录与原机的差异,刚派生时几乎不占额外空间。
- **恢复点** — 升级系统或大改环境前留一个恢复点,出问题时一键回滚。
- **磁盘管理** — 关机后可以给虚拟磁盘扩容,或回收没有用到的空间。
- **SSH** — 端口转发,一键打开终端、写入 `~/.ssh/config` 或用 VS Code 远程连接。
- **命令行** — 检查环境、安装运行时、下载安装包,以及新建、修改、启动和关闭虚拟机,都能在命令行里完成,方便写脚本。
- **排障** — 一键导出已去掉隐私信息的日志包;Windows 10 上 macOS 自己重启时也能正常回到系统。
<br />
@@ -45,9 +77,10 @@ Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows
### 环境要求
- Windows 10 / 11(64 位),支持 WHPX 虚拟化
- Windows 10 / 11(64 位),处理器支持虚拟化,并已在 BIOS 里开启 Intel VT-x / AMD-V
- 支持 Vulkan 的独立显卡(推荐 NVIDIA RTX 系列)
- 150 GB 以上可用磁盘空间(建议非 C 盘)
- 内存建议 16 GB 以上
- 可用磁盘空间建议 150 GB 以上,至少 60 GB(一个安装包约 20 GB,虚拟磁盘会随使用增长);最好不要放在系统盘或外置盘
### 安装
@@ -70,24 +103,26 @@ wails build
### 上手步骤
1. **初始化** — 首次打开按引导选好数据目录、完成宿主机体检(未开 WHPX 可一键启用并重启),在线安装运行时。
2. **新建虚拟机** — 点侧边栏 **+**,选择「离线安装包(推荐)」或先在「安装包」页下载镜像,设定 CPU、内存与磁盘。
3. **安装 macOS** — 启动后在恢复终端点右侧键盘图标一键键入安装命令,脚本会自动抹盘并完成离线安装;看到「设置助理」后点「退出恢复模式」。
4. **日常管理** — 点齿轮图标随时调整设置,或在「更多」菜单中使用「粘贴为键入」与「进入恢复模式」。
1. **初始化** — 首次打开时按引导选好数据目录,完成电脑检查(虚拟化没开可以一键开启,之后需要重启 Windows),再在线安装运行时。
2. **新建虚拟机** — 点侧边栏的 **+**,安装来源选「离线安装包」(也可以先到「安装包」页下载好),再设好 CPU、内存和磁盘。
3. **安装 macOS** — 启动虚拟机,按页面上的装机引导操作:在恢复终端里点键盘图标,装机命令会自动键入,抹盘和安装随即开始;看到「设置助理」后点「退出恢复模式」。
4. **安装 Guest Tools** — 进入 macOS 桌面后,在虚拟机页 Guest Tools 一行点「安装…」,再到 macOS 终端里运行页面给出的命令。装好后剪贴板、共享文件夹和中文输入就能用了。
5. **日常管理** — 设置、恢复点和 SSH 都在虚拟机页上;「更多」菜单里还有发送文本、进入恢复模式、派生副本、导出排障日志等操作。
### 命令行
命令行模式就在同一个 `reims-go.exe` 里:不带参数打开窗口,带子命令就在终端里执行。
命令行就在同一个 `reims-go.exe` 里:不带参数会打开窗口,带上子命令就在终端里执行。
```powershell
reims-go doctor | Out-Host # 环境体检
reims-go doctor | Out-Host # 检查电脑环境
reims-go runtime fetch | Out-Host # 在线安装运行时
reims-go installer download tahoe | Out-Host # 下载离线安装包(支持续传)
reims-go installer download tahoe | Out-Host # 下载安装包(支持续传)
reims-go vm create macos-tahoe | Out-Host # 新建虚拟机
reims-go vm start macos-tahoe | Out-Host # 启动虚拟机(交给托盘里的 Reims-Go,带剪贴板与共享目录)
reims-go vm start macos-tahoe | Out-Host # 启动虚拟机
reims-go vm stop macos-tahoe | Out-Host # 关闭虚拟机
```
`reims-go.exe` 是窗口程序,交互式 PowerShell / cmd 不会等它结束;加 `| Out-Host`(或任何管道、重定向)就会等命令执行完并给出退出码。脚本和 Agent 通过管道调用,不受影响。运行 `reims-go help` 查看全部子命令,加 `--lang en-US` 切换英文输出。
在 PowerShell 或 cmd 里直接输入命令时,要加上 `| Out-Host`,终端才会等命令执行完再返回。运行 `reims-go help` 可以查看全部子命令,加 `--lang en-US` 会改成英文输出。
<br />
@@ -98,16 +133,16 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机(交给托盘
<td width="50%">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/host-dark.webp" />
<img src="./.github/readme/host-light.webp" alt="宿主与运行时页" />
<img src="./.github/readme/host-light.webp" alt="内核页" />
</picture>
<p align="center"><sub>宿主与运行时</sub></p>
<p align="center"><sub>内核</sub></p>
</td>
<td width="50%">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/vm-dark.webp" />
<img src="./.github/readme/vm-light.webp" alt="关于此虚拟机页" />
<img src="./.github/readme/vm-light.webp" alt="虚拟机页" />
</picture>
<p align="center"><sub>关于此虚拟机</sub></p>
<p align="center"><sub>虚拟机</sub></p>
</td>
</tr>
<tr>
@@ -132,7 +167,7 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机(交给托盘
## 许可与声明
- **开源协议**:Reims-Go 本体采用 [MIT](./LICENSE) 协议;独立调用的便携运行时组件及其许可证见 [`NOTICE.md`](./NOTICE.md),每个运行时 Release 均附带对应源码包。
- **开源协议**:Reims-Go 本身采用 [Apache-2.0](./LICENSE) 协议。运行时里的 QEMU 等组件作为独立程序随附,各自的许可证见 [`NOTICE.md`](./NOTICE.md);每个运行时 Release 都附带对应的源码包。
- **关于 macOS**:Reims-Go 不包含、不分发任何 Apple 系统文件,安装包由本机直连 Apple 服务器获取。**macOS 软件许可协议仅允许在 Apple 硬件上虚拟化**,在非 Apple 硬件上使用请自行评估合规责任。本项目与 Apple Inc. 无关,macOS 为 Apple Inc. 注册商标。
## 友情链接
+31
View File
@@ -0,0 +1,31 @@
# 内存占用审计(2026-11-29)
## 范围与结论
本轮检查了 Reims-Go 的 Go 后端、React 前端、Guest Tools、QMP 截图和 VM 启停链路,并采样已运行的桌面应用,使用无磁盘 WHPX 虚拟机和 4K 图像分别测量 QEMU 启动占用与预览开销。用户的 macOS 虚拟机处于关机状态。
已确认并修复 Reims-Go 按 VM 生命周期无界保留的状态:缩略图锁、Guest Tools 注册与 WebDAV handler、进程采样、磁盘路径、绑核 PID、远程文本队列及其 worker。删除 VM 时立即回收;通过 CLI 或外部工具删除时,由 VM 轮询回收。日志和任务列表也有上限或过期清理。
本机 macOS VM 的配置与上次启动日志均记录了 8 GiB 客体内存。检查时 Windows 可用提交内存约 7.2 GiB,低于启动器对该 VM 要求的 9 GiB(含 1 GiB 余量)。QEMU 和 vGPU 在固定 macOS 图形负载下是否会持续增长,待验证。
## 测量与修复
- 在 macOS VM 关机时,每 15 秒采样一次,共 11 次。Reims-Go 主进程的私有提交为 59.9–60.5 MiB,其进程树中的 6 个 WebView2 进程合计 282.6–286.3 MiB。数值来自修复前已在运行的桌面程序。
- 用本机便携运行时(`3731afd`)启动无磁盘、无网络的 WHPX 测试机,依次配置 512、1024、512 MiB 内存。各轮第 10 秒的 QEMU 私有提交为 537.2、1049.9、537.3 MiB,工作集为 46.8、46.8、46.9 MiB,三次 QMP 退出的进程退出码均为 0。此测试覆盖固件空载阶段。
- 后台监视串口和 QEMU 日志时,旧实现遇到一直没有换行的输出会持续拼接并保留整行。现在每行暂存上限为 64 KiB,过长行跳到下一个换行,原始日志文件完整保留。
- 前端会在已结束任务超过 10 分钟后清理任务记录及通知去重标记,与后端保留时间一致。运行中的任务持续显示。
- 用相同的 3840×2160 PPM 文件生成宽 640 像素的 JPEG,各测 8 帧。`BenchmarkPreview4K` 在原版本(`704f68c`)每帧分配 56.4 MiB,按行缩放后为 1.04 MiB,下降约 98%。这是单帧累计 Go 分配量。手动复制截图仍保留全分辨率,并按行将 RGB 转为 RGBA。
- VM 详情原先随每次宿主状态刷新重新调用 `reims-ctl show`,包含窗口可见时每 10 秒一次的轮询。现在只随选择、运行/过渡状态和显式 `reims:state-changed` 事件重取,配置保存后的刷新语义保持不变。
- Go 的 RSS 在 GC 后不必然立即下降;只有保留对象持续增长才证明泄漏。不要为了压低任务管理器数字在热路径加入 `debug.FreeOSMemory`。
## 实机复测建议
使用同一 VM、固定客体负载和同一分辨率,在启动稳定后、1 小时、4 小时分别记录 QEMU 与 Reims-Go 进程树的 Private Bytes、Working Set 和句柄数。期间分别覆盖打开/隐藏 Reims-Go 窗口、切换 VM、截图、复制大图片和客体睡眠唤醒。
若 QEMU Private Bytes 在固定负载下持续线性增长,再按运行时 manifest 中的 commit 和补丁进行上游定位。既有 `qemu-win32-coroutine-fiber-commit.patch` 将每个协程栈初始提交从 1 MiB 降为 64 KiB,但仍是待真机验证的补丁,且不会改变 Guest RAM 的基础占用。
## 验证
- `go test ./...`:通过。
- `pnpm --dir frontend run build`:通过;仅有既存的 Vite 大 chunk 提示。
- 临时启用 CGO 并使用本机 MSYS2 CLANG64,`go test -race ./...` 通过。
+16 -7
View File
@@ -41,7 +41,14 @@
## 3. 便携运行时体积与目录规范
本机实测未压缩体积:**917.8 MB**(`qemu/` 828.5 MB + `reims-ctl.exe` 58.0 MB + `reims-util.exe` 31.3 MB);2026-11-28 实测使用 `zstd -T0 -15` 打包 `reims-runtime-win-x64-3731afd.tar.zst` 后仅 **`160.4 MB`**(压缩率 **17.5%**,不到同类 PySide6 打包方案 1.68 GB 的十分之一)。
已发布的 `runtime-3731afd` 是未裁剪、保留调试符号的历史基线:本机实测未压缩体积 **917.8 MB**,`zstd -T0 -15` 压缩包 **160.4 MB**。下文的新布局不改变这个既有 Release 的内容。
2026-11-29 起,新打包流程采用以下两项可复现的体积优化:
1. 只删除 Windows x64 启动器不会调用的通用工具 `qemu-system-x86_64.exe`、`elf2dmp.exe`、`qemu-edid.exe`、`qemu-io.exe`、`qemu-nbd.exe`、`qemu-storage-daemon.exe`,以及 ARM64、RISC-V、LoongArch64 的 EDK2 固件及其描述文件。x64 固件、BIOS、ROM、keymaps、动态加载的 `libva` 视频驱动和全部 DLL 均保留。
2. 对五个主要可执行文件使用 MSYS2 CLANG64 的 `llvm-objcopy` 提取调试符号、剥离 `.debug_*` 节并写入 GNU debug link。对应的 `.debug` 文件单独发布,不丢失崩溃定位能力。通用 DLL 的符号仍保留。
同一上游 `3731afd` 和相同两项本地补丁的暂存实验结果为:删除上述工具和异架构固件后 **425.3 MiB** 解压 / **98.3 MiB** 压缩;再剥离主要程序调试符号后 **166.4 MiB** 解压 / **48.0 MiB** 压缩。前者与旧包的目录统计口径略有差异,最终以实际归档解压结果为准。
### 3.1 运行时发布包结构(`reims-runtime-win-x64-<commit>.tar.zst`)
@@ -60,9 +67,11 @@ reims-runtime-<commit>/
│ ├── qemu-img.exe
│ ├── reims-vgpu-compile.exe
│ └── *.dll # 71 个自包含 CLANG64 + libva/vaon12 DLL
└── share/ # QEMU pc-bios / edk2 / keymaps 等数据文件
└── share/ # x64 pc-bios / edk2 / keymaps 等数据文件
```
同一 Release 另有 `reims-runtime-symbols-<commit>.tar.zst`,按运行时相同路径保存五个 `*.exe.debug` 文件。`manifest.json` 的 `symbols_package` 指向该附件,`sha256` 记录最终已剥离程序的哈希。GNU 调试器可通过程序内的 debug link 和符号包目录定位对应文件。调试符号包不参与客户端下载。
> **版本耦合约束**:`reims-ctl.exe`、`reims-util.exe` 与 `qemu/` 必须来自**同一个上游 commit**,作为单一版本目录原子安装与回滚,避免协议或内嵌 kext 版本错配。
### 3.2 用户数据目录结构(由用户在向导中选择,默认非系统盘如 `D:\Data\reims-go\`)
@@ -89,17 +98,17 @@ reims-runtime-<commit>/
## 4. 打包与发布流水线(M0 / M4)
- **本地打包验证(M0)**:编写 `scripts/pack-runtime.ps1`,直接从本机已编译的 `reims-vgpu` 产物生成 `reims-runtime-win-x64-3731afd.tar.zst` 与 `manifest.json`(含 SHA256),验证纯净解压启动。
- **本地打包与发布(2026-11-28 起)**:`pwsh -File scripts/pack-runtime.ps1 -Channel alpha` 一次产出三个文件:运行时包、对应源码包 `reims-runtime-src-<commit>.tar.zst`、覆盖两者的 `SHA256SUMS.txt`。补丁按 `patches/series.txt` 的顺序取,`-Patches` 可以只列实际打上的那几个。
- **本地打包与发布(2026-11-29 起)**:`pwsh -File scripts/pack-runtime.ps1 -Channel alpha` 一次产出四个压缩包及 `SHA256SUMS.txt`:运行时包、对应源码包 `reims-runtime-src-<commit>.tar.zst`、MSYS2 源码包和可选调试符号包。补丁按 `patches/series.txt` 的顺序取,`-Patches` 可以只列实际打上的那几个。
- **打包前的检查**:脚本先核对每个补丁是否与构建目录里的 diff 完全一致;不一致、或者构建目录里有补丁没涉及的文件被改动,就直接停止,不会自动修改补丁。允许改动的文件从补丁本身读出(2026-11-28 前写死为 `whpx-all.c`,带上 fiber 补丁就会误报)。
- **manifest 版本 2**:比版本 1 多记录 `vendor_qemu_commit`、`util_commit`、`metal2vulkan_commit`、`patches`(名称、作用对象、SHA256)、`channel`、`source_package`。`dll_count` 改为按实际文件统计;版本 1 的统计有误,记为 0。
- **发布位置**:运行时发布在 [`Nwflower/reims-go`](https://github.com/Nwflower/reims-go/releases) 的 GitHub Release。tag 为 `runtime-<commit>`,附件就是上面三个文件。GitHub 的预发布对应 `alpha`(2026-11-28 前叫 `candidate`),正式发布对应 `stable`。三个附件缺任何一个,客户端就不会列出这个版本。
- **发布位置**:运行时发布在 [`Nwflower/reims-go`](https://github.com/Nwflower/reims-go/releases) 的 GitHub Release。tag 为 `runtime-<commit>`,附件包含上述四个压缩包和校验清单。GitHub 的预发布对应 `alpha`(2026-11-28 前叫 `candidate`),正式发布对应 `stable`。客户端下载仍只需要运行时包与校验清单,因此旧客户端也可安装新布局。
- **客户端安装**(`internal/runtime/remote.go`):从 GitHub API 列出版本 → 下载运行时包,支持续传 → 对照 `SHA256SUMS.txt` 校验,不一致就丢弃 → 用原有的导入流程解压并激活 → 删除下载的压缩包。
- **已发布**:`runtime-3731afd`,先以候选版(即现在的 alpha)发布,同日升为稳定版。实测从 GitHub 下载 169 MB、校验、解压、激活,全程约 75 秒。
- **自动化 CI(M4,2026-11-28 改为每日自动构建)**:[`build-runtime.yml`](../.github/workflows/build-runtime.yml) 每天 03:23 UTC 运行,也可手动触发并指定上游 commit。流程:
1. 取上游默认分支的 HEAD。已有 `runtime-<commit>` 的 Release(alpha 或 stable)就跳过,所以上游不动时不消耗构建时间。
2. 在 `windows-latest` 上用 MSYS2 CLANG64,由 `scripts/apply-patch-series.ps1` 按 `patches/series.txt` 逐个处理补丁:能打上就打;反向检查通过(上游已经包含)就跳过并提醒退役;两者都不行就停止,不改补丁(AGENTS.md 规则 4)。
3. 执行上游 `scripts/install-ctl.sh --yes`,再用 `pack-runtime.ps1 -Channel alpha -Patches <实际打上的补丁>` 打包,manifest 只写实际打上的补丁(规则 5)。
4. `scripts/check-runtime-alpha.ps1` 做 alpha 准入检查(第 6 节),通过后发布为 GitHub 预发布,附件四个缺一不可。
4. `scripts/check-runtime-alpha.ps1` 做 alpha 准入检查(第 6 节),通过后发布为 GitHub 预发布,五个附件缺一不可。
5. 只保留最近 7 个未升级的 alpha 预发布,更早的连同 tag 删除;正式发布不受影响。
6. 构建失败、或有补丁已被上游合并时,在本仓库开一个 issue(已有同名的未关闭 issue 就追加评论)。
@@ -145,7 +154,7 @@ reims-runtime-<commit>/
| 通道 | 来源 | 进入条件 |
| :--- | :--- | :--- |
| `alpha` | CI 每天从上游最新 commit 自动构建并打补丁(2026-11-28 前叫 `candidate`,当时是人工指定 commit) | 由 `scripts/check-runtime-alpha.ps1` 自动检查:能构建;四个附件齐全;`SHA256SUMS.txt` 覆盖三个压缩包且校验一致;manifest 的 commit、通道、补丁与实际一致;在不含 MSYS2 的 PATH 下 `qemu-system-x86_64.exe -device help` 列出 `reims-graphics-pci` |
| `alpha` | CI 每天从上游最新 commit 自动构建并打补丁(2026-11-28 前叫 `candidate`,当时是人工指定 commit) | 由 `scripts/check-runtime-alpha.ps1` 自动检查:能构建;新布局的五个附件齐全;`SHA256SUMS.txt` 覆盖四个压缩包且校验一致;manifest 的 commit、通道、补丁、五个最终可执行文件哈希及符号包一致;视频驱动和许可证文件齐全;在不含 MSYS2 的 PATH 下列出 `reims-graphics-pci`,执行 CLI 版本检查及 qcow2 创建、读取。`-RequireSlim` 用于强制新布局,省略时仍可检查历史包 |
| `stable` | 从 `alpha` 升级 | 在一台真实 Win10 或 Win11 宿主上跑通冒烟测试:`doctor` 的运行时检查全部通过,用 golden 镜像启动到 macOS 桌面,截一张屏,正常关机。由人确认后升级 |
`reims-go` 客户端默认只拉 `stable`,`alpha` 要用户主动打开(界面开关「接收 Alpha 版」,CLI `--alpha`)。旧配置里的 `runtime_channel: "candidate"` 读作 `alpha`,CLI 的 `--candidate` 保留为 `--alpha` 的别名。这层筛选是 `reims-go` 相对于「自己跑上游安装脚本」的主要价值之一。
@@ -173,4 +182,4 @@ reims-runtime-<commit>/
- **内容**:`repo.msys2.org/mingw/sources/` 上原样的 `<base>-<version>.src.tar.zst`,内含 PKGBUILD、上游源码和 MSYS2 的补丁。每个都附 `.sig` 签名文件;打包时用 `gpgv` 和 MSYS2 密钥逐个校验,校验不过就停止。同时附一份 README,列出全部 55 个包的许可证,以及哪些附了源码。
- **`runtime-3731afd` 的结果**:22 个源码包,110 MB,签名全部通过。下载的源码缓存在 `D:\Data\reims-go\releases\msys2-sources-cache`,下次打包会复用。
`reims-go` 外壳用 MIT,前提是它和这些组件只通过独立进程交互,不链接它们。
`reims-go` 外壳用 Apache-2.0,前提是它和这些组件只通过独立进程交互,不链接它们。
+2 -1
View File
@@ -1,7 +1,7 @@
{
"name": "reims-go-frontend",
"private": true,
"version": "0.2.5",
"version": "0.2.6",
"type": "module",
"scripts": {
"dev": "vite",
@@ -11,6 +11,7 @@
"dependencies": {
"@fontsource-variable/inter": "^5.3.0",
"@radix-ui/react-alert-dialog": "^1.2.1",
"@radix-ui/react-context-menu": "^2.4.1",
"@radix-ui/react-dialog": "^1.3.1",
"@radix-ui/react-dropdown-menu": "^2.2.1",
"@radix-ui/react-toast": "^1.3.1",
+1 -1
View File
@@ -1 +1 @@
64168eba4b0b33765a8a7ffa2b52319b
f38f2bbc623190aed99c112f7b10c276
+29
View File
@@ -14,6 +14,9 @@ importers:
'@radix-ui/react-alert-dialog':
specifier: ^1.2.1
version: 1.2.1(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@radix-ui/react-context-menu':
specifier: ^2.4.1
version: 2.4.1(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@radix-ui/react-dialog':
specifier: ^1.3.1
version: 1.3.1(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
@@ -378,6 +381,19 @@ packages:
'@types/react':
optional: true
'@radix-ui/react-context-menu@2.4.1':
resolution: {integrity: sha512-Pddn3Z8lio3/ChxyXaEP3jHTTo1LTHCWwF8+mG1chQlWijP+ttVHBKwezrQTiV6Mj670ojvumqvuGh+mdv33iQ==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-context@1.3.0':
resolution: {integrity: sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==}
peerDependencies:
@@ -1363,6 +1379,19 @@ snapshots:
optionalDependencies:
'@types/react': 19.3.3
'@radix-ui/react-context-menu@2.4.1(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
dependencies:
'@radix-ui/primitive': 1.2.0
'@radix-ui/react-context': 1.3.0(@types/react@19.3.3)(react@19.3.1)
'@radix-ui/react-menu': 2.2.1(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@radix-ui/react-primitive': 2.2.0(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@radix-ui/react-use-controllable-state': 1.3.0(@types/react@19.3.3)(react@19.3.1)
react: 19.3.1
react-dom: 19.3.1(react@19.3.1)
optionalDependencies:
'@types/react': 19.3.3
'@types/react-dom': 19.3.0(@types/react@19.3.3)
'@radix-ui/react-context@1.3.0(@types/react@19.3.3)(react@19.3.1)':
dependencies:
react: 19.3.1
+240 -40
View File
@@ -1,32 +1,44 @@
import { Minus, Moon, Square, Sun, X } from 'lucide-react'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { CreateWizard, WizardDraft } from './components/CreateWizard'
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react'
import type { WizardDraft } from './components/CreateWizard'
import { DeleteDialog } from './components/DeleteDialog'
import { CloneDialog } from './components/CloneDialog'
import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog'
import { SendTextDialog } from './components/SendTextDialog'
import { HostView } from './components/HostView'
import { AppSettingsPage, ThemeMode } from './components/AppSettingsPage'
import type { ThemeMode } from './components/AppSettingsPage'
import { LogPanel, LogTab } from './components/LogPanel'
import { SettingsModal } from './components/SettingsModal'
import { Setup } from './components/Setup'
import { TitleMenus } from './components/TitleMenus'
import { HOST_ID, INSTALLERS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
import { InstallersPage } from './components/InstallersPage'
import { VMAction, VMPage } from './components/VMPage'
import { I18nKey, t } from './i18n'
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
import { LogLine, appendLog } from './lib/logs'
import { currentTask, upsertTask } from './lib/tasks'
import { AppState, CachedInstaller, CreateOpts, Locale, RuntimeSource, Task, VMDetail, VMStats } from './types'
import { macOSMajor } from './lib/macosRelease'
import { currentTask, finishedTaskTTL, pruneFinishedTasks, upsertTask } from './lib/tasks'
import { latestVMStats } from './lib/vmStats'
import { AppState, CachedInstaller, CreateOpts, Locale, RuntimeSource, Task, VMDetail } from './types'
import { Tip, TooltipProvider } from './ui/controls'
import { Toaster, useToasts } from './ui/toast'
import { api, events } from './wails'
import { WindowMinimise, WindowToggleMaximise } from '../wailsjs/runtime/runtime'
import { OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from '../wailsjs/runtime/runtime'
// Opened on demand, so each is its own chunk and stays out of the startup
// bundle: the wizard, VM settings and affinity dialogs, first-run setup, and
// the Engine / Installers / Settings pages.
const CreateWizard = lazy(() => import('./components/CreateWizard').then((m) => ({ default: m.CreateWizard })))
const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) => ({ default: m.SettingsModal })))
const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m) => ({ default: m.AffinityDialog })))
const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup })))
const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView })))
const InstallersPage = lazy(() => import('./components/InstallersPage').then((m) => ({ default: m.InstallersPage })))
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
const errText = (e: unknown) => String(e).replace(/^Error:\s*/, '')
const failKey: Record<VMAction, I18nKey> = {
start: 'failStart',
focus: 'failFocus',
screenshot: 'failScreenshot',
stop: 'failStop',
forceStop: 'failStop',
restart: 'failRestart',
@@ -50,15 +62,18 @@ export const App: React.FC = () => {
const [state, setState] = useState<AppState | null>(null)
const [selected, setSelected] = useState<string>(HOST_ID)
const [detail, setDetail] = useState<VMDetail | null>(null)
const [vmStats, setVmStats] = useState<VMStats | null>(null)
const [detailRevision, setDetailRevision] = useState(0)
const [showWizard, setShowWizard] = useState(false)
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
const [showSettings, setShowSettings] = useState(false)
const [affinityTarget, setAffinityTarget] = useState<string | null>(null)
const [affinityVersion, setAffinityVersion] = useState(0)
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
const [cloneSource, setCloneSource] = useState<string | null>(null)
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
const [busy, setBusy] = useState<Record<string, VMAction>>({})
const [dropping, setDropping] = useState(false)
const [loadError, setLoadError] = useState('')
const [themeMode, setThemeModeState] = useState<ThemeMode>(() => {
try {
@@ -94,6 +109,15 @@ export const App: React.FC = () => {
const toggleTheme = () => setThemeMode(theme === 'light' ? 'dark' : 'light')
// Sidebar can be hidden (Ctrl+B or the title-bar toggle); remembered per user.
const [sidebarOpen, setSidebarOpen] = useState<boolean>(() => {
try { return localStorage.getItem('reims-go-sidebar') !== 'hidden' } catch { return true }
})
const toggleSidebar = () => setSidebarOpen((open) => {
try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch {}
return !open
})
const [logsOpen, setLogsOpen] = useState(false)
const [logTab, setLogTab] = useState<LogTab>('app')
const [logLines, setLogLines] = useState<LogLine[]>([])
@@ -104,12 +128,12 @@ export const App: React.FC = () => {
logsOpenRef.current = logsOpen
const [taskMap, setTaskMap] = useState<Record<string, Task>>({})
const onTaskRef = useRef<(task: Task) => void>(() => {})
const notifiedTasks = useRef(new Set<string>())
const notifiedTasks = useRef(new Map<string, number>())
const [setupStage, setSetupStage] = useState<'folder' | 'runtime' | null>(null)
const toasts = useToasts()
const refresh = useCallback(async () => {
const refresh = useCallback(async (reloadDetail = false) => {
try {
const s = await api.GetState()
setState(s)
@@ -119,6 +143,7 @@ export const App: React.FC = () => {
if ((s.vms ?? []).some((v) => v.name === cur)) return cur
return s.vms && s.vms.length > 0 ? s.vms[0].name : HOST_ID
})
if (reloadDetail) setDetailRevision((revision) => revision + 1)
} catch (e) {
setLoadError(errText(e))
}
@@ -126,7 +151,7 @@ export const App: React.FC = () => {
useEffect(() => {
refresh()
const offState = events.onStateChanged(() => { refresh() })
const offState = events.onStateChanged(() => { refresh(true) })
// Logs never pop the panel open (docs/ui-redesign.md §5.2); errors only bump a badge.
const offLog = events.onLog((entry) => {
setLogLines((prev) => {
@@ -146,6 +171,11 @@ export const App: React.FC = () => {
// Keep host telemetry (memory load, free disk) fresh while the window is visible.
const hostTimer = window.setInterval(() => {
if (!document.hidden) void refresh()
const cutoff = Date.now() - finishedTaskTTL
setTaskMap((prev) => pruneFinishedTasks(prev, cutoff))
for (const [id, updatedAt] of notifiedTasks.current) {
if (updatedAt < cutoff) notifiedTasks.current.delete(id)
}
}, 10000)
return () => { offState(); offLog(); offTask(); window.clearInterval(hostTimer) }
}, [refresh])
@@ -157,21 +187,43 @@ export const App: React.FC = () => {
: undefined
useEffect(() => {
if (!selectedVM) { setDetail(null); setVmStats(null); return }
if (!selectedVM) { setDetail(null); return }
api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
}, [selectedVM?.name, state])
}, [selectedVM?.name, selectedVM?.state, state?.transitions[selectedVM?.name ?? ''], detailRevision])
// Display names (the VM's note, .reims-go-note): shown in place of the VM's
// name in the sidebar and page title; the name itself stays the identifier.
const [displayNames, setDisplayNames] = useState<Record<string, string>>({})
const vmNamesKey = vms.map((v) => v.name).join('|')
useEffect(() => {
if (!selectedVM) { setVmStats(null); return }
let live = true
const vmName = selectedVM.name
const sample = () => {
api.GetVMStats(vmName).then((st) => { if (live) setVmStats(st) }).catch(() => {})
for (const vm of vms) {
api.GetVMNote(vm.name)
.then((n) => { if (live) setDisplayNames((m) => ({ ...m, [vm.name]: (n ?? '').trim() })) })
.catch(() => {})
}
sample()
const timer = window.setInterval(sample, 3000)
return () => { live = false; window.clearInterval(timer) }
}, [selectedVM?.name, selectedVM?.state])
return () => { live = false }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [vmNamesKey])
// Each VM's macOS major version for its icon: the release recorded at
// creation (.reims-go-macos), else a guess from its name or display name.
const [releases, setReleases] = useState<Record<string, string>>({})
useEffect(() => {
let live = true
for (const vm of vms) {
api.GetVMMacOS(vm.name)
.then((r) => { if (live) setReleases((m) => ({ ...m, [vm.name]: (r ?? '').trim() })) })
.catch(() => {})
}
return () => { live = false }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [vmNamesKey])
const macosMajors: Record<string, number | null> = {}
for (const vm of vms) macosMajors[vm.name] = macOSMajor(releases[vm.name], vm.name, displayNames[vm.name])
// Live VM stats are polled by lib/vmStats.ts and read where they are shown
// (VMPage), so a 3-second tick no longer re-renders the whole App.
const locale: Locale = state?.config.locale ?? 'zh-CN'
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
@@ -183,7 +235,7 @@ export const App: React.FC = () => {
// Toast once per finished download; only live events reach here, not the seed list.
const notify = task.kind === 'installer-download' || task.kind === 'recovery-download' || task.kind === 'runtime-install'
if (task.status !== 'running' && notify && !notifiedTasks.current.has(task.id)) {
notifiedTasks.current.add(task.id)
notifiedTasks.current.set(task.id, task.updated_at)
const isRuntime = task.kind === 'runtime-install'
const isRecovery = task.kind === 'recovery-download'
if (task.status === 'done') {
@@ -207,10 +259,10 @@ export const App: React.FC = () => {
api.InstallRuntimeOnline(commit).catch((e) => fail(tr('failRuntime'), e))
}
const setChannel = (alpha: boolean) => {
api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(refresh).catch((e) => fail(tr('failGeneric'), e))
api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(() => refresh()).catch((e) => fail(tr('failGeneric'), e))
}
const setSource = (source: RuntimeSource) => {
api.SetRuntimeSource(source).then(refresh).catch((e) => fail(tr('failGeneric'), e))
api.SetRuntimeSource(source).then(() => refresh()).catch((e) => fail(tr('failGeneric'), e))
}
const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }
const importRuntime = async () => {
@@ -329,12 +381,11 @@ export const App: React.FC = () => {
}
}
const onVMAction = (action: VMAction) => {
if (!selectedVM) return
const name = selectedVM.name
const isRunning = selectedVM.state === 'running'
const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => {
switch (action) {
case 'start': return runVMAction(name, action, () => api.StartVM(name))
case 'focus': return api.FocusVMWindow(name).catch((e) => fail(tr('failFocus'), e))
case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshot(name), tr('toastScreenshotCopied'))
case 'stop': return runVMAction(name, action, () => api.StopVM(name, false), tr('toastStopped', { name }))
case 'forceStop': return runVMAction(name, action, () => api.StopVM(name, true), tr('toastStopped', { name }))
case 'restart': return runVMAction(name, action, () => api.RestartVM(name))
@@ -360,6 +411,32 @@ export const App: React.FC = () => {
}
}
const onVMAction = (action: VMAction) => {
if (!selectedVM) return
return onVMActionFor(selectedVM.name, action, selectedVM.state === 'running')
}
const onSidebarContextAction = (name: string, action: VMAction | 'settings') => {
if (action === 'settings') {
setSelected(name)
api.GetVMDetail(name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
return
}
const vm = vms.find((v) => v.name === name)
const st = state?.transitions[name] ?? vm?.state ?? 'stopped'
onVMActionFor(name, action, st === 'running')
}
// The state's own main action (Start, or Show Window while running), shared by
// Ctrl+Enter and a double-click in the sidebar.
const primaryAction = (name: string) => {
const vm = vms.find((v) => v.name === name)
if (!vm || busy[name]) return
const st = state?.transitions[name] ?? vm.state
if (st === 'stopped') onVMActionFor(name, 'start', false)
else if (st === 'running') onVMActionFor(name, 'focus', true)
}
const confirmDelete = (keepFiles: boolean) => {
const name = deleteTarget
setDeleteTarget(null)
@@ -479,11 +556,13 @@ export const App: React.FC = () => {
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
shortcutRef.current = (e: KeyboardEvent) => {
if (!e.ctrlKey || e.altKey || e.metaKey) return
if (showWizard || showSettings || deleteTarget || sendTextTarget) return
if (showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget) return
const k = e.key.toLowerCase()
if (k === 'n') { e.preventDefault(); openWizard() }
else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) }
else if (k === 'l') { e.preventDefault(); toggleLogs() }
else if (k === 'b' && !showSetup) { e.preventDefault(); toggleSidebar() }
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(selectedVM.name) }
}
useEffect(() => {
const h = (e: KeyboardEvent) => shortcutRef.current(e)
@@ -491,14 +570,85 @@ export const App: React.FC = () => {
return () => window.removeEventListener('keydown', h)
}, [])
// Tray menu: "Show in Reims-Go" selects that VM; "New VM…" opens the wizard.
// The backend has already brought the window to the front.
const openWizardRef = useRef(openWizard)
openWizardRef.current = openWizard
useEffect(() => {
const offSelect = events.onTraySelectVM((name) => { setSelected(name) })
const offNew = events.onTrayNewVM(() => { openWizardRef.current() })
return () => { offSelect(); offNew() }
}, [])
// Native Wails file drag-and-drop delivery into the selected VM's shared folder.
const dropTargetRef = useRef<{ name: string; ready: boolean }>({ name: '', ready: false })
dropTargetRef.current = {
name: selectedVM?.name ?? '',
ready: !!selectedVM && !!detail && !detail.has_installer && !detail.recovery_mode,
}
useEffect(() => {
let depth = 0
const onEnter = (e: DragEvent) => {
if (!dropTargetRef.current.ready) return
if (e.dataTransfer?.types?.includes('Files')) { depth++; setDropping(true) }
}
const onLeave = () => {
depth = Math.max(0, depth - 1)
if (depth === 0) setDropping(false)
}
const onDropEnd = () => { depth = 0; setDropping(false) }
window.addEventListener('dragenter', onEnter)
window.addEventListener('dragleave', onLeave)
window.addEventListener('drop', onDropEnd)
OnFileDrop((_x, _y, paths) => {
depth = 0
setDropping(false)
const cur = dropTargetRef.current
if (!cur.ready || !cur.name || !paths || paths.length === 0) return
api.DeliverPathsToGuest(cur.name, paths)
.then((delivered) => {
if (!delivered || delivered.length === 0) return
if (delivered.length === 1) toasts.push({ kind: 'ok', title: tr('toastFileDelivered', { name: delivered[0] }) })
else toasts.push({ kind: 'ok', title: tr('toastFilesDelivered', { n: delivered.length }) })
})
.catch((e) => fail(tr('failGuestTools'), e))
}, true)
return () => {
window.removeEventListener('dragenter', onEnter)
window.removeEventListener('dragleave', onLeave)
window.removeEventListener('drop', onDropEnd)
OnFileDropOff()
}
}, [])
return (
<TooltipProvider>
<div className="app-shell">
<header className="titlebar" onDoubleClick={() => WindowToggleMaximise()}>
<div className="brand">
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
Reims-Go
</div>
{showSetup || !state ? (
<div className="brand">
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
Reims-Go
</div>
) : (
<TitleMenus
locale={locale}
sidebarOpen={sidebarOpen}
onToggleSidebar={toggleSidebar}
logsOpen={logsOpen}
onToggleLogs={toggleLogs}
themeMode={themeMode}
onThemeMode={setThemeMode}
vm={selectedVM ? { name: selectedVM.name, state: effectiveState, busy: !!busy[selectedVM.name] } : null}
onNewVM={openWizard}
onVMAction={onVMAction}
onVMSettings={() => { if (detail) setShowSettings(true) }}
onVMDelete={() => { if (selectedVM) setDeleteTarget(selectedVM.name) }}
onNavigate={setSelected}
onOpenURL={(url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) }}
appVersion={state.app_version}
/>
)}
<div className="titlebar-right" onDoubleClick={(e) => e.stopPropagation()}>
<Tip label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}>
<button
@@ -519,6 +669,7 @@ export const App: React.FC = () => {
</header>
{showSetup && state ? (
<Suspense fallback={null}>
<Setup
locale={locale}
state={state}
@@ -534,8 +685,9 @@ export const App: React.FC = () => {
onCancelTask={cancelTask}
onImportRuntime={importRuntime}
/>
</Suspense>
) : (
<div className="workspace">
<div className={`workspace${sidebarOpen ? '' : ' sidebar-hidden'}`}>
<Sidebar
locale={locale}
vms={vms}
@@ -543,12 +695,17 @@ export const App: React.FC = () => {
selected={selected}
hostReady={hostReady}
onSelect={setSelected}
displayNames={displayNames}
macosMajors={macosMajors}
onActivate={primaryAction}
onNew={openWizard}
onVMContextAction={onSidebarContextAction}
downloading={Object.values(taskMap).some((x) => x.kind === 'installer-download' && x.status === 'running')}
/>
<main className="main">
<div className="scroll">
<Suspense fallback={null}>
{!state ? (
<div className="page">
{loadError ? <div className="notice notice-error">{loadError}</div> : <span className="muted">…</span>}
@@ -566,14 +723,17 @@ export const App: React.FC = () => {
<VMPage
locale={locale}
name={selectedVM.name}
displayName={displayNames[selectedVM.name] ?? ''}
onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))}
macosMajor={macosMajors[selectedVM.name] ?? null}
state={effectiveState}
detail={detail}
stats={vmStats}
host={state.host}
pending={pending}
busyAction={busy[selectedVM.name]}
onAction={onVMAction}
onSettings={() => setShowSettings(true)}
onOpenAffinity={() => setAffinityTarget(selectedVM.name)}
onDelete={() => setDeleteTarget(selectedVM.name)}
onViewLogs={() => { openLogs('serial'); loadSerial() }}
onCopy={copy}
@@ -601,6 +761,9 @@ export const App: React.FC = () => {
})
.catch((e) => fail(tr('failGuestTools'), e))
}}
onToast={(title) => toasts.push({ kind: 'ok', title })}
onError={fail}
dropping={dropping}
/>
) : selected === SETTINGS_ID ? (
<AppSettingsPage
@@ -617,6 +780,7 @@ export const App: React.FC = () => {
state={state}
locale={locale}
onRefresh={refresh}
onNewVM={openWizard}
onError={fail}
runtimeTask={runtimeTask}
onChannel={setChannel}
@@ -625,6 +789,7 @@ export const App: React.FC = () => {
onCancelTask={cancelTask}
/>
)}
</Suspense>
</div>
</main>
</div>
@@ -650,10 +815,14 @@ export const App: React.FC = () => {
onCancelTask={cancelTask}
host={state?.host}
runningVMs={runningVMCount}
onCopy={copy}
hostReady={hostReady}
onOpenHost={() => setSelected(HOST_ID)}
/>
)}
{showWizard && state && (
<Suspense fallback={null}>
<CreateWizard
locale={locale}
host={state.host}
@@ -661,18 +830,22 @@ export const App: React.FC = () => {
onClose={() => { setShowWizard(false); setWizardDraft(null) }}
onSubmit={submitCreate}
/>
</Suspense>
)}
{showSettings && state && detail && (
<Suspense fallback={null}>
<SettingsModal
locale={locale}
detail={detail}
stats={vmStats}
stats={latestVMStats(detail.name)}
host={state.host}
optimizations={state.optimizations}
running={effectiveState === 'running'}
onCopy={copy}
onDiskChanged={refresh}
onOpenAffinity={() => setAffinityTarget(detail.name)}
affinityVersion={affinityVersion}
onClose={() => setShowSettings(false)}
onSaved={() => {
setShowSettings(false)
@@ -680,6 +853,33 @@ export const App: React.FC = () => {
refresh()
}}
/>
</Suspense>
)}
{affinityTarget && state && (
<Suspense fallback={null}>
<AffinityDialog
locale={locale}
vmName={affinityTarget}
vcpus={detail?.name === affinityTarget ? detail.cpus : 4}
host={state.host}
globalAutoPin={state.config.auto_pin_pcores}
onClose={() => setAffinityTarget(null)}
onApplied={(st) => {
setAffinityTarget(null)
setAffinityVersion((v) => v + 1)
const count = st.effective_cpus?.length ?? 0
const mask = st.live_mask_hex || st.effective_mask_hex || '0x0'
toasts.push({
kind: 'ok',
title: st.running
? tr('toastAffinityApplied', { count, mask })
: tr('toastAffinitySaved'),
})
refresh()
}}
/>
</Suspense>
)}
{deleteTarget && (
@@ -709,7 +909,7 @@ export const App: React.FC = () => {
<SendTextDialog
locale={locale}
vmName={sendTextTarget}
guestToolsConnected={Boolean(vmStats?.guest_tools_connected ?? detail?.guest_tools_connected)}
guestToolsConnected={Boolean(latestVMStats(sendTextTarget)?.guest_tools_connected ?? detail?.guest_tools_connected)}
onCancel={() => setSendTextTarget(null)}
onConfirm={(text) => {
const target = sendTextTarget
+379
View File
@@ -0,0 +1,379 @@
import { AlertTriangle, Check, Cpu } from 'lucide-react'
import React, { useEffect, useMemo, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { HostReport, Locale, LogicalCPUInfo, VMAffinityMode, VMAffinityStatus } from '../types'
import { Button } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { Segmented, Switch } from '../ui/settings'
import { api } from '../wails'
interface Props {
locale: Locale
vmName: string
vcpus: number
host: HostReport
globalAutoPin: boolean
onClose: () => void
onApplied: (status: VMAffinityStatus) => void
}
function buildTopology(host: HostReport): LogicalCPUInfo[] {
if (host.cpu_topology && host.cpu_topology.length > 0) {
return host.cpu_topology
}
const n = Math.min(Math.max(host.logical_cpus || 1, 1), 64)
return Array.from({ length: n }, (_, i) => ({
index: i,
core_index: i,
tier: 'standard',
smt: false,
}))
}
function maskHexFromCPUs(cpus: number[]): string {
let mask = 0n
for (const idx of cpus) {
if (idx >= 0 && idx < 64) {
mask |= 1n << BigInt(idx)
}
}
return '0x' + mask.toString(16).toUpperCase()
}
function resolveAutoPreview(topology: LogicalCPUInfo[], host: HostReport, globalAutoPin: boolean, vcpus: number): number[] {
const all = topology.map((c) => c.index)
if (!globalAutoPin || !host.has_hybrid_cores) return all
const pCPUs = topology.filter((c) => c.tier === 'p').map((c) => c.index)
if (pCPUs.length >= vcpus + 1 && pCPUs.length > 0) return pCPUs
if ((host.lpe_core_count ?? 0) > 0) {
const nonLPE = topology.filter((c) => c.tier !== 'lpe').map((c) => c.index)
if (nonLPE.length >= vcpus + 1 && nonLPE.length > 0) return nonLPE
}
return all
}
export function formatAffinitySummary(locale: Locale, status: VMAffinityStatus | null): string {
if (!status) return '—'
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const count = status.effective_cpus?.length ?? 0
const mask = status.effective_mask_hex || '0x0'
switch (status.mode) {
case 'all':
return tr('affinitySummaryAll', { count })
case 'pcores':
return tr('affinitySummaryPCores', { count, mask })
case 'non_lpe':
return tr('affinitySummaryNonLPE', { count, mask })
case 'custom':
return tr('affinitySummaryCustom', { count, mask })
default: {
const effLabel = status.effective_mode === 'pcores'
? tr('affinityModePCores')
: status.effective_mode === 'non_lpe'
? tr('affinityModeNonLPE')
: tr('affinityModeAll')
return tr('affinitySummaryAuto', { eff: effLabel, count })
}
}
}
export const AffinityDialog: React.FC<Props> = ({
locale, vmName, vcpus, host, globalAutoPin, onClose, onApplied,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const topology = useMemo(() => buildTopology(host), [host])
const allIndices = useMemo(() => topology.map((c) => c.index), [topology])
const hasSMT = useMemo(() => topology.some((c) => c.smt), [topology])
const [status, setStatus] = useState<VMAffinityStatus | null>(null)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [err, setErr] = useState('')
const [mode, setMode] = useState<VMAffinityMode>('auto')
const [selected, setSelected] = useState<number[]>(allIndices)
const [disableEcoQoS, setDisableEcoQoS] = useState(true)
useEffect(() => {
let live = true
setLoading(true)
setErr('')
api.GetVMAffinity(vmName)
.then((st) => {
if (!live) return
setStatus(st)
setMode(st.mode || 'auto')
const initial = st.mode === 'custom' && st.cpus?.length > 0
? st.cpus
: (st.effective_cpus?.length > 0 ? st.effective_cpus : allIndices)
setSelected([...initial].sort((a, b) => a - b))
setDisableEcoQoS(st.disable_eco_qos)
})
.catch((e) => {
if (live) setErr(String(e).replace(/^Error:\s*/, ''))
})
.finally(() => {
if (live) setLoading(false)
})
return () => { live = false }
}, [vmName, allIndices])
const selectedSet = useMemo(() => new Set(selected), [selected])
const effectiveVCPUs = status?.vcpus || vcpus
const maskHex = useMemo(() => maskHexFromCPUs(selected), [selected])
const applyPreset = (nextMode: VMAffinityMode) => {
setMode(nextMode)
setErr('')
switch (nextMode) {
case 'all':
setSelected(allIndices)
break
case 'pcores': {
const list = topology.filter((c) => c.tier === 'p').map((c) => c.index)
setSelected(list.length > 0 ? list : allIndices)
break
}
case 'non_lpe': {
const list = topology.filter((c) => c.tier !== 'lpe').map((c) => c.index)
setSelected(list.length > 0 ? list : allIndices)
break
}
case 'auto':
setSelected(resolveAutoPreview(topology, host, globalAutoPin, effectiveVCPUs))
break
case 'custom':
break
}
}
const toggleCPU = (idx: number) => {
setMode('custom')
setErr('')
setSelected((prev) => {
const s = new Set(prev)
if (s.has(idx)) s.delete(idx)
else s.add(idx)
return Array.from(s).sort((a, b) => a - b)
})
}
const pickCustomList = (list: number[]) => {
setMode('custom')
setErr('')
setSelected([...new Set(list)].sort((a, b) => a - b))
}
const physicalOnlyList = useMemo(() => {
const seen = new Set<number>()
const out: number[] = []
for (const c of topology) {
if (!seen.has(c.core_index)) {
seen.add(c.core_index)
out.push(c.index)
}
}
return out
}, [topology])
const modeOptions: { value: VMAffinityMode; label: string }[] = [
{ value: 'auto', label: tr('affinityModeAuto') },
{ value: 'all', label: tr('affinityModeAll') },
...(host.has_hybrid_cores ? [{ value: 'pcores' as const, label: tr('affinityModePCores') }] : []),
...((host.lpe_core_count ?? 0) > 0 ? [{ value: 'non_lpe' as const, label: tr('affinityModeNonLPE') }] : []),
{ value: 'custom', label: tr('affinityModeCustom') },
]
const modeHintKey: Record<VMAffinityMode, I18nKey> = {
auto: 'affinityModeAutoHint',
all: 'affinityModeAllHint',
pcores: 'affinityModePCoresHint',
non_lpe: 'affinityModeNonLPEHint',
custom: 'affinityModeCustomHint',
}
const emptyCustom = mode === 'custom' && selected.length === 0
const oversubscribed = effectiveVCPUs > 0 && selected.length > 0 && selected.length < effectiveVCPUs
const allSelected = selected.length === allIndices.length && allIndices.length > 0
const handleSave = async () => {
if (emptyCustom) {
setErr(tr('affinityNeedOne'))
return
}
setSaving(true)
setErr('')
try {
const updated = await api.SetVMAffinity(vmName, {
mode,
cpus: mode === 'custom' ? selected : [],
disable_eco_qos: disableEcoQoS,
})
onApplied(updated)
} catch (e) {
setErr(String(e).replace(/^Error:\s*/, ''))
} finally {
setSaving(false)
}
}
const subtitle = status?.running && status.pid
? tr('affinitySubtitleRunning', { pid: status.pid, vcpus: effectiveVCPUs })
: tr('affinitySubtitleStopped', { vcpus: effectiveVCPUs })
const tierLabel = (tier: string) => {
if (tier === 'p') return 'P'
if (tier === 'e') return 'E'
if (tier === 'lpe') return 'LP-E'
return ''
}
return (
<Modal
title={`${tr('affinityTitle')} — ${vmName}`}
subtitle={subtitle}
closeLabel={tr('close')}
dismissable={!saving}
onClose={onClose}
className="affinity-dialog"
>
<div className="dialog-body affinity-body">
<div className="affinity-mode-bar">
<Segmented
label={tr('affinityTitle')}
value={mode}
onChange={(m) => applyPreset(m as VMAffinityMode)}
options={modeOptions}
/>
<p className="affinity-hint">{tr(modeHintKey[mode])}</p>
</div>
<div className="affinity-quick-bar">
<button
type="button"
className={`affinity-chip${allSelected ? ' is-active' : ''}`}
disabled={loading || saving}
onClick={() => pickCustomList(allSelected ? [allIndices[0]] : allIndices)}
>
{tr('affinitySelectAll')}
</button>
{hasSMT && (
<button
type="button"
className="affinity-chip"
disabled={loading || saving}
onClick={() => pickCustomList(physicalOnlyList)}
>
{tr('affinityPhysicalOnly')}
</button>
)}
{allIndices.length > 1 && (
<button
type="button"
className="affinity-chip"
disabled={loading || saving}
onClick={() => pickCustomList(allIndices.filter((i) => i !== 0))}
>
{tr('affinityExcludeCPU0')}
</button>
)}
{host.has_hybrid_cores && (
<button
type="button"
className="affinity-chip"
disabled={loading || saving}
onClick={() => pickCustomList(topology.filter((c) => c.tier === 'p').map((c) => c.index))}
>
{tr('affinityOnlyPCores')}
</button>
)}
{(host.lpe_core_count ?? 0) > 0 && (
<button
type="button"
className="affinity-chip"
disabled={loading || saving}
onClick={() => pickCustomList(topology.filter((c) => c.tier !== 'lpe').map((c) => c.index))}
>
{tr('affinityAvoidLPE')}
</button>
)}
</div>
<div className="affinity-grid" role="group" aria-label={tr('affinityTitle')}>
{topology.map((cpu) => {
const checked = selectedSet.has(cpu.index)
const tLabel = tierLabel(cpu.tier)
return (
<button
key={cpu.index}
type="button"
role="checkbox"
aria-checked={checked}
disabled={loading || saving}
className={`affinity-cpu${checked ? ' is-checked' : ''}${cpu.tier === 'lpe' ? ' is-lpe' : ''}`}
onClick={() => toggleCPU(cpu.index)}
>
<span className="affinity-check" aria-hidden="true">
{checked && <Check size={12} strokeWidth={3} />}
</span>
<span className="affinity-cpu-name tnum">CPU {cpu.index}</span>
<span className="affinity-cpu-meta">
{cpu.smt && <span className="affinity-core-tag tnum">C{cpu.core_index}</span>}
{tLabel && <span className={`affinity-tier tier-${cpu.tier}`}>{tLabel}</span>}
</span>
</button>
)
})}
</div>
<div className="affinity-summary">
<span className="mono tnum">
<Cpu size={13} aria-hidden="true" />{' '}
{tr('affinitySelectedSummary', { selected: selected.length, total: topology.length, mask: maskHex })}
</span>
{status?.running && status.live_mask_hex && (
<span className="affinity-live mono tnum">
{tr('affinityLiveMask', { mask: status.live_mask_hex, count: status.live_cpus?.length ?? 0 })}
</span>
)}
</div>
{oversubscribed && (
<div className="notice" role="status">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('affinityOversubWarn', { selected: selected.length, vcpus: effectiveVCPUs })}</span>
</span>
</div>
)}
<div className="affinity-eco-row">
<div className="row-main">
<div className="row-title">{tr('affinityEcoQoS')}</div>
<div className="row-sub">{tr('affinityEcoQoSDesc')}</div>
</div>
<Switch
label={tr('affinityEcoQoS')}
checked={disableEcoQoS}
disabled={loading || saving}
onChange={setDisableEcoQoS}
/>
</div>
{err && <div className="notice notice-error" role="alert">{err}</div>}
</div>
<div className="dialog-foot">
<Button onClick={onClose} disabled={saving}>{tr('cancel')}</Button>
<Button
variant="primary"
busy={saving}
disabled={loading || emptyCustom}
onClick={() => void handleSave()}
>
{status?.running ? tr('affinityApplyNow') : tr('affinitySave')}
</Button>
</div>
</Modal>
)
}
+58 -4
View File
@@ -1,8 +1,9 @@
import { Cpu, HardDrive, MemoryStick, RefreshCw, ShieldCheck } from 'lucide-react'
import React, { useState } from 'react'
import { Cpu, HardDrive, MemoryStick, Plus, RefreshCw, ShieldCheck } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { formatBytes } from '../lib/format'
import { findOptimization, kernelIrqchipHint, optBadgeClass, optStatusLabel } from '../lib/optimizations'
import { AppState, Locale, RuntimeSource, Task } from '../types'
import { AppState, Locale, RuntimeSource, StorageBreakdown, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { api } from '../wails'
import { RuntimeOnline } from './RuntimeOnline'
@@ -11,6 +12,7 @@ interface Props {
state: AppState
locale: Locale
onRefresh: () => void
onNewVM?: () => void
onError: (title: string, e: unknown) => void
runtimeTask: Task | null
onChannel: (alpha: boolean) => void
@@ -19,12 +21,19 @@ interface Props {
onCancelTask: (id: string) => void
}
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask }) => {
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, onError, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask }) => {
const [importing, setImporting] = useState(false)
const [enabling, setEnabling] = useState(false)
const [openingSched, setOpeningSched] = useState(false)
const [storage, setStorage] = useState<StorageBreakdown | null>(null)
const { host, config, runtimes, optimizations } = state
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
useEffect(() => {
let live = true
api.GetStorageBreakdown().then((s) => { if (live) setStorage(s) }).catch(() => {})
return () => { live = false }
}, [state.config.data_root, state.vms?.length, state.runtimes?.length])
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
const rebootOpt = findOptimization(optimizations, 'cold_reboot')
const gpuOpt = findOptimization(optimizations, 'discrete_gpu')
@@ -82,6 +91,16 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, r
</div>
</header>
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && !!state.active_runtime && onNewVM && (
<section className="welcome-card">
<h1>{tr('welcomeTitle')}</h1>
<p>{tr('welcomeSub')}</p>
<Button variant="primary" icon={<Plus size={14} aria-hidden="true" />} onClick={onNewVM}>
{tr('newVM')}
</Button>
</section>
)}
<div className="tiles">
<div className="tile">
<div className="tile-head">
@@ -122,6 +141,41 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, r
</div>
</div>
{storage && storage.total_bytes > 0 && (() => {
const tot = Math.max(storage.total_bytes, 1)
const vmsPct = (storage.vms_bytes / tot) * 100
const instPct = (storage.installers_bytes / tot) * 100
const rtPct = (storage.runtimes_bytes / tot) * 100
return (
<section className="card">
<div className="card-title">
<span>{tr('storageBreakdownTitle')}</span>
<span className="spacer" />
<span className="muted tnum" style={{ fontSize: 12, fontWeight: 500 }}>{formatBytes(storage.total_bytes)}</span>
</div>
<div className="storage-bar" aria-hidden="true">
{vmsPct > 0 && <div className="storage-seg-vms" style={{ width: `${vmsPct}%` }} />}
{instPct > 0 && <div className="storage-seg-inst" style={{ width: `${instPct}%` }} />}
{rtPct > 0 && <div className="storage-seg-rt" style={{ width: `${rtPct}%` }} />}
</div>
<div className="storage-legend">
<span className="storage-legend-item">
<span className="storage-dot storage-seg-vms" aria-hidden="true" />
{tr('storageVMs')} · {formatBytes(storage.vms_bytes)}
</span>
<span className="storage-legend-item">
<span className="storage-dot storage-seg-inst" aria-hidden="true" />
{tr('storageInstallers')} · {formatBytes(storage.installers_bytes)}
</span>
<span className="storage-legend-item">
<span className="storage-dot storage-seg-rt" aria-hidden="true" />
{tr('storageRuntimes')} · {formatBytes(storage.runtimes_bytes)}
</span>
</div>
</section>
)
})()}
<section className="section">
<div className="section-title">
{tr('hostRuntime')}
+162 -85
View File
@@ -1,10 +1,12 @@
import { AlertTriangle, Download, LoaderCircle, Package, Pause, Plus, RefreshCw, Trash } from 'lucide-react'
import { AlertTriangle, Check, ChevronDown, Download, LoaderCircle, Pause, Plus, RefreshCw, Trash } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { macOSMajor } from '../lib/macosRelease'
import { taskDetail } from '../lib/tasks'
import { CachedInstaller, HostReport, Locale, Release, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { api } from '../wails'
import { VersionArt } from './VersionArt'
interface Props {
locale: Locale
@@ -21,6 +23,23 @@ const gb = (b: number) => (b >= 1e9 ? `${(b / 1e9).toFixed(1)} GB` : `${Math.max
// 18.4 GB release, measured 2026-11-28): reserve 10% over the release size.
const needBytes = (r: Release) => r.size * 1.1
type ReleaseGroup = { key: string; title: string; major: number | null; releases: Release[] }
/** Newest point release first, one card per macOS major version. */
function groupReleases(releases: Release[]): ReleaseGroup[] {
const groups = new Map<string, ReleaseGroup>()
for (const release of releases) {
const major = macOSMajor(release.version, release.title)
const key = major === null ? release.title : String(major)
const group = groups.get(key) ?? { key, title: release.title, major, releases: [] }
group.releases.push(release)
groups.set(key, group)
}
return [...groups.values()]
.map((group) => ({ ...group, releases: group.releases.sort((a, b) => b.version.localeCompare(a.version, undefined, { numeric: true })) }))
.sort((a, b) => (b.major ?? -1) - (a.major ?? -1) || a.title.localeCompare(b.title))
}
/** Offline installers (roadmap M2.2): what is downloaded, and Apple's releases to download. */
export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateWithInstaller, onError, onToast }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
@@ -45,7 +64,8 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
// Refresh the downloaded list whenever a download starts or ends.
useEffect(() => { loadCached() }, [finishedCount, downloads.length])
const isDownloaded = (v: string) => (cached ?? []).some((c) => c.kind === 'offline' && !c.partial && c.version === v)
const downloaded = (version: string) => (cached ?? []).find((c) => c.kind === 'offline' && !c.partial && c.version === version)
const partial = (version: string) => (cached ?? []).some((c) => c.kind === 'offline' && c.partial && c.version === version)
const download = (version: string) => {
api.DownloadInstaller(version).catch((e) => onError(tr('failDownload'), e))
@@ -89,67 +109,105 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
</div>
)
const spaceShort = (r: Release) => !downloaded(r.version) && !running(r.version) && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
const releaseAction = (r: Release) => {
const task = running(r.version)
if (task) return <IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
const item = downloaded(r.version)
if (item) {
return (
<Button variant="primary" icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(item)}>
{tr('installersCreateVM')}
</Button>
)
}
return (
<Button icon={<Download size={14} />} disabled={spaceShort(r)} onClick={() => download(r.version)}>
{partial(r.version) ? tr('installersResume') : tr('installersDownload')}
</Button>
)
}
const releaseMeta = (r: Release) => (
<div className="row-sub">
{r.posted} · {gb(r.size)}
{spaceShort(r) && <span className="warn-text"> · {tr('installersNoSpace', { need: Math.ceil(needBytes(r) / 1e9), free: host.free_disk_gb.toFixed(0) })}</span>}
</div>
)
const groups = groupReleases(releases ?? [])
const showDownloaded = cached === null || cached.length > 0 || downloads.length > 0
return (
<div className="page">
<div className="page installers-page">
<header className="page-head">
<div className="page-title"><h1>{tr('installersTitle')}</h1></div>
<div className="page-title installers-page-title">
<h1>{tr('installersTitle')}</h1>
<span>{tr('installersHint')}</span>
</div>
<div className="actions">
<IconButton label={tr('refresh')} icon={<RefreshCw size={16} />} onClick={() => { loadCached(); loadReleases() }} />
</div>
</header>
<section className="section">
<div className="section-title">{tr('installersDownloaded')}</div>
{cached === null ? (
skeleton(2, tr('installersDownloaded'))
) : cached.length === 0 ? (
<div className="empty-panel">
<Package size={22} aria-hidden="true" />
<span>{tr('installersEmpty')}</span>
{showDownloaded && (
<section className="section">
<div className="section-title">
<span>{tr('installersDownloaded')}</span>
{cached && cached.length > 0 && <span className="section-count">{cached.length}</span>}
</div>
) : (
<div className="list">
{cached.map((c) => {
const task = c.version ? running(c.version) : undefined
return (
<div className="row" key={c.name}>
<div className="row-main">
<div className="row-title">
{c.title ?? c.name} {c.version}
{c.build && <span className="muted">({c.build})</span>}
{c.kind === 'offline' && !c.partial && <span className="badge badge-ok">{tr('installersKindOffline')}</span>}
{c.kind === 'online' && !c.partial && <span className="badge">{tr('installersKindOnline')}</span>}
{c.partial && !task && <span className="badge badge-warn">{tr('installersPartial')}</span>}
</div>
{task ? progress(task) : <div className="row-sub mono">{c.name} · {gb(c.bytes)}</div>}
</div>
<div className="row-right">
{task ? (
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
) : (
<>
{!c.partial && (c.kind === 'offline' || c.kind === 'online') && (
<Button variant={c.kind === 'offline' ? 'primary' : 'secondary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
{tr('installersCreateVM')}
</Button>
{cached === null || (cached.length === 0 && downloads.length > 0) ? (
skeleton(1, tr('installersDownloaded'))
) : (
<div className="list installer-list">
{cached.map((c) => {
const task = c.version ? running(c.version) : undefined
const title = c.title ?? c.name
return (
<div className="row installer-row" key={c.name} title={c.name}>
<span className="installer-art">
<VersionArt shape="tile" major={macOSMajor(c.version, title)} name={title} />
</span>
<div className="row-main">
<div className="row-title">
<span>{title} {c.version}</span>
{c.kind === 'offline' && !c.partial && <span className="badge badge-ok">{tr('installersKindOffline')}</span>}
{c.kind === 'online' && !c.partial && <span className="badge">{tr('installersKindOnline')}</span>}
{c.partial && !task && <span className="badge badge-warn">{tr('installersPartial')}</span>}
</div>
{task ? progress(task) : (
<div className="row-sub">{gb(c.bytes)}{c.build ? ` · ${c.build}` : ''}</div>
)}
{c.partial && c.kind === 'offline' && c.version && (
<Button icon={<Download size={14} />} onClick={() => download(c.version!)}>{tr('installersResume')}</Button>
)}
{confirmDelete === c.name ? (
<Button variant="danger" onClick={() => remove(c.name)}>{tr('installersDeleteConfirm')}</Button>
</div>
<div className="row-right">
{task ? (
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
) : (
<IconButton label={tr('installersDelete')} icon={<Trash size={15} />} onClick={() => remove(c.name)} />
<>
{!c.partial && (c.kind === 'offline' || c.kind === 'online') && (
<Button variant={c.kind === 'offline' ? 'primary' : 'secondary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
{tr('installersCreateVM')}
</Button>
)}
{c.partial && c.kind === 'offline' && c.version && (
<Button icon={<Download size={14} />} onClick={() => download(c.version!)}>{tr('installersResume')}</Button>
)}
{confirmDelete === c.name ? (
<Button variant="danger" onClick={() => remove(c.name)}>{tr('installersDeleteConfirm')}</Button>
) : (
<IconButton label={tr('installersDelete')} icon={<Trash size={15} />} onClick={() => remove(c.name)} />
)}
</>
)}
</>
)}
</div>
</div>
)
})}
</div>
)}
</section>
</div>
</div>
)
})}
</div>
)}
</section>
)}
<section className="section">
<div className="section-title">{tr('installersAvailable')}</div>
@@ -159,48 +217,67 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('offlineListFailed')}:{releasesErr}</span>
</span>
<Button onClick={loadReleases}>{tr('installersRetry')}</Button>
</div>
) : releases === null ? (
<>
{skeleton(3, tr('offlineLoading'))}
{skeleton(2, tr('offlineLoading'))}
<span className="hint">{tr('offlineLoading')}</span>
</>
) : (
<div className="list">
{releases.map((r) => {
const task = running(r.version)
const done = isDownloaded(r.version)
const short = !done && !task && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
return (
<div className="row" key={r.product}>
<div className="row-main">
<div className="row-title">
{r.title} {r.version}
<span className="muted">({r.build})</span>
</div>
{task ? progress(task) : (
<div className="row-sub">
{r.posted} · {gb(r.size)}
{short && <span className="warn-text"> · {tr('installersNoSpace', { need: Math.ceil(needBytes(r) / 1e9), free: host.free_disk_gb.toFixed(0) })}</span>}
<div className="release-list">
{groups.map((group, groupIndex) => {
const [latest, ...older] = group.releases
const task = running(latest.version)
return (
<article className="release-card" key={group.key}>
<div className="release-latest">
<span className="release-art">
<VersionArt shape="tile" major={group.major} name={group.title} />
</span>
<div className="release-copy">
<div className="row-title release-title">
<span>{latest.title}</span>
<strong>{latest.version}</strong>
{groupIndex === 0 && <span className="badge badge-accent">{tr('installersLatest')}</span>}
{downloaded(latest.version) && <Check size={15} className="ok-text" aria-label={tr('offlineCached')} />}
</div>
{task ? progress(task) : releaseMeta(latest)}
</div>
<div className="row-right">{releaseAction(latest)}</div>
</div>
{older.length > 0 && (
<details className="release-history">
<summary>
<span>{tr('installersOlder', { count: older.length })}</span>
<ChevronDown size={14} aria-hidden="true" />
</summary>
<div className="release-history-list">
{older.map((r) => {
const oldTask = running(r.version)
return (
<div className="release-history-row" key={r.product}>
<div className="row-main">
<div className="row-title">
<span>{r.version}</span>
<span className="muted">{r.build}</span>
{downloaded(r.version) && <span className="badge badge-ok">{tr('offlineCached')}</span>}
</div>
{oldTask ? progress(oldTask) : releaseMeta(r)}
</div>
<div className="row-right">{releaseAction(r)}</div>
</div>
)
})}
</div>
</details>
)}
</div>
<div className="row-right">
{task ? (
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
) : done ? (
<span className="badge badge-ok">{tr('offlineCached')}</span>
) : (
<Button icon={<Download size={14} />} disabled={short} onClick={() => download(r.version)}>{tr('installersDownload')}</Button>
)}
</div>
</div>
)
})}
</div>
</article>
)
})}
</div>
)}
<span className="hint">{tr('installersHint')}</span>
</section>
</div>
)
}
}
+114 -45
View File
@@ -1,5 +1,5 @@
import { ArrowDown, ChevronDown, ChevronUp, Eraser, HardDrive, LoaderCircle, MemoryStick, Pause, RefreshCw } from 'lucide-react'
import React, { useLayoutEffect, useRef, useState } from 'react'
import { AlertTriangle, ArrowDown, ChevronDown, ChevronUp, Copy, Eraser, LoaderCircle, Pause, RefreshCw } from 'lucide-react'
import React, { useLayoutEffect, useMemo, useRef, useState } from 'react'
import { t } from '../i18n'
import { LogLine } from '../lib/logs'
import { taskDetail, taskTitle } from '../lib/tasks'
@@ -27,6 +27,10 @@ interface Props {
onCancelTask: (id: string) => void
host?: HostReport
runningVMs?: number
onCopy?: (text: string) => void
/** False when WHPX or the runtime needs attention; the bar then leads with a link to the host page. */
hostReady?: boolean
onOpenHost?: () => void
}
/** Sticks to the bottom until the user scrolls up; offers "jump to latest" then. */
@@ -52,6 +56,15 @@ function useStickToBottom(dep: unknown, active: boolean) {
return { ref, stuck, onScroll, jump }
}
const LogRow = React.memo(({ line }: { line: LogLine }) => (
<div className={`log-line ${line.level}`}>
<span className="log-ts">{line.ts}</span>
<span className="log-src">{line.source}</span>
<span className="log-msg">{line.line}</span>
</div>
))
LogRow.displayName = 'LogRow'
const LOG_HEIGHT_KEY = 'reims-go-log-height'
const DEFAULT_LOG_HEIGHT = 240
const MIN_LOG_HEIGHT = 120
@@ -59,10 +72,42 @@ const MAX_LOG_HEIGHT = 520
export const LogPanel: React.FC<Props> = ({
locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, qemuText, showSerial, onRefreshSerial, onRefreshQemu,
task, runningTasks, onCancelTask, host, runningVMs = 0,
task, runningTasks, onCancelTask, host, runningVMs = 0, onCopy, hostReady = true, onOpenHost,
}) => {
const tr = (k: Parameters<typeof t>[1], v?: Record<string, string | number>) => t(locale, k, v)
const content = tab === 'app' ? lines : tab === 'serial' ? serialText : qemuText
const [query, setQuery] = useState('')
const [errorsOnly, setErrorsOnly] = useState(false)
const q = query.trim().toLowerCase()
const filteredLines = useMemo(() => {
return lines.filter((l) => {
if (errorsOnly && l.level !== 'error' && l.level !== 'warn') return false
if (q && !l.line.toLowerCase().includes(q) && !l.source.toLowerCase().includes(q)) return false
return true
})
}, [lines, errorsOnly, q])
// Same element list while the lines are unchanged, so an App re-render for
// something else doesn't rebuild up to MAX_LOG_LINES rows; a new line renders
// just its own row (LogRow is memoised on the line object).
const rows = useMemo(() => filteredLines.map((l) => <LogRow key={l.id} line={l} />), [filteredLines])
const filteredText = useMemo(() => {
const raw = tab === 'serial' ? serialText : qemuText
if (!q || !raw) return raw
return raw.split('\n').filter((line) => line.toLowerCase().includes(q)).join('\n')
}, [tab, serialText, qemuText, q])
const copyVisible = () => {
if (!onCopy) return
if (tab === 'app') {
const txt = filteredLines.map((l) => `${l.ts} [${l.source}] ${l.line}`).join('\n')
if (txt) onCopy(txt)
} else if (filteredText) {
onCopy(filteredText)
}
}
const content = tab === 'app' ? filteredLines : filteredText
const { ref, stuck, onScroll, jump } = useStickToBottom(content, open)
const memPct = host
@@ -75,6 +120,8 @@ export const LogPanel: React.FC<Props> = ({
const usedMemGB = host && host.total_ram_gb > 0 ? Math.max(0, host.total_ram_gb - host.avail_ram_gb) : 0
const memTone = memPct >= 90 ? ' high' : memPct >= 80 ? ' warn' : ''
const lowDisk = !!host && host.free_disk_gb > 0 && host.free_disk_gb < 30
// "D:\Data\reims-go" → "D:": the drive VM disks and snapshots grow on.
const dataDrive = /^([A-Za-z]:)/.exec(host?.data_root ?? '')?.[1]?.toUpperCase() ?? ''
const [height, setHeight] = useState<number>(() => {
try {
@@ -150,7 +197,18 @@ export const LogPanel: React.FC<Props> = ({
)}
</>
) : host ? (
// Host at a glance: a problem first (only when there is one), then
// memory, the data drive and running VMs. "Label value" pairs with
// thin rules between them; exact figures live in the tooltips.
<div className="status-telemetry">
{!hostReady && onOpenHost && (
<Tip side="top" label={tr('footerHostIssueTip')}>
<button type="button" className="status-metric status-issue" onClick={onOpenHost}>
<AlertTriangle size={12} aria-hidden="true" />
<span>{tr('footerHostIssue')}</span>
</button>
</Tip>
)}
{host.total_ram_gb > 0 && (
<Tip
side="top"
@@ -161,52 +219,71 @@ export const LogPanel: React.FC<Props> = ({
})}
>
<span className={`status-metric${memTone}`} tabIndex={0}>
<MemoryStick size={12} aria-hidden="true" />
<span>{tr('footerMem', { pct: memPct })}</span>
<span className="status-label">{tr('footerMemLabel')}</span>
<span className="status-value">{tr('footerMemValue', { used: usedMemGB.toFixed(1), total: host.total_ram_gb.toFixed(0) })}</span>
<span className="status-mini-bar" aria-hidden="true">
<span className={`status-mini-fill${memTone}`} style={{ transform: `scaleX(${memPct / 100})` }} />
</span>
<span className="status-metric-dim">({tr('footerMemAvail', { avail: host.avail_ram_gb.toFixed(1) })})</span>
</span>
</Tip>
)}
{host.free_disk_gb > 0 && (
<>
<span className="status-sep" aria-hidden="true">·</span>
<span className={`status-metric${lowDisk ? ' warn' : ''}`}>
<HardDrive size={12} aria-hidden="true" />
<span>{tr('footerDisk', { gb: host.free_disk_gb.toFixed(0) })}</span>
<Tip side="top" label={tr('footerDiskTip', { dir: host.data_root })}>
<span className={`status-metric${lowDisk ? ' warn' : ''}`} tabIndex={0}>
<span className="status-label">{dataDrive || tr('footerDiskLabel')}</span>
<span className="status-value">{tr('footerDiskValue', { gb: host.free_disk_gb.toFixed(0) })}</span>
</span>
</>
</Tip>
)}
{runningVMs > 0 && (
<>
<span className="status-sep" aria-hidden="true">·</span>
<span className="status-metric ok">
<span className="status status-running" aria-hidden="true" />
<span>{tr('footerRunningVMs', { n: runningVMs })}</span>
</span>
</>
<span className="status-metric ok">
<span className="status status-running" aria-hidden="true" />
<span className="status-value">{tr('footerRunningVMs', { n: runningVMs })}</span>
</span>
)}
</div>
) : null}
<span className="spacer" />
{open && (
<div className="tabs" role="tablist">
<button type="button" role="tab" className="tab" aria-selected={tab === 'app'} onClick={() => onTab('app')}>
{tr('logActivity')}
</button>
{showSerial && (
<>
<button type="button" role="tab" className="tab" aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
{tr('logSerial')}
</button>
<button type="button" role="tab" className="tab" aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
{tr('logQemu')}
</button>
</>
<>
<input
type="search"
className="log-filter-input"
value={query}
placeholder={tr('logSearchPlaceholder')}
aria-label={tr('logSearchPlaceholder')}
spellCheck={false}
onChange={(e) => setQuery(e.target.value)}
/>
{tab === 'app' && (
<button
type="button"
className="log-filter-pill"
aria-pressed={errorsOnly}
onClick={() => setErrorsOnly((v) => !v)}
>
{tr('logErrorsOnly')}
</button>
)}
</div>
<div className="tabs" role="tablist">
<button type="button" role="tab" className="tab" aria-selected={tab === 'app'} onClick={() => onTab('app')}>
{tr('logActivity')}
</button>
{showSerial && (
<>
<button type="button" role="tab" className="tab" aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
{tr('logSerial')}
</button>
<button type="button" role="tab" className="tab" aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
{tr('logQemu')}
</button>
</>
)}
</div>
</>
)}
{open && onCopy && (
<IconButton small tipSide="top" label={tr('logCopy')} icon={<Copy size={14} />} onClick={copyVisible} />
)}
{open && tab === 'app' && lines.length > 0 && (
<IconButton small tipSide="top" label={tr('clear')} icon={<Eraser size={14} />} onClick={onClear} />
@@ -236,18 +313,10 @@ export const LogPanel: React.FC<Props> = ({
<div className="logs-body-wrap">
<div className="logs-body" style={{ height }} ref={ref} onScroll={onScroll} role="log" aria-live="off">
{tab === 'app'
? (lines.length === 0
? (filteredLines.length === 0
? <span className="muted">{tr('logsEmpty')}</span>
: lines.map((l) => (
<div key={l.id} className={`log-line ${l.level}`}>
<span className="log-ts">{l.ts}</span>
<span className="log-src">{l.source}</span>
<span className="log-msg">{l.line}</span>
</div>
)))
: tab === 'serial'
? (serialText || <span className="muted">{tr('logsEmpty')}</span>)
: (qemuText || <span className="muted">{tr('logsEmpty')}</span>)}
: rows)
: (filteredText || <span className="muted">{tr('logsEmpty')}</span>)}
</div>
{!stuck && (
<Button className="jump-latest" icon={<ArrowDown size={14} />} onClick={jump}>
+25 -2
View File
@@ -25,11 +25,12 @@ import {
optStatusLabel,
parseKernelIrqchip,
} from '../lib/optimizations'
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMDetail, VMStats } from '../types'
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
import { api } from '../wails'
import { formatAffinitySummary } from './AffinityDialog'
// VM settings (docs/shell-design.md §4): edits are staged here and written in
// one `reims-ctl set` on Save, because upstream applies every change on the
@@ -128,11 +129,13 @@ interface Props {
running: boolean
onCopy?: (text: string) => void
onDiskChanged?: () => void
onOpenAffinity?: () => void
affinityVersion?: number
onClose: () => void
onSaved: () => void
}
export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, optimizations, running, onCopy, onDiskChanged, onClose, onSaved }) => {
export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onClose, onSaved }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
const base = useMemo(() => baseline(detail, host), [detail, host])
@@ -152,6 +155,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
const activeVMNameRef = useRef(detail.name)
activeVMNameRef.current = detail.name
const [driveErr, setDriveErr] = useState('')
const [affinityStatus, setAffinityStatus] = useState<VMAffinityStatus | null>(null)
const pane = useRef<HTMLDivElement>(null)
const presets = recommendedDisplayPresets(host)
@@ -218,6 +222,14 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
return () => { active = false }
}, [detail.name])
useEffect(() => {
let active = true
api.GetVMAffinity(detail.name)
.then((st) => { if (active) setAffinityStatus(st) })
.catch(() => {})
return () => { active = false }
}, [detail.name, running, affinityVersion])
const updateDriveShares = async (enabled: boolean, selected: string[]) => {
if (driveBusyRef.current || !driveSettings) return
driveBusyRef.current = true
@@ -341,6 +353,17 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
/>
}
/>
{onOpenAffinity && (
<SetRow
title={tr('affinityTitle')}
desc={affinityStatus ? `${formatAffinitySummary(locale, affinityStatus)} · ${tr('affinityRowDesc')}` : tr('affinityRowDesc')}
control={
<Button variant="secondary" icon={<Cpu size={13} aria-hidden="true" />} onClick={onOpenAffinity}>
{tr('affinityConfigure')}
</Button>
}
/>
)}
</SetGroup>
<SetGroup title={tr('factMemory')}>
<SetRow
+99 -17
View File
@@ -1,8 +1,11 @@
import { Cpu, Download, Monitor, Plus, Settings } from 'lucide-react'
import * as Ctx from '@radix-ui/react-context-menu'
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Play, Plus, Power, RotateCw, Settings, Square, Trash } from 'lucide-react'
import React, { useRef } from 'react'
import { I18nKey, t } from '../i18n'
import { Locale, VMListItem } from '../types'
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
import { VersionArt } from './VersionArt'
import { VMAction } from './VMPage'
export const HOST_ID = '__host__'
export const INSTALLERS_ID = '__installers__'
@@ -15,12 +18,22 @@ interface Props {
selected: string
hostReady: boolean
onSelect: (id: string) => void
/** VM name → display name (its note); empty or missing shows the name. */
displayNames?: Record<string, string>
/** VM name → macOS major version for its icon; null shows the name's initial. */
macosMajors?: Record<string, number | null>
/** Double-click on a VM: its main action (start, or show its window). */
onActivate?: (name: string) => void
onNew: () => void
onVMContextAction?: (name: string, action: VMAction | 'settings') => void
/** An installer download is running (busy dot on the Installers entry). */
downloading?: boolean
}
export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, hostReady, onSelect, onNew, downloading }) => {
export const Sidebar: React.FC<Props> = ({
locale, vms, transitions, selected, hostReady, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading,
}) => {
const tr = (k: I18nKey) => t(locale, k)
const listRef = useRef<HTMLDivElement>(null)
const ids = [...vms.map((v) => v.name), INSTALLERS_ID, HOST_ID, SETTINGS_ID]
@@ -38,13 +51,14 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
listRef.current?.querySelector<HTMLElement>(`[data-id="${CSS.escape(ids[next])}"]`)?.focus()
}
const item = (
const navBtn = (
id: string,
label: string,
icon: React.ReactNode,
badgeClass: string,
stateLabel: string,
kind: ReturnType<typeof statusKind> | null,
onDoubleClick?: () => void,
) => (
<button
key={id}
@@ -56,6 +70,7 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
aria-label={stateLabel ? `${label},${stateLabel}` : label}
tabIndex={selected === id ? 0 : -1}
onClick={() => onSelect(id)}
onDoubleClick={onDoubleClick}
>
<span className={`nav-icon-badge ${badgeClass}`} aria-hidden="true">{icon}</span>
<span className="nav-label">{label}</span>
@@ -71,36 +86,103 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
<div className="sidebar-wrap">
<aside className="sidebar">
<div className="sidebar-head">
<span>{t(locale, 'sidebarVMs')}</span>
<IconButton small label={t(locale, 'newVM')} shortcut="Ctrl+N" icon={<Plus size={15} />} onClick={onNew} tipSide="right" />
<span>{tr('sidebarVMs')}</span>
<IconButton small label={tr('newVM')} shortcut="Ctrl+N" icon={<Plus size={15} />} onClick={onNew} tipSide="right" />
</div>
<div className="nav" role="listbox" aria-label={t(locale, 'sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
{vms.length === 0 && <div className="nav-empty">{t(locale, 'emptyVMs')}</div>}
<div className="nav" role="listbox" aria-label={tr('sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
{vms.length === 0 && <div className="nav-empty">{tr('emptyVMs')}</div>}
{vms.map((vm) => {
const st = transitions[vm.name] ?? vm.state
return item(vm.name, vm.name, <Monitor size={13} />, 'nav-icon-vm', t(locale, `state_${st}` as I18nKey), statusKind(st))
const running = st === 'running'
const stopped = st === 'stopped'
const transitioning = st === 'starting' || st === 'stopping'
const label = displayNames[vm.name] || vm.name
const trigger = navBtn(
vm.name,
label,
<VersionArt shape="tile" major={macosMajors[vm.name] ?? null} name={label} />,
'nav-icon-art',
t(locale, `state_${st}` as I18nKey),
statusKind(st),
onActivate ? () => onActivate(vm.name) : undefined,
)
if (!onVMContextAction) return trigger
return (
<Ctx.Root key={vm.name}>
<Ctx.Trigger asChild>{trigger}</Ctx.Trigger>
<Ctx.Portal>
<Ctx.Content className="menu">
{stopped && (
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'start')}>
<Play size={14} /> {tr('start')}
</Ctx.Item>
)}
{running && (
<>
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'focus')}>
<AppWindow size={14} /> {tr('showWindow')}
</Ctx.Item>
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'screenshot')}>
<Camera size={14} /> {tr('copyScreenshot')}
</Ctx.Item>
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'stop')}>
<Square size={14} /> {tr('stop')}
</Ctx.Item>
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'restart')}>
<RotateCw size={14} /> {tr('restart')}
</Ctx.Item>
</>
)}
{(running || transitioning) && (
<Ctx.Item className="menu-item danger" onSelect={() => onVMContextAction(vm.name, 'forceStop')}>
<Power size={14} /> {tr('forceStop')}
</Ctx.Item>
)}
<Ctx.Separator className="menu-sep" />
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'settings')}>
<Settings size={14} /> {tr('settingsEllipsis')}
</Ctx.Item>
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openSharedFolder')}>
<FolderOpen size={14} /> {tr('openSharedFolder')}
</Ctx.Item>
{stopped && (
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'cloneVM')}>
<CopyPlus size={14} /> {tr('cloneVM')}
</Ctx.Item>
)}
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openFolder')}>
<FolderOpen size={14} /> {tr('openFolder')}
</Ctx.Item>
<Ctx.Separator className="menu-sep" />
<Ctx.Item className="menu-item danger" disabled={running || transitioning} onSelect={() => onVMContextAction(vm.name, 'delete')}>
<Trash size={14} /> {tr('delete')}
</Ctx.Item>
</Ctx.Content>
</Ctx.Portal>
</Ctx.Root>
)
})}
<div className="sidebar-sep" role="presentation" />
<div className="sidebar-section-label" aria-hidden="true">{t(locale, 'sidebarSystem')}</div>
{item(
<div className="sidebar-section-label" aria-hidden="true">{tr('sidebarSystem')}</div>
{navBtn(
INSTALLERS_ID,
t(locale, 'sidebarInstallers'),
tr('sidebarInstallers'),
<Download size={13} />,
'nav-icon-installers',
downloading ? t(locale, 'state_starting') : '',
downloading ? tr('state_starting') : '',
downloading ? 'busy' : null,
)}
{item(
{navBtn(
HOST_ID,
t(locale, 'sidebarHost'),
tr('sidebarHost'),
<Cpu size={13} />,
'nav-icon-host',
t(locale, hostReady ? 'hostReady' : 'hostNeedsAction'),
tr(hostReady ? 'hostReady' : 'hostNeedsAction'),
hostReady ? 'running' : 'warn',
)}
{item(
{navBtn(
SETTINGS_ID,
t(locale, 'sidebarSettings'),
tr('sidebarSettings'),
<Settings size={13} />,
'nav-icon-settings',
'',
+148
View File
@@ -0,0 +1,148 @@
import * as Menu from '@radix-ui/react-dropdown-menu'
import { Check, PanelLeft } from 'lucide-react'
import React, { useState } from 'react'
import { I18nKey, t } from '../i18n'
import { Locale } from '../types'
import { Tip } from '../ui/controls'
import type { ThemeMode } from './AppSettingsPage'
import { HOST_ID, INSTALLERS_ID, SETTINGS_ID } from './Sidebar'
import { VMAction } from './VMPage'
const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
interface Props {
locale: Locale
sidebarOpen: boolean
onToggleSidebar: () => void
logsOpen: boolean
onToggleLogs: () => void
themeMode: ThemeMode
onThemeMode: (mode: ThemeMode) => void
/** The selected VM and its current state, or null on the system pages. */
vm: { name: string; state: string; busy: boolean } | null
onNewVM: () => void
onVMAction: (action: VMAction) => void
onVMSettings: () => void
onVMDelete: () => void
onNavigate: (id: string) => void
onOpenURL: (url: string) => void
appVersion: string
}
/**
* The title bar's left side: a sidebar toggle and a small menu bar (VM / View /
* Help) that lists every command with its shortcut, so the keyboard paths are
* discoverable and still reachable with the sidebar hidden. Once one menu is
* open, hovering the next title switches to it, as in a native menu bar.
*/
export const TitleMenus: React.FC<Props> = ({
locale, sidebarOpen, onToggleSidebar, logsOpen, onToggleLogs, themeMode, onThemeMode,
vm, onNewVM, onVMAction, onVMSettings, onVMDelete, onNavigate, onOpenURL, appVersion,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [open, setOpen] = useState<string | null>(null)
const running = vm?.state === 'running'
const stopped = vm?.state === 'stopped'
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping'
const vmBusy = !vm || vm.busy
const item = (label: string, onSelect: () => void, opts: { shortcut?: string; disabled?: boolean; danger?: boolean } = {}) => (
<Menu.Item className={`menu-item${opts.danger ? ' danger' : ''}`} disabled={opts.disabled} onSelect={onSelect}>
<span className="menu-label">{label}</span>
{opts.shortcut && <kbd className="menu-shortcut">{opts.shortcut}</kbd>}
</Menu.Item>
)
const check = (label: string, checked: boolean, onSelect: () => void, shortcut?: string) => (
<Menu.CheckboxItem className="menu-item menu-item-check" checked={checked} onSelect={onSelect}>
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
<span className="menu-label">{label}</span>
{shortcut && <kbd className="menu-shortcut">{shortcut}</kbd>}
</Menu.CheckboxItem>
)
// `indented`: the menu has check marks, so every row shares their indent.
const menu = (id: string, label: string, content: React.ReactNode, indented = false) => (
<Menu.Root modal={false} open={open === id} onOpenChange={(o) => setOpen(o ? id : null)}>
<Menu.Trigger asChild>
<button
type="button"
className="titlebar-menu"
onPointerEnter={() => { if (open && open !== id) setOpen(id) }}
>
{label}
</button>
</Menu.Trigger>
<Menu.Portal>
<Menu.Content className={`menu titlebar-menu-content${indented ? ' menu-indented' : ''}`} align="start" sideOffset={4} collisionPadding={8}>
{content}
</Menu.Content>
</Menu.Portal>
</Menu.Root>
)
return (
<div className="titlebar-left" onDoubleClick={(e) => e.stopPropagation()}>
<Tip label={tr(sidebarOpen ? 'hideSidebar' : 'showSidebar')} shortcut="Ctrl+B">
<button
type="button"
className="titlebar-icon"
aria-label={tr(sidebarOpen ? 'hideSidebar' : 'showSidebar')}
aria-pressed={sidebarOpen}
onClick={onToggleSidebar}
>
<PanelLeft size={16} aria-hidden="true" />
</button>
</Tip>
<nav className="titlebar-menus" aria-label={tr('menuBar')}>
{menu('vm', tr('menuVM'), (
<>
{item(tr('newVMEllipsis'), onNewVM, { shortcut: 'Ctrl+N' })}
<Menu.Separator className="menu-sep" />
{running
? item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy })
: item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })}
{item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })}
{item(tr('restart'), () => onVMAction('restart'), { disabled: vmBusy || !running })}
{item(tr('copyScreenshot'), () => onVMAction('screenshot'), { disabled: vmBusy || !running })}
<Menu.Separator className="menu-sep" />
{item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm })}
{item(tr('openFolder'), () => onVMAction('openFolder'), { disabled: !vm })}
<Menu.Separator className="menu-sep" />
{item(tr('forceStop'), () => onVMAction('forceStop'), { danger: true, disabled: !vm || !(running || transitioning) })}
{item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || transitioning })}
</>
))}
{menu('view', tr('menuView'), (
<>
{check(tr('sidebarLabel'), sidebarOpen, onToggleSidebar, 'Ctrl+B')}
{check(tr('logButton'), logsOpen, onToggleLogs, 'Ctrl+L')}
<Menu.Separator className="menu-sep" />
<Menu.Label className="menu-group-label">{tr('appearance')}</Menu.Label>
<Menu.RadioGroup value={themeMode} onValueChange={(v) => onThemeMode(v as ThemeMode)}>
{(['light', 'dark', 'system'] as const).map((m) => (
<Menu.RadioItem key={m} className="menu-item menu-item-check" value={m}>
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
<span className="menu-label">{tr(m === 'light' ? 'themeLight' : m === 'dark' ? 'themeDark' : 'themeSystem')}</span>
</Menu.RadioItem>
))}
</Menu.RadioGroup>
<Menu.Separator className="menu-sep" />
{item(tr('sidebarInstallers'), () => onNavigate(INSTALLERS_ID))}
{item(tr('sidebarHost'), () => onNavigate(HOST_ID))}
{item(tr('sidebarSettings'), () => onNavigate(SETTINGS_ID))}
</>
), true)}
{menu('help', tr('menuHelp'), (
<>
{item(tr('helpProjectPage'), () => onOpenURL(REPO_URL))}
{item(tr('helpReportIssue'), () => onOpenURL(`${REPO_URL}/issues`))}
{item(tr('helpCheckUpdate'), () => onNavigate(SETTINGS_ID))}
<Menu.Separator className="menu-sep" />
<Menu.Label className="menu-group-label">Reims-Go {appVersion}</Menu.Label>
</>
))}
</nav>
</div>
)
}
File diff suppressed because it is too large. Load diff
+128
View File
@@ -0,0 +1,128 @@
import React, { useId } from 'react'
/**
* A VM's icon: its macOS major version as frosted-glass digits over soft
* folds of colour. Drawn here, with our own palettes; no Apple artwork.
* The glass is the background itself, blurred and brightened inside the
* digits' outline. Without a known version it shows the name's first letter.
*/
type Palette = [string, string, string, string]
const PALETTES: Record<number, Palette> = {
26: ['#f6e8cf', '#ebc8b4', '#a597d8', '#5450b4'], // sand → rose → lavender
15: ['#ddf2e8', '#86ccb8', '#3f8ea3', '#22446e'], // mint → teal
14: ['#ffe5d2', '#f5a48d', '#d6688f', '#6a3f8e'], // peach → coral → plum
13: ['#fff1cc', '#f7b95e', '#df7140', '#83372b'], // cream → amber
12: ['#e4ecff', '#91b1f4', '#5b70df', '#2f3592'], // ice → blue
11: ['#e5f5ff', '#88c9ee', '#3f86d0', '#233f88'], // sky → ocean
}
const FUTURE: Palette[] = [
['#f3e9ff', '#c6a8f0', '#7d6ad8', '#3c348f'],
['#e8f7f0', '#9fd8c0', '#4f9fa6', '#2a4f73'],
['#fff0e0', '#f3b98d', '#d77a74', '#6e3f72'],
]
const NEUTRAL: Palette = ['#eef0f4', '#c9ceda', '#8d95a9', '#4b5266']
function paletteFor(major: number | null): Palette {
if (major === null) return NEUTRAL
if (PALETTES[major]) return PALETTES[major]
if (major > 26) return FUTURE[(major - 27) % FUTURE.length]
return PALETTES[11]
}
function initial(name: string): string {
const ch = Array.from(name.trim().replace(/^macos[\s_-]*/i, ''))[0] ?? '?'
return ch.toUpperCase()
}
const SHAPES = {
// width, height, font size, weight, glass blur, rim width, shadow blur;
// glass: how much white the digits add; shade: how dark the drop under them.
tile: { w: 64, h: 64, size: 38, weight: 700, blur: 2.4, rim: 2.2, shadow: 1.6, glass: 1.6, shade: 0.7 },
screen: { w: 160, h: 100, size: 76, weight: 600, blur: 3.6, rim: 1.1, shadow: 2.4, glass: 1, shade: 0.36 },
}
export const VersionArt: React.FC<{
major: number | null
name: string
shape: 'tile' | 'screen'
className?: string
}> = ({ major, name, shape, className }) => {
const id = useId().replace(/[^a-zA-Z0-9_-]/g, '')
const p = paletteFor(major)
const s = SHAPES[shape]
const label = major !== null ? String(major) : initial(name)
const size = label.length > 2 ? s.size * 0.72 : label.length === 1 ? s.size * 1.08 : s.size
const text = {
x: s.w / 2,
y: s.h / 2 + size * 0.04,
textAnchor: 'middle' as const,
dominantBaseline: 'central' as const,
fontSize: size,
fontWeight: s.weight,
letterSpacing: label.length > 1 ? -size * 0.04 : 0,
style: { fontFamily: 'var(--font-sans)', fontVariantNumeric: 'tabular-nums' as const },
}
const sx = s.w / 100
const sy = s.h / 100
return (
<svg className={className} viewBox={`0 0 ${s.w} ${s.h}`} preserveAspectRatio="xMidYMid slice" aria-hidden="true">
<defs>
<linearGradient id={`${id}bg`} x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stopColor={p[0]} />
<stop offset="0.38" stopColor={p[1]} />
<stop offset="0.72" stopColor={p[2]} />
<stop offset="1" stopColor={p[3]} />
</linearGradient>
<linearGradient id={`${id}hi`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor="#ffffff" stopOpacity="0.62" />
<stop offset="1" stopColor="#ffffff" stopOpacity="0" />
</linearGradient>
<linearGradient id={`${id}sh`} x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stopColor={p[3]} stopOpacity="0" />
<stop offset="1" stopColor={p[3]} stopOpacity="0.6" />
</linearGradient>
<linearGradient id={`${id}gl`} x1="0" y1="0" x2="0.4" y2="1">
<stop offset="0" stopColor="#ffffff" stopOpacity={Math.min(1, 0.62 * s.glass)} />
<stop offset="0.55" stopColor="#ffffff" stopOpacity={Math.min(1, 0.22 * s.glass)} />
<stop offset="1" stopColor="#ffffff" stopOpacity={Math.min(1, 0.34 * s.glass)} />
</linearGradient>
<linearGradient id={`${id}rim`} x1="0" y1="0" x2="0.3" y2="1">
<stop offset="0" stopColor="#ffffff" stopOpacity="0.98" />
<stop offset="0.6" stopColor="#ffffff" stopOpacity="0.45" />
<stop offset="1" stopColor="#ffffff" stopOpacity="0.8" />
</linearGradient>
<filter id={`${id}blur`} x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation={s.blur} />
</filter>
<filter id={`${id}soft`} x="-30%" y="-30%" width="160%" height="160%">
<feGaussianBlur stdDeviation={s.shadow} />
</filter>
<clipPath id={`${id}clip`}>
<text {...text}>{label}</text>
</clipPath>
<g id={`${id}scene`}>
<rect width={s.w} height={s.h} fill={`url(#${id}bg)`} />
<g transform={`scale(${sx} ${sy})`}>
<path d="M-5 40 C16 14 40 60 70 32 S104 8 105 6 L105 -5 L-5 -5 Z" fill={`url(#${id}hi)`} />
<path d="M-5 58 C24 30 54 80 105 36 L105 50 C56 90 26 46 -5 72 Z" fill="#ffffff" fillOpacity="0.2" />
<path d="M-5 74 C22 50 52 94 80 64 S104 46 105 46 L105 105 L-5 105 Z" fill={`url(#${id}sh)`} />
<path d="M-5 58 C24 30 54 80 105 36" fill="none" stroke="#ffffff" strokeOpacity="0.55" strokeWidth="0.7" vectorEffect="non-scaling-stroke" />
</g>
</g>
</defs>
<use href={`#${id}scene`} />
{/* A soft shade under the digits so they lift off the background. */}
<text {...text} y={text.y + size * 0.05} fill={p[3]} fillOpacity={s.shade} filter={`url(#${id}soft)`}>{label}</text>
{/* The glass: the scene blurred and brightened, seen through the digits. */}
<g clipPath={`url(#${id}clip)`}>
<use href={`#${id}scene`} filter={`url(#${id}blur)`} />
<rect width={s.w} height={s.h} fill={`url(#${id}gl)`} />
</g>
<text {...text} fill="none" stroke={`url(#${id}rim)`} strokeWidth={s.rim} />
</svg>
)
}
+256
View File
@@ -13,6 +13,9 @@ const dict = {
installersTitle: '安装包',
installersDownloaded: '已下载',
installersAvailable: 'Apple 提供的版本',
installersLatest: '最新',
installersOlder: '{count} 个旧版本',
installersRetry: '重试',
installersEmpty: '还没有下载任何安装包',
installersPartial: '未下载完',
installersResume: '继续下载',
@@ -40,6 +43,27 @@ const dict = {
footerMemTip: '系统内存:已用 {used} GB / 共 {total} GB(可用 {avail} GB)',
footerDisk: '磁盘可用 {gb} GB',
footerRunningVMs: '{n} 台运行中',
footerMemLabel: '内存',
footerMemValue: '{used} / {total} GB',
footerDiskLabel: '磁盘',
footerDiskValue: '可用 {gb} GB',
footerDiskTip: '虚拟机数据目录:{dir}',
footerHostIssue: '虚拟化未就绪',
footerHostIssueTip: '打开「内核」页查看需要处理的项',
// Title-bar menus
menuBar: '菜单栏',
menuVM: '虚拟机',
menuView: '视图',
menuHelp: '帮助',
newVMEllipsis: '新建虚拟机…',
deleteEllipsis: '删除…',
sidebarLabel: '侧边栏',
showSidebar: '显示侧边栏',
hideSidebar: '隐藏侧边栏',
appearance: '外观',
helpProjectPage: '项目主页',
helpReportIssue: '报告问题',
helpCheckUpdate: '检查更新…',
settingsGeneral: '常规',
settingsAppearance: '外观与语言',
settingsAbout: '关于',
@@ -47,6 +71,53 @@ const dict = {
themeLight: '浅色',
themeDark: '深色',
themeSystem: '跟随系统',
showWindow: '显示窗口',
copyScreenshot: '截屏并复制',
toastScreenshotCopied: '已复制虚拟机画面',
failFocus: '无法定位虚拟机窗口',
failScreenshot: '截屏失败',
dropFilesHint: '松开以投递到 macOS 共享目录',
toastFilesDelivered: '已投递 {n} 个文件到共享目录',
sshOpenTerminal: '终端',
sshMore: 'SSH 工具',
sshWriteConfig: '写入 ~/.ssh/config',
sshOpenVSCode: '用 VS Code 打开',
sshSetUser: '设置 SSH 用户名…',
sshUserTitle: 'SSH 登录用户名',
sshUserDesc: '用于打开终端、写入 ~/.ssh/config 和 VS Code 直连(留空则连接时不带用户名)',
sshUserPlaceholder: '例如 admin',
toastSSHConfigWritten: '已写入 Host {alias}',
toastSSHUserSaved: '已保存 SSH 用户名',
failSSH: 'SSH 操作失败',
snapshotsTitle: '恢复点',
snapshotCreate: '创建恢复点',
snapshotEmpty: '尚未创建恢复点,升级系统或大改环境前可先留档',
snapshotHint: '停机快照 · 非异地备份',
snapshotNamePlaceholder: '例如:升级 macOS 前',
snapshotRestore: '回滚',
snapshotRestoreTitle: '回滚到「{name}」?',
snapshotRestoreDesc: '当前磁盘在此恢复点之后的改动将被覆盖,且无法撤销。',
snapshotDelete: '删除恢复点',
snapshotStopFirst: '停止虚拟机后才可管理恢复点',
toastSnapshotCreated: '已创建恢复点 {name}',
toastSnapshotRestored: '已回滚到 {name}',
toastSnapshotDeleted: '已删除恢复点 {name}',
failSnapshot: '恢复点操作失败',
displayNameEdit: '点按以修改显示名称',
displayNameLabel: '显示名称',
displayNameEditEllipsis: '修改显示名称…',
displayNameTip: '显示名称 · 虚拟机名称为 {name}(点按修改)',
fieldVMName: '虚拟机名称',
logSearchPlaceholder: '筛选日志…',
logErrorsOnly: '仅错误/警告',
logCopy: '复制日志',
storageBreakdownTitle: '空间分布',
storageVMs: '虚拟机文件',
storageInstallers: '安装包',
storageRuntimes: 'Reims-Go',
welcomeTitle: '创建第一台 macOS 虚拟机',
welcomeSub: '选择系统来源、分配核数与显卡,几步完成配置',
welcomeCheckHost: '先完成内核环境配置 →',
// Actions
newVM: '新建虚拟机',
@@ -428,6 +499,43 @@ const dict = {
driveShareNeedsTools: '需要 Guest Tools {version} 或更新版本。运行中的 VM 要先重启以更新 REIMSTOOLS,然后在 macOS 中重新运行安装命令',
driveShareMasterOff: '先开启 Windows 盘符共享',
driveShareNoDrives: '没有可共享的内部固定磁盘',
affinityTitle: '处理器相关性',
affinityMenu: '处理器相关性…',
affinityConfigure: '配置…',
affinityRowDesc: '控制 QEMU 进程在哪些宿主机逻辑处理器上运行(实时生效,无需重启)',
affinitySubtitleRunning: '运行中(PID {pid})· {vcpus} vCPU · 修改后立即生效',
affinitySubtitleStopped: '已停止 · {vcpus} vCPU · 下次启动时自动生效',
affinityModeAuto: '自动',
affinityModeAll: '所有处理器',
affinityModePCores: '仅 P 核',
affinityModeNonLPE: 'P + E 核',
affinityModeCustom: '自定义',
affinityModeAutoHint: '跟随全局策略,在混合大小核处理器上自动避开超售与低功耗核。',
affinityModeAllHint: '允许 Windows 将 QEMU 调度到全部宿主机逻辑处理器。',
affinityModePCoresHint: '仅在性能核(P-Core)上运行,减少大小核混调引起的抖动。',
affinityModeNonLPEHint: '在性能核与能效核(P + E)上运行,仅排除慢速低功耗核(LP-E)。',
affinityModeCustomHint: '勾选允许运行 QEMU 的逻辑处理器,等价于 Windows 任务管理器的处理器相关性。',
affinitySelectAll: '所有处理器',
affinityPhysicalOnly: '仅物理核',
affinityExcludeCPU0: '排除 CPU 0',
affinityOnlyPCores: '仅 P 核',
affinityAvoidLPE: '避开 LP-E',
affinitySelectedSummary: '已选 {selected} / {total} 个逻辑处理器 · 掩码 {mask}',
affinityLiveMask: 'Windows 当前生效:{mask}({count} 线程)',
affinityOversubWarn: '当前只勾选了 {selected} 个逻辑处理器,少于虚拟机分配的 {vcpus} 个 vCPU,可能导致明显卡顿。',
affinityNeedOne: '请至少勾选 1 个逻辑处理器',
affinityEcoQoS: '禁用 Windows 效率模式节流 (EcoQoS)',
affinityEcoQoSDesc: '防止 Windows 11 在窗口失焦或后台运行时把 QEMU 线程压缩到 2 个低功耗核心',
affinityApplyNow: '立即应用',
affinitySave: '保存',
affinitySummaryAuto: '自动({eff} · {count} 线程)',
affinitySummaryAll: '所有处理器({count} 线程)',
affinitySummaryPCores: '仅 P 核({count} 线程 · {mask})',
affinitySummaryNonLPE: 'P + E 核({count} 线程 · {mask})',
affinitySummaryCustom: '自定义({count} 线程 · {mask})',
toastAffinityApplied: '处理器相关性已应用({count} 个逻辑处理器 · {mask})',
toastAffinitySaved: '处理器相关性已保存,下次启动时生效',
failAffinity: '设置处理器相关性失败',
networkDesc: '通过 NAT 共享宿主的网络连接',
sshForward: 'SSH 端口转发',
sshOffDesc: '把宿主的一个端口转发到 macOS 的 22 端口',
@@ -549,6 +657,27 @@ const dict = {
statsDisk: '磁盘占用',
statsUptime: '运行时长',
statsDiskSub: '实际 {actual} / 上限 {virtual}',
// VM page (2026-11-29 redesign)
on: '开启',
netShared: '共享网络',
netOff: '无网络',
specCPUTip: '处理器 {n} 核',
specCPULiveTip: '处理器 {n} 核,当前占用 {pct}%',
specMemTip: '内存 {mem}',
specMemLiveTip: '内存 {mem},虚拟机在宿主上占用 {used}',
specNetTip: '与宿主共享网络连接',
specNetSSHTip: '与宿主共享网络连接,SSH 端口 {port}',
specNetOffTip: '虚拟机没有网络',
gtStatusConnected: '已连接',
gtStatusWaiting: '未连接',
gtStatusWaitingTip: '在 macOS 里运行安装命令后会自动连接',
gtStatusEnabled: '已启用',
gtStatusNone: '未安装',
gtStatusUpgrade: '需要更新',
gtInstall: '安装…',
gtUpdate: '更新…',
gtInstallSub: '在 macOS 终端里运行',
pendingRestartHint: '重启虚拟机后生效',
},
'en-US': {
sidebarVMs: 'Virtual machines',
@@ -559,6 +688,9 @@ const dict = {
installersTitle: 'Installers',
installersDownloaded: 'Downloaded',
installersAvailable: 'Releases from Apple',
installersLatest: 'Latest',
installersOlder: '{count} older versions',
installersRetry: 'Retry',
installersEmpty: 'No installers downloaded yet',
installersPartial: 'Partly downloaded',
installersResume: 'Resume',
@@ -586,6 +718,26 @@ const dict = {
footerMemTip: 'System memory: {used} GB used / {total} GB total ({avail} GB free)',
footerDisk: 'Disk {gb} GB free',
footerRunningVMs: '{n} running',
footerMemLabel: 'Memory',
footerMemValue: '{used} / {total} GB',
footerDiskLabel: 'Disk',
footerDiskValue: '{gb} GB free',
footerDiskTip: 'VM data folder: {dir}',
footerHostIssue: 'Virtualization not ready',
footerHostIssueTip: 'Open the Engine page to see what needs attention',
menuBar: 'Menu bar',
menuVM: 'VM',
menuView: 'View',
menuHelp: 'Help',
newVMEllipsis: 'New Virtual Machine…',
deleteEllipsis: 'Delete…',
sidebarLabel: 'Sidebar',
showSidebar: 'Show sidebar',
hideSidebar: 'Hide sidebar',
appearance: 'Appearance',
helpProjectPage: 'Project Page',
helpReportIssue: 'Report an Issue',
helpCheckUpdate: 'Check for Updates…',
settingsGeneral: 'General',
settingsAppearance: 'Appearance & language',
settingsAbout: 'About',
@@ -593,6 +745,53 @@ const dict = {
themeLight: 'Light',
themeDark: 'Dark',
themeSystem: 'System',
showWindow: 'Show window',
copyScreenshot: 'Copy screenshot',
toastScreenshotCopied: 'VM screenshot copied',
failFocus: 'Could not focus VM window',
failScreenshot: 'Screenshot failed',
dropFilesHint: 'Drop files to send to macOS shared folder',
toastFilesDelivered: 'Sent {n} files to shared folder',
sshOpenTerminal: 'Terminal',
sshMore: 'SSH tools',
sshWriteConfig: 'Write ~/.ssh/config',
sshOpenVSCode: 'Open in VS Code',
sshSetUser: 'Set SSH username…',
sshUserTitle: 'SSH login username',
sshUserDesc: 'Used for Terminal, ~/.ssh/config, and VS Code Remote-SSH (leave empty to omit user)',
sshUserPlaceholder: 'e.g. admin',
toastSSHConfigWritten: 'Wrote Host {alias}',
toastSSHUserSaved: 'Saved SSH username',
failSSH: 'SSH action failed',
snapshotsTitle: 'Restore points',
snapshotCreate: 'New restore point',
snapshotEmpty: 'No restore points yet — save one before OS updates or major changes',
snapshotHint: 'Offline snapshots · Not a backup',
snapshotNamePlaceholder: 'e.g. before-macos-update',
snapshotRestore: 'Restore',
snapshotRestoreTitle: 'Restore "{name}"?',
snapshotRestoreDesc: 'Disk changes made after this restore point will be overwritten and cannot be undone.',
snapshotDelete: 'Delete restore point',
snapshotStopFirst: 'Stop the VM before managing restore points',
toastSnapshotCreated: 'Created restore point {name}',
toastSnapshotRestored: 'Restored to {name}',
toastSnapshotDeleted: 'Deleted restore point {name}',
failSnapshot: 'Restore point failed',
displayNameEdit: 'Click to change the display name',
displayNameLabel: 'Display name',
displayNameEditEllipsis: 'Change Display Name…',
displayNameTip: 'Display name · VM name is {name} (click to change)',
fieldVMName: 'VM name',
logSearchPlaceholder: 'Filter logs…',
logErrorsOnly: 'Errors & warnings',
logCopy: 'Copy logs',
storageBreakdownTitle: 'Storage breakdown',
storageVMs: 'VM files',
storageInstallers: 'Installers',
storageRuntimes: 'Reims-Go',
welcomeTitle: 'Create your first macOS VM',
welcomeSub: 'Pick an installer, assign cores and GPU, and launch in minutes',
welcomeCheckHost: 'Set up Engine first →',
newVM: 'New virtual machine',
start: 'Start',
@@ -963,6 +1162,43 @@ const dict = {
driveShareNeedsTools: 'Requires Guest Tools {version} or newer. Restart a running VM to update REIMSTOOLS, then run the install command in macOS again',
driveShareMasterOff: 'Turn on Windows drive sharing first',
driveShareNoDrives: 'No internal fixed disks are available to share',
affinityTitle: 'Processor Affinity',
affinityMenu: 'Processor Affinity…',
affinityConfigure: 'Configure…',
affinityRowDesc: 'Choose which host logical CPUs QEMU can run on (applies live without restarting)',
affinitySubtitleRunning: 'Running (PID {pid}) · {vcpus} vCPU · Applies immediately',
affinitySubtitleStopped: 'Stopped · {vcpus} vCPU · Applied on next start',
affinityModeAuto: 'Auto',
affinityModeAll: 'All CPUs',
affinityModePCores: 'P-Cores',
affinityModeNonLPE: 'P + E',
affinityModeCustom: 'Custom',
affinityModeAutoHint: 'Follows global policy and avoids oversubscription and slow LP-E cores on hybrid CPUs.',
affinityModeAllHint: 'Allows Windows to schedule QEMU across all host logical processors.',
affinityModePCoresHint: 'Restricts QEMU to performance cores (P-cores) to minimize scheduling jitter.',
affinityModeNonLPEHint: 'Runs QEMU on P + E cores while excluding slow SoC LP-E cores.',
affinityModeCustomHint: 'Check the host logical CPUs allowed to run QEMU — identical to Windows Task Manager affinity.',
affinitySelectAll: 'All CPUs',
affinityPhysicalOnly: 'Physical cores only',
affinityExcludeCPU0: 'Exclude CPU 0',
affinityOnlyPCores: 'P-cores only',
affinityAvoidLPE: 'Exclude LP-E',
affinitySelectedSummary: '{selected} / {total} logical CPUs selected · Mask {mask}',
affinityLiveMask: 'Active in Windows: {mask} ({count} threads)',
affinityOversubWarn: 'Only {selected} logical CPUs selected for {vcpus} guest vCPUs; this may cause noticeable stalls.',
affinityNeedOne: 'Select at least 1 logical CPU',
affinityEcoQoS: 'Disable Windows EcoQoS power throttling',
affinityEcoQoSDesc: 'Prevents Windows 11 from parking unfocused/background QEMU threads onto 2 low-power cores',
affinityApplyNow: 'Apply Now',
affinitySave: 'Save',
affinitySummaryAuto: 'Auto ({eff} · {count}T)',
affinitySummaryAll: 'All CPUs ({count}T)',
affinitySummaryPCores: 'P-Cores ({count}T · {mask})',
affinitySummaryNonLPE: 'P + E ({count}T · {mask})',
affinitySummaryCustom: 'Custom ({count}T · {mask})',
toastAffinityApplied: 'Processor affinity applied ({count} logical CPUs · {mask})',
toastAffinitySaved: 'Processor affinity saved for next start',
failAffinity: 'Could not update processor affinity',
networkDesc: 'Shares the host connection through NAT',
sshForward: 'SSH port forwarding',
sshOffDesc: 'Forwards a host port to port 22 in macOS',
@@ -1081,6 +1317,26 @@ const dict = {
toastBorderlessNextStart: 'Fullscreen launch saved — applies on next restart',
statsCPU: 'QEMU CPU',
statsMemory: 'Host RAM',
on: 'On',
netShared: 'Shared network',
netOff: 'No network',
specCPUTip: '{n} CPU cores',
specCPULiveTip: '{n} CPU cores, {pct}% in use',
specMemTip: '{mem} memory',
specMemLiveTip: '{mem} memory; the VM uses {used} on this PC',
specNetTip: 'Shares this PC’s network connection',
specNetSSHTip: 'Shares this PC’s network connection; SSH on port {port}',
specNetOffTip: 'The VM has no network',
gtStatusConnected: 'Connected',
gtStatusWaiting: 'Not connected',
gtStatusWaitingTip: 'Connects once the install command has run in macOS',
gtStatusEnabled: 'Enabled',
gtStatusNone: 'Not installed',
gtStatusUpgrade: 'Update needed',
gtInstall: 'Install…',
gtUpdate: 'Update…',
gtInstallSub: 'Run in macOS Terminal',
pendingRestartHint: 'Takes effect after a restart',
statsDisk: 'Disk usage',
statsUptime: 'Uptime',
statsDiskSub: '{actual} actual / {virtual} max',
+25
View File
@@ -228,3 +228,28 @@ export function splitLangLabel(value: string, text: string): { value: string; la
const m = /^(.*?)\s*[((](.*)[))]\s*$/.exec(text)
return m ? { value, label: m[1], detail: m[2] } : { value, label: text }
}
/**
* A change saved while the VM runs, as the user would say it:
* `memory 8G→16G` becomes "内存 8 GB → 16 GB". Field names come from
* PendingChange in internal/app/app.go.
*/
export function pendingChangeText(locale: Locale, p: { field: string; from: string; to: string }, host: HostReport): string {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const bool = (v: string) => tr(v === 'true' ? 'on' : 'off')
const lang = (v: string) => splitLangLabel('', guestLangLabel(locale, v)).label
const fields: Record<string, { label: I18nKey; fmt: (v: string) => string }> = {
cpus: { label: 'factCPU', fmt: (v) => tr('cores', { n: v }) },
memory: { label: 'factMemory', fmt: formatMemory },
resolution: { label: 'resolution', fmt: resolutionLabel },
gpu: { label: 'factGraphics', fmt: (v) => gpuLabel(locale, v, host) },
displays: { label: 'displays', fmt: (v) => v },
borderless: { label: 'borderless', fmt: bool },
audio: { label: 'fieldAudio', fmt: bool },
audio_backend: { label: 'fieldAudio', fmt: (v) => v },
guest_lang: { label: 'specLang', fmt: lang },
}
const f = fields[p.field]
if (!f) return `${p.field} ${p.from} → ${p.to}`
return `${tr(f.label)} ${f.fmt(p.from)} → ${f.fmt(p.to)}`
}
+37
View File
@@ -0,0 +1,37 @@
// Which macOS major version a VM runs, for its icon. The release comes from
// GetVMMacOS (.reims-go-macos, written at creation: "26.7.3" or "tahoe");
// VMs without one are guessed from their name or display name.
const CODENAMES: [string, number][] = [
['tahoe', 26],
['sequoia', 15],
['sonoma', 14],
['ventura', 13],
['monterey', 12],
['bigsur', 11],
['big sur', 11],
['big-sur', 11],
]
function fromText(text: string): number | null {
const s = text.trim().toLowerCase()
if (!s) return null
const ver = /^(\d{2})(?:\.\d+)*$/.exec(s)
if (ver) return Number(ver[1])
for (const [name, major] of CODENAMES) if (s.includes(name)) return major
const tagged = /macos[\s_-]*(\d{2})(?!\d)/.exec(s)
if (tagged) {
const n = Number(tagged[1])
if (n >= 10 && n <= 60) return n
}
return null
}
/** The major version (26, 15, …) from the recorded release, else from the hints. */
export function macOSMajor(release: string | undefined, ...hints: (string | undefined)[]): number | null {
for (const text of [release, ...hints]) {
const n = text ? fromText(text) : null
if (n !== null) return n
}
return null
}
+13
View File
@@ -1,6 +1,19 @@
import { t } from '../i18n'
import { Locale, Task } from '../types'
// Match the finished-task retention period in internal/app/tasks.go.
export const finishedTaskTTL = 10 * 60 * 1000
export function pruneFinishedTasks(tasks: Record<string, Task>, cutoff: number): Record<string, Task> {
let next = tasks
for (const task of Object.values(tasks)) {
if (task.status === 'running' || task.updated_at >= cutoff) continue
if (next === tasks) next = { ...tasks }
delete next[task.id]
}
return next
}
/** Insert or replace a task by id; events can arrive out of order, keep the newest. */
export function upsertTask(prev: Record<string, Task>, task: Task): Record<string, Task> {
const cur = prev[task.id]
+85
View File
@@ -0,0 +1,85 @@
import { useEffect, useState } from 'react'
import { VMStats } from '../types'
import { api } from '../wails'
// Shared VM stats poller (stats_flow.go). Components that show stats
// subscribe with useVMStats, so a tick re-renders only them, not the whole
// App. One timer per VM however many subscribe; it pauses while the window
// is hidden and samples once on return.
const RUNNING_MS = 3000
// A stopped VM only changes disk usage, so it is sampled rarely.
const STOPPED_MS = 30000
interface Entry {
subs: Set<(s: VMStats) => void>
running: boolean
last: VMStats | null
timer?: number
}
const entries = new Map<string, Entry>()
function sample(name: string) {
api.GetVMStats(name)
.then((s) => {
const e = entries.get(name)
if (!e) return
e.last = s
e.subs.forEach((f) => f(s))
})
.catch(() => {})
}
function schedule(name: string, e: Entry) {
if (e.timer) window.clearInterval(e.timer)
e.timer = undefined
if (document.hidden || e.subs.size === 0) return
e.timer = window.setInterval(() => sample(name), e.running ? RUNNING_MS : STOPPED_MS)
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => {
entries.forEach((e, name) => {
if (!document.hidden && e.subs.size > 0) sample(name)
schedule(name, e)
})
})
}
/** Latest stats seen for a VM, without subscribing (e.g. when a dialog opens). */
export function latestVMStats(name: string | undefined | null): VMStats | null {
return name ? entries.get(name)?.last ?? null : null
}
/** Live stats for one VM; `running` picks the sampling rate. Null name: none. */
export function useVMStats(name: string | null, running: boolean): VMStats | null {
const [stats, setStats] = useState<VMStats | null>(() => latestVMStats(name))
useEffect(() => {
if (!name) { setStats(null); return }
let e = entries.get(name)
if (!e) {
e = { subs: new Set(), running, last: null }
entries.set(name, e)
}
setStats(e.last)
const sub = (s: VMStats) => setStats(s)
e.subs.add(sub)
// A state change (start/stop) samples at once and re-paces the timer.
e.running = running
sample(name)
schedule(name, e)
return () => {
const cur = entries.get(name)
if (!cur) return
cur.subs.delete(sub)
if (cur.subs.size === 0) {
if (cur.timer) window.clearInterval(cur.timer)
entries.delete(name)
}
}
}, [name, running])
return stats
}
+375 -54
View File
@@ -50,8 +50,9 @@ h1, h2, h3, p { margin: 0; }
height: var(--titlebar-h); flex-shrink: 0; position: relative; z-index: 10;
display: flex; align-items: center; justify-content: space-between;
padding-left: var(--sp-4);
/* No backdrop blur: the bar is opaque, so blurring behind it showed nothing
and still cost a GPU compositing layer (the GPU is shared with the VM). */
background: var(--surface-chrome);
backdrop-filter: var(--blur-chrome);
border-bottom: 1px solid var(--border);
user-select: none; --wails-draggable: drag;
}
@@ -65,6 +66,35 @@ h1, h2, h3, p { margin: 0; }
display: block; flex-shrink: 0;
}
.titlebar-right { display: flex; align-items: center; height: 100%; gap: var(--sp-1); --wails-draggable: no-drag; }
/* Left of the title bar: sidebar toggle + a small menu bar. Only the controls
opt out of window dragging; the gaps between them still move the window. */
.titlebar-left { display: flex; align-items: center; gap: 2px; height: 100%; margin-left: calc(var(--sp-2) * -1); }
.titlebar-icon, .titlebar-menu {
--wails-draggable: no-drag;
height: 28px; border: none; border-radius: var(--r-sm);
background: transparent; color: var(--text-2); cursor: pointer;
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
}
.titlebar-icon { width: 32px; display: grid; place-items: center; margin-right: 4px; }
.titlebar-menu { padding: 0 10px; font-size: var(--fs-13); font-weight: var(--fw-medium); }
.titlebar-icon:hover, .titlebar-menu:hover { background: var(--surface-hover); color: var(--text); }
.titlebar-menu[data-state="open"] { background: var(--surface-active); color: var(--text); }
.titlebar-icon:active, .titlebar-menu:active { transform: scale(0.96); }
.titlebar-menus { display: flex; align-items: center; gap: 2px; }
.titlebar-menu-content { min-width: 220px; }
/* Menu rows with a trailing shortcut, check marks and group labels. */
.menu-label { flex: 1; min-width: 0; white-space: nowrap; }
.menu-shortcut {
margin-left: 24px; font-family: var(--font-sans); font-size: var(--fs-12);
color: var(--text-3); font-variant-numeric: tabular-nums;
}
.menu-item[data-highlighted] .menu-shortcut { color: rgba(255, 255, 255, 0.78); }
.menu-item.menu-item-check, .menu-indented .menu-item { position: relative; padding-left: 28px; }
.menu-indented .menu-group-label { padding-left: 28px; }
.menu-check { position: absolute; left: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; }
.menu-group-label { padding: 6px 10px 2px; font-size: 11.5px; font-weight: var(--fw-medium); color: var(--text-3); user-select: none; }
.theme-toggle {
width: 30px; height: 28px; margin-right: var(--sp-1);
border: 1px solid var(--border); border-radius: var(--r-md);
@@ -91,16 +121,21 @@ h1, h2, h3, p { margin: 0; }
.sidebar-wrap {
width: var(--sidebar-w); flex-shrink: 0;
padding: 10px;
display: flex;
display: flex; overflow: hidden;
background: var(--surface-sidebar-rail);
border-right: 1px solid var(--border);
transition: width var(--dur-modal) var(--ease-out), padding var(--dur-modal) var(--ease-out), opacity var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out);
}
/* Hidden sidebar (Ctrl+B): slides shut; the card keeps its width so its
contents don't reflow while the rail narrows. */
.workspace.sidebar-hidden .sidebar-wrap { width: 0; padding-left: 0; padding-right: 0; opacity: 0; border-right-color: transparent; }
.sidebar-wrap > .sidebar { min-width: calc(var(--sidebar-w) - 20px); }
.sidebar {
flex: 1; min-height: 0;
display: flex; flex-direction: column; gap: var(--sp-1);
padding: 10px 8px; overflow-y: auto; overscroll-behavior: contain;
/* Translucent over a fixed gradient: a backdrop blur would look the same. */
background: var(--surface-sidebar);
backdrop-filter: var(--blur-chrome);
border: 1px solid var(--surface-sidebar-border);
border-radius: 14px;
box-shadow: var(--surface-sidebar-shadow);
@@ -132,13 +167,14 @@ h1, h2, h3, p { margin: 0; }
background: var(--accent);
color: var(--accent-text);
font-weight: var(--fw-medium);
box-shadow: 0 2px 6px rgba(0, 122, 255, 0.28), inset 0 1px 0 rgba(255, 255, 255, 0.22);
box-shadow: 0 1px 2px rgba(0, 122, 255, 0.22), inset 0 1px 0 rgba(255, 255, 255, 0.18);
}
.nav-item[aria-selected="true"] .nav-icon-badge {
background: rgba(255, 255, 255, 0.22);
color: #ffffff;
box-shadow: none;
}
.nav-item[aria-selected="true"] .nav-icon-art { background: #8d95a9; box-shadow: 0 0 0 1.5px rgba(255, 255, 255, 0.7); }
.nav-item[aria-selected="true"] .status-running {
background: #ffffff;
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.28);
@@ -163,7 +199,9 @@ h1, h2, h3, p { margin: 0; }
display: grid; place-items: center; color: #ffffff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.14), inset 0 1px 0 rgba(255, 255, 255, 0.22);
}
.nav-icon-vm { background: linear-gradient(145deg, #32a0ff 0%, #007aff 100%); }
/* A VM's macOS version artwork (VersionArt) as its icon. */
.nav-icon-art { overflow: hidden; background: #8d95a9; }
.nav-icon-art svg { width: 100%; height: 100%; display: block; }
.nav-icon-host { background: linear-gradient(145deg, #6e7cf0 0%, #4d5be0 100%); }
.nav-icon-settings { background: linear-gradient(145deg, #8e8e93 0%, #636366 100%); }
.nav-icon-installers { background: linear-gradient(145deg, #34c759 0%, #248a3d 100%); }
@@ -189,15 +227,28 @@ h1, h2, h3, p { margin: 0; }
.actions { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
/* ── macOS Tahoe "About This Mac" Hero ─────────────────── */
.vm-page { gap: 14px; padding-bottom: 10px; }
/* A narrower column than other pages: the summary reads as one block, and the
screen scales with window height so "Connection" stays above the fold. */
.page.vm-page { max-width: 568px; gap: 14px; padding-bottom: 10px; }
.vm-hero {
display: flex; flex-direction: column; align-items: center;
gap: 6px; padding: 8px 0 2px; text-align: center;
gap: 6px; padding: 4px 0 2px; text-align: center;
}
.vm-display-unit {
position: relative;
display: flex; flex-direction: column; align-items: center;
margin-bottom: 4px;
transition: transform var(--dur) var(--ease-out);
}
.vm-display-unit.is-actionable { cursor: pointer; }
@media (hover: hover) and (pointer: fine) {
.vm-display-unit.is-actionable:hover { transform: translateY(-2px); }
.vm-display-unit.is-actionable:hover .vm-screen { box-shadow: 0 20px 40px rgba(15, 23, 42, 0.22), 0 4px 10px rgba(15, 23, 42, 0.10), inset 0 1px 0 rgba(255, 255, 255, 0.14); }
.vm-display-unit.is-actionable:hover .vm-screen-play,
.vm-display-unit.is-actionable:hover .vm-screen-chip { opacity: 1; transform: none; }
.vm-display-unit.is-actionable:hover .vm-screen.is-idle .vm-screen-img { filter: saturate(0.7) brightness(0.8); }
}
.vm-display-unit.is-actionable:active { transform: scale(0.985); }
.vm-display-stand {
position: relative; width: 46px; height: 22px; margin-top: -1px;
background: linear-gradient(180deg, #b8bec8 0%, #dcdfe6 46%, #cfd4dc 100%);
@@ -218,18 +269,6 @@ h1, h2, h3, p { margin: 0; }
background: linear-gradient(180deg, #5d606c 0%, #3d4049 100%);
box-shadow: 0 5px 14px rgba(0, 0, 0, 0.52);
}
.vm-imac-wrap {
position: relative; display: inline-grid; place-items: center;
margin-bottom: 2px;
}
.vm-imac-svg {
width: 156px; height: 126px; display: block;
filter: drop-shadow(0 10px 20px rgba(15, 23, 42, 0.14));
transition: transform var(--dur) var(--ease-out), filter var(--dur) var(--ease-out);
}
:root[data-theme="dark"] .vm-imac-svg {
filter: drop-shadow(0 12px 26px rgba(0, 0, 0, 0.48));
}
.vm-hero-name {
margin: 0; max-width: 100%;
font-size: 24px; font-weight: 700; letter-spacing: -0.025em; line-height: 1.2;
@@ -241,54 +280,54 @@ h1, h2, h3, p { margin: 0; }
background: var(--surface-1); border: 1px solid var(--border);
font-size: var(--fs-12); font-weight: var(--fw-medium); color: var(--text-2);
font-variant-numeric: tabular-nums;
transition: background var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out), color var(--dur) var(--ease-out);
}
.vm-hero-pill.is-running {
background: var(--ok-soft); border-color: transparent; color: var(--ok-text);
}
.vm-hero-pill.is-busy {
background: var(--warn-soft); border-color: transparent; color: var(--warn-text);
}
.vm-hero-pill.is-broken {
background: var(--danger-soft); border-color: var(--danger-border); color: var(--danger-text);
}
.vm-hero-uptime { font-weight: var(--fw-regular); }
.vm-hero-actions {
display: flex; align-items: center; justify-content: center; flex-wrap: wrap;
gap: 8px; margin-top: 6px;
}
/* Unified 2x3 Compact Hardware Specs Card (matches mockup) */
/* Summary: 3 × 2. Row 1 (CPU, memory, storage) carries usage bars; the bar slot
is always there so the row keeps its height when the VM starts or stops. */
.vm-spec-card {
margin: 0;
display: grid; grid-template-columns: repeat(3, minmax(0, 1fr));
column-gap: 16px; row-gap: 10px;
padding: 13px 18px;
column-gap: 18px; row-gap: 12px;
padding: 14px 18px;
background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg);
box-shadow: var(--shadow-card);
}
.vm-spec-cell {
display: flex; align-items: center; gap: 8px; min-width: 0;
display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center;
column-gap: 8px; row-gap: 6px; min-width: 0; cursor: default;
}
.vm-spec-cell:focus-visible { box-shadow: none; }
.vm-spec-icon {
color: var(--text-2); display: inline-flex; align-items: center; flex-shrink: 0;
color: var(--text-3); display: inline-flex; align-items: center; flex-shrink: 0;
}
.vm-spec-val {
margin: 0; min-width: 0;
font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text);
font-size: var(--fs-13); font-weight: var(--fw-regular); color: var(--text);
font-variant-numeric: tabular-nums;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; user-select: text;
}
/* Live Telemetry Inset Card */
.vm-telemetry-card {
display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px;
padding: 11px 18px;
background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg);
box-shadow: var(--shadow-card);
.vm-spec-meter {
grid-column: 2; display: block; height: 3px; border-radius: 999px;
background: var(--surface-active); overflow: hidden;
transition: opacity var(--dur) var(--ease-out);
}
.vm-meter { display: flex; flex-direction: column; gap: 7px; min-width: 0; }
.vm-meter-head {
display: flex; align-items: center; gap: 6px;
font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text);
font-variant-numeric: tabular-nums;
}
.vm-meter-head .muted { font-weight: var(--fw-regular); }
.vm-spec-meter[data-idle] { opacity: 0; }
.vm-spec-meter .meter-fill { transition: transform 420ms var(--ease-out), background var(--dur) var(--ease-out); }
/* Compact Single-Row Connection Card (matches mockup) */
.conn-list {
@@ -303,16 +342,33 @@ h1, h2, h3, p { margin: 0; }
content: ""; position: absolute; top: 0; left: 16px; right: 16px; height: 1px; background: var(--border);
}
.conn-main {
display: flex; align-items: center; gap: 6px; min-width: 0; flex: 1;
display: flex; align-items: center; gap: 10px; min-width: 0; flex: 1;
font-size: 13.5px; color: var(--text);
}
.conn-title { font-weight: var(--fw-medium); white-space: nowrap; flex-shrink: 0; }
.conn-dot { color: var(--text-3); flex-shrink: 0; }
.conn-meta {
color: var(--text-2); font-size: var(--fs-13);
min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.conn-status {
display: inline-flex; align-items: center; gap: 6px; flex-shrink: 0;
height: 22px; padding: 0 9px; border-radius: 999px;
background: var(--surface-active); color: var(--text-2);
font-size: var(--fs-12); font-weight: var(--fw-medium); white-space: nowrap; cursor: default;
transition: background var(--dur) var(--ease-out), color var(--dur) var(--ease-out);
}
.conn-status:focus-visible { border-radius: 999px; }
.conn-status-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--status-idle); flex-shrink: 0; }
.conn-status.is-ok { background: var(--ok-soft); color: var(--ok-text); }
.conn-status.is-ok .conn-status-dot { background: var(--status-running); }
.conn-status.is-warn { background: var(--warn-soft); color: var(--warn-text); }
.conn-status.is-warn .conn-status-dot { background: var(--status-busy); }
/* A step that belongs to the row above (the tools install command). */
.conn-row.conn-sub { min-height: 40px; padding-top: 0; padding-left: 28px; }
.conn-row.conn-sub::before { display: none; }
.conn-row.conn-sub .conn-main { flex: 0 0 auto; }
.conn-ctrl { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
.conn-ctrl-grow { flex: 1; flex-shrink: 1; min-width: 0; justify-content: flex-end; }
.conn-ctrl .btn { height: 28px; padding: 0 11px; font-size: 12.5px; }
.ssh-pill {
display: inline-flex; align-items: center; gap: 6px; max-width: 100%;
@@ -426,6 +482,9 @@ h1, h2, h3, p { margin: 0; }
.notice-error .notice-icon { color: var(--danger-text); }
.notice-error ul { margin: 0; padding-left: var(--sp-4); }
.notice-info { background: var(--accent-soft); border-color: transparent; }
.notice-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.notice-title { font-weight: var(--fw-medium); }
.notice-sub { color: var(--text-2); font-variant-numeric: tabular-nums; }
.notice-info .notice-icon { color: var(--accent-soft-text); }
/* Numbered visual stepper for Install / Recovery Guide */
@@ -551,6 +610,50 @@ h1, h2, h3, p { margin: 0; }
}
.empty-panel > svg { opacity: 0.6; }
/* Installers: one major-version card per system, older point releases folded away. */
.installers-page { max-width: 780px; }
.installers-page .page-head { align-items: flex-start; }
.installers-page-title { flex-direction: column; align-items: flex-start; gap: 1px; }
.installers-page-title > span { color: var(--text-3); font-size: var(--fs-12); line-height: 1.45; }
.section-count { min-width: 20px; padding: 1px 7px; border-radius: 999px; background: var(--surface-active); color: var(--text-3); font-size: 11px; font-weight: var(--fw-medium); text-align: center; }
.installer-row { min-height: 62px; }
.installer-art, .release-art { display: block; flex-shrink: 0; overflow: hidden; border-radius: 10px; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.28), 0 2px 5px rgba(15, 23, 42, 0.12); }
.installer-art { width: 36px; height: 36px; }
.installer-art svg, .release-art svg { display: block; width: 100%; height: 100%; }
.release-list { display: flex; flex-direction: column; gap: 10px; }
.release-card { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); box-shadow: var(--shadow-card); overflow: hidden; }
.release-latest { display: flex; align-items: center; gap: 13px; min-height: 76px; padding: 13px 16px; }
.release-art { width: 46px; height: 46px; border-radius: 12px; }
.release-copy { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.release-title { flex-wrap: wrap; gap: 7px; }
.release-title > strong { font-weight: var(--fw-strong); font-variant-numeric: tabular-nums; }
.release-history { border-top: 1px solid var(--border); }
.release-history summary { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 36px; padding: 8px 16px; color: var(--text-2); font-size: var(--fs-12); cursor: pointer; user-select: none; list-style: none; transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out); }
.release-history summary::-webkit-details-marker { display: none; }
.release-history summary:hover { background: var(--surface-hover); color: var(--text); }
.release-history summary:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.release-history summary svg { transition: transform var(--dur) var(--ease-out); }
.release-history[open] summary svg { transform: rotate(180deg); }
.release-history-list { border-top: 1px solid var(--border); background: color-mix(in srgb, var(--surface-canvas) 42%, transparent); }
.release-history-row { display: flex; align-items: center; gap: 14px; min-height: 54px; padding: 9px 16px 9px 75px; position: relative; }
.release-history-row + .release-history-row::before { content: ""; position: absolute; top: 0; left: 75px; right: 16px; height: 1px; background: var(--border); }
.release-history-row .btn { min-height: 28px; }
@media (max-width: 700px) {
.release-latest { align-items: flex-start; flex-wrap: wrap; gap: 10px 12px; }
.release-copy { min-width: calc(100% - 60px); }
.release-latest > .row-right { width: 100%; padding-left: 58px; }
.release-history-row { padding-left: 16px; flex-wrap: wrap; gap: 8px; }
.release-history-row + .release-history-row::before { left: 16px; }
.release-history-row > .row-right { width: 100%; }
.installer-row { flex-wrap: wrap; gap: 10px 12px; }
.installer-row .row-main { min-width: calc(100% - 50px); }
.installer-row > .row-right { width: 100%; padding-left: 48px; }
}
@media (prefers-reduced-motion: reduce) {
.release-history summary, .release-history summary svg { transition: none; }
}
/* macOS Tahoe Switch (spring thumb + Apple active stretch) */
.switch { position: relative; display: inline-block; width: 38px; height: 22px; flex-shrink: 0; cursor: pointer; }
.switch input { position: absolute; opacity: 0; width: 100%; height: 100%; margin: 0; cursor: pointer; }
@@ -576,7 +679,6 @@ h1, h2, h3, p { margin: 0; }
flex-shrink: 0; display: flex; flex-direction: column; position: relative; z-index: 10;
border-top: 1px solid var(--border);
background: var(--surface-statusbar);
backdrop-filter: var(--blur-chrome);
}
.log-resize-handle {
position: absolute; top: -3px; left: 0; right: 0; height: 7px; z-index: 5;
@@ -594,13 +696,30 @@ h1, h2, h3, p { margin: 0; }
}
.logbar { height: var(--logbar-h); display: flex; align-items: center; gap: var(--sp-2); padding: 0 var(--sp-3) 0 var(--sp-4); }
.status-telemetry {
display: inline-flex; align-items: center; gap: 8px; min-width: 0;
display: inline-flex; align-items: center; min-width: 0; margin-left: -8px;
font-size: var(--fs-12); color: var(--text-2); user-select: none;
font-variant-numeric: tabular-nums;
}
/* "Label value" pairs separated by hairlines instead of middle dots. */
.status-metric {
display: inline-flex; align-items: center; gap: 5px; white-space: nowrap;
position: relative; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap;
height: 22px; padding: 0 10px; border-radius: var(--r-sm);
}
.status-metric + .status-metric::before {
content: ""; position: absolute; left: 0; top: 6px; bottom: 6px; width: 1px; background: var(--border-strong);
}
.status-label { color: var(--text-3); }
.status-value { color: var(--text-2); }
.status-metric.warn .status-value, .status-metric.warn .status-label { color: var(--warn-text); }
.status-metric.high .status-value, .status-metric.high .status-label { color: var(--danger-text); }
.status-metric.ok .status-value { color: var(--text-2); }
button.status-issue {
border: none; background: var(--warn-soft); color: var(--warn-text); font: inherit; font-weight: var(--fw-medium);
cursor: pointer; transition: filter var(--dur-fast) var(--ease-out);
}
button.status-issue:hover { filter: brightness(0.96); }
button.status-issue + .status-metric::before { display: none; }
button.status-issue + .status-metric { margin-left: 6px; }
.status-metric > svg { color: var(--text-3); flex-shrink: 0; }
.status-metric.warn { color: var(--warn-text); }
.status-metric.warn > svg { color: var(--warn-text); }
@@ -1060,7 +1179,8 @@ h1, h2, h3, p { margin: 0; }
/* VM screen thumbnail: compact Studio Display bezel matching mockup */
.vm-screen {
position: relative; width: 268px; max-width: 100%; aspect-ratio: 16 / 10;
position: relative; width: clamp(196px, 31vh, 260px); max-width: 100%; aspect-ratio: 16 / 10;
transition: box-shadow var(--dur) var(--ease-out);
border-radius: 10px; overflow: hidden;
border: 6px solid #1b1c20; background-color: #111216; background-size: cover; background-position: center;
box-shadow: 0 14px 32px rgba(15, 23, 42, 0.18), 0 3px 8px rgba(15, 23, 42, 0.08), inset 0 1px 0 rgba(255, 255, 255, 0.14);
@@ -1073,26 +1193,38 @@ h1, h2, h3, p { margin: 0; }
border-color: #0b0c0f;
box-shadow: 0 18px 42px rgba(0, 0, 0, 0.56), 0 0 0 1px rgba(255, 255, 255, 0.10);
}
.vm-screen-img { display: block; width: 100%; height: 100%; object-fit: cover; animation: fade-in var(--dur-modal) var(--ease-out) both; user-select: none; }
.vm-screen.is-idle .vm-screen-img { filter: saturate(0.50) brightness(0.65); transition: filter var(--dur-modal) var(--ease-out); }
.vm-screen-img {
display: block; width: 100%; height: 100%; object-fit: cover; user-select: none;
animation: fade-in var(--dur-modal) var(--ease-out) both;
transition: filter 420ms var(--ease-out);
}
.vm-screen.is-idle .vm-screen-img { filter: saturate(0.50) brightness(0.65); }
.vm-screen-art { display: block; width: 100%; height: 100%; }
.vm-screen-live {
position: absolute; top: 8px; right: 8px; z-index: 2;
width: 8px; height: 8px; border-radius: 50%;
background: var(--status-running); box-shadow: 0 0 0 3px rgba(40, 205, 65, 0.30);
animation: pulse 2.2s ease-in-out infinite;
}
/* Pointer shortcuts on the screen; shown on hover only, since the Start / Show
Window buttons below already say the same thing. */
.vm-screen-play {
position: absolute; inset: 0; z-index: 2; margin: auto; width: 44px; height: 44px; padding-left: 2px;
display: grid; place-items: center; border: none; border-radius: 50%; cursor: pointer;
background: rgba(255, 255, 255, 0.90); color: #1d1d1f;
display: grid; place-items: center; border-radius: 50%; pointer-events: none;
background: rgba(255, 255, 255, 0.92); color: #1d1d1f;
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.30), inset 0 1px 0 rgba(255, 255, 255, 0.85);
backdrop-filter: blur(12px);
transition: transform var(--dur) var(--ease-out), background var(--dur-fast) var(--ease-out);
opacity: 0; transform: scale(0.9);
transition: opacity var(--dur) var(--ease-out), transform var(--dur) var(--ease-out);
}
@media (hover: hover) and (pointer: fine) {
.vm-screen-play:hover { transform: scale(1.08); background: #ffffff; }
.vm-screen-chip {
position: absolute; left: 50%; bottom: 10px; z-index: 2; margin-left: -60px; width: 120px;
display: inline-flex; align-items: center; justify-content: center; gap: 5px;
height: 26px; border-radius: 999px; pointer-events: none;
background: rgba(20, 21, 26, 0.72); color: #fff; backdrop-filter: blur(10px);
font-size: var(--fs-12); font-weight: var(--fw-medium);
opacity: 0; transform: translateY(4px);
transition: opacity var(--dur) var(--ease-out), transform var(--dur) var(--ease-out);
}
.vm-screen-play:active { transform: scale(0.95); }
/* New-VM wizard: source cards */
.source-cards { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
@@ -1129,11 +1261,200 @@ h1, h2, h3, p { margin: 0; }
/* The assistant keeps one size across steps, like macOS setup assistants. */
.dialog.wizard-dialog { width: 760px; height: min(660px, calc(100vh - 80px)); }
/* Processor affinity / CPU core mapping dialog */
.dialog.affinity-dialog { width: 640px; max-width: calc(100vw - 48px); }
.affinity-body { display: flex; flex-direction: column; gap: 12px; }
.affinity-mode-bar { display: flex; flex-direction: column; gap: 6px; }
.affinity-hint { font-size: var(--fs-12); color: var(--text-3); }
.affinity-quick-bar { display: flex; flex-wrap: wrap; gap: 6px; }
.affinity-chip {
height: 26px; padding: 0 10px; border-radius: 999px;
border: 1px solid var(--border-strong); background: var(--surface-1); color: var(--text-2);
font-size: var(--fs-12); font-weight: var(--fw-medium); cursor: pointer;
transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out);
}
.affinity-chip:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); }
.affinity-chip.is-active { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
.affinity-chip:disabled { opacity: 0.45; cursor: not-allowed; }
.affinity-grid {
display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px;
max-height: 248px; overflow-y: auto; padding: 2px;
}
.affinity-cpu {
display: flex; align-items: center; gap: 7px; padding: 7px 9px;
border-radius: var(--r-md); border: 1px solid var(--border-strong);
background: var(--surface-1); color: var(--text-2); cursor: pointer; text-align: left;
transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
}
.affinity-cpu:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); }
.affinity-cpu:active:not(:disabled) { transform: scale(0.98); }
.affinity-cpu.is-checked { border-color: var(--accent); background: var(--accent-soft); color: var(--text); }
.affinity-cpu.is-lpe:not(.is-checked) { opacity: 0.72; }
.affinity-check {
width: 16px; height: 16px; border-radius: 4px; flex-shrink: 0;
border: 1.5px solid var(--border-strong); background: var(--surface-0);
display: grid; place-items: center; color: #fff;
}
.affinity-cpu.is-checked .affinity-check { border-color: var(--accent); background: var(--accent); }
.affinity-cpu-name { font-size: var(--fs-12); font-weight: var(--fw-medium); white-space: nowrap; }
.affinity-cpu-meta { margin-left: auto; display: inline-flex; align-items: center; gap: 4px; }
.affinity-core-tag { font-size: 10px; color: var(--text-3); }
.affinity-tier {
font-size: 10px; font-weight: var(--fw-strong); line-height: 1; padding: 2px 5px; border-radius: 999px;
}
.affinity-tier.tier-p { background: rgba(0, 122, 255, 0.14); color: var(--accent); }
.affinity-tier.tier-e { background: rgba(52, 199, 89, 0.15); color: var(--status-running); }
.affinity-tier.tier-lpe { background: rgba(255, 159, 10, 0.16); color: var(--status-busy); }
.affinity-summary {
display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px;
padding: 8px 10px; border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border);
font-size: var(--fs-12); color: var(--text-2);
}
.affinity-summary > span { display: inline-flex; align-items: center; gap: 5px; }
.affinity-live { color: var(--status-running); }
.affinity-eco-row {
display: flex; align-items: center; justify-content: space-between; gap: 12px;
padding: 10px 12px; border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border);
}
/* Reduced motion: stop decorative loops & positional motion */
@media (prefers-reduced-motion: reduce) {
.status-busy, .vm-screen-live, .skeleton-bar { animation: none; }
.vm-display-unit, .vm-display-unit.is-actionable:hover, .vm-display-unit.is-actionable:active { transform: none; }
.vm-screen-img, .vm-spec-meter .meter-fill { transition: none; }
.page, .dialog, .menu, .tooltip, .pane-anim, .step-anim, .toast[data-state="open"], .toast[data-state="closed"] {
animation-name: fade-in;
animation-duration: 140ms;
}
}
/* ── v0.2.6 Enhancements: Screenshot, Note, Dropzone, Snapshots, Log Filter, Welcome ── */
.vm-screen.is-live { cursor: pointer; }
.vm-screen-shot {
position: absolute; right: 8px; bottom: 8px; z-index: 3;
width: 30px; height: 30px; border: 1px solid rgba(255, 255, 255, 0.22); border-radius: 8px;
display: grid; place-items: center; cursor: pointer;
background: rgba(20, 22, 28, 0.68); color: #ffffff;
backdrop-filter: blur(10px);
opacity: 0; transform: translateY(3px);
transition: opacity var(--dur-fast) var(--ease-out), transform var(--dur-fast) var(--ease-out), background var(--dur-fast) var(--ease-out);
}
.vm-screen:hover .vm-screen-shot,
.vm-screen-shot:focus-visible { opacity: 1; transform: translateY(0); }
.vm-screen-shot:hover { background: rgba(20, 22, 28, 0.88); }
.vm-screen-shot:active { transform: scale(0.94); }
/* The title is the display name; click to rename in place. The pencil hangs
outside the text so the name stays centred. */
.vm-name-btn {
position: relative; display: inline-flex; align-items: center; max-width: 100%;
padding: 0 6px; border: none; border-radius: var(--r-md);
background: transparent; color: inherit; font: inherit; letter-spacing: inherit; cursor: text;
transition: background var(--dur-fast) var(--ease-out);
}
.vm-name-btn > span { overflow-wrap: anywhere; }
.vm-name-btn:hover { background: var(--surface-hover); }
.vm-name-pencil {
position: absolute; left: 100%; top: 50%; margin-left: 6px; transform: translateY(-50%);
color: var(--text-3); opacity: 0; transition: opacity var(--dur-fast) var(--ease-out);
}
.vm-name-btn:hover .vm-name-pencil, .vm-name-btn:focus-visible .vm-name-pencil { opacity: 1; }
.vm-name-input {
width: min(100%, 380px); height: 36px; padding: 0 10px; text-align: center;
border-radius: var(--r-md); border: 1px solid var(--accent); background: var(--surface-input);
color: var(--text); font-family: inherit; font-size: 24px; font-weight: 700; letter-spacing: -0.025em;
box-shadow: var(--focus-ring);
}
/* Screen + summary. Stacked by default; once the content column is wide
enough the summary becomes one labelled column beside the screen, like
"About This Mac". */
.scroll { container-type: inline-size; }
.vm-top { display: flex; flex-direction: column; gap: 14px; }
.vm-spec-label { display: none; }
@container (min-width: 760px) {
.page.vm-page { max-width: 880px; }
.vm-top {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(280px, 340px);
align-items: center; gap: 28px; padding: 6px 0 4px;
}
.vm-spec-card { grid-template-columns: minmax(0, 1fr); row-gap: 12px; padding: 16px 18px; }
/* One line per fact: icon · label · value · short usage bar at the end.
Every row has the same height, and a bar appearing or hiding when the VM
starts or stops doesn't move anything. */
.vm-spec-cell { grid-template-columns: auto 4.5em minmax(0, 1fr) 56px; column-gap: 10px; min-height: 22px; }
.vm-spec-label { display: block; font-size: var(--fs-13); color: var(--text-3); white-space: nowrap; }
.vm-spec-meter { grid-column: 4; grid-row: 1; align-self: center; }
/* Rows without a bar (graphics, network, language) give its column to the value. */
.vm-spec-cell:not(:has(.vm-spec-meter)) .vm-spec-val { grid-column: 3 / 5; }
.vm-screen { width: clamp(220px, 34vh, 300px); }
}
.vm-page-drop { position: relative; }
.drop-banner {
position: sticky; top: 0; z-index: 20;
display: flex; align-items: center; justify-content: center; gap: 8px;
padding: 12px 16px; border-radius: var(--r-lg);
background: var(--accent-soft); border: 1.5px dashed var(--accent);
color: var(--accent-soft-text); font-size: var(--fs-13); font-weight: var(--fw-medium);
backdrop-filter: var(--blur-overlay);
}
/* Interactive install stepper */
.guide-step-btn {
width: 22px; height: 22px; padding: 0; border-radius: 50%; flex-shrink: 0; margin-top: 1px;
display: grid; place-items: center; border: none; cursor: pointer;
background: var(--accent-soft); color: var(--accent-soft-text);
font-size: var(--fs-11); font-weight: var(--fw-strong); font-variant-numeric: tabular-nums;
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
}
.guide-step-btn:active { transform: scale(0.92); }
.guide-step-btn.done { background: var(--ok-soft); color: var(--ok-text); }
.guide-step.is-done .guide-step-body { opacity: 0.62; }
/* Inline snapshot creation bar */
.snap-create-bar {
display: flex; align-items: center; gap: 8px;
padding: 10px 16px; background: var(--surface-1);
border-bottom: 1px solid var(--border);
}
.snap-create-bar .input { flex: 1; height: 29px; }
.snap-meta-hint { font-size: var(--fs-12); font-weight: var(--fw-regular); color: var(--text-3); }
/* Log filter controls */
.log-filter-input {
width: 148px; height: 22px; padding: 0 8px;
border-radius: var(--r-sm); border: 1px solid var(--border-strong);
background: var(--surface-input); color: var(--text); font: inherit; font-size: var(--fs-12);
}
.log-filter-input:focus { border-color: var(--accent); box-shadow: var(--focus-ring); }
.log-filter-pill {
height: 22px; padding: 0 8px; border-radius: var(--r-sm);
border: 1px solid var(--border); background: transparent;
color: var(--text-3); font-size: 11.5px; cursor: pointer;
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out);
}
.log-filter-pill:hover { color: var(--text); background: var(--surface-hover); }
.log-filter-pill[aria-pressed="true"] { background: var(--warn-soft); border-color: transparent; color: var(--warn-text); font-weight: var(--fw-medium); }
/* Storage breakdown bar (Engine page) */
.storage-bar {
display: flex; height: 8px; border-radius: 999px; overflow: hidden;
background: var(--surface-active); gap: 2px;
}
.storage-seg-vms { background: var(--accent); }
.storage-seg-inst { background: var(--status-running); }
.storage-seg-rt { background: #7a78ff; }
.storage-legend { display: flex; flex-wrap: wrap; gap: 14px; font-size: var(--fs-12); color: var(--text-2); font-variant-numeric: tabular-nums; }
.storage-legend-item { display: inline-flex; align-items: center; gap: 6px; }
.storage-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
/* Zero-VM welcome state */
.welcome-card {
display: flex; flex-direction: column; align-items: center; text-align: center; gap: 12px;
padding: 40px 28px; margin-top: 24px;
background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-xl);
box-shadow: var(--shadow-card);
}
.welcome-card h1 { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; }
.welcome-card p { font-size: var(--fs-13); color: var(--text-2); max-width: 380px; }
+13
View File
@@ -20,6 +20,7 @@ export type DisplayInfo = host.DisplayInfo
export type DisplayPreset = host.DisplayPreset
export type AudioInfo = host.AudioInfo
export type WHPXCapabilities = host.WHPXCapabilities
export type LogicalCPUInfo = host.LogicalCPUInfo
export type GPUInfo = Model<host.GPUInfo> & {
kind: 'discrete' | 'integrated' | 'virtual' | 'unknown'
@@ -65,11 +66,23 @@ export type AppUpdateInfo = version.UpdateInfo
export type VMDetail = reims.VMDetail
export type VMStats = app.VMStats
export type DriveShareSettings = Model<app.DriveShareSettings>
export type VMAffinityMode = 'auto' | 'all' | 'pcores' | 'non_lpe' | 'custom'
export type VMAffinityUpdate = {
mode: VMAffinityMode
cpus?: number[]
disable_eco_qos: boolean
}
export type VMAffinityStatus = Omit<Model<app.VMAffinityStatus>, 'mode' | 'effective_mode'> & {
mode: VMAffinityMode
effective_mode: VMAffinityMode
}
/** One frame of a VM's screen (internal/app/thumbnail_flow.go). Empty data_url: none yet. */
export type VMThumbnail = app.VMThumbnail
export type ValidationIssue = reims.ValidationIssue
export type DiskResizeResult = reims.DiskResizeResult
export type DiskCompactResult = reims.DiskCompactResult
export type DiskSnapshot = reims.DiskSnapshot
export type StorageBreakdown = Model<app.StorageBreakdown>
export type SetOpts = reims.SetOpts
export type CreateOpts = Model<reims.CreateOpts> & {
+6 -1
View File
@@ -3,12 +3,14 @@
// re-typed here; everything else passes through unchanged.
import * as Go from '../wailsjs/go/app/App'
import { EventsOn } from '../wailsjs/runtime/runtime'
import type { AppState, CachedInstaller, DataRootChoice, LogEntry, RemoteRuntime, Task } from './types'
import type { AppState, CachedInstaller, DataRootChoice, LogEntry, RemoteRuntime, Task, VMAffinityStatus, VMAffinityUpdate } from './types'
export const api = {
...Go,
GetState: Go.GetState as () => Promise<AppState>,
GetTasks: Go.GetTasks as () => Promise<Task[]>,
GetVMAffinity: Go.GetVMAffinity as (name: string) => Promise<VMAffinityStatus>,
SetVMAffinity: Go.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
ListInstallers: Go.ListInstallers as () => Promise<CachedInstaller[] | null>,
ListRemoteRuntimes: Go.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
SuggestDataRoots: Go.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
@@ -18,4 +20,7 @@ export const events = {
onTask: (cb: (task: Task) => void) => EventsOn('reims:task', cb),
onStateChanged: (cb: () => void) => EventsOn('reims:state-changed', cb),
onLog: (cb: (entry: LogEntry) => void) => EventsOn('reims:log', cb),
// Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…".
onTraySelectVM: (cb: (name: string) => void) => EventsOn('reims:tray-select-vm', cb),
onTrayNewVM: (cb: () => void) => EventsOn('reims:tray-new-vm', cb),
}
+36
View File
@@ -24,14 +24,22 @@ export function CompactVMDisk(arg1:string):Promise<reims.DiskCompactResult>;
export function CompleteSetup(arg1:string):Promise<void>;
export function CopyVMScreenshot(arg1:string):Promise<void>;
export function CreateSnapshot(arg1:string,arg2:string):Promise<void>;
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
export function DeleteInstaller(arg1:string):Promise<void>;
export function DeleteSnapshot(arg1:string,arg2:string):Promise<void>;
export function DeleteVM(arg1:string,arg2:boolean):Promise<void>;
export function DeliverFileToGuest(arg1:string):Promise<string>;
export function DeliverPathsToGuest(arg1:string,arg2:Array<string>):Promise<Array<string>>;
export function DetachGuestTools(arg1:string):Promise<void>;
export function DismissTask(arg1:string):Promise<void>;
@@ -50,14 +58,26 @@ export function ExportDiagnostics(arg1:string):Promise<string>;
export function FinishInstall(arg1:string):Promise<void>;
export function FocusVMWindow(arg1:string):Promise<void>;
export function GetState():Promise<app.AppState>;
export function GetStorageBreakdown():Promise<app.StorageBreakdown>;
export function GetTasks():Promise<Array<app.Task>>;
export function GetVMAffinity(arg1:string):Promise<app.VMAffinityStatus>;
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
export function GetVMDriveShareSettings(arg1:string):Promise<app.DriveShareSettings>;
export function GetVMMacOS(arg1:string):Promise<string>;
export function GetVMNote(arg1:string):Promise<string>;
export function GetVMSSHUser(arg1:string):Promise<string>;
export function GetVMStats(arg1:string):Promise<app.VMStats>;
export function GetVMThumbnail(arg1:string):Promise<app.VMThumbnail>;
@@ -72,14 +92,20 @@ export function ListOfflineReleases():Promise<Array<installer.Release>>;
export function ListRemoteRuntimes():Promise<Array<runtime.Remote>>;
export function ListSnapshots(arg1:string):Promise<Array<reims.DiskSnapshot>>;
export function OpenProcessorScheduling():Promise<void>;
export function OpenSSHTerminal(arg1:string,arg2:string):Promise<void>;
export function OpenSharedFolder(arg1:string):Promise<void>;
export function OpenURL(arg1:string):Promise<void>;
export function OpenVMFolder(arg1:string):Promise<void>;
export function OpenVSCodeSSH(arg1:string,arg2:string):Promise<void>;
export function PickDirectory(arg1:string):Promise<string>;
export function PickFile(arg1:string,arg2:string):Promise<string>;
@@ -96,6 +122,8 @@ export function ResizeVMDisk(arg1:string,arg2:string):Promise<reims.DiskResizeRe
export function RestartVM(arg1:string):Promise<void>;
export function RestoreSnapshot(arg1:string,arg2:string):Promise<void>;
export function SetAutoPinPCores(arg1:boolean):Promise<void>;
export function SetDataRoot(arg1:string):Promise<void>;
@@ -110,8 +138,14 @@ export function SetRuntimeChannel(arg1:string):Promise<void>;
export function SetRuntimeSource(arg1:string):Promise<void>;
export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
export function SetVMNote(arg1:string,arg2:string):Promise<void>;
export function SetVMSSHUser(arg1:string,arg2:string):Promise<void>;
export function ShowMainWindow():Promise<void>;
export function StartVM(arg1:string):Promise<void>;
@@ -133,3 +167,5 @@ export function UseRuntime(arg1:string):Promise<void>;
export function ValidateCreate(arg1:reims.CreateOpts):Promise<Array<reims.ValidationIssue>>;
export function ValidateSet(arg1:reims.SetOpts):Promise<Array<reims.ValidationIssue>>;
export function WriteSSHConfig(arg1:string,arg2:string):Promise<string>;
+72
View File
@@ -38,6 +38,14 @@ export function CompleteSetup(arg1) {
return window['go']['app']['App']['CompleteSetup'](arg1);
}
export function CopyVMScreenshot(arg1) {
return window['go']['app']['App']['CopyVMScreenshot'](arg1);
}
export function CreateSnapshot(arg1, arg2) {
return window['go']['app']['App']['CreateSnapshot'](arg1, arg2);
}
export function CreateVM(arg1) {
return window['go']['app']['App']['CreateVM'](arg1);
}
@@ -46,6 +54,10 @@ export function DeleteInstaller(arg1) {
return window['go']['app']['App']['DeleteInstaller'](arg1);
}
export function DeleteSnapshot(arg1, arg2) {
return window['go']['app']['App']['DeleteSnapshot'](arg1, arg2);
}
export function DeleteVM(arg1, arg2) {
return window['go']['app']['App']['DeleteVM'](arg1, arg2);
}
@@ -54,6 +66,10 @@ export function DeliverFileToGuest(arg1) {
return window['go']['app']['App']['DeliverFileToGuest'](arg1);
}
export function DeliverPathsToGuest(arg1, arg2) {
return window['go']['app']['App']['DeliverPathsToGuest'](arg1, arg2);
}
export function DetachGuestTools(arg1) {
return window['go']['app']['App']['DetachGuestTools'](arg1);
}
@@ -90,14 +106,26 @@ export function FinishInstall(arg1) {
return window['go']['app']['App']['FinishInstall'](arg1);
}
export function FocusVMWindow(arg1) {
return window['go']['app']['App']['FocusVMWindow'](arg1);
}
export function GetState() {
return window['go']['app']['App']['GetState']();
}
export function GetStorageBreakdown() {
return window['go']['app']['App']['GetStorageBreakdown']();
}
export function GetTasks() {
return window['go']['app']['App']['GetTasks']();
}
export function GetVMAffinity(arg1) {
return window['go']['app']['App']['GetVMAffinity'](arg1);
}
export function GetVMDetail(arg1) {
return window['go']['app']['App']['GetVMDetail'](arg1);
}
@@ -106,6 +134,18 @@ export function GetVMDriveShareSettings(arg1) {
return window['go']['app']['App']['GetVMDriveShareSettings'](arg1);
}
export function GetVMMacOS(arg1) {
return window['go']['app']['App']['GetVMMacOS'](arg1);
}
export function GetVMNote(arg1) {
return window['go']['app']['App']['GetVMNote'](arg1);
}
export function GetVMSSHUser(arg1) {
return window['go']['app']['App']['GetVMSSHUser'](arg1);
}
export function GetVMStats(arg1) {
return window['go']['app']['App']['GetVMStats'](arg1);
}
@@ -134,10 +174,18 @@ export function ListRemoteRuntimes() {
return window['go']['app']['App']['ListRemoteRuntimes']();
}
export function ListSnapshots(arg1) {
return window['go']['app']['App']['ListSnapshots'](arg1);
}
export function OpenProcessorScheduling() {
return window['go']['app']['App']['OpenProcessorScheduling']();
}
export function OpenSSHTerminal(arg1, arg2) {
return window['go']['app']['App']['OpenSSHTerminal'](arg1, arg2);
}
export function OpenSharedFolder(arg1) {
return window['go']['app']['App']['OpenSharedFolder'](arg1);
}
@@ -150,6 +198,10 @@ export function OpenVMFolder(arg1) {
return window['go']['app']['App']['OpenVMFolder'](arg1);
}
export function OpenVSCodeSSH(arg1, arg2) {
return window['go']['app']['App']['OpenVSCodeSSH'](arg1, arg2);
}
export function PickDirectory(arg1) {
return window['go']['app']['App']['PickDirectory'](arg1);
}
@@ -182,6 +234,10 @@ export function RestartVM(arg1) {
return window['go']['app']['App']['RestartVM'](arg1);
}
export function RestoreSnapshot(arg1, arg2) {
return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2);
}
export function SetAutoPinPCores(arg1) {
return window['go']['app']['App']['SetAutoPinPCores'](arg1);
}
@@ -210,10 +266,22 @@ export function SetRuntimeSource(arg1) {
return window['go']['app']['App']['SetRuntimeSource'](arg1);
}
export function SetVMAffinity(arg1, arg2) {
return window['go']['app']['App']['SetVMAffinity'](arg1, arg2);
}
export function SetVMDriveShareSettings(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
}
export function SetVMNote(arg1, arg2) {
return window['go']['app']['App']['SetVMNote'](arg1, arg2);
}
export function SetVMSSHUser(arg1, arg2) {
return window['go']['app']['App']['SetVMSSHUser'](arg1, arg2);
}
export function ShowMainWindow() {
return window['go']['app']['App']['ShowMainWindow']();
}
@@ -257,3 +325,7 @@ export function ValidateCreate(arg1) {
export function ValidateSet(arg1) {
return window['go']['app']['App']['ValidateSet'](arg1);
}
export function WriteSSHConfig(arg1, arg2) {
return window['go']['app']['App']['WriteSSHConfig'](arg1, arg2);
}
+143
View File
@@ -160,6 +160,58 @@ export namespace app {
this.to = source["to"];
}
}
export class VMStorageItem {
name: string;
bytes: number;
static createFrom(source: any = {}) {
return new VMStorageItem(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.name = source["name"];
this.bytes = source["bytes"];
}
}
export class StorageBreakdown {
vms_bytes: number;
installers_bytes: number;
runtimes_bytes: number;
total_bytes: number;
vms: VMStorageItem[];
static createFrom(source: any = {}) {
return new StorageBreakdown(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.vms_bytes = source["vms_bytes"];
this.installers_bytes = source["installers_bytes"];
this.runtimes_bytes = source["runtimes_bytes"];
this.total_bytes = source["total_bytes"];
this.vms = this.convertValues(source["vms"], VMStorageItem);
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice && a.map) {
return (a as any[]).map(elem => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
export class Task {
id: string;
kind: string;
@@ -200,6 +252,58 @@ export namespace app {
this.updated_at = source["updated_at"];
}
}
export class VMAffinityStatus {
mode: string;
cpus: number[];
disable_eco_qos: boolean;
effective_mode: string;
effective_cpus: number[];
effective_mask_hex: string;
vcpus: number;
oversubscribed: boolean;
running: boolean;
pid?: number;
live_cpus?: number[];
live_mask_hex?: string;
live_read_error?: string;
static createFrom(source: any = {}) {
return new VMAffinityStatus(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.mode = source["mode"];
this.cpus = source["cpus"];
this.disable_eco_qos = source["disable_eco_qos"];
this.effective_mode = source["effective_mode"];
this.effective_cpus = source["effective_cpus"];
this.effective_mask_hex = source["effective_mask_hex"];
this.vcpus = source["vcpus"];
this.oversubscribed = source["oversubscribed"];
this.running = source["running"];
this.pid = source["pid"];
this.live_cpus = source["live_cpus"];
this.live_mask_hex = source["live_mask_hex"];
this.live_read_error = source["live_read_error"];
}
}
export class VMAffinityUpdate {
mode: string;
cpus?: number[];
disable_eco_qos: boolean;
static createFrom(source: any = {}) {
return new VMAffinityUpdate(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.mode = source["mode"];
this.cpus = source["cpus"];
this.disable_eco_qos = source["disable_eco_qos"];
}
}
export class VMStats {
name: string;
running: boolean;
@@ -236,6 +340,7 @@ export namespace app {
this.guest_tools_sleep_guard = source["guest_tools_sleep_guard"];
}
}
export class VMThumbnail {
data_url: string;
captured_at: number;
@@ -368,6 +473,24 @@ export namespace host {
this.kind = source["kind"];
}
}
export class LogicalCPUInfo {
index: number;
core_index: number;
tier: string;
smt: boolean;
static createFrom(source: any = {}) {
return new LogicalCPUInfo(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.index = source["index"];
this.core_index = source["core_index"];
this.tier = source["tier"];
this.smt = source["smt"];
}
}
export class Optimization {
id: string;
status: string;
@@ -424,6 +547,7 @@ export namespace host {
non_lpe_mask?: number;
non_lpe_mask_hex?: string;
non_lpe_logical_cpus?: number[];
cpu_topology?: LogicalCPUInfo[];
total_ram_gb: number;
avail_ram_gb: number;
memory_load_pct: number;
@@ -467,6 +591,7 @@ export namespace host {
this.non_lpe_mask = source["non_lpe_mask"];
this.non_lpe_mask_hex = source["non_lpe_mask_hex"];
this.non_lpe_logical_cpus = source["non_lpe_logical_cpus"];
this.cpu_topology = this.convertValues(source["cpu_topology"], LogicalCPUInfo);
this.total_ram_gb = source["total_ram_gb"];
this.avail_ram_gb = source["avail_ram_gb"];
this.memory_load_pct = source["memory_load_pct"];
@@ -660,6 +785,24 @@ export namespace reims {
this.guest_expand_cmd = source["guest_expand_cmd"];
}
}
export class DiskSnapshot {
id: string;
name: string;
created_at: number;
vm_state_bytes: number;
static createFrom(source: any = {}) {
return new DiskSnapshot(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.name = source["name"];
this.created_at = source["created_at"];
this.vm_state_bytes = source["vm_state_bytes"];
}
}
export class SetOpts {
name: string;
cpus?: number;
+160
View File
@@ -0,0 +1,160 @@
package app
import (
"context"
"fmt"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// VMAffinityUpdate is the payload passed from the UI to save and live-apply a
// VM's CPU affinity mapping and EcoQoS power-throttling policy.
type VMAffinityUpdate struct {
Mode string `json:"mode"`
CPUs []int `json:"cpus,omitempty"`
DisableEcoQoS bool `json:"disable_eco_qos"`
}
// VMAffinityStatus describes both the saved per-VM affinity policy and the live
// QEMU process affinity state (when the VM is running).
type VMAffinityStatus struct {
Mode string `json:"mode"`
CPUs []int `json:"cpus"`
DisableEcoQoS bool `json:"disable_eco_qos"`
EffectiveMode string `json:"effective_mode"`
EffectiveCPUs []int `json:"effective_cpus"`
EffectiveMaskHex string `json:"effective_mask_hex"`
VCPUs int `json:"vcpus"`
Oversubscribed bool `json:"oversubscribed"`
Running bool `json:"running"`
PID int `json:"pid,omitempty"`
LiveCPUs []int `json:"live_cpus,omitempty"`
LiveMaskHex string `json:"live_mask_hex,omitempty"`
LiveReadError string `json:"live_read_error,omitempty"`
}
func (a *App) findRunningVMPID(ctx context.Context, name string) int {
if c, err := a.client(); err == nil {
if vms, lerr := c.List(ctx); lerr == nil {
for _, vm := range vms {
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
return *vm.PID
}
}
return 0
}
}
a.mu.Lock()
defer a.mu.Unlock()
for _, vm := range a.lastVMs {
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
return *vm.PID
}
}
return 0
}
func buildVMAffinityStatus(detail reims.VMDetail, rep host.Report, globalAutoPin bool, pid int) VMAffinityStatus {
cfg := vmstart.ReadVMAffinity(detail.Directory)
res := vmstart.ResolveVMAffinity(cfg, globalAutoPin, rep, detail.CPUs)
savedCPUs := cfg.CPUs
if savedCPUs == nil {
savedCPUs = []int{}
}
effCPUs := res.CPUs
if effCPUs == nil {
effCPUs = []int{}
}
st := VMAffinityStatus{
Mode: string(res.ConfigMode),
CPUs: savedCPUs,
DisableEcoQoS: res.DisableEcoQoS,
EffectiveMode: string(res.EffectiveMode),
EffectiveCPUs: effCPUs,
EffectiveMaskHex: res.MaskHex,
VCPUs: detail.CPUs,
Oversubscribed: detail.CPUs > 0 && len(effCPUs) > 0 && len(effCPUs) < detail.CPUs,
Running: detail.State == "running" || pid > 0,
PID: pid,
}
if pid > 0 {
if procMask, _, err := host.GetProcessAffinityMask(uint32(pid)); err == nil {
limit := rep.LogicalCPUs
if limit <= 0 || limit > 64 {
limit = 64
}
st.LiveCPUs = host.MaskToCPUs(procMask, limit)
st.LiveMaskHex = fmt.Sprintf("0x%X", procMask)
} else {
st.LiveReadError = err.Error()
}
}
return st
}
// GetVMAffinity returns the per-VM processor affinity configuration, resolved
// effective CPU set, and live QEMU process affinity mask when running.
func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
detail, err := a.GetVMDetail(name)
if err != nil {
return VMAffinityStatus{}, err
}
a.mu.Lock()
root := a.cfg.DataRoot
globalAutoPin := a.cfg.AutoPinPCores
a.mu.Unlock()
rep := host.Inspect(root)
pid := 0
if detail.State == "running" {
pid = a.findRunningVMPID(a.baseCtx(), name)
}
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), nil
}
// SetVMAffinity saves a VM's processor affinity mapping and immediately applies
// it (plus EcoQoS power-throttling control) to the running QEMU process if active.
func (a *App) SetVMAffinity(name string, req VMAffinityUpdate) (VMAffinityStatus, error) {
detail, err := a.GetVMDetail(name)
if err != nil {
return VMAffinityStatus{}, err
}
if detail.Directory == "" {
return VMAffinityStatus{}, fmt.Errorf("VM %s has no directory", name)
}
a.mu.Lock()
root := a.cfg.DataRoot
globalAutoPin := a.cfg.AutoPinPCores
loc := a.cfg.Locale
a.mu.Unlock()
rep := host.Inspect(root)
eco := req.DisableEcoQoS
if _, err := vmstart.SaveVMAffinity(detail.Directory, vmstart.VMAffinityConfig{
Mode: vmstart.AffinityMode(req.Mode),
CPUs: req.CPUs,
DisableEcoQoS: &eco,
}, rep.LogicalCPUs); err != nil {
return VMAffinityStatus{}, err
}
pid := 0
if detail.State == "running" {
pid = a.findRunningVMPID(a.baseCtx(), name)
}
if pid > 0 {
line, applyErr := vmstart.ApplyVMAffinity(loc, rep, detail.Directory, globalAutoPin, pid, detail.CPUs, true)
if line != "" {
a.emitLog(name, line)
}
if applyErr != nil {
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), applyErr
}
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), nil
}
+46
View File
@@ -0,0 +1,46 @@
package app
import (
"reflect"
"testing"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/vmstart"
)
func TestBuildVMAffinityStatus(t *testing.T) {
dir := t.TempDir()
eco := true
if _, err := vmstart.SaveVMAffinity(dir, vmstart.VMAffinityConfig{
Mode: vmstart.AffinityCustom,
CPUs: []int{0, 2, 4, 6},
DisableEcoQoS: &eco,
}, 16); err != nil {
t.Fatalf("SaveVMAffinity: %v", err)
}
rep := host.Report{LogicalCPUs: 16}
st := buildVMAffinityStatus(reims.VMDetail{
Name: "test-vm",
Directory: dir,
CPUs: 6,
State: "stopped",
}, rep, true, 0)
if st.Mode != "custom" || st.EffectiveMode != "custom" {
t.Fatalf("modes = (%s, %s), want custom", st.Mode, st.EffectiveMode)
}
if !reflect.DeepEqual(st.EffectiveCPUs, []int{0, 2, 4, 6}) {
t.Fatalf("EffectiveCPUs = %v", st.EffectiveCPUs)
}
if st.EffectiveMaskHex != "0x55" {
t.Fatalf("EffectiveMaskHex = %s, want 0x55", st.EffectiveMaskHex)
}
if !st.Oversubscribed {
t.Fatalf("expected Oversubscribed=true for 4 CPUs < 6 vCPUs")
}
if !st.DisableEcoQoS {
t.Fatalf("expected DisableEcoQoS=true")
}
}
+161 -22
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"os"
"path/filepath"
"strings"
@@ -175,6 +176,7 @@ func (a *App) shutdown(ctx context.Context) {
_ = gt.Close(shutCtx)
cancel()
}
releaseVMTyping("")
}
// pollVMs refreshes the VM list every pollBusy while a VM is starting or
@@ -182,7 +184,9 @@ func (a *App) shutdown(ctx context.Context) {
// Start, stop and delete call wakePoll so their result shows up at once.
const (
pollBusy = 2 * time.Second
pollSteady = 5 * time.Second
// Exits are caught at once by watchExits and GUI actions call wakePoll, so
// the steady tick only has to notice VMs started or removed elsewhere (CLI).
pollSteady = 10 * time.Second
// polledMaxAge is how old lastVMs may be for polledVMs to reuse it. It sits
// above pollSteady so a poll that runs a little late still counts.
polledMaxAge = pollSteady + 3*time.Second
@@ -221,14 +225,13 @@ func (a *App) pollVMs(ctx context.Context) {
watchExits(ctx, vms, exitWatched, a.wakePoll)
type pinCandidate struct {
name string
dir string
pid int
}
var toPin []pinCandidate
a.mu.Lock()
loc := a.cfg.Locale
autoPin := a.cfg.AutoPinPCores
a.lastVMs = append([]reims.VMListItem(nil), vms...)
a.lastVMsAt = time.Now()
tm := a.trayMgr
runningCount := 0
var b strings.Builder
@@ -252,17 +255,65 @@ func (a *App) pollVMs(ctx context.Context) {
}
}
}
if autoPin && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 {
pinnedPIDs[*vm.PID] = true
toPin = append(toPin, pinCandidate{name: vm.Name, pid: *vm.PID})
}
if vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
pinnedPIDs[*vm.PID] = true
toPin = append(toPin, pinCandidate{name: vm.Name, dir: vm.Dir, pid: *vm.PID})
}
fmt.Fprintf(&b, "%s:%s:%s;", vm.Name, vm.State, a.transitions[vm.Name])
}
sig := b.String()
ib := a.imeBridge
liveVMs := make(map[string]struct{}, len(vms))
for _, vm := range vms {
liveVMs[vm.Name] = struct{}{}
}
removedVMs := make(map[string]struct{})
for _, vm := range a.lastVMs {
if _, ok := liveVMs[vm.Name]; !ok {
removedVMs[vm.Name] = struct{}{}
}
}
for name := range a.rebootWatchers {
if _, ok := liveVMs[name]; !ok {
removedVMs[name] = struct{}{}
}
}
for name := range a.diskPaths {
if _, ok := liveVMs[name]; !ok {
removedVMs[name] = struct{}{}
}
}
for name := range a.procSamples {
if _, ok := liveVMs[name]; !ok {
removedVMs[name] = struct{}{}
}
}
maps.DeleteFunc(a.diskPaths, func(name string, _ cachedDiskPath) bool {
_, ok := liveVMs[name]
return !ok
})
maps.DeleteFunc(a.procSamples, func(name string, _ host.ProcessSample) bool {
_, ok := liveVMs[name]
return !ok
})
gt := a.guestTools
a.lastVMs = append([]reims.VMListItem(nil), vms...)
a.lastVMsAt = time.Now()
a.mu.Unlock()
prunePinnedPIDs(pinnedPIDs, vms)
for name := range removedVMs {
a.mu.Lock()
delete(a.transitions, name)
delete(a.pendingChanges, name)
a.mu.Unlock()
stopVMMonitor(name)
a.cancelRebootWatcher(name)
releaseVMTyping(name)
releaseVMThumbnail(name)
if gt != nil {
gt.UnregisterVM(name)
}
}
if ib != nil {
ib.SetTargets(imeTargets)
}
@@ -279,12 +330,18 @@ func (a *App) pollVMs(ctx context.Context) {
}
for _, cand := range toPin {
vmCPUs := 0
vmDir := cand.dir
if c, cerr := a.client(); cerr == nil {
if det, derr := c.Show(ctx, cand.name); derr == nil {
vmCPUs = det.CPUs
if vmDir == "" {
vmDir = det.Directory
}
}
}
a.emitLog(cand.name, vmstart.PinQEMU(loc, cachedHost, cand.pid, vmCPUs))
if line, _ := vmstart.ApplyVMAffinity(loc, cachedHost, vmDir, autoPin, cand.pid, vmCPUs, false); line != "" {
a.emitLog(cand.name, line)
}
}
if sig != lastSig {
lastSig = sig
@@ -345,6 +402,20 @@ func watchExits(ctx context.Context, vms []reims.VMListItem, watched map[int]boo
}
}
func prunePinnedPIDs(pinned map[int]bool, vms []reims.VMListItem) {
running := make(map[int]struct{}, len(vms))
for _, vm := range vms {
if vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
running[*vm.PID] = struct{}{}
}
}
for pid := range pinned {
if _, ok := running[pid]; !ok {
delete(pinned, pid)
}
}
}
// polledVMs returns the list pollVMs saw last if it is at most polledMaxAge
// old, so per-VM samplers (stats, thumbnails, heartbeats) don't each spawn
// their own `reims-ctl list`. A stale or missing poll falls back to one.
@@ -454,7 +525,9 @@ func (a *App) GetState() AppState {
rep := host.Inspect(cfgCopy.DataRoot)
runtimes, _ := rt.List(&cfgCopy)
active, _ := rt.ResolveActive(&cfgCopy)
vms, _ := a.listVMsInternal(context.Background())
// The poller's list (≤ polledMaxAge old, and invalidated by wakePoll after
// start/stop/delete) instead of another `reims-ctl list` per refresh.
vms, _ := a.polledVMs(context.Background())
var activePatches []string
if active != nil {
@@ -557,15 +630,13 @@ func (a *App) startTray() {
OnShow: func() {
a.ShowMainWindow()
},
OnStartVM: func(name string) {
_ = a.StartVM(name)
},
OnStopVM: func(name string) {
_ = a.StopVM(name, false)
},
OnOpenSharedDir: func(name string) {
_ = a.OpenSharedFolder(name)
OnNewVM: func() {
a.ShowMainWindow()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:tray-new-vm")
}
},
OnVMAction: a.trayVMAction,
OnQuit: func() {
a.QuitApp()
},
@@ -573,6 +644,10 @@ func (a *App) startTray() {
a.mu.Lock()
loc := a.cfg.Locale
cached := append([]reims.VMListItem(nil), a.lastVMs...)
transitions := make(map[string]string, len(a.transitions))
for k, v := range a.transitions {
transitions[k] = v
}
a.mu.Unlock()
if len(cached) == 0 {
if vms, err := a.listVMsInternal(context.Background()); err == nil {
@@ -581,10 +656,19 @@ func (a *App) startTray() {
}
items := make([]tray.VMItem, 0, len(cached))
for _, vm := range cached {
items = append(items, tray.VMItem{
Name: vm.Name,
Running: vm.State == "running",
})
state := vm.State
if t := transitions[vm.Name]; t != "" {
state = t
}
// The display name is the VM's note, read straight from its
// folder (no reims-ctl call while the menu is opening).
label := ""
if vm.Dir != "" {
if b, err := os.ReadFile(filepath.Join(vm.Dir, vmNoteFileName)); err == nil {
label = sanitizeVMNote(string(b))
}
}
items = append(items, tray.VMItem{Name: vm.Name, Label: label, State: state})
}
return tray.Snapshot{
LocaleZh: loc == i18n.ZhCN,
@@ -601,6 +685,54 @@ func (a *App) startTray() {
a.mu.Unlock()
}
// trayVMAction runs a command picked from the tray menu. The main window may
// be hidden, so failures (and a copied screenshot, which has no other visible
// result) are reported as a Windows notification from the tray icon.
func (a *App) trayVMAction(name string, act tray.Action) {
a.mu.Lock()
zh := a.cfg.Locale == i18n.ZhCN
tm := a.trayMgr
a.mu.Unlock()
pick := func(cn, en string) string {
if zh {
return cn
}
return en
}
var err error
var failTitle string
switch act {
case tray.ActStart:
err, failTitle = a.StartVM(name), pick("无法启动 ", "Couldn't start ")+name
case tray.ActStop:
err, failTitle = a.StopVM(name, false), pick("无法关机 ", "Couldn't shut down ")+name
case tray.ActForceStop:
err, failTitle = a.StopVM(name, true), pick("无法强制关机 ", "Couldn't force shut down ")+name
case tray.ActRestart:
err, failTitle = a.RestartVM(name), pick("无法重启 ", "Couldn't restart ")+name
case tray.ActShowWindow:
err, failTitle = a.FocusVMWindow(name), pick("找不到 ", "Couldn't find the window of ")+name+pick(" 的窗口", "")
case tray.ActScreenshot:
if err = a.CopyVMScreenshot(name); err == nil && tm != nil {
tm.Notify(pick("已复制屏幕截图", "Screenshot copied"), name, false)
}
failTitle = pick("截图失败:", "Screenshot failed: ") + name
case tray.ActSharedFolder:
err, failTitle = a.OpenSharedFolder(name), pick("无法打开共享文件夹", "Couldn't open the shared folder")
case tray.ActOpenInApp:
a.ShowMainWindow()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:tray-select-vm", name)
}
}
if err != nil {
a.emitLog(name, failTitle+": "+err.Error())
if tm != nil {
tm.Notify(failTitle, err.Error(), true)
}
}
}
func (a *App) SetDataRoot(dir string) error {
dir = strings.TrimSpace(dir)
if dir == "" {
@@ -1026,7 +1158,14 @@ func (a *App) DeleteVM(name string, keepFiles bool) error {
delete(a.pendingChanges, name)
delete(a.transitions, name)
delete(a.diskPaths, name)
delete(a.procSamples, name)
gt := a.guestTools
a.mu.Unlock()
releaseVMTyping(name)
releaseVMThumbnail(name)
if gt != nil {
gt.UnregisterVM(name)
}
a.wakePoll()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
return nil
+38
View File
@@ -64,6 +64,44 @@ func TestWatchExitsTracksRunningPIDs(t *testing.T) {
}
}
func TestPrunePinnedPIDs(t *testing.T) {
runningPID, stoppedPID := 42, 43
pinned := map[int]bool{runningPID: true, stoppedPID: true, 44: true}
prunePinnedPIDs(pinned, []reims.VMListItem{
{Name: "running", State: "running", PID: &runningPID},
{Name: "stopped", State: "stopped", PID: &stoppedPID},
})
if len(pinned) != 1 || !pinned[runningPID] {
t.Fatalf("pinned = %v, want only running PID %d", pinned, runningPID)
}
}
func TestReleaseVMTypingDrainsAndRemovesQueue(t *testing.T) {
const name = "typing-release-test"
done := make(chan struct{})
a := &App{}
typing.mu.Lock()
ch := make(chan remoteTextItem)
typing.remoteQueues[name] = ch
typing.lastHintAt[name] = time.Now()
typing.mu.Unlock()
go func() {
a.runRemoteTextQueue(name, ch)
close(done)
}()
releaseVMTyping(name)
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("remote typing worker did not exit")
}
typing.mu.Lock()
defer typing.mu.Unlock()
if len(typing.remoteQueues) != 0 || len(typing.lastHintAt) != 0 || len(typing.closing) != 0 {
t.Fatal("typing state remains after VM release")
}
}
func TestWakePollMarksStaleAndWakesOnce(t *testing.T) {
a := &App{pollWake: make(chan struct{}, 1)}
a.lastVMsAt = time.Now()
+16 -6
View File
@@ -116,14 +116,24 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error {
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone settings: %v", serr))
}
}
if src.GuestLang != "" {
if src.GuestLang != "" || vmstart.HasSavedVMAffinity(src.Directory) {
if cloned, serr := c.Show(ctx, cloneName); serr == nil && cloned.Directory != "" {
prep, lerr := a.prep(cloneName)
if lerr == nil {
lerr = prep.ApplyGuestLang(ctx, cloned.Directory, src.GuestLang, false)
if src.GuestLang != "" {
prep, lerr := a.prep(cloneName)
if lerr == nil {
lerr = prep.ApplyGuestLang(ctx, cloned.Directory, src.GuestLang, false)
}
if lerr != nil {
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone language (%s): %v", src.GuestLang, lerr))
}
}
if lerr != nil {
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone language (%s): %v", src.GuestLang, lerr))
if werr := writeVMMacOS(cloned.Directory, readVMMacOS(src.Directory)); werr != nil {
a.emitLog(cloneName, fmt.Sprintf("Warning: could not copy macOS release: %v", werr))
}
if vmstart.HasSavedVMAffinity(src.Directory) {
if _, aerr := vmstart.SaveVMAffinity(cloned.Directory, vmstart.ReadVMAffinity(src.Directory), rep.LogicalCPUs); aerr != nil {
a.emitLog(cloneName, fmt.Sprintf("Warning: could not copy CPU affinity setting: %v", aerr))
}
}
}
}
+12 -2
View File
@@ -106,13 +106,23 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
if guestLang == "" && opts.SourceMode != "disk" {
guestLang = opencore.DefaultGuestLang(cfgCopy.Locale)
}
if guestLang != "" {
vmDir := strings.TrimSpace(opts.Dir)
release := ""
if opts.SourceMode != "disk" {
release = strings.TrimSpace(opts.MacOS)
}
vmDir := ""
if guestLang != "" || release != "" {
vmDir = strings.TrimSpace(opts.Dir)
if d, serr := c.Show(ctx, opts.Name); serr == nil && d.Directory != "" {
vmDir = d.Directory
} else if vmDir == "" {
vmDir = filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms", opts.Name)
}
}
if werr := writeVMMacOS(vmDir, release); werr != nil {
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not record macOS release (%s): %v", release, werr))
}
if guestLang != "" {
prep, lerr := a.prep(opts.Name)
if lerr == nil {
lerr = prep.ApplyGuestLang(ctx, vmDir, guestLang, false)
+142
View File
@@ -0,0 +1,142 @@
package app
import (
"context"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"github.com/Nwflower/reims-go/internal/installer"
)
const vmNoteFileName = ".reims-go-note"
// VMStorageItem is one VM's disk footprint under DataRoot.
type VMStorageItem struct {
Name string `json:"name"`
Bytes int64 `json:"bytes"`
}
// StorageBreakdown summarizes how DataRoot space is distributed across VM files,
// cached macOS installers, and all other Reims-Go data.
type StorageBreakdown struct {
VMsBytes int64 `json:"vms_bytes"`
InstallersBytes int64 `json:"installers_bytes"`
RuntimesBytes int64 `json:"runtimes_bytes"`
TotalBytes int64 `json:"total_bytes"`
VMs []VMStorageItem `json:"vms"`
}
// vmDirectory finds a VM's folder from the list pollVMs already holds, so
// per-VM file reads (the note) don't each run `reims-ctl show`; it falls
// back to show when the list has no entry or no folder for it.
func (a *App) vmDirectory(name string) string {
if vms, err := a.polledVMs(context.Background()); err == nil {
for _, vm := range vms {
if vm.Name == name && vm.Dir != "" {
return vm.Dir
}
}
}
if d, err := a.GetVMDetail(name); err == nil {
return d.Directory
}
return ""
}
// GetVMNote returns the optional single-line note saved for a VM.
func (a *App) GetVMNote(name string) string {
dir := a.vmDirectory(name)
if dir == "" {
return ""
}
b, err := os.ReadFile(filepath.Join(dir, vmNoteFileName))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
// SetVMNote stores a short single-line note next to the VM directory.
func (a *App) SetVMNote(name, note string) error {
note = sanitizeVMNote(note)
dir := a.vmDirectory(name)
if dir == "" {
return fmt.Errorf("VM directory not found")
}
p := filepath.Join(dir, vmNoteFileName)
if note == "" {
_ = os.Remove(p)
return nil
}
return os.WriteFile(p, []byte(note+"\n"), 0o644)
}
func sanitizeVMNote(note string) string {
note = strings.ReplaceAll(note, "\r", " ")
note = strings.ReplaceAll(note, "\n", " ")
note = strings.TrimSpace(note)
runes := []rune(note)
if len(runes) > 120 {
return string(runes[:120])
}
return note
}
// GetStorageBreakdown computes disk usage across DataRoot subdirectories.
func (a *App) GetStorageBreakdown() StorageBreakdown {
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
vmsDir := filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms")
return computeStorageBreakdown(cfgCopy.DataRoot, vmsDir, installer.Dir(&cfgCopy), cfgCopy.ImagesDir())
}
func computeStorageBreakdown(dataRoot, vmsDir, installersDir, imagesDir string) StorageBreakdown {
var out StorageBreakdown
if entries, err := os.ReadDir(vmsDir); err == nil {
for _, e := range entries {
if !e.IsDir() {
continue
}
sz := dirSizeBytes(filepath.Join(vmsDir, e.Name()))
out.VMs = append(out.VMs, VMStorageItem{Name: e.Name(), Bytes: sz})
out.VMsBytes += sz
}
}
if imgBytes := dirSizeBytes(imagesDir); imgBytes > 0 {
out.VMsBytes += imgBytes
}
sort.Slice(out.VMs, func(i, j int) bool {
return out.VMs[i].Bytes > out.VMs[j].Bytes
})
out.InstallersBytes = dirSizeBytes(installersDir)
// Keep the existing JSON field for frontend compatibility, but attribute all
// remaining DataRoot usage (runtimes, config, cache, releases, etc.) to Reims-Go.
out.RuntimesBytes = dirSizeBytes(dataRoot) - out.VMsBytes - out.InstallersBytes
if out.RuntimesBytes < 0 {
out.RuntimesBytes = 0
}
out.TotalBytes = out.VMsBytes + out.InstallersBytes + out.RuntimesBytes
return out
}
func dirSizeBytes(root string) int64 {
if root == "" {
return 0
}
var total int64
_ = filepath.WalkDir(root, func(_ string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return nil
}
if info, err := d.Info(); err == nil {
total += info.Size()
}
return nil
})
return total
}
+67
View File
@@ -0,0 +1,67 @@
package app
import (
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/driver/reims"
)
func TestParseDiskSnapshotsJSON(t *testing.T) {
raw := []byte(`{
"format": "qcow2",
"snapshots": [
{"id": "1", "name": "before-ota", "vm-state-size": 0, "date-sec": 1764400000},
{"id": "2", "name": "clean-xcode", "vm-state-size": 0, "date-sec": 1764403600}
]
}`)
fmtName, snaps, err := reims.ParseDiskSnapshotsJSON(raw)
if err != nil {
t.Fatal(err)
}
if fmtName != "qcow2" || len(snaps) != 2 || snaps[0].Name != "before-ota" || snaps[1].CreatedAt != 1764403600 {
t.Fatalf("unexpected snapshots: format=%q snaps=%+v", fmtName, snaps)
}
}
func TestValidateSnapshotName(t *testing.T) {
if got, err := reims.ValidateSnapshotName(" before-ota-26.2 "); err != nil || got != "before-ota-26.2" {
t.Fatalf("valid name failed: %q %v", got, err)
}
if _, err := reims.ValidateSnapshotName(" "); err == nil {
t.Fatal("expected error for empty snapshot name")
}
if _, err := reims.ValidateSnapshotName(`bad"quote`); err == nil {
t.Fatal("expected error for quote in snapshot name")
}
}
func TestSanitizeVMNoteAndStorageBreakdown(t *testing.T) {
if got := sanitizeVMNote(" Xcode 26\nBuilder "); got != "Xcode 26 Builder" {
t.Fatalf("sanitizeVMNote = %q", got)
}
root := t.TempDir()
vms := filepath.Join(root, "vms")
inst := filepath.Join(root, "installers")
rtDir := filepath.Join(root, "runtimes")
_ = os.MkdirAll(filepath.Join(vms, "mac-a"), 0o755)
_ = os.MkdirAll(filepath.Join(vms, "mac-b"), 0o755)
_ = os.MkdirAll(inst, 0o755)
_ = os.MkdirAll(rtDir, 0o755)
_ = os.MkdirAll(filepath.Join(root, "cache"), 0o755)
_ = os.WriteFile(filepath.Join(vms, "mac-a", "disk.qcow2"), make([]byte, 200), 0o644)
_ = os.WriteFile(filepath.Join(vms, "mac-b", "disk.qcow2"), make([]byte, 500), 0o644)
_ = os.WriteFile(filepath.Join(inst, "tahoe.img"), make([]byte, 1000), 0o644)
_ = os.WriteFile(filepath.Join(rtDir, "qemu.exe"), make([]byte, 300), 0o644)
_ = os.WriteFile(filepath.Join(root, "cache", "download.tmp"), make([]byte, 75), 0o644)
_ = os.WriteFile(filepath.Join(root, "reims-go.json"), make([]byte, 25), 0o644)
bd := computeStorageBreakdown(root, vms, inst, "")
if bd.VMsBytes != 700 || bd.InstallersBytes != 1000 || bd.RuntimesBytes != 400 || bd.TotalBytes != 2100 {
t.Fatalf("breakdown = %+v", bd)
}
if len(bd.VMs) != 2 || bd.VMs[0].Name != "mac-b" || bd.VMs[0].Bytes != 500 {
t.Fatalf("VMs order = %+v", bd.VMs)
}
}
+38
View File
@@ -6,6 +6,7 @@ import (
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/driver/reims"
@@ -311,6 +312,43 @@ func (a *App) DeliverFileToGuest(name string) (string, error) {
if err != nil || picked == "" {
return "", err
}
return a.deliverHostFile(name, picked)
}
// DeliverPathsToGuest copies one or more dropped host file paths into
// `<DataRoot>/shared/<vmName>`, skipping directories.
func (a *App) DeliverPathsToGuest(name string, paths []string) ([]string, error) {
if len(paths) == 0 {
return nil, nil
}
var delivered []string
var lastErr error
for _, p := range paths {
if strings.TrimSpace(p) == "" {
continue
}
st, err := os.Stat(p)
if err != nil {
lastErr = err
continue
}
if st.IsDir() {
continue
}
base, err := a.deliverHostFile(name, p)
if err != nil {
lastErr = err
continue
}
delivered = append(delivered, base)
}
if len(delivered) == 0 && lastErr != nil {
return nil, lastErr
}
return delivered, nil
}
func (a *App) deliverHostFile(name, picked string) (string, error) {
sharedDir := a.vmSharedDir(name)
if err := os.MkdirAll(sharedDir, 0o755); err != nil {
return "", err
+40
View File
@@ -0,0 +1,40 @@
package app
import (
"os"
"path/filepath"
"strings"
)
// vmMacOSFileName records which macOS release a VM was created with, for its
// icon. reims-ctl keeps no such field in vm.toml.
const vmMacOSFileName = ".reims-go-macos"
// GetVMMacOS returns the macOS release recorded when the VM was created: an
// installer version such as "26.7.3", or a codename such as "tahoe" for an
// online-recovery install. It is "" for VMs made from an existing disk or
// before this was recorded; the UI then guesses from the VM's name.
func (a *App) GetVMMacOS(name string) string {
dir := a.vmDirectory(name)
if dir == "" {
return ""
}
return readVMMacOS(dir)
}
func readVMMacOS(dir string) string {
b, err := os.ReadFile(filepath.Join(dir, vmMacOSFileName))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
// writeVMMacOS stores release next to vm.toml; an empty release writes nothing.
func writeVMMacOS(dir, release string) error {
release = strings.TrimSpace(strings.ReplaceAll(strings.ReplaceAll(release, "\r", ""), "\n", ""))
if dir == "" || release == "" {
return nil
}
return os.WriteFile(filepath.Join(dir, vmMacOSFileName), []byte(release+"\n"), 0o644)
}
+25
View File
@@ -0,0 +1,25 @@
package app
import "testing"
func TestVMMacOSRoundTrip(t *testing.T) {
dir := t.TempDir()
if got := readVMMacOS(dir); got != "" {
t.Fatalf("empty dir: got %q", got)
}
if err := writeVMMacOS(dir, ""); err != nil {
t.Fatal(err)
}
if got := readVMMacOS(dir); got != "" {
t.Fatalf("empty release wrote %q", got)
}
if err := writeVMMacOS(dir, " 26.7.3\r\n"); err != nil {
t.Fatal(err)
}
if got := readVMMacOS(dir); got != "26.7.3" {
t.Fatalf("got %q, want 26.7.3", got)
}
if err := writeVMMacOS("", "tahoe"); err != nil {
t.Fatalf("no dir should be a no-op, got %v", err)
}
}
+91
View File
@@ -0,0 +1,91 @@
package app
import (
"fmt"
"path/filepath"
"sort"
"strings"
"github.com/Nwflower/reims-go/internal/driver/reims"
rt "github.com/Nwflower/reims-go/internal/runtime"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// ListSnapshots returns all internal qcow2 restore points for a VM, newest first.
func (a *App) ListSnapshots(name string) ([]reims.DiskSnapshot, error) {
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return nil, err
}
d, err := a.GetVMDetail(name)
if err != nil {
return nil, err
}
diskPath := resolveVMDiskPath(d)
if diskPath == "" || !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
return nil, nil
}
env := rt.BuildChildEnv(&cfgCopy, *active)
snaps, err := reims.ListDiskSnapshots(a.baseCtx(), active.QemuImgPath(), env, diskPath)
if err != nil {
return nil, err
}
sort.SliceStable(snaps, func(i, j int) bool {
return snaps[i].CreatedAt > snaps[j].CreatedAt
})
return snaps, nil
}
// CreateSnapshot creates a named offline restore point inside a stopped VM's qcow2 disk.
func (a *App) CreateSnapshot(name, snapName string) error {
return a.runSnapshotOp(name, "-c", snapName, "Created restore point")
}
// RestoreSnapshot rolls back a stopped VM's qcow2 disk to the named restore point.
func (a *App) RestoreSnapshot(name, snapName string) error {
return a.runSnapshotOp(name, "-a", snapName, "Restored restore point")
}
// DeleteSnapshot removes a named restore point from a stopped VM's qcow2 disk.
func (a *App) DeleteSnapshot(name, snapName string) error {
return a.runSnapshotOp(name, "-d", snapName, "Deleted restore point")
}
func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return err
}
c := reims.NewClient(&cfgCopy, *active)
ctx := a.baseCtx()
d, err := a.GetVMDetail(name)
if err != nil {
return err
}
if a.isVMRunning(ctx, c, name, d) {
return fmt.Errorf("stop %s before managing restore points", name)
}
diskPath := resolveVMDiskPath(d)
if diskPath == "" {
return fmt.Errorf("VM %s has no disk path", name)
}
if !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
return fmt.Errorf("restore points are only supported on .qcow2 disks")
}
env := rt.BuildChildEnv(&cfgCopy, *active)
if err := reims.RunDiskSnapshot(ctx, active.QemuImgPath(), env, flag, snapName, diskPath); err != nil {
return err
}
a.emitLog(name, fmt.Sprintf("%s %q", verb, strings.TrimSpace(snapName)))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return nil
}
+203
View File
@@ -0,0 +1,203 @@
package app
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
)
const sshUserFileName = ".reims-go-ssh-user"
var safeSSHUserRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
// sshHostAlias returns a stable ~/.ssh/config Host alias for a VM.
func sshHostAlias(vmName string) string {
var b strings.Builder
b.WriteString("reims-")
for _, r := range strings.ToLower(strings.TrimSpace(vmName)) {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
b.WriteRune(r)
} else {
b.WriteByte('-')
}
}
return b.String()
}
// GetVMSSHUser returns the remembered SSH login user for a VM (empty if unset).
func (a *App) GetVMSSHUser(name string) string {
d, err := a.GetVMDetail(name)
if err != nil || d.Directory == "" {
return ""
}
b, err := os.ReadFile(filepath.Join(d.Directory, sshUserFileName))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
// SetVMSSHUser persists the preferred SSH login user for a VM.
func (a *App) SetVMSSHUser(name, user string) error {
user = strings.TrimSpace(user)
if user != "" && !safeSSHUserRe.MatchString(user) {
return fmt.Errorf("invalid SSH username %q", user)
}
d, err := a.GetVMDetail(name)
if err != nil {
return err
}
if d.Directory == "" {
return fmt.Errorf("VM directory not found")
}
p := filepath.Join(d.Directory, sshUserFileName)
if user == "" {
_ = os.Remove(p)
return nil
}
return os.WriteFile(p, []byte(user+"\n"), 0o644)
}
// OpenSSHTerminal launches an interactive Windows Terminal (falling back to
// PowerShell) connected to the VM's forwarded SSH port.
func (a *App) OpenSSHTerminal(name, user string) error {
d, err := a.GetVMDetail(name)
if err != nil {
return err
}
if !d.Network || d.SSHPort <= 0 {
return fmt.Errorf("SSH port forwarding is not enabled for %s", name)
}
user = strings.TrimSpace(user)
if user == "" {
user = a.GetVMSSHUser(name)
} else if !safeSSHUserRe.MatchString(user) {
return fmt.Errorf("invalid SSH username %q", user)
} else {
_ = a.SetVMSSHUser(name, user)
}
target := "127.0.0.1"
if user != "" {
target = user + "@127.0.0.1"
}
portStr := fmt.Sprintf("%d", d.SSHPort)
var cmd *exec.Cmd
if wt, err := exec.LookPath("wt.exe"); err == nil {
cmd = exec.Command(wt, "new-tab", "--title", name, "ssh", "-p", portStr, target)
} else if ps, err := exec.LookPath("powershell.exe"); err == nil {
cmd = exec.Command(ps, "-NoExit", "-Command", fmt.Sprintf("ssh -p %s %s", portStr, target))
} else {
return fmt.Errorf("neither Windows Terminal (wt.exe) nor powershell.exe was found")
}
if err := cmd.Start(); err != nil {
return fmt.Errorf("open SSH terminal: %w", err)
}
a.emitLog(name, fmt.Sprintf("Opened SSH terminal (%s -p %s)", target, portStr))
return nil
}
// WriteSSHConfig idempotently writes or updates a Host block for the VM in
// ~/.ssh/config and returns the configured Host alias (e.g. "reims-macos-tahoe").
func (a *App) WriteSSHConfig(name, user string) (string, error) {
d, err := a.GetVMDetail(name)
if err != nil {
return "", err
}
if !d.Network || d.SSHPort <= 0 {
return "", fmt.Errorf("SSH port forwarding is not enabled for %s", name)
}
user = strings.TrimSpace(user)
if user == "" {
user = a.GetVMSSHUser(name)
} else if !safeSSHUserRe.MatchString(user) {
return "", fmt.Errorf("invalid SSH username %q", user)
} else {
_ = a.SetVMSSHUser(name, user)
}
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("locate home directory: %w", err)
}
sshDir := filepath.Join(home, ".ssh")
if err := os.MkdirAll(sshDir, 0o700); err != nil {
return "", fmt.Errorf("create ~/.ssh: %w", err)
}
cfgPath := filepath.Join(sshDir, "config")
alias := sshHostAlias(name)
if err := upsertSSHConfigBlock(cfgPath, name, alias, d.SSHPort, user); err != nil {
return "", err
}
a.emitLog(name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (127.0.0.1:%d)", alias, d.SSHPort))
return alias, nil
}
// OpenVSCodeSSH ensures the VM's Host block is present in ~/.ssh/config and
// launches VS Code (falling back to Cursor) in Remote-SSH mode.
func (a *App) OpenVSCodeSSH(name, user string) error {
alias, err := a.WriteSSHConfig(name, user)
if err != nil {
return err
}
var bin string
for _, cand := range []string{"code.cmd", "code", "cursor.cmd", "cursor"} {
if p, err := exec.LookPath(cand); err == nil {
bin = p
break
}
}
if bin == "" {
return fmt.Errorf("VS Code or Cursor CLI not found on PATH (Host %s has been written to ~/.ssh/config)", alias)
}
cmd := exec.Command(bin, "--remote", "ssh-remote+"+alias)
if err := cmd.Start(); err != nil {
return fmt.Errorf("launch editor Remote-SSH: %w", err)
}
a.emitLog(name, fmt.Sprintf("Launched %s Remote-SSH for %s", filepath.Base(bin), alias))
return nil
}
func upsertSSHConfigBlock(cfgPath, vmName, alias string, port int, user string) error {
startMark := fmt.Sprintf("# >>> reims-go:%s >>>", vmName)
endMark := fmt.Sprintf("# <<< reims-go:%s <<<", vmName)
var block strings.Builder
block.WriteString(startMark + "\n")
block.WriteString(fmt.Sprintf("Host %s\n", alias))
block.WriteString(" HostName 127.0.0.1\n")
block.WriteString(fmt.Sprintf(" Port %d\n", port))
if user != "" {
block.WriteString(fmt.Sprintf(" User %s\n", user))
}
block.WriteString(" StrictHostKeyChecking accept-new\n")
block.WriteString(endMark + "\n")
existingBytes, err := os.ReadFile(cfgPath)
if err != nil && !os.IsNotExist(err) {
return err
}
content := strings.ReplaceAll(string(existingBytes), "\r\n", "\n")
var updated string
if si := strings.Index(content, startMark); si >= 0 {
if ei := strings.Index(content[si:], endMark); ei >= 0 {
endPos := si + ei + len(endMark)
if endPos < len(content) && content[endPos] == '\n' {
endPos++
}
updated = content[:si] + block.String() + content[endPos:]
}
}
if updated == "" {
if content != "" && !strings.HasSuffix(content, "\n") {
content += "\n"
}
if content != "" && !strings.HasSuffix(content, "\n\n") {
content += "\n"
}
updated = content + block.String()
}
return os.WriteFile(cfgPath, []byte(updated), 0o600)
}
+50
View File
@@ -0,0 +1,50 @@
package app
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestSSHHostAlias(t *testing.T) {
if got := sshHostAlias("macos-tahoe"); got != "reims-macos-tahoe" {
t.Fatalf("alias = %q", got)
}
if got := sshHostAlias("My Mac 26"); got != "reims-my-mac-26" {
t.Fatalf("alias = %q", got)
}
}
func TestUpsertSSHConfigBlockIdempotent(t *testing.T) {
cfg := filepath.Join(t.TempDir(), "config")
initial := "Host prod\n HostName 10.0.0.5\n"
if err := os.WriteFile(cfg, []byte(initial), 0o600); err != nil {
t.Fatal(err)
}
if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", 2222, "alice"); err != nil {
t.Fatal(err)
}
b1, _ := os.ReadFile(cfg)
s1 := string(b1)
if !strings.Contains(s1, "Host prod") || !strings.Contains(s1, "Host reims-macos-tahoe") || !strings.Contains(s1, "Port 2222") || !strings.Contains(s1, "User alice") {
t.Fatalf("unexpected first config:\n%s", s1)
}
// Updating port and user must replace the block in place without duplicating it.
if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", 2223, "bob"); err != nil {
t.Fatal(err)
}
b2, _ := os.ReadFile(cfg)
s2 := string(b2)
if strings.Count(s2, "Host reims-macos-tahoe") != 1 {
t.Fatalf("expected single block, got:\n%s", s2)
}
if !strings.Contains(s2, "Port 2223") || !strings.Contains(s2, "User bob") || strings.Contains(s2, "User alice") {
t.Fatalf("block not updated:\n%s", s2)
}
if !strings.Contains(s2, "Host prod") {
t.Fatalf("existing user config lost:\n%s", s2)
}
}
+90 -6
View File
@@ -6,13 +6,17 @@ package app
// show its last screen. Nothing here touches vm.toml or the guest.
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"image/png"
"os"
"path/filepath"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/thumb"
@@ -29,7 +33,10 @@ const thumbWidth = 640
// thumbLocks keeps one capture per VM in flight: QMP serves a single client
// and the page polls on a timer.
var thumbLocks sync.Map // name → *sync.Mutex
var thumbLocks = struct {
mu sync.Mutex
locks map[string]*sync.Mutex
}{locks: make(map[string]*sync.Mutex)}
func (a *App) thumbPath(name string) string {
a.mu.Lock()
@@ -38,12 +45,35 @@ func (a *App) thumbPath(name string) string {
return filepath.Join(dir, "thumbs", name+".jpg")
}
func vmThumbLock(name string) *sync.Mutex {
thumbLocks.mu.Lock()
defer thumbLocks.mu.Unlock()
mu := thumbLocks.locks[name]
if mu == nil {
mu = &sync.Mutex{}
thumbLocks.locks[name] = mu
}
return mu
}
// releaseVMThumbnail waits for an in-flight capture before releasing its lock,
// so an old request cannot install a new lock after the VM has been deleted.
func releaseVMThumbnail(name string) {
mu := vmThumbLock(name)
mu.Lock()
thumbLocks.mu.Lock()
if thumbLocks.locks[name] == mu {
delete(thumbLocks.locks, name)
}
thumbLocks.mu.Unlock()
mu.Unlock()
}
// GetVMThumbnail returns the VM's screen: a fresh frame while it runs, else
// the last one saved. An empty DataURL means there is no frame to show.
func (a *App) GetVMThumbnail(name string) (VMThumbnail, error) {
path := a.thumbPath(name)
l, _ := thumbLocks.LoadOrStore(name, &sync.Mutex{})
mu := l.(*sync.Mutex)
mu := vmThumbLock(name)
if mu.TryLock() {
defer mu.Unlock()
if t, ok := a.captureThumb(name, path); ok {
@@ -53,6 +83,60 @@ func (a *App) GetVMThumbnail(name string) (VMThumbnail, error) {
return readThumb(path, false), nil
}
// FocusVMWindow brings a running VM's QEMU display window to the foreground,
// restoring it first if minimized (docs/ui-redesign.md §6 B5).
func (a *App) FocusVMWindow(name string) error {
vm, ok := a.polledVM(name)
if !ok || vm.State != "running" || vm.PID == nil || *vm.PID <= 0 {
return fmt.Errorf("VM %s is not running", name)
}
if !host.FocusProcessWindow(uint32(*vm.PID)) {
return fmt.Errorf("could not locate display window for %s", name)
}
return nil
}
// CopyVMScreenshot captures a full-resolution frame from a running VM over QMP
// and writes it as a PNG/DIB image to the Windows clipboard.
func (a *App) CopyVMScreenshot(name string) error {
vm, ok := a.polledVM(name)
if !ok || vm.State != "running" || vm.Dir == "" {
return fmt.Errorf("VM %s is not running", name)
}
mu := vmThumbLock(name)
mu.Lock()
defer mu.Unlock()
a.mu.Lock()
tmp := a.cfg.TempDir()
a.mu.Unlock()
if err := os.MkdirAll(tmp, 0o755); err != nil {
return err
}
raw := filepath.Join(tmp, "screenshot-"+name)
defer os.Remove(raw)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw)
if err != nil {
return fmt.Errorf("capture screen: %w", err)
}
img, err := thumb.Load(raw, format)
if err != nil {
return fmt.Errorf("decode screen: %w", err)
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
return fmt.Errorf("encode PNG: %w", err)
}
if err := (guesttools.OSClipboard{}).WritePNG(buf.Bytes()); err != nil {
return fmt.Errorf("copy image to clipboard: %w", err)
}
a.emitLog(name, "Copied VM screenshot to clipboard")
return nil
}
func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
typing.mu.Lock()
busy := typing.busy[name]
@@ -85,11 +169,11 @@ func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
if err != nil {
return VMThumbnail{}, false
}
img, err := thumb.Load(raw, format)
if err != nil || thumb.Blank(img) {
img, err := thumb.LoadPreview(raw, format, thumbWidth)
if err != nil || img == nil {
return VMThumbnail{}, false
}
jpg, err := thumb.JPEG(thumb.Scale(img, thumbWidth), 80)
jpg, err := thumb.JPEG(img, 80)
if err != nil {
return VMThumbnail{}, false
}
+22
View File
@@ -0,0 +1,22 @@
package app
import "testing"
func TestReleaseVMThumbnailRemovesLock(t *testing.T) {
const name = "thumbnail-release-test"
t.Cleanup(func() { releaseVMThumbnail(name) })
first := vmThumbLock(name)
if got := vmThumbLock(name); got != first {
t.Fatal("same VM should share a thumbnail lock")
}
releaseVMThumbnail(name)
thumbLocks.mu.Lock()
remaining := len(thumbLocks.locks)
thumbLocks.mu.Unlock()
if remaining != 0 {
t.Fatalf("thumbnail locks remain after release: %d", remaining)
}
if got := vmThumbLock(name); got == first {
t.Fatal("released lock was reused")
}
}
+41 -3
View File
@@ -34,10 +34,12 @@ var typing = struct {
busy map[string]bool
lastHintAt map[string]time.Time
remoteQueues map[string]chan remoteTextItem
closing map[string]bool
}{
busy: map[string]bool{},
lastHintAt: map[string]time.Time{},
remoteQueues: map[string]chan remoteTextItem{},
closing: map[string]bool{},
}
// ErrNotTypeable is what the UI matches to show its own message.
@@ -184,15 +186,48 @@ func (a *App) injectRemoteText(vmName, vmDir, text string) {
typing.remoteQueues[vmName] = ch
go a.runRemoteTextQueue(vmName, ch)
}
typing.mu.Unlock()
if typing.closing[vmName] {
typing.mu.Unlock()
return
}
// releaseVMTyping closes ch under this lock. Keep the nonblocking send
// inside the same critical section as the closing check.
select {
case ch <- remoteTextItem{vmDir: vmDir, text: text}:
default:
}
typing.mu.Unlock()
}
func releaseVMTyping(vmName string) {
typing.mu.Lock()
names := []string{vmName}
if vmName == "" {
names = make([]string, 0, len(typing.remoteQueues))
for name := range typing.remoteQueues {
names = append(names, name)
}
}
for _, name := range names {
ch := typing.remoteQueues[name]
if ch == nil {
delete(typing.lastHintAt, name)
} else if !typing.closing[name] {
typing.closing[name] = true
close(ch)
}
}
typing.mu.Unlock()
}
func (a *App) runRemoteTextQueue(vmName string, ch <-chan remoteTextItem) {
defer func() {
typing.mu.Lock()
delete(typing.remoteQueues, vmName)
delete(typing.lastHintAt, vmName)
delete(typing.closing, vmName)
typing.mu.Unlock()
}()
for item := range ch {
dir := item.vmDir
combined := item.text
@@ -201,7 +236,10 @@ func (a *App) runRemoteTextQueue(vmName string, ch <-chan remoteTextItem) {
if !isControlOnlyText(combined) {
for draining := true; draining; {
select {
case next := <-ch:
case next, ok := <-ch:
if !ok {
return // the VM was removed while draining the queue
}
if isControlOnlyText(next.text) {
_, _ = a.injectTextIntoVM(vmName, dir, combined, true)
combined = next.text
+22
View File
@@ -0,0 +1,22 @@
package app
import (
"testing"
"time"
)
func TestRemoteTextWorkerExitsWithPendingTextOnClosedQueue(t *testing.T) {
queue := make(chan remoteTextItem, 1)
queue <- remoteTextItem{text: "pending input"}
close(queue)
done := make(chan struct{})
go func() {
defer close(done)
new(App).runRemoteTextQueue("removed-test-vm", queue)
}()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("worker kept draining the closed queue")
}
}
+53 -62
View File
@@ -13,6 +13,7 @@ import (
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// vmMonitors holds per-VM background log tailers & boot/install heartbeats.
@@ -49,12 +50,15 @@ func stopAllVMMonitors() {
}
func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Time) {
stopVMMonitor(name)
if detail.Directory == "" {
stopVMMonitor(name)
return
}
ctx, cancel := context.WithCancel(a.baseCtx())
vmMonitors.mu.Lock()
if cur, ok := vmMonitors.entries[name]; ok {
cur.cancel()
}
vmMonitors.seq++
myID := vmMonitors.seq
vmMonitors.entries[name] = struct {
@@ -82,9 +86,8 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
diskPath := filepath.Join(detail.Directory, "disk.qcow2")
// Only read logs belonging to this boot (ignore files last touched before StartVM).
serialOff := initialLogOffset(serialPath, startAt)
qemuOff := initialLogOffset(qemuPath, startAt)
var serialPartial, qemuPartial string
serial := logTail{offset: initialLogOffset(serialPath, startAt)}
qemu := logTail{offset: initialLogOffset(qemuPath, startAt)}
seenEvents := map[string]bool{}
lastDiskSize := fileSizeBytes(diskPath)
@@ -104,16 +107,13 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
case <-ctx.Done():
return
case <-logTicker.C:
var newLines []string
serialOff, serialPartial, newLines = readNewLogLines(serialPath, serialOff, serialPartial)
for _, line := range newLines {
for _, line := range serial.read(serialPath) {
if key, msg := parseSerialMilestone(loc, line); msg != "" && !seenEvents[key] {
seenEvents[key] = true
a.emitLog(name, msg)
}
}
qemuOff, qemuPartial, newLines = readNewLogLines(qemuPath, qemuOff, qemuPartial)
for _, line := range newLines {
for _, line := range qemu.read(qemuPath) {
if key, msg := parseQemuMilestone(loc, line); msg != "" {
if key != "" && seenEvents[key] {
continue
@@ -214,44 +214,57 @@ func initialLogOffset(path string, startAt time.Time) int64 {
return 0
}
func readNewLogLines(path string, offset int64, partial string) (int64, string, []string) {
info, err := os.Stat(path)
if err != nil {
return offset, partial, nil
}
// Log rotated or recreated (e.g., new boot overwrote serial.log / qemu.log).
if info.Size() < offset {
offset = 0
partial = ""
}
if info.Size() == offset {
return offset, partial, nil
}
const maxMonitorLine = 64 << 10
type logTail struct {
offset int64
partial string
skipping bool // an oversized line continues into the next read
}
func (t *logTail) read(path string) []string {
f, err := os.Open(path)
if err != nil {
return offset, partial, nil
return nil
}
defer f.Close()
if _, err := f.Seek(offset, io.SeekStart); err != nil {
return offset, partial, nil
info, err := f.Stat()
if err != nil {
return nil
}
// Log rotated or recreated (e.g., new boot overwrote serial.log / qemu.log).
if info.Size() < t.offset {
*t = logTail{}
}
if info.Size() == t.offset {
return nil
}
const maxChunk = 256 * 1024
data, err := io.ReadAll(io.LimitReader(f, maxChunk))
if err != nil || len(data) == 0 {
return offset, partial, nil
data := make([]byte, min(info.Size()-t.offset, maxChunk))
n, err := f.ReadAt(data, t.offset)
if (err != nil && err != io.EOF) || n == 0 {
return nil
}
offset += int64(len(data))
combined := partial + string(data)
parts := strings.Split(combined, "\n")
partial = parts[len(parts)-1]
lines := make([]string, 0, len(parts)-1)
for _, p := range parts[:len(parts)-1] {
s := strings.TrimSpace(strings.TrimRight(p, "\r"))
if s != "" {
t.offset += int64(n)
var lines []string
for rest := string(data[:n]); rest != ""; {
line, after, complete := strings.Cut(rest, "\n")
rest = after
if t.skipping || len(t.partial)+len(line) > maxMonitorLine {
t.partial = ""
t.skipping = !complete
continue
}
if !complete {
t.partial = strings.Clone(t.partial + line)
break
}
if s := strings.TrimSpace(t.partial + line); s != "" {
lines = append(lines, s)
}
t.partial = ""
}
return offset, partial, lines
return lines
}
func parseSerialMilestone(loc i18n.Locale, line string) (key, msg string) {
@@ -364,24 +377,13 @@ func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Repo
case strings.Contains(lowExtra, "kernel-irqchip=on"):
irqMode = "on"
}
plan := host.SelectSafeAffinity(rep, detail.CPUs)
pinStr := vmstart.AffinitySummary(loc, rep, detail.Directory, pinPCores, detail.CPUs)
if loc == i18n.ZhCN {
coldStr := "关闭"
if qmpAddr != "" {
coldStr = "开启"
}
pinStr := "关"
if pinPCores && rep.HasHybridCores {
switch plan.Mode {
case "pcores":
pinStr = fmt.Sprintf("开(%dP/%d线程)", plan.CoreCount, plan.ThreadCount)
case "non_lpe":
pinStr = fmt.Sprintf("P+E(%d核/%d线程,避开LP-E)", plan.CoreCount, plan.ThreadCount)
default:
pinStr = fmt.Sprintf("自动跳过(%d核≥%dP线程)", detail.CPUs, plan.PThreads)
}
}
a.emitLog(name, fmt.Sprintf("[启动] 运行时 %s · %d 核 / %s(可用提交内存 %.1f GB)· 图形 %s · 磁盘 %s · irqchip=%s · 绑P核=%s · Win10冷重启=%s",
a.emitLog(name, fmt.Sprintf("[启动] 运行时 %s · %d 核 / %s(可用提交内存 %.1f GB)· 图形 %s · 磁盘 %s · irqchip=%s · 核心映射=%s · Win10冷重启=%s",
rtCommit, detail.CPUs, detail.Memory, rep.CommitAvailGB, detail.Graphics, strings.ToUpper(detail.DiskController), irqMode, pinStr, coldStr))
return
}
@@ -389,17 +391,6 @@ func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Repo
if qmpAddr != "" {
coldStr = "on"
}
pinStr := "off"
if pinPCores && rep.HasHybridCores {
switch plan.Mode {
case "pcores":
pinStr = fmt.Sprintf("on(%dP/%dT)", plan.CoreCount, plan.ThreadCount)
case "non_lpe":
pinStr = fmt.Sprintf("P+E(%dC/%dT,no-LPE)", plan.CoreCount, plan.ThreadCount)
default:
pinStr = fmt.Sprintf("skipped(%dvCPU>=%dPT)", detail.CPUs, plan.PThreads)
}
}
a.emitLog(name, fmt.Sprintf("[start] runtime %s · %d vCPU / %s (commit free %.1f GB) · graphics %s · disk %s · irqchip=%s · P-core=%s · Win10-cold-reboot=%s",
a.emitLog(name, fmt.Sprintf("[start] runtime %s · %d vCPU / %s (commit free %.1f GB) · graphics %s · disk %s · irqchip=%s · affinity=%s · Win10-cold-reboot=%s",
rtCommit, detail.CPUs, detail.Memory, rep.CommitAvailGB, detail.Graphics, strings.ToUpper(detail.DiskController), irqMode, pinStr, coldStr))
}
+41
View File
@@ -1,6 +1,9 @@
package app
import (
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
@@ -9,6 +12,44 @@ import (
"github.com/Nwflower/reims-go/internal/i18n"
)
func TestLogTailDiscardsOversizeLinesAndResumes(t *testing.T) {
path := filepath.Join(t.TempDir(), "serial.log")
write := func(flags int, text string) {
t.Helper()
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|flags, 0o600)
if err != nil {
t.Fatal(err)
}
defer f.Close()
if _, err := f.WriteString(text); err != nil {
t.Fatal(err)
}
}
var tail logTail
write(os.O_TRUNC, "boot\r\n"+strings.Repeat("x", maxMonitorLine))
if got := tail.read(path); !slices.Equal(got, []string{"boot"}) || len(tail.partial) != maxMonitorLine {
t.Fatal("expected a complete line and an unfinished line at the limit")
}
for range 12 {
write(os.O_APPEND, strings.Repeat("y", maxMonitorLine))
if got := tail.read(path); len(got) != 0 || !tail.skipping || len(tail.partial) != 0 {
t.Fatal("oversized line retained across polls")
}
}
write(os.O_APPEND, "ignored\r\nnext\r\npar")
if got := tail.read(path); !slices.Equal(got, []string{"next"}) {
t.Fatalf("after discarded line: %q", got)
}
write(os.O_APPEND, "tial\n"+strings.Repeat("z", maxMonitorLine+1))
if got := tail.read(path); !slices.Equal(got, []string{"partial"}) || !tail.skipping {
t.Fatalf("after split line: %q", got)
}
write(os.O_TRUNC, "new boot\n")
if got := tail.read(path); !slices.Equal(got, []string{"new boot"}) {
t.Fatalf("after truncation: %q", got)
}
}
func TestParseSerialAndQemuMilestones(t *testing.T) {
k, msg := parseSerialMilestone(i18n.ZhCN, `BdsDxe: starting Boot0002 "UEFI QEMU HARDDISK"`)
if k != "serial:boot" || !strings.Contains(msg, "OpenCore") {
+7 -4
View File
@@ -51,16 +51,19 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s
}); err != nil {
return err
}
if !cfg.AutoPinPCores || !rep.HasHybridCores || rep.PCoreMask == 0 {
return nil
}
vms, err := prep.Client.List(ctx)
if err != nil {
return nil
}
for _, vm := range vms {
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
fmt.Fprintln(os.Stderr, vmstart.PinQEMU(cfg.Locale, rep, *vm.PID, d.CPUs))
vmDir := vm.Dir
if vmDir == "" {
vmDir = d.Directory
}
if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" {
fmt.Fprintln(os.Stderr, line)
}
}
}
return nil
+118
View File
@@ -0,0 +1,118 @@
package reims
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// DiskSnapshot describes one internal qcow2 snapshot returned by `qemu-img info --output=json`.
type DiskSnapshot struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedAt int64 `json:"created_at"` // Unix seconds
VMStateBytes int64 `json:"vm_state_bytes"` // 0 for offline disk-only snapshots
}
type qemuImgInfoJSON struct {
Format string `json:"format"`
Snapshots []struct {
ID string `json:"id"`
Name string `json:"name"`
VMStateSize int64 `json:"vm-state-size"`
DateSec int64 `json:"date-sec"`
} `json:"snapshots"`
}
// ParseDiskSnapshotsJSON parses `qemu-img info --output=json` output.
func ParseDiskSnapshotsJSON(raw []byte) (string, []DiskSnapshot, error) {
var info qemuImgInfoJSON
if err := json.Unmarshal(raw, &info); err != nil {
return "", nil, fmt.Errorf("parse qemu-img info json: %w", err)
}
out := make([]DiskSnapshot, 0, len(info.Snapshots))
for _, s := range info.Snapshots {
out = append(out, DiskSnapshot{
ID: s.ID,
Name: s.Name,
CreatedAt: s.DateSec,
VMStateBytes: s.VMStateSize,
})
}
return strings.ToLower(strings.TrimSpace(info.Format)), out, nil
}
// ListDiskSnapshots lists internal qcow2 snapshots via `qemu-img info --output=json`.
func ListDiskSnapshots(ctx context.Context, qemuImgPath string, env []string, diskPath string) ([]DiskSnapshot, error) {
if _, err := os.Stat(qemuImgPath); err != nil {
return nil, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
cmd := exec.CommandContext(ctx, qemuImgPath, "info", "--output=json", diskPath)
configureCmd(cmd)
cmd.Env = env
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
msg := strings.TrimSpace(stderr.String())
if msg != "" {
return nil, fmt.Errorf("qemu-img info %s: %s", filepath.Base(diskPath), msg)
}
return nil, fmt.Errorf("qemu-img info %s: %w", filepath.Base(diskPath), err)
}
format, snaps, err := ParseDiskSnapshotsJSON(stdout.Bytes())
if err != nil {
return nil, err
}
if format != "qcow2" {
return nil, nil
}
return snaps, nil
}
// ValidateSnapshotName checks that a snapshot tag is safe for `qemu-img snapshot`.
func ValidateSnapshotName(snapName string) (string, error) {
snapName = strings.TrimSpace(snapName)
if snapName == "" {
return "", fmt.Errorf("snapshot name is required")
}
if len([]rune(snapName)) > 64 {
return "", fmt.Errorf("snapshot name must be 64 characters or fewer")
}
for _, r := range snapName {
if r < 0x20 || r == 0x7f || r == '"' || r == '\'' || r == '`' || r == '\\' {
return "", fmt.Errorf("snapshot name contains invalid characters")
}
}
return snapName, nil
}
// RunDiskSnapshot executes `qemu-img snapshot <flag> <snapName> <diskPath>`
// where flag is "-c" (create), "-a" (apply/restore), or "-d" (delete).
func RunDiskSnapshot(ctx context.Context, qemuImgPath string, env []string, flag, snapName, diskPath string) error {
if _, err := os.Stat(qemuImgPath); err != nil {
return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
snapName, err := ValidateSnapshotName(snapName)
if err != nil {
return err
}
cmd := exec.CommandContext(ctx, qemuImgPath, "snapshot", flag, snapName, diskPath)
configureCmd(cmd)
cmd.Env = env
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
msg := strings.TrimSpace(stderr.String())
if msg != "" {
return fmt.Errorf("qemu-img snapshot %s %q: %s", flag, snapName, msg)
}
return fmt.Errorf("qemu-img snapshot %s %q: %w", flag, snapName, err)
}
return nil
}
+20
View File
@@ -276,6 +276,26 @@ func TestServerAuthClipboardAndSharedFiles(t *testing.T) {
}
}
func TestUnregisterVMReleasesVMState(t *testing.T) {
srv := NewServer(&memClipboard{})
cfg := VMConfig{VMName: "deleted-vm", Token: strings.Repeat("a", 64), SharedDir: t.TempDir()}
srv.RegisterVM(cfg)
if _, err := srv.getOrCreateDAVHandler(cfg.VMName, cfg.SharedDir); err != nil {
t.Fatal(err)
}
srv.mu.Lock()
srv.davHandlers[cfg.VMName+"/drives/C"] = srv.davHandlers[cfg.VMName]
srv.davRoots[cfg.VMName+"/drives/C"] = `C:\`
srv.mu.Unlock()
srv.UnregisterVM(cfg.VMName)
srv.mu.RLock()
defer srv.mu.RUnlock()
if len(srv.vms) != 0 || len(srv.davHandlers) != 0 || len(srv.davRoots) != 0 {
t.Fatalf("VM state remains: vms=%d davHandlers=%d davRoots=%d", len(srv.vms), len(srv.davHandlers), len(srv.davRoots))
}
}
func TestServerWebDAVAuthAndOperations(t *testing.T) {
tmp := t.TempDir()
vmDir := filepath.Join(tmp, "vm")
+16
View File
@@ -381,6 +381,22 @@ func (s *Server) RegisterVM(cfg VMConfig) {
s.mu.Unlock()
}
// UnregisterVM releases all host-side state owned by a deleted VM. In-flight
// requests retain only their own snapshot and fail authentication on retry.
func (s *Server) UnregisterVM(vmName string) {
s.mu.Lock()
delete(s.vms, vmName)
delete(s.davHandlers, vmName)
delete(s.davRoots, vmName)
for key := range s.davHandlers {
if strings.HasPrefix(key, vmName+"/") {
delete(s.davHandlers, key)
delete(s.davRoots, key)
}
}
s.mu.Unlock()
}
// SetHostTextHandler registers a callback invoked when a host-side window hook
// (e.g. reims-vgpu-window WM_CHAR bridge) submits Unicode text to POST /v1/host-text.
func (s *Server) SetHostTextHandler(fn func(vmName, text string)) {
+3
View File
@@ -4,3 +4,6 @@ package host
// ForegroundPID is not implemented off Windows and always reports no owner.
func ForegroundPID() uint32 { return 0 }
// FocusProcessWindow is not implemented off Windows.
func FocusProcessWindow(uint32) bool { return false }
+74 -1
View File
@@ -2,7 +2,22 @@
package host
import "unsafe"
import (
"syscall"
"unsafe"
)
var (
procEnumWindows = user32.NewProc("EnumWindows")
procIsWindowVisible = user32.NewProc("IsWindowVisible")
procIsIconic = user32.NewProc("IsIconic")
procShowWindow = user32.NewProc("ShowWindow")
procSetForegroundWin = user32.NewProc("SetForegroundWindow")
procBringWindowToTop = user32.NewProc("BringWindowToTop")
procAttachThreadInput = user32.NewProc("AttachThreadInput")
)
const swRestore = 9
// ForegroundPID returns the process that owns the foreground window, or 0
// when there is none (locked screen, desktop focused).
@@ -15,3 +30,61 @@ func ForegroundPID() uint32 {
_, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
return pid
}
// FocusProcessWindow finds the primary visible top-level window belonging to
// pid, restores it if minimized, and brings it to the foreground.
func FocusProcessWindow(pid uint32) bool {
if pid == 0 {
return false
}
var found uintptr
cb := syscall.NewCallback(func(hwnd uintptr, _ uintptr) uintptr {
vis, _, _ := procIsWindowVisible.Call(hwnd)
if vis == 0 {
return 1
}
var winPID uint32
_, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&winPID)))
if winPID == pid {
found = hwnd
return 0
}
return 1
})
_, _, _ = procEnumWindows.Call(cb, 0)
if found == 0 {
return false
}
iconic, _, _ := procIsIconic.Call(found)
if iconic != 0 {
_, _, _ = procShowWindow.Call(found, swRestore)
}
fgHwnd, _, _ := procGetForegroundWindow.Call()
curTid, _, _ := procGetCurrentThreadId.Call()
var fgTid uintptr
if fgHwnd != 0 {
fgTid, _, _ = procGetWindowThreadProcessId.Call(fgHwnd, 0)
}
targetTid, _, _ := procGetWindowThreadProcessId.Call(found, 0)
attachedFg := false
attachedTarget := false
if fgTid != 0 && fgTid != curTid {
if r, _, _ := procAttachThreadInput.Call(curTid, fgTid, 1); r != 0 {
attachedFg = true
}
}
if targetTid != 0 && targetTid != curTid && targetTid != fgTid {
if r, _, _ := procAttachThreadInput.Call(curTid, targetTid, 1); r != 0 {
attachedTarget = true
}
}
_, _, _ = procBringWindowToTop.Call(found)
_, _, _ = procSetForegroundWin.Call(found)
if attachedTarget {
_, _, _ = procAttachThreadInput.Call(curTid, targetTid, 0)
}
if attachedFg {
_, _, _ = procAttachThreadInput.Call(curTid, fgTid, 0)
}
return true
}
+87 -15
View File
@@ -34,22 +34,30 @@ type WHPXCapabilities struct {
NestedVirtProbeError string `json:"nested_virt_probe_error,omitempty"`
}
type LogicalCPUInfo struct {
Index int `json:"index"`
CoreIndex int `json:"core_index"`
Tier string `json:"tier"` // "p" | "e" | "lpe" | "standard"
SMT bool `json:"smt"`
}
type Report struct {
OS string `json:"os"`
Arch string `json:"arch"`
LogicalCPUs int `json:"logical_cpus"`
PhysicalCores int `json:"physical_cores"`
HasHybridCores bool `json:"has_hybrid_cores"`
PCoreCount int `json:"p_core_count"`
ECoreCount int `json:"e_core_count"`
LPECoreCount int `json:"lpe_core_count,omitempty"`
PCoreMask uint64 `json:"p_core_mask"`
PCoreMaskHex string `json:"p_core_mask_hex"`
PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"`
ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"`
NonLPEMask uint64 `json:"non_lpe_mask,omitempty"`
NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"`
NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"`
OS string `json:"os"`
Arch string `json:"arch"`
LogicalCPUs int `json:"logical_cpus"`
PhysicalCores int `json:"physical_cores"`
HasHybridCores bool `json:"has_hybrid_cores"`
PCoreCount int `json:"p_core_count"`
ECoreCount int `json:"e_core_count"`
LPECoreCount int `json:"lpe_core_count,omitempty"`
PCoreMask uint64 `json:"p_core_mask"`
PCoreMaskHex string `json:"p_core_mask_hex"`
PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"`
ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"`
NonLPEMask uint64 `json:"non_lpe_mask,omitempty"`
NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"`
NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"`
CPUTopology []LogicalCPUInfo `json:"cpu_topology,omitempty"`
TotalRAMGB float64 `json:"total_ram_gb"`
AvailRAMGB float64 `json:"avail_ram_gb"`
MemoryLoadPct int `json:"memory_load_pct"`
@@ -120,3 +128,67 @@ func PickRecommendedGPU(gpus []GPUInfo) *GPUInfo {
}
return nil
}
// AllCPUsMask returns the 64-bit affinity mask covering logical CPUs 0..n-1
// (capped at 64 bits, matching Win32 SetProcessAffinityMask group 0).
func AllCPUsMask(logicalCPUs int) uint64 {
if logicalCPUs <= 0 {
return 0
}
if logicalCPUs >= 64 {
return ^uint64(0)
}
return (uint64(1) << uint(logicalCPUs)) - 1
}
// CPUsToMask encodes a list of logical CPU indices (0..maxCPUs-1, max 63) into
// an affinity bitmask and returns the normalized sorted CPU list alongside it.
func CPUsToMask(cpus []int, maxCPUs int) (uint64, []int) {
limit := maxCPUs
if limit <= 0 || limit > 64 {
limit = 64
}
var mask uint64
for _, idx := range cpus {
if idx >= 0 && idx < limit {
mask |= uint64(1) << uint(idx)
}
}
return mask, MaskToCPUs(mask, limit)
}
// MaskToCPUs decodes an affinity bitmask into sorted logical CPU indices.
func MaskToCPUs(mask uint64, maxCPUs int) []int {
limit := maxCPUs
if limit <= 0 || limit > 64 {
limit = 64
}
var out []int
for i := 0; i < limit; i++ {
if mask&(uint64(1)<<uint(i)) != 0 {
out = append(out, i)
}
}
return out
}
// DefaultCPUTopology constructs a homogeneous fallback topology when detailed
// OS processor-core probing is unavailable.
func DefaultCPUTopology(logicalCPUs int) []LogicalCPUInfo {
limit := logicalCPUs
if limit < 0 {
limit = 0
}
if limit > 64 {
limit = 64
}
out := make([]LogicalCPUInfo, limit)
for i := 0; i < limit; i++ {
out[i] = LogicalCPUInfo{
Index: i,
CoreIndex: i,
Tier: "standard",
}
}
return out
}
+14 -1
View File
@@ -14,6 +14,7 @@ func Inspect(dataRoot string) Report {
OS: runtime.GOOS,
Arch: runtime.GOARCH,
LogicalCPUs: runtime.NumCPU(),
CPUTopology: DefaultCPUTopology(runtime.NumCPU()),
DataRoot: dataRoot,
WHPX: WHPXUnsupported,
RecommendedResolution: rec,
@@ -23,7 +24,19 @@ func Inspect(dataRoot string) Report {
}
func PinProcessToPCores(pid uint32, mask uint64) error {
return fmt.Errorf("P-core affinity pinning is only supported on Windows (current OS: %s)", runtime.GOOS)
return SetProcessAffinityMask(pid, mask)
}
func SetProcessAffinityMask(pid uint32, mask uint64) error {
return fmt.Errorf("process CPU affinity is only supported on Windows (current OS: %s)", runtime.GOOS)
}
func GetProcessAffinityMask(pid uint32) (uint64, uint64, error) {
return 0, 0, fmt.Errorf("process CPU affinity is only supported on Windows (current OS: %s)", runtime.GOOS)
}
func DisableProcessPowerThrottling(pid uint32) error {
return fmt.Errorf("process power throttling control is only supported on Windows (current OS: %s)", runtime.GOOS)
}
func EnableWHPXElevated() error {
+13
View File
@@ -22,3 +22,16 @@ func TestGPUClassificationAndRecommendation(t *testing.T) {
t.Fatalf("expected NVIDIA discrete GPU to be recommended, got %#v", rec)
}
}
func TestAffinityMaskHelpers(t *testing.T) {
if got := AllCPUsMask(8); got != 0xFF {
t.Fatalf("AllCPUsMask(8) = 0x%X, want 0xFF", got)
}
if got := AllCPUsMask(64); got != ^uint64(0) {
t.Fatalf("AllCPUsMask(64) = 0x%X, want all-ones", got)
}
mask, cpus := CPUsToMask([]int{4, 1, 4, -1, 16}, 16)
if mask != 0x12 || len(cpus) != 2 || cpus[0] != 1 || cpus[1] != 4 {
t.Fatalf("CPUsToMask = (0x%X, %v), want (0x12, [1 4])", mask, cpus)
}
}
+97 -4
View File
@@ -5,8 +5,10 @@ package host
import (
"encoding/binary"
"fmt"
"math/bits"
"path/filepath"
"runtime"
"sort"
"strings"
"syscall"
"unsafe"
@@ -20,6 +22,8 @@ var (
procDeviceIoControl = kernel32.NewProc("DeviceIoControl")
procOpenProcess = kernel32.NewProc("OpenProcess")
procSetProcessAffinityMask = kernel32.NewProc("SetProcessAffinityMask")
procGetProcessAffinityMask = kernel32.NewProc("GetProcessAffinityMask")
procSetProcessInformation = kernel32.NewProc("SetProcessInformation")
procCloseHandle = kernel32.NewProc("CloseHandle")
advapi32 = syscall.NewLazyDLL("advapi32.dll")
@@ -37,8 +41,12 @@ const (
regSZ = 1
regExpandSZ = 2
regMultiSZ = 7
processSetInformation = 0x0200
whvCapHypervisorPresent = 0x00000001
processSetInformation = 0x0200
processQueryLimitedInformation = 0x1000
processPowerThrottlingClass = 4
powerThrottlingCurrentVersion = 1
powerThrottlingExecutionSpeed = 0x1
whvCapHypervisorPresent = 0x00000001
)
type memoryStatusEx struct {
@@ -84,6 +92,10 @@ func Inspect(dataRoot string) Report {
rep.NonLPEMaskHex = fmt.Sprintf("0x%X", topo.nonLPEMask)
rep.NonLPELogicalCPUs = topo.nonLPELPs
}
rep.CPUTopology = topo.cpus
}
if len(rep.CPUTopology) == 0 {
rep.CPUTopology = DefaultCPUTopology(rep.LogicalCPUs)
}
if totalGB, availGB, ok := probeMemoryGB(); ok {
rep.TotalRAMGB = totalGB
@@ -110,8 +122,13 @@ func Inspect(dataRoot string) Report {
return rep
}
// PinProcessToPCores restricts the given PID's affinity mask to P-cores.
// PinProcessToPCores restricts the given PID's affinity mask to the given bitmask.
func PinProcessToPCores(pid uint32, mask uint64) error {
return SetProcessAffinityMask(pid, mask)
}
// SetProcessAffinityMask sets the Win32 processor affinity mask for pid.
func SetProcessAffinityMask(pid uint32, mask uint64) error {
if mask == 0 {
return fmt.Errorf("invalid affinity mask 0")
}
@@ -127,6 +144,60 @@ func PinProcessToPCores(pid uint32, mask uint64) error {
return nil
}
// GetProcessAffinityMask reads the current process and system affinity masks for pid.
func GetProcessAffinityMask(pid uint32) (uint64, uint64, error) {
h, _, err := procOpenProcess.Call(uintptr(processQueryLimitedInformation), 0, uintptr(pid))
if h == 0 {
return 0, 0, fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer procCloseHandle.Call(h)
var procMask, sysMask uintptr
r, _, err := procGetProcessAffinityMask.Call(
h,
uintptr(unsafe.Pointer(&procMask)),
uintptr(unsafe.Pointer(&sysMask)),
)
if r == 0 {
return 0, 0, fmt.Errorf("GetProcessAffinityMask(%d): %w", pid, err)
}
return uint64(procMask), uint64(sysMask), nil
}
type processPowerThrottlingState struct {
Version uint32
ControlMask uint32
StateMask uint32
}
// DisableProcessPowerThrottling opts pid out of Windows EcoQoS execution-speed
// power throttling so background / unfocused QEMU threads are not parked onto
// efficiency or LP-E cores by the scheduler.
func DisableProcessPowerThrottling(pid uint32) error {
if err := procSetProcessInformation.Find(); err != nil {
return err
}
h, _, err := procOpenProcess.Call(uintptr(processSetInformation), 0, uintptr(pid))
if h == 0 {
return fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer procCloseHandle.Call(h)
state := processPowerThrottlingState{
Version: powerThrottlingCurrentVersion,
ControlMask: powerThrottlingExecutionSpeed,
StateMask: 0,
}
r, _, err := procSetProcessInformation.Call(
h,
uintptr(processPowerThrottlingClass),
uintptr(unsafe.Pointer(&state)),
uintptr(unsafe.Sizeof(state)),
)
if r == 0 {
return fmt.Errorf("SetProcessInformation(ProcessPowerThrottling, %d): %w", pid, err)
}
return nil
}
// EnableWHPXElevated invokes a standard Windows UAC prompt to enable Windows Hypervisor Platform.
func EnableWHPXElevated() error {
verb, _ := syscall.UTF16PtrFromString("runas")
@@ -194,6 +265,7 @@ type hybridTopology struct {
pLPs []int
eLPs []int
nonLPELPs []int
cpus []LogicalCPUInfo
}
func probeHybridTopology() (topo hybridTopology, ok bool) {
@@ -240,22 +312,43 @@ func probeHybridTopology() (topo hybridTopology, ok bool) {
return
}
hasThreeTiers := len(effSet) >= 3
isHybrid := len(effSet) >= 2
topo.phys = len(cores)
var eMask uint64
for _, c := range cores {
for coreIdx, c := range cores {
tier := "standard"
switch {
case c.eff == maxEff:
topo.pCount++
topo.pMask |= c.mask
topo.nonLPEMask |= c.mask
if isHybrid {
tier = "p"
}
case hasThreeTiers && c.eff == minEff:
topo.lpeCount++
tier = "lpe"
default:
topo.eCount++
eMask |= c.mask
topo.nonLPEMask |= c.mask
tier = "e"
}
smt := bits.OnesCount64(c.mask) > 1
for i := 0; i < 64; i++ {
if c.mask&(uint64(1)<<uint(i)) != 0 {
topo.cpus = append(topo.cpus, LogicalCPUInfo{
Index: i,
CoreIndex: coreIdx,
Tier: tier,
SMT: smt,
})
}
}
}
sort.Slice(topo.cpus, func(i, j int) bool {
return topo.cpus[i].Index < topo.cpus[j].Index
})
if !hasThreeTiers {
topo.nonLPEMask = 0
}
+35
View File
@@ -0,0 +1,35 @@
//go:build windows
package host
import (
"os"
"testing"
)
func TestWindowsProcessAffinityAndTopology(t *testing.T) {
pid := uint32(os.Getpid())
procMask, sysMask, err := GetProcessAffinityMask(pid)
if err != nil {
t.Fatalf("GetProcessAffinityMask(self=%d): %v", pid, err)
}
if procMask == 0 || sysMask == 0 {
t.Fatalf("unexpected zero masks: proc=0x%X sys=0x%X", procMask, sysMask)
}
if procMask&sysMask != procMask {
t.Fatalf("procMask 0x%X is not subset of sysMask 0x%X", procMask, sysMask)
}
rep := Inspect(t.TempDir())
if len(rep.CPUTopology) == 0 {
t.Fatalf("expected non-empty CPUTopology on Windows")
}
for i, c := range rep.CPUTopology {
if i > 0 && c.Index <= rep.CPUTopology[i-1].Index {
t.Fatalf("CPUTopology not strictly sorted at %d: %+v", i, rep.CPUTopology)
}
if c.Tier == "" {
t.Fatalf("empty tier for CPU %d", c.Index)
}
}
}
+78
View File
@@ -0,0 +1,78 @@
package thumb
import (
"bufio"
"fmt"
"image"
"image/color"
"io"
"os"
)
// LoadPreview box-filters a screendump and returns nil for a blank frame.
// PPM is the live capture format. Read one scanline at a time so a preview
// never needs a full-resolution frame in the Go heap.
func LoadPreview(path, format string, maxWidth int) (image.Image, error) {
if maxWidth < 1 {
return nil, fmt.Errorf("invalid preview width %d", maxWidth)
}
if format == "png" {
img, err := Load(path, format)
if err != nil || Blank(img) {
return nil, err
}
return Scale(img, maxWidth), nil
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
r := bufio.NewReader(f)
size, err := ppmSize(r)
if err != nil {
return nil, err
}
w, h := size.X, size.Y
dw := min(w, maxWidth)
dh := max(1, h*dw/w)
img := image.NewRGBA(image.Rect(0, 0, dw, dh))
row := make([]byte, w*3)
sums := make([][3]uint64, dw)
step := max(1, w/64)
var samples blankSamples
for y := 0; y < dh; y++ {
y0, y1 := y*h/dh, (y+1)*h/dh
clear(sums)
for sy := y0; sy < y1; sy++ {
if _, err := io.ReadFull(r, row); err != nil {
return nil, fmt.Errorf("ppm: %w", err)
}
if sy%step == 0 {
for x := 0; x < w; x += step {
samples.add(row[3*x], row[3*x+1], row[3*x+2])
}
}
for x := range sums {
block := row[3*(x*w/dw) : 3*((x+1)*w/dw)]
var red, green, blue uint32
for i := 0; i < len(block); i += 3 {
red += uint32(block[i])
green += uint32(block[i+1])
blue += uint32(block[i+2])
}
sums[x][0] += uint64(red)
sums[x][1] += uint64(green)
sums[x][2] += uint64(blue)
}
}
for x, sum := range sums {
pixels := uint64(((x+1)*w/dw - x*w/dw) * (y1 - y0))
img.SetRGBA(x, y, color.RGBA{uint8(sum[0] / pixels), uint8(sum[1] / pixels), uint8(sum[2] / pixels), 255})
}
}
if samples.blank() {
return nil, nil
}
return img, nil
}
+47 -27
View File
@@ -31,6 +31,27 @@ func Load(path, format string) (image.Image, error) {
// decodePPM reads a binary PPM (P6, maxval ≤ 255), the format QEMU's
// screendump writes when no format is given.
func decodePPM(r *bufio.Reader) (image.Image, error) {
size, err := ppmSize(r)
if err != nil {
return nil, err
}
w, h := size.X, size.Y
img := image.NewRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
row := img.Pix[y*img.Stride : (y+1)*img.Stride]
// Expand RGB to RGBA backwards in the same row.
if _, err := io.ReadFull(r, row[:w*3]); err != nil {
return nil, fmt.Errorf("ppm: %w", err)
}
for x := w - 1; x >= 0; x-- {
copy(row[x*4:x*4+3], row[x*3:x*3+3])
row[x*4+3] = 255
}
}
return img, nil
}
func ppmSize(r *bufio.Reader) (image.Point, error) {
tok := func() (string, error) {
var b []byte
for {
@@ -54,34 +75,26 @@ func decodePPM(r *bufio.Reader) (image.Image, error) {
}
magic, err := tok()
if err != nil {
return nil, err
return image.Point{}, err
}
if magic != "P6" {
return nil, fmt.Errorf("ppm: unsupported magic %q", magic)
return image.Point{}, fmt.Errorf("ppm: unsupported magic %q", magic)
}
var dims [3]int
for i := range dims {
s, err := tok()
if err != nil {
return nil, err
return image.Point{}, err
}
if dims[i], err = strconv.Atoi(s); err != nil {
return nil, fmt.Errorf("ppm: bad header: %w", err)
return image.Point{}, fmt.Errorf("ppm: bad header: %w", err)
}
}
w, h, maxv := dims[0], dims[1], dims[2]
if w <= 0 || h <= 0 || w > 16384 || h > 16384 || maxv <= 0 || maxv > 255 {
return nil, errors.New("ppm: unsupported size or depth")
return image.Point{}, errors.New("ppm: unsupported size or depth")
}
px := make([]byte, w*h*3)
if _, err := io.ReadFull(r, px); err != nil {
return nil, fmt.Errorf("ppm: %w", err)
}
img := image.NewRGBA(image.Rect(0, 0, w, h))
for i, j := 0, 0; i < len(px); i, j = i+3, j+4 {
img.Pix[j], img.Pix[j+1], img.Pix[j+2], img.Pix[j+3] = px[i], px[i+1], px[i+2], 255
}
return img, nil
return image.Pt(w, h), nil
}
// Scale shrinks img to at most maxW pixels wide by averaging each source
@@ -153,26 +166,33 @@ func scaleRGBA(dst, src *image.RGBA, sw, sh, dw, dh int) {
func Blank(img image.Image) bool {
b := img.Bounds()
step := max(1, b.Dx()/64)
var first color.RGBA
firstSet := false
diff := 0
total := 0
var samples blankSamples
for y := b.Min.Y; y < b.Max.Y; y += step {
for x := b.Min.X; x < b.Max.X; x += step {
r, g, bl, _ := img.At(x, y).RGBA()
c := color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(bl >> 8), 255}
if !firstSet {
first, firstSet = c, true
}
if absDiff(c.R, first.R)+absDiff(c.G, first.G)+absDiff(c.B, first.B) > 24 {
diff++
}
total++
samples.add(uint8(r>>8), uint8(g>>8), uint8(bl>>8))
}
}
return total == 0 || diff*100 < total // under 1% of samples differ
return samples.blank()
}
type blankSamples struct {
first color.RGBA
total, diff int
}
func (s *blankSamples) add(r, g, b byte) {
if s.total == 0 {
s.first = color.RGBA{r, g, b, 255}
}
s.total++
if absDiff(r, s.first.R)+absDiff(g, s.first.G)+absDiff(b, s.first.B) > 24 {
s.diff++
}
}
func (s blankSamples) blank() bool { return s.total == 0 || s.diff*100 < s.total }
func absDiff(a, b uint8) int {
if a > b {
return int(a - b)
+70
View File
@@ -6,6 +6,8 @@ import (
"fmt"
"image"
"image/color"
"os"
"path/filepath"
"testing"
)
@@ -42,6 +44,24 @@ func TestDecodePPMRejectsP3(t *testing.T) {
}
}
func TestDecodePPMRejectsTruncatedPixels(t *testing.T) {
data := ppm(3, 2, func(x, y int) [3]byte { return [3]byte{} })
if _, err := decodePPM(bufio.NewReader(bytes.NewReader(data[:len(data)-1]))); err == nil {
t.Fatal("want error for truncated pixel data")
}
}
func BenchmarkDecodePPM4K(b *testing.B) {
data := ppm(3840, 2160, func(x, y int) [3]byte { return [3]byte{byte(x), byte(y), 7} })
b.SetBytes(int64(len(data)))
b.ReportAllocs()
for i := 0; i < b.N; i++ {
if _, err := decodePPM(bufio.NewReader(bytes.NewReader(data))); err != nil {
b.Fatal(err)
}
}
}
func TestScaleKeepsAspect(t *testing.T) {
img := image.NewRGBA(image.Rect(0, 0, 1920, 1080))
out := Scale(img, 640)
@@ -79,6 +99,56 @@ func BenchmarkScale4K(b *testing.B) {
}
}
func BenchmarkPreview4K(b *testing.B) {
path := filepath.Join(b.TempDir(), "4k.ppm")
data := ppm(3840, 2160, func(x, y int) [3]byte { return [3]byte{byte(x), byte(y), 7} })
if err := os.WriteFile(path, data, 0o600); err != nil {
b.Fatal(err)
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
img, err := LoadPreview(path, "ppm", 640)
if err != nil || img == nil {
b.Fatalf("load preview: %v", err)
}
if _, err := JPEG(img, 80); err != nil {
b.Fatal(err)
}
}
}
func TestPreviewMatchesFullFrame(t *testing.T) {
path := filepath.Join(t.TempDir(), "screen.ppm")
for _, tc := range []struct{ w, h, width int }{{301, 167, 64}, {11, 3, 640}, {43, 1, 5}, {100, 99, 1}} {
for _, flat := range []bool{false, true} {
data := ppm(tc.w, tc.h, func(x, y int) [3]byte {
if flat {
return [3]byte{32, 32, 32}
}
return [3]byte{byte(x * 53), byte(y * 77), byte(x + y)}
})
if err := os.WriteFile(path, data, 0o600); err != nil {
t.Fatal(err)
}
full, err := Load(path, "ppm")
if err != nil {
t.Fatal(err)
}
got, err := LoadPreview(path, "ppm", tc.width)
if err != nil || (got == nil) != Blank(full) {
t.Fatalf("preview %v: blank or decode mismatch: %v", tc, err)
}
if got != nil {
want := Scale(full, tc.width).(*image.RGBA)
if got.Bounds() != want.Bounds() || !bytes.Equal(got.(*image.RGBA).Pix, want.Pix) {
t.Fatalf("preview pixels differ for %v", tc)
}
}
}
}
}
func TestBlank(t *testing.T) {
flat := image.NewRGBA(image.Rect(0, 0, 200, 100))
if !Blank(flat) {
+221 -9
View File
@@ -9,8 +9,16 @@ import (
// VMItem is a lightweight summary shown inside the system tray menu.
type VMItem struct {
Name string
Running bool
Name string // identifier passed back to callbacks
Label string // display name (the VM's note); empty shows Name
State string // running | stopped | starting | stopping | broken
}
func (v VMItem) title() string {
if v.Label != "" {
return v.Label
}
return v.Name
}
// Snapshot holds the live state read each time the user opens the tray menu.
@@ -19,14 +27,218 @@ type Snapshot struct {
VMs []VMItem
}
// Callbacks wires tray actions back into the Wails application.
// Action is a per-VM command picked from the tray menu.
type Action int
const (
ActStart Action = iota + 1
ActStop
ActForceStop
ActRestart
ActShowWindow
ActScreenshot
ActSharedFolder
ActOpenInApp
)
// Callbacks wires tray actions back into the Wails application. Each runs
// on its own goroutine, never on the tray's window thread.
type Callbacks struct {
OnShow func()
OnStartVM func(name string)
OnStopVM func(name string)
OnOpenSharedDir func(name string)
OnQuit func()
GetSnapshot func() Snapshot
OnShow func()
OnNewVM func()
OnVMAction func(name string, act Action)
OnQuit func()
GetSnapshot func() Snapshot
}
// Menu command IDs. A VM's commands are cmdVMBase + index*vmSlot + Action.
const (
cmdShow = 1001
cmdQuit = 1002
cmdNewVM = 1003
cmdVMBase = 2000
vmSlot = 20
maxTrayVMs = 16
)
// dotKind is the coloured status mark drawn beside a VM, as in the sidebar.
type dotKind int
const (
dotNone dotKind = iota
dotRunning
dotStopped
dotBusy
dotBroken
)
// menuEntry is one row of the tray menu, built by buildMenu and drawn by the
// platform code, so the structure is testable without Win32.
type menuEntry struct {
ID int
Label string // "\t" right-aligns what follows, like a shortcut
Default bool
Disabled bool
Separator bool
Dot dotKind
Sub []menuEntry
}
type texts struct {
show, newVM, quit string
start, stop, forceStop, restart, showWindow, shot string
shared, openInApp string
running, stopped, starting, stopping, broken, unknown string
}
func menuTexts(zh bool) texts {
if zh {
return texts{
show: "显示 Reims-Go", newVM: "新建虚拟机…", quit: "退出 Reims-Go",
start: "启动", stop: "关机", forceStop: "强制关机", restart: "重启",
showWindow: "显示窗口", shot: "复制屏幕截图",
shared: "打开共享文件夹", openInApp: "在 Reims-Go 中查看",
running: "运行中", stopped: "已停止", starting: "启动中…", stopping: "正在关机…",
broken: "配置损坏", unknown: "未知",
}
}
return texts{
show: "Show Reims-Go", newVM: "New Virtual Machine…", quit: "Quit Reims-Go",
start: "Start", stop: "Shut Down", forceStop: "Force Shut Down", restart: "Restart",
showWindow: "Show Window", shot: "Copy Screenshot",
shared: "Open Shared Folder", openInApp: "Show in Reims-Go",
running: "Running", stopped: "Stopped", starting: "Starting…", stopping: "Shutting down…",
broken: "Broken", unknown: "Unknown",
}
}
func vmCmd(i int, act Action) int { return cmdVMBase + i*vmSlot + int(act) }
// decodeVMCmd splits a VM command ID into the VM's index and the action.
func decodeVMCmd(id int) (int, Action, bool) {
if id < cmdVMBase || id >= cmdVMBase+maxTrayVMs*vmSlot {
return 0, 0, false
}
off := id - cmdVMBase
act := Action(off % vmSlot)
if act < ActStart || act > ActOpenInApp {
return 0, 0, false
}
return off / vmSlot, act, true
}
// buildMenu lays out the tray menu for a snapshot: Show (default), New VM,
// one submenu per VM whose default item is the state's main action (Start,
// or Show Window while running), then Quit.
func buildMenu(snap Snapshot) []menuEntry {
t := menuTexts(snap.LocaleZh)
menu := []menuEntry{
{ID: cmdShow, Label: t.show, Default: true},
{ID: cmdNewVM, Label: t.newVM},
}
vms := snap.VMs
if len(vms) > maxTrayVMs {
vms = vms[:maxTrayVMs]
}
if len(vms) > 0 {
menu = append(menu, menuEntry{Separator: true})
}
sep := menuEntry{Separator: true}
for i, vm := range vms {
cmd := func(act Action, label string) menuEntry { return menuEntry{ID: vmCmd(i, act), Label: label} }
var sub []menuEntry
var dot dotKind
var state string
switch vm.State {
case "running":
dot, state = dotRunning, t.running
show := cmd(ActShowWindow, t.showWindow)
show.Default = true
sub = []menuEntry{
show, cmd(ActScreenshot, t.shot), cmd(ActSharedFolder, t.shared), sep,
cmd(ActRestart, t.restart), cmd(ActStop, t.stop), cmd(ActForceStop, t.forceStop), sep,
cmd(ActOpenInApp, t.openInApp),
}
case "starting", "stopping":
dot, state = dotBusy, t.starting
if vm.State == "stopping" {
state = t.stopping
}
sub = []menuEntry{cmd(ActForceStop, t.forceStop), sep, cmd(ActOpenInApp, t.openInApp)}
case "broken":
dot, state = dotBroken, t.broken
sub = []menuEntry{cmd(ActOpenInApp, t.openInApp)}
case "stopped":
dot, state = dotStopped, t.stopped
start := cmd(ActStart, t.start)
start.Default = true
sub = []menuEntry{start, cmd(ActSharedFolder, t.shared), sep, cmd(ActOpenInApp, t.openInApp)}
default:
dot, state = dotStopped, t.unknown
sub = []menuEntry{cmd(ActOpenInApp, t.openInApp)}
}
menu = append(menu, menuEntry{Label: vm.title() + "\t" + state, Dot: dot, Sub: sub})
}
return append(menu, menuEntry{Separator: true}, menuEntry{ID: cmdQuit, Label: t.quit})
}
// dotPixels draws a status dot as size×size premultiplied BGRA pixels (the
// layout a 32-bit menu bitmap wants): a filled, anti-aliased circle, or a
// ring for "stopped" so the state differs by shape as well as colour.
func dotPixels(size int, kind dotKind) []byte {
px := make([]byte, size*size*4)
var r, g, b uint8
switch kind {
case dotRunning:
r, g, b = 0x30, 0xD1, 0x58
case dotBusy:
r, g, b = 0xFF, 0x9F, 0x0A
case dotBroken:
r, g, b = 0xFF, 0x45, 0x3A
case dotStopped:
r, g, b = 0x8E, 0x8E, 0x93
default:
return px
}
c := float64(size) / 2
outer := float64(size) * 0.28 // dot diameter ≈ 56% of the check-mark cell
inner := 0.0
if kind == dotStopped {
inner = outer - maxf(1.4, float64(size)*0.09)
}
const ss = 4 // 4×4 supersampling for smooth edges
for y := 0; y < size; y++ {
for x := 0; x < size; x++ {
hits := 0
for sy := 0; sy < ss; sy++ {
for sx := 0; sx < ss; sx++ {
dx := float64(x) + (float64(sx)+0.5)/ss - c
dy := float64(y) + (float64(sy)+0.5)/ss - c
d2 := dx*dx + dy*dy
if d2 <= outer*outer && d2 >= inner*inner {
hits++
}
}
}
if hits == 0 {
continue
}
a := hits * 255 / (ss * ss)
off := (y*size + x) * 4
px[off+0] = uint8(int(b) * a / 255)
px[off+1] = uint8(int(g) * a / 255)
px[off+2] = uint8(int(r) * a / 255)
px[off+3] = uint8(a)
}
}
return px
}
func maxf(a, b float64) float64 {
if a > b {
return a
}
return b
}
// resizePNGIcon scales an embedded PNG (e.g. assets/logo.png) to size×size PNG
+3 -2
View File
@@ -9,5 +9,6 @@ func Start(_ []byte, _ string, _ Callbacks) (*Manager, error) {
return &Manager{}, nil
}
func (m *Manager) UpdateTooltip(_ string) {}
func (m *Manager) Close() {}
func (m *Manager) UpdateTooltip(_ string) {}
func (m *Manager) Notify(_, _ string, _ bool) {}
func (m *Manager) Close() {}
+80
View File
@@ -8,6 +8,86 @@ import (
"testing"
)
func findEntry(entries []menuEntry, label string) *menuEntry {
for i := range entries {
if entries[i].Label == label {
return &entries[i]
}
}
return nil
}
func TestBuildMenuPerState(t *testing.T) {
menu := buildMenu(Snapshot{LocaleZh: true, VMs: []VMItem{
{Name: "macos-tahoe", Label: "日常", State: "running"},
{Name: "macos-dev", State: "stopped"},
{Name: "macos-busy", State: "starting"},
}})
if !menu[0].Default || menu[0].ID != cmdShow {
t.Fatalf("first item should be the default Show, got %+v", menu[0])
}
if last := menu[len(menu)-1]; last.ID != cmdQuit {
t.Fatalf("last item should be Quit, got %+v", last)
}
run := findEntry(menu, "日常\t运行中")
if run == nil || run.Dot != dotRunning {
t.Fatalf("running VM should use its display name and a running dot: %+v", menu)
}
if !run.Sub[0].Default || run.Sub[0].ID != vmCmd(0, ActShowWindow) {
t.Fatalf("running VM's default action should be Show Window, got %+v", run.Sub[0])
}
stop := findEntry(menu, "macos-dev\t已停止")
if stop == nil || stop.Dot != dotStopped || stop.Sub[0].ID != vmCmd(1, ActStart) || !stop.Sub[0].Default {
t.Fatalf("stopped VM should default to Start: %+v", stop)
}
for _, e := range stop.Sub {
if e.ID == vmCmd(1, ActStop) || e.ID == vmCmd(1, ActShowWindow) {
t.Fatalf("stopped VM must not offer %+v", e)
}
}
busy := findEntry(menu, "macos-busy\t启动中…")
if busy == nil || busy.Dot != dotBusy || busy.Sub[0].ID != vmCmd(2, ActForceStop) {
t.Fatalf("starting VM should only offer force stop first: %+v", busy)
}
}
func TestDecodeVMCmdRoundTrip(t *testing.T) {
for i := 0; i < maxTrayVMs; i++ {
for act := ActStart; act <= ActOpenInApp; act++ {
gi, ga, ok := decodeVMCmd(vmCmd(i, act))
if !ok || gi != i || ga != act {
t.Fatalf("vmCmd(%d,%d) decoded to (%d,%d,%v)", i, act, gi, ga, ok)
}
}
}
for _, id := range []int{cmdShow, cmdQuit, cmdNewVM, cmdVMBase, cmdVMBase + maxTrayVMs*vmSlot} {
if _, _, ok := decodeVMCmd(id); ok {
t.Fatalf("id %d should not decode as a VM command", id)
}
}
}
func TestDotPixels(t *testing.T) {
const size = 16
alpha := func(px []byte, x, y int) byte { return px[(y*size+x)*4+3] }
run := dotPixels(size, dotRunning)
if alpha(run, size/2, size/2) != 255 || alpha(run, 0, 0) != 0 {
t.Fatal("running dot should be solid in the centre and clear in the corner")
}
ring := dotPixels(size, dotStopped)
if alpha(ring, size/2, size/2) != 0 {
t.Fatal("stopped dot should be a ring with a clear centre")
}
for i := 0; i < len(run); i += 4 {
if run[i] > run[i+3] || run[i+1] > run[i+3] || run[i+2] > run[i+3] {
t.Fatal("pixels must be premultiplied (colour ≤ alpha)")
}
}
}
func TestResizePNGIcon(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 128, 128))
for y := 0; y < 128; y++ {
+246 -92
View File
@@ -8,6 +8,9 @@ import (
"sync"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
var (
@@ -32,6 +35,13 @@ var (
procLoadIconW = user32.NewProc("LoadIconW")
procDestroyIcon = user32.NewProc("DestroyIcon")
procCreateIconFromResourceEx = user32.NewProc("CreateIconFromResourceEx")
procSetMenuItemInfoW = user32.NewProc("SetMenuItemInfoW")
procSetMenuInfo = user32.NewProc("SetMenuInfo")
procGetSystemMetrics = user32.NewProc("GetSystemMetrics")
gdi32 = syscall.NewLazyDLL("gdi32.dll")
procCreateDIBSection = gdi32.NewProc("CreateDIBSection")
procDeleteObject = gdi32.NewProc("DeleteObject")
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetModuleHandle = kernel32.NewProc("GetModuleHandleW")
@@ -59,22 +69,29 @@ const (
nifMessage = 0x00000001
nifIcon = 0x00000002
nifTip = 0x00000004
nifInfo = 0x00000010
niifInfo = 0x00000001
niifError = 0x00000003
mfString = 0x00000000
mfGrayed = 0x00000001
mfPopup = 0x00000010
mfSeparator = 0x00000800
miimBitmap = 0x00000080
mimStyle = 0x00000010
mnsCheckOrBmp = 0x04000000
smCxMenuCheck = 71
dibRGBColors = 0
biRGB = 0
tpmRightButton = 0x0002
tpmBottomAlign = 0x0020
tpmReturnCmd = 0x0100
tpmNonotify = 0x0080
idiApplication = 32512
cmdShow = 1001
cmdQuit = 1002
cmdVMBase = 2000 // per-VM slots: base + i*10 + {0: start/stop, 1: shared folder}
maxTrayVMs = 16
trayIconUID = 1
)
@@ -124,6 +141,46 @@ type notifyIconDataW struct {
HBalloonIcon uintptr
}
type menuItemInfoW struct {
CbSize uint32
FMask uint32
FType uint32
FState uint32
WID uint32
HSubMenu uintptr
HbmpChecked uintptr
HbmpUnchecked uintptr
DwItemData uintptr
DwTypeData *uint16
Cch uint32
HbmpItem uintptr
}
type menuInfoW struct {
CbSize uint32
FMask uint32
DwStyle uint32
CyMax uint32
HbrBack uintptr
DwContextHelpID uint32
DwMenuData uintptr
}
type bitmapInfo struct {
BiSize uint32
BiWidth int32
BiHeight int32
BiPlanes uint16
BiBitCount uint16
BiCompression uint32
BiSizeImage uint32
BiXPelsPerMeter int32
BiYPelsPerMeter int32
BiClrUsed uint32
BiClrImportant uint32
BmiColors [1]uint32
}
var (
activeMu sync.RWMutex
activeMgr *Manager
@@ -317,74 +374,151 @@ func appendMenuString(menu uintptr, flags uintptr, id uintptr, label string) {
_, _, _ = procAppendMenuW.Call(menu, flags, id, uintptr(unsafe.Pointer(u16)))
}
// Menu theme: tray menus sit next to the taskbar, so they follow the Windows
// *system* theme (SystemUsesLightTheme), as the shell's own tray menus do.
// uxtheme's SetPreferredAppMode (ordinal 135) forces dark or light for this
// process's popup menus and FlushMenuThemes (ordinal 136) applies a change
// made while running. Both are undocumented but stable since Windows 10 1903;
// where they are missing the menu keeps the default light look.
const (
appModeForceDark = 2
appModeForceLight = 3
)
var (
themeOnce sync.Once
setAppMode uintptr
flushMenuTheme uintptr
)
func systemUsesLightTheme() bool {
k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Themes\Personalize`, registry.QUERY_VALUE)
if err != nil {
return true
}
defer k.Close()
v, _, err := k.GetIntegerValue("SystemUsesLightTheme")
return err != nil || v != 0
}
func applyMenuTheme() {
themeOnce.Do(func() {
h, err := windows.LoadLibrary("uxtheme.dll")
if err != nil {
return
}
setAppMode, _ = windows.GetProcAddressByOrdinal(h, 135)
flushMenuTheme, _ = windows.GetProcAddressByOrdinal(h, 136)
})
if setAppMode == 0 {
return
}
mode := uintptr(appModeForceDark)
if systemUsesLightTheme() {
mode = appModeForceLight
}
_, _, _ = syscall.SyscallN(setAppMode, mode)
if flushMenuTheme != 0 {
_, _, _ = syscall.SyscallN(flushMenuTheme)
}
}
// dotBitmap makes a 32-bit premultiplied-alpha DIB of a status dot, sized to
// the menu's check-mark cell. The caller deletes it once the menu is gone.
func dotBitmap(kind dotKind) uintptr {
size, _, _ := procGetSystemMetrics.Call(smCxMenuCheck)
if size < 12 {
size = 16
}
px := dotPixels(int(size), kind)
bi := bitmapInfo{BiWidth: int32(size), BiHeight: -int32(size), BiPlanes: 1, BiBitCount: 32, BiCompression: biRGB}
bi.BiSize = uint32(unsafe.Sizeof(bi) - unsafe.Sizeof(bi.BmiColors))
var bits unsafe.Pointer
hbm, _, _ := procCreateDIBSection.Call(0, uintptr(unsafe.Pointer(&bi)), dibRGBColors, uintptr(unsafe.Pointer(&bits)), 0, 0)
if hbm == 0 || bits == nil {
return 0
}
copy(unsafe.Slice((*byte)(bits), len(px)), px)
return hbm
}
// renderMenu turns menu entries into a Win32 popup menu. Bitmaps it creates
// are appended to *bitmaps for the caller to free after TrackPopupMenu.
func renderMenu(entries []menuEntry, bitmaps *[]uintptr, dots map[dotKind]uintptr) uintptr {
h, _, _ := procCreatePopupMenu.Call()
if h == 0 {
return 0
}
// One column for check marks and bitmaps, not two.
mi := menuInfoW{FMask: mimStyle, DwStyle: mnsCheckOrBmp}
mi.CbSize = uint32(unsafe.Sizeof(mi))
_, _, _ = procSetMenuInfo.Call(h, uintptr(unsafe.Pointer(&mi)))
for pos, e := range entries {
switch {
case e.Separator:
_, _, _ = procAppendMenuW.Call(h, mfSeparator, 0, 0)
continue
case len(e.Sub) > 0:
sub := renderMenu(e.Sub, bitmaps, dots)
if sub == 0 {
continue
}
appendMenuString(h, mfPopup, sub, e.Label)
default:
flags := uintptr(mfString)
if e.Disabled {
flags |= mfGrayed
}
appendMenuString(h, flags, uintptr(e.ID), e.Label)
if e.Default {
_, _, _ = procSetMenuDefaultItem.Call(h, uintptr(e.ID), 0)
}
}
if e.Dot != dotNone {
hbm, ok := dots[e.Dot]
if !ok {
hbm = dotBitmap(e.Dot)
dots[e.Dot] = hbm
if hbm != 0 {
*bitmaps = append(*bitmaps, hbm)
}
}
if hbm != 0 {
ii := menuItemInfoW{FMask: miimBitmap, HbmpItem: hbm}
ii.CbSize = uint32(unsafe.Sizeof(ii))
_, _, _ = procSetMenuItemInfoW.Call(h, uintptr(pos), 1, uintptr(unsafe.Pointer(&ii)))
}
}
}
return h
}
func (m *Manager) showContextMenu() {
var snap Snapshot
if m.cb.GetSnapshot != nil {
snap = m.cb.GetSnapshot()
}
zh := snap.LocaleZh
if len(snap.VMs) > maxTrayVMs {
snap.VMs = snap.VMs[:maxTrayVMs]
}
m.mu.Lock()
m.menuVMs = append([]VMItem(nil), snap.VMs...)
m.mu.Unlock()
hMenu, _, _ := procCreatePopupMenu.Call()
applyMenuTheme()
var bitmaps []uintptr
hMenu := renderMenu(buildMenu(snap), &bitmaps, map[dotKind]uintptr{})
if hMenu == 0 {
return
}
defer procDestroyMenu.Call(hMenu)
showLabel := "Show Reims-Go"
quitLabel := "Quit Reims-Go"
startLabel := "Start"
stopLabel := "Stop"
sharedLabel := "Open Shared Folder"
runningTag := "Running"
stoppedTag := "Stopped"
if zh {
showLabel = "显示 Reims-Go"
quitLabel = "退出 Reims-Go"
startLabel = "启动"
stopLabel = "停止"
sharedLabel = "打开共享目录"
runningTag = "运行中"
stoppedTag = "已停止"
}
appendMenuString(hMenu, mfString, cmdShow, showLabel)
_, _, _ = procSetMenuDefaultItem.Call(hMenu, cmdShow, 0)
vms := snap.VMs
if len(vms) > maxTrayVMs {
vms = vms[:maxTrayVMs]
}
m.mu.Lock()
m.menuVMs = append([]VMItem(nil), vms...)
m.mu.Unlock()
if len(vms) > 0 {
_, _, _ = procAppendMenuW.Call(hMenu, mfSeparator, 0, 0)
for i, vm := range vms {
sub, _, _ := procCreatePopupMenu.Call()
if sub == 0 {
continue
}
base := uintptr(cmdVMBase + i*10)
if vm.Running {
appendMenuString(sub, mfString, base+0, stopLabel)
} else {
appendMenuString(sub, mfString, base+0, startLabel)
}
appendMenuString(sub, mfString, base+1, sharedLabel)
dot := "○"
stateTag := stoppedTag
if vm.Running {
dot = "●"
stateTag = runningTag
}
appendMenuString(hMenu, mfPopup, sub, fmt.Sprintf("%s %s (%s)", dot, vm.Name, stateTag))
// DestroyMenu also destroys the submenus; bitmaps are freed separately.
defer func() {
_, _, _ = procDestroyMenu.Call(hMenu)
for _, hbm := range bitmaps {
_, _, _ = procDeleteObject.Call(hbm)
}
}
_, _, _ = procAppendMenuW.Call(hMenu, mfSeparator, 0, 0)
appendMenuString(hMenu, mfString, cmdQuit, quitLabel)
}()
var pt winPoint
_, _, _ = procGetCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
@@ -410,44 +544,64 @@ func (m *Manager) dispatchCommand(cmd int) {
if m.cb.OnShow != nil {
go m.cb.OnShow()
}
case cmdNewVM:
if m.cb.OnNewVM != nil {
go m.cb.OnNewVM()
}
case cmdQuit:
if m.cb.OnQuit != nil {
go m.cb.OnQuit()
}
default:
if cmd >= cmdVMBase {
idx := (cmd - cmdVMBase) / 10
act := (cmd - cmdVMBase) % 10
m.mu.Lock()
var item VMItem
valid := idx >= 0 && idx < len(m.menuVMs)
if valid {
item = m.menuVMs[idx]
}
m.mu.Unlock()
if !valid {
return
}
switch act {
case 0:
if item.Running {
if m.cb.OnStopVM != nil {
go m.cb.OnStopVM(item.Name)
}
} else {
if m.cb.OnStartVM != nil {
go m.cb.OnStartVM(item.Name)
}
}
case 1:
if m.cb.OnOpenSharedDir != nil {
go m.cb.OnOpenSharedDir(item.Name)
}
}
idx, act, ok := decodeVMCmd(cmd)
if !ok {
return
}
m.mu.Lock()
var item VMItem
valid := idx < len(m.menuVMs)
if valid {
item = m.menuVMs[idx]
}
m.mu.Unlock()
if valid && m.cb.OnVMAction != nil {
go m.cb.OnVMAction(item.Name, act)
}
}
}
// Notify shows a Windows notification from the tray icon, used for results
// of tray actions while the main window may be hidden.
func (m *Manager) Notify(title, text string, isError bool) {
if m == nil {
return
}
m.mu.Lock()
if m.closed || m.hwnd == 0 {
m.mu.Unlock()
return
}
nid := m.buildNID(nifInfo)
m.mu.Unlock()
copyUTF16(nid.SzInfoTitle[:], title)
copyUTF16(nid.SzInfo[:], text)
nid.DwInfoFlags = niifInfo
if isError {
nid.DwInfoFlags = niifError
}
_, _, _ = procShellNotifyIconW.Call(nimModify, uintptr(unsafe.Pointer(&nid)))
}
func copyUTF16(dst []uint16, s string) {
u, _ := syscall.UTF16FromString(s)
n := len(u)
if n > len(dst)-1 {
n = len(dst) - 1
}
copy(dst, u[:n])
dst[n] = 0
}
func trayWndProc(hwnd uintptr, msg uint32, wparam, lparam uintptr) uintptr {
activeMu.RLock()
m := activeMgr
+2 -2
View File
@@ -16,8 +16,8 @@ import (
// Version is the current Reims-Go release version. Release builds may override
// it at link time with:
//
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.5"
var Version = "v0.2.5"
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.6"
var Version = "v0.2.6"
const (
DefaultReleasesRepo = "Nwflower/Reims-Go"
+356
View File
@@ -0,0 +1,356 @@
package vmstart
import (
"encoding/json"
"errors"
"fmt"
"math/bits"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
const affinityConfigFile = ".reims-go-affinity.json"
// AffinityMode selects how a VM's QEMU process maps onto host logical CPUs.
type AffinityMode string
const (
AffinityAuto AffinityMode = "auto"
AffinityAll AffinityMode = "all"
AffinityPCores AffinityMode = "pcores"
AffinityNonLPE AffinityMode = "non_lpe"
AffinityCustom AffinityMode = "custom"
)
// VMAffinityConfig is persisted per VM in <vmDir>/.reims-go-affinity.json
// without modifying upstream vm.toml.
type VMAffinityConfig struct {
Mode AffinityMode `json:"mode"`
CPUs []int `json:"cpus,omitempty"`
DisableEcoQoS *bool `json:"disable_eco_qos,omitempty"`
}
// ShouldDisableEcoQoS reports whether Windows EcoQoS power throttling should
// be turned off for the VM's QEMU process. Defaults to true.
func (c VMAffinityConfig) ShouldDisableEcoQoS() bool {
if c.DisableEcoQoS == nil {
return true
}
return *c.DisableEcoQoS
}
// NormalizeAffinityMode maps empty or unknown mode values to AffinityAuto.
func NormalizeAffinityMode(m AffinityMode) AffinityMode {
switch AffinityMode(strings.ToLower(strings.TrimSpace(string(m)))) {
case AffinityAll:
return AffinityAll
case AffinityPCores:
return AffinityPCores
case AffinityNonLPE:
return AffinityNonLPE
case AffinityCustom:
return AffinityCustom
default:
return AffinityAuto
}
}
// DefaultVMAffinityConfig returns the default per-VM affinity preference.
func DefaultVMAffinityConfig() VMAffinityConfig {
eco := true
return VMAffinityConfig{
Mode: AffinityAuto,
DisableEcoQoS: &eco,
}
}
// ReadVMAffinity loads <vmDir>/.reims-go-affinity.json, returning defaults when
// absent or unreadable.
func ReadVMAffinity(vmDir string) VMAffinityConfig {
def := DefaultVMAffinityConfig()
if strings.TrimSpace(vmDir) == "" {
return def
}
raw, err := os.ReadFile(filepath.Join(vmDir, affinityConfigFile))
if err != nil {
return def
}
var cfg VMAffinityConfig
if json.Unmarshal(raw, &cfg) != nil {
return def
}
cfg.Mode = NormalizeAffinityMode(cfg.Mode)
if cfg.Mode == AffinityCustom {
_, cfg.CPUs = host.CPUsToMask(cfg.CPUs, 64)
} else {
cfg.CPUs = nil
}
if cfg.DisableEcoQoS == nil {
eco := true
cfg.DisableEcoQoS = &eco
}
return cfg
}
// HasSavedVMAffinity reports whether <vmDir>/.reims-go-affinity.json exists.
func HasSavedVMAffinity(vmDir string) bool {
if strings.TrimSpace(vmDir) == "" {
return false
}
_, err := os.Stat(filepath.Join(vmDir, affinityConfigFile))
return err == nil
}
// SaveVMAffinity validates and atomically writes <vmDir>/.reims-go-affinity.json.
func SaveVMAffinity(vmDir string, cfg VMAffinityConfig, maxCPUs int) (VMAffinityConfig, error) {
if strings.TrimSpace(vmDir) == "" {
return VMAffinityConfig{}, errors.New("VM directory is empty")
}
cfg.Mode = NormalizeAffinityMode(cfg.Mode)
if cfg.DisableEcoQoS == nil {
eco := true
cfg.DisableEcoQoS = &eco
}
if cfg.Mode == AffinityCustom {
limit := maxCPUs
if limit <= 0 || limit > 64 {
limit = 64
}
mask, normalized := host.CPUsToMask(cfg.CPUs, limit)
if mask == 0 {
return VMAffinityConfig{}, errors.New("select at least one valid host CPU")
}
cfg.CPUs = normalized
} else {
cfg.CPUs = nil
}
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return VMAffinityConfig{}, err
}
dst := filepath.Join(vmDir, affinityConfigFile)
tmp := dst + ".tmp"
if err := os.WriteFile(tmp, data, 0o600); err != nil {
return VMAffinityConfig{}, err
}
if err := os.Rename(tmp, dst); err != nil {
_ = os.Remove(tmp)
return VMAffinityConfig{}, err
}
return cfg, nil
}
// ResolvedAffinity is the concrete CPU mask computed for a VM on the current host.
type ResolvedAffinity struct {
ConfigMode AffinityMode
EffectiveMode AffinityMode
Mask uint64
MaskHex string
CPUs []int
ShouldPin bool
DisableEcoQoS bool
AutoSkipped bool
PThreads int
}
// ResolveVMAffinity computes the effective host CPU mask for a VM given its
// saved config, global auto-pin setting, current host report, and vCPU count.
func ResolveVMAffinity(cfg VMAffinityConfig, globalAutoPin bool, rep host.Report, vcpus int) ResolvedAffinity {
limit := rep.LogicalCPUs
if limit <= 0 {
limit = len(rep.CPUTopology)
}
if limit <= 0 {
limit = 64
}
if limit > 64 {
limit = 64
}
allMask := host.AllCPUsMask(limit)
allCPUs := host.MaskToCPUs(allMask, limit)
mode := NormalizeAffinityMode(cfg.Mode)
res := ResolvedAffinity{
ConfigMode: mode,
EffectiveMode: AffinityAll,
Mask: allMask,
MaskHex: fmt.Sprintf("0x%X", allMask),
CPUs: allCPUs,
DisableEcoQoS: cfg.ShouldDisableEcoQoS(),
PThreads: len(rep.PCoreLogicalCPUs),
}
if res.PThreads == 0 {
res.PThreads = rep.PCoreCount
}
applyMask := func(eff AffinityMode, mask uint64) ResolvedAffinity {
if mask == 0 {
return res
}
cpus := host.MaskToCPUs(mask, limit)
if len(cpus) == 0 {
return res
}
res.EffectiveMode = eff
res.Mask = mask
res.MaskHex = fmt.Sprintf("0x%X", mask)
res.CPUs = cpus
res.ShouldPin = mask != allMask
return res
}
switch mode {
case AffinityAll:
return res
case AffinityPCores:
if rep.HasHybridCores && rep.PCoreMask > 0 {
return applyMask(AffinityPCores, rep.PCoreMask)
}
return res
case AffinityNonLPE:
if rep.LPECoreCount > 0 && rep.NonLPEMask > 0 {
return applyMask(AffinityNonLPE, rep.NonLPEMask)
}
return res
case AffinityCustom:
mask, _ := host.CPUsToMask(cfg.CPUs, limit)
if mask != 0 {
return applyMask(AffinityCustom, mask)
}
return res
default: // AffinityAuto
if !globalAutoPin || !rep.HasHybridCores || rep.PCoreMask == 0 {
return res
}
plan := host.SelectSafeAffinity(rep, vcpus)
res.PThreads = plan.PThreads
switch plan.Mode {
case "pcores":
return applyMask(AffinityPCores, plan.Mask)
case "non_lpe":
return applyMask(AffinityNonLPE, plan.Mask)
default:
res.AutoSkipped = true
return res
}
}
}
// ApplyVMAffinity applies the VM's persisted CPU affinity mask and EcoQoS
// setting to a running QEMU PID. When forceApplyAll is true (e.g. a live user
// edit switching back to "all"), SetProcessAffinityMask is called even for the
// all-CPUs mask to clear any previous restriction.
func ApplyVMAffinity(loc i18n.Locale, rep host.Report, vmDir string, globalAutoPin bool, pid, vcpus int, forceApplyAll bool) (string, error) {
cfg := ReadVMAffinity(vmDir)
res := ResolveVMAffinity(cfg, globalAutoPin, rep, vcpus)
zh := loc == i18n.ZhCN
ecoDisabled := false
if res.DisableEcoQoS {
if err := host.DisableProcessPowerThrottling(uint32(pid)); err == nil {
ecoDisabled = true
}
}
var ecoSuffix string
if ecoDisabled {
if zh {
ecoSuffix = ",已禁用 EcoQoS 节流"
} else {
ecoSuffix = ", EcoQoS disabled"
}
}
if res.ShouldPin || forceApplyAll {
targetMask := res.Mask
if res.EffectiveMode == AffinityAll {
if _, sysMask, err := host.GetProcessAffinityMask(uint32(pid)); err == nil && sysMask != 0 {
targetMask = sysMask
}
}
if targetMask == 0 {
return "", errors.New("no valid CPU affinity mask available")
}
if err := host.SetProcessAffinityMask(uint32(pid), targetMask); err != nil {
line := fmt.Sprintf("[CPU] Warning: CPU affinity update failed for PID %d (mask 0x%X): %v", pid, targetMask, err)
return line, err
}
count := bits.OnesCount64(targetMask)
maskHex := fmt.Sprintf("0x%X", targetMask)
switch res.EffectiveMode {
case AffinityPCores:
if zh {
return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 绑定到 P 核(%d 个逻辑处理器,掩码 %s%s)", pid, count, maskHex, ecoSuffix), nil
}
return fmt.Sprintf("[CPU] Pinned QEMU (PID %d) to P-cores (%d logical CPUs, mask %s%s)", pid, count, maskHex, ecoSuffix), nil
case AffinityNonLPE:
if zh {
return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 绑定到 P+E 核(%d 个逻辑处理器,排除 LP-E 核,掩码 %s%s)", pid, count, maskHex, ecoSuffix), nil
}
return fmt.Sprintf("[CPU] Pinned QEMU (PID %d) to P+E cores (%d logical CPUs, LP-E excluded, mask %s%s)", pid, count, maskHex, ecoSuffix), nil
case AffinityCustom:
if zh {
return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 映射到自定义核心(%d 个逻辑处理器,掩码 %s%s)", pid, count, maskHex, ecoSuffix), nil
}
return fmt.Sprintf("[CPU] Mapped QEMU (PID %d) to custom CPUs (%d logical CPUs, mask %s%s)", pid, count, maskHex, ecoSuffix), nil
default:
if zh {
return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 设为所有处理器(%d 个逻辑处理器,掩码 %s%s)", pid, count, maskHex, ecoSuffix), nil
}
return fmt.Sprintf("[CPU] Set QEMU (PID %d) affinity to all CPUs (%d logical CPUs, mask %s%s)", pid, count, maskHex, ecoSuffix), nil
}
}
if res.AutoSkipped {
if zh {
return fmt.Sprintf("[CPU] 跳过自动绑核:虚拟机配置了 %d vCPU,超过可用安全绑定上限(P 核仅 %d 线程),使用全部核心%s", vcpus, res.PThreads, ecoSuffix), nil
}
return fmt.Sprintf("[CPU] Skipped auto pinning: VM has %d vCPUs, exceeding safe headroom (only %d P-core threads); using all CPUs%s", vcpus, res.PThreads, ecoSuffix), nil
}
if ecoDisabled {
if zh {
return fmt.Sprintf("[CPU] 已为 QEMU (PID %d) 禁用 Windows EcoQoS 效率节流(当前使用全部处理器)", pid), nil
}
return fmt.Sprintf("[CPU] Disabled Windows EcoQoS power throttling for QEMU (PID %d) (using all CPUs)", pid), nil
}
return "", nil
}
// AffinitySummary formats a concise summary for startup logs.
func AffinitySummary(loc i18n.Locale, rep host.Report, vmDir string, globalAutoPin bool, vcpus int) string {
cfg := ReadVMAffinity(vmDir)
res := ResolveVMAffinity(cfg, globalAutoPin, rep, vcpus)
zh := loc == i18n.ZhCN
switch res.EffectiveMode {
case AffinityPCores:
if zh {
return fmt.Sprintf("P核(%d线程)", len(res.CPUs))
}
return fmt.Sprintf("P-cores(%dT)", len(res.CPUs))
case AffinityNonLPE:
if zh {
return fmt.Sprintf("P+E(%d线程,避开LP-E)", len(res.CPUs))
}
return fmt.Sprintf("P+E(%dT,no-LPE)", len(res.CPUs))
case AffinityCustom:
if zh {
return fmt.Sprintf("自定义(%d线程,%s)", len(res.CPUs), res.MaskHex)
}
return fmt.Sprintf("custom(%dT,%s)", len(res.CPUs), res.MaskHex)
default:
if res.AutoSkipped {
if zh {
return fmt.Sprintf("自动跳过(%d核≥%dP线程)", vcpus, res.PThreads)
}
return fmt.Sprintf("skipped(%dvCPU>=%dPT)", vcpus, res.PThreads)
}
if zh {
return "全部核心"
}
return "all"
}
}
+85
View File
@@ -0,0 +1,85 @@
package vmstart
import (
"reflect"
"testing"
"github.com/Nwflower/reims-go/internal/host"
)
func TestVMAffinityRoundTripAndResolve(t *testing.T) {
dir := t.TempDir()
// Default when sidecar does not exist.
def := ReadVMAffinity(dir)
if def.Mode != AffinityAuto || !def.ShouldDisableEcoQoS() {
t.Fatalf("unexpected default: %+v", def)
}
// Custom mode rejects empty selection.
if _, err := SaveVMAffinity(dir, VMAffinityConfig{Mode: AffinityCustom}, 16); err == nil {
t.Fatalf("expected error for empty custom CPU list")
}
// Save custom deduplicated/sorted CPUs with EcoQoS disabled=false.
eco := false
saved, err := SaveVMAffinity(dir, VMAffinityConfig{
Mode: AffinityCustom,
CPUs: []int{5, 2, 2, 0, 99, -1},
DisableEcoQoS: &eco,
}, 16)
if err != nil {
t.Fatalf("SaveVMAffinity: %v", err)
}
wantCPUs := []int{0, 2, 5}
if !reflect.DeepEqual(saved.CPUs, wantCPUs) || saved.ShouldDisableEcoQoS() {
t.Fatalf("saved = %+v, want cpus %v eco=false", saved, wantCPUs)
}
loaded := ReadVMAffinity(dir)
if loaded.Mode != AffinityCustom || !reflect.DeepEqual(loaded.CPUs, wantCPUs) || loaded.ShouldDisableEcoQoS() {
t.Fatalf("loaded = %+v", loaded)
}
// Resolve on homogeneous 16-thread CPU.
amd := host.Report{LogicalCPUs: 16}
res := ResolveVMAffinity(loaded, true, amd, 4)
if res.EffectiveMode != AffinityCustom || res.Mask != 0x25 || !res.ShouldPin {
t.Fatalf("custom resolve = %+v, want mask 0x25", res)
}
// Resolve auto on 3-tier Arrow Lake.
arrowLake := host.Report{
LogicalCPUs: 16,
HasHybridCores: true,
PCoreCount: 6,
ECoreCount: 8,
LPECoreCount: 2,
PCoreMask: 0x3C03,
PCoreLogicalCPUs: []int{0, 1, 10, 11, 12, 13},
NonLPEMask: 0x3FFF,
NonLPELogicalCPUs: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
}
r4 := ResolveVMAffinity(DefaultVMAffinityConfig(), true, arrowLake, 4)
if r4.EffectiveMode != AffinityPCores || r4.Mask != 0x3C03 || !r4.ShouldPin {
t.Fatalf("auto 4 vCPU = %+v", r4)
}
r8 := ResolveVMAffinity(DefaultVMAffinityConfig(), true, arrowLake, 8)
if r8.EffectiveMode != AffinityNonLPE || r8.Mask != 0x3FFF || !r8.ShouldPin {
t.Fatalf("auto 8 vCPU = %+v", r8)
}
r14 := ResolveVMAffinity(DefaultVMAffinityConfig(), true, arrowLake, 14)
if r14.EffectiveMode != AffinityAll || !r14.AutoSkipped || r14.ShouldPin {
t.Fatalf("auto 14 vCPU = %+v", r14)
}
// Explicit pcores overrides auto headroom limit when user explicitly asks for it.
rExplicitP := ResolveVMAffinity(VMAffinityConfig{Mode: AffinityPCores}, false, arrowLake, 8)
if rExplicitP.EffectiveMode != AffinityPCores || rExplicitP.Mask != 0x3C03 || !rExplicitP.ShouldPin {
t.Fatalf("explicit pcores = %+v", rExplicitP)
}
// Explicit all returns full mask and ShouldPin=false (forceApplyAll handles live reset).
rAll := ResolveVMAffinity(VMAffinityConfig{Mode: AffinityAll}, true, arrowLake, 4)
if rAll.EffectiveMode != AffinityAll || rAll.Mask != 0xFFFF || rAll.ShouldPin {
t.Fatalf("explicit all = %+v", rAll)
}
}
+6
View File
@@ -42,6 +42,12 @@ func main() {
MinWidth: 920,
MinHeight: 600,
Frameless: true,
DragAndDrop: &options.DragAndDrop{
EnableFileDrop: true,
DisableWebViewDrop: true,
CSSDropProperty: "--wails-drop-target",
CSSDropValue: "drop",
},
AssetServer: &assetserver.Options{
Assets: assets,
},
+174
View File
@@ -0,0 +1,174 @@
#Requires -Version 7.0
<#
.SYNOPSIS
Build GitHub Release notes for a Reims-Go app tag from CHANGELOG.md.
.DESCRIPTION
Extracts the matching `## <Tag>` section from CHANGELOG.md and wraps it with
download, stable runtime, known limitation, license, and compare links.
Fails fast if CHANGELOG.md has no entry for -Tag or the section is empty,
preventing releases with empty/auto-only notes.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Tag,
[string]$ChangelogPath = 'CHANGELOG.md',
[string]$OutFile = '',
[string]$Repo = 'Nwflower/Reims-Go',
[string]$PrevTag = '',
[string]$StableRuntimeTag = '',
[string]$StableRuntimeTitle = '',
[string]$Summary = ''
)
$ErrorActionPreference = 'Stop'
if ($Tag -notmatch '^v[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$') {
throw "Invalid release tag '$Tag' (expected semantic version starting with 'v', e.g. v0.2.5)."
}
if (-not (Test-Path -LiteralPath $ChangelogPath)) {
throw "Changelog file not found: $ChangelogPath"
}
$utf8NoBom = [Text.UTF8Encoding]::new($false)
$raw = [IO.File]::ReadAllText((Resolve-Path -LiteralPath $ChangelogPath).Path, $utf8NoBom)
$lines = $raw -split "\r?\n"
$headingPattern = '^##\s+(?<tag>v[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?)(?:\s|$|[—–\-\(])'
$inSection = $false
$found = $false
$sectionLines = [Collections.Generic.List[string]]::new()
$detectedPrevTag = ''
foreach ($line in $lines) {
if ($line -match '^##\s+') {
if ($inSection) {
if ($line -match $headingPattern) {
$detectedPrevTag = $Matches['tag']
}
break
}
if ($line -match $headingPattern -and $Matches['tag'] -eq $Tag) {
$inSection = $true
$found = $true
continue
}
} elseif ($inSection) {
$sectionLines.Add($line)
}
}
if (-not $found) {
throw "CHANGELOG.md does not contain a '## $Tag' section. Add release notes for $Tag to $ChangelogPath before releasing."
}
# Trim leading and trailing blank lines.
while ($sectionLines.Count -gt 0 -and [string]::IsNullOrWhiteSpace($sectionLines[0])) {
$sectionLines.RemoveAt(0)
}
while ($sectionLines.Count -gt 0 -and [string]::IsNullOrWhiteSpace($sectionLines[$sectionLines.Count - 1])) {
$sectionLines.RemoveAt($sectionLines.Count - 1)
}
$hasContent = $false
foreach ($l in $sectionLines) {
$t = $l.Trim()
if ($t -ne '' -and $t -notmatch '^#+\s+') {
$hasContent = $true
break
}
}
if (-not $hasContent) {
throw "CHANGELOG.md section '## $Tag' has no release note entries."
}
# If CHANGELOG.md has an introductory paragraph before the first ### subheading,
# place it at the top of the release notes (above ### 下载).
$leadLines = [Collections.Generic.List[string]]::new()
$bodyLines = [Collections.Generic.List[string]]::new()
$seenSubheading = $false
foreach ($l in $sectionLines) {
if (-not $seenSubheading -and $l -match '^###\s+') {
$seenSubheading = $true
}
if ($seenSubheading) {
$bodyLines.Add($l)
} else {
$leadLines.Add($l)
}
}
if (-not $seenSubheading) {
# Section has prose/bullets without ### subheadings: keep them under ### 变更说明.
$bodyLines.Add('### 变更说明')
$bodyLines.Add('')
foreach ($l in $leadLines) { $bodyLines.Add($l) }
$leadLines.Clear()
} else {
while ($leadLines.Count -gt 0 -and [string]::IsNullOrWhiteSpace($leadLines[$leadLines.Count - 1])) {
$leadLines.RemoveAt($leadLines.Count - 1)
}
}
if ([string]::IsNullOrWhiteSpace($PrevTag)) {
$PrevTag = $detectedPrevTag
}
$blocks = [Collections.Generic.List[string]]::new()
if (-not [string]::IsNullOrWhiteSpace($Summary)) {
$blocks.Add("Reims-Go ${Tag}:$($Summary.Trim())")
} elseif ($leadLines.Count -gt 0) {
$blocks.Add(($leadLines -join "`n").Trim())
}
$downloadLines = @(
'### 下载'
''
"- ``reims-go-$Tag-windows-amd64.exe``:单文件,免安装。双击打开界面,带子命令即在终端运行(如 ``reims-go vm list``);"
"- ``reims-go-$Tag-windows-amd64.zip``:较小的下载,解压后得到相同的 EXE。"
'- `SHA256SUMS.txt` 包含 EXE 和 ZIP 的 SHA256。'
)
if (-not [string]::IsNullOrWhiteSpace($StableRuntimeTag)) {
$rtLabel = if (-not [string]::IsNullOrWhiteSpace($StableRuntimeTitle)) { $StableRuntimeTitle } else { $StableRuntimeTag }
$downloadLines += ''
$downloadLines += "当前稳定版运行时为 [$rtLabel](https://github.com/$Repo/releases/tag/$StableRuntimeTag),已经装过的不用重装。"
}
$blocks.Add(($downloadLines -join "`n"))
$blocks.Add(($bodyLines -join "`n").Trim())
$blocks.Add(@"
### 已知限制
- 没有代码签名,第一次运行时 Windows SmartScreen 会拦截,需要点「更多信息」→「仍要运行」。
"@.Trim())
$blocks.Add(@"
### 许可证
Reims-Go 自身代码采用 Apache-2.0 许可证。运行时组件按各自的 GPL/LGPL 许可证分发,对应源码与许可证文本随运行时 Release 一起提供。
本应用不包含、也不分发任何 Apple 系统文件;macOS 安装包由你的电脑直接从 Apple 服务器下载。macOS 的软件许可只允许在 Apple 硬件上运行 macOS 虚拟机,使用前请自行确认合规。
"@.Trim())
if (-not [string]::IsNullOrWhiteSpace($PrevTag)) {
$blocks.Add("完整更新日志见 [CHANGELOG.md](https://github.com/$Repo/blob/main/CHANGELOG.md) · 完整提交对比:[$PrevTag...$Tag](https://github.com/$Repo/compare/$PrevTag...$Tag)。")
} else {
$blocks.Add("完整更新日志见 [CHANGELOG.md](https://github.com/$Repo/blob/main/CHANGELOG.md)。")
}
$output = ($blocks -join "`n`n") + "`n"
if (-not [string]::IsNullOrWhiteSpace($OutFile)) {
$parent = Split-Path -Parent $OutFile
if (-not [string]::IsNullOrWhiteSpace($parent)) {
New-Item -ItemType Directory -Force -Path $parent | Out-Null
}
[IO.File]::WriteAllText($OutFile, $output, $utf8NoBom)
} else {
[Console]::Out.Write($output)
}
+51 -8
View File
@@ -5,10 +5,9 @@
.DESCRIPTION
Fails unless all of these hold:
1. All four release assets exist in -OutDir: the runtime, its source
package, the MSYS2 source package and SHA256SUMS.txt (spec section 7:
a runtime is never published without its sources).
2. SHA256SUMS.txt lists the three archives, and every hash matches.
1. The runtime, both source packages and SHA256SUMS.txt exist. Slim
releases also require the matching detached symbols archive.
2. SHA256SUMS.txt lists all release archives and every hash matches.
3. manifest.json in the runtime names -Commit, channel "alpha", the source
package, and exactly the patches in -AppliedPatches.
4. The runtime's own qemu-system-x86_64.exe, run with a PATH holding only
@@ -27,6 +26,7 @@ param(
[Parameter(Mandatory = $true)]
[string]$Zstd,
[string[]]$AppliedPatches = @(),
[switch]$RequireSlim,
# Only for checking packages built before the 2026-11-28 rename ("candidate").
[string]$ExpectChannel = 'alpha',
[string]$TempRoot = $env:RUNNER_TEMP
@@ -42,19 +42,23 @@ $names = @{
sums = 'SHA256SUMS.txt'
}
# 1. All four assets.
$symbolsName = "reims-runtime-symbols-$Commit"
if ($RequireSlim -or (Test-Path -LiteralPath (Join-Path $OutDir "$symbolsName.tar.zst"))) {
$names.symbols = "$symbolsName.tar.zst"
}
# 1. All assets for this layout.
foreach ($k in $names.Keys) {
$p = Join-Path $OutDir $names[$k]
if (-not (Test-Path -LiteralPath $p)) { throw "Missing release asset: $($names[$k])" }
}
Write-Host 'PASS four release assets present'
Write-Host "PASS $($names.Count) release assets present"
# 2. Sums cover the three archives and match.
# 2. Sums cover the archives and match.
$sums = @{}
foreach ($line in Get-Content -LiteralPath (Join-Path $OutDir $names.sums)) {
if ($line -match '^([0-9a-fA-F]{64})\s+\*?(.+)$') { $sums[$Matches[2].Trim()] = $Matches[1].ToLowerInvariant() }
}
foreach ($k in 'runtime', 'source', 'msys2') {
foreach ($k in ($names.Keys | Where-Object { $_ -ne 'sums' })) {
$n = $names[$k]
if (-not $sums.ContainsKey($n)) { throw "SHA256SUMS.txt has no entry for $n" }
$got = (Get-FileHash -Algorithm SHA256 -LiteralPath (Join-Path $OutDir $n)).Hash.ToLowerInvariant()
@@ -80,12 +84,34 @@ try {
if ($m.commit -ne $Commit) { throw "manifest commit is $($m.commit), expected $Commit" }
if ($m.channel -ne $ExpectChannel) { throw "manifest channel is $($m.channel), expected $ExpectChannel" }
if ($m.source_package -ne $names.source) { throw "manifest source_package is $($m.source_package), expected $($names.source)" }
$files = @(Get-ChildItem -LiteralPath $root -Recurse -File)
if ($m.file_count -ne $files.Count) { throw "manifest file_count is $($m.file_count), actual $($files.Count)" }
$rawBytes = [int64](($files | Measure-Object Length -Sum).Sum)
if ($m.raw_bytes -ne $rawBytes) { throw "manifest raw_bytes is $($m.raw_bytes), actual $rawBytes" }
$declared = @($m.patches | ForEach-Object { $_.name })
if (($declared -join ',') -ne ($AppliedPatches -join ',')) {
throw "manifest patches [$($declared -join ', ')] differ from those applied [$($AppliedPatches -join ', ')]"
}
Write-Host "PASS manifest: commit $Commit, channel $($m.channel), patches [$($declared -join ', ')]"
if ($m.symbols_package -or $names.symbols) {
if (!$names.symbols -or $m.symbols_package -ne $names.symbols) { throw 'Missing or mismatched symbols package' }
$symTar = Join-Path $work 'symbols.tar'
& $Zstd -d -q -f (Join-Path $OutDir $names.symbols) -o $symTar
if ($LASTEXITCODE) { throw 'Cannot decompress symbols package' }
$members = & (Join-Path $env:SystemRoot 'System32\tar.exe') -tf $symTar
if ($LASTEXITCODE) { throw 'Cannot list symbols package' }
foreach ($rel in 'bin/reims-ctl.exe','bin/reims-util.exe','qemu/bin/qemu-system-x86_64.exe','qemu/bin/qemu-img.exe','qemu/bin/reims-vgpu-compile.exe') {
$hash = (Get-FileHash -LiteralPath (Join-Path $root $rel) -Algorithm SHA256).Hash
if ($hash -ne $m.sha256.$rel) { throw "Manifest hash mismatch for $rel" }
if ("$symbolsName/$rel.debug" -notin $members) { throw "Missing debug file for $rel" }
}
foreach ($rel in 'qemu/bin/libva.dll','qemu/bin/libva_win32.dll','qemu/bin/vaon12_drv_video.dll','NOTICE.md','MSYS2-PACKAGES.txt') {
if (!(Test-Path -LiteralPath (Join-Path $root $rel) -PathType Leaf)) { throw "Missing runtime dependency: $rel" }
}
Write-Host 'PASS stripped executable hashes, detached debug members and video driver files'
}
# 4. QEMU runs from the bundle alone and has the reims device.
$qemuBin = Join-Path $root 'qemu\bin'
$psi = [Diagnostics.ProcessStartInfo]::new((Join-Path $qemuBin 'qemu-system-x86_64.exe'), '-device help')
@@ -102,6 +128,23 @@ try {
if ($proc.ExitCode -ne 0) { throw "qemu -device help exited $($proc.ExitCode): $err" }
if ($out -notmatch 'reims-graphics-pci') { throw "qemu -device help does not list reims-graphics-pci`n$out`n$err" }
Write-Host 'PASS qemu-system-x86_64 -device help lists reims-graphics-pci (no MSYS2 on PATH)'
if ($names.symbols) {
$oldPath = $env:PATH
$img = Join-Path $qemuBin 'qemu-img.exe'
try {
$env:PATH = $psi.Environment['PATH']
foreach ($exe in 'reims-ctl.exe','reims-util.exe') {
& (Join-Path $root "bin/$exe") --version
if ($LASTEXITCODE) { throw "$exe --version failed ($LASTEXITCODE)" }
}
$disk = Join-Path $work 'test.qcow2'
& $img create -f qcow2 $disk 32M
if ($LASTEXITCODE) { throw "qemu-img create failed ($LASTEXITCODE)" }
$info = & $img info --output=json $disk
if ($LASTEXITCODE -or (($info -join "`n" | ConvertFrom-Json).'virtual-size' -ne 32MB)) { throw 'qemu-img info failed' }
} finally { $env:PATH = $oldPath }
Write-Host 'PASS CLI versions and qcow2 creation / inspection (no MSYS2 on PATH)'
}
} finally {
Remove-Item -Recurse -Force -LiteralPath $work -ErrorAction SilentlyContinue
}
+70 -14
View File
@@ -4,7 +4,7 @@
package, and SHA256SUMS.txt, ready to publish as a GitHub Release.
.DESCRIPTION
Outputs, in -OutDir (all four are assets of one GitHub Release):
Outputs, in -OutDir (all five are assets of one GitHub Release):
reims-runtime-win-x64-<commit>.tar.zst runtime (bin/, qemu/, manifest.json,
NOTICE.md, licenses/, patches/,
MSYS2-PACKAGES.txt)
@@ -12,7 +12,8 @@
trees at the built commits + patches/
reims-runtime-msys2-src-<commit>.tar.zst sources of the copyleft MSYS2 packages
whose DLLs are bundled (pack-msys2-sources.ps1)
SHA256SUMS.txt all three archives
reims-runtime-symbols-<commit>.tar.zst detached debug files for the five programs
SHA256SUMS.txt all four archives
manifest.json (schema 2) states what the package was really built from:
upstream commit, vendor/qemu commit, reims-util and metal2vulkan commits,
@@ -30,7 +31,7 @@
pwsh -File scripts/pack-runtime.ps1 -Channel alpha
pwsh -File scripts/pack-runtime.ps1 -Patches reims-vgpu-cargo-lock.patch,qemu-whpx-win10-compat.patch
#>
[CmdletBinding()]
[CmdletBinding(PositionalBinding = $false)]
param(
[string]$ReimsRepo = 'D:\DevTools\reims-vgpu',
[string]$CargoHome = 'D:\DevTools\cargo',
@@ -61,6 +62,27 @@ function Invoke-Native([string]$exe, [string[]]$argv) {
if ($LASTEXITCODE -ne 0) { throw "$exe $($argv -join ' ') failed ($LASTEXITCODE)" }
}
function Invoke-GitApply([string]$repo, [string]$patchText, [switch]$Check) {
$psi = [Diagnostics.ProcessStartInfo]::new()
$psi.FileName = (Get-Command git).Source
$psi.WorkingDirectory = $repo
$psi.UseShellExecute = $false
$psi.RedirectStandardInput = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.ArgumentList.Add('apply')
if ($Check) { $psi.ArgumentList.Add('--check') }
$psi.ArgumentList.Add('-')
$proc = [Diagnostics.Process]::Start($psi)
$proc.StandardInput.NewLine = "`n"
$proc.StandardInput.Write($patchText)
$proc.StandardInput.Close()
$stdout = $proc.StandardOutput.ReadToEnd()
$stderr = $proc.StandardError.ReadToEnd()
$proc.WaitForExit()
if ($proc.ExitCode) { throw "git apply failed in $repo ($($proc.ExitCode)): $stdout$stderr" }
}
function Get-Sha256([string]$path) {
(Get-FileHash -Algorithm SHA256 -LiteralPath $path).Hash.ToLowerInvariant()
}
@@ -174,16 +196,41 @@ foreach ($targetName in $byTarget.Keys) {
New-Item -ItemType Directory -Force -Path $verifyDir | Out-Null
$headRev = (git -C $repo rev-parse HEAD).Trim()
Invoke-Native 'git' @('init', '-q', $verifyDir)
Invoke-Native 'git' @('-C', $verifyDir, 'config', 'core.autocrlf', 'false')
Invoke-Native 'git' @('-C', $verifyDir, 'config', 'core.eol', 'lf')
Invoke-Native 'git' @('-C', $verifyDir, 'config', 'core.filemode', 'false')
Write-Utf8 (Join-Path $verifyDir '.gitattributes') '* text eol=lf`n'
$tar = Join-Path $TempRoot ("patch-verify-" + [guid]::NewGuid() + '.tar')
Invoke-Native 'git' @('-C', $repo, 'archive', '--format=tar', '-o', $tar, $headRev)
Invoke-Native 'tar.exe' @('-xf', $tar, '-C', $verifyDir)
Remove-Item -LiteralPath $tar -Force
# bsdtar expands the upstream LF bytes, but Windows text tools used
# during extraction must not decide the comparison's line endings.
foreach ($file in Get-ChildItem -LiteralPath $verifyDir -Recurse -File) {
if ($file.LinkType) { continue }
$bytes = [IO.File]::ReadAllBytes($file.FullName)
$text = [Text.Encoding]::UTF8.GetString($bytes)
if ($text.Contains([char]0)) { continue }
$lf = $text.Replace("`r`n", "`n")
if ($lf -cne $text) {
[IO.File]::WriteAllText($file.FullName, $lf, [Text.UTF8Encoding]::new($false))
}
}
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'add', '-A')
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'commit', '-q', '-m', 'base')
Invoke-Native 'git' @('-C', $verifyDir, 'add', '--renormalize', '.')
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'commit', '-q', '--allow-empty', '-m', 'normalize-lf')
foreach ($ps in $group) {
$pf = Join-Path $patchesDir $ps.Name
Invoke-Native 'git' @('-C', $verifyDir, 'apply', '--check', $pf)
Invoke-Native 'git' @('-C', $verifyDir, 'apply', $pf)
# .patch files may be checked out with CRLF on Windows. Keep the
# authoritative file intact while comparing its LF representation
# with a Git tree archived and indexed with LF line endings.
$patchLf = Join-Path $TempRoot ("patch-lf-" + [guid]::NewGuid() + '.patch')
$patchText = [IO.File]::ReadAllText($pf).Replace("`r`n", "`n")
[IO.File]::WriteAllText($patchLf, $patchText, [Text.UTF8Encoding]::new($false))
Invoke-GitApply $verifyDir $patchText -Check
Invoke-GitApply $verifyDir $patchText
Remove-Item -LiteralPath $patchLf -Force
}
$expectedDiff = (& git -C $verifyDir -c core.autocrlf=false diff --full-index | Out-String).Replace("`r`n", "`n").TrimEnd()
if ($treeDiff -ne $expectedDiff) {
@@ -213,6 +260,7 @@ if ($otherCtl.Count -or $otherQemu.Count) {
$bundleName = "reims-runtime-win-x64-$id"
$srcName = "reims-runtime-src-$id"
$symbolsName = "reims-runtime-symbols-$id"
$stageRoot = Join-Path $TempRoot "pack-$id"
$bundleDir = Join-Path $stageRoot $bundleName
$srcDir = Join-Path $stageRoot $srcName
@@ -221,11 +269,16 @@ New-Item -ItemType Directory -Force -Path "$bundleDir\bin", "$bundleDir\qemu", "
# ── 3. Runtime bundle ────────────────────────────────────────
Write-Host "==> Staging $bundleName ($Channel)"
Copy-Item -LiteralPath $ctlExe -Destination "$bundleDir\bin\reims-ctl.exe"
Copy-Item -LiteralPath $utilExe -Destination "$bundleDir\bin\reims-util.exe"
$resolvedQemu = (Get-Item -LiteralPath $QemuDir).Target
if (-not $resolvedQemu) { $resolvedQemu = $QemuDir }
Copy-Item -Path "$resolvedQemu\*" -Destination "$bundleDir\qemu" -Recurse -Force
$keyFiles = @(& (Join-Path $PSScriptRoot 'stage-runtime-binaries.ps1') -CargoBin $CargoBin -QemuDir $resolvedQemu `
-BundleDir $bundleDir -SymbolsDir (Join-Path $stageRoot $symbolsName) -Objcopy (Join-Path $Msys2 'clang64/bin/llvm-objcopy.exe') | ForEach-Object { $_ })
$expectedKeyFiles = @('bin/reims-ctl.exe', 'bin/reims-util.exe', 'qemu/bin/qemu-system-x86_64.exe',
'qemu/bin/qemu-img.exe', 'qemu/bin/reims-vgpu-compile.exe')
if ($keyFiles.Count -ne 5 -or (Compare-Object $expectedKeyFiles $keyFiles)) {
$keyFiles | ForEach-Object { Write-Host "Unexpected stager output [$($_.GetType().FullName)]: $_" }
throw 'Binary stager did not return exactly the five expected executable paths'
}
Copy-Item -LiteralPath (Join-Path $repoRoot 'NOTICE.md') -Destination "$bundleDir\NOTICE.md"
foreach ($ps in $patchSpecs) { Copy-Item -LiteralPath (Join-Path $patchesDir $ps.Name) -Destination "$bundleDir\patches\" }
@@ -333,12 +386,10 @@ packages listed in ``MSYS2-PACKAGES.txt``, with links to their sources.
"@
# ── 5. Manifest (schema 2) ───────────────────────────────────
$allFiles = Get-ChildItem -LiteralPath $bundleDir -Recurse -File
$keyFiles = @('bin/reims-ctl.exe', 'bin/reims-util.exe', 'qemu/bin/qemu-system-x86_64.exe', 'qemu/bin/qemu-img.exe', 'qemu/bin/reims-vgpu-compile.exe')
$hashes = [ordered]@{}
foreach ($rel in $keyFiles) {
$fp = Join-Path $bundleDir ($rel -replace '/', '\')
if (Test-Path -LiteralPath $fp) { $hashes[$rel] = Get-Sha256 $fp }
$hashes[$rel] = Get-Sha256 $fp
}
$manifest = [ordered]@{
schema_version = 2
@@ -353,15 +404,18 @@ $manifest = [ordered]@{
patches = $patchEntries
channel = $Channel
source_package = "$srcName.tar.zst"
symbols_package = "$symbolsName.tar.zst"
qemu_version = $qemuVersionLine
util_version = $utilVersionLine
built_at = (Get-Date).ToString('o')
file_count = $allFiles.Count + 1
file_count = (Get-ChildItem -LiteralPath $bundleDir -Recurse -File).Count + 1
dll_count = $dlls.Count
raw_bytes = [int64](($allFiles | Measure-Object Length -Sum).Sum) # PowerShell 7 sums to a double; JSON must stay an integer
raw_bytes = [int64]((Get-ChildItem -LiteralPath $bundleDir -Recurse -File | Measure-Object Length -Sum).Sum) # Add the manifest's own size after writing it below.
sha256 = $hashes
}
Write-Utf8 "$bundleDir\manifest.json" ($manifest | ConvertTo-Json -Depth 5)
$manifest.raw_bytes += (Get-Item -LiteralPath "$bundleDir\manifest.json").Length
Write-Utf8 "$bundleDir\manifest.json" ($manifest | ConvertTo-Json -Depth 5)
# ── 6. Archives and sums ─────────────────────────────────────
Write-Host '==> Compressing runtime'
@@ -370,11 +424,13 @@ New-TarZst $stageRoot $bundleName $runtimeArchive
Write-Host '==> Compressing sources'
$srcArchive = Join-Path $OutDir "$srcName.tar.zst"
New-TarZst $stageRoot $srcName $srcArchive
$symbolsArchive = Join-Path $OutDir "$symbolsName.tar.zst"
New-TarZst $stageRoot $symbolsName $symbolsArchive
$rtHash = Get-Sha256 $runtimeArchive
$srcHash = Get-Sha256 $srcArchive
Write-Utf8 "$runtimeArchive.sha256" "$rtHash $bundleName.tar.zst`n"
Write-Utf8 (Join-Path $OutDir 'SHA256SUMS.txt') "$rtHash $bundleName.tar.zst`n$srcHash $srcName.tar.zst`n"
Write-Utf8 (Join-Path $OutDir 'SHA256SUMS.txt') "$rtHash $bundleName.tar.zst`n$srcHash $srcName.tar.zst`n$(Get-Sha256 $symbolsArchive) $symbolsName.tar.zst`n"
# Sources of the copyleft MSYS2 packages, as their own asset (adds a line to SHA256SUMS.txt).
& (Join-Path $PSScriptRoot 'pack-msys2-sources.ps1') -PackagesFile (Join-Path $bundleDir 'MSYS2-PACKAGES.txt') -Commit $id -OutDir $OutDir -Msys2 $Msys2 -TempRoot $TempRoot
+42
View File
@@ -0,0 +1,42 @@
# Stage the Windows x64 payload and matching GNU debug files. Inputs are read-only.
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string]$CargoBin,
[Parameter(Mandatory)] [string]$QemuDir,
[Parameter(Mandatory)] [string]$BundleDir,
[Parameter(Mandatory)] [string]$SymbolsDir,
[Parameter(Mandatory)] [string]$Objcopy
)
$ErrorActionPreference = 'Stop'
$programs = @('bin/reims-ctl.exe', 'bin/reims-util.exe', 'qemu/bin/qemu-system-x86_64.exe',
'qemu/bin/qemu-img.exe', 'qemu/bin/reims-vgpu-compile.exe')
# Omit only the paths tested with the x64 launcher. Keep new upstream files,
# in particular dynamically loaded video drivers, ROMs, and license notices.
$tools = @('bin/qemu-system-x86_64w.exe', 'bin/elf2dmp.exe', 'bin/qemu-edid.exe',
'bin/qemu-io.exe', 'bin/qemu-nbd.exe', 'bin/qemu-storage-daemon.exe')
foreach ($file in Get-ChildItem -LiteralPath $QemuDir -Recurse -Force -File) {
$rel = [IO.Path]::GetRelativePath($QemuDir, $file.FullName).Replace('\', '/')
if ($rel -in $tools) { continue }
if ($rel -match '^share/edk2-(aarch64|riscv64|loongarch64)-(code|vars)\.fd$' -or
$rel -match '^share/firmware/\d+-edk2-(aarch64|riscv64|loongarch64)\.json$') { continue }
if ("qemu/$rel" -in $programs) { continue }
$dest = Join-Path $BundleDir "qemu/$rel"
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $dest))
Copy-Item -LiteralPath $file.FullName -Destination $dest
}
foreach ($rel in $programs) {
$src = if ($rel.StartsWith('qemu/')) { Join-Path $QemuDir $rel.Substring(5) }
else { Join-Path $CargoBin (Split-Path -Leaf $rel) }
$dest = Join-Path $BundleDir $rel
$debug = Join-Path $SymbolsDir "$rel.debug"
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $dest))
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $debug))
& $Objcopy --only-keep-debug $src $debug | Out-Null
if ($LASTEXITCODE) { throw "Extracting symbols from $src failed ($LASTEXITCODE)" }
& $Objcopy --strip-debug "--add-gnu-debuglink=$debug" $src $dest | Out-Null
if ($LASTEXITCODE) { throw "Stripping $src failed ($LASTEXITCODE)" }
}
# The packer hashes these final, stripped bytes for manifest.json.
$programs