Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6367d17216 | ||
|
|
460de66ac4 | ||
|
|
338a9ee220 | ||
|
|
eb2b102bd5 | ||
|
|
7697374132 | ||
|
|
b839242716 | ||
|
|
181d952388 | ||
|
|
7abcc64e6f | ||
|
|
0934d9d206 | ||
|
|
003e4a08e7 | ||
|
|
704f68cdce | ||
|
|
ab49d79a71 | ||
|
|
c0f08be124 | ||
|
|
dac10a52bc | ||
|
|
b007f6b445 | ||
|
|
48e75ca665 | ||
|
|
9c8a75448d | ||
|
|
3b26f6117f | ||
|
|
f5ec733230 | ||
|
|
7641a7c948 | ||
|
|
1276050569 | ||
|
|
8acc0c3c23 | ||
|
|
172df5c4d5 | ||
|
|
f85e1aba88 | ||
|
|
a7921e998b | ||
|
|
24f29f806f | ||
|
|
33ac322bb2 | ||
|
|
5000e00780 | ||
|
|
d21ee22c80 | ||
|
|
99e189bef2 | ||
|
|
0ad5652ecd | ||
|
|
4cf1e8ea37 | ||
|
|
31a72892de | ||
|
|
12fa25d089 | ||
|
|
181ad64618 | ||
|
|
1017301682 | ||
|
|
470ed2d30a | ||
|
|
2f1e0bb0e4 | ||
|
|
69803355bf | ||
|
|
d30c694e2f | ||
|
|
8397d15bc5 | ||
|
|
c62bf17d91 | ||
|
|
b2237997f2 | ||
|
|
331d0748a4 | ||
|
|
437aceb580 | ||
|
|
d2cdb3a09a | ||
|
|
e195858a0e | ||
|
|
24acc9d6ed | ||
|
|
ce2a0ed813 | ||
|
|
b2f7f036d8 | ||
|
|
9e4bc98c7d | ||
|
|
8b6073b6b1 | ||
|
|
105ca9c88e | ||
|
|
7b0fbd5978 | ||
|
|
fc284e99ab | ||
|
|
4bde4f3cf5 | ||
|
|
faa2b71202 | ||
|
|
45a2d48560 | ||
|
|
168c7140f8 | ||
|
|
9e357ba38c | ||
|
|
d42a4f85f0 | ||
|
|
17497aee73 | ||
|
|
f601236f74 | ||
|
|
c4df14c785 | ||
|
|
a962c52bcb | ||
|
|
05ad179ee3 | ||
|
|
efa2f743c1 | ||
|
|
05cc34cbaa | ||
|
|
3f8cf11d3d | ||
|
|
404090d8ed | ||
|
|
eb14a1610f | ||
|
|
60dd772b83 | ||
|
|
6d16105201 | ||
|
|
36c937d718 | ||
|
|
c7fe3d27f0 | ||
|
|
f6f6bfce34 |
No files matched your search
@@ -6,6 +6,12 @@
|
||||
"runtimeExecutable": "wails",
|
||||
"runtimeArgs": ["dev", "-browser=false"],
|
||||
"port": 34115
|
||||
},
|
||||
{
|
||||
"name": "wails-dev-firstrun",
|
||||
"runtimeExecutable": "pwsh",
|
||||
"runtimeArgs": ["-NoProfile", "-Command", "$env:REIMS_GO_FIRST_RUN='1'; $env:REIMS_GO_LOCATION_FILE='D:/Build/Temp/reims-firstrun/location.json'; wails dev -browser=false"],
|
||||
"port": 34115
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
name: Bug 反馈
|
||||
description: 报告启动失败、安装异常或界面问题
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: 问题描述
|
||||
description: 简述遇到了什么问题,以及预期行为。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: env
|
||||
attributes:
|
||||
label: 宿主机环境
|
||||
description: 建议附带 `reims-go doctor` 输出(请勿包含序列号、MAC 地址或 OSK 等敏感信息)。
|
||||
placeholder: |
|
||||
- Windows 版本:例如 Windows 11 24H2 / Windows 10 22H2
|
||||
- CPU / 显卡:例如 i7-12700K / RTX 4070 Ti
|
||||
- Reims-Go 版本:例如 v0.2.0
|
||||
- 运行时版本:例如 runtime-3731afd
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: 复现步骤
|
||||
placeholder: |
|
||||
1. ...
|
||||
2. ...
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: 相关日志(可选)
|
||||
render: text
|
||||
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: 开发路线图(Roadmap)
|
||||
url: https://github.com/Nwflower/Reims-Go/blob/main/docs/roadmap.md
|
||||
about: 查看当前进度与已规划功能,避免重复提问
|
||||
@@ -0,0 +1,16 @@
|
||||
name: 功能建议
|
||||
description: 提出新功能想法或体验改进建议
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: textarea
|
||||
id: summary
|
||||
attributes:
|
||||
label: 你希望解决什么问题或新增什么功能?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: details
|
||||
attributes:
|
||||
label: 补充说明(可选)
|
||||
description: 使用场景、交互设想或参考案例。
|
||||
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 39 KiB |
@@ -0,0 +1,309 @@
|
||||
name: Build Portable Runtime (Alpha)
|
||||
|
||||
# Daily: build the newest steelbrain/reims-vgpu commit with the patch queue
|
||||
# (patches/series.txt) and publish it as a GitHub prerelease = the alpha
|
||||
# channel (portable-runtime-spec.md section 6). Never publishes stable:
|
||||
# promotion needs a real-host smoke test and a person (AGENTS.md rule 6).
|
||||
on:
|
||||
schedule:
|
||||
- cron: "23 3 * * *" # 03:23 UTC daily; skipped when upstream has not moved
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
upstream_commit:
|
||||
description: "steelbrain/reims-vgpu commit (empty = upstream default branch HEAD)"
|
||||
required: false
|
||||
default: ""
|
||||
publish:
|
||||
description: "Publish as an alpha prerelease (never stable)"
|
||||
type: boolean
|
||||
default: true
|
||||
rebuild:
|
||||
description: "Build a new patch revision (runtime-<commit>-pN) even if this upstream commit is already released"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: build-runtime
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
UPSTREAM_URL: https://github.com/steelbrain/reims-vgpu.git
|
||||
KEEP_ALPHAS: "7" # unpromoted alpha prereleases kept; older ones are deleted
|
||||
|
||||
jobs:
|
||||
resolve:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
commit: ${{ steps.r.outputs.commit }}
|
||||
skip: ${{ steps.r.outputs.skip }}
|
||||
suffix: ${{ steps.r.outputs.suffix }}
|
||||
steps:
|
||||
- id: r
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
WANT: ${{ inputs.upstream_commit }}
|
||||
REBUILD: ${{ inputs.rebuild }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git clone -q --filter=blob:none --no-checkout "$UPSTREAM_URL" up
|
||||
commit="$(git -C up rev-parse --verify "${WANT:-HEAD}^{commit}")"
|
||||
echo "commit=$commit" >> "$GITHUB_OUTPUT"
|
||||
# Already published (alpha or stable) under any short-hash length or -pN revision?
|
||||
max_rev=0
|
||||
for tag in $(gh release list -R "$GITHUB_REPOSITORY" --limit 1000 --json tagName -q '.[].tagName' | grep '^runtime-' || true); do
|
||||
rest="${tag#runtime-}"
|
||||
base="${rest%%-p*}"
|
||||
case "$commit" in
|
||||
"$base"*)
|
||||
rev=1
|
||||
if [ "$rest" != "$base" ]; then
|
||||
num="${rest#"$base"-p}"
|
||||
case "$num" in
|
||||
''|*[!0-9]*) ;;
|
||||
*) rev="$num" ;;
|
||||
esac
|
||||
fi
|
||||
if [ "$rev" -gt "$max_rev" ]; then max_rev="$rev"; fi
|
||||
echo "Upstream $commit is already released as $tag (rev $rev)"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
skip=false
|
||||
suffix=""
|
||||
if [ "$max_rev" -gt 0 ]; then
|
||||
if [ "$REBUILD" = "true" ]; then
|
||||
suffix="-p$((max_rev + 1))"
|
||||
echo "Rebuild requested: will publish with suffix $suffix"
|
||||
else
|
||||
skip=true
|
||||
fi
|
||||
fi
|
||||
echo "skip=$skip" >> "$GITHUB_OUTPUT"
|
||||
echo "suffix=$suffix" >> "$GITHUB_OUTPUT"
|
||||
|
||||
build:
|
||||
needs: resolve
|
||||
if: needs.resolve.outputs.skip != 'true'
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 150
|
||||
outputs:
|
||||
short: ${{ steps.patches.outputs.short }}
|
||||
release_id: ${{ steps.patches.outputs.release_id }}
|
||||
applied: ${{ steps.patches.outputs.applied }}
|
||||
merged: ${{ steps.patches.outputs.merged }}
|
||||
conflict: ${{ steps.patches.outputs.conflict }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup MSYS2 CLANG64
|
||||
id: msys2
|
||||
uses: msys2/setup-msys2@v2
|
||||
with:
|
||||
msystem: CLANG64
|
||||
update: true
|
||||
install: >-
|
||||
git zstd tar mingw-w64-clang-x86_64-toolchain
|
||||
mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-meson
|
||||
mingw-w64-clang-x86_64-ninja mingw-w64-clang-x86_64-pkgconf
|
||||
mingw-w64-clang-x86_64-glib2 mingw-w64-clang-x86_64-pixman
|
||||
mingw-w64-clang-x86_64-gtk3 mingw-w64-clang-x86_64-libslirp
|
||||
mingw-w64-clang-x86_64-libusb mingw-w64-clang-x86_64-libva
|
||||
mingw-w64-clang-x86_64-mesa mingw-w64-clang-x86_64-vulkan-loader
|
||||
mingw-w64-clang-x86_64-python mingw-w64-clang-x86_64-python-pip
|
||||
|
||||
- name: Check out upstream and apply the patch queue
|
||||
id: patches
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$work = Join-Path $env:RUNNER_TEMP 'reims-vgpu'
|
||||
foreach ($d in 'cargo', 'xdg-data', 'xdg-cache') { New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP $d) | Out-Null }
|
||||
# The runner's git defaults to core.autocrlf=true; LF patches need an LF
|
||||
# checkout (upstream also rewrites CRLF files to LF, install-ctl.sh).
|
||||
git config --global core.autocrlf false
|
||||
git clone -q $env:UPSTREAM_URL $work
|
||||
if ($LASTEXITCODE) { throw 'clone failed' }
|
||||
git -C $work checkout -q '${{ needs.resolve.outputs.commit }}'
|
||||
if ($LASTEXITCODE) { throw 'checkout failed' }
|
||||
git -C $work submodule update --init --depth 1 vendor/qemu
|
||||
if ($LASTEXITCODE) { git -C $work submodule update --init vendor/qemu }
|
||||
if ($LASTEXITCODE) { throw 'vendor/qemu submodule failed' }
|
||||
$short = (git -C $work rev-parse --short=7 HEAD).Trim()
|
||||
$releaseId = "$short${{ needs.resolve.outputs.suffix }}"
|
||||
"short=$short" >> $env:GITHUB_OUTPUT
|
||||
"release_id=$releaseId" >> $env:GITHUB_OUTPUT
|
||||
|
||||
# Applies what applies, skips what upstream already has, stops on a
|
||||
# conflict without touching the patch (AGENTS.md rule 4).
|
||||
$resultFile = Join-Path $env:RUNNER_TEMP 'patches.json'
|
||||
try {
|
||||
pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -ResultFile $resultFile
|
||||
$ok = $LASTEXITCODE -eq 0
|
||||
} finally {
|
||||
if (Test-Path $resultFile) {
|
||||
$r = Get-Content -Raw $resultFile | ConvertFrom-Json
|
||||
"applied=$(@($r.applied) -join ',')" >> $env:GITHUB_OUTPUT
|
||||
"merged=$(@($r.merged) -join ',')" >> $env:GITHUB_OUTPUT
|
||||
"conflict=$($r.conflict)" >> $env:GITHUB_OUTPUT
|
||||
"APPLIED_PATCHES=$(@($r.applied) -join ',')" >> $env:GITHUB_ENV
|
||||
}
|
||||
}
|
||||
if (-not $ok) { throw 'patch queue does not apply' }
|
||||
"UPSTREAM_DIR=$work" >> $env:GITHUB_ENV
|
||||
"SHORT_COMMIT=$short" >> $env:GITHUB_ENV
|
||||
"RELEASE_ID=$releaseId" >> $env:GITHUB_ENV
|
||||
"CARGO_HOME=$(Join-Path $env:RUNNER_TEMP 'cargo')" >> $env:GITHUB_ENV
|
||||
"XDG_DATA_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-data')" >> $env:GITHUB_ENV
|
||||
"XDG_CACHE_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-cache')" >> $env:GITHUB_ENV
|
||||
|
||||
- name: Build upstream runtime in MSYS2 CLANG64
|
||||
shell: msys2 {0}
|
||||
env:
|
||||
REIMS_INSTALL_SKIP_HOST_CHECKS: "1"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd "$(cygpath -u "$UPSTREAM_DIR")"
|
||||
# Upstream's own non-interactive CLANG64 build script.
|
||||
bash scripts/install-ctl.sh --yes
|
||||
|
||||
- name: Package alpha runtime and source archives
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$outDir = Join-Path $env:RUNNER_TEMP 'releases'
|
||||
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
|
||||
# In-process call, so an empty list (every patch already upstream) binds
|
||||
# as an empty array rather than being dropped as an empty argument.
|
||||
$applied = @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
|
||||
& ./scripts/pack-runtime.ps1 `
|
||||
-ReimsRepo $env:UPSTREAM_DIR `
|
||||
-CargoHome $env:CARGO_HOME `
|
||||
-QemuDir (Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current') `
|
||||
-Msys2 '${{ steps.msys2.outputs.msys2-location }}' `
|
||||
-OutDir $outDir `
|
||||
-TempRoot $env:RUNNER_TEMP `
|
||||
-Channel alpha `
|
||||
-ReleaseId $env:RELEASE_ID `
|
||||
-Patches $applied
|
||||
|
||||
- name: Alpha entry gate
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
& ./scripts/check-runtime-alpha.ps1 `
|
||||
-OutDir (Join-Path $env:RUNNER_TEMP 'releases') `
|
||||
-Commit $env:RELEASE_ID -RequireSlim `
|
||||
-Zstd (Join-Path '${{ steps.msys2.outputs.msys2-location }}' 'usr\bin\zstd.exe') `
|
||||
-AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
|
||||
|
||||
- name: Upload alpha artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: reims-runtime-win-x64-${{ env.RELEASE_ID }}-alpha
|
||||
path: |
|
||||
${{ runner.temp }}/releases/reims-runtime-*.tar.zst
|
||||
${{ runner.temp }}/releases/SHA256SUMS.txt
|
||||
retention-days: 14
|
||||
|
||||
- name: Publish alpha prerelease (never stable)
|
||||
if: github.event_name == 'schedule' || inputs.publish
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
MERGED: ${{ steps.patches.outputs.merged }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$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", "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 { '' }
|
||||
$notes = @"
|
||||
**Alpha** runtime (``$c``), built automatically from upstream [steelbrain/reims-vgpu@$short](https://github.com/steelbrain/reims-vgpu/commit/${{ needs.resolve.outputs.commit }}).
|
||||
|
||||
Not smoke-tested on a real host. It becomes stable only after ``scripts/smoke-runtime.ps1`` passes on a real Windows host and a person approves (portable-runtime-spec.md section 6).
|
||||
|
||||
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
|
||||
if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" }
|
||||
|
||||
- name: Mirror alpha prerelease to GitCode (best-effort)
|
||||
if: github.event_name == 'schedule' || inputs.publish
|
||||
continue-on-error: true
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
|
||||
GITHUB_REPO: ${{ github.repository }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
if (-not $env:GITCODE_TOKEN) {
|
||||
Write-Host 'GITCODE_TOKEN not set; skipping GitCode mirror'
|
||||
exit 0
|
||||
}
|
||||
$tag = "runtime-$($env:RELEASE_ID)"
|
||||
git fetch --tags origin
|
||||
git -c credential.helper= push "https://Nwflower:$($env:GITCODE_TOKEN)@gitcode.com/Nwflower/Reims-Go.git" "refs/tags/${tag}:refs/tags/${tag}"
|
||||
python scripts/sync-gitcode-release.py $tag
|
||||
|
||||
- name: Prune old alpha prereleases
|
||||
if: github.event_name == 'schedule' || inputs.publish
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
# Only unpromoted runtime prereleases; stable releases are never touched.
|
||||
$alphas = gh release list -R $env:GITHUB_REPOSITORY --limit 1000 --json tagName,isPrerelease,isDraft,createdAt | ConvertFrom-Json |
|
||||
Where-Object { $_.tagName -like 'runtime-*' -and $_.isPrerelease -and -not $_.isDraft } |
|
||||
Sort-Object createdAt -Descending
|
||||
$alphas | Select-Object -Skip ([int]$env:KEEP_ALPHAS) | ForEach-Object {
|
||||
Write-Host "Deleting old alpha $($_.tagName)"
|
||||
gh release delete $_.tagName -R $env:GITHUB_REPOSITORY --yes --cleanup-tag
|
||||
}
|
||||
|
||||
report:
|
||||
needs: [resolve, build]
|
||||
if: always() && needs.resolve.outputs.skip != 'true' && (failure() || needs.build.outputs.merged != '')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
RESULT: ${{ needs.build.result }}
|
||||
COMMIT: ${{ needs.resolve.outputs.commit }}
|
||||
CONFLICT: ${{ needs.build.outputs.conflict }}
|
||||
MERGED: ${{ needs.build.outputs.merged }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# One open issue per kind; later runs add a comment instead of a new issue.
|
||||
file_issue() {
|
||||
local title="$1" body="$2" n
|
||||
n="$(gh issue list -R "$GITHUB_REPOSITORY" --state open --search "in:title \"$title\"" --json number,title -q ".[] | select(.title == \"$title\") | .number" | head -n1)"
|
||||
if [ -n "$n" ]; then
|
||||
gh issue comment "$n" -R "$GITHUB_REPOSITORY" --body "$body"
|
||||
else
|
||||
gh issue create -R "$GITHUB_REPOSITORY" --title "$title" --body "$body"
|
||||
fi
|
||||
}
|
||||
if [ "$RESULT" != "success" ]; then
|
||||
if [ -n "$CONFLICT" ]; then
|
||||
why="Patch \`$CONFLICT\` neither applies to upstream \`$COMMIT\` nor is already there. Per AGENTS.md rule 4 the patch was not edited; a person decides how to rebase or retire it."
|
||||
else
|
||||
why="The build, packaging or alpha gate failed for upstream \`$COMMIT\`; see the log."
|
||||
fi
|
||||
file_issue "Runtime alpha build failed" "$why"$'\n\n'"Run: $RUN_URL"$'\n\n'"No alpha was published."
|
||||
fi
|
||||
if [ -n "$MERGED" ]; then
|
||||
file_issue "Patch queue: patches already upstream" "Upstream \`$COMMIT\` already contains: \`$MERGED\`. They were skipped. Record the merge commit in portable-runtime-spec.md section 5, then remove them from patches/ and patches/series.txt."$'\n\n'"Run: $RUN_URL"
|
||||
fi
|
||||
@@ -0,0 +1,61 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
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: |
|
||||
pnpm --dir frontend install --frozen-lockfile
|
||||
pnpm --dir frontend build
|
||||
|
||||
- name: Go test & vet
|
||||
shell: pwsh
|
||||
run: |
|
||||
go test ./...
|
||||
go vet ./...
|
||||
|
||||
- name: Build reims-go.exe (window + command-line mode)
|
||||
shell: pwsh
|
||||
run: |
|
||||
New-Item -ItemType Directory -Force -Path build/bin | Out-Null
|
||||
go build -trimpath -tags desktop,production -ldflags "-H windowsgui" -o build/bin/reims-go.exe .
|
||||
# Command-line mode must still answer through a pipe from the GUI-subsystem build.
|
||||
$out = & build/bin/reims-go.exe version | Out-String
|
||||
if ($LASTEXITCODE -ne 0 -or $out -notmatch '^reims-go ') { throw "reims-go.exe version failed: $out" }
|
||||
@@ -0,0 +1,154 @@
|
||||
name: Release Reims-Go
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Release tag to build & publish (e.g. v0.2.1)"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || '' }}
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
cache-dependency-path: frontend/pnpm-lock.yaml
|
||||
|
||||
- name: Resolve version tag
|
||||
shell: pwsh
|
||||
run: |
|
||||
$tag = if ('${{ github.event_name }}' -eq 'workflow_dispatch') { '${{ inputs.tag }}' } else { '${{ github.ref_name }}' }
|
||||
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: |
|
||||
pnpm --dir frontend install --frozen-lockfile
|
||||
pnpm --dir frontend build
|
||||
|
||||
- name: Go test & vet
|
||||
shell: pwsh
|
||||
run: |
|
||||
go test ./...
|
||||
go vet ./...
|
||||
|
||||
- name: Install Wails CLI
|
||||
shell: pwsh
|
||||
run: go install github.com/wailsapp/wails/v2/cmd/wails@v2.17.1
|
||||
|
||||
- name: Build Windows x64 binary
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tag = $env:RELEASE_TAG
|
||||
$dist = 'dist-release'
|
||||
New-Item -ItemType Directory -Force -Path $dist | Out-Null
|
||||
$verPkg = 'github.com/Nwflower/reims-go/internal/version'
|
||||
# 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
|
||||
$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)"
|
||||
})
|
||||
[IO.File]::WriteAllText((Join-Path $dist 'SHA256SUMS.txt'), ($lines -join "`n") + "`n", [Text.UTF8Encoding]::new($false))
|
||||
Get-Content (Join-Path $dist 'SHA256SUMS.txt')
|
||||
|
||||
- name: Publish GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
shell: pwsh
|
||||
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 {
|
||||
$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" `
|
||||
--notes-file $notesFile
|
||||
if ($LASTEXITCODE -ne 0) { throw "gh release create failed ($LASTEXITCODE)" }
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
name: Sync Mirror to GitCode
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
release:
|
||||
types: [published, released, edited, prereleased]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Specific release tag to sync (empty = latest app release + all runtime-* releases)"
|
||||
required: false
|
||||
default: ""
|
||||
sync_releases:
|
||||
description: "Also sync Release metadata and assets to GitCode"
|
||||
type: boolean
|
||||
default: true
|
||||
|
||||
concurrency:
|
||||
group: sync-gitcode
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GITCODE_REPO: Nwflower/Reims-Go
|
||||
GITCODE_USER: Nwflower
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Push main branch and tags to GitCode
|
||||
env:
|
||||
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "$GITCODE_TOKEN" ]; then
|
||||
echo "GITCODE_TOKEN secret is not configured; skipping."
|
||||
exit 0
|
||||
fi
|
||||
git fetch --tags origin
|
||||
# Use GIT_ASKPASS so the token never appears in URLs or process argv.
|
||||
askpass="$(mktemp)"
|
||||
chmod 700 "$askpass"
|
||||
cat > "$askpass" <<'EOF'
|
||||
#!/bin/sh
|
||||
case "$1" in
|
||||
*Username*) printf '%s\n' "$GITCODE_USER" ;;
|
||||
*) printf '%s\n' "$GITCODE_TOKEN" ;;
|
||||
esac
|
||||
EOF
|
||||
trap 'rm -f "$askpass"' EXIT
|
||||
GIT_TERMINAL_PROMPT=0 GIT_ASKPASS="$askpass" git -c credential.helper= push "https://gitcode.com/${GITCODE_REPO}.git" HEAD:refs/heads/main
|
||||
GIT_TERMINAL_PROMPT=0 GIT_ASKPASS="$askpass" git -c credential.helper= push "https://gitcode.com/${GITCODE_REPO}.git" --tags
|
||||
|
||||
- name: Sync Release and assets to GitCode
|
||||
if: github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && inputs.sync_releases)
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
|
||||
GITHUB_REPO: ${{ github.repository }}
|
||||
TARGET_TAG: ${{ github.event.release.tag_name || inputs.tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "$GITCODE_TOKEN" ]; then
|
||||
echo "GITCODE_TOKEN secret is not configured; skipping release sync."
|
||||
exit 0
|
||||
fi
|
||||
if [ -n "$TARGET_TAG" ]; then
|
||||
python3 scripts/sync-gitcode-release.py "$TARGET_TAG"
|
||||
else
|
||||
python3 scripts/sync-gitcode-release.py
|
||||
fi
|
||||
@@ -21,20 +21,20 @@
|
||||
## 事实核验与安全规则
|
||||
|
||||
1. **上游行为以一手源码为准**:引用 `reims-ctl` / `reims-vgpu` 行为时附上游 commit 与 `文件:行号`;未实测项显式标「待验证」。
|
||||
2. **不绕过系统安全与人工确认**:UAC 提权启用 WHPX、重启 Windows、macOS GUI 安装向导、发布 Release 等操作由人确认触发。
|
||||
2. **不绕过系统安全与人工确认**:UAC 提权启用 WHPX、重启 Windows、macOS GUI 安装向导、发布正式 Release 等操作由人确认触发。唯一例外(2026-11-28 决定):`build-runtime.yml` 每天从上游自动构建,通过 alpha 准入检查后可以自动发布为 GitHub **预发布**(`alpha` 通道),也会自动删除较旧的、未升级的 alpha 预发布。升为 `stable`(正式发布)始终由人触发。
|
||||
3. **敏感与专有内容零入库**:严禁提交 SMC OSK、SMBIOS 真实序列号、MAC 地址、任何 Apple IPSW / BaseSystem / 解密固件或闭源二进制。
|
||||
4. **对上游的修改只走补丁队列**:不长期维护 fork。改动以补丁形式放在 `patches/`,在 `docs/portable-runtime-spec.md` 第 5 节登记,目标是清零。补丁打不上就停下报告,不要自动改补丁。向上游提 PR 由人来做。
|
||||
5. **运行时包必须如实声明来源**:`manifest.json` 写清上游 commit、`vendor/qemu` commit 和全部补丁。带补丁的包不能写成「纯上游」。
|
||||
6. **用户只拿 `stable` 通道**:CI 产物只进 `candidate`,经真实宿主冒烟测试并由人确认后才升级(`portable-runtime-spec.md` 第 6 节)。
|
||||
6. **用户只拿 `stable` 通道**:CI 产物只进 `alpha`(2026-11-28 前叫 `candidate`),经真实宿主冒烟测试并由人确认后才升级(`portable-runtime-spec.md` 第 6 节)。
|
||||
7. **配置只通过 `reims-ctl set` 写入**:不直接改 `vm.toml`,让上游的校验和 OpenCore 重建逻辑生效(`docs/shell-design.md`)。
|
||||
|
||||
## 开源合规边界
|
||||
|
||||
- `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 保持私有。
|
||||
- 2026-11-28 已决定:仓库 [`Nwflower/reims-go`](https://github.com/Nwflower/reims-go) 公开,便携运行时通过它的 GitHub Release 分发。因此每个运行时 Release **必须**附带对应源码包和许可证文本,缺一不可。新包先进 `candidate`(GitHub 预发布),经真实宿主冒烟并由人确认后才升为 `stable`。
|
||||
- 2026-11-28 已决定:仓库 [`Nwflower/reims-go`](https://github.com/Nwflower/reims-go) 公开,便携运行时通过它的 GitHub Release 分发。因此每个运行时 Release **必须**附带对应源码包和许可证文本,缺一不可。新包先进 `alpha`(GitHub 预发布,由 CI 每天从上游自动构建),经真实宿主冒烟并由人确认后才升为 `stable`。
|
||||
|
||||
## 文档导航
|
||||
|
||||
@@ -43,5 +43,5 @@
|
||||
- [`docs/architecture.md`](docs/architecture.md) — Go + Wails 分层架构、环境隔离、WHPX/GPU/P-Core 自动调优与控制面设计
|
||||
- [`docs/shell-design.md`](docs/shell-design.md) — 外壳设计原语:配置模型与交互对齐 macOS(Virtualization.framework 与 macOS 人机界面规范)
|
||||
- [`docs/ui-redesign.md`](docs/ui-redesign.md) — 前端改版方案:VM 主面板信息架构、视觉令牌、进度与日志、分阶段计划
|
||||
- [`patches/`](patches/) — 对上游的补丁队列(当前只有 Win10 WHPX 兼容补丁)
|
||||
- [`patches/`](patches/) — 对上游的补丁队列,清单见 `patches/README.md`
|
||||
- [`docs/roadmap.md`](docs/roadmap.md) — M0–M4 里程碑与验收标准
|
||||
@@ -0,0 +1,138 @@
|
||||
# 更新日志
|
||||
|
||||
本文件只记录 Reims-Go 桌面应用的变化。便携运行时(`runtime-*`)的版本另见 [Releases](https://github.com/Nwflower/Reims-Go/releases)。
|
||||
|
||||
## v0.2.6 — 2026-11-29
|
||||
|
||||
### 新功能
|
||||
|
||||
- **独立 CPU 绑核**:每台虚拟机可单独选择自动、全部核心、性能核、避开低功耗核或自定义核心组合,运行中修改立即生效,派生副本时自动继承。
|
||||
- **离线恢复点**:支持在关机状态下为虚拟磁盘创建、回滚与删除恢复点。
|
||||
- **SSH 快捷工具**:支持记住 SSH 用户名,一键打开终端、写入 `~/.ssh/config` 或通过 VS Code Remote-SSH 连接。
|
||||
- **窗口控制、截图与文件拖放**:支持一键前置虚拟机窗口、复制全分辨率屏幕截图到剪贴板,以及把文件直接拖进应用窗口传到共享文件夹。
|
||||
- **虚拟机显示名称与页面改版**:支持点击标题就地修改显示名称(保留底层标识名),宽窗口下预览与规格摘要并排呈现;围绕当前状态突出主操作,整合 Guest Tools 与磁盘/网络/实时负载摘要。
|
||||
- **标题栏菜单与可折叠侧栏**:新增标题栏菜单(虚拟机 / 视图 / 帮助,带快捷键)和 `Ctrl+B` 侧栏折叠,支持侧栏虚拟机右键菜单,状态栏信息更加精简。
|
||||
- **系统托盘菜单改版**:每台虚拟机拥有独立子菜单与状态圆点,自动跟随 Windows 系统浅/深色主题,后台操作失败或复制截图时通过系统通知提示。
|
||||
- **macOS 版本图标与「安装包」页改版**:记录虚拟机创建时的 macOS 版本并在侧栏和未截屏预览中展示对应版本数字图标;「安装包」页按大版本归组卡片、折叠旧小版本并新增重试按钮。
|
||||
|
||||
### 优化与修复
|
||||
|
||||
- **内存与资源回收优化**:删除虚拟机或退出时及时释放缩略图锁、Guest Tools 注册与 WebDAV 处理器、远程键入队列、监控协程和绑核记录;4K 屏幕预览改用按行流式缩放,大幅降低内存分配;串口与 QEMU 日志监控限制单行缓存上限。
|
||||
- **前端渲染与包体优化**:次级页面与弹窗改为按需懒加载,单机统计轮询下沉至虚拟机页以减少整页重绘,定期清理过期任务记录,并移除不透明区域的冗余毛玻璃合成层。
|
||||
- **修复空间分布统计**:修正虚拟机目录路径(`reims-ctl/vms`),并将数据目录内其余文件一并归入 Reims-Go 空间分布。
|
||||
- **开源协议与发行包调整**:Reims-Go 本体协议由 MIT 变更为 Apache-2.0;Release 同时提供 `.zip` 压缩包与独立 `.exe`,并自动依据 `CHANGELOG.md` 生成发布说明。
|
||||
|
||||
## v0.2.5 — 2026-11-29
|
||||
|
||||
### 新功能
|
||||
|
||||
- 运行时下载与更新检查新增 GitCode 国内镜像源,默认自动优先 GitHub 并在不可达时自动切换 GitCode。
|
||||
- 桌面外壳视觉与交互升级:精简 VM 主页为 Studio Display 预览、2×3 图标规格卡、单行连接分组与可一键复制的技术信息;支持日志抽屉顶部拖拽调整高度。
|
||||
- 侧栏「宿主与运行时」改称「内核」,将应用配置拆分为独立「设置」标签页(新增浅色 / 深色 / 跟随系统外观切换)。
|
||||
- 底部状态栏空闲时实时展示宿主机内存占用百分比、可用内存、数据盘剩余空间与运行中虚拟机数量。
|
||||
|
||||
### 优化与修复
|
||||
|
||||
- 内嵌开源 Inter Variable 字体并按 Windows DirectWrite 特性显式映射多字重中文字体栈,修复默认字重偏轻与中英文混排断层问题。
|
||||
- 修复 GitCode API 将 alpha 运行时预发布返回为 `prerelease=false` 导致稳定通道误报新版本的问题。
|
||||
- 遵循 Windows 系统代理配置并在 GitHub API 触发限流时自动回退网页解析,下载检查失败时提供一键重试。
|
||||
- 按实际图形后端(`reims-vgpu` / `vmware-svga`)显示准确的虚拟机窗口快捷键提示。
|
||||
|
||||
## v0.2.4 — 2026-11-29
|
||||
|
||||
### 新功能
|
||||
|
||||
- 分辨率选项新增「全屏」,原来单独的全屏开关并入其中。
|
||||
- HiDPI 分辨率标出实际显示大小,例如「看起来像 1280 × 800」。
|
||||
- 宿主页显示 Windows 处理器计划(程序优先或后台服务),并可一键以管理员身份打开设置。
|
||||
|
||||
### 优化
|
||||
|
||||
- 分辨率推荐按 macOS 实际进入 HiDPI 的条件判断,只列出放得进屏幕的尺寸;进不了 HiDPI 时会说明怎么办。
|
||||
- 虚拟机自己关机或退出后,界面立即显示已停止,不再最多等 5 秒。
|
||||
- 设置页能正确读出已保存的分辨率、显示器数量、VMware SVGA 显卡后端和不限时的关机等待。
|
||||
- 显示器数量改成多块后可以再改回 1。
|
||||
|
||||
## v0.2.3 — 2026-11-28
|
||||
|
||||
### 新功能
|
||||
|
||||
- 命令行并入 `reims-go.exe`:双击打开界面,带子命令即在终端运行,不再单独提供命令行版。
|
||||
- 从命令行启动的虚拟机交给 Reims-Go 界面托管,界面没开时自动在托盘后台运行,同样有剪贴板、共享目录和 Win10 自动冷重启。
|
||||
- 同时只运行一个 Reims-Go,再次双击会唤出已打开的窗口。
|
||||
- 可把 Windows 本地磁盘只读共享给 macOS,每台虚拟机单独开启,默认关闭。
|
||||
|
||||
### 优化
|
||||
|
||||
- 虚拟机页面在后台查询虚拟机状态的次数减少约八成。
|
||||
- 屏幕缩略图生成更快、改为每 15 秒刷新,虚拟机窗口在前台时暂停截图,减少对虚拟机的打扰。
|
||||
- 命令行启动失败时直接显示原因。
|
||||
|
||||
## v0.2.2 — 2026-11-28
|
||||
|
||||
### 新功能
|
||||
|
||||
- Guest Tools 2.0:支持图片剪贴板,共享目录可直接挂载到 macOS。
|
||||
- 可向虚拟机发送中文和 emoji,宿主机输入法也能直接输入到虚拟机。
|
||||
- 系统托盘驻留,关闭窗口后最小化到托盘,可从托盘启停虚拟机。
|
||||
- 一键开关 macOS 防休眠。
|
||||
- 详情页实时显示虚拟机的 CPU、内存、磁盘占用和运行时长。
|
||||
- 详情页显示虚拟机屏幕缩略图。
|
||||
- 按显示器分辨率和缩放推荐 HiDPI 分辨率。
|
||||
- 可预设 macOS 系统语言,恢复模式和设置助理不再总是英文。
|
||||
- 虚拟磁盘支持停机扩容和回收未用空间。
|
||||
- 可切换音频后端,并检查宿主机的播放和录音设备。
|
||||
- 设置面板改版为 macOS 系统设置风格,改动可逐项撤销。
|
||||
- 运行时候选通道改名为 alpha,每天自动从上游构建。
|
||||
|
||||
### 优化
|
||||
|
||||
- 截取缩略图改用更快的格式,截图时虚拟机的卡顿大幅减少。
|
||||
- 运行中虚拟机的状态识别更准确,相关提示和保护恢复正常。
|
||||
|
||||
## v0.2.1 — 2026-11-28
|
||||
|
||||
### 新功能
|
||||
|
||||
- 离线装机辅助盘自动完成抹盘和安装命令,装机不用手敲长命令。
|
||||
- 一键进入或退出恢复模式,可挂载离线镜像或下载在线恢复镜像。
|
||||
- Guest Tools:宿主机与 macOS 之间双向剪贴板和共享文件夹。
|
||||
- 已关机的虚拟机可秒级派生出独立副本。
|
||||
- 新建虚拟机时可导入 VMDK 或 RAW 磁盘。
|
||||
- 一键导出已脱敏的排障日志包。
|
||||
- 宿主页显示当前版本并检查更新。
|
||||
|
||||
### 优化
|
||||
|
||||
- 新建虚拟机默认使用 NVMe 磁盘,旧虚拟机可一键升级。
|
||||
- 绑核支持三层大小核,虚拟 CPU 多于性能核时自动避开低功耗核。
|
||||
- Win10 冷重启使用的控制通道只在本机可见,虚拟机内无法访问。
|
||||
- 数据目录在外置盘、网络盘或内存负载过高时给出提示。
|
||||
- 临时文件全部放在数据目录里,不再写入 C 盘。
|
||||
|
||||
## v0.2.0 — 2026-11-28
|
||||
|
||||
### 新功能
|
||||
|
||||
- 默认用离线安装包装机,装机引导精简为三步。
|
||||
- 新增「安装包」页面,可下载、暂停、续传和删除离线安装包。
|
||||
- 按 Windows 实际可用内存推荐内存大小,新建、修改和启动前都会检查。
|
||||
- 首次启动时先检查 WHPX、显卡和内存,再安装运行时。
|
||||
- 新建助手增加确认页,创建改在后台进行。
|
||||
|
||||
### 优化
|
||||
|
||||
- 宿主页去掉重复信息,运行时合并为一个列表。
|
||||
- 新建时虚拟机重名会提前提示。
|
||||
- 运行时版本列表缓存 10 分钟,避免触发 GitHub 访问次数限制。
|
||||
|
||||
## v0.1.0 — 2026-11-28
|
||||
|
||||
### 新功能
|
||||
|
||||
- 首个版本:单文件桌面应用,在 Windows x64 上运行带 GPU 加速的 macOS 虚拟机,无需自己编译。
|
||||
- 虚拟机列表、启动和关机、分类设置面板与分步新建助手。
|
||||
- 离线安装包下载,支持暂停和续传。
|
||||
- 运行时在线安装,分稳定版和候选版两个通道。
|
||||
- 宿主机体检,虚拟机启动后自动绑定到性能核。
|
||||
- Win10 上虚拟机内部重启时自动冷重启。
|
||||
@@ -1,30 +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.
|
||||
|
||||
This license covers reims-go's own code (Go backend and frontend shell) only.
|
||||
The portable runtime packages distributed as release assets bundle third-party
|
||||
components (QEMU under GPL-2.0, reims-vgpu / reims-ctl / reims-util /
|
||||
metal2vulkan under GPL-2.0-or-later OR LGPL-3.0-or-later, and MSYS2 CLANG64
|
||||
libraries under their own licenses). Each runtime release ships the matching
|
||||
source package, NOTICE.md and licenses/ — see docs/portable-runtime-spec.md §7.
|
||||
"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.
|
||||
@@ -1,10 +1,14 @@
|
||||
# Third-Party Notices
|
||||
|
||||
`reims-go` itself (Go backend and desktop frontend) is licensed separately 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:
|
||||
precompiled binaries built from the following upstream open-source projects.
|
||||
Each runtime release ships the matching source package, `NOTICE.md`, and
|
||||
`licenses/` (see `docs/portable-runtime-spec.md` §7):
|
||||
|
||||
1. **reims-vgpu / reims-ctl**
|
||||
- Upstream: https://github.com/steelbrain/reims-vgpu
|
||||
|
||||
@@ -1,37 +1,187 @@
|
||||
# reims-go
|
||||
<p align="center">
|
||||
<a href="https://github.com/Nwflower/Reims-Go">
|
||||
<img src="./assets/logo.png" width="76" height="76" alt="Reims-Go" />
|
||||
</a>
|
||||
</p>
|
||||
|
||||
> Windows 桌面端 **免编译、一站式 `reims-vgpu` macOS 虚拟机启动器与开发者工作台**(Go + Wails,GUI + CLI 一体)。
|
||||
<h1 align="center">Reims-Go</h1>
|
||||
|
||||
## 为什么做 reims-go?
|
||||
<p align="center">
|
||||
在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。
|
||||
</p>
|
||||
|
||||
上游 [steelbrain/reims-vgpu](https://github.com/steelbrain/reims-vgpu) 已经实现了在 Windows 原生 QEMU + WHPX 上将 macOS Guest 的 Metal 图形转译到宿主机 Vulkan GPU(如 NVIDIA RTX 4070 Ti)。但当前使用门槛依然很高:
|
||||
<p align="center">
|
||||
<a href="https://github.com/Nwflower/Reims-Go/releases"><strong>下载</strong></a> ·
|
||||
<a href="#快速开始">快速开始</a> ·
|
||||
<a href="#界面">界面</a> ·
|
||||
<a href="./docs/roadmap.md">路线图</a>
|
||||
</p>
|
||||
|
||||
1. **安装编译繁琐**:需手动安装 MSYS2、换镜像源、装 Rust、拉取 `vendor/qemu` 并本地编译 1800+ 目标(耗时 15–30 分钟)。
|
||||
2. **默认污染 C 盘**:MSYS2、Cargo/Rustup、QEMU 构建和上百 GB 的 macOS 虚拟盘默认全部写入 `%USERPROFILE%` 与 `C:\msys64`。
|
||||
3. **硬件排障靠手工**:缺少 WHPX 一键体检、多显卡/虚拟显示适配器(如 ToDesk/GameViewer)自动过滤、Intel 12–14 代大小核 P-Core 亲和性绑核。
|
||||
4. **缺少开发者工作流**:上游 `reims-ctl` 未内置 CoW 秒级派生、快照管理、QMP 控制与自动化测试闭环;现有社区 GUI(如 PySide6 打包的 `Reims-GUI-Win`)包体达 1.68 GB 且绕开了 `reims-ctl`,难以跟进上游更新。
|
||||
<br />
|
||||
|
||||
**`reims-go` 的解法**:
|
||||
- **免编译便携运行时**:通过 CI 预编译单套 `reims-runtime-win-x64`(仅含 `reims-ctl.exe` + `reims-util.exe` + 自包含 71 DLL 的 `qemu/`,**彻底脱离 MSYS2 / Rust / Git**),经本机冒烟测试后进入 `stable` 通道,用户端下载解压即用。
|
||||
- **把上游当内核**:不长期维护 fork。对上游的修改只放在 `patches/` 补丁队列里,同时向上游提 PR,合并后删掉,目标是补丁数清零。
|
||||
- **轻量单文件外壳**:Go + Wails(复用系统内置 WebView2),GUI 与 CLI 共用同一套 Go 核心包,不捆绑 Python / PowerShell 7。
|
||||
- **紧贴 `reims-ctl` 生态**:以子进程封装 `reims-ctl` 与 `reims-util`(并通过 `XDG_*` 环境变量强制隔离到用户指定盘符),上游更新只需同步发布新版运行时包。
|
||||
- **GUI 宿主机断点续传离线下载**:通过 `reims-util --json` 在宿主机直接下载可复用的 **macOS 离线完整安装包**(结构化进度条 + 自动断点续传 + 缓存管理),规避 Recovery 内经 QEMU SLIRP 在线拉取 ~17 GB 易因 Apple CDN 断流失败的问题。
|
||||
- **工程化增值能力**:WHPX 与 Windows 提交内存(Commit Limit)一键体检、自动锁定独显 Vulkan ICD、P-Core 绑核、CoW 派生与快照、独立 QMP/SSH/截屏控制。
|
||||
<p align="center">
|
||||
<img src="./.github/readme/hero.webp" width="100%" alt="Reims-Go 主窗口:浅色外观下的虚拟机页与深色外观下的内核页" />
|
||||
</p>
|
||||
|
||||
## 技术可行性基线(2026-11-28 本机实测)
|
||||
<br />
|
||||
|
||||
- **Win10 19045 + RTX 4070 Ti 实测可用,但需要本地补丁**:本机已在 `Reims vGPU` 窗口内成功引导并进入 `Install macOS Tahoe` 图形安装界面。这次用的 QEMU 带着 [`patches/qemu-whpx-win10-compat.patch`](patches/qemu-whpx-win10-compat.patch)(修复 Win10 上 WHPX 建 vCPU `hr=80070057` 与 `WHvResetPartition` 空指针 `0xc0000005` 崩溃),不是纯上游构建。补丁的管理方式见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) 第 5 节。
|
||||
- **上游没有 Release、变动很快**:2026-11-21 到 11-28 上游有 100 多个提交。所以 `reims-go` 只给用户发冒烟测试过的 `stable` 运行时(同上文档第 6 节)。
|
||||
- **目标宿主**:Win10 的扩展支持已在 2026 年 10 月结束,上游只在 Win11 上测过。对外以 Win11 为主,Win10 靠补丁保证本机可用。
|
||||
- **便携运行时剥离实测通过**:将 `reims-ctl.exe`(58 MB)、`reims-util.exe`(31.3 MB)与 `qemu/current/`(828.5 MB,含 71 个 DLL)置于纯净 `PATH`(无 MSYS2、无 Rust、无源码仓库)中运行,`reims-ctl doctor` 的 **9/9 运行时检查全部通过**(详情见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md))。
|
||||
- **本机开发环境就绪**:`Go 1.27.3`、`Node.js`、`pnpm`、`WebView2 Runtime 158.0` 均已存在。
|
||||
Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows 桌面应用。从检查电脑、安装运行时、下载 macOS,到创建和日常使用虚拟机,都在一个窗口里完成。
|
||||
|
||||
## 文档索引
|
||||
> 早期迭代中,功能与界面仍在持续打磨。
|
||||
|
||||
- [`AGENTS.md`](AGENTS.md) — 仓库约定、存储红线与开源合规边界
|
||||
- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时实测记录、目录规范与打包方案
|
||||
- [`docs/architecture.md`](docs/architecture.md) — Go + Wails 系统架构与模块设计
|
||||
- [`docs/shell-design.md`](docs/shell-design.md) — 外壳设计原语:配置模型与交互对齐 macOS,随时修改、标明生效时机
|
||||
- [`patches/`](patches/) — 对上游的补丁队列
|
||||
- [`docs/roadmap.md`](docs/roadmap.md) — M0–M4 开发路线图与验收门槛
|
||||
<br />
|
||||
|
||||
## 特性
|
||||
|
||||
### 开箱即用
|
||||
|
||||
- **不用编译** — 运行时在应用里一键下载安装,不用装 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 />
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Windows 10 / 11(64 位),处理器支持虚拟化,并已在 BIOS 里开启 Intel VT-x / AMD-V
|
||||
- 支持 Vulkan 的独立显卡(推荐 NVIDIA RTX 系列)
|
||||
- 内存建议 16 GB 以上
|
||||
- 可用磁盘空间建议 150 GB 以上,至少 60 GB(一个安装包约 20 GB,虚拟磁盘会随使用增长);最好不要放在系统盘或外置盘
|
||||
|
||||
### 安装
|
||||
|
||||
前往 [Releases](https://github.com/Nwflower/Reims-Go/releases) 下载单文件 `reims-go.exe`,双击即可运行。
|
||||
|
||||
<details>
|
||||
<summary>从源码构建</summary>
|
||||
|
||||
需预先安装 [Go](https://go.dev/dl/)、[Node.js](https://nodejs.org)、[pnpm](https://pnpm.io) 与 [Wails](https://wails.io/docs/gettingstarted/installation):
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/Nwflower/Reims-Go
|
||||
cd Reims-Go
|
||||
wails build
|
||||
```
|
||||
|
||||
产物位于 `build\bin\reims-go.exe`。
|
||||
|
||||
</details>
|
||||
|
||||
### 上手步骤
|
||||
|
||||
1. **初始化** — 首次打开时按引导选好数据目录,完成电脑检查(虚拟化没开可以一键开启,之后需要重启 Windows),再在线安装运行时。
|
||||
2. **新建虚拟机** — 点侧边栏的 **+**,安装来源选「离线安装包」(也可以先到「安装包」页下载好),再设好 CPU、内存和磁盘。
|
||||
3. **安装 macOS** — 启动虚拟机,按页面上的装机引导操作:在恢复终端里点键盘图标,装机命令会自动键入,抹盘和安装随即开始;看到「设置助理」后点「退出恢复模式」。
|
||||
4. **安装 Guest Tools** — 进入 macOS 桌面后,在虚拟机页 Guest Tools 一行点「安装…」,再到 macOS 终端里运行页面给出的命令。装好后剪贴板、共享文件夹和中文输入就能用了。
|
||||
5. **日常管理** — 设置、恢复点和 SSH 都在虚拟机页上;「更多」菜单里还有发送文本、进入恢复模式、派生副本、导出排障日志等操作。
|
||||
|
||||
### 命令行
|
||||
|
||||
命令行就在同一个 `reims-go.exe` 里:不带参数会打开窗口,带上子命令就在终端里执行。
|
||||
|
||||
```powershell
|
||||
reims-go doctor | Out-Host # 检查电脑环境
|
||||
reims-go runtime fetch | 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 vm stop macos-tahoe | Out-Host # 关闭虚拟机
|
||||
```
|
||||
|
||||
在 PowerShell 或 cmd 里直接输入命令时,要加上 `| Out-Host`,终端才会等命令执行完再返回。运行 `reims-go help` 可以查看全部子命令,加 `--lang en-US` 会改成英文输出。
|
||||
|
||||
<br />
|
||||
|
||||
## 界面
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/host-dark.webp" />
|
||||
<img src="./.github/readme/host-light.webp" alt="内核页" />
|
||||
</picture>
|
||||
<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="虚拟机页" />
|
||||
</picture>
|
||||
<p align="center"><sub>虚拟机</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/settings-dark.webp" />
|
||||
<img src="./.github/readme/settings-light.webp" alt="虚拟机设置" />
|
||||
</picture>
|
||||
<p align="center"><sub>虚拟机设置</sub></p>
|
||||
</td>
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/wizard-dark.webp" />
|
||||
<img src="./.github/readme/wizard-light.webp" alt="新建虚拟机向导" />
|
||||
</picture>
|
||||
<p align="center"><sub>新建虚拟机</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<br />
|
||||
|
||||
## 许可与声明
|
||||
|
||||
- **开源协议**: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. 注册商标。
|
||||
|
||||
## 友情链接
|
||||
|
||||
- [LINUX DO](https://linux.do/) — 新的理想型社区
|
||||
|
||||
<br />
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://www.star-history.com/#Nwflower/Reims-Go&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Nwflower/Reims-Go&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Nwflower/Reims-Go&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Nwflower/Reims-Go&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
@@ -1,612 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
type PendingChange struct {
|
||||
Field string `json:"field"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
}
|
||||
|
||||
type AppState struct {
|
||||
Config *config.Config `json:"config"`
|
||||
Host host.Report `json:"host"`
|
||||
Runtimes []rt.Installed `json:"runtimes"`
|
||||
ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"`
|
||||
VMs []reims.VMListItem `json:"vms"`
|
||||
Transitions map[string]string `json:"transitions"`
|
||||
PendingChanges map[string][]PendingChange `json:"pending_changes"`
|
||||
}
|
||||
|
||||
type rebootWatcherEntry struct {
|
||||
id uint64
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type App struct {
|
||||
ctx context.Context
|
||||
mu sync.Mutex
|
||||
cfg *config.Config
|
||||
transitions map[string]string
|
||||
pendingChanges map[string][]PendingChange
|
||||
rebootWatchers map[string]rebootWatcherEntry
|
||||
nextWatcherID uint64
|
||||
stopPoll context.CancelFunc
|
||||
}
|
||||
|
||||
func NewApp() *App {
|
||||
cfg, err := config.Load("")
|
||||
if err != nil {
|
||||
cfg = config.Default()
|
||||
}
|
||||
return &App{
|
||||
cfg: cfg,
|
||||
transitions: make(map[string]string),
|
||||
pendingChanges: make(map[string][]PendingChange),
|
||||
rebootWatchers: make(map[string]rebootWatcherEntry),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) startup(ctx context.Context) {
|
||||
a.ctx = ctx
|
||||
pollCtx, cancel := context.WithCancel(ctx)
|
||||
a.stopPoll = cancel
|
||||
go a.pollVMs(pollCtx)
|
||||
}
|
||||
|
||||
func (a *App) shutdown(ctx context.Context) {
|
||||
if a.stopPoll != nil {
|
||||
a.stopPoll()
|
||||
}
|
||||
a.mu.Lock()
|
||||
for name, entry := range a.rebootWatchers {
|
||||
entry.cancel()
|
||||
delete(a.rebootWatchers, name)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *App) pollVMs(ctx context.Context) {
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
// Cache static hybrid P-core mask once instead of querying host every tick.
|
||||
a.mu.Lock()
|
||||
initRoot := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
cachedHost := host.Inspect(initRoot)
|
||||
var lastSig string
|
||||
pinnedPIDs := make(map[int]bool)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
vms, err := a.listVMsInternal(ctx)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
a.mu.Lock()
|
||||
var b strings.Builder
|
||||
for _, vm := range vms {
|
||||
if tr, ok := a.transitions[vm.Name]; ok {
|
||||
if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") {
|
||||
delete(a.transitions, vm.Name)
|
||||
if vm.State == "stopped" {
|
||||
delete(a.pendingChanges, vm.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Auto-pin P-cores once per running QEMU PID.
|
||||
if a.cfg.AutoPinPCores && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
|
||||
if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 {
|
||||
if err := host.PinProcessToPCores(uint32(*vm.PID), cachedHost.PCoreMask); err == nil {
|
||||
pinnedPIDs[*vm.PID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&b, "%s:%s:%s;", vm.Name, vm.State, a.transitions[vm.Name])
|
||||
}
|
||||
sig := b.String()
|
||||
a.mu.Unlock()
|
||||
if sig != lastSig {
|
||||
lastSig = sig
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) client() (*reims.Client, error) {
|
||||
a.mu.Lock()
|
||||
cfg := a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
|
||||
}
|
||||
return reims.NewClient(cfg, *active), nil
|
||||
}
|
||||
|
||||
func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.List(ctx)
|
||||
}
|
||||
|
||||
func (a *App) emitLog(source, line string) {
|
||||
if a.ctx == nil {
|
||||
return
|
||||
}
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:log", map[string]string{
|
||||
"ts": time.Now().Format("15:04:05"),
|
||||
"source": source,
|
||||
"line": line,
|
||||
})
|
||||
}
|
||||
|
||||
type logWriter struct {
|
||||
emit func(string)
|
||||
buf strings.Builder
|
||||
}
|
||||
|
||||
func (w *logWriter) Write(p []byte) (int, error) {
|
||||
sc := bufio.NewScanner(strings.NewReader(string(p)))
|
||||
for sc.Scan() {
|
||||
line := strings.TrimSpace(sc.Text())
|
||||
if line != "" {
|
||||
w.emit(line)
|
||||
}
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (a *App) GetState() AppState {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
trCopy := make(map[string]string, len(a.transitions))
|
||||
for k, v := range a.transitions {
|
||||
trCopy[k] = v
|
||||
}
|
||||
pcCopy := make(map[string][]PendingChange, len(a.pendingChanges))
|
||||
for k, v := range a.pendingChanges {
|
||||
pcCopy[k] = append([]PendingChange(nil), v...)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
runtimes, _ := rt.List(&cfgCopy)
|
||||
active, _ := rt.ResolveActive(&cfgCopy)
|
||||
vms, _ := a.listVMsInternal(context.Background())
|
||||
|
||||
return AppState{
|
||||
Config: &cfgCopy,
|
||||
Host: rep,
|
||||
Runtimes: runtimes,
|
||||
ActiveRuntime: active,
|
||||
VMs: vms,
|
||||
Transitions: trCopy,
|
||||
PendingChanges: pcCopy,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
return c.Show(context.Background(), name)
|
||||
}
|
||||
|
||||
func (a *App) SetLocale(raw string) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.cfg.Locale = i18n.Normalize(raw)
|
||||
return config.Save("", a.cfg)
|
||||
}
|
||||
|
||||
func (a *App) SetAutoPinPCores(enabled bool) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.cfg.AutoPinPCores = enabled
|
||||
return config.Save("", a.cfg)
|
||||
}
|
||||
|
||||
func (a *App) SetDataRoot(dir string) error {
|
||||
dir = strings.TrimSpace(dir)
|
||||
if dir == "" {
|
||||
return fmt.Errorf("data root cannot be empty")
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.cfg.DataRoot = dir
|
||||
err := a.cfg.EnsureDirs()
|
||||
if err == nil {
|
||||
err = config.Save("", a.cfg)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) PickDirectory(title string) (string, error) {
|
||||
return wailsRuntime.OpenDirectoryDialog(a.ctx, wailsRuntime.OpenDialogOptions{
|
||||
Title: title,
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) PickFile(title, pattern string) (string, error) {
|
||||
opts := wailsRuntime.OpenDialogOptions{Title: title}
|
||||
if pattern != "" {
|
||||
opts.Filters = []wailsRuntime.FileFilter{{DisplayName: pattern, Pattern: pattern}}
|
||||
}
|
||||
return wailsRuntime.OpenFileDialog(a.ctx, opts)
|
||||
}
|
||||
|
||||
func (a *App) EnableWHPX() error {
|
||||
a.emitLog("host", "Requesting Windows UAC to enable HypervisorPlatform...")
|
||||
return host.EnableWHPXElevated()
|
||||
}
|
||||
|
||||
func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
|
||||
a.mu.Lock()
|
||||
cfg := a.cfg
|
||||
a.mu.Unlock()
|
||||
a.emitLog("runtime", "Installing portable runtime: "+archivePath)
|
||||
inst, err := rt.InstallFromArchive(cfg, archivePath)
|
||||
if err != nil {
|
||||
a.emitLog("runtime", "Install failed: "+err.Error())
|
||||
return nil, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.cfg.ActiveRuntime = inst.Commit
|
||||
_ = config.Save("", a.cfg)
|
||||
a.mu.Unlock()
|
||||
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed & activated -> %s", inst.Commit, inst.Dir))
|
||||
return inst, nil
|
||||
}
|
||||
|
||||
func (a *App) UseRuntime(commit string) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.cfg.ActiveRuntime = commit
|
||||
return config.Save("", a.cfg)
|
||||
}
|
||||
|
||||
func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
return reims.ValidateCreate(opts, host.Inspect(root))
|
||||
}
|
||||
|
||||
func (a *App) PreviewCreate(opts reims.CreateOpts) (string, error) {
|
||||
return reims.PreviewCreateCommand(opts)
|
||||
}
|
||||
|
||||
func (a *App) CreateVM(opts reims.CreateOpts) error {
|
||||
if issues := a.ValidateCreate(opts); len(issues) > 0 {
|
||||
return fmt.Errorf("%s", issues[0].Message)
|
||||
}
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
startAfterCreate := opts.Start
|
||||
if startAfterCreate && a.needsColdRebootWorkaround() {
|
||||
// Defer starting so StartVM can inject Win10 -no-reboot + QMP watcher first.
|
||||
opts.Start = false
|
||||
}
|
||||
w, finishTask := a.ctlTaskWriter("vm-create", opts.Name)
|
||||
a.emitLog(opts.Name, "Creating VM "+opts.Name+"...")
|
||||
err = c.Create(context.Background(), opts, w, w)
|
||||
finishTask(err)
|
||||
if err != nil {
|
||||
a.emitLog(opts.Name, "Create error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.emitLog(opts.Name, "VM "+opts.Name+" ready.")
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
if startAfterCreate && !opts.Start {
|
||||
return a.StartVM(opts.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
|
||||
cur, err := a.GetVMDetail(opts.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
return reims.ValidateSet(opts, cur, host.Inspect(root)), nil
|
||||
}
|
||||
|
||||
func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
|
||||
cur, err := a.GetVMDetail(opts.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
if issues := reims.ValidateSet(opts, cur, host.Inspect(root)); len(issues) > 0 {
|
||||
return fmt.Errorf("%s", issues[0].Message)
|
||||
}
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(opts.Name, line) }}
|
||||
if err := c.Set(context.Background(), opts, w, w); err != nil {
|
||||
a.emitLog(opts.Name, "Set error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
if cur.State == "running" {
|
||||
var diffs []PendingChange
|
||||
if opts.CPUs > 0 && opts.CPUs != cur.CPUs {
|
||||
diffs = append(diffs, PendingChange{Field: "cpus", From: fmt.Sprintf("%d", cur.CPUs), To: fmt.Sprintf("%d", opts.CPUs)})
|
||||
}
|
||||
if opts.Memory != "" && !strings.EqualFold(opts.Memory, cur.Memory) {
|
||||
diffs = append(diffs, PendingChange{Field: "memory", From: cur.Memory, To: opts.Memory})
|
||||
}
|
||||
if opts.Resolution != "" && opts.Resolution != cur.Resolution {
|
||||
diffs = append(diffs, PendingChange{Field: "resolution", From: cur.Resolution, To: opts.Resolution})
|
||||
}
|
||||
if opts.GPU != "" && opts.GPU != cur.GPU {
|
||||
diffs = append(diffs, PendingChange{Field: "gpu", From: cur.GPU, To: opts.GPU})
|
||||
}
|
||||
if len(diffs) > 0 {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[opts.Name] = append(a.pendingChanges[opts.Name], diffs...)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
a.emitLog(opts.Name, "Updated VM settings for "+opts.Name)
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) needsColdRebootWorkaround() bool {
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
return host.Inspect(root).NeedsColdRebootWorkaround
|
||||
}
|
||||
|
||||
func (a *App) cancelRebootWatcher(name string) {
|
||||
a.mu.Lock()
|
||||
if entry, ok := a.rebootWatchers[name]; ok {
|
||||
entry.cancel()
|
||||
delete(a.rebootWatchers, name)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
|
||||
a.cancelRebootWatcher(name)
|
||||
baseCtx := a.ctx
|
||||
if baseCtx == nil {
|
||||
baseCtx = context.Background()
|
||||
}
|
||||
watchCtx, cancel := context.WithCancel(baseCtx)
|
||||
a.mu.Lock()
|
||||
a.nextWatcherID++
|
||||
myID := a.nextWatcherID
|
||||
a.rebootWatchers[name] = rebootWatcherEntry{id: myID, cancel: cancel}
|
||||
a.mu.Unlock()
|
||||
|
||||
go func() {
|
||||
defer func() {
|
||||
cancel()
|
||||
a.mu.Lock()
|
||||
if cur, ok := a.rebootWatchers[name]; ok && cur.id == myID {
|
||||
delete(a.rebootWatchers, name)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
}()
|
||||
|
||||
guestReset, err := qmp.WatchForGuestReset(watchCtx, qmpAddr)
|
||||
if err != nil || !guestReset {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
tr := a.transitions[name]
|
||||
a.mu.Unlock()
|
||||
if tr == "stopping" {
|
||||
return
|
||||
}
|
||||
|
||||
a.emitLog(name, "Win10 WHPX cold-reboot: guest requested reboot, restarting in a fresh Hyper-V partition...")
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
a.emitLog(name, "Win10 WHPX cold-reboot aborted: "+err.Error())
|
||||
return
|
||||
}
|
||||
// Wait briefly for QEMU to finish exiting cleanly under -no-reboot.
|
||||
deadline := time.Now().Add(12 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if watchCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
vms, err := c.List(watchCtx)
|
||||
if err == nil {
|
||||
stopped := false
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name && vm.State == "stopped" {
|
||||
stopped = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if stopped {
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
}
|
||||
if watchCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if err := a.StartVM(name); err != nil {
|
||||
a.emitLog(name, "Win10 WHPX cold-reboot start failed: "+err.Error())
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (a *App) StartVM(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
|
||||
var qmpAddr string
|
||||
if a.needsColdRebootWorkaround() {
|
||||
if port, perr := qmp.AllocateFreePort(); perr == nil {
|
||||
cur, serr := c.Show(context.Background(), name)
|
||||
existing := ""
|
||||
if serr == nil {
|
||||
existing = cur.ExtraArgs
|
||||
}
|
||||
merged := qmp.MergeWin10RebootArgs(existing, port)
|
||||
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
|
||||
a.emitLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error())
|
||||
} else {
|
||||
qmpAddr = fmt.Sprintf("127.0.0.1:%d", port)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
a.transitions[name] = "starting"
|
||||
delete(a.pendingChanges, name)
|
||||
a.mu.Unlock()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
|
||||
a.emitLog(name, "Starting "+name+"...")
|
||||
if err := c.Start(context.Background(), name, w, w); err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, name)
|
||||
a.mu.Unlock()
|
||||
a.emitLog(name, "Start error: "+err.Error())
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return err
|
||||
}
|
||||
if qmpAddr != "" {
|
||||
a.watchWin10ColdReboot(name, qmpAddr)
|
||||
}
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) StopVM(name string, force bool) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
a.mu.Lock()
|
||||
a.transitions[name] = "stopping"
|
||||
a.mu.Unlock()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
|
||||
a.emitLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force))
|
||||
if force {
|
||||
err = c.StopForce(context.Background(), name, w, w)
|
||||
} else {
|
||||
err = c.Stop(context.Background(), name, w, w)
|
||||
}
|
||||
if err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, name)
|
||||
a.mu.Unlock()
|
||||
a.emitLog(name, "Stop error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, name)
|
||||
a.mu.Unlock()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) RestartVM(name string) error {
|
||||
if err := a.StopVM(name, false); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.StartVM(name)
|
||||
}
|
||||
|
||||
func (a *App) EjectInstaller(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
|
||||
a.emitLog(name, "Ejecting installer from "+name+"...")
|
||||
if err := c.Eject(context.Background(), name, w, w); err != nil {
|
||||
a.emitLog(name, "Eject error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.emitLog(name, "Installer ejected.")
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) DeleteVM(name string, keepFiles bool) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
a.emitLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
|
||||
if err := c.Delete(context.Background(), name, keepFiles, io.Discard, io.Discard); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, name)
|
||||
delete(a.transitions, name)
|
||||
a.mu.Unlock()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
// OpenVMFolder shows the VM's directory in File Explorer.
|
||||
func (a *App) OpenVMFolder(name string) error {
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Directory == "" {
|
||||
return fmt.Errorf("VM %s has no directory", name)
|
||||
}
|
||||
return host.OpenFolder(d.Directory)
|
||||
}
|
||||
|
||||
func (a *App) ReadVMLogs(name string, serial bool) (string, error) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return c.ReadLogs(context.Background(), name, serial)
|
||||
}
|
||||
|
After Width: | Height: | Size: 35 KiB |
@@ -0,0 +1,68 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#3b8cff"/>
|
||||
<stop offset="0.55" stop-color="#2f5bea"/>
|
||||
<stop offset="1" stop-color="#3b1fb8"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="gloss" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#ffffff" stop-opacity="0.28"/>
|
||||
<stop offset="0.45" stop-color="#ffffff" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#6d5dfc"/>
|
||||
<stop offset="0.45" stop-color="#ff7a9a"/>
|
||||
<stop offset="0.8" stop-color="#ffb86b"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="lake" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#2f6bff"/>
|
||||
<stop offset="1" stop-color="#1a2a8f"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="bolt" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#ffe14d"/>
|
||||
<stop offset="1" stop-color="#ff9f0a"/>
|
||||
</linearGradient>
|
||||
<clipPath id="screen">
|
||||
<rect x="252" y="372" width="520" height="318" rx="26"/>
|
||||
</clipPath>
|
||||
<filter id="shadow" x="-20%" y="-20%" width="140%" height="150%">
|
||||
<feDropShadow dx="0" dy="22" stdDeviation="26" flood-color="#0b0d3a" flood-opacity="0.35"/>
|
||||
</filter>
|
||||
<filter id="iconShadow" x="-10%" y="-10%" width="120%" height="125%">
|
||||
<feDropShadow dx="0" dy="14" stdDeviation="16" flood-color="#000000" flood-opacity="0.22"/>
|
||||
</filter>
|
||||
</defs>
|
||||
|
||||
<!-- squircle base -->
|
||||
<g filter="url(#iconShadow)">
|
||||
<rect x="80" y="80" width="864" height="864" rx="200" fill="url(#bg)"/>
|
||||
<rect x="80" y="80" width="864" height="864" rx="200" fill="url(#gloss)"/>
|
||||
</g>
|
||||
|
||||
<!-- VM window -->
|
||||
<g filter="url(#shadow)">
|
||||
<rect x="220" y="268" width="584" height="454" rx="52" fill="#f7f8fc"/>
|
||||
</g>
|
||||
<circle cx="280" cy="322" r="17" fill="#ff5f57"/>
|
||||
<circle cx="332" cy="322" r="17" fill="#febc2e"/>
|
||||
<circle cx="384" cy="322" r="17" fill="#28c840"/>
|
||||
|
||||
<!-- guest display: a lake at dusk -->
|
||||
<g clip-path="url(#screen)">
|
||||
<rect x="252" y="372" width="520" height="318" fill="url(#sky)"/>
|
||||
<circle cx="600" cy="540" r="44" fill="#fff3d6" opacity="0.9"/>
|
||||
<path d="M252 560 L340 470 L400 520 L480 430 L560 505 L620 465 L700 530 L772 480 L772 600 L252 600 Z" fill="#2b2d7a"/>
|
||||
<path d="M252 585 L330 530 L420 575 L500 520 L590 570 L672 535 L772 580 L772 610 L252 610 Z" fill="#1c1f5e"/>
|
||||
<rect x="252" y="598" width="520" height="92" fill="url(#lake)"/>
|
||||
<rect x="560" y="616" width="80" height="6" rx="3" fill="#fff3d6" opacity="0.7"/>
|
||||
<rect x="574" y="636" width="52" height="6" rx="3" fill="#fff3d6" opacity="0.5"/>
|
||||
<rect x="586" y="656" width="28" height="6" rx="3" fill="#fff3d6" opacity="0.35"/>
|
||||
</g>
|
||||
|
||||
<!-- GPU acceleration badge -->
|
||||
<g filter="url(#shadow)">
|
||||
<circle cx="776" cy="724" r="128" fill="#16182e"/>
|
||||
</g>
|
||||
<circle cx="776" cy="724" r="128" fill="none" stroke="#ffffff" stroke-opacity="0.92" stroke-width="16"/>
|
||||
<path d="M800 628 L708 744 L768 744 L748 822 L846 700 L784 700 Z" fill="url(#bolt)" stroke="#ffcf3a" stroke-width="6" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.2 KiB |
|
Before Width: | Height: | Size: 130 KiB After Width: | Height: | Size: 272 KiB |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 62 KiB |
@@ -0,0 +1,6 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
// attachConsole is only needed for Windows GUI-subsystem builds.
|
||||
func attachConsole() {}
|
||||
@@ -0,0 +1,58 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
var (
|
||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procAttachConsole = kernel32.NewProc("AttachConsole")
|
||||
)
|
||||
|
||||
const attachParentProcess = ^uintptr(0) // ATTACH_PARENT_PROCESS, (DWORD)-1
|
||||
|
||||
// attachConsole gives command-line mode somewhere to write. reims-go.exe is
|
||||
// a GUI-subsystem program, so Windows starts it without a console. Handles
|
||||
// the caller passed in (a pipe, a file: how agents and scripts run it) are
|
||||
// kept; only missing ones are pointed at the console of the terminal that
|
||||
// launched it.
|
||||
func attachConsole() {
|
||||
out, errOut, in := usable(os.Stdout), usable(os.Stderr), usable(os.Stdin)
|
||||
if out && errOut && in {
|
||||
return
|
||||
}
|
||||
if r, _, _ := procAttachConsole.Call(attachParentProcess); r == 0 {
|
||||
return // started from Explorer or a shortcut: nowhere to write
|
||||
}
|
||||
if !out || !errOut {
|
||||
if f, err := os.OpenFile("CONOUT$", os.O_RDWR, 0); err == nil {
|
||||
if !out {
|
||||
os.Stdout = f
|
||||
}
|
||||
if !errOut {
|
||||
os.Stderr = f
|
||||
}
|
||||
}
|
||||
}
|
||||
if !in {
|
||||
if f, err := os.OpenFile("CONIN$", os.O_RDWR, 0); err == nil {
|
||||
os.Stdin = f
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// usable reports whether f wraps a real handle the caller passed in.
|
||||
func usable(f *os.File) bool {
|
||||
if f == nil {
|
||||
return false
|
||||
}
|
||||
h := syscall.Handle(f.Fd())
|
||||
if h == 0 || h == syscall.InvalidHandle {
|
||||
return false
|
||||
}
|
||||
t, err := syscall.GetFileType(h)
|
||||
return err == nil && t != syscall.FILE_TYPE_UNKNOWN
|
||||
}
|
||||
@@ -6,11 +6,10 @@
|
||||
|
||||
1. **零编译上手**:用户拿到单个 `reims-go.exe`(或便携压缩包),首次启动向导自动检测环境 → 下载/导入便携运行时 → 创建并启动 macOS Tahoe。
|
||||
2. **不重复造 `reims-ctl` 的轮子**:`reims-go` 通过受控子进程包装 `reims-ctl`(及 `qemu-img`),避免像手写 PowerShell 启动脚本那样在每次上游变更参数时失效。
|
||||
3. **GUI 与 CLI 同源**:所有核心能力落在 `internal/` Go 包中;既可双击启动 Wails 桌面界面,也可通过 `reims-go <subcommand>` 在终端或 CI 中自动化调用。
|
||||
3. **GUI 与 CLI 同源、同一个 exe**:所有核心能力落在 `internal/` Go 包中。只发布一个 `reims-go.exe`:双击(无参数)打开 Wails 桌面界面,带子命令(`reims-go <subcommand>`)走命令行模式,供终端、脚本、CI 和 Agent 调用。2026-11-28 起不再单独发布 `reims-go-cli.exe`。
|
||||
4. **C 盘零污染**:所有运行时、下载缓存、VM 磁盘与快照严格留在用户选定的 `<DataRoot>` 下。
|
||||
5. **Day-1 中英双语(`zh-CN` / `en-US`)**:前端界面、装机引导文案(默认贴合简体中文 macOS 恢复与安装界面术语,如「磁盘工具 → 抹掉为 APFS → 重新安装 macOS」)与 CLI 输出从第一天即内置双语字典,自动跟随系统语言并支持在界面顶部实时切换(持久化到 `reims-go.json`)。
|
||||
6. **跨平台开发友好**:虽然宿主机运行目标优先面向 Windows x86-64(WHPX),但所有 Windows 原生 API(`WinHvPlatform.dll`、注册表 Vulkan ICD、`GetLogicalProcessorInformationEx`、进程亲和性)严格隔离在 `*_windows.go` 构建标签中,提供 `*_other.go` 桩实现,确保在中文 macOS 开发环境上也能直接进行前端开发、`go build` 与 `go test ./...`。
|
||||
7. **面向未来扩展**:驱动层抽象出 `Engine` 接口,当前实现 `reims`(macOS x86-64 WHPX),预留扩展位以对接后续 `vphone`(iOS)或远程宿主模式。
|
||||
|
||||
## 2. 总体分层架构
|
||||
|
||||
@@ -18,15 +17,15 @@
|
||||
flowchart TB
|
||||
subgraph UI["交互层"]
|
||||
GUI["Wails 桌面界面\n(React / Vite + WebView2)"]
|
||||
CLI["CLI 子命令\n(reims-go doctor/runtime/vm/clone/exec)"]
|
||||
CLI["命令行模式(同一个 exe)\n(reims-go doctor/runtime/installer/vm)"]
|
||||
end
|
||||
|
||||
subgraph Core["Go 核心服务层 (internal/)"]
|
||||
Preflight["host/ 环境体检与调优\n(WHPX检测与一键提权、提交内存预检、\nVulkan ICD扫描、P/E核亲和性绑核)"]
|
||||
RuntimeMgr["runtime/ 便携运行时管理\n(Release拉取、SHA256校验、\n原子解压、版本切换与回滚)"]
|
||||
InstallerMgr["installer/ 离线安装包下载管理\n(reims-util --json 宿主机直连下载、\n断点续传、版本目录与缓存清理)"]
|
||||
VMMgr["vm/ 生命周期与工作流\n(向导创建、日志流、eject、\nGolden Image、CoW 派生与快照)"]
|
||||
Control["control/ 带外控制\n(独立QMP客户端、SSH执行、\n截屏与状态监控)"]
|
||||
VMMgr["driver/reims 与 App 编排\n(创建、启停、eject、日志流、\nCoW 派生、磁盘扩容与回收)"]
|
||||
Control["qmp/ guesttools/ opencore/\n(QMP 键入与截屏、冷重启监视、\n剪贴板与共享目录、客体语言)"]
|
||||
end
|
||||
|
||||
subgraph External["外部运行时(独立子进程,全部在 DataRoot 下)"]
|
||||
@@ -60,18 +59,17 @@ flowchart TB
|
||||
|
||||
### 3.2 `internal/runtime` — 便携运行时管理
|
||||
- 维护 `<DataRoot>\runtimes\` 下的多版本便携运行时包:
|
||||
- **可选 CDN / 镜像端点 + 环境自动探测**:支持配置多下载端点(`GitHub 官方`、可选国内加速镜像或用户自定义镜像前缀)及「导入本地 `.tar.zst` 包」离线安装;拉取前对已启用端点并行发轻量 `HEAD` 探测(2 秒超时),按延迟自动择优,也允许用户在设置中手动锁定端点;
|
||||
- **来源**:本仓库的 GitHub Release(主源,tag `runtime-<commit>`,预发布为 `alpha`,正式发布为 `stable`)与官方镜像仓 [GitCode `Nwflower/Reims-Go`](https://gitcode.com/Nwflower/Reims-Go)(支持 `auto` 自动回退、`github`、`gitcode` 三种模式;自动读取环境变量与 Windows 系统代理;GitHub 限流时自动降级网页解析),均支持 HTTP `Range` 断点续传并强制对照 `SHA256SUMS.txt` 校验;也可以导入本地 `.tar.zst` 包;
|
||||
- 校验 `manifest.json` 与 SHA256 后解压至 `<commit>.tmp` 再原子重命名,失败不破坏现有版本;
|
||||
- 统一构造子进程环境(`XDG_*`、`REIMS_CTL_QEMU`、`PATH`),彻底消除对用户全局环境变量与 C 盘的依赖;
|
||||
- **可承接上游未来官方发布**:运行时源采用清单化拉取协议,若上游 `steelbrain/reims-vgpu` 日后提供官方 Windows 预编译包,可直接切换源承接。
|
||||
|
||||
### 3.3 `internal/installer` — GUI 离线安装包下载管理器(2026-11-28 实测沉淀)
|
||||
- **背景与痛点**:实测通过在线恢复镜像(`--macos tahoe`)在 Guest Recovery 内经 QEMU 用户态 NAT(`slirp`)拉取 ~17 GB 系统包时,受限于 Apple CDN 频繁 `Peer disconnected` 与 `OSISDownloadOperation` 抗断流能力弱,极易在耗时数十分钟后接近完成时失败重来。
|
||||
- **方案设计(基于 `reims-util 0.1.0` 一手 CLI 能力)**:
|
||||
1. **动态版本列表**:调用 `reims-util.exe offline-installer list --json` 获取 Apple 目录可用的 macOS Tahoe 精确版本(如 `26.7.3`),供 GUI 下拉选择(同时保留在线恢复模式作为备选)。
|
||||
2. **下载路由可选 + 环境自动探测(合规直连 Apple 官方源)**:macOS 系统包一律从 Apple 官方软件更新目录拉取并校验 chunklist 哈希(不接入第三方非官方镜像)。支持在设置与下载页配置路由模式:`自动探测(推荐)` / `直连 Apple CDN(绕过系统代理,清空代理环境变量并注入 NO_PROXY=*)` / `跟随系统代理` / `自定义 HTTP/SOCKS5 代理`。自动模式下在下载前花 1–2 秒并行探测直连与系统代理访问 Apple 目录的连通性与首字节延迟,国内环境自动命中 Apple 国内边缘节点(2026-11-28 实测直连 `220.194.76.155` 稳定 11.2 MiB/s、零断流),直连受限时自动回退系统代理。
|
||||
2. **只从 Apple 官方源下载**:macOS 系统包由 `reims-util` 从 Apple 软件更新目录拉取,并校验 chunklist,不接第三方镜像。`reims-go` 不做路由选择,`reims-util` 使用进程环境里的代理变量(2026-11-28 实测,国内直连 Apple 边缘节点稳定在 11.2 MiB/s)。
|
||||
3. **宿主机直连下载 + 结构化进度条**:调用 `reims-util.exe offline-installer <version> -o <DataRoot>\data\reims-ctl\installers --json`(或在建机时走 `reims-ctl create --macos <version> --offline --network false` 共享同一缓存目录)。`reims-util --json` 原生按行输出 JSON 进度事件,Go 后端实时解析并通过 Wails `EventsEmit` 推送进度百分比、已下载字节、速率与断流重试状态,无需脆弱正则匹配。
|
||||
4. **暂停 / 断点续传与空间预警**:`reims-util` 原生支持中断后重跑同命令自动断点续传;GUI 提供「暂停/取消」与「继续下载」按钮,并在目标盘剩余空间不足 40 GB 时前置预警。
|
||||
4. **暂停 / 断点续传与空间预警**:`reims-util` 原生支持中断后重跑同命令自动断点续传;GUI 提供「暂停/取消」与「继续下载」按钮。`reims-util` 一开始就会创建与完整镜像同样大小的 `.part` 文件,所以下载前先检查剩余空间是否够安装包大小的 1.1 倍。
|
||||
5. **缓存复用与可视化清理**:已下载的离线镜像常驻 `<DataRoot>\data\reims-ctl\installers\`,GUI 包装 `reims-ctl downloads` 与 `reims-ctl downloads delete <NAME>` 展示体积并支持一键清理;后续新建 VM 直接通过 `--installer <path>` 复用本地镜像,零重复下载。
|
||||
6. **离线装机 3 步引导卡**:使用离线包创建 VM 时默认开启 `--network false`(遵从 `reims-ctl create --help` 建议,阻止安装器联网拉更新),并在 GUI 突出提示:① 磁盘工具抹掉最大 `QEMU HARDDISK Media` 为 APFS → ② 打开终端执行 `sh /Volumes/Installer/install-macos.sh` → ③ 装完点击「弹出安装盘并恢复网络」。
|
||||
|
||||
@@ -79,20 +77,32 @@ flowchart TB
|
||||
- 包装 `list --json`、`show`、`create`、`start`、`stop`、`set`、`eject`、`delete`、`logs`、`command`、`doctor`、`downloads`。
|
||||
- 流式捕获 stdout/stderr 与串口日志,实时推送到 Wails 前端事件总线(`runtime.EventsEmit`),让用户在安装 macOS Tahoe 期间直观看到进度与内核启动日志。
|
||||
- **Win10 自动冷重启补偿(2026-11-28 实测沉淀)**:Win10 19045 缺少 `WHvResetPartition`,Guest 内部热重启时 QEMU 会停在 `WHPX: Unexpected VP exit code 4`。在 Win10 宿主上可通过 `--extra-args "-no-reboot"` 让 QEMU 收到 Guest 重启请求时干净退出,再由 `reims-go` 自动重新 `start` 建立新分区,实现无感重启体验(待实测验证)。
|
||||
- **QMP 不抢上游的 socket**:上游 `reims-ctl` 自己就有 QMP 客户端,走每台 VM 的 `qmp.sock`(Windows 上是 Winsock AF_UNIX,`crates/reims-ctl/src/qmp.rs:1-8`、`vm.rs:1000-1027`)。QEMU 的一个 `-qmp` 同一时间只接受一个客户端,第二个连接会一直等到超时(同上 `qmp.rs` 注释,引自 QEMU `chardev/char-socket.c`)。所以 `reims-go` **不连这个 socket**,否则会卡住 `reims-ctl stop` 等命令;它通过 `reims-ctl set --extra-args` 另开一个自己的 monitor(`-qmp tcp:127.0.0.1:<port>,server=on,wait=off`)。QEMU 允许多个 `-qmp`,但与上游参数是否冲突仍**待 M3.2 实测**。
|
||||
- **两条 QMP 通道**:上游 `reims-ctl` 给每台 VM 开一个 `qmp.sock`(Windows 上是 Winsock AF_UNIX,`crates/reims-ctl/src/qmp.rs:1-8`、`vm.rs:1000-1027`)。QEMU 的一个 `-qmp` 同一时间只接受一个客户端,第二个连接会一直等到超时(同上 `qmp.rs` 注释,引自 QEMU `chardev/char-socket.c`)。
|
||||
- 键入(`qmp.TypeIntoVM`)和截屏缩略图(`qmp.Screendump`)都是短连接,直接连 `qmp.sock`,并且按 VM 串行(`type_flow.go` 的 `typing`、`thumbnail_flow.go` 的 `thumbLocks`);键入期间不截屏。它们连着的时候,`reims-ctl stop` 要等它们断开,实际延迟**待验证**。
|
||||
- Win10 冷重启监视需要长连接,所以通过 `reims-ctl set --extra-args` 另开一个 AF_UNIX monitor(`qmp.RebootSocketPath`),不占用 `qmp.sock`。不用 TCP,是为了不让客体经 SLIRP 的 `10.0.2.2` 访问到这个 monitor。
|
||||
- **配置写入只用 `set`**:`reims-ctl set` 的修改在**下次启动**时生效(`cli.rs:73`);改图形会在 VM 停止时重建 OpenCore 镜像(`cli.rs:242`)。可改字段见 `cli.rs:551-616`,外壳如何呈现见 [`shell-design.md`](shell-design.md)。
|
||||
|
||||
### 3.5 `internal/vm` 与 `internal/control` — 开发者进阶能力(M3)
|
||||
- **CoW 秒级派生**:使用便携运行时自带的 `qemu-img.exe create -f qcow2 -F qcow2 -b <golden> <overlay>` 生成写时复制派生盘,挂入临时实例,实现秒级拉起与无痕销毁(待验证 `reims-ctl create --disk <overlay> --disk-mode in-place` 对 backing file 的兼容性)。
|
||||
- **带外控制**:通过 QMP 查询运行态、优雅关机(失败再回退终止,避免粗暴 `taskkill` 伤盘)、截屏与键鼠注入;结合 `--ssh-port` 提供命令执行通道。
|
||||
### 3.5 启动编排:`internal/vmstart` 与 GUI 编排层
|
||||
- `internal/vmstart` 是 GUI 和 CLI 共用的启动步骤:提交内存预检、离线辅助盘、恢复模式引导菜单、客体语言重放、WHPX 嵌套虚拟化兼容,以及启动后的 P 核绑定。GUI 的 `StartVM`(`app.go`)调用它;CLI 的 `vm start`(`internal/cli/start.go`)通常把启动交给界面进程,只在指定了 `--data-root` 时自己调用它。
|
||||
- 只有界面进程做的两步:Guest Tools 桥接(`guesttools_flow.go`)和 Win10 冷重启监视(`app.go`)。这两步都需要启动后仍在运行的进程,而命令执行完就退出,所以 `vm start` 会把启动交给界面进程:
|
||||
- 界面已在运行:按 Wails 单实例协议(`options.SingleInstanceLock`,WM_COPYDATA)把 `--start-vm=<名称>` 发给它,不弹窗;
|
||||
- 界面没在运行:以 `--background` 拉起一个只在托盘里运行的界面进程(`StartHidden`)。拉起时与调用方的控制台和句柄分离,Agent 读的管道会随命令结束而关闭;
|
||||
- 两种情况都由界面调用 `StartVM`,再把结果写到 `<DataRoot>\tmp\cli-start-*.json`(只接受这个目录下的这类文件名),命令读到后带退出码返回。
|
||||
- 指定了 `--data-root` 的 `vm start` 仍在命令进程里启动,没有剪贴板和共享目录,Win10 上客体重启后不会自动拉起。
|
||||
- 单实例:同一用户只运行一个界面进程。再次双击会把已有窗口调到前台。`wails dev` 构建用另一个锁名(`internal/cli/instance_id_dev.go`),不会和已安装的 Reims-Go 互相抢。
|
||||
- 命令行模式与 Windows 子系统:`reims-go.exe` 是 GUI 子系统程序。命令行模式会保留调用方传入的句柄(管道、文件),缺失的才用 `AttachConsole` 接回父进程控制台(`console_windows.go`)。所以 Agent、脚本、管道调用都能正常拿到输出和退出码;在交互式 PowerShell / cmd 里,提示符会先返回,要等命令结束需加 `| Out-Host`。
|
||||
- GUI 的其余编排在 `internal/app` 的 `App`(`app.go`)和各个 `*_flow.go` 里:CoW 派生(`clone_flow.go`)、磁盘扩容与回收(`disk_flow.go`)、运行监视与里程碑日志(`vm_monitor.go`)。
|
||||
- **CoW 派生**:先 `qemu-img create -f qcow2 -F qcow2 -b <golden> <overlay>`,再 `reims-ctl create --disk <overlay> --disk-mode in-place`,原盘不改。真机上从派生盘启动**待验证**。
|
||||
- **SSH**:只展示 `reims-ctl` 的 `--ssh-port` 转发端口,没有命令执行通道。
|
||||
|
||||
## 4. 建议代码目录结构
|
||||
## 4. 代码目录结构
|
||||
|
||||
```text
|
||||
reims-go/
|
||||
├── cmd/
|
||||
│ └── reims-go/ # 主入口(无参启动 Wails GUI,带子命令走 CLI 模式)
|
||||
├── main.go # 唯一入口:无参数启动 Wails 界面,带子命令走 internal/cli(附 console_*.go)
|
||||
├── internal/
|
||||
│ ├── app/ # GUI 编排层与 Wails 绑定(App、*_flow.go、tasks.go、vm_monitor.go、window_launch.go)
|
||||
│ ├── cli/ # 命令行模式:子命令、把 vm start 交给界面进程
|
||||
│ ├── config/ # reims-go.json(含 locale: zh-CN|en-US、DataRoot、P-Core 开关)
|
||||
│ ├── i18n/ # Go 端中英双语消息字典与结构化错误码
|
||||
│ ├── host/ # WHPX、提交内存预检、Vulkan ICD、P/E 核拓扑、进程亲和性(*_windows.go + *_other.go)
|
||||
@@ -100,12 +110,19 @@ reims-go/
|
||||
│ ├── installer/ # reims-util --json 离线安装包下载、断点续传、缓存管理
|
||||
│ ├── driver/
|
||||
│ │ └── reims/ # reims-ctl 子进程包装与 JSON/日志解析
|
||||
│ ├── qmp/ # 独立 QMP TCP 客户端
|
||||
│ └── vm/ # VM 编排、CoW 派生、向导状态机
|
||||
│ ├── qmp/ # QMP 客户端:键入、截屏、Win10 冷重启监视
|
||||
│ ├── vmstart/ # GUI 与 CLI 共用的启动前检查、准备与绑核
|
||||
│ ├── guesttools/ # 宿客剪贴板与 WebDAV 共享目录、REIMSTOOLS 辅助盘
|
||||
│ ├── opencore/ # 改写 OpenCore 镜像里的 prev-lang:kbd
|
||||
│ ├── thumb/ # 把截屏缩小成 JPEG
|
||||
│ ├── tray/ # 系统托盘
|
||||
│ └── version/ # 版本号与更新检查
|
||||
├── frontend/ # Wails 前端(轻量 React + Vite + TypeScript + zh-CN/en-US i18n)
|
||||
├── patches/ # 上游临时补丁队列(合入即退役)
|
||||
├── scripts/
|
||||
│ └── pack-runtime.ps1 # 从本地构建打包便携运行时(tar.zst + manifest)
|
||||
│ ├── pack-runtime.ps1 # 从本地构建打包便携运行时(tar.zst + manifest)
|
||||
│ ├── pack-msys2-sources.ps1 # 打包对应的 MSYS2 copyleft 源码
|
||||
│ └── smoke-runtime.ps1 # 生成 alpha → stable 冒烟报告
|
||||
└── docs/
|
||||
```
|
||||
|
||||
|
||||
@@ -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 ./...` 通过。
|
||||
@@ -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,7 +98,21 @@ reims-runtime-<commit>/
|
||||
## 4. 打包与发布流水线(M0 / M4)
|
||||
|
||||
- **本地打包验证(M0)**:编写 `scripts/pack-runtime.ps1`,直接从本机已编译的 `reims-vgpu` 产物生成 `reims-runtime-win-x64-3731afd.tar.zst` 与 `manifest.json`(含 SHA256),验证纯净解压启动。
|
||||
- **自动化 CI(M4)**:在 GitHub Actions `windows-latest` runner 上使用 MSYS2 CLANG64,先打上第 5 节的补丁队列,再执行上游构建脚本,产出 `reims-runtime-win-x64-<commit>.tar.zst`、`SHA256SUMS.txt` 和对应源码包(第 7 节)。CI 产物只进 `candidate` 通道,不直接发给用户(第 6 节)。
|
||||
- **本地打包与发布(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`。客户端下载仍只需要运行时包与校验清单,因此旧客户端也可安装新布局。
|
||||
- **客户端安装**(`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 预发布,五个附件缺一不可。
|
||||
5. 只保留最近 7 个未升级的 alpha 预发布,更早的连同 tag 删除;正式发布不受影响。
|
||||
6. 构建失败、或有补丁已被上游合并时,在本仓库开一个 issue(已有同名的未关闭 issue 就追加评论)。
|
||||
|
||||
CI 产物只进 `alpha` 通道,不直接发给用户(第 6 节)。注意 GitHub 会在仓库 60 天无活动后停用定时 workflow。
|
||||
- **CI 测不到 Win10**:`windows-latest` 是 Windows Server 2022/2025,复现不了第 5 节的 Win10 问题,而且 GitHub 托管 runner 一般不提供 WHPX。CI 只能保证「能构建、`-device help` 列出 `reims-graphics-pci`」,能不能启动 VM 要靠第 6 节的本机冒烟测试。
|
||||
|
||||
## 5. 补丁队列(把上游当内核来优化的方式)
|
||||
@@ -98,33 +121,51 @@ reims-runtime-<commit>/
|
||||
|
||||
| 补丁 | 作用对象 | 解决的问题 | 状态 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `reims-vgpu-win32-unicode-input.patch` | `reims-vgpu` 的 `crates/reims-vgpu-window`(`native/windows.rs`、`native/sdl_thread/ui.rs`) | SDL3 窗口层未开启 TextInput 且只转发 `0x04..=0xE7` 物理扫描码,导致直接投递 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR` 或宿主机 IME 上屏的文字被吞;通过 `SDL_SetWindowsMessageHook` 仅在设置 `REIMS_GO_INPUT_URL`(仅限 `127.0.0.1`)时异步转发非物理按键字符给宿主机文本注入桥 | 2026-11-28 新增补丁,待编入下一版 alpha 运行时冒烟验证后提 PR |
|
||||
| `reims-vgpu-cargo-lock.patch` | 上游 `reims-vgpu`(`3731afd`)的 `Cargo.lock` | 不改代码。cargo 构建时会给 `metal2vulkan`、`metal2vulkan-air`、`metal2vulkan-runtime` 补上 `source = "git+…metal2vulkan?rev=0b0ac58…"`;带上这个补丁,源码包才和实际构建一致 | 不需要上游 PR;上游 `Cargo.lock` 补齐后删除 |
|
||||
| `reims-ctl-win32-random-bytes.patch` | `steelbrain/reims-vgpu` (`3731afd`) 的 `crates/reims-ctl/src/vm.rs` | `random_bytes()`(`vm.rs:849-864`)在打不开 `/dev/urandom` 时退回用「纳秒时间 ^ (pid << 64)」当种子。Windows 上永远走这条退路,于是新 VM 的 MAC 后 3 字节(也就是 OpenCore 的 ROM)只剩约 22 位、可预测的时钟熵,第 4 段永远是 4 的倍数。改成用 std `RandomState` 做哈希(它的密钥来自系统随机源 ProcessPrng),不加依赖,不改 Cargo 文件 | 2026-11-29 新增补丁,`git apply --check` 通过;本机没有 Rust 工具链,尚未编译,待编入下一版 alpha 运行时验证后提 PR |
|
||||
| `qemu-whpx-win10-compat.patch` | `vendor/qemu` 的 `target/i386/whpx/whpx-all.c` | ① `whpx_tsc_deadline_refused()`(`3210-3230`)原实现在真实分区上建、删 vCPU 0,Win10 19045 上随后 `whpx_init_vcpu()` 再次创建 vCPU 0 时必现 `WHvCreateVirtualProcessor` 返回 `E_INVALIDARG`(`hr=80070057`),改为独立临时探测分区;② `whpx_set_registers()`(`534`)直接调用 `WHvResetPartition` 未判空,Win10 19045 的 `WinHvPlatform.dll` 不导出该接口导致重置阶段必现 `0xc0000005 at 0x0` 崩溃(已核对导出表,10 个 supplemental API 中仅此一处漏判空) | 2026-11-28 实测复现并修复,待提交上游 PR(由人操作) |
|
||||
| `qemu-whpx-win10-startup-ipis.patch` | 同上(在前一项之后应用) | Win10 开启内核 irqchip 时转发多核 INIT/SIPI,避免 XNU 从核启动停住 | 已合入补丁队列,客体冷重启待验证,待提交上游 PR |
|
||||
| `qemu-whpx-nested-virt-nonfatal.patch` | 同上(在前两项之后应用) | 部分 Win11 宿主 `WHvSetPartitionProperty(NestedVirtualization)` 返回 `hr=0x80370302`(`WHV_E_UNKNOWN_PROPERTY`)导致 QEMU 在 `whpx-all.c:3479-3483` 直接致命退出,改为非致命警告并清零 `Bank1.NestedVirtSupport`,保留 `kernel-irqchip=on` 内核态 x2APIC 加速 | 2026-11-28 新增补丁,待编入下一版 alpha 运行时并在 Win11 真机冒烟验证后提 PR |
|
||||
| `qemu-win32-coroutine-fiber-commit.patch` | `vendor/qemu` 的 `util/coroutine-windows.c` | 登录 Apple ID 等高并发 VA-API + 磁盘 I/O 场景下,`CreateFiber(1 MiB)` 预先提交整块 1 MiB 协程栈易耗尽 Windows Commit Charge 返回 `NULL`,未判空即调用 `SwitchToFiber(NULL)` 触发 `0xc0000005`(读 `0x0000000000000010`)崩溃;改用 `CreateFiberEx(64 KiB, 1 MiB, 0, ...)` 并将 `NULL` 与 `IsThreadAFiber()` 纳入显式处理 | 2026-11-28 符号化定位并新增补丁,待编入下一版 alpha 运行时实测验证后提 PR |
|
||||
|
||||
### 5.1 本机实测排障与待验证优化沉淀(2026-11-28,Win10 19045)
|
||||
1. **Win10 下默认关闭 `kernel-irqchip` 导致高 CPU 开销(待验证优化)**:
|
||||
- Win10 19045 因缺少 `WHvCapabilityCodeProcessorPerfmonFeatures`(`hr=80370300`)进入 `whpx_is_legacy_os()` 分支(`whpx-all.c:3347-3397`),默认关闭 `kernel-irqchip`,导致上游专为 WHPX 实现的无锁 MSI-X(`whpx_send_msi_direct`)和无 BQL 运行(`whpx_vcpu_pre_run`,见上游 `docs/qemu.md:135-136`)全部失效;实测在 Guest 内以 6.7–10 MB/s 写入磁盘时 QEMU 消耗达 1.7–2.7 个满核 CPU 与 ~15,530 ops/s。
|
||||
- 本机 `WinHvPlatform.dll` 导出表已确认包含 `WHvSetVirtualProcessorInterruptControllerState2` 与 `WHvRequestInterrupt`,后续在 M3.1 实测强制 `-accel whpx,kernel-irqchip=on` 的稳定性;若稳定则优先向上游提 PR。
|
||||
- 最小 WHP 实验发现,同一从核首次启动并进入 `HLT` 后,第二次由客体发送的 SIPI 超时;经 `WHvRequestInterrupt` 转发可连续启动。[`qemu-whpx-win10-startup-ipis.patch`](../patches/qemu-whpx-win10-startup-ipis.patch) 只在 Win10、内核 irqchip 和多核同时启用时转发 INIT/SIPI。8 核两次冷启动和 12 核冷启动均已进入桌面,x2APIC、FileVault、SSH 和图形登录通过;默认启动及正常关机也通过。客体冷重启仍待验证。
|
||||
2. **Windows 提交内存(Commit Limit)硬拦截**:
|
||||
- 32 GB 物理内存宿主在开启常见软件后,实测可用提交内存(`FreeVirtualMemory`)仅 `14.7 GiB`(即使空闲物理内存仍有 `17.3 GiB`);QEMU 启动时一次性 `CreateFileMapping` 提交全部 Guest RAM,分配 `16G` 直接退出报 `Cannot set up guest memory 'ram': 系统资源不足`。`reims-go` 必须在体检与启动前检测提交内存并动态限位(详见 [`architecture.md`](architecture.md) 3.1 节)。
|
||||
3. **在线 Recovery 拉取 17 GB 极易因 Apple CDN 断流失败**:
|
||||
- 实测拉取 961 MB 恢复镜像期间 Apple CDN 即出现 6 次 `Peer disconnected`;在 Recovery 内经 QEMU 用户态 NAT(`slirp`)拉取 ~17 GB 系统包时,`OSISDownloadOperation` 抗断流能力差,易在接近完成(实测 `disk.qcow2` 已达 `16.95 GiB`)时失败。因此 `reims-go` GUI 默认改为宿主机调用 `reims-util offline-installer --json` 断点续传下载离线安装包(详见 [`architecture.md`](architecture.md) 3.3 节)。
|
||||
4. **登录 Apple ID 后 `SwitchToFiber(NULL)` 崩溃(`0xc0000005`,读 `0x10`)**:
|
||||
- 2026-11-28 对真实崩溃栈在 `runtime-3731afd` 上符号化定位:`whpx_vcpu_run` → `execute_ncq_command`(`hw/ide/ahci.c:1096`)→ `blk_aio_prwv`(`block/block-backend.c:1624`)→ `qemu_aio_coroutine_enter`(`util/qemu-coroutine.c:298`)→ `qemu_coroutine_switch`(`util/coroutine-windows.c:59`)→ `KERNELBASE!SwitchToFiber`(`movq 0x10(%rcx), %rax`)。
|
||||
- 根因是 `util/coroutine-windows.c:78` 调用 `CreateFiber(COROUTINE_STACK_SIZE, ...)` 预提交整块 1 MiB 栈,在 VA-API HEVC 批量解码 + iCloud/AHCI 并发读盘叠加导致 Commit Charge 见底时返回 `NULL`,且未判空直接传给 `SwitchToFiber`。补丁 [`qemu-win32-coroutine-fiber-commit.patch`](../patches/qemu-win32-coroutine-fiber-commit.patch) 改用 `CreateFiberEx(64 KiB, 1 MiB, 0, ...)` 并补齐空指针诊断与 `IsThreadAFiber()` 保护。
|
||||
|
||||
规则:
|
||||
1. 补丁原文的权威副本放在 `reims-go/patches/`。macos-vm-lab 的那份是研究时的原始记录。
|
||||
2. 每次跟进上游 commit 时,先 `git apply --check`。打不上就停在 `candidate`,不要自动改补丁。
|
||||
2. 每次跟进上游 commit 时,先 `git apply --check`(CI 中由 `scripts/apply-patch-series.ps1` 执行)。打不上就停下,不发布 alpha,不要自动改补丁。
|
||||
3. 补丁文件必须是**无 BOM、LF 行尾**,由 `.gitattributes` 的 `*.patch -text` 保证。用 PowerShell 5.1 的 `Out-File` 或 `>` 生成的补丁会带 BOM 和 CRLF,`git apply` 不认(2026-11-28 实测,原始副本就是这样)。
|
||||
4. 上游合并之后,在表里记下合并 commit,然后删掉补丁。
|
||||
5. `patches/series.txt` 是补丁队列的唯一清单,规定作用对象和应用顺序;CI 和 `pack-runtime.ps1` 都从它读取。加、删补丁只改这个文件和本节的表。
|
||||
|
||||
## 6. 发布通道(已验证通道)
|
||||
|
||||
上游变动非常快(2026-11-21 到 11-28 有 100 多个提交,截至 2026-11-28 没有任何 GitHub Release),出现过某个提交弄坏 `reims-ctl` 安装的情况([issue #138](https://github.com/steelbrain/reims-vgpu/issues/138))。所以运行时**不跟上游最新 commit**,而是分两级:
|
||||
上游变动非常快(2026-11-21 到 11-28 有 100 多个提交,截至 2026-11-28 没有任何 GitHub Release),出现过某个提交弄坏 `reims-ctl` 安装的情况([issue #138](https://github.com/steelbrain/reims-vgpu/issues/138))。所以用户默认拿到的运行时**不跟上游最新 commit**,而是分两级:CI 每天把上游最新 commit 构建成 `alpha`,人从 alpha 中挑一个冒烟通过的升为 `stable`。
|
||||
|
||||
| 通道 | 来源 | 进入条件 |
|
||||
| :--- | :--- | :--- |
|
||||
| `candidate` | CI 按指定上游 commit 构建并打补丁 | 能构建;`qemu-system-x86_64.exe -device help` 列出 `reims-graphics-pci`;SHA256 清单齐全 |
|
||||
| `stable` | 从 `candidate` 升级 | 在一台真实 Win10 或 Win11 宿主上跑通冒烟测试:`doctor` 的运行时检查全部通过,用 golden 镜像启动到 macOS 桌面,截一张屏,正常关机。由人确认后升级 |
|
||||
| `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`,`candidate` 要用户主动打开。这层筛选是 `reims-go` 相对于「自己跑上游安装脚本」的主要价值之一。
|
||||
`reims-go` 客户端默认只拉 `stable`,`alpha` 要用户主动打开(界面开关「接收 Alpha 版」,CLI `--alpha`)。旧配置里的 `runtime_channel: "candidate"` 读作 `alpha`,CLI 的 `--candidate` 保留为 `--alpha` 的别名。这层筛选是 `reims-go` 相对于「自己跑上游安装脚本」的主要价值之一。
|
||||
|
||||
升级记录:
|
||||
|
||||
| 运行时 | alpha 发布 | 冒烟测试 | 升为稳定版 |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| `runtime-3731afd` | 2026-11-28 | 真实宿主 Windows 10 19045,启动到 macOS 桌面并正常关机,由人确认通过 | 2026-11-28 |
|
||||
|
||||
升级不重新打包,只把 GitHub Release 从预发布改为正式发布,所以用户拿到的文件与冒烟测试用的完全相同。包内 `manifest.json` 的 `channel` 字段记录的是构建时的通道,会一直是 `alpha`(2026-11-28 前的包是 `candidate`);客户端只看 Release 的发布状态。alpha 预发布只保留最近 7 个,正在冒烟的那个如果被挤出,可以用手动触发重新构建同一 commit。
|
||||
|
||||
## 7. 许可证与源码义务
|
||||
|
||||
@@ -133,4 +174,12 @@ reims-runtime-<commit>/
|
||||
- 运行时里 MSYS2 CLANG64 DLL 对应的包名、版本,以及其中 LGPL/GPL 组件(如 glib)的源码或获取方式(具体清单**待 M0.1 打包时列出**);
|
||||
- `licenses/` 里的许可证全文。
|
||||
|
||||
`reims-go` 外壳用 MIT,前提是它和这些组件只通过独立进程交互,不链接它们。
|
||||
2026-11-28 的做法(`runtime-3731afd`):
|
||||
- **源码包内容**:四个上游仓库在对应 commit 的原始源码树(用 `git archive` 导出),加上构建时下载的 QEMU meson 子项目、`patches/` 里的补丁原文和重建说明。补丁不预先打在源码树上,由使用者按说明自行应用;已实测两个补丁都能直接打到这份源码上。
|
||||
- **DLL**:71 个 DLL 全部来自 55 个 MSYS2 包,`MSYS2-PACKAGES.txt` 按 DLL 列出所属包和版本,并给出源码下载地址(`repo.msys2.org/mingw/sources/` 和 MINGW-packages)。
|
||||
- **MSYS2 包的源码(2026-11-28 决定单独打包)**:只给下载地址不够稳妥,因为 MSYS2 删掉旧版本后链接就会失效。所以许可证要求提供源码的包,其源码作为同一个 Release 的第四个附件 `reims-runtime-msys2-src-<commit>.tar.zst` 发布。这满足 GPLv2 §3 和 LGPL-2.1 §6「在同一处提供源码」的要求。由 `scripts/pack-msys2-sources.ps1` 生成,`pack-runtime.ps1` 会自动调用它。
|
||||
- **筛选规则**:从本机 pacman 数据库读取每个包的 `%BASE%` 和 `%LICENSE%`。只要有一项许可证的所有可选项都含 GPL、LGPL 或 MPL,就需要附源码。如果有可选的宽松许可证(例如 freetype 可选 FTL,zstd 可选 BSD),就不附。只适用于文档的条目(`documentation:`)不算。
|
||||
- **内容**:`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` 外壳用 Apache-2.0,前提是它和这些组件只通过独立进程交互,不链接它们。
|
||||
@@ -1,13 +1,23 @@
|
||||
# 开发路线图与里程碑(Roadmap)
|
||||
|
||||
> 原则:先打通“最小可用闭环”(本地打包便携运行时 → Go 核心驱动 → Wails GUI),再扩展自动化与 CI 自动发版。每个里程碑均有明确的可验证验收标准(DoD)。
|
||||
>
|
||||
> 后续规划从用户任务出发:先让用户装得上、用得稳、改坏了能恢复,再减少开发工作流中的手工步骤。功能数量、参数覆盖率和竞品对标不单独构成立项理由。
|
||||
|
||||
## 规划与验收口径
|
||||
|
||||
- **[x] 只表示代码或脚本已经实现**,不自动表示已进入公开 Release,也不代表真机验收通过;是否达成 DoD 以各里程碑的状态说明和实测记录为准。
|
||||
- **已发布**:用户能从公开 `stable` Release 获得,且应用、运行时、manifest、补丁与源码包描述一致。
|
||||
- **已验收**:在记录清楚的 Windows、GPU、运行时和 macOS 版本组合上完成真实用户任务,并留下可复核结果;单元测试或 CI 构建成功不能代替这一步。
|
||||
- **后续条目必须先回答**:服务哪类用户、解决哪一步阻塞、现有替代办法是什么、怎样验收、失败如何恢复。没有这些内容的点子留在候选池,不占版本计划。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M0["M0 便携包与环境验证\n(2–3 天)"] --> M1["M1 Go 核心层与 CLI\n(1 周)"]
|
||||
M1 --> M2["M2 Wails 桌面 GUI MVP\n(1–2 周)"]
|
||||
M2 --> M3["M3 硬件调优与 CoW/QMP\n(1–2 周)"]
|
||||
M3 --> M4["M4 CI 自动构建与发版\n(1 周)"]
|
||||
M3 --> M4["M4 CI 自动构建与发版"]
|
||||
M4 --> M5["M5 macOS 日常主力体验\n(v0.2.2+)"]
|
||||
```
|
||||
|
||||
---
|
||||
@@ -16,10 +26,10 @@ flowchart LR
|
||||
|
||||
**目标**:把本机已验证可用的 `reims-vgpu` 产出一份标准、可复现、可校验的便携运行时压缩包,并在纯净目录中验证完整建机/启动闭环。
|
||||
|
||||
- [ ] **M0.0**:把 Win10 补丁的来龙去脉记清楚:在 `vendor/qemu` 里 `git diff` 与 `patches/qemu-whpx-win10-compat.patch` 比对一致;用一份**不带补丁**的上游构建在本机启动一次 VM,记下失败现象(作为补丁必要性的证据,也是向上游提 PR 的材料)。
|
||||
- [ ] **M0.1**:编写 `scripts/pack-runtime.ps1`,从本地 `reims-vgpu` 安装产物打包 `reims-runtime-win-x64-<commit>.tar.zst`、`manifest.json`(含 SHA256、`vendor/qemu` commit、补丁清单与哈希)、`patches/`、`NOTICE.md` 与 `licenses/`,实测压缩体积,并列出包内 MSYS2 DLL 对应的包名与许可证。
|
||||
- [ ] **M0.2**:在 `D:\Build\Temp\` 纯净路径中解压该包,验证在不依赖 MSYS2 / Rust / 源码仓库的条件下,可正常 `list --json`、`doctor`(9/9 运行时项通过)并拉起现有 `m0` 虚拟机进入 macOS 桌面。
|
||||
- [ ] **M0.3**:在本地初始化 `go.mod` 与 Wails 工具链检查(确认 `wails doctor` 通过)。
|
||||
- [x] **M0.0**:把 Win10 补丁的来龙去脉记清楚:在 `vendor/qemu` 里 `git diff` 与 `patches/qemu-whpx-win10-compat.patch` 比对一致;并在 `patches/README.md` 与 `docs/upstream-pr-prep.md` 归档复现与修复证据。
|
||||
- [x] **M0.1**:编写 `scripts/pack-runtime.ps1`,从本地 `reims-vgpu` 安装产物打包 `reims-runtime-win-x64-<commit>.tar.zst`、`manifest.json`(含 SHA256、`vendor/qemu` commit、补丁清单与哈希)、`patches/`、`NOTICE.md` 与 `licenses/`,并附 `pack-msys2-sources.ps1` 打包对应 MSYS2 copyleft 源码。
|
||||
- [x] **M0.2**:在独立路径解压并发布稳定版运行时 `runtime-3731afd`,验证在不依赖 MSYS2 / Rust / 源码仓库的条件下可正常 `list --json`、`doctor` 并拉起 macOS 桌面。
|
||||
- [x] **M0.3**:初始化 `go.mod` 与 Wails v2 工具链并完成可执行文件构建。
|
||||
|
||||
**DoD**:
|
||||
- 存在可重复生成的便携运行时包及其 SHA256 清单;
|
||||
@@ -31,8 +41,9 @@ flowchart LR
|
||||
|
||||
**目标**:先用纯 Go 打通所有底层能力与单元测试,确保 CLI 单独就能跑完整个生命周期。
|
||||
|
||||
- [ ] **M1.1**:`internal/config` + `internal/i18n` — 实现配置持久化(`locale: zh-CN | en-US`、`data_root`)与双语消息字典;`internal/host` 实现 Windows 原生体检(`*_windows.go`:含 WHPX、**物理内存与可用提交内存 `FreeVirtualMemory` 安全档位推荐**、Vulkan ICD、P/E 核拓扑)与非 Windows 桩(`*_other.go`,确保 macOS 开发环境可直接 `go test ./...`)。
|
||||
- [ ] **M1.2**:`internal/runtime` — 实现便携运行时导入(本地 `.tar.zst` 与 HTTP 下载)、SHA256 校验、原子解压、版本切换与子进程环境变量构造(`XDG_*` + `REIMS_CTL_QEMU`)。
|
||||
- [x] **M1.1**:`internal/config` + `internal/i18n` — 实现配置持久化(`locale: zh-CN | en-US`、`data_root`)与双语消息字典;`internal/host` 实现 Windows 原生体检(`*_windows.go`:含 WHPX、**物理内存与可用提交内存 `FreeVirtualMemory` 安全档位推荐**、Vulkan ICD、三层 P/E/LP-E 核拓扑、磁盘总线类型探测)与非 Windows 桩(`*_other.go`)。
|
||||
- [x] **M1.2**:`internal/runtime` — 实现便携运行时导入(本地 `.tar.zst` 与 HTTP 下载)、SHA256 校验、原子解压、版本切换与子进程环境变量构造(`XDG_*` + `REIMS_CTL_QEMU`)。
|
||||
- 2026-11-28:补上在线安装,运行时从本仓库的 GitHub Release 下载(`runtime-<commit>` tag,alpha 和稳定版两个通道;alpha 在 2026-11-28 前叫候选版),支持续传,并对照 `SHA256SUMS.txt` 校验。CLI 用 `reims-go runtime available` 和 `reims-go runtime fetch [commit]`;界面在宿主页和首次启动页。细节见 `portable-runtime-spec.md` 第 4 节。
|
||||
- [x] **M1.3**:`internal/installer` — 封装 `reims-util offline-installer list --json`、`reims-util offline-installer <ver> -o <DataRoot>\data\reims-ctl\installers --json` 与 `reims-ctl downloads`:实现结构化 JSON 进度流解析、取消/断点续传与缓存清理。
|
||||
- 2026-11-28 完成。
|
||||
- CLI:`reims-go installer list | download <版本> | cached | delete <文件名>`。
|
||||
@@ -50,8 +61,8 @@ flowchart LR
|
||||
- 未实测:
|
||||
- 完整跑完一次离线安装包下载(18.4 GB);
|
||||
- 下载完成时 `done` 事件里是否带 `installer.build` 字段(代码按可选处理)。
|
||||
- [ ] **M1.4**:`internal/driver/reims` — 封装 `reims-ctl` 的 `list --json`、`show`、`create`、`start`、`stop`、`set`、`eject`、`delete`、`logs`、`downloads`,带 Fake CLI 单元测试。
|
||||
- [ ] **M1.5**:`cmd/reims-go` — 提供 `doctor`、`runtime install/list/use`、`installer list/download/delete`、`vm list/create/start/stop/eject/logs` 子命令,支持 `--lang zh|en` 与中英双语输出。
|
||||
- [x] **M1.4**:`internal/driver/reims` — 封装 `reims-ctl` 的 `list --json`、`show`、`create`、`start`、`stop`、`set`、`insert`、`eject`、`update-opencore`、`delete`、`logs`、`downloads` 与 `qemu-img` 转换/CoW 派生,带单元测试。
|
||||
- [x] **M1.5**:命令行模式(2026-11-28 起从 `cmd/reims-go` 移到 `internal/cli`,并入 `reims-go.exe`)— 提供 `doctor`、`runtime available/fetch/install/list/use`、`installer list/download/cached/delete`、`vm list/create/set/start/stop/eject/type`、`version` 子命令,支持 `--lang zh-CN|en-US` 与中英双语输出。
|
||||
|
||||
**DoD**:
|
||||
- 在一个从未 dot-source `reims-env.ps1` 的全新 PowerShell 中,仅运行 `reims-go` CLI 即可完成体检、导入运行时、断点续传下载离线包、启动/查看 VM;
|
||||
@@ -63,52 +74,193 @@ flowchart LR
|
||||
|
||||
**目标**:做成真正给普通开发者/自己点几下就能用的轻量桌面应用。
|
||||
|
||||
- [ ] **M2.1**:**首次启动向导(中英双语实时切换)** — 自动识别系统语言(支持顶部一键切换 `中文 / English`);展示环境体检卡片(WHPX、**提交内存与推荐 RAM**、显卡、磁盘);WHPX 未开时提供「一键提权启用并重启」按钮;引导选择非 C 盘数据目录并一键安装/导入便携运行时。
|
||||
- [ ] **M2.2**:**离线安装包下载管理器(核心体验)** — 调用 `reims-util --json` 展示可选 macOS Tahoe 精确版本,在 GUI 内直接触发宿主机直连下载、实时显示进度条 / 速率 / 已下体积 / 自动重试状态、支持「暂停/取消」与「断点续传」,并可视化管理 `<DataRoot>\data\reims-ctl\installers` 缓存。
|
||||
- [ ] **M2.3**:**VM 主面板与创建/装机引导(贴合简体中文 / 英文 macOS 界面术语)** — 实例列表、实时状态、一键启停与串口/图形日志抽屉;新建默认推荐复用本地离线包(附 `--network false`,启动前校验提交内存),装机侧边栏展示离线安装 3 步引导(抹盘 APFS → `sh /Volumes/Installer/install-macos.sh` → 一键 **弹出安装盘并恢复网络**)。
|
||||
- [ ] **M2.4**:打包为单文件 `reims-go.exe`(验证体积与冷启动速度)。
|
||||
- [ ] **M2.5**:**设置面板(对齐 macOS)** — 按 [`shell-design.md`](shell-design.md) 第 3 节的类别分页(平台、引导、CPU、内存、存储、网络、图形与显示器、音频、键盘与指针、串口与日志、高级);VM 运行中也能打开、能改,每个字段标出生效时机;保存前先在 Go 里校验(含提交内存与 ICD 检查),再调用 `reims-ctl set` 写入;平台类字段只读且脱敏。
|
||||
- [ ] **M2.6**:**待生效修改** — 详情页列出「已保存、下次启动才生效」的修改(例如 `cpus 8→12`),提供「重启以应用」按钮;状态模型按 `shell-design.md` 第 4 节实现。
|
||||
- [ ] **M2.7**:**主窗口结构** — 侧边栏 + 详情 + 工具栏,新建用分步助手,最后一步显示将执行的 `reims-ctl create` 命令(`shell-design.md` 第 5 节)。
|
||||
- [x] **M2.1**:**首次启动向导(中英双语实时切换)** — 自动识别系统语言(支持切换 `中文 / English`);引导选择非 C 盘数据目录(外置盘风险提示)、展示环境体检(WHPX 一键提权启用、Vulkan 显卡、提交内存推荐值)并一键在线安装/导入便携运行时。
|
||||
- [x] **M2.2**:**离线安装包下载管理器(核心体验)** — 调用 `reims-util --json` 展示可选 macOS Tahoe 精确版本,在 GUI 内直接触发宿主机直连下载、实时显示进度条 / 速率 / 已下体积 / 自动重试状态、支持「暂停/取消」与「断点续传」,并可视化管理 `<DataRoot>\data\reims-ctl\installers` 缓存。
|
||||
- 2026-11-28(v0.2):侧边栏新增「安装包」页。上半部分是已下载的安装包:可以继续未下载完的、删除(两步确认,删除走 `reims-ctl downloads delete`)。下半部分是 Apple 提供的版本:下载、进度、暂停。下载前检查剩余空间(按安装包大小加 10% 计,因为一开始就会占满整个镜像的空间)。速率显示在进度的悬停提示里。暂停后再次下载会接着下。
|
||||
- [x] **M2.3**:**VM 主面板与创建/装机引导(贴合简体中文 / 英文 macOS 界面术语)** — 实例列表、实时状态、一键启停与串口/图形日志抽屉;新建默认推荐复用本地离线包 + 默认 `NVMe` 磁盘控制器,启动前校验提交内存;离线安装通过纯 Go HFS+ 辅助盘 `REIMSHELP` 自动绕过 macOS 26.7.3 缺 `pkgutil` / `installer -target` 失效,支持空白盘自动 APFS 抹盘 + QMP 一键键入;提供对称的「进入/退出恢复模式」切换与约 1 GB 在线恢复镜像兜底拉取。
|
||||
- [x] **M2.4**:打包为单文件 `reims-go.exe`(~13.3 MB)。无代码签名,冷启动时间待量化实测。
|
||||
- 2026-11-28:不再单独发布命令行版 `reims-go-cli.exe`,命令行模式并入同一个 exe:带子命令即走命令行;`vm start` 把启动交给界面进程(没在运行就以 `--background` 拉起到托盘),因此命令行启动的 VM 也有剪贴板、共享目录和 Win10 冷重启。细节见 [`architecture.md`](architecture.md) 3.5 节。
|
||||
- [x] **M2.5**:**设置面板(对齐 macOS)** — 按 [`shell-design.md`](shell-design.md) 类别分页;VM 运行中可改并标出生效时机;保存前在 Go 侧校验提交内存与 ICD,写入仅走 `reims-ctl set`。
|
||||
- [x] **M2.6**:**待生效修改** — 详情页列出「已保存、下次启动才生效」的修改并提供「重启以应用」按钮。
|
||||
- [x] **M2.7**:**主窗口结构** — 侧边栏 + 详情 + 工具栏,分步新建助手并在最后一步预览完整 `reims-ctl` 命令。
|
||||
|
||||
**DoD**:
|
||||
- 双击 `reims-go.exe` 即可走完「体检 → 导入运行时 → GUI 断点续传下载离线安装包 → 创建/启动 VM → 离线装完并弹出安装盘」全流程,无需打开命令行。
|
||||
- 双击 `reims-go.exe` 即可走完「体检 → 导入运行时 → GUI 断点续传下载离线安装包 → 创建/启动 VM → 离线装完并退出恢复模式」全流程,无需打开命令行。
|
||||
- VM 运行中修改 CPU / 内存 / 显示器数量并保存,重启后 `reims-ctl show` 显示新值;非法输入(如内存超过宿主可用提交内存、ICD 文件不存在)在保存前被拦下。
|
||||
- **可测量的时间目标**:从首次双击到出现 macOS 安装界面 ≤ 10 分钟。不计入:开启 WHPX 后的重启、运行时下载、从 Apple 下载离线安装包。macOS 离线安装本身的耗时单独实测记录(**待验证**),不作为 DoD。
|
||||
- **可测量的时间目标**:从首次双击到出现 macOS 安装界面 ≤ 10 分钟(不计入开启 WHPX 重启、运行时下载与 Apple 安装包下载)。macOS 离线安装第二阶段耗时受宿主磁盘与 `kernel-irqchip` 影响,继续实测记录。
|
||||
|
||||
---
|
||||
|
||||
## M3:硬件自动调优与开发者进阶能力
|
||||
## M3:硬件自动调优、宿客互通与开发者进阶能力
|
||||
|
||||
**目标**:补齐现有社区 GUI 的空白,对接 `macos-vm-lab` 的工程化需求。
|
||||
**目标**:补齐硬件调优、宿客互通、安全边界与工程化能力。M3 的功能随 v0.2.1 发布。
|
||||
|
||||
- [ ] **M3.1**:**P-Core 自动绑核与 Win10 `kernel-irqchip=on` 验证** — 启动 VM 后自动定位对应 `qemu-system-x86_64.exe` PID 并应用 P-Core 亲和性掩码,界面显示当前绑核状态;实测 Win10 下强制开启 `kernel-irqchip=on` 的稳定性与 I/O CPU 收益(稳定则优先向上游提 PR)。
|
||||
- [ ] **M3.2**:**独立 QMP 与优雅关机** — 通过 `--extra-args` 接入独立 TCP QMP 通道(不抢占 `reims-ctl` 自带的 `qmp.sock`),实现运行态监控、优雅关机与截屏(实测验证不与上游内置参数冲突)。
|
||||
- [ ] **M3.3**:**Golden Image 与 CoW 秒级派生** — 支持将已装好系统的 VM 标记为模板,用 `qemu-img` 秒级派生临时测试实例,销毁后模板哈希不变。
|
||||
- [ ] **M3.4**:**一键打包排障日志** — 收集体检报告、QEMU/串口日志(自动脱敏序列号/MAC/OSK),一键导出 `.zip`。
|
||||
- [x] **M3.1**:**三层大小核防超售绑核与 WHPX 兼容自愈** — 识别三层混合架构(P + E + LP-E,如 Intel Core Ultra 200 无超线程 CPU),`vCPU < P 核逻辑线程数` 时绑 P 核,超出时自动改绑 `P + E`(仅排除慢速 LP-E 核)避免自旋锁超售卡顿;自动探测 Win11 `hr=0x80370302` 嵌套虚拟化属性并预置/补丁化处理;新建 VM 默认 `NVMe` 控制器。
|
||||
- [x] **M3.2**:**安全 AF_UNIX QMP 通道与键入** — Win10 冷重启辅助 QMP 通道已迁至 Windows `AF_UNIX` 套接字(杜绝 SLIRP 下 `10.0.2.2:<port>` 宿主机逃逸风险,自动清理旧 TCP 参数);已基于 `reims-ctl` 的 `qmp.sock` 实现 QMP 键盘一键键入。后续按需补齐优雅关机增强与 QMP 截屏。
|
||||
- [x] **M3.3**:**安全鉴权 Guest Tools(双向剪贴板 + 共享目录)** — 内置仅监听 `127.0.0.1` 的纯 Go HTTP 宿客桥接(每台 VM 独立 256-bit 随机 Bearer Token + 严格共享目录路径隔离),通过纯 Go HFS+ 辅助盘 `REIMSTOOLS` 一键安装免 Xcode/Python 的 macOS LaunchAgent,支持双向 UTF-8 剪贴板与 `~/Desktop/ReimsShare` ↔ `<DataRoot>/shared/<vm>` 双向文件同步。**(macOS 桌面端真机联调待验证)**
|
||||
- [x] **M3.4**:**退出恢复模式自动升级 `NVMe` + 存储/内存性能诊断** — 对旧 `AHCI` VM 在退出恢复模式时自动切至 `NVMe`,并在 VM 主页提供一键升级按钮;自动检测外置 USB/网络盘(`GetDriveTypeW` + `IOCTL_STORAGE_QUERY_PROPERTY` `BusTypeUsb`)与高内存负载(≥ 85%)并展示可操作提示。
|
||||
- [x] **M3.5**:**一键导出脱敏排障日志包(`.zip`)** — 收集体检报告、运行时清单、VM 配置、自动脱敏(序列号/MAC/SMC OSK/Bearer Token)的 QEMU、串口与应用日志,一键导出到 `<DataRoot>/reports/` 并定位目录(已通过单测验证零敏感信息泄漏)。
|
||||
- [x] **M3.6**:**磁盘导入增强(VMDK / RAW 自动转 qcow2)** — 复用便携运行时内置 `qemu-img convert`,新建向导支持直接选择 `.vmdk` / `.raw` 并自动转为 `.qcow2` 导入。**(真机大容量 VMDK 转换待验证)**
|
||||
- [x] **M3.7**:**Golden Image 与 CoW 秒级派生** — 已停止的已装系统 VM 支持在「更多」里通过 `qemu-img create -f qcow2 -b <golden> -F qcow2` + `reims-ctl create --disk --disk-mode in-place` 秒级派生独立身份副本,原盘只读不改。**(真机 CoW 派生启动待验证)**
|
||||
|
||||
**DoD**:
|
||||
- P-Core 绑核、QMP 连接、CoW 派生在本机均有实测通过记录。
|
||||
- 三层大小核防超售绑核、`AF_UNIX` QMP、Guest Tools 剪贴板与共享目录、CoW 派生在真实宿主均有实测通过记录。
|
||||
|
||||
**状态**:功能都已实现,但 DoD 还没达成。M3.3(Guest Tools 真机联调)、M3.6(大容量 VMDK 转换)、M3.7(CoW 派生启动)还没有真机实测记录。
|
||||
|
||||
---
|
||||
|
||||
## M4:GitHub Actions 自动化构建与发布
|
||||
## M4:上游性能/窗口跟进与 CI 自动发布
|
||||
|
||||
**目标**:彻底自动化上游跟进,用户点「检查更新」即可拉取新版运行时与外壳。
|
||||
**目标**:自动化跟进上游 Windows 性能与窗口体验改进,建立 `alpha` → `stable` 冒烟发布闭环。
|
||||
|
||||
- [ ] **M4.1**:编写 GitHub Actions workflow:在 `windows-latest` 上通过 MSYS2 CLANG64,先 `git apply --check` 并打上 `patches/` 补丁队列,再构建指定上游 commit 的 `reims-runtime-win-x64-<commit>.tar.zst`、`SHA256SUMS.txt` 与源码包。产物只进 `candidate` 通道。补丁打不上时 workflow 失败,不自动修补丁。
|
||||
- [ ] **M4.2**:**`candidate` → `stable` 升级流程**(排在自动发版之前):编写 `scripts/smoke-runtime.ps1`,在真实宿主上解压候选包,跑 `doctor`、用 golden 镜像启动到桌面、截屏、正常关机,输出报告;由人看过报告后再升级为 `stable`。规则见 `portable-runtime-spec.md` 第 6 节。
|
||||
- [ ] **M4.3**:自动构建 `reims-go.exe` 并发布 GitHub Release,客户端接入在线版本检查,默认只拉 `stable`,支持一键回滚旧版本。
|
||||
- [ ] **M4.4**:补齐 `NOTICE.md`、第三方许可证包、对应源码包(含本地补丁)与安全/合规核验清单(`portable-runtime-spec.md` 第 7 节)。
|
||||
- [ ] **M4.5**:补丁上游化:整理 `patches/` 里每个补丁的复现步骤与实测证据,交给人向上游提 PR;合并后从队列删除。
|
||||
- [ ] **M4.1**:**上游窗口与性能 PR 跟进(运行时升级,持续跟踪)** — 已建立跟踪清单 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md),跟踪上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 关键 Windows PR(`#153`、`#152`、`#107`、`#123`、`#172` 与 Win→Command)合入后由 `build-runtime.yml` 的每日构建自动产出 `alpha` 运行时。
|
||||
- [x] **M4.2**:编写 GitHub Actions workflow([ci.yml](../.github/workflows/ci.yml) + [build-runtime.yml](../.github/workflows/build-runtime.yml)):CI 自动先构建前端再跑 `go test` / `go vet` 并编译 CLI 与 GUI;运行时构建 workflow 每天从上游最新 commit 自动构建(2026-11-28 起;已发布过的 commit 跳过),在 `windows-latest` 上通过 MSYS2 CLANG64 拉取 `vendor/qemu`、按 `patches/series.txt` 应用补丁(已被上游合并的跳过并开 issue 提醒,冲突就停止)、调用上游 `scripts/install-ctl.sh --yes`、执行 `scripts/pack-runtime.ps1`,经 `scripts/check-runtime-alpha.ps1` 准入检查后发布 `alpha` 预发布包与对应源码包,并只保留最近 7 个 alpha。**(GitHub Actions 运行时编译待首次手动触发实跑验证)**
|
||||
- [x] **M4.3**:**`alpha` → `stable` 冒烟脚本** — 已编写 [scripts/smoke-runtime.ps1](../scripts/smoke-runtime.ps1),支持校验 SHA-256、在干净隔离目录(无 MSYS2 PATH)解压并跑 `reims-ctl doctor` / `list --json` 与合规文件核查,产出供人工评审的 Markdown 冒烟报告。
|
||||
- [x] **M4.4**:**客户端自动发布与在线更新检查** — 已新增 [.github/workflows/release.yml](../.github/workflows/release.yml)(打 `v*` tag 自动跑测、构建 `reims-go-<tag>-windows-amd64.exe` + `SHA256SUMS.txt`(2026-11-28 前还附带 `reims-go-cli-<tag>-windows-amd64.exe`) 并发布 GitHub Release);客户端与 CLI 接入 `internal/version` 版本号与稳定版在线更新检查(`HostView` 一键检查/跳转下载,运行时支持多版本回滚切换);合规文件(`NOTICE.md`、`LICENSE`、运行时源码包与 `MSYS2-PACKAGES.txt`)已随构建脚本落盘。
|
||||
- [ ] **M4.5**:**补丁上游化(人工提交 PR)** — 已在 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md) 整理好 4 个 QEMU 补丁的根因、复现步骤与实测证据,待人工向上游提 PR 并合入后从 `patches/` 队列清零。
|
||||
|
||||
**DoD**:
|
||||
- 触发一次 tag/手动 workflow 即可产出完整的 `candidate`(App + Runtime + SHA256 + 源码包);冒烟通过并经人确认后升为 `stable`;在干净目录下载 `stable` 后,按 M2 的时间目标跑通。
|
||||
- 触发一次 tag/手动 workflow 即可产出完整的 `alpha`(App + Runtime + SHA256 + 源码包);冒烟通过并经人确认后升为 `stable`;在干净目录下载 `stable` 后,按 M2 的时间目标跑通。
|
||||
|
||||
**状态**:客户端 Release(`release.yml`)已随 v0.2.1 跑通;运行时构建(`build-runtime.yml`)还没在 GitHub Actions 上实跑过,所以 DoD 还没达成。
|
||||
|
||||
---
|
||||
|
||||
## M5(v0.2.2+):macOS 日常主力体验与性能优化
|
||||
|
||||
**目标**:让 macOS 虚拟机真正脱离「仅供测试与点亮」,在图形/磁盘性能、窗口与键鼠直觉、宿客无缝协作和长期运维安全性上达到可作为日常主力/开发机使用的水准。本阶段优先验收已有能力;除“可反悔的停机快照”外,不因竞品具有类似功能就新增独立子系统。
|
||||
|
||||
### 核心体验的实现与跟进清单
|
||||
|
||||
- [ ] **M5.1(上游运行时联动)**:**沉浸全屏、无黑边缩放与 GPU 性能升级**
|
||||
- 本仓已完成:VM 详情页与设置页/新建向导补齐「无边框全屏启动」开关(走 `reims-ctl set --borderless`,支持运行中变更进入待生效列表)与按显卡后端区分的真实快捷键提示(`reims-vgpu` 捕获时显示 `Ctrl+Alt+Win` 释放输入,`vmware-svga` GTK 窗口显示 `Ctrl+Alt+F` / `Ctrl+Alt+G`);
|
||||
- 待上游跟进:待 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md) 中上游 `reims-vgpu` PR 合入后由 `build-runtime.yml` 产出新 `alpha`,冒烟后升为 `stable`:`#123`(`Ctrl+Alt+Enter` 运行中热切全屏)、`#172`(Windows 拖动窗口动态贴合、消除黑边)、`#152`(原生 Windows Vulkan 后端)、`#153`(NVIDIA MAILBOX/FIFO 首帧优化)、`#107`(采样纹理回读就地消费)。
|
||||
- [ ] **M5.2(本仓 + 上游)**:**HiDPI 智能推荐与 Mac 键位习惯适配**
|
||||
- 本仓已完成:`internal/host` 新增原生 Windows 物理显示器与 DPI 缩放探测(`EnumDisplayMonitors` + `EnumDisplaySettingsW` + `GetDpiForMonitor`),按主屏分辨率与 DPI 缩放自动推荐 1× / 2× HiDPI 预设(2K/2.5K/4K/16:10),并在宿主页、新建向导第 4 步与设置页展示智能推荐与多屏引导;设置页键盘分类补齐 Mac 键位提示;
|
||||
- 待验证:自由指针模式下 `Win` 键映射 macOS `Command`(优先随上游 PR 落地,避免维护私有分叉)。
|
||||
- [x] **M5.3(本仓)**:**Guest Tools 2.0(图片剪贴板 + 真挂载式共享目录)**
|
||||
- 剪贴板 2.0:Windows 端支持原生 `"PNG"` 与 32-bit `CF_DIB` 双向图片剪贴板编解码(纯 Go,零外部依赖),服务端基于 `GetClipboardSequenceNumber()` 实现低延迟长轮询事件唤醒(`?since=&wait=&accept=image`),Guest POSIX 脚本使用 macOS 原生 `osascript` + `sips` 实现零 Xcode/Python 的文本 + PNG 截图双向剪贴板;
|
||||
- 共享目录 2.0:在 `reims-go` 内置仅监听 `127.0.0.1`、带 per-VM 256-bit Basic/Bearer Token 鉴权与严格目录防穿越的纯 Go **WebDAV 服务**(`/dav/<vm>/`),Guest 侧优先 `mount_webdav` 实时零双份挂载到 `~/Desktop/ReimsShare` 并在不可用时自动回退同步模式;
|
||||
- Windows 盘符只读共享:每台 VM 在「存储与网络」设置中独立开启内部固定盘符,默认全部关闭,系统盘显示敏感信息提示;新增 `/dav/<vm>/drives/<盘符>/`,由服务端同时限制 HTTP 写方法和文件打开标志,持久化并复核 Volume GUID 防止盘符重绑定,限制 `PROPFIND Depth` 避免整盘递归,并验证 Junction / 符号链接解析后的目标仍在授权盘符内。Guest Tools 4 根据 `/v1/config` 自动挂载/卸载 `Windows C` 等 Finder 卷,关闭开关立即拒绝新请求。**(macOS Finder 真机挂载、只读兼容与重连待验证)**
|
||||
- UI 升级:主界面实时显示 Guest Tools 连接状态、`WebDAV 挂载` / `文件同步` 模式徽章、旧版工具升级提示与「投递文件到 macOS」快捷入口。**(macOS 桌面端真机 WebDAV 挂载与图片剪贴板联调待验证)**
|
||||
- [x] **M5.4(本仓)**:**防休眠守护、系统托盘驻留与资源状态条**
|
||||
- 防休眠守护:Guest Tools 2.0 支持由宿主机 UI 一键实时开关 `caffeinate -dims`(免 sudo,通过 `/v1/config` 实时下发),并在 `REIMSTOOLS` 附带可选 `Apply-Prevent-Sleep-pmset.command`;
|
||||
- Windows 系统托盘驻留:新增纯 Go Win32 `internal/tray`(`Shell_NotifyIconW` + 动态中英文右键菜单,含 VM 状态/快捷启停/打开共享目录/显示窗口/退出),默认关闭主窗口最小化到托盘(可在宿主页开关),保障后台 Guest Tools 桥接不断线;
|
||||
- VM 实时资源条:新增 `internal/host` 进程 CPU%/内存采样与纯 Go `.qcow2` 实际占用 vs 逻辑容量解析,在 VM 详情页每 3 秒轻量展示 QEMU CPU、宿主机内存、磁盘占比与运行时长。
|
||||
|
||||
- [x] **M5.5(本仓 + 上游化)**:**系统外预设 macOS 系统语言(`prev-lang:kbd`)**
|
||||
- 根因:`reims-util@7867384`(`src/opencore/config.rs:216-228`)在生成 `opencore.qcow2` 时将 `NVRAM > Add/Delete > prev-lang:kbd` 硬编码为 `en-US:0`,导致每次进入恢复模式、设置助理和登录界面均强制回退为英文。
|
||||
- 本仓已实现:新增纯 Go `internal/opencore`(直读/原地改写 `opencore.qcow2` / `opencore.img` 的 GPT+FAT32 `EFI/OC/config.plist` 中 `NVRAM > Add/Delete > prev-lang:kbd`,必要时自动回退 `qemu-img` 原子转换);新建向导、VM 设置「通用」页、VM 详情页与 CLI(`--guest-lang`)均已支持预设(默认跟随界面语言,如 `zh-Hans:0` / `zh-Hans:252` / `zh-Hant:0` / `en-US:0` / `ja-JP:0` / `ko-KR:0`),偏好持久化到 `.reims-go-guest-lang` 并在 `update-opencore`、显卡切换、CoW 克隆与 `StartVM` 前自动重放(`zh-Hans:0` vs `zh-Hans:252` 在 Tahoe Recovery 下的真机键盘布局表现**待验证**)。
|
||||
- 长期上游化:向 `reims-util` / `reims-ctl` 提议支持 `opencore --lang` 并在 `update-opencore` 重建时保留原有 `prev-lang:kbd`(登记在 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md))。
|
||||
|
||||
### 运维与开发工作流的实现清单
|
||||
|
||||
- [x] **M5.6(本仓)**:**磁盘 I/O 进阶调优与空间生命周期管理**
|
||||
- 已实现:封装 `qemu-img resize` 停机扩容(支持 `+32G`/`+64G`/`+128G`/`256G` 等增量与绝对目标,防误缩容,完成后自动生成不依赖盘符序号的 macOS `diskutil repairDisk` + `apfs resizeContainer` 一键扩展命令);封装停机「回收未用空间」(校验非 CoW overlay 与剩余空间后重写稀疏 `.qcow2` 并通过 `qemu-img check` 完整性校验再原子替换);补齐 `NVMe` / `VirtIO-blk` / `SATA` 控制器说明并接入设置页「存储与网络」与 CLI(`vm resize` / `vm compact`);
|
||||
- 待验证:已装 macOS 26 真机下 `nvme` vs `virtio-blk` 实际编译/读写基准对比。
|
||||
- [ ] **M5.7(本仓)**:**可视化停机快照与一键回滚**
|
||||
- 基于 M3.7 已落地的 CoW / Golden Image 基础设施,提供命名停机检查点(如「升级 macOS 26.8 前」)、历史列表与一键回滚,确保日常环境改坏或 OTA 失败可秒级恢复。
|
||||
- [ ] **M5.8(本仓)**:**多端口转发与开发者工作流直连**
|
||||
- 网络设置页支持自定义多条宿客 TCP 端口转发(如 `3000→3000`、`8080→8080`,安全合并至 `--extra-args` 或跟进上游多 `hostfwd`);
|
||||
- 详情页提供「打开 SSH 终端」、一键写入 `~/.ssh/config`(`Host reims-<vm>`)与 VS Code / Cursor Remote-SSH 直连入口;
|
||||
- Guest Tools 提供可选「宿主机代理快捷配置」(经 `10.0.2.2:<port>` 显式开启/一键清除,方便 Homebrew / Xcode / npm 下载)。
|
||||
- [x] **M5.9(本仓 + 上游验证)**:**音频延迟与麦克风链路打磨**
|
||||
- 已实现:`internal/host` 接入原生 Win32 `winmm.dll`(`waveOutGetNumDevs` / `waveInGetNumDevs` + 设备名枚举,与上游 `reims-ctl` `sound_devices()` 探测一致);修复 `ParseShow` 在指定显式 `--audio-backend`(如 `dsound`/`none`)时误判音频关闭的 Bug;设置页「输入与音频」与 CLI(`vm set --audio-backend`)支持切换音频后端(`自动(dsound)` / `DirectSound` / `静音设备`),实时展示宿主播放与录音设备状态(无输出/无麦克风时明确提示上游 `reims-ctl` 路由到 `none` 的行为)及 48 kHz / P-Core / 麦克风权限排查指引;
|
||||
- 待验证:真实 macOS 桌面下 DirectSound 播放延迟与麦克风会议录音实测记录。
|
||||
|
||||
### 按需评估的能力
|
||||
|
||||
- [ ] **M5.10(按需评估)**:**Windows USB 设备直通可行性评估** — 上游 `crates/reims-ctl/src/usb.rs` 当前仅枚举 Linux sysfs,Windows 需依赖 WinUSB / UsbDk 驱动替换,复杂度与风险较高;仅在核心体验稳定后评估作为可选高级功能(用于 iPhone 真机调试 / 硬件密钥)。
|
||||
- [ ] **M5.11(按需评估)**:**QMP 实时缩略图与自动化脚本接口** — 复用现有 QMP 通道补齐 VM 画面缩略图预览与 CLI 自动化操作。
|
||||
|
||||
**DoD(v0.2.2 验收标准)**:
|
||||
- 在真实 Windows 宿主上,使用 `reims-go` 启动 macOS 可完成:**新建/恢复阶段即可外部预设中文语言(`prev-lang:kbd`)、热切沉浸全屏/无黑边缩放、清晰 HiDPI 显示、图文双向剪贴板、零双份占用的挂载式共享目录、托盘后台常驻不掉线**,且持续高负载开发(编译/浏览器/多任务)稳定无明显卡顿或意外断连。
|
||||
|
||||
---
|
||||
|
||||
## 后续执行顺序:按用户任务验收
|
||||
|
||||
上面的 M5.x 是实现索引,不代表执行顺序,也不构成持续增加功能的承诺。后续迭代按下面的用户任务排序;同一任务优先修复和验证已有能力,只有现有路径确实无法完成任务时才新增功能。P0 表示任务优先级,不表示全部塞进同一个版本;每轮只选择能够完整验收的范围。
|
||||
|
||||
### U1(P0):第一次使用就能装到桌面,失败也知道怎么处理
|
||||
|
||||
**用户故事**:我只按向导操作,不需要理解 WHPX、Vulkan、OpenCore 或 QEMU 参数,就能得到可用的 macOS 桌面;下载中断、磁盘不足或提权取消时,可以安全重试。
|
||||
|
||||
**实现范围**:
|
||||
|
||||
1. 先完成 M4 的发布闭环:实跑运行时 CI;确保公开资产的 manifest、补丁和源码包一致;冒烟报告记录最终资产完整 SHA-256,发布后替换资产必须退回 `alpha` 重新验收。
|
||||
2. 用公开应用和运行时,在声明支持的 Windows / GPU / macOS 组合上跑「干净用户目录 → 体检 → 下载/导入 → 创建 → 安装 → 退出恢复模式」完整流程,而不是只跑 `doctor` 和单元测试。
|
||||
3. 针对用户真实会遇到的中断做故障注入:暂停/断网后续传、磁盘不足、UAC 取消、运行时损坏、安装进程退出。界面说明发生了什么、数据是否保留以及下一步怎么做。
|
||||
|
||||
**验收证据**:每个受支持组合都有版本、耗时、结果和日志记录;失败后可以重试或安全清理,不留下无法解释的半配置 VM;公开文档描述与用户实际下载的稳定资产一致。
|
||||
|
||||
**不扩大范围**:不为了增加“支持数量”贸然承诺未测试的 GPU、Windows 或 macOS 版本,也不把高级参数暴露给首次使用者。
|
||||
|
||||
### U2(P0):一天开发工作不被显示、输入和宿客协作打断
|
||||
|
||||
**用户故事**:我在 macOS 里使用 IDE、浏览器和构建工具,同时与 Windows 交换文字、图片和文件;全屏、HiDPI、快捷键、声音和共享目录应当稳定,不需要反复重连或调整底层参数。
|
||||
|
||||
**实现范围**:
|
||||
|
||||
1. 集中验收 M5.1–M5.5 和 M5.9 的已有实现;上游图形 PR 只有在能改善可测的全屏、缩放、帧率、首帧延迟或稳定性时才进入新运行时。
|
||||
2. 在真实宿主完成一个完整工作日(8 小时)的编译、浏览器、多任务、图文剪贴板和共享目录混合负载,并覆盖窗口尺寸/DPI 变化、宿主睡眠唤醒、Guest Tools 重连和音频/麦克风场景。
|
||||
3. 资源条和诊断信息用于解释卡顿、内存压力、磁盘压力和断连,不继续增加没有明确排障用途的指标。
|
||||
|
||||
**验收证据**:记录宿主硬件、运行时和 macOS 版本,以及卡顿、断连、延迟和恢复结果;未通过的组合明确限制或降级,不把“有开关”写成“体验已完成”。
|
||||
|
||||
**不扩大范围**:现有剪贴板和 WebDAV 能完成任务时,不另做一套拖放协议、共享文件系统或无缝窗口模式。
|
||||
|
||||
### U3(P0):升级系统和调整环境之前,用户可以反悔
|
||||
|
||||
**用户故事**:在 macOS OTA、开发环境大改或磁盘整理之前,我能留下一个有名字的恢复点;改坏后可以回到之前状态,操作中断也不会弄坏原盘。
|
||||
|
||||
**实现范围**:
|
||||
|
||||
1. 将 M5.7 的**停机快照与一键回滚**作为本任务的核心新增能力:名称、说明、创建时间、历史列表、删除和带确认的回滚;不要求运行中内存热快照。
|
||||
2. 校验可用空间、VM 停机状态和 CoW backing file 链;创建、删除、回滚及磁盘 compact/resize 都要考虑进程中断和空间不足,禁止误删仍被派生盘依赖的基盘。
|
||||
3. 明确“快照不是备份”。先验证数据目录的离线备份与恢复说明;只有用户确实需要跨机器迁移或自动保留策略时,才评估独立导出格式和调度功能。
|
||||
|
||||
**验收证据**:真实执行“创建恢复点 → 修改/升级系统 → 回滚 → 启动并核对应用与文件”;对创建和回滚过程做中断测试,原盘与可用恢复点均不受损。
|
||||
|
||||
**不扩大范围**:在显存和设备状态序列化未经上游验证前,不做运行中内存快照、快照树花哨可视化或 instant clone 承诺。
|
||||
|
||||
### U4(P1):Windows 与 macOS 开发工具可以直接接起来
|
||||
|
||||
**用户故事**:我在 Windows 编辑代码,在 macOS 构建和签名,再从 Windows 浏览器或 IDE 访问客体服务;常用连接可以保存,重启 VM 后仍可使用。
|
||||
|
||||
**实现范围**:
|
||||
|
||||
1. 围绕一条完整链路实现 M5.8:多 TCP 端口转发、端口冲突检测、SSH 终端与 SSH config、VS Code / Cursor Remote-SSH,以及明确开关和一键清除的宿主代理配置。
|
||||
2. 复用已经验收的剪贴板、文件投递和共享目录,把连接入口放在用户执行任务的页面,而不是再增加一个堆满网络参数的“高级中心”。
|
||||
3. 默认仅绑定需要的宿主地址,清楚展示暴露端口和代理状态;CLI 只补这条工作流需要的命令,不追求完整封装所有 QMP 能力。
|
||||
|
||||
**验收证据**:不手写 `--extra-args` 或网络命令,完成「Windows 编辑 → macOS 构建 → Windows 浏览器预览 → 取回日志/产物」,并在 VM 重启后验证连接恢复。
|
||||
|
||||
**不扩大范围**:不为对标通用虚拟机而引入桥接网络、虚拟交换机等子系统;SLIRP 无法覆盖具体任务时再重新评估。
|
||||
|
||||
### U5(按需候选):只有明确场景和验证路径,才进入版本计划
|
||||
|
||||
- **iPhone 真机调试 / 硬件密钥**:先确认目标用户和现有替代办法,再评估 M5.10 的 Windows USB 原型、驱动签名与恢复风险;不直接扩展成全量 USB 直通。
|
||||
- **自动化脚本接口**:先有一个会反复执行的真实流程,例如每日创建干净测试机、运行测试并回收,再设计最小 CLI/API;不为“自动化能力完整”封装全部上游命令。
|
||||
- **独立备份、迁移和保留策略**:先证明离线备份说明不够,再确定格式、兼容与恢复验收;不能只实现“导出”而没有“恢复”测试。
|
||||
- **拖放、无缝窗口、更多客户机系统、企业管理**:暂不排期。只有现有方案被真实任务证明不足,且收益高于维护成本时才重新讨论。
|
||||
|
||||
### 新功能进入迭代前的统一门槛
|
||||
|
||||
1. 写明用户故事、受阻步骤、当前替代办法和不做的后果。
|
||||
2. 优先复用现有 GUI、CLI、Guest Tools 与上游能力,说明为什么不能只靠文档或默认配置解决。
|
||||
3. 同时设计校验、失败恢复、隐私与安全边界;涉及磁盘和身份配置的操作必须可回退或可重建。
|
||||
4. 写明真实用户任务 DoD、测试矩阵和证据形式;只有单元测试的功能保持“已实现”,不得写成“已验收”。
|
||||
5. 发布时核对用户实际获得的稳定资产和文档。P0 任务未通过时,不用新增 P1 功能代替修复。
|
||||
|
||||
---
|
||||
|
||||
## 不做的事
|
||||
|
||||
- **不为功能列表更好看而做功能**:不盲目扩张企业管理、多平台、多客户机或全量 QMP/API 封装;所有新增能力先经过上面的用户任务与验收门槛。
|
||||
- **不维护长期 fork**:对上游的改动只走补丁队列,目标是清零(见 `portable-runtime-spec.md` 第 5 节)。
|
||||
- **不跟踪上游最新 commit**:用户只拿到冒烟过的 `stable`。
|
||||
- **暂不实现 `vphone` 等其他 `Engine`**:接口位置先留着,等 x86 macOS 主线稳定后再说。
|
||||
- **暂不做 TAP / Wi-Fi MacNAT 虚拟网卡驱动安装器**:维护与签名风险高,优先服务好 SLIRP + 多端口转发 + Guest Tools 共享目录。
|
||||
- **暂不强推运行中内存热快照(`savevm`)**:在未验证 `reims-vgpu` 显存与设备状态序列化前,以可靠的停机快照与 CoW 派生为准。
|
||||
- **暂不兼容已淘汰的 `apple-gfx` 旧图形栈**,暂不实现 `vphone` 等其他 `Engine`(接口位置保留)。
|
||||
@@ -43,7 +43,7 @@
|
||||
| 键盘与指针 | 点击窗口时捕获键鼠 | `--capture` | 下次启动 | — |
|
||||
| 串口与日志 | 日志开关、日志级别 | `--logs`、`--log-level` | 下次启动 | 日志在详情页抽屉里实时查看 |
|
||||
| 高级 | 关机等待时间、额外 QEMU 参数、环境变量 | `--stop-timeout`、`--extra-args`、`--env` | 下次启动 | `reims-go` 自己注入的 QMP 参数要和用户填的分开存放、合并写入,不能互相覆盖 |
|
||||
| (VZ 有,上游没有) | 共享目录、剪贴板、vsock | 无 | — | 先不做,界面上也不放占位 |
|
||||
| 宿客协作(Reims-Go 扩展) | ReimsShare、Windows 盘符只读共享、剪贴板 | Guest Tools HTTP/WebDAV,无对应 `reims-ctl` 参数 | 立即生效 | 每台 VM 独立配置;盘符共享默认全部关闭,仅枚举内部固定磁盘,系统盘提示敏感信息风险 |
|
||||
|
||||
## 4. 状态模型
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# UI 审视(2026-11-28)
|
||||
|
||||
> 标准:[dickwu/apple-design-skill](https://github.com/dickwu/apple-design-skill)(MIT;其中 `references/hig/*.md` 为 Apple HIG 原文镜像,版权归 Apple)。按它的五个视角依次看:无障碍 → 平台惯例 → 视觉与工艺 → 交互 → 文案。每条标严重度(Critical / High / Medium / Low),写清现状、依据、改法。
|
||||
> 范围:VM 主页、VM 设置、宿主与运行时、安装包、新建向导。截图取自 `wails dev`,1280×820,浅色与深色两种外观。
|
||||
|
||||
## 结论:需要改进(Needs work)
|
||||
|
||||
没有 Critical。High 有 5 条,集中在两点:
|
||||
|
||||
- **主页什么都想放**。同一份配置在一页里出现三到四次,功能介绍也写在页面上。
|
||||
- **上游原始字符串直接给人看**。
|
||||
|
||||
留白不够,主要不是间距数值的问题,而是内容太多,又层层套框。
|
||||
|
||||
## High
|
||||
|
||||
**H1 · VM 主页信息重复,层级是平的**
|
||||
- 现状:一页从上到下堆了 9 块:标题栏、iMac 主视觉、资源条、提示条、装机引导、Guest Tools 卡片、SSH 行、规格清单、macOS 分组、显示器分组、快捷键条、技术信息。
|
||||
- CPU 型号出现 2 次,「类型」2 次,分辨率 2 次。
|
||||
- 网络在规格清单里写一次(原始字符串),在 SSH 行又写一次。
|
||||
- 依据:`layout.md > Best practices`:把最重要的放在最上方;用留白和分组表达关系;用渐进披露代替堆叠。
|
||||
- 改法:按「关于本机」的模式重排。
|
||||
- 第一屏只留四样:主视觉、名称、一行规格、主操作。
|
||||
- 规格只说一次。
|
||||
- 连接相关(SSH、Guest Tools、共享文件夹)收成一个分组列表。
|
||||
- 原始值全部收进底部的「技术信息」折叠区。
|
||||
|
||||
**H2 · Guest Tools 卡片写成了功能介绍**
|
||||
- 现状:
|
||||
- 第一句是 80 多字的卖点:「免 Xcode/Python 的 Guest Tools 2.0:支持文本 + PNG 截图双向剪贴板(长轮询低延迟)、WebDAV 零双份挂载……」。
|
||||
- 卡片里又套了一层带边框的开关行,下面还有三个并排按钮。
|
||||
- 依据:
|
||||
- `writing.md`:说清楚,删掉多余的字。
|
||||
- `layout.md`:用容器或留白分组,二选一,不要层层套框。
|
||||
- 改法:
|
||||
- 卡片改成分组列表里的普通行:状态写在描述里,操作放右侧。
|
||||
- 安装命令只在工具盘已插入时出现。
|
||||
- 功能介绍删掉,交给 README。
|
||||
|
||||
**H3 · 上游原始字符串直接展示**
|
||||
- 现状:
|
||||
- 网络显示 `user (MAC configured), ssh on 127.0.0.1:2222`。
|
||||
- 类型显示 `x86-64 macOS guest (q35 and OpenCore, WHPX)`。
|
||||
- 设置项标题里直接带 `(REIMS_VGPU_LOG)`、`kernel-irqchip`。
|
||||
- 依据:`writing.md`:标签描述效果,不描述实现。
|
||||
- 改法:
|
||||
- 主界面只用人话:「NAT · SSH 2222」。
|
||||
- 环境变量和参数名放进描述或「技术信息」,标题只保留名词。
|
||||
|
||||
**H4 · 系统原生下拉框和自绘控件混在一起**
|
||||
- 现状:设置「通用」页和新建向导里的 `<select>` 一展开就是 Windows 原生黑底列表,和周围的分段控件、卡片完全不搭(用户截图)。
|
||||
- 依据:`pop-up-buttons.md`:弹出按钮用于一组互斥选项,要给默认值,标签要让人不展开也能预判。
|
||||
- 改法:
|
||||
- 做一个与 macOS 弹出按钮同形的 `PopupSelect`:当前值加 ⌃⌄ 箭头;菜单里当前项带 ✓;次要信息(键盘布局、构建号)用灰字跟在后面。
|
||||
- 全局替换所有 `<select>`。
|
||||
|
||||
**H5 · 窗口和分组标题重复**
|
||||
- 现状:
|
||||
- 设置窗口标题是「macos-tahoe 设置」。
|
||||
- 「通用」页的分组标题「macOS 系统语言」下面,行标题还是「macOS 系统语言」。
|
||||
- 主页标题「关于此虚拟机」正下方是一个更大的「macos-tahoe」。
|
||||
- 依据:
|
||||
- `settings.md`:多页设置窗口的标题就是当前那一页。
|
||||
- `writing.md`:删掉多余的字。
|
||||
- 改法:
|
||||
- 设置窗口标题只写实例名,副标题写状态。
|
||||
- 分组标题和行标题不能同名。
|
||||
- 主页去掉「关于此虚拟机」。
|
||||
|
||||
## Medium
|
||||
|
||||
- **M1 文案没有统一风格**:同一层级里,有的写短语,有的写两三句并用分号连接,还有的夹着 `#123`、`docs/upstream-pr-prep.md` 这种开发者引用。
|
||||
- 规则:标题是名词;描述一句话,说开启后的效果;不写「需支持……的运行时」这类条件链,条件放进禁用原因。
|
||||
- **M2 字号层级太多**:同一页里用了 22 / 16 / 13.5 / 13 / 12 / 11.5 / 11 七档。
|
||||
- 对齐 macOS 文字样式:Large Title 26、Title 3 15、Body 13、Callout 12、Subheadline 11。主页只用其中四档。
|
||||
- **M3 状态说了三遍**:侧栏圆点、主视觉下的胶囊、主按钮文字都在表达同一个状态。保留侧栏和副标题两处即可。
|
||||
- **M4 卡片里再套卡片**:Guest Tools 卡片里的开关行、命令行各自有边框。全局规定框最多一层。
|
||||
- **M5 宿主页**:四个指标卡加五个分组,每组都带灰色提示,看起来很满。指标卡可以保留,提示文字要压到一行以内。
|
||||
- **M6 新建向导**:每个字段下面都有一两行灰字,例如「留空则使用数据目录」这种可以改成占位文字的说明。
|
||||
|
||||
## Low
|
||||
|
||||
- 快捷键条只是普通信息,却装在一个框里。改成页面底部的一行脚注。
|
||||
- 安装包页的「正在读取 Apple 的版本列表…」也放在列表框里,看上去像是一条数据。
|
||||
|
||||
## 做得好的
|
||||
|
||||
- 侧栏图标、分段控件、开关已经有 macOS 的样子;深色和浅色外观都完整。
|
||||
- 设置窗口刚改成分组行加依赖置灰,`pop-up` 以外的控件已经统一。
|
||||
- 主操作每个状态只有一个,符合 `buttons.md`「每个视图一到两个主按钮」。
|
||||
|
||||
## 改版落地
|
||||
|
||||
| 项 | 处理 |
|
||||
| --- | --- |
|
||||
| H1、H2、H3、M3、M4、Low-1 | 重写 `VMPage`:主视觉 → 一行规格 → 操作按钮 → 上下文提示 → 「连接」分组 → 「技术信息」折叠 → 快捷键脚注 |
|
||||
| H4 | 新增 `ui/settings.tsx > PopupSelect`,替换设置和向导中的 `<select>` |
|
||||
| H5、M1 | 设置窗口标题只用实例名;分组标题去重;精简设置、主页、向导文案 |
|
||||
| M2 | 主页只用 26 / 15 / 13 / 12 四档 |
|
||||
| M5、M6、Low-2 | 本轮不做,留作后续 |
|
||||
@@ -258,6 +258,8 @@ macos-tahoe ● 运行中 · 12 分钟 [▣ 显示 VM 窗
|
||||
|
||||
### 7.2 目录结构
|
||||
|
||||
> 现状:没有照这个结构拆分,zustand 也没有引入。实际目录是 `components/`(页面与对话框)、`ui/`(基件封装)、`lib/`(格式化、日志、任务)、`styles/`,状态仍集中在 `App.tsx`。下面是原计划,保留作参考。
|
||||
|
||||
```text
|
||||
src/
|
||||
app/ AppShell, TitleBar, Sidebar, StatusBar
|
||||
@@ -318,7 +320,7 @@ src/
|
||||
|
||||
### 阶段 1:结构改版(约 1 周,需要 B1–B4、B7)
|
||||
|
||||
- 引入 Radix、lucide、zustand,按 7.2 拆分目录。
|
||||
- 引入 Radix、lucide、zustand,按 7.2 拆分目录。(Radix 和 lucide 已在阶段 0 引入;zustand 和目录拆分没有做,见 7.2)
|
||||
- 实现新页头(按状态切换主操作)、「⋯」菜单、右键菜单。
|
||||
- 状态栏 + 任务进度 + 三页签日志面板。
|
||||
- 装机步骤条、概要卡片、技术信息折叠区。
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# 上游 PR 跟进与补丁上游化准备(M4.1 / M4.5)
|
||||
|
||||
> 遵循 [`AGENTS.md`](../AGENTS.md) 规则 4:本仓库不维护长期 fork,所有对上游的改动仅以补丁队列存于 [`patches/`](../patches/),向上游提交 PR 由人工确认执行。
|
||||
|
||||
---
|
||||
|
||||
## 一、上游 Windows 重点 PR 跟踪清单(M4.1)
|
||||
|
||||
目标上游仓库:[`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)(当前稳定运行时基准 commit:`3731afd`)。
|
||||
|
||||
| 上游 PR | 方向 | 价值与影响 | 建议动作 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `#153` | 图形呈现 | Windows NVIDIA MAILBOX 经 FIFO 首帧优化,改善高帧率与首帧延迟 | 合入后 `build-runtime.yml` 每日构建自动产出 `alpha`,再跑冒烟 |
|
||||
| `#152` | 平台层 | 原生 Windows Vulkan 后端,减少 Windows 图形适配开销 | 合入后升级运行时并对比帧率/稳定性 |
|
||||
| `#107` | 图形内存 | 采样纹理回读就地消费,降低显存/内存拷贝开销 | 合入后随运行时一并纳入 |
|
||||
| `#123` | 窗口体验 | `Ctrl+Alt+Enter` 热切全屏 | 合入后在前端文档/帮助提示同步快捷键 |
|
||||
| `#172` | 窗口体验 | Windows 拖动窗口贴合,消除缩放黑边 | 合入后验证高 DPI 与多显示器缩放 |
|
||||
| Win → Command | 键位映射 | 自由指针下 Windows 键映射为 macOS Command | 优先向上游提议/提交 PR,避免长期维护私有补丁 |
|
||||
| `reims-util` `--lang` / `prev-lang:kbd` | 客体语言预设 | `reims-util@7867384` `src/opencore/config.rs:216-228` 硬编码 `prev-lang:kbd=en-US:0` 并置于 `NVRAM > Delete`,导致恢复模式/设置助理强制回退英文 | 短期本仓停机改写 `opencore.qcow2` 并在 `update-opencore` 后重放;长期向上游提议 `opencore --lang` 与重建保留 |
|
||||
|
||||
---
|
||||
|
||||
## 二、待提交上游 PR 的本地补丁证据汇总(M4.5)
|
||||
|
||||
目标上游仓库:[`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)(基准 commit:`4571bc5`),修改文件均为 `target/i386/whpx/whpx-all.c`。
|
||||
|
||||
### PR 1:`whpx: probe TSC deadline on throwaway partition and guard WHvResetPartition`
|
||||
|
||||
- **补丁文件**:[`patches/qemu-whpx-win10-compat.patch`](../patches/qemu-whpx-win10-compat.patch)
|
||||
- **影响环境**:Windows 10 22H2(Build 19045)启用 WHPX 的 x86-64 宿主。
|
||||
- **复现与根因**:
|
||||
1. `whpx_tsc_deadline_refused()`(`target/i386/whpx/whpx-all.c:3211`)在正式 `whpx_global.partition` 上临时创建并删除 vCPU 0;Windows 10 19045 上随后 `whpx_init_vcpu()` 再次为 vCPU 0 调用 `WHvCreateVirtualProcessor` 必现失败,返回 `E_INVALIDARG (0x80070057)`。
|
||||
2. `whpx_set_registers()`(`target/i386/whpx/whpx-all.c:530`)在复位状态直接调用 `whp_dispatch.WHvResetPartition`,但该 API 在 Windows 11 才新增;Windows 10 上函数指针为空,引发空指针解引用崩溃(`0xc0000005`)。
|
||||
- **最小修复**:
|
||||
1. 改在一次性探测 partition 上测试 `WHvX64RegisterTscDeadline`,测完即销毁探测 partition;
|
||||
2. 调用 `WHvResetPartition` 前判断 `whp_dispatch.WHvResetPartition != NULL`。
|
||||
- **实测证据**:已在 Windows 10 19045 真机通过多轮冷启动与日常使用验证(见 `runtime-3731afd` 稳定版运行时)。
|
||||
|
||||
### PR 2:`whpx: forward INIT/SIPI via WHvRequestInterrupt on legacy Windows 10 with kernel-irqchip`
|
||||
|
||||
- **补丁文件**:[`patches/qemu-whpx-win10-startup-ipis.patch`](../patches/qemu-whpx-win10-startup-ipis.patch)(依赖 PR 1)
|
||||
- **影响环境**:Windows 10 19045 开启 `kernel-irqchip=on` 且多核(`smp.max_cpus > 1`)的 macOS 客体。
|
||||
- **复现与根因**:
|
||||
- Win10 上开启 WHPX 内核态 APIC 仿真后,XNU 启动从核(AP)发出的 INIT/SIPI 可能无法唤醒已 halt 的从核,导致客体卡在多核拉起阶段。
|
||||
- **最小修复**:
|
||||
- 仅在 `whpx_is_legacy_os() && whpx_irqchip_in_kernel() && ms->smp.max_cpus > 1` 且宿主支持 `X64ApicInitSipiExitTrap` 时开启捕获,并在 `WHvRunVpExitReasonX64ApicInitSipiTrap` 退出中通过 `WHvRequestInterrupt` 转发 INIT/SIPI(忽略 INIT level deassert)。
|
||||
- **实测证据**:Win10 19045 上 8 核两次冷启动、12 核冷启动均验证 x2APIC、FileVault、SSH 与图形登录通过;客体软重启仍由外层 `AF_UNIX` QMP 监控兜底(待进一步观测纯补丁下软重启行为)。
|
||||
|
||||
### PR 3:`whpx: make nested virtualization property failure non-fatal`
|
||||
|
||||
- **补丁文件**:[`patches/qemu-whpx-nested-virt-nonfatal.patch`](../patches/qemu-whpx-nested-virt-nonfatal.patch)(依赖 PR 1 & PR 2)
|
||||
- **影响环境**:部分 Windows 11 宿主(如 24H2 / Home 或 Core Ultra 200 系列)。
|
||||
- **复现与根因**:
|
||||
- `WHvGetCapability` 返回 `Bank1.NestedVirtSupport = 1`,但实际调用 `WHvSetPartitionProperty(WHvPartitionPropertyCodeNestedVirtualization)` 时返回 `hr=0x80370302`(`WHV_E_UNKNOWN_PROPERTY`)。
|
||||
- 上游原代码(`target/i386/whpx/whpx-all.c:3533-3545`)将该错误当作致命错误直接 `goto error` 中止 VM 启动,迫使用户退回 `kernel-irqchip=off`(损失 Hyper-V 内核态 x2APIC / SynIC 加速)。
|
||||
- **最小修复**:
|
||||
- 将 `error_report` + `goto error` 改为 `warn_report` 并将 `processor_features.Bank1.NestedVirtSupport` 清零,继续保留完整 `kernel-irqchip=on` 启动。
|
||||
- **实测状态**:已在 `Reims-Go` 宿主探测逻辑(`internal/host/whpx_probe_windows.go`)复现 `hr=0x80370302`;带该补丁的 `alpha` 运行时需经真机编译冒烟验证后再提上游 PR(**待验证**)。
|
||||
|
||||
### PR 4:`util/coroutine-windows: reserve 1 MiB stack with 64 KiB initial commit and check fiber creation`
|
||||
|
||||
- **补丁文件**:[`patches/qemu-win32-coroutine-fiber-commit.patch`](../patches/qemu-win32-coroutine-fiber-commit.patch)(独立于 PR 1–3,修改 `util/coroutine-windows.c`)
|
||||
- **影响环境**:Windows 10 / 11 宿主在高并发磁盘 I/O + GPU/VA-API 显存提交叠加场景(如登录 Apple ID 触发 iCloud/Spotlight 并发读盘与 HEVC 硬解)。
|
||||
- **复现与根因**:
|
||||
1. `runtime-3731afd` 真机崩溃日志在 `CPU 0/WHPX` 线程触发 `0xc0000005`(read of `0x0000000000000010`),符号化调用栈为 `execute_ncq_command`(`hw/ide/ahci.c:1096`)→ `blk_aio_prwv`(`block/block-backend.c:1624`)→ `qemu_aio_coroutine_enter`(`util/qemu-coroutine.c:298`)→ `qemu_coroutine_switch`(`util/coroutine-windows.c:58`)→ `KERNELBASE!SwitchToFiber`(`movq 0x10(%rcx), %rax`)。
|
||||
2. `qemu_coroutine_new()`(`util/coroutine-windows.c:78`)调用 `CreateFiber(COROUTINE_STACK_SIZE, ...)`,Windows 会将 `1 MiB` 全部作为初始 Commit Size 立即扣除系统 Commit Charge;当提交内存见底时 `CreateFiber` 返回 `NULL`,原代码未判空即返回并在 `SwitchToFiber(NULL)` 崩溃。
|
||||
3. 同时 `qemu_coroutine_self()`(`util/coroutine-windows.c:99`)直接调用 `ConvertThreadToFiber(NULL)`,若线程已被外部库转为 Fiber 会返回 `NULL`(`ERROR_ALREADY_FIBER`)且同样未检查。
|
||||
- **最小修复**:
|
||||
1. 改用 `CreateFiberEx(64 * 1024, COROUTINE_STACK_SIZE, 0, ...)`,保留完整 1 MiB 栈空间但将每个协程初始提交降为 64 KiB(提交开销降低 16 倍);
|
||||
2. 在 `qemu_coroutine_self()` 中通过 `IsThreadAFiber()` 复用现有 Fiber;
|
||||
3. 对 `co->fiber == NULL` 与 `leader->fiber == NULL` 打印 `GetLastError()` 并显式 `abort()`,杜绝静默空指针解引用。
|
||||
- **实测状态**:补丁已通过 `git apply --check`(基于 `4571bc5`);需编入下一版 `alpha` 运行时并在真机验证登录后高负载场景(**待验证**)。
|
||||
|
||||
---
|
||||
|
||||
## 三、补丁退役检查表
|
||||
|
||||
每当上游合入对应 PR(每日构建会跳过该补丁,并开 issue「Patch queue: patches already upstream」提醒)后:
|
||||
1. 移除 `patches/` 下对应 `.patch` 文件,并同步更新 `patches/series.txt` 与 `patches/README.md`;
|
||||
2. 等下一次每日构建,或手动触发 `.github/workflows/build-runtime.yml`,产出新 `alpha`;
|
||||
3. 在真机运行 `scripts/smoke-runtime.ps1` 并人工确认通过后升级为 `stable`。
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>reims-go</title>
|
||||
<title>Reims-Go</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "reims-go-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.6",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -9,7 +9,9 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"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 @@
|
||||
63074d720d82ba66da97ce3a9813911e
|
||||
f38f2bbc623190aed99c112f7b10c276
|
||||
@@ -8,9 +8,15 @@ importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@fontsource-variable/inter':
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
'@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)
|
||||
@@ -305,6 +311,9 @@ packages:
|
||||
'@floating-ui/utils@0.2.12':
|
||||
resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==}
|
||||
|
||||
'@fontsource-variable/inter@5.3.0':
|
||||
resolution: {integrity: sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==}
|
||||
|
||||
'@jridgewell/gen-mapping@0.3.13':
|
||||
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
|
||||
|
||||
@@ -372,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:
|
||||
@@ -1293,6 +1315,8 @@ snapshots:
|
||||
|
||||
'@floating-ui/utils@0.2.12': {}
|
||||
|
||||
'@fontsource-variable/inter@5.3.0': {}
|
||||
|
||||
'@jridgewell/gen-mapping@0.3.13':
|
||||
dependencies:
|
||||
'@jridgewell/sourcemap-codec': 1.6.0
|
||||
@@ -1355,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
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#3b8cff"/>
|
||||
<stop offset="0.55" stop-color="#2f5bea"/>
|
||||
<stop offset="1" stop-color="#3b1fb8"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="gloss" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#ffffff" stop-opacity="0.28"/>
|
||||
<stop offset="0.45" stop-color="#ffffff" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#6d5dfc"/>
|
||||
<stop offset="0.45" stop-color="#ff7a9a"/>
|
||||
<stop offset="0.8" stop-color="#ffb86b"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="lake" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#2f6bff"/>
|
||||
<stop offset="1" stop-color="#1a2a8f"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="bolt" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#ffe14d"/>
|
||||
<stop offset="1" stop-color="#ff9f0a"/>
|
||||
</linearGradient>
|
||||
<clipPath id="screen">
|
||||
<rect x="252" y="372" width="520" height="318" rx="26"/>
|
||||
</clipPath>
|
||||
<filter id="shadow" x="-20%" y="-20%" width="140%" height="150%">
|
||||
<feDropShadow dx="0" dy="22" stdDeviation="26" flood-color="#0b0d3a" flood-opacity="0.35"/>
|
||||
</filter>
|
||||
<filter id="iconShadow" x="-10%" y="-10%" width="120%" height="125%">
|
||||
<feDropShadow dx="0" dy="14" stdDeviation="16" flood-color="#000000" flood-opacity="0.22"/>
|
||||
</filter>
|
||||
</defs>
|
||||
|
||||
<!-- squircle base -->
|
||||
<g filter="url(#iconShadow)">
|
||||
<rect x="80" y="80" width="864" height="864" rx="200" fill="url(#bg)"/>
|
||||
<rect x="80" y="80" width="864" height="864" rx="200" fill="url(#gloss)"/>
|
||||
</g>
|
||||
|
||||
<!-- VM window -->
|
||||
<g filter="url(#shadow)">
|
||||
<rect x="220" y="268" width="584" height="454" rx="52" fill="#f7f8fc"/>
|
||||
</g>
|
||||
<circle cx="280" cy="322" r="17" fill="#ff5f57"/>
|
||||
<circle cx="332" cy="322" r="17" fill="#febc2e"/>
|
||||
<circle cx="384" cy="322" r="17" fill="#28c840"/>
|
||||
|
||||
<!-- guest display: a lake at dusk -->
|
||||
<g clip-path="url(#screen)">
|
||||
<rect x="252" y="372" width="520" height="318" fill="url(#sky)"/>
|
||||
<circle cx="600" cy="540" r="44" fill="#fff3d6" opacity="0.9"/>
|
||||
<path d="M252 560 L340 470 L400 520 L480 430 L560 505 L620 465 L700 530 L772 480 L772 600 L252 600 Z" fill="#2b2d7a"/>
|
||||
<path d="M252 585 L330 530 L420 575 L500 520 L590 570 L672 535 L772 580 L772 610 L252 610 Z" fill="#1c1f5e"/>
|
||||
<rect x="252" y="598" width="520" height="92" fill="url(#lake)"/>
|
||||
<rect x="560" y="616" width="80" height="6" rx="3" fill="#fff3d6" opacity="0.7"/>
|
||||
<rect x="574" y="636" width="52" height="6" rx="3" fill="#fff3d6" opacity="0.5"/>
|
||||
<rect x="586" y="656" width="28" height="6" rx="3" fill="#fff3d6" opacity="0.35"/>
|
||||
</g>
|
||||
|
||||
<!-- GPU acceleration badge -->
|
||||
<g filter="url(#shadow)">
|
||||
<circle cx="776" cy="724" r="128" fill="#16182e"/>
|
||||
</g>
|
||||
<circle cx="776" cy="724" r="128" fill="none" stroke="#ffffff" stroke-opacity="0.92" stroke-width="16"/>
|
||||
<path d="M800 628 L708 744 L768 744 L748 822 L846 700 L784 700 Z" fill="url(#bolt)" stroke="#ffcf3a" stroke-width="6" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.2 KiB |
@@ -1,28 +1,59 @@
|
||||
import { Minus, Square, X } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { CreateWizard } from './components/CreateWizard'
|
||||
import { Minus, Moon, Square, Sun, X } from 'lucide-react'
|
||||
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { WizardDraft } from './components/CreateWizard'
|
||||
import { DeleteDialog } from './components/DeleteDialog'
|
||||
import { HostView } from './components/HostView'
|
||||
import { CloneDialog } from './components/CloneDialog'
|
||||
import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog'
|
||||
import { SendTextDialog } from './components/SendTextDialog'
|
||||
import type { ThemeMode } from './components/AppSettingsPage'
|
||||
import { LogPanel, LogTab } from './components/LogPanel'
|
||||
import { SettingsModal } from './components/SettingsModal'
|
||||
import { HOST_ID, Sidebar } from './components/Sidebar'
|
||||
import { TitleMenus } from './components/TitleMenus'
|
||||
import { HOST_ID, INSTALLERS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
|
||||
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, Locale, Task, VMDetail } from './types'
|
||||
import { TooltipProvider } from './ui/controls'
|
||||
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 { backend } from './wails'
|
||||
import { api, events } from './wails'
|
||||
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',
|
||||
eject: 'failEject',
|
||||
finishInstall: 'failFinishInstall',
|
||||
enterRecovery: 'failEnterRecovery',
|
||||
attachInstaller: 'failAttachInstaller',
|
||||
attachGuestTools: 'failGuestTools',
|
||||
detachGuestTools: 'failGuestTools',
|
||||
openSharedFolder: 'failOpenFolder',
|
||||
upgradeNVMe: 'failUpgradeNVMe',
|
||||
exportDiagnostics: 'failExportDiagnostics',
|
||||
cloneVM: 'failCloneVM',
|
||||
type: 'failType',
|
||||
sendText: 'failType',
|
||||
delete: 'failDelete',
|
||||
openFolder: 'failOpenFolder',
|
||||
}
|
||||
@@ -31,35 +62,88 @@ 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 [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 {
|
||||
const saved = localStorage.getItem('reims-go-theme')
|
||||
if (saved === 'dark' || saved === 'light') return saved
|
||||
} catch {}
|
||||
return 'system'
|
||||
})
|
||||
const [sysDark, setSysDark] = useState<boolean>(() =>
|
||||
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-color-scheme: dark)').matches,
|
||||
)
|
||||
const theme: 'light' | 'dark' = themeMode === 'system' ? (sysDark ? 'dark' : 'light') : themeMode
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.theme = theme
|
||||
}, [theme])
|
||||
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia?.('(prefers-color-scheme: dark)')
|
||||
if (!mq) return
|
||||
const onChange = (e: MediaQueryListEvent) => setSysDark(e.matches)
|
||||
mq.addEventListener('change', onChange)
|
||||
return () => mq.removeEventListener('change', onChange)
|
||||
}, [])
|
||||
|
||||
const setThemeMode = (mode: ThemeMode) => {
|
||||
setThemeModeState(mode)
|
||||
try {
|
||||
if (mode === 'system') localStorage.removeItem('reims-go-theme')
|
||||
else localStorage.setItem('reims-go-theme', mode)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
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[]>([])
|
||||
const [serialLog, setSerialLog] = useState('')
|
||||
const [qemuLog, setQemuLog] = useState('')
|
||||
const [unseenErrors, setUnseenErrors] = useState(0)
|
||||
const logsOpenRef = useRef(logsOpen)
|
||||
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 backend.getState()
|
||||
const s = await api.GetState()
|
||||
setState(s)
|
||||
setLoadError('')
|
||||
setSelected((cur) => {
|
||||
if (cur === HOST_ID) return cur
|
||||
if (cur === HOST_ID || cur === INSTALLERS_ID || cur === SETTINGS_ID) return cur
|
||||
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))
|
||||
}
|
||||
@@ -67,9 +151,9 @@ export const App: React.FC = () => {
|
||||
|
||||
useEffect(() => {
|
||||
refresh()
|
||||
const offState = backend.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 = backend.onLog((entry) => {
|
||||
const offLog = events.onLog((entry) => {
|
||||
setLogLines((prev) => {
|
||||
const next = appendLog(prev, entry)
|
||||
const last = next[next.length - 1]
|
||||
@@ -80,20 +164,66 @@ export const App: React.FC = () => {
|
||||
})
|
||||
})
|
||||
// Tasks (docs/ui-redesign.md §6 B1): seed from the backend, then follow events.
|
||||
backend.getTasks().then((list) => {
|
||||
api.GetTasks().then((list) => {
|
||||
setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev))
|
||||
}).catch(() => {})
|
||||
const offTask = backend.onTask((task) => onTaskRef.current(task))
|
||||
return () => { offState(); offLog(); offTask() }
|
||||
const offTask = events.onTask((task) => onTaskRef.current(task))
|
||||
// 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])
|
||||
|
||||
const vms = state?.vms ?? []
|
||||
const selectedVM = selected !== HOST_ID ? vms.find((v) => v.name === selected) : undefined
|
||||
const runningVMCount = vms.filter((v) => (state?.transitions[v.name] ?? v.state) === 'running').length
|
||||
const selectedVM = selected !== HOST_ID && selected !== INSTALLERS_ID && selected !== SETTINGS_ID
|
||||
? vms.find((v) => v.name === selected)
|
||||
: undefined
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedVM) { setDetail(null); return }
|
||||
backend.getVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
|
||||
}, [selectedVM?.name, state])
|
||||
api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
|
||||
}, [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(() => {
|
||||
let live = true
|
||||
for (const vm of vms) {
|
||||
api.GetVMNote(vm.name)
|
||||
.then((n) => { if (live) setDisplayNames((m) => ({ ...m, [vm.name]: (n ?? '').trim() })) })
|
||||
.catch(() => {})
|
||||
}
|
||||
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)
|
||||
@@ -103,15 +233,54 @@ export const App: React.FC = () => {
|
||||
|
||||
onTaskRef.current = (task: Task) => {
|
||||
// Toast once per finished download; only live events reach here, not the seed list.
|
||||
if (task.status !== 'running' && task.kind === 'installer-download' && !notifiedTasks.current.has(task.id)) {
|
||||
notifiedTasks.current.add(task.id)
|
||||
if (task.status === 'done') toasts.push({ kind: 'ok', title: tr('toastInstallerReady', { v: task.subject }) })
|
||||
else if (task.status === 'canceled') toasts.push({ kind: 'ok', title: tr('toastDownloadPaused') })
|
||||
else fail(tr('failDownload'), task.error ?? '')
|
||||
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.set(task.id, task.updated_at)
|
||||
const isRuntime = task.kind === 'runtime-install'
|
||||
const isRecovery = task.kind === 'recovery-download'
|
||||
if (task.status === 'done') {
|
||||
if (isRecovery) {
|
||||
toasts.push({ kind: 'ok', title: tr('toastOnlineRecoveryAttached', { name: task.subject }) })
|
||||
refresh()
|
||||
} else {
|
||||
toasts.push({ kind: 'ok', title: isRuntime ? tr('toastRuntimeReady', { v: task.result || task.subject }) : tr('toastInstallerReady', { v: task.subject }) })
|
||||
}
|
||||
} else if (task.status === 'canceled') toasts.push({ kind: 'ok', title: tr('toastDownloadPaused') })
|
||||
else fail(tr(isRuntime ? 'failRuntime' : isRecovery ? 'failAttachInstaller' : 'failDownload'), task.error ?? '')
|
||||
}
|
||||
setTaskMap((prev) => upsertTask(prev, task))
|
||||
}
|
||||
const { task: activeTask, running: runningTasks } = currentTask(taskMap)
|
||||
const runtimeTask = Object.values(taskMap)
|
||||
.filter((x) => x.kind === 'runtime-install')
|
||||
.sort((a, b) => b.updated_at - a.updated_at)[0] ?? null
|
||||
|
||||
const installRuntime = (commit: string) => {
|
||||
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))
|
||||
}
|
||||
const setSource = (source: RuntimeSource) => {
|
||||
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 () => {
|
||||
try {
|
||||
const file = await api.PickFile(tr('importRuntime'), '*.tar.zst;*.zip')
|
||||
if (!file) return
|
||||
await api.InstallRuntimeArchive(file)
|
||||
await refresh()
|
||||
} catch (e) {
|
||||
fail(tr('failRuntime'), e)
|
||||
}
|
||||
}
|
||||
const folderDone = async () => {
|
||||
const s = await api.GetState().catch(() => null)
|
||||
if (s) setState(s)
|
||||
setSetupStage(s?.active_runtime ? null : 'runtime')
|
||||
}
|
||||
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
|
||||
|
||||
const openLogs = (tab: LogTab = 'app') => {
|
||||
setLogTab(tab)
|
||||
@@ -124,15 +293,21 @@ export const App: React.FC = () => {
|
||||
setUnseenErrors(0)
|
||||
}
|
||||
|
||||
const loadSerial = async (name = selectedVM?.name) => {
|
||||
const loadVMLog = async (serial: boolean, name = selectedVM?.name) => {
|
||||
if (!name) return
|
||||
try {
|
||||
setSerialLog(await backend.readVMLogs(name, true))
|
||||
const text = await api.ReadVMLogs(name, serial)
|
||||
if (serial) setSerialLog(text)
|
||||
else setQemuLog(text)
|
||||
} catch (e) {
|
||||
setSerialLog(errText(e))
|
||||
if (serial) setSerialLog(errText(e))
|
||||
else setQemuLog(errText(e))
|
||||
}
|
||||
}
|
||||
|
||||
const loadSerial = (name?: string) => loadVMLog(true, name)
|
||||
const loadQemu = (name?: string) => loadVMLog(false, name)
|
||||
|
||||
const fail = (title: string, e: unknown) =>
|
||||
toasts.push({ kind: 'error', title, description: errText(e), action: { label: tr('viewLogs'), onClick: () => openLogs('app') } })
|
||||
|
||||
@@ -152,25 +327,139 @@ export const App: React.FC = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const onVMAction = (action: VMAction) => {
|
||||
if (!selectedVM) return
|
||||
const name = selectedVM.name
|
||||
// Paste as keystrokes: the backend refuses text a US keyboard can't type
|
||||
// (ErrNotTypeable in type_flow.go), which gets a message of its own.
|
||||
const typeInto = async (name: string, fn: () => Promise<number>) => {
|
||||
setBusy((b) => ({ ...b, [name]: 'type' }))
|
||||
try {
|
||||
const n = await fn()
|
||||
toasts.push({ kind: 'ok', title: tr('toastTyped', { n }) })
|
||||
} catch (e) {
|
||||
if (errText(e).includes('not typeable')) {
|
||||
toasts.push({ kind: 'error', title: tr('failType'), description: tr('typeUntypeable') })
|
||||
} else {
|
||||
fail(tr('failType'), e)
|
||||
}
|
||||
} finally {
|
||||
setBusy((b) => {
|
||||
const { [name]: _, ...rest } = b
|
||||
return rest
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const attachInstaller = async (name: string, running: boolean) => {
|
||||
try {
|
||||
const cached = (await api.ListInstallers()) ?? []
|
||||
const hasCached = cached.some(
|
||||
(x) => !x.partial && (x.kind === 'offline' || x.kind === 'online' || /\.(img|dmg)$/i.test(x.name)),
|
||||
)
|
||||
let picked = ''
|
||||
if (!hasCached) {
|
||||
picked = await api.PickFile(tr('pickRecoveryTitle'), '*.img;*.dmg')
|
||||
if (!picked) {
|
||||
setOnlineRecoveryTarget(name)
|
||||
return
|
||||
}
|
||||
}
|
||||
setBusy((b) => ({ ...b, [name]: 'attachInstaller' }))
|
||||
try {
|
||||
const fileName = await api.AttachInstaller(name, picked)
|
||||
toasts.push({
|
||||
kind: 'ok',
|
||||
title: tr(running ? 'toastInstallerAttachedNextStart' : 'toastInstallerAttached', { name: fileName }),
|
||||
})
|
||||
await refresh()
|
||||
} finally {
|
||||
setBusy((b) => {
|
||||
const { [name]: _, ...rest } = b
|
||||
return rest
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
fail(tr('failAttachInstaller'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => {
|
||||
switch (action) {
|
||||
case 'start': return runVMAction(name, action, () => backend.startVM(name))
|
||||
case 'stop': return runVMAction(name, action, () => backend.stopVM(name, false), tr('toastStopped', { name }))
|
||||
case 'forceStop': return runVMAction(name, action, () => backend.stopVM(name, true), tr('toastStopped', { name }))
|
||||
case 'restart': return runVMAction(name, action, () => backend.restartVM(name))
|
||||
case 'eject': return runVMAction(name, action, () => backend.ejectInstaller(name), tr('toastEjected'))
|
||||
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))
|
||||
case 'eject': return runVMAction(name, action, () => api.EjectInstaller(name), tr('toastEjected'))
|
||||
case 'finishInstall': return runVMAction(name, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished'))
|
||||
case 'enterRecovery': return runVMAction(name, action, () => api.EnterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery'))
|
||||
case 'attachInstaller': return attachInstaller(name, isRunning)
|
||||
case 'attachGuestTools': return runVMAction(name, action, () => api.AttachGuestTools(name), tr(isRunning ? 'toastGuestToolsAttachedNextStart' : 'toastGuestToolsAttached'))
|
||||
case 'detachGuestTools': return runVMAction(name, action, () => api.DetachGuestTools(name), tr(isRunning ? 'toastGuestToolsDetachedNextStart' : 'toastGuestToolsDetached'))
|
||||
case 'openSharedFolder':
|
||||
return api.OpenSharedFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
|
||||
case 'upgradeNVMe':
|
||||
return runVMAction(name, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady'))
|
||||
case 'exportDiagnostics':
|
||||
return runVMAction(name, action, async () => { await api.ExportDiagnostics(name) }, tr('toastDiagExported'))
|
||||
case 'cloneVM':
|
||||
return setCloneSource(name)
|
||||
case 'type': return typeInto(name, () => api.TypeClipboard(name))
|
||||
case 'sendText': return setSendTextTarget(name)
|
||||
case 'openFolder':
|
||||
return backend.openVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
|
||||
return api.OpenVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
|
||||
case 'delete': return setDeleteTarget(name)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
if (name) runVMAction(name, 'delete', () => backend.deleteVM(name, keepFiles), tr('toastDeleted', { name }))
|
||||
if (name) runVMAction(name, 'delete', () => api.DeleteVM(name, keepFiles), tr('toastDeleted', { name }))
|
||||
}
|
||||
|
||||
const confirmOnlineRecovery = () => {
|
||||
const name = onlineRecoveryTarget
|
||||
setOnlineRecoveryTarget(null)
|
||||
if (!name) return
|
||||
api.DownloadAndAttachOnlineRecovery(name, 'latest')
|
||||
.then(() => toasts.push({ kind: 'ok', title: tr('toastOnlineRecoveryStarted') }))
|
||||
.catch((e) => fail(tr('failAttachInstaller'), e))
|
||||
}
|
||||
|
||||
const confirmClone = (cloneName: string) => {
|
||||
const src = cloneSource
|
||||
setCloneSource(null)
|
||||
if (!src) return
|
||||
runVMAction(src, 'cloneVM', async () => {
|
||||
await api.CloneVMCoW(src, cloneName)
|
||||
setSelected(cloneName)
|
||||
}, tr('toastCloned', { name: cloneName }))
|
||||
}
|
||||
|
||||
const openWizard = () => {
|
||||
@@ -179,9 +468,76 @@ export const App: React.FC = () => {
|
||||
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
|
||||
return
|
||||
}
|
||||
setWizardDraft(null)
|
||||
setShowWizard(true)
|
||||
}
|
||||
|
||||
const openWizardWithInstaller = (item: CachedInstaller) => {
|
||||
if (!state?.active_runtime) {
|
||||
setSelected(HOST_ID)
|
||||
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
|
||||
return
|
||||
}
|
||||
const existing = new Set((state.vms ?? []).map((v) => v.name.toLowerCase()))
|
||||
let defaultName = 'macos-tahoe'
|
||||
for (let i = 2; existing.has(defaultName.toLowerCase()); i++) {
|
||||
defaultName = `macos-tahoe-${i}`
|
||||
}
|
||||
const isOffline = item.kind === 'offline' && !!item.version
|
||||
setWizardDraft({
|
||||
step: 1,
|
||||
opts: {
|
||||
name: defaultName,
|
||||
dir: '',
|
||||
source_mode: isOffline ? 'offline' : 'installer',
|
||||
macos: isOffline ? item.version : '',
|
||||
offline: isOffline,
|
||||
installer: isOffline ? '' : item.path,
|
||||
cpus: state.host.logical_cpus >= 12 ? 8 : 4,
|
||||
memory: `${recommendedMemoryGB(state.host)}G`,
|
||||
disk_size: '128G',
|
||||
disk_mode: 'copy',
|
||||
disk_controller: 'nvme',
|
||||
graphics: 'reims-vgpu',
|
||||
gpu: state.host.recommended_gpu?.vulkan_icd ?? 'auto',
|
||||
resolution: recommendedResolution(state.host),
|
||||
displays: 1,
|
||||
borderless: false,
|
||||
capture: false,
|
||||
audio: true,
|
||||
network: !isOffline,
|
||||
ssh_port: 0,
|
||||
logs: true,
|
||||
guest_lang: defaultGuestLang(locale),
|
||||
start: true,
|
||||
},
|
||||
})
|
||||
setShowWizard(true)
|
||||
}
|
||||
|
||||
// The wizard closes as soon as the create starts; progress lives in the status bar
|
||||
// (vm-create task). On failure the toast reopens the wizard with the same answers.
|
||||
const submitCreate = (payload: CreateOpts, draft: WizardDraft) => {
|
||||
setShowWizard(false)
|
||||
setWizardDraft(null)
|
||||
const name = payload.name
|
||||
api.CreateVM(payload)
|
||||
.then(() => {
|
||||
toasts.push({ kind: 'ok', title: tr('toastCreated', { name }) })
|
||||
setSelected(name)
|
||||
return refresh()
|
||||
})
|
||||
.catch((e) => {
|
||||
void refresh()
|
||||
toasts.push({
|
||||
kind: 'error',
|
||||
title: tr('failCreate', { name }),
|
||||
description: errText(e),
|
||||
action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const copy = async (text: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
@@ -192,7 +548,7 @@ export const App: React.FC = () => {
|
||||
}
|
||||
|
||||
const setLang = async (l: Locale) => {
|
||||
await backend.setLocale(l)
|
||||
await api.SetLocale(l)
|
||||
refresh()
|
||||
}
|
||||
|
||||
@@ -200,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) 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)
|
||||
@@ -212,22 +570,124 @@ 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={() => backend.winToggleMaximise()}>
|
||||
<div className="brand">
|
||||
<span className="brand-mark" aria-hidden="true">R</span>
|
||||
reims-go
|
||||
</div>
|
||||
<div className="win-controls" onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<button type="button" className="win-btn" aria-label={tr('minimize')} onClick={() => backend.winMinimise()}><Minus size={14} /></button>
|
||||
<button type="button" className="win-btn" aria-label={tr('maximize')} onClick={() => backend.winToggleMaximise()}><Square size={12} /></button>
|
||||
<button type="button" className="win-btn close" aria-label={tr('closeWindow')} onClick={() => backend.winQuit()}><X size={15} /></button>
|
||||
<header className="titlebar" onDoubleClick={() => WindowToggleMaximise()}>
|
||||
{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
|
||||
type="button"
|
||||
className="theme-toggle"
|
||||
aria-label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}
|
||||
onClick={toggleTheme}
|
||||
>
|
||||
{theme === 'light' ? <Moon size={14} aria-hidden="true" /> : <Sun size={14} aria-hidden="true" />}
|
||||
</button>
|
||||
</Tip>
|
||||
<div className="win-controls">
|
||||
<button type="button" className="win-btn" aria-label={tr('minimize')} onClick={() => WindowMinimise()}><Minus size={14} aria-hidden="true" /></button>
|
||||
<button type="button" className="win-btn" aria-label={tr('maximize')} onClick={() => WindowToggleMaximise()}><Square size={12} aria-hidden="true" /></button>
|
||||
<button type="button" className="win-btn close" aria-label={tr('closeWindow')} onClick={() => api.RequestClose()}><X size={15} aria-hidden="true" /></button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="workspace">
|
||||
{showSetup && state ? (
|
||||
<Suspense fallback={null}>
|
||||
<Setup
|
||||
locale={locale}
|
||||
state={state}
|
||||
stage={state.needs_setup ? 'folder' : 'runtime'}
|
||||
runtimeTask={runtimeTask}
|
||||
onLocale={setLang}
|
||||
onFolderDone={folderDone}
|
||||
onFinish={() => setSetupStage(null)}
|
||||
onError={fail}
|
||||
onChannel={setChannel}
|
||||
onSource={setSource}
|
||||
onInstallRuntime={installRuntime}
|
||||
onCancelTask={cancelTask}
|
||||
onImportRuntime={importRuntime}
|
||||
/>
|
||||
</Suspense>
|
||||
) : (
|
||||
<div className={`workspace${sidebarOpen ? '' : ' sidebar-hidden'}`}>
|
||||
<Sidebar
|
||||
locale={locale}
|
||||
vms={vms}
|
||||
@@ -235,19 +695,37 @@ 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>}
|
||||
</div>
|
||||
) : selected === INSTALLERS_ID ? (
|
||||
<InstallersPage
|
||||
locale={locale}
|
||||
host={state.host}
|
||||
tasks={Object.values(taskMap)}
|
||||
onCreateWithInstaller={openWizardWithInstaller}
|
||||
onError={fail}
|
||||
onToast={(title) => toasts.push({ kind: 'ok', title })}
|
||||
/>
|
||||
) : selectedVM ? (
|
||||
<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}
|
||||
host={state.host}
|
||||
@@ -255,59 +733,119 @@ export const App: React.FC = () => {
|
||||
busyAction={busy[selectedVM.name]}
|
||||
onAction={onVMAction}
|
||||
onSettings={() => setShowSettings(true)}
|
||||
onOpenAffinity={() => setAffinityTarget(selectedVM.name)}
|
||||
onDelete={() => setDeleteTarget(selectedVM.name)}
|
||||
onViewLogs={() => { openLogs('serial'); loadSerial() }}
|
||||
onCopy={copy}
|
||||
onTypeText={(text) => typeInto(selectedVM.name, () => api.TypeText(selectedVM.name, text))}
|
||||
onToggleBorderless={(enabled) => {
|
||||
api.ToggleBorderless(selectedVM.name, enabled)
|
||||
.then(() => {
|
||||
toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastBorderlessNextStart' : 'toastBorderlessUpdated') })
|
||||
return refresh()
|
||||
})
|
||||
.catch((e) => fail(tr('failGeneric'), e))
|
||||
}}
|
||||
onTogglePreventSleep={(enabled) => {
|
||||
api.SetGuestPreventSleep(selectedVM.name, enabled)
|
||||
.then(() => {
|
||||
toasts.push({ kind: 'ok', title: tr(enabled ? 'toastPreventSleepOn' : 'toastPreventSleepOff') })
|
||||
return refresh()
|
||||
})
|
||||
.catch((e) => fail(tr('failGuestTools'), e))
|
||||
}}
|
||||
onDeliverFile={() => {
|
||||
api.DeliverFileToGuest(selectedVM.name)
|
||||
.then((fileName) => {
|
||||
if (fileName) toasts.push({ kind: 'ok', title: tr('toastFileDelivered', { name: fileName }) })
|
||||
})
|
||||
.catch((e) => fail(tr('failGuestTools'), e))
|
||||
}}
|
||||
onToast={(title) => toasts.push({ kind: 'ok', title })}
|
||||
onError={fail}
|
||||
dropping={dropping}
|
||||
/>
|
||||
) : selected === SETTINGS_ID ? (
|
||||
<AppSettingsPage
|
||||
state={state}
|
||||
locale={locale}
|
||||
themeMode={themeMode}
|
||||
onThemeMode={setThemeMode}
|
||||
onSetLocale={setLang}
|
||||
onRefresh={refresh}
|
||||
onError={fail}
|
||||
/>
|
||||
) : (
|
||||
<HostView
|
||||
state={state}
|
||||
locale={locale}
|
||||
onRefresh={refresh}
|
||||
onNewVM={openWizard}
|
||||
onError={fail}
|
||||
onSetLocale={setLang}
|
||||
runtimeTask={runtimeTask}
|
||||
onChannel={setChannel}
|
||||
onSource={setSource}
|
||||
onInstallRuntime={installRuntime}
|
||||
onCancelTask={cancelTask}
|
||||
/>
|
||||
)}
|
||||
</Suspense>
|
||||
</div>
|
||||
|
||||
<LogPanel
|
||||
locale={locale}
|
||||
open={logsOpen}
|
||||
onToggle={toggleLogs}
|
||||
tab={selectedVM ? logTab : 'app'}
|
||||
onTab={(tab) => { setLogTab(tab); if (tab === 'serial') loadSerial() }}
|
||||
lines={logLines}
|
||||
unseenErrors={unseenErrors}
|
||||
onClear={() => setLogLines([])}
|
||||
serialText={serialLog}
|
||||
showSerial={!!selectedVM}
|
||||
onRefreshSerial={() => loadSerial()}
|
||||
task={activeTask}
|
||||
runningTasks={runningTasks}
|
||||
onCancelTask={(id) => { backend.cancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }}
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showWizard && state && (
|
||||
<CreateWizard
|
||||
{!showSetup && (
|
||||
<LogPanel
|
||||
locale={locale}
|
||||
host={state.host}
|
||||
onClose={() => setShowWizard(false)}
|
||||
onCreated={(name) => {
|
||||
setShowWizard(false)
|
||||
setSelected(name)
|
||||
refresh()
|
||||
}}
|
||||
open={logsOpen}
|
||||
onToggle={toggleLogs}
|
||||
tab={selectedVM ? logTab : 'app'}
|
||||
onTab={(tab) => { setLogTab(tab); if (tab === 'serial') loadSerial(); if (tab === 'qemu') loadQemu() }}
|
||||
lines={logLines}
|
||||
unseenErrors={unseenErrors}
|
||||
onClear={() => setLogLines([])}
|
||||
serialText={serialLog}
|
||||
qemuText={qemuLog}
|
||||
showSerial={!!selectedVM}
|
||||
onRefreshSerial={() => loadSerial()}
|
||||
onRefreshQemu={() => loadQemu()}
|
||||
task={activeTask}
|
||||
runningTasks={runningTasks}
|
||||
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}
|
||||
draft={wizardDraft}
|
||||
onClose={() => { setShowWizard(false); setWizardDraft(null) }}
|
||||
onSubmit={submitCreate}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{showSettings && state && detail && (
|
||||
<Suspense fallback={null}>
|
||||
<SettingsModal
|
||||
locale={locale}
|
||||
detail={detail}
|
||||
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)
|
||||
@@ -315,12 +853,72 @@ 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 && (
|
||||
<DeleteDialog locale={locale} name={deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
|
||||
)}
|
||||
|
||||
{cloneSource && (
|
||||
<CloneDialog
|
||||
locale={locale}
|
||||
sourceName={cloneSource}
|
||||
defaultCloneName={`${cloneSource}-clone`}
|
||||
onCancel={() => setCloneSource(null)}
|
||||
onConfirm={confirmClone}
|
||||
/>
|
||||
)}
|
||||
|
||||
{onlineRecoveryTarget && (
|
||||
<OnlineRecoveryDialog
|
||||
locale={locale}
|
||||
name={onlineRecoveryTarget}
|
||||
onCancel={() => setOnlineRecoveryTarget(null)}
|
||||
onConfirm={confirmOnlineRecovery}
|
||||
/>
|
||||
)}
|
||||
|
||||
{sendTextTarget && (
|
||||
<SendTextDialog
|
||||
locale={locale}
|
||||
vmName={sendTextTarget}
|
||||
guestToolsConnected={Boolean(latestVMStats(sendTextTarget)?.guest_tools_connected ?? detail?.guest_tools_connected)}
|
||||
onCancel={() => setSendTextTarget(null)}
|
||||
onConfirm={(text) => {
|
||||
const target = sendTextTarget
|
||||
setSendTextTarget(null)
|
||||
typeInto(target, () => api.TypeText(target, text))
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} />
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import { Download } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
import { AppState, AppUpdateInfo, Locale } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
export type ThemeMode = 'light' | 'dark' | 'system'
|
||||
|
||||
interface Props {
|
||||
state: AppState
|
||||
locale: Locale
|
||||
themeMode: ThemeMode
|
||||
onThemeMode: (mode: ThemeMode) => void
|
||||
onSetLocale: (l: Locale) => void
|
||||
onRefresh: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
export const AppSettingsPage: React.FC<Props> = ({
|
||||
state, locale, themeMode, onThemeMode, onSetLocale, onRefresh, onError,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { host, config, optimizations } = state
|
||||
const [appUpdate, setAppUpdate] = useState<AppUpdateInfo | null>(null)
|
||||
const [checkingUpdate, setCheckingUpdate] = useState(false)
|
||||
const [updateErr, setUpdateErr] = useState('')
|
||||
|
||||
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
|
||||
|
||||
const runUpdateCheck = async (force: boolean) => {
|
||||
setCheckingUpdate(true)
|
||||
setUpdateErr('')
|
||||
try {
|
||||
const info = await api.CheckAppUpdate(force)
|
||||
setAppUpdate(info)
|
||||
} catch (e) {
|
||||
setUpdateErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
setCheckingUpdate(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void runUpdateCheck(false)
|
||||
}, [])
|
||||
|
||||
const guard = (fn: () => Promise<unknown>) => async () => {
|
||||
try {
|
||||
await fn()
|
||||
onRefresh()
|
||||
} catch (e) {
|
||||
onError(tr('failGeneric'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const pickDataRoot = guard(async () => {
|
||||
const dir = await api.PickDirectory(tr('hostDataRoot'))
|
||||
if (dir) await api.SetDataRoot(dir)
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
<div className="page-title"><h1>{tr('sidebarSettings')}</h1></div>
|
||||
</header>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settingsGeneral')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('hostDataRoot')}</div>
|
||||
<div className="row-sub mono">{config.data_root}</div>
|
||||
</div>
|
||||
<div className="row-right"><Button onClick={pickDataRoot}>{tr('choose')}</Button></div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('autoPinPCores')}
|
||||
<span className={`badge ${optBadgeClass(pcoreOpt?.status)}`}>
|
||||
{optStatusLabel(locale, pcoreOpt?.status)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="row-sub">
|
||||
{pcoreOpt?.supported
|
||||
? tr('optPCoreSub', { detail: pcoreOpt.detail ?? `${host.p_core_count}P+${host.e_core_count}E` })
|
||||
: tr('optPCoreUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Switch
|
||||
label={tr('autoPinPCores')}
|
||||
disabled={!pcoreOpt?.supported}
|
||||
checked={!!pcoreOpt?.supported && config.auto_pin_pcores}
|
||||
onChange={(checked) => guard(() => api.SetAutoPinPCores(checked))()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('minimizeToTray')}</div>
|
||||
<div className="row-sub">{tr('minimizeToTraySub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Switch
|
||||
label={tr('minimizeToTray')}
|
||||
checked={config.minimize_to_tray !== false}
|
||||
onChange={(checked) => guard(() => api.SetMinimizeToTray(checked))()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settingsAppearance')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main"><div className="row-title">{tr('themeLabel')}</div></div>
|
||||
<div className="row-right">
|
||||
<Segmented
|
||||
label={tr('themeLabel')}
|
||||
value={themeMode}
|
||||
onChange={onThemeMode}
|
||||
options={[
|
||||
{ value: 'light', label: tr('themeLight') },
|
||||
{ value: 'dark', label: tr('themeDark') },
|
||||
{ value: 'system', label: tr('themeSystem') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main"><div className="row-title">{tr('language')}</div></div>
|
||||
<div className="row-right">
|
||||
<Segmented
|
||||
label={tr('language')}
|
||||
value={locale}
|
||||
onChange={onSetLocale}
|
||||
options={[
|
||||
{ value: 'zh-CN', label: '中文' },
|
||||
{ value: 'en-US', label: 'English' },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settingsAbout')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('appVersionTitle')} <span className="mono">{state.app_version ?? appUpdate?.current ?? 'v0.2.2'}</span>
|
||||
{appUpdate && !appUpdate.has_update && (
|
||||
<span className="badge badge-ok">{tr('appUpToDate')}</span>
|
||||
)}
|
||||
</div>
|
||||
{appUpdate?.has_update ? (
|
||||
<div className="row-sub">{tr('appUpdateAvailable', { v: appUpdate.latest })}</div>
|
||||
) : updateErr ? (
|
||||
<div className="row-sub" title={updateErr}>{tr('appUpdateLookupFailed')}</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{appUpdate?.has_update && (appUpdate.page_url || appUpdate.download_url) ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={<Download size={14} aria-hidden="true" />}
|
||||
onClick={() => guard(() => api.OpenURL(appUpdate.page_url || appUpdate.download_url || ''))()}
|
||||
>
|
||||
{tr('appDownloadUpdate')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button busy={checkingUpdate} onClick={() => void runUpdateCheck(true)}>
|
||||
{tr('appCheckUpdate')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import React, { useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { Locale } from '../types'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
sourceName: string
|
||||
defaultCloneName: string
|
||||
onCancel: () => void
|
||||
onConfirm: (cloneName: string) => void
|
||||
}
|
||||
|
||||
export const CloneDialog: React.FC<Props> = ({ locale, sourceName, defaultCloneName, onCancel, onConfirm }) => {
|
||||
const [cloneName, setCloneName] = useState(defaultCloneName)
|
||||
const trimmed = cloneName.trim()
|
||||
return (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{t(locale, 'cloneTitle', { name: sourceName })}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">
|
||||
{t(locale, 'cloneDesc')}
|
||||
</Alert.Description>
|
||||
<div className="field field-spaced">
|
||||
<label className="field-label" htmlFor="clone-name">{t(locale, 'cloneNameLabel')}</label>
|
||||
<input
|
||||
id="clone-name"
|
||||
className="input mono"
|
||||
value={cloneName}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
onChange={(e) => setCloneName(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' && trimmed) onConfirm(trimmed) }}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn">{t(locale, 'cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-primary" disabled={!trimmed} onClick={() => onConfirm(trimmed)}>
|
||||
{t(locale, 'cloneConfirm')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)
|
||||
}
|
||||
@@ -1,54 +1,113 @@
|
||||
import { Check } from 'lucide-react'
|
||||
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { shortGPUName } from '../lib/format'
|
||||
import { CreateOpts, HostReport, Locale, ValidationIssue } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import {
|
||||
GUEST_LANG_PRESETS,
|
||||
MEMORY_MARKS,
|
||||
controllerLabel,
|
||||
defaultGuestLang,
|
||||
formatMemory,
|
||||
gpuLabel,
|
||||
guestLangLabel,
|
||||
memorySafeLimitGB,
|
||||
parseMemoryGB,
|
||||
recommendedCPUs,
|
||||
hidpiLooksLike,
|
||||
hostDisplayAdvice,
|
||||
hostDisplayDesc,
|
||||
recommendedDisplayPresets,
|
||||
recommendedMemoryGB,
|
||||
recommendedResolution,
|
||||
shortGPUName,
|
||||
splitLangLabel,
|
||||
sshCommand,
|
||||
} from '../lib/format'
|
||||
import { CachedInstaller, CreateOpts, HostReport, Locale, Release, ValidationIssue } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { NumberField, PopupSelect, RangeField, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { backend } from '../wails'
|
||||
import { api } from '../wails'
|
||||
|
||||
/** Reopen the wizard where the user left it (e.g. after a failed create). */
|
||||
export interface WizardDraft {
|
||||
opts: CreateOpts
|
||||
step: number
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
host: HostReport
|
||||
draft?: WizardDraft | null
|
||||
onClose: () => void
|
||||
onCreated: (name: string) => void
|
||||
/** Called with the cleaned payload; the caller runs the create in the background. */
|
||||
onSubmit: (payload: CreateOpts, draft: WizardDraft) => void
|
||||
}
|
||||
|
||||
export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated }) => {
|
||||
const REVIEW_STEP = 5
|
||||
|
||||
// Which wizard step owns each ValidationIssue.field (internal/driver/reims/reims.go ValidateCreate).
|
||||
const STEP_OF_FIELD: Record<string, number> = {
|
||||
installer: 1, disk: 1, macos: 1, guest_lang: 1,
|
||||
cpus: 2, memory: 2,
|
||||
disk_size: 3, disk_controller: 3,
|
||||
graphics: 4, gpu: 4, resolution: 4, displays: 4, ssh_port: 4,
|
||||
}
|
||||
const stepOfIssue = (i: ValidationIssue) => STEP_OF_FIELD[i.field] ?? REVIEW_STEP
|
||||
|
||||
// Step ① as large cards, one per way to get macOS (Parallels / UTM style).
|
||||
const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideIcon; title: I18nKey; sub: I18nKey }[] = [
|
||||
{ mode: 'offline', icon: Package, title: 'srcOfflineTitle', sub: 'srcOfflineSub' },
|
||||
{ mode: 'apple', icon: CloudDownload, title: 'srcAppleTitle', sub: 'srcAppleSub' },
|
||||
{ mode: 'installer', icon: Disc3, title: 'srcInstallerTitle', sub: 'srcInstallerSub' },
|
||||
{ mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' },
|
||||
]
|
||||
|
||||
export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, onSubmit }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [step, setStep] = useState(1)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [step, setStep] = useState(draft?.step ?? 1)
|
||||
// Once the user has reached the review step, keep validating so step markers stay current.
|
||||
const [reviewed, setReviewed] = useState(draft?.step === REVIEW_STEP)
|
||||
const [checking, setChecking] = useState(false)
|
||||
const [err, setErr] = useState('')
|
||||
const [issues, setIssues] = useState<ValidationIssue[]>([])
|
||||
const [cmdPreview, setCmdPreview] = useState('')
|
||||
|
||||
const [opts, setOpts] = useState<CreateOpts>({
|
||||
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
|
||||
name: 'macos-tahoe',
|
||||
dir: '',
|
||||
source_mode: 'apple',
|
||||
macos: 'tahoe',
|
||||
// Offline by default: one exact release that installs with no network
|
||||
// (roadmap M2.3; `reims-ctl create --help`, upstream 3731afd).
|
||||
source_mode: 'offline',
|
||||
macos: '',
|
||||
offline: true,
|
||||
installer: '',
|
||||
cpus: host.logical_cpus >= 12 ? 8 : 4,
|
||||
memory: host.total_ram_gb >= 24 ? '16G' : '8G',
|
||||
cpus: recommendedCPUs(host),
|
||||
memory: `${recommendedMemoryGB(host)}G`,
|
||||
disk_size: '128G',
|
||||
disk: '',
|
||||
disk_mode: 'copy',
|
||||
disk_controller: 'nvme',
|
||||
graphics: 'reims-vgpu',
|
||||
gpu: host.recommended_gpu?.vulkan_icd ?? 'auto',
|
||||
resolution: '1920x1080',
|
||||
resolution: recommendedResolution(host),
|
||||
displays: 1,
|
||||
borderless: false,
|
||||
capture: false,
|
||||
audio: true,
|
||||
network: true,
|
||||
network: false,
|
||||
ssh_port: 0,
|
||||
logs: true,
|
||||
guest_lang: defaultGuestLang(locale),
|
||||
start: true,
|
||||
})
|
||||
const set = (patch: Partial<CreateOpts>) => setOpts((o) => ({ ...o, ...patch }))
|
||||
|
||||
const buildPayload = (): CreateOpts => {
|
||||
const p: CreateOpts = { ...opts }
|
||||
if (p.source_mode === 'apple') {
|
||||
const p: CreateOpts = { ...opts, offline: opts.source_mode === 'offline' }
|
||||
if (p.source_mode === 'offline') {
|
||||
p.installer = ''
|
||||
p.disk = ''
|
||||
} else if (p.source_mode === 'apple') {
|
||||
p.installer = ''
|
||||
p.disk = ''
|
||||
} else if (p.source_mode === 'installer') {
|
||||
@@ -63,68 +122,89 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (step !== 5) return
|
||||
const payload = buildPayload()
|
||||
Promise.all([backend.validateCreate(payload), backend.previewCreate(payload)])
|
||||
.then(([iss, cmd]) => {
|
||||
setIssues(iss ?? [])
|
||||
setCmdPreview(cmd)
|
||||
if (step === REVIEW_STEP) setReviewed(true)
|
||||
}, [step])
|
||||
|
||||
// Offline releases come from Apple's catalog (a few seconds); downloaded ones are marked.
|
||||
const [releases, setReleases] = useState<Release[] | null>(null)
|
||||
const [cached, setCached] = useState<CachedInstaller[]>([])
|
||||
const [releasesErr, setReleasesErr] = useState('')
|
||||
useEffect(() => {
|
||||
if (opts.source_mode !== 'offline' || releases) return
|
||||
let live = true
|
||||
api.ListInstallers().then((l) => { if (live) setCached(l ?? []) }).catch(() => {})
|
||||
api.ListOfflineReleases()
|
||||
.then((list) => {
|
||||
if (!live) return
|
||||
setReleases(list ?? [])
|
||||
if (!opts.macos && list && list.length > 0) set({ macos: list[0].version })
|
||||
})
|
||||
.catch((e) => setErr(String(e)))
|
||||
}, [step, opts])
|
||||
.catch((e) => { if (live) setReleasesErr(String(e).replace(/^Error:\s*/, '')) })
|
||||
return () => { live = false }
|
||||
}, [opts.source_mode])
|
||||
const isCached = (v: string) => cached.some((c) => c.kind === 'offline' && !c.partial && c.version === v)
|
||||
const chosenRelease = releases?.find((r) => r.version === opts.macos)
|
||||
// reims-util pre-allocates the whole image as it starts (19.7 GB for an 18.4 GB release, measured).
|
||||
const needGB = chosenRelease && !isCached(chosenRelease.version) ? Math.ceil((chosenRelease.size * 1.1) / 1e9) : 0
|
||||
|
||||
useEffect(() => {
|
||||
if (!reviewed && step !== REVIEW_STEP) return
|
||||
let live = true
|
||||
setChecking(true)
|
||||
const timer = setTimeout(() => {
|
||||
const payload = buildPayload()
|
||||
Promise.all([api.ValidateCreate(payload), api.PreviewCreate(payload)])
|
||||
.then(([iss, cmd]) => {
|
||||
if (!live) return
|
||||
setIssues(iss ?? [])
|
||||
setCmdPreview(cmd)
|
||||
setErr('')
|
||||
})
|
||||
.catch((e) => { if (live) setErr(String(e).replace(/^Error:\s*/, '')) })
|
||||
.finally(() => { if (live) setChecking(false) })
|
||||
}, 200)
|
||||
return () => { live = false; clearTimeout(timer) }
|
||||
}, [step, reviewed, opts])
|
||||
|
||||
const pickDir = async () => {
|
||||
const dir = await backend.pickDirectory(tr('vmDir'))
|
||||
const dir = await api.PickDirectory(tr('vmDir'))
|
||||
if (dir) set({ dir })
|
||||
}
|
||||
|
||||
const pickFile = async (field: 'installer' | 'disk', pattern: string) => {
|
||||
const f = await backend.pickFile(tr(field === 'installer' ? 'sourceInstaller' : 'sourceDisk'), pattern)
|
||||
const f = await api.PickFile(tr(field === 'installer' ? 'sourceInstaller' : 'sourceDisk'), pattern)
|
||||
if (f) set({ [field]: f })
|
||||
}
|
||||
|
||||
const handleCreate = async () => {
|
||||
setErr('')
|
||||
setBusy(true)
|
||||
try {
|
||||
const payload = buildPayload()
|
||||
await backend.createVM(payload)
|
||||
onCreated(payload.name)
|
||||
} catch (e) {
|
||||
setErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
const handleCreate = () => onSubmit(buildPayload(), { opts, step: REVIEW_STEP })
|
||||
const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : [])
|
||||
|
||||
const realGPUs = (host.gpus ?? []).filter((g) => g.kind !== 'virtual')
|
||||
const threads = Math.max(host.logical_cpus || 0, 1)
|
||||
const cpuRec = recommendedCPUs(host)
|
||||
const memRec = recommendedMemoryGB(host)
|
||||
const memSafe = memorySafeLimitGB(host)
|
||||
const memMax = Math.max(Math.floor((host.total_ram_gb || 16) * 0.85), memRec, 4)
|
||||
const memGB = Math.round(parseMemoryGB(opts.memory) ?? memRec)
|
||||
const steps: I18nKey[] = ['step1', 'step2', 'step3', 'step4', 'step5']
|
||||
|
||||
const presets = <T extends string | number>(values: T[], current: T | undefined, label: (v: T) => string, pick: (v: T) => void) => (
|
||||
<div className="presets">
|
||||
{values.map((v) => (
|
||||
<button key={v} type="button" className="preset" aria-pressed={current === v} onClick={() => pick(v)}>
|
||||
{label(v)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<Modal title={tr('wizardTitle')} closeLabel={tr('close')} dismissable={!busy} onClose={onClose}>
|
||||
<Modal className="wizard-dialog" title={tr('wizardTitle')} closeLabel={tr('close')} onClose={onClose}>
|
||||
<nav className="wizard-steps" aria-label={tr('wizardTitle')}>
|
||||
{steps.map((key, idx) => {
|
||||
const n = idx + 1
|
||||
const bad = issueSteps.has(n) && n !== REVIEW_STEP
|
||||
const done = !bad && (step > n || (reviewed && n < REVIEW_STEP))
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
className={`wizard-step${step > n ? ' done' : ''}`}
|
||||
className={`wizard-step${done ? ' done' : ''}${bad ? ' has-issue' : ''}`}
|
||||
aria-current={step === n ? 'step' : undefined}
|
||||
disabled={busy}
|
||||
onClick={() => setStep(n)}
|
||||
>
|
||||
{step > n && <Check size={12} />}
|
||||
{bad ? <CircleAlert size={12} /> : done && <Check size={12} />}
|
||||
{tr(key)}
|
||||
</button>
|
||||
)
|
||||
@@ -134,220 +214,521 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, onClose, onCreated
|
||||
<div className="dialog-body">
|
||||
{err && <div className="notice notice-error">{err}</div>}
|
||||
|
||||
<div key={step} className="step-anim">
|
||||
{step === 1 && (
|
||||
<>
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-name">{tr('vmName')}</label>
|
||||
<input id="vm-name" className="input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />
|
||||
<div className="source-cards" role="radiogroup" aria-label={tr('step1')}>
|
||||
{SOURCES.map((s) => {
|
||||
const Icon = s.icon
|
||||
const on = opts.source_mode === s.mode
|
||||
return (
|
||||
<label key={s.mode} className="source-card" data-selected={on || undefined}>
|
||||
<input
|
||||
type="radio"
|
||||
name="source"
|
||||
checked={on}
|
||||
onChange={() => set({
|
||||
source_mode: s.mode,
|
||||
network: s.mode !== 'offline',
|
||||
...(s.mode === 'apple' ? { macos: 'tahoe' } : {}),
|
||||
...(s.mode === 'offline' ? { macos: releases?.[0]?.version ?? '' } : {}),
|
||||
})}
|
||||
/>
|
||||
<span className={`source-icon source-icon-${s.mode}`} aria-hidden="true"><Icon size={20} /></span>
|
||||
<span className="source-title">
|
||||
{tr(s.title)}
|
||||
{s.mode === 'offline' && <span className="badge badge-accent">{tr('recommendedBadge')}</span>}
|
||||
</span>
|
||||
<span className="source-sub">{tr(s.sub)}</span>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-dir">{tr('vmDir')}</label>
|
||||
<div className="input-group">
|
||||
<input id="vm-dir" className="input mono" value={opts.dir ?? ''} onChange={(e) => set({ dir: e.target.value })} />
|
||||
<Button onClick={pickDir}>{tr('choose')}</Button>
|
||||
</div>
|
||||
<span className="hint">{tr('vmDirHint')}</span>
|
||||
</div>
|
||||
|
||||
<fieldset className="field choices fieldset">
|
||||
<legend className="field-label">{tr('step1')}</legend>
|
||||
{(['apple', 'installer', 'disk'] as const).map((mode) => (
|
||||
<label key={mode} className="choice">
|
||||
<input
|
||||
type="radio"
|
||||
name="source"
|
||||
checked={opts.source_mode === mode}
|
||||
onChange={() => set({ source_mode: mode, ...(mode === 'apple' ? { macos: opts.macos || 'tahoe' } : {}) })}
|
||||
<SetGroup>
|
||||
{opts.source_mode === 'apple' && (
|
||||
<SetRow
|
||||
title={tr('macosVersion')}
|
||||
control={<PopupSelect id="vm-macos" label={tr('macosVersion')} value={opts.macos} onChange={(macos) => set({ macos })} options={[{ value: 'tahoe', label: 'macOS Tahoe' }]} />}
|
||||
/>
|
||||
)}
|
||||
{opts.source_mode === 'offline' && (
|
||||
<SetRow
|
||||
title={tr('macosVersion')}
|
||||
desc={releasesErr
|
||||
? <span className="warn-text">{tr('offlineListFailed')}:{releasesErr}</span>
|
||||
: needGB > 0 && host.free_disk_gb > 0 && host.free_disk_gb < needGB + 10
|
||||
? <span className="warn-text">{tr('offlineSpaceWarn', { free: host.free_disk_gb.toFixed(0), need: needGB })}</span>
|
||||
: tr('offlineHint')}
|
||||
control={!releases
|
||||
? <span className="muted">{releasesErr ? '—' : tr('offlineLoading')}</span>
|
||||
: (
|
||||
<PopupSelect
|
||||
id="vm-release"
|
||||
label={tr('macosVersion')}
|
||||
value={opts.macos}
|
||||
onChange={(macos) => set({ macos })}
|
||||
options={releases.map((r) => ({
|
||||
value: r.version,
|
||||
label: `macOS ${r.version}`,
|
||||
detail: `${(r.size / 1e9).toFixed(1)} GB${isCached(r.version) ? ` · ${tr('offlineCached')}` : ''}`,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{(opts.source_mode === 'installer' || opts.source_mode === 'disk') && (() => {
|
||||
const isInstaller = opts.source_mode === 'installer'
|
||||
const file = (isInstaller ? opts.installer : opts.disk) ?? ''
|
||||
return (
|
||||
<SetRow
|
||||
title={tr(isInstaller ? 'srcInstallerTitle' : 'srcDiskTitle')}
|
||||
desc={file ? <span className="mono path-text" title={file}>{file}</span> : tr('wizNoFile')}
|
||||
control={
|
||||
<Button onClick={() => (isInstaller
|
||||
? pickFile('installer', '*.img;*.dmg')
|
||||
: pickFile('disk', '*.qcow2;*.img;*.vmdk;*.raw'))}
|
||||
>
|
||||
{tr('wizChooseFile')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{tr(mode === 'apple' ? 'sourceApple' : mode === 'installer' ? 'sourceInstaller' : 'sourceDisk')}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
|
||||
{opts.source_mode === 'apple' && (
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-macos">{tr('macosVersion')}</label>
|
||||
<select id="vm-macos" className="select" value={opts.macos} onChange={(e) => set({ macos: e.target.value })}>
|
||||
<option value="tahoe">{tr('macosTahoe')}</option>
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{opts.source_mode !== 'apple' && (
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-src">
|
||||
{tr(opts.source_mode === 'installer' ? 'sourceInstaller' : 'sourceDisk')}
|
||||
</label>
|
||||
<div className="input-group">
|
||||
<input
|
||||
id="vm-src"
|
||||
className="input mono"
|
||||
value={(opts.source_mode === 'installer' ? opts.installer : opts.disk) ?? ''}
|
||||
onChange={(e) => set(opts.source_mode === 'installer' ? { installer: e.target.value } : { disk: e.target.value })}
|
||||
)
|
||||
})()}
|
||||
<SetRow
|
||||
title={tr('guestLangShort')}
|
||||
desc={tr('guestLangHint')}
|
||||
control={
|
||||
<PopupSelect
|
||||
id="vm-guest-lang"
|
||||
label={tr('guestLangShort')}
|
||||
value={opts.guest_lang || defaultGuestLang(locale)}
|
||||
onChange={(guest_lang) => set({ guest_lang })}
|
||||
options={GUEST_LANG_PRESETS.map((p) => splitLangLabel(p.value, locale === 'zh-CN' ? p.zh : p.en))}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => (opts.source_mode === 'installer'
|
||||
? pickFile('installer', '*.img;*.dmg')
|
||||
: pickFile('disk', '*.qcow2;*.img'))}
|
||||
>
|
||||
{tr('choose')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
}
|
||||
/>
|
||||
</SetGroup>
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<>
|
||||
<div className="field">
|
||||
<span className="field-label">{tr('factCPU')} · {tr('hostThreads', { n: host.logical_cpus })}</span>
|
||||
{presets(
|
||||
[4, 6, 8, 12].filter((n) => n <= Math.max(host.logical_cpus, 4)),
|
||||
opts.cpus,
|
||||
(n) => tr('cores', { n }),
|
||||
(cpus) => set({ cpus }),
|
||||
)}
|
||||
<span className="hint">{tr('cpuHint')}</span>
|
||||
</div>
|
||||
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-mem">{tr('factMemory')} · {tr('hostMemory', { n: host.total_ram_gb.toFixed(0) })}</label>
|
||||
{presets(['4G', '8G', '12G', '16G', '24G'], opts.memory, (m) => m, (memory) => set({ memory }))}
|
||||
<input id="vm-mem" className="input" value={opts.memory} onChange={(e) => set({ memory: e.target.value })} />
|
||||
<span className="hint">{tr('memHint')}</span>
|
||||
</div>
|
||||
</>
|
||||
<SetGroup>
|
||||
<SetRow
|
||||
title={tr('vcpus')}
|
||||
desc={(opts.cpus ?? 0) > threads - 2 && threads > 2
|
||||
? <span className="warn-text">{tr('cpuOverHint')}</span>
|
||||
: tr('cpuRecHint', { rec: cpuRec, n: threads })}
|
||||
block={
|
||||
<RangeField
|
||||
label={tr('vcpus')}
|
||||
value={opts.cpus ?? cpuRec}
|
||||
min={1}
|
||||
max={threads}
|
||||
unit={tr('coresUnit')}
|
||||
onChange={(cpus) => set({ cpus })}
|
||||
recommend={[Math.min(4, cpuRec), cpuRec]}
|
||||
warnFrom={threads > 2 ? threads - 1 : undefined}
|
||||
marks={[1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 64].concat(threads).map((n) => ({ value: n, label: String(n) }))}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('guestMemory')}
|
||||
desc={memGB > memSafe
|
||||
? <span className="warn-text">{tr('memOverHint')}</span>
|
||||
: host.commit_avail_gb > 0
|
||||
? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: memRec })
|
||||
: tr('memRecHint', { rec: memRec, n: host.total_ram_gb.toFixed(0) })}
|
||||
block={
|
||||
<RangeField
|
||||
label={tr('guestMemory')}
|
||||
value={memGB}
|
||||
min={2}
|
||||
max={memMax}
|
||||
unit="GB"
|
||||
onChange={(gb) => set({ memory: `${gb}G` })}
|
||||
recommend={[Math.min(4, memRec), memRec]}
|
||||
warnFrom={memSafe + 1}
|
||||
marks={MEMORY_MARKS.concat(memMax).map((n) => ({ value: n, label: String(n) }))}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SetGroup>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
opts.source_mode !== 'disk' ? (
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-disk">{tr('diskSize')}</label>
|
||||
{presets(['64G', '128G', '256G', '512G'], opts.disk_size, (s) => s, (disk_size) => set({ disk_size }))}
|
||||
<input id="vm-disk" className="input" value={opts.disk_size ?? ''} onChange={(e) => set({ disk_size: e.target.value })} />
|
||||
<span className="hint">{tr('diskSizeHint')}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-diskmode">{tr('diskMode')}</label>
|
||||
<select
|
||||
id="vm-diskmode"
|
||||
className="select"
|
||||
value={opts.disk_mode}
|
||||
onChange={(e) => set({ disk_mode: e.target.value as 'copy' | 'in-place' })}
|
||||
>
|
||||
<option value="copy">{tr('diskModeCopy')}</option>
|
||||
<option value="in-place">{tr('diskModeInPlace')}</option>
|
||||
</select>
|
||||
</div>
|
||||
)
|
||||
<SetGroup>
|
||||
{opts.source_mode !== 'disk' ? (
|
||||
<SetRow
|
||||
title={tr('diskSize')}
|
||||
desc={tr('diskSizeHint')}
|
||||
control={
|
||||
<Segmented
|
||||
label={tr('diskSize')}
|
||||
value={opts.disk_size}
|
||||
onChange={(disk_size) => set({ disk_size })}
|
||||
options={Array.from(new Set(['64G', '128G', '256G', '512G', opts.disk_size ?? '128G'])).map((v) => ({ value: v, label: formatMemory(v) }))}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<SetRow
|
||||
title={tr('diskMode')}
|
||||
control={
|
||||
<Segmented
|
||||
label={tr('diskMode')}
|
||||
value={opts.disk_mode}
|
||||
onChange={(disk_mode) => set({ disk_mode })}
|
||||
options={[
|
||||
{ value: 'copy' as const, label: tr('diskModeCopy') },
|
||||
{ value: 'in-place' as const, label: tr('diskModeInPlace') },
|
||||
]}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<SetRow
|
||||
title={tr('diskController')}
|
||||
desc={tr('diskControllerNvmeHint')}
|
||||
control={
|
||||
<Segmented
|
||||
label={tr('diskController')}
|
||||
value={opts.disk_controller ?? 'nvme'}
|
||||
onChange={(disk_controller) => set({ disk_controller })}
|
||||
options={[
|
||||
{ value: 'nvme' as const, label: 'NVMe' },
|
||||
{ value: 'ahci' as const, label: 'SATA' },
|
||||
...(opts.source_mode === 'disk' ? [{ value: 'virtio' as const, label: 'VirtIO' }] : []),
|
||||
]}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SetGroup>
|
||||
)}
|
||||
|
||||
{step === 4 && (
|
||||
<>
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-gfx">{tr('graphicsBackend')}</label>
|
||||
<select
|
||||
id="vm-gfx"
|
||||
className="select"
|
||||
value={opts.graphics}
|
||||
onChange={(e) => set({ graphics: e.target.value as 'reims-vgpu' | 'vmware-svga' })}
|
||||
>
|
||||
<option value="reims-vgpu">{tr('graphicsReims')}</option>
|
||||
<option value="vmware-svga">{tr('graphicsSvga')}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{opts.graphics === 'reims-vgpu' && (
|
||||
<>
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-gpu">{tr('gpuSelect')}</label>
|
||||
<select id="vm-gpu" className="select" value={opts.gpu} onChange={(e) => set({ gpu: e.target.value })}>
|
||||
<option value="auto">{tr('gpuAutoOption')}</option>
|
||||
{realGPUs.map((g) => (
|
||||
<option key={g.vulkan_icd} value={g.vulkan_icd}>{shortGPUName(g.name)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="field-row">
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-res">{tr('resolution')}</label>
|
||||
<select id="vm-res" className="select" value={opts.resolution} onChange={(e) => set({ resolution: e.target.value })}>
|
||||
<option value="1920x1080">1920 × 1080</option>
|
||||
<option value="2560x1440">2560 × 1440</option>
|
||||
<option value="2880x1800">2880 × 1800 HiDPI</option>
|
||||
<option value="3840x2160">3840 × 2160 HiDPI</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-displays">{tr('displays')}</label>
|
||||
<select id="vm-displays" className="select" value={opts.displays} onChange={(e) => set({ displays: Number(e.target.value) })}>
|
||||
{[1, 2, 3, 4].map((d) => <option key={d} value={d}>{d}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="field">
|
||||
<label className="field-label" htmlFor="vm-ssh">{tr('sshPort')}</label>
|
||||
<input
|
||||
id="vm-ssh"
|
||||
className="input"
|
||||
type="number"
|
||||
min={0}
|
||||
max={65535}
|
||||
value={opts.ssh_port ?? 0}
|
||||
onChange={(e) => set({ ssh_port: Number(e.target.value) })}
|
||||
<SetGroup title={tr('groupGraphics')}>
|
||||
<SetRow
|
||||
title={tr('graphicsBackend')}
|
||||
desc={opts.graphics === 'vmware-svga' ? tr('graphicsSvgaDesc') : tr('graphicsReimsDesc')}
|
||||
control={
|
||||
<Segmented
|
||||
label={tr('graphicsBackend')}
|
||||
value={opts.graphics}
|
||||
onChange={(graphics) => set({ graphics })}
|
||||
options={[
|
||||
{ value: 'reims-vgpu' as const, label: tr('graphicsReimsShort') },
|
||||
{ value: 'vmware-svga' as const, label: tr('graphicsSvgaShort') },
|
||||
]}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<span className="hint">{tr('sshPortHint')}</span>
|
||||
</div>
|
||||
<SetRow
|
||||
title={tr('gpuSelect')}
|
||||
disabled={opts.graphics !== 'reims-vgpu'}
|
||||
reason={tr('gpuSvgaReason')}
|
||||
desc={realGPUs.length === 0 ? <span className="warn-text">{tr('gpuUnavailableHint')}</span> : undefined}
|
||||
control={
|
||||
<PopupSelect
|
||||
id="vm-gpu"
|
||||
label={tr('gpuSelect')}
|
||||
value={opts.gpu}
|
||||
onChange={(gpu) => set({ gpu })}
|
||||
options={[
|
||||
{ value: 'auto', label: tr('gpuAutoTitle'), detail: host.recommended_gpu ? shortGPUName(host.recommended_gpu.name) : undefined },
|
||||
...realGPUs.map((g) => ({ value: g.vulkan_icd, label: shortGPUName(g.name) })),
|
||||
]}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('resolution')}
|
||||
disabled={opts.graphics !== 'reims-vgpu'}
|
||||
reason={tr('gpuSvgaReason')}
|
||||
desc={[hostDisplayDesc(host, tr), hostDisplayAdvice(host, tr)].filter(Boolean).join(' · ') || undefined}
|
||||
control={
|
||||
<PopupSelect
|
||||
id="vm-res"
|
||||
label={tr('resolution')}
|
||||
value={opts.resolution}
|
||||
onChange={(resolution) => set({ resolution })}
|
||||
options={recommendedDisplayPresets(host).map((p) => ({
|
||||
value: p.resolution,
|
||||
label: p.label,
|
||||
detail: [p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '', p.recommended ? tr('recommendedBadge') : ''].filter(Boolean).join(' · ') || undefined,
|
||||
}))}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('displays')}
|
||||
disabled={opts.graphics !== 'reims-vgpu'}
|
||||
reason={tr('gpuSvgaReason')}
|
||||
control={
|
||||
<Segmented
|
||||
label={tr('displays')}
|
||||
value={opts.displays}
|
||||
onChange={(displays) => set({ displays })}
|
||||
options={[1, 2, 3, 4].map((d) => ({ value: d, label: String(d) }))}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SetGroup>
|
||||
|
||||
<div className="choices">
|
||||
{([
|
||||
['audio', 'enableAudio'],
|
||||
['network', 'enableNetwork'],
|
||||
['logs', 'enableLogs'],
|
||||
['start', 'startAfterCreate'],
|
||||
] as const).map(([key, label]) => (
|
||||
<label key={key} className="choice">
|
||||
<input type="checkbox" checked={!!opts[key]} onChange={(e) => set({ [key]: e.target.checked })} />
|
||||
{tr(label)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<SetGroup title={tr('wizOptions')}>
|
||||
<SetRow
|
||||
title={tr('networkTitle')}
|
||||
desc={opts.source_mode === 'offline' ? tr('networkOfflineHint') : tr('networkDesc')}
|
||||
control={<Switch label={tr('networkTitle')} checked={!!opts.network} onChange={(network) => set({ network })} />}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('sshForward')}
|
||||
desc={(opts.ssh_port ?? 0) > 0 ? <code className="inline-code">{sshCommand(opts.ssh_port ?? 0)}</code> : tr('sshOffDesc')}
|
||||
disabled={!opts.network}
|
||||
reason={tr('sshNeedsNetwork')}
|
||||
control={
|
||||
<div className="hstack">
|
||||
{(opts.ssh_port ?? 0) > 0 && (
|
||||
<NumberField label={tr('sshPort')} value={opts.ssh_port ?? 0} min={1} max={65535} onChange={(ssh_port) => set({ ssh_port })} />
|
||||
)}
|
||||
<Switch label={tr('sshForward')} checked={(opts.ssh_port ?? 0) > 0} onChange={(on) => set({ ssh_port: on ? 2222 : 0 })} />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('enableAudio')}
|
||||
control={<Switch label={tr('enableAudio')} checked={!!opts.audio} onChange={(audio) => set({ audio })} />}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('captureInput')}
|
||||
desc={tr('captureInputHint')}
|
||||
control={<Switch label={tr('captureInput')} checked={!!opts.capture} onChange={(capture) => set({ capture })} />}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('fullscreenLaunch')}
|
||||
desc={tr('fullscreenLaunchHint')}
|
||||
control={<Switch label={tr('fullscreenLaunch')} checked={!!opts.borderless} onChange={(borderless) => set({ borderless })} />}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('enableLogs')}
|
||||
control={<Switch label={tr('enableLogs')} checked={!!opts.logs} onChange={(logs) => set({ logs })} />}
|
||||
/>
|
||||
</SetGroup>
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === 5 && (
|
||||
<>
|
||||
{issues.length > 0 ? (
|
||||
<div className="notice notice-error">
|
||||
<ul>{issues.map((i) => <li key={i.field + i.code}>{i.message}</li>)}</ul>
|
||||
</div>
|
||||
) : (
|
||||
<span className="hint">{tr('validationPassed')}</span>
|
||||
)}
|
||||
<div className="field">
|
||||
<span className="field-label">{tr('commandPreview')}</span>
|
||||
<div className="code">{cmdPreview}</div>
|
||||
</div>
|
||||
{busy && <span className="hint">{tr('creating')}</span>}
|
||||
</>
|
||||
<Review
|
||||
locale={locale}
|
||||
host={host}
|
||||
opts={opts}
|
||||
issues={issues}
|
||||
checking={checking}
|
||||
command={cmdPreview}
|
||||
onEdit={setStep}
|
||||
onName={(name) => set({ name })}
|
||||
onPickDir={pickDir}
|
||||
onDir={(dir) => set({ dir })}
|
||||
onStartAfter={(start) => set({ start })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="dialog-foot">
|
||||
<Button variant="ghost" disabled={step === 1 || busy} onClick={() => setStep(step - 1)}>{tr('back')}</Button>
|
||||
{step < 5 ? (
|
||||
<Button variant="ghost" disabled={step === 1} onClick={() => setStep(step - 1)}>{tr('back')}</Button>
|
||||
{step < REVIEW_STEP ? (
|
||||
<Button variant="primary" onClick={() => setStep(step + 1)}>{tr('next')}</Button>
|
||||
) : (
|
||||
<Button variant="primary" busy={busy} disabled={issues.length > 0} onClick={handleCreate}>{tr('createNow')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={checking || !!err || issues.length > 0 || !cmdPreview}
|
||||
title={tr('createStartedHint')}
|
||||
onClick={handleCreate}
|
||||
>
|
||||
{tr('createNow')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
interface ReviewProps {
|
||||
locale: Locale
|
||||
host: HostReport
|
||||
opts: CreateOpts
|
||||
issues: ValidationIssue[]
|
||||
checking: boolean
|
||||
command: string
|
||||
onEdit: (step: number) => void
|
||||
onName: (name: string) => void
|
||||
onDir: (dir: string) => void
|
||||
onPickDir: () => void
|
||||
onStartAfter: (start: boolean) => void
|
||||
}
|
||||
|
||||
type Row = { label: string; value: string; mono?: boolean }
|
||||
|
||||
const fileName = (p?: string) => (p ?? '').split(/[\\/]/).pop() || (p ?? '')
|
||||
|
||||
/** Step ⑤: what will be created, grouped by the step that set it, with the CLI equivalent folded away. */
|
||||
const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, command, onEdit, onName, onDir, onPickDir, onStartAfter }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const onOff = (b?: boolean) => tr(b ? 'summaryOn' : 'off')
|
||||
|
||||
const source = opts.source_mode === 'offline'
|
||||
? tr('summaryOfflineSource', { v: opts.macos ?? '' })
|
||||
: opts.source_mode === 'apple'
|
||||
? tr('summaryAppleSource', { v: opts.macos === 'tahoe' ? 'macOS 26 Tahoe' : (opts.macos ?? '') })
|
||||
: opts.source_mode === 'installer'
|
||||
? tr('summaryInstallerSource', { file: fileName(opts.installer) })
|
||||
: tr('summaryDiskSource', { file: fileName(opts.disk) })
|
||||
|
||||
const res = (opts.resolution ?? '').replace(/x/i, ' × ')
|
||||
const graphicsRows: Row[] = opts.graphics === 'reims-vgpu'
|
||||
? [
|
||||
{ label: tr('factGraphics'), value: `${gpuLabel(locale, opts.gpu, host)} · reims-vgpu` },
|
||||
{ label: tr('resolution'), value: (opts.displays ?? 1) > 1 ? `${opts.displays} × (${res})` : res },
|
||||
]
|
||||
: [{ label: tr('factGraphics'), value: `${tr('softwareGraphics')} · vmware-svga` }]
|
||||
|
||||
const groups: { step: number; title: I18nKey; rows: Row[] }[] = [
|
||||
{
|
||||
step: 1,
|
||||
title: 'step1',
|
||||
rows: [
|
||||
{ label: tr('summarySource'), value: source },
|
||||
{ label: tr('guestLangShort'), value: guestLangLabel(locale, opts.guest_lang) },
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 2,
|
||||
title: 'step2',
|
||||
rows: [
|
||||
{ label: tr('factCPU'), value: tr('cores', { n: opts.cpus }) },
|
||||
{ label: tr('factMemory'), value: formatMemory(opts.memory) },
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 3,
|
||||
title: 'step3',
|
||||
rows: [
|
||||
...(opts.source_mode !== 'disk'
|
||||
? [{ label: tr('diskSize'), value: tr('summaryDiskGrow', { size: formatMemory(opts.disk_size ?? '') }) }]
|
||||
: [{ label: tr('diskMode'), value: tr(opts.disk_mode === 'in-place' ? 'diskModeInPlace' : 'diskModeCopy') }]),
|
||||
{ label: tr('diskController'), value: controllerLabel(opts.disk_controller ?? 'nvme') },
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 4,
|
||||
title: 'step4',
|
||||
rows: [
|
||||
...graphicsRows,
|
||||
{ label: tr('fieldAudio'), value: onOff(opts.audio) },
|
||||
{ label: tr('fieldNetwork'), value: onOff(opts.network) },
|
||||
{ label: tr('captureInput'), value: onOff(opts.capture) },
|
||||
{ label: tr('summarySSH'), value: opts.ssh_port ? tr('summarySSHPort', { n: opts.ssh_port }) : tr('off') },
|
||||
{ label: tr('summaryLogs'), value: onOff(opts.logs) },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const nameIssue = issues.find((i) => i.field === 'name')?.message
|
||||
const general = issues.filter((i) => stepOfIssue(i) === REVIEW_STEP && i.field !== 'name')
|
||||
|
||||
const copy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(command)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 1500)
|
||||
} catch { /* clipboard unavailable; the text stays selectable */ }
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<SetGroup>
|
||||
<SetRow
|
||||
title={tr('vmName')}
|
||||
error={nameIssue}
|
||||
control={<input className="input name-input" aria-label={tr('vmName')} value={opts.name} onChange={(e) => onName(e.target.value)} spellCheck={false} />}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('vmDir')}
|
||||
desc={opts.dir ? <span className="mono path-text" title={opts.dir}>{opts.dir}</span> : tr('summaryDefaultDir')}
|
||||
control={
|
||||
<div className="hstack">
|
||||
{opts.dir && <Button variant="ghost" onClick={() => onDir('')}>{tr('useDefault')}</Button>}
|
||||
<Button onClick={onPickDir}>{tr('wizChooseFile')}</Button>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('startAfterCreate')}
|
||||
control={<Switch label={tr('startAfterCreate')} checked={!!opts.start} onChange={onStartAfter} />}
|
||||
/>
|
||||
</SetGroup>
|
||||
|
||||
{checking && issues.length === 0 ? (
|
||||
<div className="review-status">{tr('validationChecking')}</div>
|
||||
) : issues.length > 0 ? (
|
||||
<div className="review-status bad"><CircleAlert size={14} />{tr('issuesCount', { n: issues.length })}</div>
|
||||
) : (
|
||||
<div className="review-status ok"><CircleCheck size={14} />{tr('validationPassed')}</div>
|
||||
)}
|
||||
|
||||
{general.length > 0 && (
|
||||
<div className="notice notice-error">
|
||||
<ul>{general.map((i) => <li key={i.field + i.code}>{i.message}</li>)}</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="review-groups">
|
||||
{groups.map((g) => {
|
||||
const own = issues.filter((i) => stepOfIssue(i) === g.step)
|
||||
return (
|
||||
<section key={g.step} className={`review-group${own.length ? ' has-issue' : ''}`} aria-label={tr(g.title)}>
|
||||
<header className="review-head">
|
||||
<span className="review-title">{tr(g.title)}</span>
|
||||
<button type="button" className="link-btn" onClick={() => onEdit(g.step)}>{tr('summaryEdit')}</button>
|
||||
</header>
|
||||
<dl className="review-rows">
|
||||
{g.rows.map((r) => (
|
||||
<React.Fragment key={r.label}>
|
||||
<dt>{r.label}</dt>
|
||||
<dd className={r.mono ? 'mono' : undefined} title={r.value}>{r.value}</dd>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</dl>
|
||||
{own.length > 0 && (
|
||||
<ul className="review-issues">
|
||||
{own.map((i) => <li key={i.field + i.code}><CircleAlert size={12} />{i.message}</li>)}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<details className="review-cmd">
|
||||
<summary><ChevronRight size={14} />{tr('commandToggle')}</summary>
|
||||
<div className="review-cmd-body">
|
||||
<span className="hint">{tr('commandToggleHint')}</span>
|
||||
<div className="review-cmd-box">
|
||||
<div className="code">{command || '…'}</div>
|
||||
<IconButton
|
||||
small
|
||||
label={copied ? tr('toastCopied') : tr('copy')}
|
||||
icon={copied ? <Check size={14} /> : <Copy size={14} />}
|
||||
disabled={!command}
|
||||
onClick={copy}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,24 +1,43 @@
|
||||
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 { AppState, Locale } from '../types'
|
||||
import { formatBytes } from '../lib/format'
|
||||
import { findOptimization, kernelIrqchipHint, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
import { AppState, Locale, RuntimeSource, StorageBreakdown, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { backend } from '../wails'
|
||||
import { api } from '../wails'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
|
||||
interface Props {
|
||||
state: AppState
|
||||
locale: Locale
|
||||
onRefresh: () => void
|
||||
onNewVM?: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onSetLocale: (l: Locale) => void
|
||||
runtimeTask: Task | null
|
||||
onChannel: (alpha: boolean) => void
|
||||
onSource: (source: RuntimeSource) => void
|
||||
onInstallRuntime: (commit: string) => void
|
||||
onCancelTask: (id: string) => void
|
||||
}
|
||||
|
||||
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, onSetLocale }) => {
|
||||
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 { host, config, runtimes } = state
|
||||
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')
|
||||
|
||||
const whpx = {
|
||||
ready: { short: tr('whpxReady'), hint: '', tone: 'ok' },
|
||||
no_hypervisor: { short: tr('whpxNoHvShort'), hint: tr('whpxNoHv'), tone: 'warn' },
|
||||
@@ -37,20 +56,23 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
|
||||
const enableWHPX = async () => {
|
||||
setEnabling(true)
|
||||
await guard(() => backend.enableWHPX())()
|
||||
await guard(() => api.EnableWHPX())()
|
||||
setEnabling(false)
|
||||
}
|
||||
|
||||
const pickDataRoot = guard(async () => {
|
||||
const dir = await backend.pickDirectory(tr('hostDataRoot'))
|
||||
if (dir) await backend.setDataRoot(dir)
|
||||
})
|
||||
// One UAC prompt, then Windows' own Performance Options; the choice shows
|
||||
// here on the next refresh.
|
||||
const openScheduling = async () => {
|
||||
setOpeningSched(true)
|
||||
await guard(() => api.OpenProcessorScheduling())()
|
||||
setOpeningSched(false)
|
||||
}
|
||||
|
||||
const importRuntime = async () => {
|
||||
setImporting(true)
|
||||
await guard(async () => {
|
||||
const file = await backend.pickFile(tr('importRuntime'), '*.tar.zst;*.zip')
|
||||
if (file) await backend.installRuntimeArchive(file)
|
||||
const file = await api.PickFile(tr('importRuntime'), '*.tar.zst;*.zip')
|
||||
if (file) await api.InstallRuntimeArchive(file)
|
||||
})()
|
||||
setImporting(false)
|
||||
}
|
||||
@@ -69,105 +91,176 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
</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"><ShieldCheck size={14} /> {tr('whpxTitle')}</div>
|
||||
<div className={`tile-value ${whpx.tone}`}>{whpx.short}</div>
|
||||
<div className="tile-sub">{host.os}/{host.arch}</div>
|
||||
</div>
|
||||
<div className="tile">
|
||||
<div className="tile-head"><Cpu size={14} /> {tr('hostCPU')}</div>
|
||||
<div className="tile-value">{tr('hostCoresThreads', { c: host.physical_cores, t: host.logical_cpus })}</div>
|
||||
<div className="tile-sub">
|
||||
{host.has_hybrid_cores ? tr('hostHybrid', { p: host.p_core_count, e: host.e_core_count }) : tr('hostSymmetric')}
|
||||
<div className="tile-head">
|
||||
<span className={`tile-icon ${whpx.tone}`} aria-hidden="true"><ShieldCheck size={13} /></span>
|
||||
{tr('whpxTitle')}
|
||||
</div>
|
||||
<div className={`tile-value ${whpx.tone}`}>{whpx.short}</div>
|
||||
{host.whpx === 'missing' ? (
|
||||
<Button variant="primary" className="tile-action" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
|
||||
) : whpx.hint ? (
|
||||
<div className="tile-sub" title={whpx.hint}>{whpx.hint}</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="tile">
|
||||
<div className="tile-head"><MemoryStick size={14} /> {tr('hostRAM')}</div>
|
||||
<div className="tile-head">
|
||||
<span className="tile-icon accent" aria-hidden="true"><Cpu size={13} /></span>
|
||||
{tr('hostCPU')}
|
||||
</div>
|
||||
<div className="tile-value">{tr('hostCoresThreads', { c: host.physical_cores, t: host.logical_cpus })}</div>
|
||||
{host.p_core_count > 0 && host.e_core_count > 0 && (
|
||||
<div className="tile-sub">{host.p_core_count}P + {host.e_core_count}E</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="tile">
|
||||
<div className="tile-head">
|
||||
<span className="tile-icon accent" aria-hidden="true"><MemoryStick size={13} /></span>
|
||||
{tr('hostRAM')}
|
||||
</div>
|
||||
<div className="tile-value">{tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })}</div>
|
||||
<div className="tile-sub">{tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}</div>
|
||||
</div>
|
||||
<div className="tile">
|
||||
<div className="tile-head"><HardDrive size={14} /> {tr('hostDisk')}</div>
|
||||
<div className="tile-head">
|
||||
<span className="tile-icon" aria-hidden="true"><HardDrive size={13} /></span>
|
||||
{tr('hostDisk')}
|
||||
</div>
|
||||
<div className="tile-value">{host.free_disk_gb.toFixed(0)} GB</div>
|
||||
<div className="tile-sub mono">{config.data_root}</div>
|
||||
</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')}
|
||||
<Button variant={runtimes && runtimes.length > 0 ? 'secondary' : 'primary'} busy={importing} onClick={importRuntime}>
|
||||
<Button variant="ghost" busy={importing} onClick={importRuntime}>
|
||||
{tr('importRuntime')}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="list">
|
||||
{!runtimes || runtimes.length === 0 ? (
|
||||
<div className="row"><span className="row-sub">{tr('noRuntime')}</span></div>
|
||||
) : (
|
||||
runtimes.map((rt) => (
|
||||
<div className="row" key={rt.commit}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="mono">{rt.commit}</span>
|
||||
<span className="muted">{rt.manifest.qemu_version}</span>
|
||||
{rt.active && <span className="badge badge-ok">{tr('activeBadge')}</span>}
|
||||
</div>
|
||||
<div className="row-sub mono">{rt.dir}</div>
|
||||
</div>
|
||||
{!rt.active && (
|
||||
<div className="row-right">
|
||||
<Button onClick={guard(() => backend.useRuntime(rt.commit))}>{tr('activate')}</Button>
|
||||
</div>
|
||||
)}
|
||||
<RuntimeOnline
|
||||
locale={locale}
|
||||
channel={config.runtime_channel === 'alpha' ? 'alpha' : 'stable'}
|
||||
source={config.runtime_source === 'github' || config.runtime_source === 'gitcode' ? config.runtime_source : 'auto'}
|
||||
installed={runtimes ?? []}
|
||||
task={runtimeTask}
|
||||
onChannel={onChannel}
|
||||
onSource={onSource}
|
||||
onInstall={onInstallRuntime}
|
||||
onCancel={onCancelTask}
|
||||
/>
|
||||
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
|
||||
<div className="row" key={rt.commit}>
|
||||
<div className="row-main">
|
||||
<div className="row-title"><span className="mono">{rt.commit}</span></div>
|
||||
<div className="row-sub">{rt.manifest.qemu_version.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
<div className="row-right">
|
||||
<Button onClick={guard(() => api.UseRuntime(rt.commit))}>{tr('activate')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('hostSystem')}</div>
|
||||
<div className="section-title">{tr('hostOptimizations')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('hostWHPX')}</div>
|
||||
{whpx.hint && <div className="row-sub">{whpx.hint}</div>}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{host.whpx === 'missing' ? (
|
||||
<Button variant="primary" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
|
||||
) : (
|
||||
<span className={`badge ${whpx.tone === 'ok' ? 'badge-ok' : 'badge-warn'}`}>{whpx.short}</span>
|
||||
)}
|
||||
<div className="row-title">
|
||||
{tr('optKernelIrqchipTitle')}
|
||||
<span className={`badge ${optBadgeClass(irqOpt?.status)}`}>{optStatusLabel(locale, irqOpt?.status)}</span>
|
||||
</div>
|
||||
<div className="row-sub">{kernelIrqchipHint(locale, irqOpt)}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('hostDataRoot')}</div>
|
||||
<div className="row-sub mono">{config.data_root}</div>
|
||||
<div className="row-title">
|
||||
{tr('optColdRebootTitle')}
|
||||
<span className={`badge ${optBadgeClass(rebootOpt?.status)}`}>{optStatusLabel(locale, rebootOpt?.status)}</span>
|
||||
</div>
|
||||
<div className="row-sub">
|
||||
{tr(rebootOpt?.supported ? 'optColdRebootAuto' : 'optColdRebootUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right"><Button onClick={pickDataRoot}>{tr('choose')}</Button></div>
|
||||
</div>
|
||||
{host.has_hybrid_cores && (
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('autoPinPCores')}</div>
|
||||
<div className="row-sub mono">{host.p_core_mask_hex}</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('optDiscreteGpuTitle')}
|
||||
<span className={`badge ${optBadgeClass(gpuOpt?.status)}`}>{optStatusLabel(locale, gpuOpt?.status)}</span>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<label className="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={tr('autoPinPCores')}
|
||||
checked={config.auto_pin_pcores}
|
||||
onChange={(e) => guard(() => backend.setAutoPinPCores(e.target.checked))()}
|
||||
/>
|
||||
<span className="slider" />
|
||||
</label>
|
||||
<div className="row-sub">
|
||||
{gpuOpt?.status === 'recommended'
|
||||
? tr('optDiscreteGpuRec', { name: gpuOpt.detail ?? '' })
|
||||
: gpuOpt?.status === 'available'
|
||||
? tr('optDiscreteGpuIntegrated', { name: gpuOpt.detail ?? '' })
|
||||
: tr('optDiscreteGpuUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('optSchedTitle')}
|
||||
{host.processor_scheduling && (
|
||||
<span className="badge">{tr(host.processor_scheduling === 'background' ? 'optSchedBackground' : 'optSchedPrograms')}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-sub">{tr('optSchedSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button busy={openingSched} onClick={openScheduling}>{tr('optSchedOpen')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -180,33 +273,36 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
realGPUs.map((g) => (
|
||||
<div className="row" key={g.vulkan_icd}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<div className="row-title" title={g.vulkan_icd}>
|
||||
{g.name}
|
||||
<span className={`badge ${g.kind === 'discrete' ? 'badge-accent' : ''}`}>{gpuKind(g.kind)}</span>
|
||||
{host.recommended_gpu?.vulkan_icd === g.vulkan_icd && <span className="badge badge-ok">{tr('gpuRecommended')}</span>}
|
||||
</div>
|
||||
<div className="row-sub mono">{g.vulkan_icd}</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('hostPrefs')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main"><div className="row-title">{tr('language')}</div></div>
|
||||
<div className="row-right">
|
||||
<div className="segmented" role="group" aria-label={tr('language')}>
|
||||
<button type="button" aria-pressed={locale === 'zh-CN'} onClick={() => onSetLocale('zh-CN')}>中文</button>
|
||||
<button type="button" aria-pressed={locale === 'en-US'} onClick={() => onSetLocale('en-US')}>English</button>
|
||||
{(host.displays?.length ?? 0) > 0 && (
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('hostDisplays')}</div>
|
||||
<div className="list">
|
||||
{(host.displays ?? []).map((d, idx) => (
|
||||
<div className="row" key={d.name || idx}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{d.width} × {d.height}
|
||||
{d.refresh_hz ? ` @ ${d.refresh_hz}Hz` : ''}
|
||||
<span className="badge">{d.scale_pct || 100}%</span>
|
||||
{d.primary && <span className="badge badge-ok">{tr('hostDisplayPrimary')}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
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
|
||||
host: HostReport
|
||||
tasks: Task[]
|
||||
onCreateWithInstaller: (item: CachedInstaller) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onToast: (title: string) => void
|
||||
}
|
||||
|
||||
const gb = (b: number) => (b >= 1e9 ? `${(b / 1e9).toFixed(1)} GB` : `${Math.max(1, Math.ceil(b / 1e6))} MB`)
|
||||
|
||||
// reims-util creates the whole image as soon as a download starts (19.7 GB for an
|
||||
// 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)
|
||||
const [cached, setCached] = useState<CachedInstaller[] | null>(null)
|
||||
const [releases, setReleases] = useState<Release[] | null>(null)
|
||||
const [releasesErr, setReleasesErr] = useState('')
|
||||
const [confirmDelete, setConfirmDelete] = useState('')
|
||||
|
||||
const downloads = tasks.filter((x) => x.kind === 'installer-download')
|
||||
const running = (version: string) => downloads.find((x) => x.status === 'running' && x.subject === version)
|
||||
const finishedCount = downloads.filter((x) => x.status !== 'running').length
|
||||
|
||||
const loadCached = () => api.ListInstallers().then((l) => setCached(l ?? [])).catch((e) => onError(tr('failGeneric'), e))
|
||||
const loadReleases = () => {
|
||||
setReleases(null)
|
||||
setReleasesErr('')
|
||||
api.ListOfflineReleases()
|
||||
.then((l) => setReleases(l ?? []))
|
||||
.catch((e) => setReleasesErr(String(e).replace(/^Error:\s*/, '')))
|
||||
}
|
||||
useEffect(() => { loadReleases() }, [])
|
||||
// Refresh the downloaded list whenever a download starts or ends.
|
||||
useEffect(() => { loadCached() }, [finishedCount, downloads.length])
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
const remove = async (name: string) => {
|
||||
if (confirmDelete !== name) { setConfirmDelete(name); return }
|
||||
setConfirmDelete('')
|
||||
try {
|
||||
await api.DeleteInstaller(name)
|
||||
onToast(tr('toastDeleted', { name }))
|
||||
loadCached()
|
||||
} catch (e) {
|
||||
onError(tr('failDelete'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const progress = (task: Task) => (
|
||||
<span className="task-inline row-sub">
|
||||
<LoaderCircle size={14} className="spin" aria-hidden="true" />
|
||||
{task.percent >= 0 && (
|
||||
<span className="progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
|
||||
</span>
|
||||
)}
|
||||
<span>{task.percent >= 0 ? `${Math.floor(task.percent)}%` : ''} {taskDetail(task)}</span>
|
||||
</span>
|
||||
)
|
||||
|
||||
const skeleton = (rows: number, label?: string) => (
|
||||
<div className="skeleton-list" role="status" aria-label={label}>
|
||||
{Array.from({ length: rows }).map((_, i) => (
|
||||
<div className="skeleton-row" key={i} aria-hidden="true">
|
||||
<div className="skeleton-stack">
|
||||
<div className="skeleton-bar w-title" />
|
||||
<div className="skeleton-bar w-sub" />
|
||||
</div>
|
||||
<div className="skeleton-bar w-btn" />
|
||||
</div>
|
||||
))}
|
||||
</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 installers-page">
|
||||
<header className="page-head">
|
||||
<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>
|
||||
|
||||
{showDownloaded && (
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
<span>{tr('installersDownloaded')}</span>
|
||||
{cached && cached.length > 0 && <span className="section-count">{cached.length}</span>}
|
||||
</div>
|
||||
{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>
|
||||
)}
|
||||
</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>
|
||||
)}
|
||||
{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>
|
||||
)}
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('installersAvailable')}</div>
|
||||
{releasesErr ? (
|
||||
<div className="notice notice-error" role="alert">
|
||||
<span className="notice-main">
|
||||
<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(2, tr('offlineLoading'))}
|
||||
<span className="hint">{tr('offlineLoading')}</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>
|
||||
)}
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { ArrowDown, ChevronDown, ChevronUp, Eraser, LoaderCircle, 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'
|
||||
import { Locale, Task } from '../types'
|
||||
import { HostReport, Locale, Task } from '../types'
|
||||
import { Button, IconButton, Tip } from '../ui/controls'
|
||||
|
||||
export type LogTab = 'app' | 'serial'
|
||||
export type LogTab = 'app' | 'serial' | 'qemu'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -18,11 +18,19 @@ interface Props {
|
||||
unseenErrors: number
|
||||
onClear: () => void
|
||||
serialText: string
|
||||
qemuText: string
|
||||
showSerial: boolean
|
||||
onRefreshSerial: () => void
|
||||
onRefreshQemu: () => void
|
||||
task: Task | null
|
||||
runningTasks: number
|
||||
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. */
|
||||
@@ -48,29 +56,138 @@ 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
|
||||
const MAX_LOG_HEIGHT = 520
|
||||
|
||||
export const LogPanel: React.FC<Props> = ({
|
||||
locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, showSerial, onRefreshSerial,
|
||||
task, runningTasks, onCancelTask,
|
||||
locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, qemuText, showSerial, onRefreshSerial, onRefreshQemu,
|
||||
task, runningTasks, onCancelTask, host, runningVMs = 0, onCopy, hostReady = true, onOpenHost,
|
||||
}) => {
|
||||
const tr = (k: Parameters<typeof t>[1]) => t(locale, k)
|
||||
const content = tab === 'app' ? lines : serialText
|
||||
const tr = (k: Parameters<typeof t>[1], v?: Record<string, string | number>) => t(locale, k, v)
|
||||
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
|
||||
? Math.max(0, Math.min(100, host.memory_load_pct > 0
|
||||
? host.memory_load_pct
|
||||
: host.total_ram_gb > 0
|
||||
? Math.round(((host.total_ram_gb - host.avail_ram_gb) / host.total_ram_gb) * 100)
|
||||
: 0))
|
||||
: 0
|
||||
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 {
|
||||
const saved = Number(localStorage.getItem(LOG_HEIGHT_KEY))
|
||||
if (Number.isFinite(saved) && saved >= MIN_LOG_HEIGHT && saved <= MAX_LOG_HEIGHT) return saved
|
||||
} catch {}
|
||||
return DEFAULT_LOG_HEIGHT
|
||||
})
|
||||
const [dragging, setDragging] = useState(false)
|
||||
const dragRef = useRef<{ startY: number; startH: number } | null>(null)
|
||||
|
||||
const onResizeDown = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
e.preventDefault()
|
||||
e.currentTarget.setPointerCapture(e.pointerId)
|
||||
dragRef.current = { startY: e.clientY, startH: height }
|
||||
setDragging(true)
|
||||
}
|
||||
const onResizeMove = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!dragRef.current) return
|
||||
const next = Math.min(MAX_LOG_HEIGHT, Math.max(MIN_LOG_HEIGHT, Math.round(dragRef.current.startH + (dragRef.current.startY - e.clientY))))
|
||||
setHeight(next)
|
||||
}
|
||||
const onResizeUp = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!dragRef.current) return
|
||||
dragRef.current = null
|
||||
setDragging(false)
|
||||
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId)
|
||||
try { localStorage.setItem(LOG_HEIGHT_KEY, String(height)) } catch {}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="logs">
|
||||
{open && (
|
||||
<div
|
||||
className="log-resize-handle"
|
||||
role="separator"
|
||||
aria-orientation="horizontal"
|
||||
aria-label={tr('resizeLogPanel')}
|
||||
data-dragging={dragging}
|
||||
onPointerDown={onResizeDown}
|
||||
onPointerMove={onResizeMove}
|
||||
onPointerUp={onResizeUp}
|
||||
onPointerCancel={onResizeUp}
|
||||
onDoubleClick={() => {
|
||||
setHeight(DEFAULT_LOG_HEIGHT)
|
||||
try { localStorage.setItem(LOG_HEIGHT_KEY, String(DEFAULT_LOG_HEIGHT)) } catch {}
|
||||
}}
|
||||
>
|
||||
<span className="log-resize-pill" aria-hidden="true" />
|
||||
</div>
|
||||
)}
|
||||
<div className="logbar">
|
||||
{task && (
|
||||
{task ? (
|
||||
<>
|
||||
<Tip label={[task.step, taskDetail(task)].filter(Boolean).join(' · ') || taskTitle(locale, task)} side="top">
|
||||
<span className="task" tabIndex={0}>
|
||||
<LoaderCircle size={14} className="spin" />
|
||||
<LoaderCircle size={14} className="spin" aria-hidden="true" />
|
||||
<span className="task-label">
|
||||
{runningTasks > 1 ? t(locale, 'tasksRunning', { n: runningTasks }) : taskTitle(locale, task)}
|
||||
</span>
|
||||
{task.percent >= 0 && (
|
||||
<>
|
||||
<span className="progress" aria-hidden="true"><div style={{ width: `${task.percent}%` }} /></span>
|
||||
<span>{Math.floor(task.percent)}%</span>
|
||||
<span className="progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
|
||||
</span>
|
||||
<span className="task-pct">{Math.floor(task.percent)}%</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
@@ -79,19 +196,94 @@ export const LogPanel: React.FC<Props> = ({
|
||||
<IconButton small tipSide="top" label={tr('pauseDownload')} icon={<Pause size={14} />} onClick={() => onCancelTask(task.id)} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<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>
|
||||
) : 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"
|
||||
label={tr('footerMemTip', {
|
||||
used: usedMemGB.toFixed(1),
|
||||
total: host.total_ram_gb.toFixed(1),
|
||||
avail: host.avail_ram_gb.toFixed(1),
|
||||
})}
|
||||
>
|
||||
<span className={`status-metric${memTone}`} tabIndex={0}>
|
||||
<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>
|
||||
</Tip>
|
||||
)}
|
||||
{host.free_disk_gb > 0 && (
|
||||
<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-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 && (
|
||||
<>
|
||||
<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 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} />
|
||||
@@ -99,32 +291,32 @@ export const LogPanel: React.FC<Props> = ({
|
||||
{open && tab === 'serial' && (
|
||||
<IconButton small tipSide="top" label={tr('refresh')} icon={<RefreshCw size={14} />} onClick={onRefreshSerial} />
|
||||
)}
|
||||
{open && tab === 'qemu' && (
|
||||
<IconButton small tipSide="top" label={tr('refresh')} icon={<RefreshCw size={14} />} onClick={onRefreshQemu} />
|
||||
)}
|
||||
{!open && unseenErrors > 0 && <span className="badge badge-error" aria-hidden="true">{unseenErrors}</span>}
|
||||
<IconButton
|
||||
small
|
||||
tipSide="top"
|
||||
label={open ? tr('collapseLogs') : tr('expandLogs')}
|
||||
shortcut="Ctrl+L"
|
||||
icon={open ? <ChevronDown size={16} /> : <ChevronUp size={16} />}
|
||||
onClick={onToggle}
|
||||
aria-expanded={open}
|
||||
/>
|
||||
<Tip label={open ? tr('collapseLogs') : tr('expandLogs')} shortcut="Ctrl+L" side="top">
|
||||
<button
|
||||
type="button"
|
||||
className="log-toggle-btn"
|
||||
onClick={onToggle}
|
||||
aria-expanded={open}
|
||||
aria-label={open ? tr('collapseLogs') : tr('expandLogs')}
|
||||
>
|
||||
<span>{tr('logButton')}</span>
|
||||
{open ? <ChevronDown size={14} aria-hidden="true" /> : <ChevronUp size={14} aria-hidden="true" />}
|
||||
</button>
|
||||
</Tip>
|
||||
</div>
|
||||
|
||||
{open && (
|
||||
<div className="logs-body-wrap">
|
||||
<div className="logs-body" ref={ref} onScroll={onScroll} role="log" aria-live="off">
|
||||
<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>
|
||||
)))
|
||||
: (serialText || <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}>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import React from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { Locale } from '../types'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
name: string
|
||||
onCancel: () => void
|
||||
onConfirm: () => void
|
||||
}
|
||||
|
||||
export const OnlineRecoveryDialog: React.FC<Props> = ({ locale, name, onCancel, onConfirm }) => (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{t(locale, 'onlineRecoveryTitle')}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">
|
||||
{t(locale, 'onlineRecoveryDesc', { name })}
|
||||
</Alert.Description>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn">{t(locale, 'cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-primary" onClick={onConfirm}>
|
||||
{t(locale, 'onlineRecoveryConfirm')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)
|
||||
@@ -0,0 +1,146 @@
|
||||
import { Download, LoaderCircle, Pause, RefreshCw } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
import { InstalledRuntime, Locale, RemoteRuntime, RuntimeSource, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
channel: 'stable' | 'alpha'
|
||||
source: RuntimeSource
|
||||
installed: InstalledRuntime[]
|
||||
task: Task | null
|
||||
onChannel: (alpha: boolean) => void
|
||||
onSource: (source: RuntimeSource) => void
|
||||
onInstall: (commit: string) => void
|
||||
onCancel: (taskId: string) => void
|
||||
}
|
||||
|
||||
const gb = (b: number) => (b >= 1e9 ? `${(b / 1e9).toFixed(1)} GB` : `${Math.ceil(b / 1e6)} MB`)
|
||||
|
||||
/** "QEMU emulator version 11.1.90" → "QEMU 11.1.90". */
|
||||
const shortQemu = (v: string) => v.replace(/^QEMU emulator version\s*/i, 'QEMU ')
|
||||
|
||||
/**
|
||||
* The runtime rows: the active runtime and whether it is current (or, with
|
||||
* none installed, the newest release to install), then download source and alpha switches.
|
||||
*/
|
||||
export const RuntimeOnline: React.FC<Props> = ({ locale, channel, source, installed, task, onChannel, onSource, onInstall, onCancel }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [remote, setRemote] = useState<RemoteRuntime[] | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
const [reload, setReload] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
setRemote(null)
|
||||
setError('')
|
||||
api.ListRemoteRuntimes()
|
||||
.then((list) => { if (live) setRemote(list ?? []) })
|
||||
.catch((e) => { if (live) setError(String(e).replace(/^Error:\s*/, '')) })
|
||||
return () => { live = false }
|
||||
}, [channel, source, task?.status === 'done', reload])
|
||||
|
||||
const active = installed.find((i) => i.active) ?? installed[0]
|
||||
const latest = remote?.[0]
|
||||
const sameRuntimeId = (a: string, b: string) => {
|
||||
const [baseA, revA = ''] = a.split('-', 2)
|
||||
const [baseB, revB = ''] = b.split('-', 2)
|
||||
return revA === revB && (baseA.startsWith(baseB) || baseB.startsWith(baseA))
|
||||
}
|
||||
const isInstalled = (c: string) => installed.some((i) => sameRuntimeId(i.commit, c))
|
||||
const running = task?.status === 'running'
|
||||
const updatable = !!latest && !isInstalled(latest.commit)
|
||||
|
||||
let sub: React.ReactNode
|
||||
if (running && task) {
|
||||
sub = (
|
||||
<div className="row-sub task-inline">
|
||||
<LoaderCircle size={14} className="spin" aria-hidden="true" />
|
||||
{task.percent >= 0 && (
|
||||
<span className="progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
|
||||
</span>
|
||||
)}
|
||||
<span>{task.percent >= 0 ? `${Math.floor(task.percent)}%` : ''} {taskDetail(task)}</span>
|
||||
</div>
|
||||
)
|
||||
} else if (active && !updatable) {
|
||||
sub = <div className="row-sub">{shortQemu(active.manifest.qemu_version)}</div>
|
||||
} else if (error) {
|
||||
const isRateLimit = /rate limit|HTTP 403|HTTP 429/i.test(error)
|
||||
const msg = isRateLimit ? tr('runtimeLookupRateLimit') : `${tr('runtimeLookupFailed')}: ${error}`
|
||||
sub = <div className="row-sub" title={error}>{msg}</div>
|
||||
} else if (!remote) {
|
||||
sub = <div className="row-sub">…</div>
|
||||
} else if (!latest) {
|
||||
sub = <div className="row-sub">{tr('runtimeNoneOnChannel')}</div>
|
||||
} else {
|
||||
const srcLabel = latest.source === 'gitcode' ? 'GitCode' : latest.source === 'github' ? 'GitHub' : ''
|
||||
sub = (
|
||||
<div className="row-sub">
|
||||
{active ? tr('runtimeNewer', { v: latest.commit }) : tr('runtimeLatest', { v: latest.commit })}
|
||||
{' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)}
|
||||
{srcLabel ? ` · ${srcLabel}` : ''}
|
||||
{latest.archive_size > 0 ? ` · ${gb(latest.archive_size)}` : ''}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{active ? <>{tr('runtimeCurrent')} <span className="mono">{active.commit}</span></> : tr('runtimeOnline')}
|
||||
</div>
|
||||
{sub}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{running && task?.cancelable ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => onCancel(task.id)} />
|
||||
) : !running && error ? (
|
||||
<Button icon={<RefreshCw size={14} />} onClick={() => setReload((n) => n + 1)}>
|
||||
{tr('runtimeRetry')}
|
||||
</Button>
|
||||
) : !running && updatable ? (
|
||||
<Button variant="primary" icon={<Download size={14} />} onClick={() => onInstall(latest!.commit)}>
|
||||
{tr(active ? 'runtimeUpdate' : 'runtimeInstall')}
|
||||
</Button>
|
||||
) : !running && active && remote ? (
|
||||
<span className="badge badge-ok">{tr('runtimeUpToDate')}</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('runtimeSource')}</div>
|
||||
<div className="row-sub">{tr('runtimeSourceHint')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Segmented
|
||||
label={tr('runtimeSource')}
|
||||
value={source}
|
||||
onChange={onSource}
|
||||
options={(['auto', 'github', 'gitcode'] as RuntimeSource[]).map((s) => ({
|
||||
value: s,
|
||||
label: tr(`runtimeSource_${s}` as I18nKey),
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('runtimeAlpha')}</div>
|
||||
<div className="row-sub">{tr('runtimeAlphaHint')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Switch label={tr('runtimeAlpha')} checked={channel === 'alpha'} onChange={onChannel} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import React, { useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { Locale } from '../types'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
vmName: string
|
||||
guestToolsConnected: boolean
|
||||
onCancel: () => void
|
||||
onConfirm: (text: string) => void
|
||||
}
|
||||
|
||||
export const SendTextDialog: React.FC<Props> = ({ locale, vmName, guestToolsConnected, onCancel, onConfirm }) => {
|
||||
const [text, setText] = useState('')
|
||||
const canSend = text.length > 0
|
||||
|
||||
return (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{t(locale, 'sendTextTitle', { name: vmName })}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">
|
||||
{t(locale, guestToolsConnected ? 'sendTextDesc' : 'sendTextDescNoGT')}
|
||||
</Alert.Description>
|
||||
<div className="field field-spaced">
|
||||
<textarea
|
||||
className="input textarea"
|
||||
rows={4}
|
||||
placeholder={t(locale, 'sendTextPlaceholder')}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && canSend) {
|
||||
e.preventDefault()
|
||||
onConfirm(text)
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn">{t(locale, 'cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-primary" disabled={!canSend} onClick={() => onConfirm(text)}>
|
||||
{t(locale, 'sendTextConfirm')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
import { FolderOpen, HardDrive } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { AppState, DataRootCheck, DataRootChoice, Locale, RuntimeSource, Task } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Segmented } from '../ui/settings'
|
||||
import { recommendedMemoryGB, shortGPUName } from '../lib/format'
|
||||
import { api } from '../wails'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
state: AppState
|
||||
stage: 'folder' | 'runtime'
|
||||
runtimeTask: Task | null
|
||||
onLocale: (l: Locale) => void
|
||||
onFolderDone: () => void
|
||||
onFinish: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onChannel: (alpha: boolean) => void
|
||||
onSource: (source: RuntimeSource) => void
|
||||
onInstallRuntime: (commit: string) => void
|
||||
onCancelTask: (id: string) => void
|
||||
onImportRuntime: () => void
|
||||
}
|
||||
|
||||
const LOW_SPACE_GB = 60
|
||||
|
||||
/** First launch: choose the data folder, then (optionally) install the runtime. */
|
||||
export const Setup: React.FC<Props> = (p) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(p.locale, k, v)
|
||||
return (
|
||||
<div className="setup">
|
||||
<div className="setup-card">
|
||||
{p.stage === 'folder' ? <FolderStep {...p} tr={tr} /> : <RuntimeStep {...p} tr={tr} />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type StepProps = Props & { tr: (k: I18nKey, v?: Record<string, string | number>) => string }
|
||||
|
||||
const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, onError }) => {
|
||||
const [choices, setChoices] = useState<DataRootChoice[]>([])
|
||||
const [custom, setCustom] = useState('')
|
||||
const [customMode, setCustomMode] = useState(false)
|
||||
const [selected, setSelected] = useState('')
|
||||
const [check, setCheck] = useState<DataRootCheck | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
api.SuggestDataRoots().then((list) => {
|
||||
const l = list ?? []
|
||||
setChoices(l)
|
||||
const rec = l.find((c) => c.recommended) ?? l[0]
|
||||
if (rec) setSelected(rec.path)
|
||||
}).catch((e) => onError(tr('failGeneric'), e))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selected) { setCheck(null); return }
|
||||
let live = true
|
||||
api.CheckDataRoot(selected).then((c) => { if (live) setCheck(c) }).catch(() => {})
|
||||
return () => { live = false }
|
||||
}, [selected])
|
||||
|
||||
const browse = async () => {
|
||||
const dir = await api.PickDirectory(tr('setupTitle')).catch(() => '')
|
||||
if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) }
|
||||
}
|
||||
|
||||
const next = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await api.CompleteSetup(selected)
|
||||
onFolderDone()
|
||||
} catch (e) {
|
||||
onError(tr('failGeneric'), e)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const option = (path: string, meta: React.ReactNode) => (
|
||||
<label key={path} className="choice-card" data-selected={selected === path}>
|
||||
<input type="radio" name="data-root" checked={selected === path} onChange={() => setSelected(path)} />
|
||||
<HardDrive size={18} aria-hidden="true" />
|
||||
<span className="choice-card-main">
|
||||
<span className="mono choice-card-path">{path}</span>
|
||||
<span className="choice-card-meta">{meta}</span>
|
||||
</span>
|
||||
</label>
|
||||
)
|
||||
|
||||
const notices: string[] = []
|
||||
if (check?.error) notices.push(check.error)
|
||||
else if (check) {
|
||||
if (check.system) notices.push(tr('setupWarnSystem'))
|
||||
if (check.external) notices.push(tr('setupWarnExternal'))
|
||||
if (check.free_gb > 0 && check.free_gb < LOW_SPACE_GB) notices.push(tr('setupWarnSpace'))
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="setup-head">
|
||||
<h1>{tr('setupTitle')}</h1>
|
||||
<p>{tr('setupDesc')}</p>
|
||||
</div>
|
||||
<div className="choices-list" role="radiogroup" aria-label={tr('setupTitle')}>
|
||||
{choices.map((c) => option(c.path, (
|
||||
<>
|
||||
{tr('setupFree', { n: c.free_gb.toFixed(0) })}
|
||||
{c.recommended && <span className="badge badge-accent">{tr('setupRecommended')}</span>}
|
||||
{c.system && <span className="badge">{tr('setupSystem')}</span>}
|
||||
{c.external && <span className="badge badge-warn">{tr('setupExternal')}</span>}
|
||||
</>
|
||||
)))}
|
||||
{customMode ? (
|
||||
<div className="input-group">
|
||||
<input
|
||||
className="input mono"
|
||||
aria-label={tr('setupOther')}
|
||||
value={custom}
|
||||
placeholder="D:\VMs\reims-go"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
autoFocus
|
||||
onFocus={() => custom && setSelected(custom)}
|
||||
onChange={(e) => { setCustom(e.target.value); setSelected(e.target.value.trim()) }}
|
||||
/>
|
||||
<Button icon={<FolderOpen size={14} />} onClick={browse}>{tr('choose')}</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Button variant="ghost" icon={<FolderOpen size={14} />} onClick={() => setCustomMode(true)} className="choice-other">{tr('setupOther')}</Button>
|
||||
)}
|
||||
</div>
|
||||
{notices.length > 0 && (
|
||||
<div className={check?.error ? 'notice notice-error' : 'hint warn'}>{notices.join(';')}</div>
|
||||
)}
|
||||
{!check?.error && check?.has_config && <div className="hint">{tr('setupReuse')}</div>}
|
||||
{customMode && check && check.path === custom && !check.error && (
|
||||
<div className="hint">{tr('setupFree', { n: check.free_gb.toFixed(0) })}</div>
|
||||
)}
|
||||
<div className="setup-foot">
|
||||
<Segmented
|
||||
label={tr('language')}
|
||||
value={locale}
|
||||
onChange={onLocale}
|
||||
options={[
|
||||
{ value: 'zh-CN', label: '中文' },
|
||||
{ value: 'en-US', label: 'English' },
|
||||
]}
|
||||
/>
|
||||
<Button variant="primary" busy={busy} disabled={!selected || !!check?.error} onClick={next}>{tr('setupContinue')}</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask, onImportRuntime, onFinish, onError }) => {
|
||||
const ready = !!state.active_runtime
|
||||
const { host } = state
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
const enableWHPX = async () => {
|
||||
setEnabling(true)
|
||||
try { await api.EnableWHPX() } catch (e) { onError(tr('failGeneric'), e) } finally { setEnabling(false) }
|
||||
}
|
||||
const whpxOK = host.whpx === 'ready'
|
||||
const gpu = host.recommended_gpu ?? (host.gpus ?? []).find((g) => g.kind !== 'virtual')
|
||||
const recMem = recommendedMemoryGB(host)
|
||||
return (
|
||||
<>
|
||||
<div className="setup-head">
|
||||
<h1>{tr('setupRuntimeTitle')}</h1>
|
||||
<p>{tr('setupRuntimeDesc')}</p>
|
||||
</div>
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('setupCheck')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('hostWHPX')}</div>
|
||||
{!whpxOK && (
|
||||
<div className="row-sub">
|
||||
{tr(host.whpx === 'missing' ? 'whpxMissing' : host.whpx === 'no_hypervisor' ? 'whpxNoHv' : 'whpxUnsupported')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{host.whpx === 'missing' ? (
|
||||
<Button variant="primary" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
|
||||
) : (
|
||||
<span className={`badge ${whpxOK ? 'badge-ok' : 'badge-warn'}`}>
|
||||
{tr(whpxOK ? 'whpxReady' : host.whpx === 'no_hypervisor' ? 'whpxNoHvShort' : 'whpxUnsupportedShort')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('setupGPU')}</div>
|
||||
<div className="row-sub">{gpu ? shortGPUName(gpu.name) : tr('setupNoGPU')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<span className={`badge ${gpu ? 'badge-ok' : 'badge-warn'}`}>{tr(gpu ? 'whpxReady' : 'hostNeedsAction')}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('hostRAM')}</div>
|
||||
<div className="row-sub">
|
||||
{host.commit_avail_gb > 0
|
||||
? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: recMem })
|
||||
: tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<span className={`badge ${recMem >= 8 ? 'badge-ok' : 'badge-warn'}`}>{tr('setupRecMem', { n: recMem })}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<div className="list">
|
||||
<RuntimeOnline
|
||||
locale={locale}
|
||||
channel={state.config.runtime_channel === 'alpha' ? 'alpha' : 'stable'}
|
||||
source={state.config.runtime_source === 'github' || state.config.runtime_source === 'gitcode' ? state.config.runtime_source : 'auto'}
|
||||
installed={state.runtimes ?? []}
|
||||
task={runtimeTask}
|
||||
onChannel={onChannel}
|
||||
onSource={onSource}
|
||||
onInstall={onInstallRuntime}
|
||||
onCancel={onCancelTask}
|
||||
/>
|
||||
</div>
|
||||
<div className="setup-foot">
|
||||
<Button variant="ghost" onClick={onImportRuntime}>{tr('setupImport')}</Button>
|
||||
<Button variant={ready ? 'primary' : 'secondary'} disabled={runtimeTask?.status === 'running'} onClick={onFinish}>
|
||||
{tr(ready ? 'setupDone' : 'setupLater')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,15 @@
|
||||
import { Cpu, Monitor, Plus } 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__'
|
||||
export const SETTINGS_ID = '__settings__'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -13,12 +18,24 @@ 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 }) => {
|
||||
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), HOST_ID]
|
||||
const ids = [...vms.map((v) => v.name), INSTALLERS_ID, HOST_ID, SETTINGS_ID]
|
||||
|
||||
// Listbox keyboard model: ↑/↓/Home/End move selection and focus together.
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
@@ -34,7 +51,15 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
|
||||
listRef.current?.querySelector<HTMLElement>(`[data-id="${CSS.escape(ids[next])}"]`)?.focus()
|
||||
}
|
||||
|
||||
const item = (id: string, label: string, icon: React.ReactNode, stateLabel: string, kind: ReturnType<typeof statusKind>) => (
|
||||
const navBtn = (
|
||||
id: string,
|
||||
label: string,
|
||||
icon: React.ReactNode,
|
||||
badgeClass: string,
|
||||
stateLabel: string,
|
||||
kind: ReturnType<typeof statusKind> | null,
|
||||
onDoubleClick?: () => void,
|
||||
) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
@@ -42,39 +67,129 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
|
||||
data-id={id}
|
||||
className="nav-item"
|
||||
aria-selected={selected === id}
|
||||
aria-label={`${label},${stateLabel}`}
|
||||
aria-label={stateLabel ? `${label},${stateLabel}` : label}
|
||||
tabIndex={selected === id ? 0 : -1}
|
||||
onClick={() => onSelect(id)}
|
||||
onDoubleClick={onDoubleClick}
|
||||
>
|
||||
{icon}
|
||||
<span className={`nav-icon-badge ${badgeClass}`} aria-hidden="true">{icon}</span>
|
||||
<span className="nav-label">{label}</span>
|
||||
<Tip label={stateLabel} side="right">
|
||||
<span className="hstack"><StatusShape kind={kind} /></span>
|
||||
</Tip>
|
||||
{kind && (
|
||||
<Tip label={stateLabel} side="right">
|
||||
<span className="hstack"><StatusShape kind={kind} /></span>
|
||||
</Tip>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
|
||||
return (
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-head">
|
||||
<span>{t(locale, 'sidebarVMs')}</span>
|
||||
<IconButton small label={t(locale, 'newVM')} shortcut="Ctrl+N" icon={<Plus size={16} />} 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>}
|
||||
{vms.map((vm) => {
|
||||
const st = transitions[vm.name] ?? vm.state
|
||||
return item(vm.name, vm.name, <Monitor size={16} />, t(locale, `state_${st}` as I18nKey), statusKind(st))
|
||||
})}
|
||||
<div className="sidebar-sep" role="presentation" />
|
||||
{item(
|
||||
HOST_ID,
|
||||
t(locale, 'sidebarHost'),
|
||||
<Cpu size={16} />,
|
||||
t(locale, hostReady ? 'hostReady' : 'hostNeedsAction'),
|
||||
hostReady ? 'running' : 'warn',
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
<div className="sidebar-wrap">
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-head">
|
||||
<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={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
|
||||
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">{tr('sidebarSystem')}</div>
|
||||
{navBtn(
|
||||
INSTALLERS_ID,
|
||||
tr('sidebarInstallers'),
|
||||
<Download size={13} />,
|
||||
'nav-icon-installers',
|
||||
downloading ? tr('state_starting') : '',
|
||||
downloading ? 'busy' : null,
|
||||
)}
|
||||
{navBtn(
|
||||
HOST_ID,
|
||||
tr('sidebarHost'),
|
||||
<Cpu size={13} />,
|
||||
'nav-icon-host',
|
||||
tr(hostReady ? 'hostReady' : 'hostNeedsAction'),
|
||||
hostReady ? 'running' : 'warn',
|
||||
)}
|
||||
{navBtn(
|
||||
SETTINGS_ID,
|
||||
tr('sidebarSettings'),
|
||||
<Settings size={13} />,
|
||||
'nav-icon-settings',
|
||||
'',
|
||||
null,
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -1,16 +1,54 @@
|
||||
import { t } from '../i18n'
|
||||
import { GPUInfo, HostReport, Locale, VMDetail } from '../types'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { DisplayPreset, GPUInfo, HostReport, Locale, VMDetail } from '../types'
|
||||
|
||||
// Human-readable values for the main view (docs/ui-redesign.md §4.3).
|
||||
// Raw values stay available under "Technical details".
|
||||
|
||||
/** "16G" / "16384M" / "16GiB" → "16 GB". Unknown shapes pass through. */
|
||||
export function formatMemory(raw: string): string {
|
||||
const MEMORY_CHOICES = [4, 6, 8, 12, 16, 24, 32, 48, 64]
|
||||
|
||||
/**
|
||||
* Largest offered memory size that fits in 60% of physical RAM and in the
|
||||
* commit memory free now, minus 1 GB for QEMU and 2 GB for the host. Mirrors
|
||||
* host.RecommendedMemoryGB (internal/host/memory.go).
|
||||
*/
|
||||
export function recommendedMemoryGB(host: HostReport): number {
|
||||
let limit = host.total_ram_gb * 0.6
|
||||
if (host.commit_avail_gb > 0) limit = Math.min(limit, host.commit_avail_gb - 3)
|
||||
return MEMORY_CHOICES.reduce((best, m) => (m <= limit ? m : best), MEMORY_CHOICES[0])
|
||||
}
|
||||
|
||||
/** Memory sizes offered as quick picks, in GB. */
|
||||
export const MEMORY_MARKS = MEMORY_CHOICES
|
||||
|
||||
/**
|
||||
* Largest memory size in GB that still fits the same limits
|
||||
* recommendedMemoryGB applies; above it the settings slider turns amber.
|
||||
*/
|
||||
export function memorySafeLimitGB(host: HostReport): number {
|
||||
let limit = host.total_ram_gb * 0.6
|
||||
if (host.commit_avail_gb > 0) limit = Math.min(limit, host.commit_avail_gb - 3)
|
||||
return Math.max(Math.floor(limit), recommendedMemoryGB(host))
|
||||
}
|
||||
|
||||
/** vCPU count suggested for a new VM; same rule as the create wizard. */
|
||||
export function recommendedCPUs(host: HostReport): number {
|
||||
const rec = host.logical_cpus >= 12 ? 8 : 4
|
||||
return host.logical_cpus > 0 ? Math.min(rec, host.logical_cpus) : rec
|
||||
}
|
||||
|
||||
/** "16G" / "16384M" / "16GiB" → 16. Null when the shape is unknown. */
|
||||
export function parseMemoryGB(raw: string | undefined): number | null {
|
||||
const m = /^\s*(\d+(?:\.\d+)?)\s*([KMGT])?(?:i?B)?\s*$/i.exec(raw ?? '')
|
||||
if (!m) return raw
|
||||
if (!m) return null
|
||||
const n = Number(m[1])
|
||||
const unit = (m[2] ?? 'M').toUpperCase()
|
||||
const gb = unit === 'T' ? n * 1024 : unit === 'G' ? n : unit === 'M' ? n / 1024 : n / 1024 / 1024
|
||||
return unit === 'T' ? n * 1024 : unit === 'G' ? n : unit === 'M' ? n / 1024 : n / 1024 / 1024
|
||||
}
|
||||
|
||||
/** "16G" / "16384M" / "16GiB" → "16 GB". Unknown shapes pass through. */
|
||||
export function formatMemory(raw: string): string {
|
||||
const gb = parseMemoryGB(raw)
|
||||
if (gb === null) return raw
|
||||
const rounded = gb >= 10 ? Math.round(gb) : Math.round(gb * 10) / 10
|
||||
return `${rounded} GB`
|
||||
}
|
||||
@@ -46,15 +84,18 @@ export function resolutionLabel(raw: string): string {
|
||||
return Math.abs(w / h - 16 / 9) < 0.01 ? `${h}p` : `${w}×${h}`
|
||||
}
|
||||
|
||||
/** A `gpu` value ("auto" or a Vulkan ICD path) as the card's short name, e.g. "RTX 4070 Ti". */
|
||||
export function gpuLabel(locale: Locale, icd: string | undefined, host: HostReport): string {
|
||||
if (!icd || icd === 'auto') {
|
||||
return host.recommended_gpu ? shortGPUName(host.recommended_gpu.name) : t(locale, 'gpuAuto')
|
||||
}
|
||||
const found = findGPU(host, icd)
|
||||
return found ? shortGPUName(found.name) : t(locale, 'gpuAuto')
|
||||
}
|
||||
|
||||
export function graphicsLabel(locale: Locale, d: VMDetail, host: HostReport): string {
|
||||
if (d.graphics && d.graphics !== 'reims-vgpu') return t(locale, 'softwareGraphics')
|
||||
let gpu: string
|
||||
if (!d.gpu || d.gpu === 'auto') {
|
||||
gpu = host.recommended_gpu ? shortGPUName(host.recommended_gpu.name) : t(locale, 'gpuAuto')
|
||||
} else {
|
||||
const found = findGPU(host, d.gpu)
|
||||
gpu = found ? shortGPUName(found.name) : t(locale, 'gpuAuto')
|
||||
}
|
||||
const gpu = gpuLabel(locale, d.gpu, host)
|
||||
const res = resolutionLabel(d.resolution)
|
||||
const screens = d.displays > 1 ? `${d.displays} × ${res}` : res
|
||||
return res ? `${gpu} · ${screens}` : gpu
|
||||
@@ -63,3 +104,152 @@ export function graphicsLabel(locale: Locale, d: VMDetail, host: HostReport): st
|
||||
export function sshCommand(port: number): string {
|
||||
return `ssh -p ${port} 127.0.0.1`
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (!bytes || bytes <= 0) return '0 B'
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
let v = bytes
|
||||
let i = 0
|
||||
while (v >= 1024 && i < units.length - 1) {
|
||||
v /= 1024
|
||||
i++
|
||||
}
|
||||
const digits = v >= 100 || i === 0 ? 0 : v >= 10 ? 1 : 2
|
||||
return `${v.toFixed(digits)} ${units[i]}`
|
||||
}
|
||||
|
||||
/** Compact "54 / 128 GB" when both are gigabytes, falling back to full units. */
|
||||
export function formatDiskUsage(actual: number, virtual: number): string {
|
||||
const GiB = 1024 ** 3
|
||||
if (actual >= GiB && virtual >= GiB && virtual < 1024 * GiB) {
|
||||
const a = actual / GiB
|
||||
const v = virtual / GiB
|
||||
const aStr = a >= 10 ? Math.round(a).toString() : a.toFixed(1)
|
||||
const vStr = Math.round(v).toString()
|
||||
return `${aStr} / ${vStr} GB`
|
||||
}
|
||||
return `${formatBytes(actual)} / ${formatBytes(virtual)}`
|
||||
}
|
||||
|
||||
export function formatUptime(sec: number, locale: Locale): string {
|
||||
if (!sec || sec <= 0) return '—'
|
||||
const h = Math.floor(sec / 3600)
|
||||
const m = Math.floor((sec % 3600) / 60)
|
||||
const s = sec % 60
|
||||
if (locale === 'zh-CN') {
|
||||
if (h > 0) return `${h}小时 ${m}分`
|
||||
if (m > 0) return `${m}分 ${s}秒`
|
||||
return `${s}秒`
|
||||
}
|
||||
if (h > 0) return `${h}h ${m}m`
|
||||
if (m > 0) return `${m}m ${s}s`
|
||||
return `${s}s`
|
||||
}
|
||||
|
||||
// Used only when the host report has no presets: with nothing known about the
|
||||
// screen, no size can be called HiDPI (internal/host/display.go).
|
||||
const DEFAULT_DISPLAY_PRESETS: DisplayPreset[] = [
|
||||
{ resolution: '1920x1080', label: '1920 × 1080', hidpi: false, recommended: true },
|
||||
{ resolution: '2560x1440', label: '2560 × 1440', hidpi: false },
|
||||
{ resolution: '2880x1800', label: '2880 × 1800', hidpi: false },
|
||||
]
|
||||
|
||||
type Tr = (k: I18nKey, v?: Record<string, string | number>) => string
|
||||
|
||||
// The resolution row's description: the main display and its scaling.
|
||||
export function hostDisplayDesc(host: HostReport, tr: Tr): string | undefined {
|
||||
const d = host.primary_display
|
||||
if (!d) return undefined
|
||||
return tr('hostDisplayHint', { w: d.width, h: d.height, scale: d.scale_pct || 100 })
|
||||
}
|
||||
|
||||
// How to get a HiDPI (sharp-text) macOS desktop when no window size gives
|
||||
// one on this screen; undefined when one does.
|
||||
export function hostDisplayAdvice(host: HostReport, tr: Tr): string | undefined {
|
||||
const tip: Record<string, I18nKey> = {
|
||||
fullscreen: 'hidpiTipFullscreen',
|
||||
scale: 'hidpiTipScale',
|
||||
unavailable: 'hidpiTipUnavailable',
|
||||
}
|
||||
const key = host.hidpi_advice ? tip[host.hidpi_advice] : undefined
|
||||
return key ? tr(key) : undefined
|
||||
}
|
||||
|
||||
// "Looks like" size of a HiDPI preset: macOS draws it at half each way.
|
||||
export function hidpiLooksLike(resolution: string, tr: Tr): string | undefined {
|
||||
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(resolution)
|
||||
return m ? tr('resLooksLike', { w: Math.round(Number(m[1]) / 2), h: Math.round(Number(m[2]) / 2) }) : undefined
|
||||
}
|
||||
|
||||
export function recommendedDisplayPresets(host: HostReport): DisplayPreset[] {
|
||||
if (host.display_presets && host.display_presets.length > 0) {
|
||||
return host.display_presets
|
||||
}
|
||||
return DEFAULT_DISPLAY_PRESETS
|
||||
}
|
||||
|
||||
export function recommendedResolution(host: HostReport): string {
|
||||
if (host.recommended_resolution) return host.recommended_resolution
|
||||
const rec = recommendedDisplayPresets(host).find((p) => p.recommended)
|
||||
return rec?.resolution ?? '1920x1080'
|
||||
}
|
||||
|
||||
export interface GuestLangPreset {
|
||||
value: string
|
||||
zh: string
|
||||
en: string
|
||||
}
|
||||
|
||||
export const GUEST_LANG_PRESETS: GuestLangPreset[] = [
|
||||
{ value: 'zh-Hans:0', zh: '简体中文(美式键盘,推荐)', en: 'Simplified Chinese (US Keyboard)' },
|
||||
{ value: 'zh-Hans:252', zh: '简体中文(拼音键盘)', en: 'Simplified Chinese (Pinyin)' },
|
||||
{ value: 'zh-Hant:0', zh: '繁體中文(美式键盘)', en: 'Traditional Chinese (US Keyboard)' },
|
||||
{ value: 'en-US:0', zh: 'English (US)', en: 'English (US)' },
|
||||
{ value: 'ja-JP:0', zh: '日本語(美式键盘)', en: 'Japanese (US Keyboard)' },
|
||||
{ value: 'ko-KR:0', zh: '한국어(美式键盘)', en: 'Korean (US Keyboard)' },
|
||||
]
|
||||
|
||||
export function defaultGuestLang(locale: Locale): string {
|
||||
return locale === 'en-US' ? 'en-US:0' : 'zh-Hans:0'
|
||||
}
|
||||
|
||||
export function guestLangLabel(locale: Locale, code: string | undefined): string {
|
||||
if (!code) return defaultGuestLang(locale)
|
||||
const hit = GUEST_LANG_PRESETS.find((p) => p.value === code)
|
||||
if (hit) return locale === 'zh-CN' ? hit.zh : hit.en
|
||||
return code
|
||||
}
|
||||
|
||||
/**
|
||||
* Split "简体中文(美式键盘,推荐)" / "Simplified Chinese (US Keyboard)" into a
|
||||
* pop-up label and its grey detail, so the menu reads like macOS.
|
||||
*/
|
||||
export function splitLangLabel(value: string, text: string): { value: string; label: string; detail?: string } {
|
||||
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)}`
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, Optimization, OptimizationStatus } from '../types'
|
||||
|
||||
export type KernelIrqchipMode = 'auto' | 'on' | 'off'
|
||||
|
||||
export function findOptimization(list: Optimization[] | undefined, id: string): Optimization | undefined {
|
||||
return (list ?? []).find((o) => o.id === id)
|
||||
}
|
||||
|
||||
export function optBadgeClass(status: OptimizationStatus | undefined): string {
|
||||
switch (status) {
|
||||
case 'recommended':
|
||||
case 'auto':
|
||||
return 'badge-ok'
|
||||
case 'experimental':
|
||||
return 'badge-warn'
|
||||
case 'available':
|
||||
return 'badge-accent'
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function optStatusLabel(locale: Locale, status: OptimizationStatus | undefined): string {
|
||||
const keyMap: Record<OptimizationStatus, I18nKey> = {
|
||||
recommended: 'optRecommended',
|
||||
available: 'optAvailable',
|
||||
experimental: 'optExperimental',
|
||||
auto: 'optAuto',
|
||||
unavailable: 'optUnavailable',
|
||||
}
|
||||
return t(locale, keyMap[status ?? 'unavailable'])
|
||||
}
|
||||
|
||||
export function kernelIrqchipHint(locale: Locale, opt: Optimization | undefined): string {
|
||||
if (!opt) return t(locale, 'optKernelIrqchipUnavailable')
|
||||
if (opt.status === 'recommended') return t(locale, 'optKernelIrqchipRec')
|
||||
if (opt.status === 'experimental') return t(locale, 'optKernelIrqchipExp')
|
||||
if (opt.detail === 'win10-needs-patch') return t(locale, 'optKernelIrqchipWin10NoPatch')
|
||||
if (opt.detail && opt.detail.startsWith('0x')) return t(locale, 'optKernelIrqchipNestedErr', { code: opt.detail })
|
||||
return t(locale, 'optKernelIrqchipUnavailable')
|
||||
}
|
||||
|
||||
const IRQCHIP_RE = /(?:^|\s)-machine\s+kernel-irqchip=(on|off)(?=\s|$)/i
|
||||
const INLINE_IRQCHIP_RE = /\bkernel-irqchip=(on|off)\b/i
|
||||
|
||||
export function parseKernelIrqchip(extraArgs: string | undefined): KernelIrqchipMode {
|
||||
const raw = (extraArgs ?? '').trim()
|
||||
const m = raw.match(IRQCHIP_RE) ?? raw.match(INLINE_IRQCHIP_RE)
|
||||
if (!m) return 'auto'
|
||||
return m[1].toLowerCase() === 'on' ? 'on' : 'off'
|
||||
}
|
||||
|
||||
export function applyKernelIrqchip(extraArgs: string | undefined, mode: KernelIrqchipMode): string {
|
||||
const cleaned = (extraArgs ?? '')
|
||||
.replace(/(?:^|\s)-machine\s+kernel-irqchip=(?:on|off)(?=\s|$)/gi, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
if (mode === 'auto') return cleaned
|
||||
const flag = `-machine kernel-irqchip=${mode}`
|
||||
return cleaned ? `${cleaned} ${flag}` : flag
|
||||
}
|
||||
@@ -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]
|
||||
@@ -19,7 +32,9 @@ export function currentTask(all: Record<string, Task>): { task: Task | null; run
|
||||
export function taskTitle(locale: Locale, task: Task): string {
|
||||
switch (task.kind) {
|
||||
case 'installer-download': return t(locale, 'taskDownload', { v: task.subject })
|
||||
case 'recovery-download': return t(locale, 'taskRecoveryDownload', { name: task.subject })
|
||||
case 'vm-create': return t(locale, 'taskCreate', { name: task.subject })
|
||||
case 'runtime-install': return t(locale, 'taskRuntime', { v: task.subject })
|
||||
default: return task.subject
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,85 +1,246 @@
|
||||
/* Design tokens. Components reference these only — no raw colours, sizes or
|
||||
spacing in component CSS or inline styles. See docs/ui-redesign.md §4.1. */
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
/* Bundled open-source Inter Variable (SIL OFL 1.1, Latin ~47 KB) — optical twin of Apple SF Pro. */
|
||||
@font-face {
|
||||
font-family: "ReimsSans";
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
font-weight: 100 900;
|
||||
src: url("@fontsource-variable/inter/files/inter-latin-wght-normal.woff2") format("woff2-variations");
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
|
||||
/* Type */
|
||||
--font-sans: "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
|
||||
--font-mono: "Cascadia Mono", "JetBrains Mono", Consolas, monospace;
|
||||
--fs-12: 12px; /* captions, badges, log text */
|
||||
--fs-13: 13px; /* secondary text, controls */
|
||||
--fs-14: 14px; /* body */
|
||||
--fs-16: 16px; /* subtitles */
|
||||
--fs-20: 20px; /* page titles */
|
||||
--fs-24: 24px; /* empty-state titles */
|
||||
--fw-regular: 400;
|
||||
--fw-strong: 600;
|
||||
/* Map installed PingFang SC / HarmonyOS Sans SC / MiSans / Noto Sans SC / Source Han Sans CN
|
||||
explicitly across weights. On Windows DirectWrite, PingFang SC Regular renders overly thin
|
||||
compared to macOS Retina CoreText, so body weights (400–550) map to Medium for balanced ink. */
|
||||
@font-face {
|
||||
font-family: "ReimsCJK";
|
||||
font-style: normal;
|
||||
font-weight: 400 550;
|
||||
src:
|
||||
local("PingFang SC Medium"), local("PingFangSC-Medium"),
|
||||
local("HarmonyOS Sans SC"), local("HarmonyOS_Sans_SC"),
|
||||
local("MiSans Regular"), local("MiSans"),
|
||||
local("Noto Sans SC Medium"), local("NotoSansSC-Medium"),
|
||||
local("Noto Sans SC"), local("NotoSansSC-Regular"),
|
||||
local("Source Han Sans CN Medium"), local("SourceHanSansCN-Medium"),
|
||||
local("Source Han Sans CN Regular"), local("SourceHanSansCN-Regular");
|
||||
unicode-range: U+2E80-9FFF, U+3000-303F, U+FF00-FFEF, U+F900-FAFF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: "ReimsCJK";
|
||||
font-style: normal;
|
||||
font-weight: 560 900;
|
||||
src:
|
||||
local("PingFang SC Semibold"), local("PingFangSC-Semibold"),
|
||||
local("PingFang SC Bold"), local("PingFangSC-Bold"),
|
||||
local("HarmonyOS Sans SC Bold"), local("HarmonyOS_Sans_SC_Bold"),
|
||||
local("MiSans Demibold"), local("MiSans Semibold"), local("MiSans Bold"),
|
||||
local("Noto Sans SC SemiBold"), local("NotoSansSC-SemiBold"), local("Noto Sans SC Bold"),
|
||||
local("Source Han Sans CN Bold"), local("SourceHanSansCN-Bold");
|
||||
unicode-range: U+2E80-9FFF, U+3000-303F, U+FF00-FFEF, U+F900-FAFF;
|
||||
}
|
||||
|
||||
/* Design tokens — macOS Tahoe aesthetic with Windows platform craft (Light default, Dark & System supported). */
|
||||
:root {
|
||||
color-scheme: light;
|
||||
|
||||
/* Typography */
|
||||
--font-sans: "ReimsSans", "ReimsCJK", "PingFang SC Medium", "PingFang SC", "HarmonyOS Sans SC", "MiSans", "Noto Sans SC", "Source Han Sans CN", -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", system-ui, sans-serif;
|
||||
--font-mono: "SF Mono", "JetBrains Mono", "Cascadia Mono", Consolas, monospace;
|
||||
--fs-11: 11px;
|
||||
--fs-12: 12px;
|
||||
--fs-13: 13px;
|
||||
--fs-14: 14px;
|
||||
--fs-15: 15px;
|
||||
--fs-16: 16px;
|
||||
--fs-20: 20px;
|
||||
--fs-24: 24px;
|
||||
--fw-regular: 450;
|
||||
--fw-medium: 540;
|
||||
--fw-strong: 640;
|
||||
|
||||
/* Spacing (4px grid) */
|
||||
--sp-1: 4px;
|
||||
--sp-2: 8px;
|
||||
--sp-3: 12px;
|
||||
--sp-4: 16px;
|
||||
--sp-5: 20px;
|
||||
--sp-6: 24px;
|
||||
--sp-8: 32px;
|
||||
|
||||
/* Radius */
|
||||
--r-sm: 4px;
|
||||
--r-md: 6px;
|
||||
--r-lg: 8px;
|
||||
--r-xl: 12px;
|
||||
--r-sm: 6px;
|
||||
--r-md: 8px;
|
||||
--r-lg: 12px;
|
||||
--r-xl: 16px;
|
||||
|
||||
/* Surfaces */
|
||||
--surface-0: #1c1c1f; /* window */
|
||||
--surface-sidebar: #171719;
|
||||
--surface-chrome: #141416; /* title bar, log bar */
|
||||
--surface-1: rgba(255, 255, 255, 0.04); /* cards */
|
||||
--surface-2: #26262b; /* menus, dialogs, tooltips */
|
||||
--surface-input: rgba(0, 0, 0, 0.25);
|
||||
--surface-hover: rgba(255, 255, 255, 0.06);
|
||||
--surface-active: rgba(255, 255, 255, 0.10);
|
||||
--border: rgba(255, 255, 255, 0.08);
|
||||
--border-strong: rgba(255, 255, 255, 0.14);
|
||||
--scrim: rgba(0, 0, 0, 0.55);
|
||||
/* Surfaces (macOS Tahoe Light) */
|
||||
--surface-0: #ffffff;
|
||||
--surface-canvas: #ffffff;
|
||||
--surface-sidebar-rail: linear-gradient(180deg, #e7f0fa 0%, #dde8f7 100%);
|
||||
--surface-sidebar: linear-gradient(180deg, rgba(255, 255, 255, 0.80) 0%, rgba(247, 250, 255, 0.72) 100%);
|
||||
--surface-sidebar-border: rgba(255, 255, 255, 0.90);
|
||||
--surface-sidebar-shadow: 0 4px 18px rgba(15, 35, 70, 0.065), 0 0 0 1px rgba(15, 23, 42, 0.06);
|
||||
--surface-chrome: linear-gradient(180deg, #eff4fb 0%, #e8f0fa 100%);
|
||||
--surface-statusbar: #eef3fa;
|
||||
--surface-1: #f5f6f8;
|
||||
--surface-card-elevated: #ffffff;
|
||||
--surface-2: rgba(255, 255, 255, 0.94);
|
||||
--surface-input: #ffffff;
|
||||
--surface-hover: rgba(15, 23, 42, 0.048);
|
||||
--surface-active: rgba(15, 23, 42, 0.085);
|
||||
--border: rgba(15, 23, 42, 0.08);
|
||||
--border-strong: rgba(15, 23, 42, 0.14);
|
||||
--highlight-top: inset 0 1px 0 rgba(255, 255, 255, 0.85);
|
||||
--scrim: rgba(15, 23, 42, 0.28);
|
||||
--shadow-btn: 0 1px 2px rgba(15, 23, 42, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.7);
|
||||
--shadow-card: 0 1px 2px rgba(15, 23, 42, 0.025);
|
||||
--shadow-overlay: 0 22px 58px rgba(15, 23, 42, 0.18), 0 4px 14px rgba(15, 23, 42, 0.06), 0 0 0 1px rgba(15, 23, 42, 0.06);
|
||||
--blur-chrome: blur(20px) saturate(180%);
|
||||
--blur-overlay: blur(18px) saturate(165%);
|
||||
|
||||
/* Text */
|
||||
--text: #f2f2f4;
|
||||
--text-2: #a8a8b0;
|
||||
--text-3: #74747e;
|
||||
--text-code: #c9ccd6;
|
||||
--text: #1d1d1f;
|
||||
--text-2: #424247;
|
||||
--text-3: #6e6e73;
|
||||
--text-code: #2c2c30;
|
||||
|
||||
/* Semantics */
|
||||
--accent: #3b8cf6;
|
||||
--accent-hover: #5299f7;
|
||||
/* Semantics (Apple System Colours) */
|
||||
--accent: #007aff;
|
||||
--accent-hover: #006be6;
|
||||
--accent-text: #ffffff;
|
||||
--accent-soft: rgba(59, 140, 246, 0.18);
|
||||
--accent-soft-text: #8dbcfb;
|
||||
--focus-ring: 0 0 0 2px rgba(59, 140, 246, 0.55);
|
||||
--accent-soft: rgba(0, 122, 255, 0.11);
|
||||
--accent-soft-text: #0066d6;
|
||||
--focus-ring: 0 0 0 3px rgba(0, 122, 255, 0.30);
|
||||
|
||||
--status-running: #3fb950;
|
||||
--status-busy: #d4a72c;
|
||||
--status-error: #f0625a;
|
||||
--status-idle: #74747e;
|
||||
--status-running: #28cd41;
|
||||
--status-busy: #ff9f0a;
|
||||
--status-error: #ff3b30;
|
||||
--status-idle: #aeaeb2;
|
||||
|
||||
--danger: #f0625a;
|
||||
--danger-soft: rgba(240, 98, 90, 0.14);
|
||||
--notice-soft: rgba(212, 167, 44, 0.10);
|
||||
--notice-border: rgba(212, 167, 44, 0.32);
|
||||
--ok-soft: rgba(40, 205, 65, 0.13);
|
||||
--ok-text: #188c2c;
|
||||
--warn-soft: rgba(255, 159, 10, 0.14);
|
||||
--warn-text: #a86200;
|
||||
|
||||
/* Motion */
|
||||
--dur-fast: 120ms;
|
||||
--dur: 200ms;
|
||||
--danger: #ff3b30;
|
||||
--danger-soft: rgba(255, 59, 48, 0.10);
|
||||
--danger-border: rgba(255, 59, 48, 0.28);
|
||||
--danger-text: #d70015;
|
||||
--notice-soft: rgba(255, 159, 10, 0.10);
|
||||
--notice-border: rgba(255, 159, 10, 0.28);
|
||||
|
||||
--seg-thumb: #ffffff;
|
||||
|
||||
/* Motion (emil-design-eng & apple-design curves) */
|
||||
--ease-out: cubic-bezier(0.23, 1, 0.32, 1);
|
||||
--ease-in-out: cubic-bezier(0.77, 0, 0.175, 1);
|
||||
--ease-spring: cubic-bezier(0.32, 0.72, 0, 1);
|
||||
--dur-press: 100ms;
|
||||
--dur-fast: 130ms;
|
||||
--dur: 180ms;
|
||||
--dur-modal: 220ms;
|
||||
--dur-toast: 280ms;
|
||||
|
||||
/* Layout */
|
||||
--titlebar-h: 40px;
|
||||
--titlebar-h: 42px;
|
||||
--logbar-h: 32px;
|
||||
--sidebar-w: 232px;
|
||||
--page-max: 960px;
|
||||
--sidebar-w: 248px;
|
||||
--page-max: 632px;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
|
||||
--surface-0: #1b1c20;
|
||||
--surface-canvas: #1d1e23;
|
||||
--surface-sidebar-rail: #17181c;
|
||||
--surface-sidebar: linear-gradient(180deg, rgba(40, 41, 48, 0.94) 0%, rgba(34, 35, 41, 0.92) 100%);
|
||||
--surface-sidebar-border: rgba(255, 255, 255, 0.09);
|
||||
--surface-sidebar-shadow: 0 6px 22px rgba(0, 0, 0, 0.36), inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
||||
--surface-chrome: linear-gradient(180deg, #212228 0%, #1c1d22 100%);
|
||||
--surface-statusbar: #18191e;
|
||||
--surface-1: rgba(255, 255, 255, 0.048);
|
||||
--surface-card-elevated: rgba(255, 255, 255, 0.075);
|
||||
--surface-2: rgba(42, 43, 50, 0.94);
|
||||
--surface-input: rgba(0, 0, 0, 0.28);
|
||||
--surface-hover: rgba(255, 255, 255, 0.075);
|
||||
--surface-active: rgba(255, 255, 255, 0.12);
|
||||
--border: rgba(255, 255, 255, 0.085);
|
||||
--border-strong: rgba(255, 255, 255, 0.16);
|
||||
--highlight-top: inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
||||
--scrim: rgba(0, 0, 0, 0.56);
|
||||
--shadow-btn: 0 1px 2px rgba(0, 0, 0, 0.30), inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
||||
--shadow-card: 0 1px 3px rgba(0, 0, 0, 0.18);
|
||||
--shadow-overlay: 0 26px 68px rgba(0, 0, 0, 0.58), 0 0 0 1px rgba(255, 255, 255, 0.09);
|
||||
|
||||
--text: #f5f5f7;
|
||||
--text-2: #c2c2ca;
|
||||
--text-3: #92929c;
|
||||
--text-code: #d4d6e0;
|
||||
|
||||
--accent: #0a84ff;
|
||||
--accent-hover: #2492ff;
|
||||
--accent-text: #ffffff;
|
||||
--accent-soft: rgba(10, 132, 255, 0.20);
|
||||
--accent-soft-text: #64b0ff;
|
||||
--focus-ring: 0 0 0 3px rgba(10, 132, 255, 0.45);
|
||||
|
||||
--status-running: #30d158;
|
||||
--status-busy: #ffd60a;
|
||||
--status-error: #ff453a;
|
||||
--status-idle: #6e6e76;
|
||||
|
||||
--ok-soft: rgba(48, 209, 88, 0.16);
|
||||
--ok-text: #30d158;
|
||||
--warn-soft: rgba(255, 214, 10, 0.15);
|
||||
--warn-text: #ffd60a;
|
||||
|
||||
--danger: #ff453a;
|
||||
--danger-soft: rgba(255, 69, 58, 0.15);
|
||||
--danger-border: rgba(255, 69, 58, 0.34);
|
||||
--danger-text: #ff8b83;
|
||||
--notice-soft: rgba(255, 214, 10, 0.10);
|
||||
--notice-border: rgba(255, 214, 10, 0.28);
|
||||
|
||||
--seg-thumb: #555760;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
:root {
|
||||
--dur-press: 0ms;
|
||||
--dur-fast: 0ms;
|
||||
--dur: 0ms;
|
||||
--dur-modal: 0ms;
|
||||
--dur-toast: 0ms;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-transparency: reduce) {
|
||||
:root {
|
||||
--surface-chrome: #ffffff;
|
||||
--surface-2: #ffffff;
|
||||
--surface-sidebar: #eef3fa;
|
||||
--blur-chrome: none;
|
||||
--blur-overlay: none;
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
--surface-chrome: #1b1c20;
|
||||
--surface-2: #2a2b32;
|
||||
--surface-sidebar: #24252b;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-contrast: more) {
|
||||
:root {
|
||||
--border: rgba(15, 23, 42, 0.20);
|
||||
--border-strong: rgba(15, 23, 42, 0.34);
|
||||
--text-2: #3a3a3d;
|
||||
--text-3: #5a5a5f;
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
--border: rgba(255, 255, 255, 0.20);
|
||||
--border-strong: rgba(255, 255, 255, 0.34);
|
||||
--text-2: #d2d2da;
|
||||
--text-3: #a6a6b0;
|
||||
}
|
||||
}
|
||||
@@ -1,209 +1,124 @@
|
||||
// Backend types come from the Wails-generated models (wailsjs/go/models.ts,
|
||||
// regenerated by `wails dev` / `wails build`). This file only adds what Go
|
||||
// cannot say: string unions, and `| null` for slices Go may send as nil.
|
||||
import { app, config, host, installer, reims, runtime, version } from '../wailsjs/go/models'
|
||||
|
||||
/** A generated class as a plain data shape (no convertValues helper). */
|
||||
type Model<T> = Omit<T, 'convertValues'>
|
||||
|
||||
export type Locale = 'zh-CN' | 'en-US'
|
||||
|
||||
export interface Config {
|
||||
data_root: string
|
||||
export type RuntimeSource = 'auto' | 'github' | 'gitcode'
|
||||
|
||||
export type Config = Model<config.Config> & {
|
||||
locale: Locale
|
||||
active_runtime?: string
|
||||
auto_pin_pcores: boolean
|
||||
default_gpu?: string
|
||||
runtime_channel?: 'stable' | 'alpha' | ''
|
||||
runtime_source?: RuntimeSource | ''
|
||||
}
|
||||
|
||||
export interface GPUInfo {
|
||||
name: string
|
||||
vulkan_icd: string
|
||||
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'
|
||||
}
|
||||
|
||||
export interface HostReport {
|
||||
os: string
|
||||
arch: string
|
||||
logical_cpus: number
|
||||
physical_cores: number
|
||||
has_hybrid_cores: boolean
|
||||
p_core_count: number
|
||||
e_core_count: number
|
||||
p_core_mask: number
|
||||
p_core_mask_hex: string
|
||||
p_core_logical_cpus?: number[]
|
||||
e_core_logical_cpus?: number[]
|
||||
total_ram_gb: number
|
||||
avail_ram_gb: number
|
||||
data_root: string
|
||||
free_disk_gb: number
|
||||
export type OptimizationStatus = 'recommended' | 'available' | 'experimental' | 'auto' | 'unavailable'
|
||||
|
||||
export type Optimization = Model<host.Optimization> & {
|
||||
id: 'pcore_pin' | 'kernel_irqchip' | 'cold_reboot' | 'discrete_gpu' | string
|
||||
status: OptimizationStatus
|
||||
}
|
||||
|
||||
export type HostReport = Omit<Model<host.Report>, 'gpus' | 'recommended_gpu'> & {
|
||||
whpx: 'ready' | 'no_hypervisor' | 'missing' | 'unsupported'
|
||||
gpus: GPUInfo[]
|
||||
recommended_gpu?: GPUInfo
|
||||
}
|
||||
|
||||
export interface RuntimeManifest {
|
||||
commit: string
|
||||
full_commit: string
|
||||
qemu_version: string
|
||||
util_version: string
|
||||
built_at: string
|
||||
file_count: number
|
||||
dll_count: number
|
||||
raw_bytes: number
|
||||
export type RuntimeManifest = Model<runtime.Manifest>
|
||||
export type InstalledRuntime = Model<runtime.Installed>
|
||||
|
||||
export type RemoteRuntime = Model<runtime.Remote> & {
|
||||
channel: 'stable' | 'alpha'
|
||||
source?: 'github' | 'gitcode'
|
||||
}
|
||||
|
||||
export interface InstalledRuntime {
|
||||
commit: string
|
||||
dir: string
|
||||
active: boolean
|
||||
manifest: RuntimeManifest
|
||||
}
|
||||
|
||||
export interface VMListItem {
|
||||
name: string
|
||||
dir: string
|
||||
pid: number | null
|
||||
export type VMListItem = Model<reims.VMListItem> & {
|
||||
state: 'running' | 'stopped' | 'broken'
|
||||
}
|
||||
|
||||
export interface PendingChange {
|
||||
field: string
|
||||
from: string
|
||||
to: string
|
||||
}
|
||||
export type PendingChange = app.PendingChange
|
||||
|
||||
export interface AppState {
|
||||
export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizations' | 'runtimes' | 'active_runtime' | 'vms'> & {
|
||||
config: Config
|
||||
host: HostReport
|
||||
optimizations?: Optimization[]
|
||||
runtimes: InstalledRuntime[] | null
|
||||
active_runtime?: InstalledRuntime
|
||||
vms: VMListItem[] | null
|
||||
transitions: Record<string, string>
|
||||
pending_changes: Record<string, PendingChange[]>
|
||||
}
|
||||
|
||||
export interface VMDetail {
|
||||
name: string
|
||||
state: string
|
||||
kind: string
|
||||
directory: string
|
||||
cpus: number
|
||||
memory: string
|
||||
disk: string
|
||||
disk_controller: string
|
||||
graphics: string
|
||||
display: string
|
||||
displays: number
|
||||
resolution: string
|
||||
gpu: string
|
||||
has_opencore: boolean
|
||||
has_installer: boolean
|
||||
installer_path?: string
|
||||
cpu_model: string
|
||||
audio: boolean
|
||||
audio_raw: string
|
||||
network: boolean
|
||||
network_summary: string
|
||||
ssh_port: number
|
||||
logs: boolean
|
||||
log_level: string
|
||||
stop_timeout: number
|
||||
capture: boolean
|
||||
borderless: boolean
|
||||
extra_args: string
|
||||
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 interface ValidationIssue {
|
||||
field: string
|
||||
code: string
|
||||
message: string
|
||||
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 interface CreateOpts {
|
||||
name: string
|
||||
dir?: string
|
||||
source_mode?: 'apple' | 'installer' | 'disk'
|
||||
macos?: string
|
||||
installer?: string
|
||||
cpus: number
|
||||
memory: string
|
||||
disk_size?: string
|
||||
disk?: string
|
||||
export type CreateOpts = Model<reims.CreateOpts> & {
|
||||
source_mode?: 'offline' | 'apple' | 'installer' | 'disk'
|
||||
disk_mode?: 'copy' | 'in-place'
|
||||
disk_controller?: 'nvme' | 'ahci' | 'virtio'
|
||||
graphics: 'reims-vgpu' | 'vmware-svga'
|
||||
cpus: number
|
||||
memory: string
|
||||
gpu: string
|
||||
resolution: string
|
||||
displays: number
|
||||
borderless?: boolean
|
||||
audio?: boolean
|
||||
network?: boolean
|
||||
ssh_port?: number
|
||||
logs?: boolean
|
||||
start?: boolean
|
||||
}
|
||||
|
||||
export interface SetOpts {
|
||||
name: string
|
||||
cpus?: number
|
||||
memory?: string
|
||||
graphics?: string
|
||||
displays?: number
|
||||
disk_controller?: string
|
||||
resolution?: string
|
||||
borderless?: boolean
|
||||
capture?: boolean
|
||||
gpu?: string
|
||||
logs?: boolean
|
||||
log_level?: string
|
||||
audio?: boolean
|
||||
audio_backend?: string
|
||||
network?: boolean
|
||||
ssh_port?: number
|
||||
stop_timeout?: number
|
||||
extra_args?: string
|
||||
export type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
|
||||
|
||||
/** A tracked long-running job pushed as "reims:task" (internal/app/tasks.go). */
|
||||
export type Task = Model<app.Task> & {
|
||||
kind: 'installer-download' | 'vm-create' | string
|
||||
status: TaskStatus
|
||||
}
|
||||
|
||||
/** An offline installer Apple offers (`reims-util offline-installer list`). */
|
||||
export type Release = installer.Release
|
||||
|
||||
/** A file kept in the installers directory. */
|
||||
export type CachedInstaller = Model<installer.Cached> & {
|
||||
kind: 'offline' | 'online' | 'ipsw' | 'other'
|
||||
}
|
||||
|
||||
export type DataRootChoice = app.DataRootChoice
|
||||
export type DataRootCheck = app.DataRootCheck
|
||||
|
||||
/** A "reims:log" event (internal/app/app.go emitLog); not a Go struct, so not generated. */
|
||||
export interface LogEntry {
|
||||
ts: string
|
||||
source: string
|
||||
line: string
|
||||
}
|
||||
|
||||
export type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
|
||||
|
||||
/** A tracked long-running job pushed as "reims:task" (tasks.go). */
|
||||
export interface Task {
|
||||
id: string
|
||||
kind: 'installer-download' | 'vm-create' | string
|
||||
subject: string
|
||||
vm?: string
|
||||
step: string
|
||||
done: number
|
||||
total: number
|
||||
/** -1 when unknown */
|
||||
percent: number
|
||||
/** bytes per second, 0 when unknown */
|
||||
rate: number
|
||||
status: TaskStatus
|
||||
error?: string
|
||||
result?: string
|
||||
cancelable: boolean
|
||||
started_at: number
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
/** An offline installer Apple offers (`reims-util offline-installer list`). */
|
||||
export interface Release {
|
||||
product: string
|
||||
title: string
|
||||
version: string
|
||||
build: string
|
||||
posted: string
|
||||
size: number
|
||||
}
|
||||
|
||||
/** A file kept in the installers directory. */
|
||||
export interface CachedInstaller {
|
||||
name: string
|
||||
path: string
|
||||
bytes: number
|
||||
kind: 'offline' | 'online' | 'ipsw' | 'other'
|
||||
partial: boolean
|
||||
title?: string
|
||||
version?: string
|
||||
build?: string
|
||||
}
|
||||
@@ -44,7 +44,7 @@ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
aria-busy={busy || undefined}
|
||||
{...rest}
|
||||
>
|
||||
{busy ? <LoaderCircle size={14} className="spin" /> : icon}
|
||||
{busy ? <LoaderCircle size={14} className="spin" aria-hidden="true" /> : icon}
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
@@ -73,7 +73,7 @@ export const IconButton = React.forwardRef<HTMLButtonElement, IconButtonProps>(
|
||||
aria-busy={busy || undefined}
|
||||
{...rest}
|
||||
>
|
||||
{busy ? <LoaderCircle size={16} className="spin" /> : icon}
|
||||
{busy ? <LoaderCircle size={16} className="spin" aria-hidden="true" /> : icon}
|
||||
</button>
|
||||
</Tip>
|
||||
),
|
||||
|
||||
@@ -10,16 +10,18 @@ interface Props {
|
||||
/** While false, Esc / outside click / ✕ are ignored (e.g. during a create). */
|
||||
dismissable?: boolean
|
||||
onClose: () => void
|
||||
/** Extra class on the dialog box, e.g. a wider variant. */
|
||||
className?: string
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
/** Modal frame: head with title and ✕; children supply body/steps/foot sections. */
|
||||
export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissable = true, onClose, children }) => (
|
||||
export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, children }) => (
|
||||
<RDialog.Root open onOpenChange={(open) => { if (!open && dismissable) onClose() }}>
|
||||
<RDialog.Portal>
|
||||
<RDialog.Overlay className="overlay" />
|
||||
<RDialog.Content
|
||||
className="dialog"
|
||||
className={className ? `dialog ${className}` : 'dialog'}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
// Focus the first form field rather than ✕, so the close tooltip doesn't pop on open.
|
||||
onOpenAutoFocus={(e) => {
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import { Check, ChevronsUpDown, CircleAlert, Lock, RotateCcw } from 'lucide-react'
|
||||
import React, { useEffect, useId, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { IconButton } from './controls'
|
||||
|
||||
// Settings page primitives (docs/ui-redesign.md, docs/shell-design.md §4):
|
||||
// one row shell — title and description on the left, the control on the
|
||||
// right — plus the switch, segmented control, range field and option cards
|
||||
// every category builds its rows from, so the whole panel reads as one set.
|
||||
|
||||
/** A labelled block of rows, like a grouped list in macOS System Settings. */
|
||||
export const SetGroup: React.FC<{ title?: string; note?: React.ReactNode; children: React.ReactNode }> = ({ title, note, children }) => (
|
||||
<section className="sgroup">
|
||||
{title && <h3 className="sgroup-title">{title}</h3>}
|
||||
<div className="sgroup-list">{children}</div>
|
||||
{note && <p className="sgroup-note">{note}</p>}
|
||||
</section>
|
||||
)
|
||||
|
||||
interface RowProps {
|
||||
title: string
|
||||
desc?: React.ReactNode
|
||||
/** Control drawn on the right of the title. */
|
||||
control?: React.ReactNode
|
||||
/** Control drawn under the title at full width (sliders, cards). */
|
||||
block?: React.ReactNode
|
||||
/** The value differs from what the VM has now. */
|
||||
dirty?: boolean
|
||||
onReset?: () => void
|
||||
resetLabel?: string
|
||||
/** The row can't act right now; `reason` says why. */
|
||||
disabled?: boolean
|
||||
reason?: string
|
||||
error?: string
|
||||
/** Anchor so a validation error can scroll its row into view. */
|
||||
field?: string
|
||||
}
|
||||
|
||||
/** One setting: title, one line of description, a control, and its state marks. */
|
||||
export const SetRow: React.FC<RowProps> = ({ title, desc, control, block, dirty, onReset, resetLabel, disabled, reason, error, field }) => {
|
||||
const titleId = useId()
|
||||
return (
|
||||
<div
|
||||
className="srow"
|
||||
data-field={field}
|
||||
data-dirty={dirty || undefined}
|
||||
data-disabled={disabled || undefined}
|
||||
data-error={error ? true : undefined}
|
||||
role="group"
|
||||
aria-labelledby={titleId}
|
||||
>
|
||||
<div className="srow-head">
|
||||
<div className="srow-text">
|
||||
<div className="srow-title" id={titleId}>
|
||||
{title}
|
||||
{dirty && <span className="dirty-dot" aria-hidden="true" />}
|
||||
</div>
|
||||
{desc && <div className="srow-desc">{desc}</div>}
|
||||
{disabled && reason && (
|
||||
<div className="srow-reason"><Lock size={12} aria-hidden="true" />{reason}</div>
|
||||
)}
|
||||
</div>
|
||||
{(control || (dirty && onReset)) && (
|
||||
<div className="srow-ctrl">
|
||||
{dirty && onReset && !disabled && (
|
||||
<IconButton small label={resetLabel ?? 'Reset'} icon={<RotateCcw size={13} />} onClick={onReset} className="srow-reset" tipSide="top" />
|
||||
)}
|
||||
{control && <fieldset className="srow-fieldset" disabled={disabled}>{control}</fieldset>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{block && <fieldset className="srow-fieldset srow-block" disabled={disabled}>{block}</fieldset>}
|
||||
{error && <div className="srow-error" role="alert"><CircleAlert size={13} aria-hidden="true" />{error}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Read-only row: a label and its value. */
|
||||
export const SetValue: React.FC<{ title: string; value: React.ReactNode; mono?: boolean }> = ({ title, value, mono }) => (
|
||||
<div className="srow srow-kv">
|
||||
<div className="srow-head">
|
||||
<div className="srow-title">{title}</div>
|
||||
<div className={`srow-value${mono ? ' mono' : ''}`}>{value}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
export const Switch: React.FC<{ checked: boolean; onChange: (v: boolean) => void; label: string; disabled?: boolean }> = ({ checked, onChange, label, disabled }) => (
|
||||
<label className="switch">
|
||||
<input type="checkbox" role="switch" aria-label={label} checked={checked} disabled={disabled} onChange={(e) => onChange(e.target.checked)} />
|
||||
<span className="slider" />
|
||||
</label>
|
||||
)
|
||||
|
||||
export interface SegOption<V> {
|
||||
value: V
|
||||
label: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Segmented control with a sliding highlight. A radio group under the hood:
|
||||
* arrow keys move the choice, Tab leaves the group.
|
||||
*/
|
||||
export function Segmented<V extends string | number>({ options, value, onChange, label, wide }: {
|
||||
options: SegOption<V>[]
|
||||
value: V | undefined
|
||||
onChange: (v: V) => void
|
||||
label: string
|
||||
/** Stretch to the row's width with equal segments. */
|
||||
wide?: boolean
|
||||
}) {
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
const [thumb, setThumb] = useState<{ x: number; w: number } | null>(null)
|
||||
|
||||
const measure = () => {
|
||||
const el = box.current?.querySelector<HTMLElement>('[aria-checked="true"]')
|
||||
setThumb(el ? { x: el.offsetLeft, w: el.offsetWidth } : null)
|
||||
}
|
||||
useLayoutEffect(measure, [value, options])
|
||||
useEffect(() => {
|
||||
if (!box.current || typeof ResizeObserver === 'undefined') return
|
||||
const ro = new ResizeObserver(measure)
|
||||
ro.observe(box.current)
|
||||
return () => ro.disconnect()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
const onKey = (e: React.KeyboardEvent) => {
|
||||
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return
|
||||
e.preventDefault()
|
||||
const enabled = options.filter((o) => !o.disabled)
|
||||
const i = enabled.findIndex((o) => o.value === value)
|
||||
const next = enabled[(i + (e.key === 'ArrowRight' ? 1 : -1) + enabled.length) % enabled.length]
|
||||
if (next) {
|
||||
onChange(next.value)
|
||||
requestAnimationFrame(() => box.current?.querySelector<HTMLElement>('[aria-checked="true"]')?.focus())
|
||||
}
|
||||
}
|
||||
|
||||
const hasActive = options.some((o) => o.value === value)
|
||||
return (
|
||||
<div ref={box} className={`seg${wide ? ' seg-wide' : ''}`} role="radiogroup" aria-label={label} onKeyDown={onKey}>
|
||||
{thumb && <span className="seg-thumb" style={{ transform: `translateX(${thumb.x}px)`, width: thumb.w }} aria-hidden="true" />}
|
||||
{options.map((o, i) => {
|
||||
const on = o.value === value
|
||||
return (
|
||||
<button
|
||||
key={String(o.value)}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={on}
|
||||
tabIndex={on || (!hasActive && i === 0) ? 0 : -1}
|
||||
disabled={o.disabled}
|
||||
onClick={() => onChange(o.value)}
|
||||
>
|
||||
{o.label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface NumberProps {
|
||||
value: number
|
||||
min: number
|
||||
max: number
|
||||
step?: number
|
||||
unit?: string
|
||||
label: string
|
||||
onChange: (v: number) => void
|
||||
/** Width in characters; the default fits five digits. */
|
||||
size?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Number field with a unit suffix and no spinner. It keeps what is typed so
|
||||
* far and commits a whole, clamped number on Enter or blur; ↑/↓ step it.
|
||||
*/
|
||||
export const NumberField: React.FC<NumberProps> = ({ value, min, max, step = 1, unit, label, onChange, size = 5 }) => {
|
||||
const [text, setText] = useState(String(value))
|
||||
useEffect(() => { setText(String(value)) }, [value])
|
||||
const clamp = (v: number) => Math.min(max, Math.max(min, Math.round(v / step) * step))
|
||||
const commit = () => {
|
||||
const n = Number.parseFloat(text)
|
||||
if (!Number.isFinite(n)) { setText(String(value)); return }
|
||||
const c = clamp(n)
|
||||
setText(String(c))
|
||||
if (c !== value) onChange(c)
|
||||
}
|
||||
return (
|
||||
<div className="num-field">
|
||||
<input
|
||||
className="num-input"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
aria-label={label}
|
||||
style={{ width: `${size + 1.5}ch` }}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value.replace(/[^\d.]/g, ''))}
|
||||
onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); commit() }
|
||||
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
onChange(clamp(value + (e.key === 'ArrowUp' ? step : -step)))
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{unit && <span className="num-unit">{unit}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Drop marks that would sit closer than `gap` percent to the one before. */
|
||||
function thinMarks(marks: RangeMark[], min: number, max: number, gap = 9): RangeMark[] {
|
||||
const span = Math.max(max - min, 1)
|
||||
const out: RangeMark[] = []
|
||||
let last = -Infinity
|
||||
for (const m of marks) {
|
||||
if (m.value < min || m.value > max) continue
|
||||
const p = ((m.value - min) / span) * 100
|
||||
if (p - last < gap) continue
|
||||
out.push(m)
|
||||
last = p
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export interface RangeMark {
|
||||
value: number
|
||||
label: string
|
||||
}
|
||||
|
||||
interface RangeProps {
|
||||
value: number
|
||||
min: number
|
||||
max: number
|
||||
step?: number
|
||||
unit: string
|
||||
label: string
|
||||
onChange: (v: number) => void
|
||||
/** Clickable labels under the track. */
|
||||
marks?: RangeMark[]
|
||||
/** Highlighted "recommended" span of the track. */
|
||||
recommend?: [number, number]
|
||||
/** From here to the end the track turns amber. */
|
||||
warnFrom?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Slider and number field bound to one value. The slider and the marks write
|
||||
* straight away; the field commits on Enter or blur (NumberField).
|
||||
*/
|
||||
export const RangeField: React.FC<RangeProps> = ({ value, min, max, step = 1, unit, label, onChange, marks, recommend, warnFrom }) => {
|
||||
const span = Math.max(max - min, 1)
|
||||
const pct = (v: number) => `${((Math.min(max, Math.max(min, v)) - min) / span) * 100}%`
|
||||
const shown = marks ? thinMarks(marks, min, max) : []
|
||||
|
||||
const over = warnFrom !== undefined && value >= warnFrom
|
||||
return (
|
||||
<div className="range-field" data-warn={over || undefined}>
|
||||
<div className="range-main">
|
||||
<div className="range-rail-wrap">
|
||||
<div className="range-rail" aria-hidden="true">
|
||||
<div className="range-track" />
|
||||
{recommend && (
|
||||
<div className="range-band rec" style={{ left: pct(recommend[0]), width: `calc(${pct(recommend[1])} - ${pct(recommend[0])})` }} />
|
||||
)}
|
||||
{warnFrom !== undefined && warnFrom <= max && (
|
||||
<div className="range-band warn" style={{ left: pct(warnFrom), right: 0 }} />
|
||||
)}
|
||||
<div className="range-fill" style={{ width: pct(value) }} />
|
||||
</div>
|
||||
<input
|
||||
className="range"
|
||||
type="range"
|
||||
aria-label={label}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
value={value}
|
||||
onChange={(e) => onChange(Number(e.target.value))}
|
||||
/>
|
||||
{shown.length > 0 && (
|
||||
<div className="range-marks">
|
||||
{shown.map((m) => (
|
||||
<button
|
||||
key={m.value}
|
||||
type="button"
|
||||
tabIndex={-1}
|
||||
className="range-mark"
|
||||
aria-pressed={m.value === value}
|
||||
style={{ left: pct(m.value) }}
|
||||
onClick={() => onChange(m.value)}
|
||||
>
|
||||
{m.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<NumberField value={value} min={min} max={max} step={step} unit={unit} label={label} onChange={onChange} size={3} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export interface CardOption<V> {
|
||||
value: V
|
||||
title: string
|
||||
sub?: string
|
||||
badges?: string[]
|
||||
/** Small picture drawn above the title (e.g. a screen shape). */
|
||||
art?: React.ReactNode
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
/** A row of option cards, one picked: a radio group with larger targets. */
|
||||
export function OptionCards<V extends string>({ options, value, onChange, label, columns }: {
|
||||
options: CardOption<V>[]
|
||||
value: V | undefined
|
||||
onChange: (v: V) => void
|
||||
label: string
|
||||
columns?: number
|
||||
}) {
|
||||
const name = useId()
|
||||
return (
|
||||
<div className="opt-cards" role="radiogroup" aria-label={label} style={columns ? { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` } : undefined}>
|
||||
{options.map((o) => (
|
||||
<label key={o.value} className="opt-card" data-selected={o.value === value || undefined} data-disabled={o.disabled || undefined}>
|
||||
<input type="radio" name={name} checked={o.value === value} disabled={o.disabled} onChange={() => onChange(o.value)} />
|
||||
{o.art}
|
||||
<span className="opt-card-title" title={o.title}>{o.title}</span>
|
||||
{o.sub && <span className="opt-card-sub">{o.sub}</span>}
|
||||
{o.badges && o.badges.length > 0 && (
|
||||
<span className="opt-card-badges">{o.badges.map((b) => <span key={b} className="badge badge-accent">{b}</span>)}</span>
|
||||
)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export interface PopupOption<V> {
|
||||
value: V
|
||||
label: string
|
||||
/** Secondary text drawn after the label in grey, e.g. a build number. */
|
||||
detail?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Pop-up button (HIG pop-up-buttons.md): shows the current choice with ⌃⌄
|
||||
* and opens a menu where the current item carries a checkmark. Replaces the
|
||||
* native <select>, whose Windows list ignores the app's theme.
|
||||
*/
|
||||
export function PopupSelect<V extends string>({ value, options, onChange, label, placeholder, wide, id }: {
|
||||
value: V | undefined
|
||||
options: PopupOption<V>[]
|
||||
onChange: (v: V) => void
|
||||
label: string
|
||||
placeholder?: string
|
||||
/** Fill the container's width instead of sizing to the label. */
|
||||
wide?: boolean
|
||||
id?: string
|
||||
}) {
|
||||
const cur = options.find((o) => o.value === value)
|
||||
return (
|
||||
<Menu.Root modal={false}>
|
||||
<Menu.Trigger asChild>
|
||||
<button type="button" id={id} className={`popup-btn${wide ? ' popup-wide' : ''}`} aria-label={label}>
|
||||
<span className="popup-value">
|
||||
{cur ? cur.label : <span className="muted">{placeholder ?? value ?? ''}</span>}
|
||||
{cur?.detail && <span className="popup-detail">{cur.detail}</span>}
|
||||
</span>
|
||||
<ChevronsUpDown size={13} aria-hidden="true" className="popup-chevron" />
|
||||
</button>
|
||||
</Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Content className="menu popup-menu" align="start" sideOffset={4} collisionPadding={8}>
|
||||
<Menu.RadioGroup value={value ?? ''} onValueChange={(v) => onChange(v as V)}>
|
||||
{options.map((o) => (
|
||||
<Menu.RadioItem key={o.value} value={o.value} disabled={o.disabled} className="menu-item popup-item">
|
||||
<Menu.ItemIndicator className="popup-check"><Check size={13} /></Menu.ItemIndicator>
|
||||
<span className="popup-item-label">{o.label}</span>
|
||||
{o.detail && <span className="popup-detail">{o.detail}</span>}
|
||||
</Menu.RadioItem>
|
||||
))}
|
||||
</Menu.RadioGroup>
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
</Menu.Root>
|
||||
)
|
||||
}
|
||||
|
||||
/** A screen outline with the resolution's aspect ratio. */
|
||||
export const ScreenArt: React.FC<{ w: number; h: number }> = ({ w, h }) => {
|
||||
const W = 44
|
||||
const H = Math.max(18, Math.min(34, Math.round((W * h) / Math.max(w, 1))))
|
||||
return <span className="screen-art" style={{ width: W, height: H }} aria-hidden="true" />
|
||||
}
|
||||
@@ -1,104 +1,26 @@
|
||||
import {
|
||||
AppState,
|
||||
CachedInstaller,
|
||||
Release,
|
||||
Task,
|
||||
CreateOpts,
|
||||
InstalledRuntime,
|
||||
LogEntry,
|
||||
SetOpts,
|
||||
ValidationIssue,
|
||||
VMDetail,
|
||||
} from './types'
|
||||
// Backend calls are the Wails-generated bindings (wailsjs/go/app/App). Only
|
||||
// the calls whose results carry the unions or nil slices added in types.ts are
|
||||
// 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, VMAffinityStatus, VMAffinityUpdate } from './types'
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
go?: {
|
||||
main?: {
|
||||
App?: {
|
||||
GetState(): Promise<AppState>
|
||||
GetVMDetail(name: string): Promise<VMDetail>
|
||||
SetLocale(locale: string): Promise<void>
|
||||
SetAutoPinPCores(enabled: boolean): Promise<void>
|
||||
SetDataRoot(dir: string): Promise<void>
|
||||
PickDirectory(title: string): Promise<string>
|
||||
PickFile(title: string, pattern: string): Promise<string>
|
||||
EnableWHPX(): Promise<void>
|
||||
InstallRuntimeArchive(path: string): Promise<InstalledRuntime>
|
||||
UseRuntime(commit: string): Promise<void>
|
||||
ValidateCreate(opts: CreateOpts): Promise<ValidationIssue[]>
|
||||
PreviewCreate(opts: CreateOpts): Promise<string>
|
||||
CreateVM(opts: CreateOpts): Promise<void>
|
||||
ValidateSet(opts: SetOpts): Promise<ValidationIssue[]>
|
||||
ApplyVMSettings(opts: SetOpts): Promise<void>
|
||||
StartVM(name: string): Promise<void>
|
||||
StopVM(name: string, force: boolean): Promise<void>
|
||||
RestartVM(name: string): Promise<void>
|
||||
EjectInstaller(name: string): Promise<void>
|
||||
DeleteVM(name: string, keepFiles: boolean): Promise<void>
|
||||
ReadVMLogs(name: string, serial: boolean): Promise<string>
|
||||
OpenVMFolder(name: string): Promise<void>
|
||||
GetTasks(): Promise<Task[]>
|
||||
CancelTask(id: string): Promise<void>
|
||||
DismissTask(id: string): Promise<void>
|
||||
ListOfflineReleases(): Promise<Release[]>
|
||||
DownloadInstaller(version: string): Promise<string>
|
||||
ListInstallers(): Promise<CachedInstaller[] | null>
|
||||
DeleteInstaller(name: string): Promise<void>
|
||||
}
|
||||
}
|
||||
}
|
||||
runtime?: {
|
||||
EventsOn(event: string, cb: (...args: any[]) => void): () => void
|
||||
WindowMinimise(): void
|
||||
WindowToggleMaximise(): void
|
||||
Quit(): void
|
||||
}
|
||||
}
|
||||
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>,
|
||||
}
|
||||
|
||||
function app() {
|
||||
const api = window.go?.main?.App
|
||||
if (!api) {
|
||||
throw new Error('Wails backend not attached')
|
||||
}
|
||||
return api
|
||||
}
|
||||
|
||||
export const backend = {
|
||||
getState: () => app().GetState(),
|
||||
getVMDetail: (name: string) => app().GetVMDetail(name),
|
||||
setLocale: (locale: string) => app().SetLocale(locale),
|
||||
setAutoPinPCores: (enabled: boolean) => app().SetAutoPinPCores(enabled),
|
||||
setDataRoot: (dir: string) => app().SetDataRoot(dir),
|
||||
pickDirectory: (title: string) => app().PickDirectory(title),
|
||||
pickFile: (title: string, pattern: string) => app().PickFile(title, pattern),
|
||||
enableWHPX: () => app().EnableWHPX(),
|
||||
installRuntimeArchive: (path: string) => app().InstallRuntimeArchive(path),
|
||||
useRuntime: (commit: string) => app().UseRuntime(commit),
|
||||
validateCreate: (opts: CreateOpts) => app().ValidateCreate(opts),
|
||||
previewCreate: (opts: CreateOpts) => app().PreviewCreate(opts),
|
||||
createVM: (opts: CreateOpts) => app().CreateVM(opts),
|
||||
validateSet: (opts: SetOpts) => app().ValidateSet(opts),
|
||||
applyVMSettings: (opts: SetOpts) => app().ApplyVMSettings(opts),
|
||||
startVM: (name: string) => app().StartVM(name),
|
||||
stopVM: (name: string, force: boolean) => app().StopVM(name, force),
|
||||
restartVM: (name: string) => app().RestartVM(name),
|
||||
ejectInstaller: (name: string) => app().EjectInstaller(name),
|
||||
deleteVM: (name: string, keepFiles: boolean) => app().DeleteVM(name, keepFiles),
|
||||
readVMLogs: (name: string, serial: boolean) => app().ReadVMLogs(name, serial),
|
||||
openVMFolder: (name: string) => app().OpenVMFolder(name),
|
||||
getTasks: () => app().GetTasks(),
|
||||
cancelTask: (id: string) => app().CancelTask(id),
|
||||
dismissTask: (id: string) => app().DismissTask(id),
|
||||
listOfflineReleases: () => app().ListOfflineReleases(),
|
||||
downloadInstaller: (version: string) => app().DownloadInstaller(version),
|
||||
listInstallers: () => app().ListInstallers(),
|
||||
deleteInstaller: (name: string) => app().DeleteInstaller(name),
|
||||
onTask: (cb: (task: Task) => void) => window.runtime?.EventsOn('reims:task', cb) ?? (() => {}),
|
||||
onStateChanged: (cb: () => void) => window.runtime?.EventsOn('reims:state-changed', cb) ?? (() => {}),
|
||||
onLog: (cb: (entry: LogEntry) => void) => window.runtime?.EventsOn('reims:log', cb) ?? (() => {}),
|
||||
winMinimise: () => window.runtime?.WindowMinimise(),
|
||||
winToggleMaximise: () => window.runtime?.WindowToggleMaximise(),
|
||||
winQuit: () => window.runtime?.Quit(),
|
||||
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),
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
import {reims} from '../models';
|
||||
import {version} from '../models';
|
||||
import {app} from '../models';
|
||||
import {runtime} from '../models';
|
||||
import {installer} from '../models';
|
||||
|
||||
export function ApplyVMSettings(arg1:reims.SetOpts):Promise<void>;
|
||||
|
||||
export function AttachGuestTools(arg1:string):Promise<void>;
|
||||
|
||||
export function AttachInstaller(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function CancelTask(arg1:string):Promise<void>;
|
||||
|
||||
export function CheckAppUpdate(arg1:boolean):Promise<version.UpdateInfo>;
|
||||
|
||||
export function CheckDataRoot(arg1:string):Promise<app.DataRootCheck>;
|
||||
|
||||
export function CloneVMCoW(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
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>;
|
||||
|
||||
export function DownloadAndAttachOnlineRecovery(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function DownloadInstaller(arg1:string):Promise<string>;
|
||||
|
||||
export function EjectInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function EnableWHPX():Promise<void>;
|
||||
|
||||
export function EnterRecovery(arg1:string):Promise<void>;
|
||||
|
||||
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>;
|
||||
|
||||
export function InstallRuntimeArchive(arg1:string):Promise<runtime.Installed>;
|
||||
|
||||
export function InstallRuntimeOnline(arg1:string):Promise<string>;
|
||||
|
||||
export function ListInstallers():Promise<Array<installer.Cached>>;
|
||||
|
||||
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>;
|
||||
|
||||
export function PreviewCreate(arg1:reims.CreateOpts):Promise<string>;
|
||||
|
||||
export function QuitApp():Promise<void>;
|
||||
|
||||
export function ReadVMLogs(arg1:string,arg2:boolean):Promise<string>;
|
||||
|
||||
export function RequestClose():Promise<void>;
|
||||
|
||||
export function ResizeVMDisk(arg1:string,arg2:string):Promise<reims.DiskResizeResult>;
|
||||
|
||||
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>;
|
||||
|
||||
export function SetGuestPreventSleep(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function SetLocale(arg1:string):Promise<void>;
|
||||
|
||||
export function SetMinimizeToTray(arg1:boolean):Promise<void>;
|
||||
|
||||
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>;
|
||||
|
||||
export function StopVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function SuggestDataRoots():Promise<Array<app.DataRootChoice>>;
|
||||
|
||||
export function ToggleBorderless(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function TypeClipboard(arg1:string):Promise<number>;
|
||||
|
||||
export function TypeText(arg1:string,arg2:string):Promise<number>;
|
||||
|
||||
export function UpgradeDiskToNVMe(arg1:string):Promise<void>;
|
||||
|
||||
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>;
|
||||
@@ -0,0 +1,331 @@
|
||||
// @ts-check
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
export function ApplyVMSettings(arg1) {
|
||||
return window['go']['app']['App']['ApplyVMSettings'](arg1);
|
||||
}
|
||||
|
||||
export function AttachGuestTools(arg1) {
|
||||
return window['go']['app']['App']['AttachGuestTools'](arg1);
|
||||
}
|
||||
|
||||
export function AttachInstaller(arg1, arg2) {
|
||||
return window['go']['app']['App']['AttachInstaller'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CancelTask(arg1) {
|
||||
return window['go']['app']['App']['CancelTask'](arg1);
|
||||
}
|
||||
|
||||
export function CheckAppUpdate(arg1) {
|
||||
return window['go']['app']['App']['CheckAppUpdate'](arg1);
|
||||
}
|
||||
|
||||
export function CheckDataRoot(arg1) {
|
||||
return window['go']['app']['App']['CheckDataRoot'](arg1);
|
||||
}
|
||||
|
||||
export function CloneVMCoW(arg1, arg2) {
|
||||
return window['go']['app']['App']['CloneVMCoW'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CompactVMDisk(arg1) {
|
||||
return window['go']['app']['App']['CompactVMDisk'](arg1);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function DismissTask(arg1) {
|
||||
return window['go']['app']['App']['DismissTask'](arg1);
|
||||
}
|
||||
|
||||
export function DownloadAndAttachOnlineRecovery(arg1, arg2) {
|
||||
return window['go']['app']['App']['DownloadAndAttachOnlineRecovery'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DownloadInstaller(arg1) {
|
||||
return window['go']['app']['App']['DownloadInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EjectInstaller(arg1) {
|
||||
return window['go']['app']['App']['EjectInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EnableWHPX() {
|
||||
return window['go']['app']['App']['EnableWHPX']();
|
||||
}
|
||||
|
||||
export function EnterRecovery(arg1) {
|
||||
return window['go']['app']['App']['EnterRecovery'](arg1);
|
||||
}
|
||||
|
||||
export function ExportDiagnostics(arg1) {
|
||||
return window['go']['app']['App']['ExportDiagnostics'](arg1);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function GetVMThumbnail(arg1) {
|
||||
return window['go']['app']['App']['GetVMThumbnail'](arg1);
|
||||
}
|
||||
|
||||
export function InstallRuntimeArchive(arg1) {
|
||||
return window['go']['app']['App']['InstallRuntimeArchive'](arg1);
|
||||
}
|
||||
|
||||
export function InstallRuntimeOnline(arg1) {
|
||||
return window['go']['app']['App']['InstallRuntimeOnline'](arg1);
|
||||
}
|
||||
|
||||
export function ListInstallers() {
|
||||
return window['go']['app']['App']['ListInstallers']();
|
||||
}
|
||||
|
||||
export function ListOfflineReleases() {
|
||||
return window['go']['app']['App']['ListOfflineReleases']();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function OpenURL(arg1) {
|
||||
return window['go']['app']['App']['OpenURL'](arg1);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function PickFile(arg1, arg2) {
|
||||
return window['go']['app']['App']['PickFile'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function PreviewCreate(arg1) {
|
||||
return window['go']['app']['App']['PreviewCreate'](arg1);
|
||||
}
|
||||
|
||||
export function QuitApp() {
|
||||
return window['go']['app']['App']['QuitApp']();
|
||||
}
|
||||
|
||||
export function ReadVMLogs(arg1, arg2) {
|
||||
return window['go']['app']['App']['ReadVMLogs'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RequestClose() {
|
||||
return window['go']['app']['App']['RequestClose']();
|
||||
}
|
||||
|
||||
export function ResizeVMDisk(arg1, arg2) {
|
||||
return window['go']['app']['App']['ResizeVMDisk'](arg1, arg2);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function SetDataRoot(arg1) {
|
||||
return window['go']['app']['App']['SetDataRoot'](arg1);
|
||||
}
|
||||
|
||||
export function SetGuestPreventSleep(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetGuestPreventSleep'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetLocale(arg1) {
|
||||
return window['go']['app']['App']['SetLocale'](arg1);
|
||||
}
|
||||
|
||||
export function SetMinimizeToTray(arg1) {
|
||||
return window['go']['app']['App']['SetMinimizeToTray'](arg1);
|
||||
}
|
||||
|
||||
export function SetRuntimeChannel(arg1) {
|
||||
return window['go']['app']['App']['SetRuntimeChannel'](arg1);
|
||||
}
|
||||
|
||||
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']();
|
||||
}
|
||||
|
||||
export function StartVM(arg1) {
|
||||
return window['go']['app']['App']['StartVM'](arg1);
|
||||
}
|
||||
|
||||
export function StopVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['StopVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SuggestDataRoots() {
|
||||
return window['go']['app']['App']['SuggestDataRoots']();
|
||||
}
|
||||
|
||||
export function ToggleBorderless(arg1, arg2) {
|
||||
return window['go']['app']['App']['ToggleBorderless'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function TypeClipboard(arg1) {
|
||||
return window['go']['app']['App']['TypeClipboard'](arg1);
|
||||
}
|
||||
|
||||
export function TypeText(arg1, arg2) {
|
||||
return window['go']['app']['App']['TypeText'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function UpgradeDiskToNVMe(arg1) {
|
||||
return window['go']['app']['App']['UpgradeDiskToNVMe'](arg1);
|
||||
}
|
||||
|
||||
export function UseRuntime(arg1) {
|
||||
return window['go']['app']['App']['UseRuntime'](arg1);
|
||||
}
|
||||
|
||||
export function ValidateCreate(arg1) {
|
||||
return window['go']['app']['App']['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);
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
import {reims} from '../models';
|
||||
import {main} from '../models';
|
||||
import {runtime} from '../models';
|
||||
import {installer} from '../models';
|
||||
|
||||
export function ApplyVMSettings(arg1:reims.SetOpts):Promise<void>;
|
||||
|
||||
export function CancelTask(arg1:string):Promise<void>;
|
||||
|
||||
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
|
||||
|
||||
export function DeleteInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function DeleteVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function DismissTask(arg1:string):Promise<void>;
|
||||
|
||||
export function DownloadInstaller(arg1:string):Promise<string>;
|
||||
|
||||
export function EjectInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function EnableWHPX():Promise<void>;
|
||||
|
||||
export function GetState():Promise<main.AppState>;
|
||||
|
||||
export function GetTasks():Promise<Array<main.Task>>;
|
||||
|
||||
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
|
||||
|
||||
export function InstallRuntimeArchive(arg1:string):Promise<runtime.Installed>;
|
||||
|
||||
export function ListInstallers():Promise<Array<installer.Cached>>;
|
||||
|
||||
export function ListOfflineReleases():Promise<Array<installer.Release>>;
|
||||
|
||||
export function OpenVMFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function PickDirectory(arg1:string):Promise<string>;
|
||||
|
||||
export function PickFile(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function PreviewCreate(arg1:reims.CreateOpts):Promise<string>;
|
||||
|
||||
export function ReadVMLogs(arg1:string,arg2:boolean):Promise<string>;
|
||||
|
||||
export function RestartVM(arg1:string):Promise<void>;
|
||||
|
||||
export function SetAutoPinPCores(arg1:boolean):Promise<void>;
|
||||
|
||||
export function SetDataRoot(arg1:string):Promise<void>;
|
||||
|
||||
export function SetLocale(arg1:string):Promise<void>;
|
||||
|
||||
export function StartVM(arg1:string):Promise<void>;
|
||||
|
||||
export function StopVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
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>>;
|
||||
@@ -1,119 +0,0 @@
|
||||
// @ts-check
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
export function ApplyVMSettings(arg1) {
|
||||
return window['go']['main']['App']['ApplyVMSettings'](arg1);
|
||||
}
|
||||
|
||||
export function CancelTask(arg1) {
|
||||
return window['go']['main']['App']['CancelTask'](arg1);
|
||||
}
|
||||
|
||||
export function CreateVM(arg1) {
|
||||
return window['go']['main']['App']['CreateVM'](arg1);
|
||||
}
|
||||
|
||||
export function DeleteInstaller(arg1) {
|
||||
return window['go']['main']['App']['DeleteInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function DeleteVM(arg1, arg2) {
|
||||
return window['go']['main']['App']['DeleteVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DismissTask(arg1) {
|
||||
return window['go']['main']['App']['DismissTask'](arg1);
|
||||
}
|
||||
|
||||
export function DownloadInstaller(arg1) {
|
||||
return window['go']['main']['App']['DownloadInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EjectInstaller(arg1) {
|
||||
return window['go']['main']['App']['EjectInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EnableWHPX() {
|
||||
return window['go']['main']['App']['EnableWHPX']();
|
||||
}
|
||||
|
||||
export function GetState() {
|
||||
return window['go']['main']['App']['GetState']();
|
||||
}
|
||||
|
||||
export function GetTasks() {
|
||||
return window['go']['main']['App']['GetTasks']();
|
||||
}
|
||||
|
||||
export function GetVMDetail(arg1) {
|
||||
return window['go']['main']['App']['GetVMDetail'](arg1);
|
||||
}
|
||||
|
||||
export function InstallRuntimeArchive(arg1) {
|
||||
return window['go']['main']['App']['InstallRuntimeArchive'](arg1);
|
||||
}
|
||||
|
||||
export function ListInstallers() {
|
||||
return window['go']['main']['App']['ListInstallers']();
|
||||
}
|
||||
|
||||
export function ListOfflineReleases() {
|
||||
return window['go']['main']['App']['ListOfflineReleases']();
|
||||
}
|
||||
|
||||
export function OpenVMFolder(arg1) {
|
||||
return window['go']['main']['App']['OpenVMFolder'](arg1);
|
||||
}
|
||||
|
||||
export function PickDirectory(arg1) {
|
||||
return window['go']['main']['App']['PickDirectory'](arg1);
|
||||
}
|
||||
|
||||
export function PickFile(arg1, arg2) {
|
||||
return window['go']['main']['App']['PickFile'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function PreviewCreate(arg1) {
|
||||
return window['go']['main']['App']['PreviewCreate'](arg1);
|
||||
}
|
||||
|
||||
export function ReadVMLogs(arg1, arg2) {
|
||||
return window['go']['main']['App']['ReadVMLogs'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RestartVM(arg1) {
|
||||
return window['go']['main']['App']['RestartVM'](arg1);
|
||||
}
|
||||
|
||||
export function SetAutoPinPCores(arg1) {
|
||||
return window['go']['main']['App']['SetAutoPinPCores'](arg1);
|
||||
}
|
||||
|
||||
export function SetDataRoot(arg1) {
|
||||
return window['go']['main']['App']['SetDataRoot'](arg1);
|
||||
}
|
||||
|
||||
export function SetLocale(arg1) {
|
||||
return window['go']['main']['App']['SetLocale'](arg1);
|
||||
}
|
||||
|
||||
export function StartVM(arg1) {
|
||||
return window['go']['main']['App']['StartVM'](arg1);
|
||||
}
|
||||
|
||||
export function StopVM(arg1, arg2) {
|
||||
return window['go']['main']['App']['StopVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function UseRuntime(arg1) {
|
||||
return window['go']['main']['App']['UseRuntime'](arg1);
|
||||
}
|
||||
|
||||
export function ValidateCreate(arg1) {
|
||||
return window['go']['main']['App']['ValidateCreate'](arg1);
|
||||
}
|
||||
|
||||
export function ValidateSet(arg1) {
|
||||
return window['go']['main']['App']['ValidateSet'](arg1);
|
||||
}
|
||||
@@ -3,7 +3,9 @@ module github.com/Nwflower/reims-go
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/ulikunitz/xz v0.5.17
|
||||
github.com/wailsapp/wails/v2 v2.17.1
|
||||
golang.org/x/net v0.60.0
|
||||
golang.org/x/sys v0.48.0
|
||||
)
|
||||
|
||||
@@ -33,6 +35,5 @@ require (
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
github.com/wailsapp/go-webview2 v1.0.22 // indirect
|
||||
golang.org/x/crypto v0.57.0 // indirect
|
||||
golang.org/x/net v0.60.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
)
|
||||
@@ -52,6 +52,8 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ=
|
||||
github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
|
||||
github.com/ulikunitz/xz v0.5.17 h1:flR0y/x1hgM8EGV1AW3Xll6T413G0glV8UfBwR617V4=
|
||||
github.com/ulikunitz/xz v0.5.17/go.mod h1:H9Rt/W6/Qj27PGauhQc6nfCDy7vHpzsOThBSaYDoEhw=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
)
|
||||
|
||||
func TestPolledVMsReusesFreshPoll(t *testing.T) {
|
||||
pid := 42
|
||||
a := &App{pollWake: make(chan struct{}, 1)}
|
||||
a.lastVMs = []reims.VMListItem{{Name: "m0", Dir: `D:\vms\m0`, PID: &pid, State: "running"}}
|
||||
a.lastVMsAt = time.Now()
|
||||
|
||||
vm, ok := a.polledVM("m0")
|
||||
if !ok || vm.State != "running" || vm.Dir != `D:\vms\m0` || *vm.PID != 42 {
|
||||
t.Fatalf("polledVM = %+v, %v", vm, ok)
|
||||
}
|
||||
if _, ok := a.polledVM("missing"); ok {
|
||||
t.Fatal("unknown VM should not be found")
|
||||
}
|
||||
|
||||
vms, _ := a.polledVMs(context.Background())
|
||||
vms[0].State = "stopped"
|
||||
if a.lastVMs[0].State != "running" {
|
||||
t.Fatal("polledVMs must return a copy, not the cached slice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWatchExitsTracksRunningPIDs(t *testing.T) {
|
||||
gone := 999999 // no such process: WaitProcessExit reports it exited at once
|
||||
stopped := reims.VMListItem{Name: "m1", State: "stopped"}
|
||||
running := reims.VMListItem{Name: "m0", State: "running", PID: &gone}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
exits := make(chan struct{}, 4)
|
||||
watched := map[int]bool{}
|
||||
watchExits(ctx, []reims.VMListItem{running, stopped}, watched, func() { exits <- struct{}{} })
|
||||
watchExits(ctx, []reims.VMListItem{running, stopped}, watched, func() { exits <- struct{}{} })
|
||||
if len(watched) != 1 || !watched[gone] {
|
||||
t.Fatalf("watched = %v, want only %d", watched, gone)
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
select {
|
||||
case <-exits:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("onExit not called for an exited process")
|
||||
}
|
||||
select {
|
||||
case <-exits:
|
||||
t.Fatal("a PID already watched must not get a second waiter")
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
running.State = "stopped"
|
||||
watchExits(ctx, []reims.VMListItem{running, stopped}, watched, func() {})
|
||||
if len(watched) != 0 {
|
||||
t.Fatalf("watched = %v, want empty once the VM stopped", watched)
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
a.wakePoll()
|
||||
a.wakePoll() // a second wake while one is pending must not block
|
||||
if !a.lastVMsAt.IsZero() {
|
||||
t.Fatal("wakePoll should mark the polled list stale")
|
||||
}
|
||||
select {
|
||||
case <-a.pollWake:
|
||||
default:
|
||||
t.Fatal("wakePoll should signal pollVMs")
|
||||
}
|
||||
select {
|
||||
case <-a.pollWake:
|
||||
t.Fatal("pending wakes should coalesce into one")
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// CloneVMCoW derives a new VM instantaneously from a stopped source VM using a
|
||||
// qcow2 copy-on-write overlay (`qemu-img create -f qcow2 -b <src> -F qcow2`)
|
||||
// so the source golden disk is never mutated while the clone gets its own fresh
|
||||
// OpenCore identity (SMBIOS/serial/MAC) via `reims-ctl create --disk --disk-mode in-place`.
|
||||
func (a *App) CloneVMCoW(sourceName, cloneName string) error {
|
||||
cloneName = strings.TrimSpace(cloneName)
|
||||
if cloneName == "" {
|
||||
return fmt.Errorf("clone VM name is required")
|
||||
}
|
||||
if strings.EqualFold(sourceName, cloneName) {
|
||||
return fmt.Errorf("clone name must differ from source VM")
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
src, err := a.GetVMDetail(sourceName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, sourceName, src) {
|
||||
return fmt.Errorf("stop %s before deriving a CoW clone so the backing disk is clean", sourceName)
|
||||
}
|
||||
if src.HasInstaller {
|
||||
return fmt.Errorf("exit recovery mode on %s before deriving a CoW clone", sourceName)
|
||||
}
|
||||
srcDisk := src.Disk
|
||||
if srcDisk != "" && !filepath.IsAbs(srcDisk) && src.Directory != "" {
|
||||
srcDisk = filepath.Join(src.Directory, srcDisk)
|
||||
}
|
||||
if srcDisk == "" {
|
||||
return fmt.Errorf("source VM %s has no disk path", sourceName)
|
||||
}
|
||||
if _, err := os.Stat(srcDisk); err != nil {
|
||||
return fmt.Errorf("source disk not found (%s): %w", srcDisk, err)
|
||||
}
|
||||
|
||||
// Validate clone name and check for name collisions.
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
nameCheck := reims.ValidateCreate(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep)
|
||||
for _, iss := range nameCheck {
|
||||
if iss.Field == "name" {
|
||||
return fmt.Errorf("%s", iss.Message)
|
||||
}
|
||||
}
|
||||
if existing, err := c.List(ctx); err == nil {
|
||||
for _, vm := range existing {
|
||||
if strings.EqualFold(vm.Name, cloneName) {
|
||||
return fmt.Errorf("VM %q already exists", cloneName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
overlayPath := filepath.Join(cfgCopy.ImagesDir(), fmt.Sprintf("cow-%s.qcow2", cloneName))
|
||||
if _, err := os.Stat(overlayPath); err == nil {
|
||||
return fmt.Errorf("CoW overlay file already exists: %s", overlayPath)
|
||||
}
|
||||
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(cloneName, line) })
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
a.emitLog(cloneName, fmt.Sprintf("Creating CoW overlay for %s backed by %s...", cloneName, filepath.Base(srcDisk)))
|
||||
if err := reims.CreateCoWOverlay(ctx, active.QemuImgPath(), env, srcDisk, overlayPath, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
audio := src.Audio
|
||||
network := src.Network
|
||||
logs := src.Logs
|
||||
capture := src.Capture
|
||||
createOpts := reims.CreateOpts{
|
||||
Name: cloneName,
|
||||
SourceMode: "disk",
|
||||
Disk: overlayPath,
|
||||
DiskMode: "in-place",
|
||||
DiskController: src.DiskController,
|
||||
CPUs: src.CPUs,
|
||||
Memory: src.Memory,
|
||||
Graphics: src.Graphics,
|
||||
GPU: src.GPU,
|
||||
Resolution: src.Resolution,
|
||||
Displays: src.Displays,
|
||||
Capture: &capture,
|
||||
Audio: &audio,
|
||||
Network: &network,
|
||||
Logs: &logs,
|
||||
Start: false,
|
||||
}
|
||||
if err := c.Create(ctx, createOpts, w, w); err != nil {
|
||||
_ = os.Remove(overlayPath)
|
||||
return err
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(createOpts); ok {
|
||||
if serr := c.Set(ctx, postSet, w, w); serr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone settings: %v", serr))
|
||||
}
|
||||
}
|
||||
if src.GuestLang != "" || vmstart.HasSavedVMAffinity(src.Directory) {
|
||||
if cloned, serr := c.Show(ctx, cloneName); serr == nil && cloned.Directory != "" {
|
||||
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 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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
a.emitLog(cloneName, fmt.Sprintf("CoW clone %s ready (backing image %s untouched)", cloneName, srcDisk))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/opencore"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
if issues := a.ValidateCreate(opts); len(issues) > 0 {
|
||||
return fmt.Errorf("%s", issues[0].Message)
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
|
||||
// Always defer starting to StartVM so commit-memory checks, Win10 cold-reboot
|
||||
// QMP wiring, and Win11 WHPX nested-virt fallback apply uniformly.
|
||||
startAfterCreate := opts.Start
|
||||
opts.Start = false
|
||||
|
||||
ctx, cancel := context.WithCancel(a.baseCtx())
|
||||
defer cancel()
|
||||
taskID, w, finishTask := a.ctlTaskWriterWithCancel("vm-create", opts.Name, cancel)
|
||||
a.emitLog(opts.Name, "Creating VM "+opts.Name+"...")
|
||||
|
||||
existingVMs, _ := c.List(ctx)
|
||||
if removed, rerr := reims.CleanAbortedCreateDir(cfgCopy.XDGDataDir(), opts, existingVMs); rerr != nil {
|
||||
a.emitLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
|
||||
} else if removed != "" {
|
||||
a.emitLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
|
||||
}
|
||||
|
||||
// Pre-fetch OcBinaryData with an idle-read timeout so slow GitHub links do
|
||||
// not trigger reims-util's 180s HTTP-200 truncate-and-restart loop.
|
||||
if installer.ShouldPrefetchOcBinaryData(active.Manifest.UtilCommit, active.Manifest.UtilVersion) {
|
||||
loggedPrefetch := false
|
||||
perr := installer.EnsureCachedAsset(ctx, cfgCopy.XDGCacheDir(), installer.OcBinaryDataAsset, nil, func(u installer.Update) {
|
||||
if !loggedPrefetch && u.Kind == installer.KindStep {
|
||||
loggedPrefetch = true
|
||||
a.emitLog(opts.Name, opts.Name+": "+u.Message)
|
||||
}
|
||||
tasks.update(taskID, u)
|
||||
})
|
||||
if perr != nil {
|
||||
if errors.Is(perr, context.Canceled) {
|
||||
finishTask(perr)
|
||||
a.emitLog(opts.Name, "Create canceled.")
|
||||
return perr
|
||||
}
|
||||
a.emitLog(opts.Name, "Pre-fetch OpenCore resources skipped (reims-ctl will retry): "+perr.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// Convert VMDK / RAW disks into qcow2 before invoking reims-ctl create.
|
||||
var convertedTmp string
|
||||
if opts.Disk != "" && reims.NeedsDiskConversion(opts.Disk) {
|
||||
convertedTmp = filepath.Join(cfgCopy.TempDir(), fmt.Sprintf("import-%s-%d.qcow2", opts.Name, time.Now().Unix()))
|
||||
defer os.Remove(convertedTmp)
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Converting %s to qcow2 via qemu-img...", filepath.Base(opts.Disk)))
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
if cerr := reims.ConvertDiskToQCOW2(ctx, active.QemuImgPath(), env, opts.Disk, convertedTmp, w, w); cerr != nil {
|
||||
finishTask(cerr)
|
||||
a.emitLog(opts.Name, "Disk conversion error: "+cerr.Error())
|
||||
return cerr
|
||||
}
|
||||
opts.Disk = convertedTmp
|
||||
opts.DiskMode = "copy"
|
||||
}
|
||||
|
||||
err = c.Create(ctx, opts, w, w)
|
||||
if err != nil {
|
||||
finishTask(err)
|
||||
a.emitLog(opts.Name, "Create error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(opts); ok {
|
||||
var parts []string
|
||||
if postSet.DiskController != "" {
|
||||
parts = append(parts, "disk="+strings.ToUpper(postSet.DiskController))
|
||||
}
|
||||
if postSet.Capture != nil && !*postSet.Capture {
|
||||
parts = append(parts, "capture=off")
|
||||
}
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Applying VM defaults for %s (%s)...", opts.Name, strings.Join(parts, ", ")))
|
||||
if serr := c.Set(ctx, postSet, w, w); serr != nil {
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not apply post-create defaults (%s): %v", strings.Join(parts, ", "), serr))
|
||||
}
|
||||
}
|
||||
guestLang := strings.TrimSpace(opts.GuestLang)
|
||||
if guestLang == "" && opts.SourceMode != "disk" {
|
||||
guestLang = opencore.DefaultGuestLang(cfgCopy.Locale)
|
||||
}
|
||||
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)
|
||||
}
|
||||
if lerr != nil {
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not apply macOS language (%s): %v", guestLang, lerr))
|
||||
}
|
||||
}
|
||||
finishTask(nil)
|
||||
a.emitLog(opts.Name, "VM "+opts.Name+" ready.")
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
if startAfterCreate {
|
||||
return a.StartVM(opts.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
type diagnosticsBundle struct {
|
||||
HostReport host.Report
|
||||
Optimizations []host.Optimization
|
||||
Runtime *rt.Installed
|
||||
VMDetail *reims.VMDetail
|
||||
SerialLog string
|
||||
QEMULog string
|
||||
AppLogs []string
|
||||
}
|
||||
|
||||
func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
|
||||
if err := os.MkdirAll(filepath.Dir(zipPath), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.Create(zipPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
zw := zip.NewWriter(f)
|
||||
addFile := func(name, content string) error {
|
||||
w, err := zw.Create(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = w.Write([]byte(reims.RedactText(content)))
|
||||
return err
|
||||
}
|
||||
addJSON := func(name string, v any) error {
|
||||
raw, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return addFile(name, string(raw)+"\n")
|
||||
}
|
||||
|
||||
hostSummary := map[string]any{
|
||||
"generated_at": time.Now().UTC().Format(time.RFC3339),
|
||||
"host": b.HostReport,
|
||||
"optimizations": b.Optimizations,
|
||||
}
|
||||
if err := addJSON("host-report.json", hostSummary); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
if b.Runtime != nil {
|
||||
if err := addJSON("runtime-manifest.json", b.Runtime.Manifest); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if b.VMDetail != nil {
|
||||
sanitized := *b.VMDetail
|
||||
sanitized.NetworkSummary = reims.RedactLogLine(sanitized.NetworkSummary)
|
||||
sanitized.ExtraArgs = reims.RedactLogLine(sanitized.ExtraArgs)
|
||||
if err := addJSON("vm-detail.json", sanitized); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(b.SerialLog) != "" {
|
||||
if err := addFile("serial.log", b.SerialLog); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(b.QEMULog) != "" {
|
||||
if err := addFile("qemu.log", b.QEMULog); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(b.AppLogs) > 0 {
|
||||
if err := addFile("app-logs.txt", strings.Join(b.AppLogs, "\n")+"\n"); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
return f.Close()
|
||||
}
|
||||
|
||||
// ExportDiagnostics collects a redacted troubleshooting zip bundle (host probe,
|
||||
// runtime manifest, VM detail, serial/QEMU logs, and recent app logs) into
|
||||
// `<DataRoot>/reports/` and opens the folder in File Explorer.
|
||||
func (a *App) ExportDiagnostics(name string) (string, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
appLogs := append([]string(nil), a.recentLogs...)
|
||||
a.mu.Unlock()
|
||||
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
var active *rt.Installed
|
||||
var patchNames []string
|
||||
if inst, err := rt.ResolveActive(&cfgCopy); err == nil {
|
||||
active = inst
|
||||
for _, p := range inst.Manifest.Patches {
|
||||
patchNames = append(patchNames, p.Name)
|
||||
}
|
||||
}
|
||||
bundle := diagnosticsBundle{
|
||||
HostReport: rep,
|
||||
Optimizations: host.EvaluateOptimizations(rep, patchNames),
|
||||
Runtime: active,
|
||||
AppLogs: appLogs,
|
||||
}
|
||||
|
||||
label := "host"
|
||||
if strings.TrimSpace(name) != "" {
|
||||
label = name
|
||||
if c, err := a.client(); err == nil {
|
||||
ctx := context.Background()
|
||||
if d, derr := a.GetVMDetail(name); derr == nil {
|
||||
bundle.VMDetail = &d
|
||||
}
|
||||
if serial, serr := c.ReadLogs(ctx, name, true); serr == nil {
|
||||
bundle.SerialLog = serial
|
||||
}
|
||||
if qemuLog, qerr := c.ReadLogs(ctx, name, false); qerr == nil {
|
||||
bundle.QEMULog = qemuLog
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
reportsDir := filepath.Join(cfgCopy.DataRoot, "reports")
|
||||
zipName := fmt.Sprintf("reims-go-diag-%s-%s.zip", label, time.Now().Format("20060102-150405"))
|
||||
zipPath := filepath.Join(reportsDir, zipName)
|
||||
if err := writeDiagnosticsZip(zipPath, bundle); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.emitLog(label, "Diagnostics exported: "+zipPath)
|
||||
_ = host.OpenFolder(reportsDir)
|
||||
return zipPath, nil
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
)
|
||||
|
||||
func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) {
|
||||
zipPath := filepath.Join(t.TempDir(), "reports", "diag.zip")
|
||||
err := writeDiagnosticsZip(zipPath, diagnosticsBundle{
|
||||
HostReport: host.Report{OS: "windows", LogicalCPUs: 16, DataRootDriveType: "fixed"},
|
||||
VMDetail: &reims.VMDetail{
|
||||
Name: "macos-tahoe",
|
||||
NetworkSummary: "user, mac 52:54:00:ab:cd:ef, ssh on 127.0.0.1:2222",
|
||||
ExtraArgs: "-device isa-applesmc,osk=ourhardworkbythesewordsguardedpleasedontsteal",
|
||||
},
|
||||
SerialLog: "OpenCore presents iMac20,1, serial C02FAKE123456\n",
|
||||
QEMULog: "Authorization: Bearer 0123456789abcdef0123456789abcdef\n",
|
||||
AppLogs: []string{`REIMS_TOKEN="abcdef0123456789abcdef0123456789"`},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("writeDiagnosticsZip: %v", err)
|
||||
}
|
||||
|
||||
zr, err := zip.OpenReader(zipPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer zr.Close()
|
||||
|
||||
var all strings.Builder
|
||||
for _, f := range zr.File {
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(rc)
|
||||
rc.Close()
|
||||
all.WriteString(f.Name + ":\n" + string(b) + "\n")
|
||||
}
|
||||
text := all.String()
|
||||
for _, secret := range []string{
|
||||
"52:54:00:ab:cd:ef",
|
||||
"C02FAKE123456",
|
||||
"ourhardworkbythesewordsguardedpleasedontsteal",
|
||||
"0123456789abcdef0123456789abcdef",
|
||||
"abcdef0123456789abcdef0123456789",
|
||||
} {
|
||||
if strings.Contains(text, secret) {
|
||||
t.Fatalf("diagnostics zip leaked secret %q\n%s", secret, text)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(text, "[redacted]") {
|
||||
t.Fatalf("expected [redacted] markers in zip output")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"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"
|
||||
)
|
||||
|
||||
// ResizeVMDisk expands a stopped VM's virtual disk via `qemu-img resize` and
|
||||
// returns the macOS `diskutil` command needed to grow the APFS container inside
|
||||
// the guest.
|
||||
func (a *App) ResizeVMDisk(name, newSize string) (reims.DiskResizeResult, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return reims.DiskResizeResult{}, err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return reims.DiskResizeResult{}, err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return reims.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name)
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" {
|
||||
return reims.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name)
|
||||
}
|
||||
|
||||
taskCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-resize", name, cancel)
|
||||
a.emitLog(name, fmt.Sprintf("Resizing disk for %s (%s)...", name, strings.TrimSpace(newSize)))
|
||||
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
res, err := reims.ResizeDisk(taskCtx, active.QemuImgPath(), env, diskPath, newSize, w, w)
|
||||
if err != nil {
|
||||
finishTask(err)
|
||||
a.emitLog(name, "Disk resize error: "+err.Error())
|
||||
return reims.DiskResizeResult{}, err
|
||||
}
|
||||
finishTask(nil)
|
||||
a.emitLog(name, fmt.Sprintf("Expanded disk for %s: %.0f GB -> %.0f GB (run diskutil inside macOS to expand APFS)",
|
||||
name, float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30)))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// CompactVMDisk rewrites a stopped VM's standalone qcow2 image into a freshly
|
||||
// compacted sparse qcow2 file to reclaim unused/TRIMmed host disk space.
|
||||
func (a *App) CompactVMDisk(name string) (reims.DiskCompactResult, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return reims.DiskCompactResult{}, err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return reims.DiskCompactResult{}, err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return reims.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name)
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" {
|
||||
return reims.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name)
|
||||
}
|
||||
|
||||
taskCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-compact", name, cancel)
|
||||
a.emitLog(name, fmt.Sprintf("Compacting qcow2 disk for %s to reclaim unused space...", name))
|
||||
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
res, err := reims.CompactDisk(taskCtx, active.QemuImgPath(), env, diskPath, w, w)
|
||||
if err != nil {
|
||||
finishTask(err)
|
||||
a.emitLog(name, "Disk compact error: "+err.Error())
|
||||
return reims.DiskCompactResult{}, err
|
||||
}
|
||||
finishTask(nil)
|
||||
a.emitLog(name, fmt.Sprintf("Compacted disk for %s: %.2f GB -> %.2f GB (reclaimed %.2f GB)",
|
||||
name,
|
||||
float64(res.BeforeBytes)/float64(1<<30),
|
||||
float64(res.AfterBytes)/float64(1<<30),
|
||||
float64(res.ReclaimedBytes)/float64(1<<30)))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// DriveShareInfo describes one currently available internal fixed drive.
|
||||
type DriveShareInfo struct {
|
||||
Drive string `json:"drive"`
|
||||
Root string `json:"root"`
|
||||
Selected bool `json:"selected"`
|
||||
System bool `json:"system"`
|
||||
}
|
||||
|
||||
// DriveShareSettings is the live, per-VM read-only drive sharing configuration.
|
||||
type DriveShareSettings struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
RequiredAgentVersion int `json:"required_agent_version"`
|
||||
Drives []DriveShareInfo `json:"drives"`
|
||||
}
|
||||
|
||||
func shareableFixedDrives() []host.Drive {
|
||||
all := host.ListDrives()
|
||||
out := make([]host.Drive, 0, len(all))
|
||||
for _, drive := range all {
|
||||
if drive.External {
|
||||
continue
|
||||
}
|
||||
if _, ok := guesttools.NormalizeDriveLetter(drive.Root); ok && drive.VolumeGUID != "" {
|
||||
out = append(out, drive)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeDriveSelection(available []host.Drive, selected []string) ([]string, error) {
|
||||
allowed := make(map[string]bool, len(available))
|
||||
for _, drive := range available {
|
||||
if letter, ok := guesttools.NormalizeDriveLetter(drive.Root); ok && !drive.External {
|
||||
allowed[letter] = true
|
||||
}
|
||||
}
|
||||
requested := make(map[string]bool, len(selected))
|
||||
for _, raw := range selected {
|
||||
letter, ok := guesttools.NormalizeDriveLetter(raw)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid drive %q", raw)
|
||||
}
|
||||
if !allowed[letter] {
|
||||
return nil, fmt.Errorf("drive %s is not an available internal fixed drive", letter)
|
||||
}
|
||||
requested[letter] = true
|
||||
}
|
||||
out := []string{}
|
||||
for _, drive := range available {
|
||||
letter, _ := guesttools.NormalizeDriveLetter(drive.Root)
|
||||
if requested[letter] {
|
||||
out = append(out, letter)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// validatedDriveConfig derives runtime roots only from currently present fixed volumes
|
||||
// whose stable GUID matches the user's persisted selection. It never saves filtered state.
|
||||
func validatedDriveConfig(cfg guesttools.VMConfig) guesttools.VMConfig {
|
||||
return validatedDriveConfigForVolumes(cfg, shareableFixedDrives())
|
||||
}
|
||||
|
||||
func validatedDriveConfigForVolumes(cfg guesttools.VMConfig, available []host.Drive) guesttools.VMConfig {
|
||||
selected := make(map[string]bool, len(cfg.SharedDrives))
|
||||
for _, raw := range cfg.SharedDrives {
|
||||
if letter, ok := guesttools.NormalizeDriveLetter(raw); ok {
|
||||
selected[letter] = true
|
||||
}
|
||||
}
|
||||
cfg.SharedDrives = []string{}
|
||||
cfg.DriveRoots = make(map[string]string)
|
||||
for _, drive := range available {
|
||||
if drive.External || drive.VolumeGUID == "" {
|
||||
continue
|
||||
}
|
||||
letter, _ := guesttools.NormalizeDriveLetter(drive.Root)
|
||||
expected := cfg.DriveVolumes[letter]
|
||||
if !selected[letter] || expected == "" || !strings.EqualFold(expected, drive.VolumeGUID) {
|
||||
continue
|
||||
}
|
||||
cfg.SharedDrives = append(cfg.SharedDrives, letter)
|
||||
cfg.DriveRoots[letter] = drive.Root
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func selectedVolumeIdentities(available []host.Drive, selected []string) map[string]string {
|
||||
wanted := make(map[string]bool, len(selected))
|
||||
for _, letter := range selected {
|
||||
wanted[letter] = true
|
||||
}
|
||||
out := make(map[string]string)
|
||||
for _, drive := range available {
|
||||
letter, ok := guesttools.NormalizeDriveLetter(drive.Root)
|
||||
if ok && wanted[letter] && drive.VolumeGUID != "" {
|
||||
out[letter] = drive.VolumeGUID
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func makeDriveShareSettings(cfg guesttools.VMConfig, available []host.Drive) DriveShareSettings {
|
||||
selected := make(map[string]bool, len(cfg.SharedDrives))
|
||||
for _, raw := range cfg.SharedDrives {
|
||||
if letter, ok := guesttools.NormalizeDriveLetter(raw); ok {
|
||||
selected[letter] = true
|
||||
}
|
||||
}
|
||||
settings := DriveShareSettings{
|
||||
Enabled: cfg.DriveSharingEnabled, ReadOnly: true,
|
||||
RequiredAgentVersion: guesttools.DriveShareAgentVersion, Drives: []DriveShareInfo{},
|
||||
}
|
||||
for _, drive := range available {
|
||||
if drive.External {
|
||||
continue
|
||||
}
|
||||
letter, ok := guesttools.NormalizeDriveLetter(drive.Root)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
expected := cfg.DriveVolumes[letter]
|
||||
identityMatches := expected != "" && strings.EqualFold(expected, drive.VolumeGUID)
|
||||
settings.Drives = append(settings.Drives, DriveShareInfo{
|
||||
Drive: letter, Root: drive.Root, Selected: selected[letter] && identityMatches, System: drive.System,
|
||||
})
|
||||
}
|
||||
return settings
|
||||
}
|
||||
|
||||
// GetVMDriveShareSettings returns per-VM switches without creating Guest Tools config.
|
||||
func (a *App) GetVMDriveShareSettings(name string) (DriveShareSettings, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
cfg, _ := guesttools.ReadVMConfig(detail.Directory)
|
||||
return makeDriveShareSettings(cfg, shareableFixedDrives()), nil
|
||||
}
|
||||
|
||||
// SetVMDriveShareSettings persists selected drive letters and applies access control immediately.
|
||||
func (a *App) SetVMDriveShareSettings(name string, enabled bool, drives []string) (DriveShareSettings, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
if detail.Directory == "" {
|
||||
return DriveShareSettings{}, fmt.Errorf("VM %s has no directory", name)
|
||||
}
|
||||
available := shareableFixedDrives()
|
||||
normalized, err := normalizeDriveSelection(available, drives)
|
||||
if err != nil {
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
cfg, err := guesttools.LoadOrCreateVMConfig(detail.Directory, name, a.vmSharedDir(name), port)
|
||||
if err != nil {
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
cfg.DriveSharingEnabled = enabled
|
||||
cfg.SharedDrives = normalized
|
||||
cfg.DriveVolumes = selectedVolumeIdentities(available, normalized)
|
||||
if err := guesttools.SaveVMConfig(detail.Directory, cfg); err != nil {
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
a.emitLog(name, fmt.Sprintf("Read-only Windows drive sharing enabled=%v drives=%v", enabled, normalized))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return makeDriveShareSettings(cfg, available), nil
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
)
|
||||
|
||||
func TestNormalizeDriveSelectionRejectsUnavailableAndExternalDrives(t *testing.T) {
|
||||
available := []host.Drive{{Root: `C:\`, System: true}, {Root: `D:\`}, {Root: `E:\`, External: true}}
|
||||
got, err := normalizeDriveSelection(available, []string{"d", "D:", `C:\`})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 || got[0] != "C" || got[1] != "D" {
|
||||
t.Fatalf("normalized selection = %#v, want [C D]", got)
|
||||
}
|
||||
for _, selected := range [][]string{{"E"}, {"Z"}, {"../C"}, {"C:/"}} {
|
||||
if _, err := normalizeDriveSelection(available, selected); err == nil {
|
||||
t.Fatalf("selection %#v unexpectedly accepted", selected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatedDriveConfigRejectsMissingAndReboundVolumes(t *testing.T) {
|
||||
cfg := guesttools.VMConfig{
|
||||
DriveSharingEnabled: true, SharedDrives: []string{"C", "D", "E"},
|
||||
DriveVolumes: map[string]string{"C": "vol-c", "D": "old-volume-d"},
|
||||
}
|
||||
available := []host.Drive{
|
||||
{Root: `C:\`, VolumeGUID: "vol-c"},
|
||||
{Root: `D:\`, VolumeGUID: "new-volume-d"},
|
||||
{Root: `E:\`, VolumeGUID: "vol-e", External: true},
|
||||
}
|
||||
got := validatedDriveConfigForVolumes(cfg, available)
|
||||
if len(got.SharedDrives) != 1 || got.SharedDrives[0] != "C" || got.DriveRoots["C"] != `C:\` {
|
||||
t.Fatalf("validated config = %#v, want only original C volume", got)
|
||||
}
|
||||
if len(got.DriveVolumes) != 2 {
|
||||
t.Fatalf("runtime validation mutated persisted identities: %#v", got.DriveVolumes)
|
||||
}
|
||||
cfg.SharedDrives = []string{"C"}
|
||||
cfg.DriveVolumes = nil
|
||||
if got := validatedDriveConfigForVolumes(cfg, available); len(got.SharedDrives) != 0 {
|
||||
t.Fatalf("legacy config without volume identity was trusted: %#v", got)
|
||||
}
|
||||
}
|
||||
func TestMakeDriveShareSettingsDefaultsToReadOnlyAndPerDriveSelection(t *testing.T) {
|
||||
available := []host.Drive{{Root: `C:\`, System: true, VolumeGUID: "vol-c"}, {Root: `D:\`, VolumeGUID: "vol-d"}}
|
||||
settings := makeDriveShareSettings(guesttools.VMConfig{}, available)
|
||||
if settings.Enabled || !settings.ReadOnly || settings.RequiredAgentVersion != guesttools.DriveShareAgentVersion {
|
||||
t.Fatalf("unexpected defaults: %#v", settings)
|
||||
}
|
||||
if settings.Drives == nil || len(settings.Drives) != 2 {
|
||||
t.Fatalf("drives = %#v, want two entries", settings.Drives)
|
||||
}
|
||||
settings = makeDriveShareSettings(guesttools.VMConfig{DriveSharingEnabled: true, SharedDrives: []string{"D"}, DriveVolumes: map[string]string{"D": "vol-d"}}, available)
|
||||
if !settings.Enabled || settings.Drives[0].Selected || !settings.Drives[1].Selected || !settings.Drives[0].System {
|
||||
t.Fatalf("unexpected settings: %#v", settings)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func (a *App) vmSharedDir(name string) string {
|
||||
a.mu.Lock()
|
||||
dir := filepath.Join(a.cfg.SharedDir(), name)
|
||||
a.mu.Unlock()
|
||||
return dir
|
||||
}
|
||||
|
||||
func (a *App) guestToolsImagePath(name string) string {
|
||||
a.mu.Lock()
|
||||
cacheDir := a.cfg.XDGCacheDir()
|
||||
a.mu.Unlock()
|
||||
return filepath.Join(cacheDir, "reims-go", "guest-tools", name+"-tools.img")
|
||||
}
|
||||
|
||||
// ensureGuestToolsBridge starts the shared localhost HTTP bridge once and
|
||||
// registers any already-configured VMs so Guest Tools reconnects seamlessly
|
||||
// across reims-go restarts.
|
||||
func (a *App) ensureGuestToolsBridge() (*guesttools.Server, int, error) {
|
||||
a.mu.Lock()
|
||||
srv := a.guestTools
|
||||
if srv == nil {
|
||||
srv = guesttools.NewServer(nil)
|
||||
srv.SetHostTextHandler(func(vmName, text string) {
|
||||
a.injectRemoteText(vmName, "", text)
|
||||
})
|
||||
a.guestTools = srv
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
port, err := srv.Start(guesttools.DefaultPort)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return srv, port, nil
|
||||
}
|
||||
|
||||
// inputBridgeEnv returns REIMS_GO_INPUT_URL and REIMS_GO_INPUT_TOKEN env vars
|
||||
// for the VM's QEMU/reims-vgpu-window child process so direct WM_CHAR / IME
|
||||
// commits can forward to reims-go's local text router.
|
||||
func (a *App) inputBridgeEnv(name, vmDir string) []string {
|
||||
if vmDir == "" {
|
||||
return nil
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil || port <= 0 {
|
||||
return nil
|
||||
}
|
||||
cfg, err := guesttools.LoadOrCreateVMConfig(vmDir, name, a.vmSharedDir(name), port)
|
||||
if err != nil || cfg.Token == "" {
|
||||
return nil
|
||||
}
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
return []string{
|
||||
fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port),
|
||||
"REIMS_GO_INPUT_TOKEN=" + cfg.Token,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) registerExistingGuestTools(ctx context.Context) {
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
vms, err := c.List(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, vm := range vms {
|
||||
det, err := c.Show(ctx, vm.Name)
|
||||
if err != nil || det.Directory == "" {
|
||||
continue
|
||||
}
|
||||
if cfg, ok := guesttools.ReadVMConfig(det.Directory); ok {
|
||||
if cfg.SharedDir == "" {
|
||||
cfg.SharedDir = a.vmSharedDir(vm.Name)
|
||||
}
|
||||
if cfg.Port != port {
|
||||
cfg.Port = port
|
||||
_ = guesttools.SaveVMConfig(det.Directory, cfg)
|
||||
}
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) populateGuestToolsDetail(d *reims.VMDetail) {
|
||||
if d == nil || d.Name == "" {
|
||||
return
|
||||
}
|
||||
d.GuestToolsAttached = reims.HasGuestToolsArgs(d.ExtraArgs)
|
||||
d.SharedDir = a.vmSharedDir(d.Name)
|
||||
if cfg, ok := guesttools.ReadVMConfig(d.Directory); ok {
|
||||
d.GuestToolsConfigured = true
|
||||
d.GuestToolsPreventSleep = cfg.PreventSleep
|
||||
if cfg.SharedDir != "" {
|
||||
d.SharedDir = cfg.SharedDir
|
||||
}
|
||||
if srv, _, err := a.ensureGuestToolsBridge(); err == nil {
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
st := srv.Status(d.Name, 15*time.Second)
|
||||
d.GuestToolsConnected = st.Connected
|
||||
d.GuestToolsMountMode = st.MountMode
|
||||
d.GuestToolsSleepActive = st.SleepActive
|
||||
d.GuestToolsAgentVersion = st.AgentVersion
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// syncGuestTools ensures the host HTTP bridge is running and refreshes the
|
||||
// REIMSTOOLS HFS+ image before VM start when Guest Tools is configured or attached.
|
||||
func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail) {
|
||||
if cur.Directory == "" {
|
||||
return
|
||||
}
|
||||
attached := reims.HasGuestToolsArgs(cur.ExtraArgs)
|
||||
cfg, configured := guesttools.ReadVMConfig(cur.Directory)
|
||||
if !attached && !configured {
|
||||
return
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
a.emitLog(name, "Warning: could not start Guest Tools bridge: "+err.Error())
|
||||
return
|
||||
}
|
||||
sharedDir := a.vmSharedDir(name)
|
||||
cfg, err = guesttools.LoadOrCreateVMConfig(cur.Directory, name, sharedDir, port)
|
||||
if err != nil {
|
||||
a.emitLog(name, "Warning: could not load Guest Tools config: "+err.Error())
|
||||
return
|
||||
}
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
if !attached {
|
||||
return
|
||||
}
|
||||
imgPath := a.guestToolsImagePath(name)
|
||||
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
|
||||
a.emitLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error())
|
||||
return
|
||||
}
|
||||
merged := reims.MergeGuestToolsArgs(cur.ExtraArgs, imgPath)
|
||||
if merged != cur.ExtraArgs {
|
||||
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err == nil {
|
||||
cur.ExtraArgs = merged
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AttachGuestTools prepares the per-VM Bearer token, ensures the shared folder
|
||||
// and localhost bridge are active, builds the read-only REIMSTOOLS HFS+ disk,
|
||||
// and attaches it to the VM via `reims-ctl set --extra-args`.
|
||||
func (a *App) AttachGuestTools(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Directory == "" {
|
||||
return fmt.Errorf("VM %s has no directory", name)
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sharedDir := a.vmSharedDir(name)
|
||||
if err := os.MkdirAll(sharedDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg, err := guesttools.LoadOrCreateVMConfig(d.Directory, name, sharedDir, port)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
|
||||
imgPath := a.guestToolsImagePath(name)
|
||||
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
|
||||
return fmt.Errorf("build REIMSTOOLS disk: %w", err)
|
||||
}
|
||||
merged := reims.MergeGuestToolsArgs(d.ExtraArgs, imgPath)
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
ctx := context.Background()
|
||||
if merged != d.ExtraArgs {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &merged}, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
Field: "guest_tools",
|
||||
From: "detached",
|
||||
To: "attached",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Guest Tools disk (REIMSTOOLS) attached on 127.0.0.1:%d; shared folder: %s", port, sharedDir))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DetachGuestTools removes the REIMSTOOLS installer USB disk from QEMU
|
||||
// extra-args while keeping the background clipboard/shared-folder bridge active.
|
||||
func (a *App) DetachGuestTools(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
stripped := reims.StripGuestToolsArgs(d.ExtraArgs)
|
||||
ctx := context.Background()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
if stripped != d.ExtraArgs {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &stripped}, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
Field: "guest_tools",
|
||||
From: "attached",
|
||||
To: "ejected",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
a.emitLog(name, "Guest Tools disk (REIMSTOOLS) ejected; clipboard & shared folder bridge remains active")
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// OpenSharedFolder opens `<DataRoot>/shared/<vmName>` in Windows File Explorer.
|
||||
func (a *App) OpenSharedFolder(name string) error {
|
||||
dir := a.vmSharedDir(name)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return host.OpenFolder(dir)
|
||||
}
|
||||
|
||||
// SetGuestPreventSleep toggles the live macOS prevent-sleep guard (`caffeinate -dims`)
|
||||
// for a VM and persists the preference in `.reims-go-tools.json`.
|
||||
func (a *App) SetGuestPreventSleep(name string, enabled bool) error {
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Directory == "" {
|
||||
return fmt.Errorf("VM %s has no directory", name)
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sharedDir := a.vmSharedDir(name)
|
||||
cfg, err := guesttools.LoadOrCreateVMConfig(d.Directory, name, sharedDir, port)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.PreventSleep = enabled
|
||||
if err := guesttools.SaveVMConfig(d.Directory, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
srv.SetPreventSleep(name, enabled)
|
||||
a.emitLog(name, fmt.Sprintf("Guest Tools prevent-sleep guard set to %v", enabled))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeliverFileToGuest opens a file picker and copies the selected host file into
|
||||
// `<DataRoot>/shared/<vmName>` so it immediately appears inside macOS ReimsShare.
|
||||
func (a *App) DeliverFileToGuest(name string) (string, error) {
|
||||
if a.ctx == nil {
|
||||
return "", fmt.Errorf("window not ready")
|
||||
}
|
||||
picked, err := wailsRuntime.OpenFileDialog(a.ctx, wailsRuntime.OpenDialogOptions{
|
||||
Title: "Select file to send to " + name,
|
||||
})
|
||||
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
|
||||
}
|
||||
src, err := os.Open(picked)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
base := filepath.Base(picked)
|
||||
dstPath := filepath.Join(sharedDir, base)
|
||||
tmp, err := os.CreateTemp(sharedDir, ".reims-deliver-*")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
if _, err := io.Copy(tmp, src); err != nil {
|
||||
_ = tmp.Close()
|
||||
_ = os.Remove(tmpName)
|
||||
return "", err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
_ = os.Remove(tmpName)
|
||||
return "", err
|
||||
}
|
||||
if err := os.Rename(tmpName, dstPath); err != nil {
|
||||
_ = os.Remove(tmpName)
|
||||
return "", err
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Delivered %s to shared folder (%s)", base, sharedDir))
|
||||
return base, nil
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package app
|
||||
|
||||
// Finishing an offline install (roadmap M2.3): take the installer out and turn
|
||||
// the network back on, which an offline install keeps off so its installer
|
||||
// downloads no update (`reims-ctl create --help`, upstream 3731afd).
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// recoveryPickerMarkerFile tracks OpenCore ShowPicker state managed by
|
||||
// reims-go's recovery-mode toggle inside the VM directory:
|
||||
// - "want": EnterRecovery ran while VM was running; apply --boot-selection=true before next start.
|
||||
// - "on": --boot-selection=true is active on opencore.qcow2.
|
||||
// - "restore": FinishInstall ran while VM was running; apply --boot-selection=false before next start.
|
||||
// - "": Normal direct boot (file absent).
|
||||
func isRecoveryModeActive(d reims.VMDetail) bool {
|
||||
if d.HasInstaller {
|
||||
return true
|
||||
}
|
||||
m := vmstart.ReadRecoveryMarker(d.Directory)
|
||||
return m == "on" || m == "want"
|
||||
}
|
||||
|
||||
func (a *App) pickCachedRecoveryInstaller() (string, error) {
|
||||
ic, err := a.installerClient()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
items, err := ic.ListCached()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// ListCached sorts ascending by name; walk in reverse so newer versions win.
|
||||
// Prefer complete offline installers, then online installers, then other .img/.dmg.
|
||||
for _, wantKind := range []string{"offline", "online", "other"} {
|
||||
for i := len(items) - 1; i >= 0; i-- {
|
||||
it := items[i]
|
||||
if it.Partial || it.Kind != wantKind {
|
||||
continue
|
||||
}
|
||||
lower := strings.ToLower(it.Name)
|
||||
if wantKind == "other" && !strings.HasSuffix(lower, ".img") && !strings.HasSuffix(lower, ".dmg") {
|
||||
continue
|
||||
}
|
||||
return it.Path, nil
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (a *App) isVMRunning(ctx context.Context, c *reims.Client, name string, d reims.VMDetail) bool {
|
||||
if d.State == "running" {
|
||||
return true
|
||||
}
|
||||
if list, err := c.List(ctx); err == nil {
|
||||
for _, vm := range list {
|
||||
if vm.Name == name && vm.State == "running" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// EnterRecovery enables OpenCore's boot picker (--boot-selection=true) so the
|
||||
// VM can boot macOS's built-in Recovery volume without needing an external
|
||||
// installer image (upstream reims-util 7867384 sets HideAuxiliary=false).
|
||||
// If the VM is running, the change is queued for the next start/restart.
|
||||
func (a *App) EnterRecovery(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
ctx := context.Background()
|
||||
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
marker := vmstart.ReadRecoveryMarker(d.Directory)
|
||||
if marker != "on" {
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "want")
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
Field: "recovery",
|
||||
From: "off",
|
||||
To: "on",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
a.emitLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
|
||||
} else {
|
||||
a.emitLog(name, "Enabling OpenCore boot picker for recovery mode...")
|
||||
if err := c.UpdateOpenCore(ctx, name, true, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "on")
|
||||
if prep, err := a.prep(name); err == nil {
|
||||
prep.ReplayGuestLang(ctx, d.Directory)
|
||||
}
|
||||
a.emitLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AttachInstaller attaches an installer/recovery image to the VM for its next
|
||||
// start (`reims-ctl insert NAME PATH`). When installerPath is empty, the newest
|
||||
// complete cached installer in the installers directory is used. Returns the
|
||||
// attached file's base name.
|
||||
func (a *App) AttachInstaller(name, installerPath string) (string, error) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
path := strings.TrimSpace(installerPath)
|
||||
if path == "" {
|
||||
path, err = a.pickCachedRecoveryInstaller()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if path == "" {
|
||||
return "", errors.New("no cached installer image found")
|
||||
}
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
ctx := context.Background()
|
||||
|
||||
base := filepath.Base(path)
|
||||
a.emitLog(name, "Attaching installer image to "+name+": "+base)
|
||||
if err := c.Insert(ctx, name, path, w, w); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
Field: "installer",
|
||||
From: "ejected",
|
||||
To: "attached",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return base, nil
|
||||
}
|
||||
|
||||
// DownloadAndAttachOnlineRecovery downloads Apple's ~1 GB online recovery image
|
||||
// (`reims-util online-installer`) in a background task and attaches it to the
|
||||
// VM via `reims-ctl insert` as soon as it finishes.
|
||||
func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, error) {
|
||||
ic, err := a.installerClient()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := a.GetVMDetail(name); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, t := range tasks.list() {
|
||||
if t.Kind == "recovery-download" && t.Status == TaskRunning && t.Subject == name {
|
||||
return t.ID, nil
|
||||
}
|
||||
}
|
||||
v := strings.TrimSpace(version)
|
||||
if v == "" {
|
||||
v = "latest"
|
||||
}
|
||||
a.ensureTaskEmitter()
|
||||
base := a.ctx
|
||||
if base == nil {
|
||||
base = context.Background()
|
||||
}
|
||||
ctx, cancel := context.WithCancel(base)
|
||||
id := tasks.start("recovery-download", name, "", cancel)
|
||||
a.emitLog(name, "Downloading Apple online recovery image (~1 GB) for "+name+"...")
|
||||
go func() {
|
||||
defer cancel()
|
||||
res, err := ic.DownloadOnline(ctx, v, func(u installer.Update) {
|
||||
switch u.Kind {
|
||||
case installer.KindStep, installer.KindNote:
|
||||
a.emitLog(name, u.Message)
|
||||
}
|
||||
tasks.update(id, u)
|
||||
})
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
a.emitLog(name, "Online recovery download paused; starting again continues where it stopped")
|
||||
tasks.finish(id, "", context.Canceled)
|
||||
} else {
|
||||
a.emitLog(name, "Online recovery download error: "+err.Error())
|
||||
tasks.finish(id, "", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
tasks.update(id, installer.Update{
|
||||
Kind: installer.KindStep,
|
||||
Step: "attaching online recovery image",
|
||||
Message: "attaching online recovery image",
|
||||
Percent: -1,
|
||||
})
|
||||
attached, err := a.AttachInstaller(name, res.Image)
|
||||
if err != nil {
|
||||
a.emitLog(name, "Failed to attach online recovery image: "+err.Error())
|
||||
tasks.finish(id, "", err)
|
||||
return
|
||||
}
|
||||
a.emitLog(name, "Online recovery image attached: "+attached)
|
||||
tasks.finish(id, attached, nil)
|
||||
}()
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// FinishInstall exits recovery mode: ejects any attached installer, removes
|
||||
// REIMSHELP, enables the network if off, and restores OpenCore direct boot
|
||||
// (--boot-selection=false) if recovery mode enabled the boot picker.
|
||||
func (a *App) FinishInstall(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
ctx := context.Background()
|
||||
|
||||
if d.HasInstaller {
|
||||
a.emitLog(name, "Ejecting installer from "+name+"...")
|
||||
if err := c.Eject(ctx, name, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
stripped := reims.StripOfflineHelperArgs(d.ExtraArgs)
|
||||
setOpts := reims.SetOpts{Name: name}
|
||||
needSet := false
|
||||
upgradedNVMe := false
|
||||
if !d.Network {
|
||||
on := true
|
||||
setOpts.Network = &on
|
||||
needSet = true
|
||||
a.emitLog(name, "Turning the network on for "+name+"...")
|
||||
}
|
||||
if d.HasInstaller && strings.EqualFold(d.DiskController, "ahci") {
|
||||
setOpts.DiskController = "nvme"
|
||||
needSet = true
|
||||
upgradedNVMe = true
|
||||
a.emitLog(name, "Upgrading disk controller for "+name+" from SATA/AHCI to NVMe...")
|
||||
}
|
||||
if stripped != d.ExtraArgs {
|
||||
setOpts.ExtraArgs = &stripped
|
||||
needSet = true
|
||||
}
|
||||
if needSet {
|
||||
if err := c.Set(ctx, setOpts, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
running := a.isVMRunning(ctx, c, name, d)
|
||||
marker := vmstart.ReadRecoveryMarker(d.Directory)
|
||||
if running {
|
||||
var diffs []PendingChange
|
||||
if d.HasInstaller {
|
||||
diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"})
|
||||
}
|
||||
if !d.Network {
|
||||
diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"})
|
||||
}
|
||||
if upgradedNVMe {
|
||||
diffs = append(diffs, PendingChange{Field: "disk_controller", From: "ahci", To: "nvme"})
|
||||
}
|
||||
switch marker {
|
||||
case "want":
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "")
|
||||
case "on":
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "restore")
|
||||
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
|
||||
}
|
||||
if len(diffs) > 0 {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], diffs...)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
} else {
|
||||
if marker == "on" || marker == "restore" {
|
||||
a.emitLog(name, "Restoring OpenCore direct boot after exiting recovery mode...")
|
||||
if err := c.UpdateOpenCore(ctx, name, false, w, w); err != nil {
|
||||
a.emitLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
|
||||
} else {
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "")
|
||||
if prep, err := a.prep(name); err == nil {
|
||||
prep.ReplayGuestLang(ctx, d.Directory)
|
||||
}
|
||||
}
|
||||
} else if marker != "" {
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "")
|
||||
}
|
||||
}
|
||||
a.emitLog(name, "Exited recovery mode")
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpgradeDiskToNVMe switches an existing installed VM from legacy SATA/AHCI to
|
||||
// NVMe via `reims-ctl set --disk-controller nvme` (applies at next start if running).
|
||||
func (a *App) UpgradeDiskToNVMe(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.HasInstaller {
|
||||
return errors.New("exit recovery mode (eject installer) before switching disk controller")
|
||||
}
|
||||
if strings.EqualFold(d.DiskController, "nvme") {
|
||||
return nil
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
ctx := context.Background()
|
||||
a.emitLog(name, "Upgrading disk controller for "+name+" to NVMe...")
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
Field: "disk_controller",
|
||||
From: d.DiskController,
|
||||
To: "nvme",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
// Wails bindings for offline installers (roadmap M1.3). The download manager
|
||||
// page (M2.2) builds on these; downloads report through tasks (tasks.go).
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
// populateGuestLangDetail fills VMDetail.GuestLang from the VM's persisted
|
||||
// sidecar preference, falling back to reading prev-lang:kbd directly from its
|
||||
// OpenCore image so existing VMs accurately reflect their boot/recovery locale.
|
||||
func (a *App) populateGuestLangDetail(d *reims.VMDetail) {
|
||||
if d == nil || d.Directory == "" {
|
||||
return
|
||||
}
|
||||
if saved := opencore.ReadSavedGuestLang(d.Directory); saved != "" {
|
||||
d.GuestLang = saved
|
||||
return
|
||||
}
|
||||
if ocPath := opencore.ResolveOpenCorePath(d.Directory); ocPath != "" {
|
||||
if lang, err := opencore.ReadImagePrevLang(ocPath); err == nil && lang != "" {
|
||||
d.GuestLang = lang
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// prep returns the shared start/OpenCore helpers (internal/vmstart) for one VM,
|
||||
// logging to that VM's log panel.
|
||||
func (a *App) prep(name string) (*vmstart.Prep, error) {
|
||||
a.mu.Lock()
|
||||
cfg := *a.cfg
|
||||
a.mu.Unlock()
|
||||
return vmstart.New(cfg, func(line string) { a.emitLog(name, line) })
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package app
|
||||
|
||||
// Online runtime install from GitHub Releases (internal/runtime/remote.go).
|
||||
// Downloads run as "runtime-install" tasks, so progress shows in the status bar.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func (a *App) baseCtx() context.Context {
|
||||
if a.ctx != nil {
|
||||
return a.ctx
|
||||
}
|
||||
return context.Background()
|
||||
}
|
||||
|
||||
func (a *App) includeAlpha() bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return rt.NormalizeChannel(a.cfg.RuntimeChannel) == rt.ChannelAlpha
|
||||
}
|
||||
|
||||
func (a *App) runtimeSource() string {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return rt.NormalizeSource(a.cfg.RuntimeSource)
|
||||
}
|
||||
|
||||
// remoteCache keeps the release list for a while: GitHub allows 60
|
||||
// unauthenticated API requests an hour, and the host page, first launch and
|
||||
// the CLI all ask for it.
|
||||
var remoteCache struct {
|
||||
sync.Mutex
|
||||
at time.Time
|
||||
alpha bool
|
||||
source string
|
||||
list []rt.Remote
|
||||
}
|
||||
|
||||
const remoteCacheTTL = 10 * time.Minute
|
||||
|
||||
// ListRemoteRuntimes lists published runtimes for the configured channel and source.
|
||||
func (a *App) ListRemoteRuntimes() ([]rt.Remote, error) {
|
||||
alpha := a.includeAlpha()
|
||||
source := a.runtimeSource()
|
||||
remoteCache.Lock()
|
||||
defer remoteCache.Unlock()
|
||||
if remoteCache.list != nil && remoteCache.alpha == alpha && remoteCache.source == source && time.Since(remoteCache.at) < remoteCacheTTL {
|
||||
return remoteCache.list, nil
|
||||
}
|
||||
list, err := rt.DefaultSourceFor(source).ListRemote(a.baseCtx(), alpha)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
remoteCache.at, remoteCache.alpha, remoteCache.source, remoteCache.list = time.Now(), alpha, source, list
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// forgetRemoteRuntimes drops the cached list (after an install or a channel/source change).
|
||||
func forgetRemoteRuntimes() {
|
||||
remoteCache.Lock()
|
||||
remoteCache.list = nil
|
||||
remoteCache.Unlock()
|
||||
}
|
||||
|
||||
// SetRuntimeChannel picks "stable" or "alpha" for online installs
|
||||
// ("candidate", the old name for alpha, is still accepted).
|
||||
func (a *App) SetRuntimeChannel(channel string) error {
|
||||
switch channel {
|
||||
case rt.ChannelStable, rt.ChannelAlpha, "candidate":
|
||||
channel = rt.NormalizeChannel(channel)
|
||||
default:
|
||||
return fmt.Errorf("unknown channel %q", channel)
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.cfg.RuntimeChannel = channel
|
||||
forgetRemoteRuntimes()
|
||||
return config.Save("", a.cfg)
|
||||
}
|
||||
|
||||
// SetRuntimeSource picks "auto", "github", or "gitcode" for online runtime and
|
||||
// app update lookups.
|
||||
func (a *App) SetRuntimeSource(source string) error {
|
||||
switch strings.ToLower(strings.TrimSpace(source)) {
|
||||
case "", rt.SourceAuto, rt.SourceGitHub, rt.SourceGitCode:
|
||||
source = rt.NormalizeSource(source)
|
||||
default:
|
||||
return fmt.Errorf("unknown runtime source %q", source)
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.cfg.RuntimeSource = source
|
||||
forgetRemoteRuntimes()
|
||||
appUpdateCache.Lock()
|
||||
appUpdateCache.info = nil
|
||||
appUpdateCache.Unlock()
|
||||
return config.Save("", a.cfg)
|
||||
}
|
||||
|
||||
// InstallRuntimeOnline downloads, verifies and installs a published runtime
|
||||
// ("" or "latest" for the newest on the channel) and makes it active. It runs
|
||||
// in the background and returns the task ID; CancelTask pauses the download,
|
||||
// which resumes on the next install.
|
||||
func (a *App) InstallRuntimeOnline(commit string) (string, error) {
|
||||
a.mu.Lock()
|
||||
if a.needsSetup {
|
||||
a.mu.Unlock()
|
||||
return "", errors.New("choose a data folder first")
|
||||
}
|
||||
cfg := *a.cfg
|
||||
a.mu.Unlock()
|
||||
|
||||
subject := strings.TrimSpace(commit)
|
||||
if subject == "" {
|
||||
subject = "latest"
|
||||
}
|
||||
for _, t := range tasks.list() {
|
||||
if t.Kind == "runtime-install" && t.Status == TaskRunning {
|
||||
return t.ID, nil
|
||||
}
|
||||
}
|
||||
a.ensureTaskEmitter()
|
||||
ctx, cancel := context.WithCancel(a.baseCtx())
|
||||
id := tasks.start("runtime-install", subject, "", cancel)
|
||||
go func() {
|
||||
defer cancel()
|
||||
res, err := a.installRuntime(ctx, &cfg, commit, id)
|
||||
switch {
|
||||
case err == nil:
|
||||
tasks.finish(id, res, nil)
|
||||
case ctx.Err() != nil:
|
||||
a.emitLog("runtime", "Runtime download paused; installing again continues where it stopped")
|
||||
tasks.finish(id, "", context.Canceled)
|
||||
default:
|
||||
a.emitLog("runtime", "Runtime install error: "+err.Error())
|
||||
tasks.finish(id, "", err)
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
}()
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, taskID string) (string, error) {
|
||||
src := rt.DefaultSourceFor(cfg.RuntimeSource)
|
||||
step := func(msg string) {
|
||||
a.emitLog("runtime", msg)
|
||||
tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: msg, Percent: -1})
|
||||
}
|
||||
step("Looking up runtime releases")
|
||||
// An explicit commit may be an alpha even on the stable channel: the
|
||||
// user asked for it by name.
|
||||
list, err := src.ListRemote(ctx, rt.NormalizeChannel(cfg.RuntimeChannel) == rt.ChannelAlpha || (commit != "" && commit != "latest"))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
r, err := rt.Pick(list, commit)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if !rt.IsInstalled(cfg, r.Commit) {
|
||||
step("Downloading runtime " + r.Commit)
|
||||
path, err := src.Download(ctx, *r, rt.DownloadsDir(cfg), func(done, total int64) {
|
||||
tasks.update(taskID, installer.Update{
|
||||
Kind: installer.KindProgress, Step: "downloading runtime " + r.Commit,
|
||||
Done: done, Total: total, Percent: percent(done, total),
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
step("Installing runtime " + r.Commit)
|
||||
inst, err := rt.InstallFromArchive(cfg, path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
_ = os.Remove(path) // the unpacked runtime is what's kept
|
||||
r.Commit = inst.Commit
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
a.cfg.ActiveRuntime = r.Commit
|
||||
err = config.Save("", a.cfg)
|
||||
a.mu.Unlock()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.emitLog("runtime", fmt.Sprintf("Runtime %s (%s) installed and active", r.Commit, r.Channel))
|
||||
return r.Commit, nil
|
||||
}
|
||||
|
||||
func percent(done, total int64) float64 {
|
||||
if total <= 0 {
|
||||
return -1
|
||||
}
|
||||
return float64(done) * 100 / float64(total)
|
||||
}
|
||||
|
||||
var appUpdateCache struct {
|
||||
sync.Mutex
|
||||
at time.Time
|
||||
info *version.UpdateInfo
|
||||
}
|
||||
|
||||
// CheckAppUpdate checks GitHub Releases for a newer stable Reims-Go version.
|
||||
// Results are cached for 10 minutes unless force is true.
|
||||
func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) {
|
||||
source := a.runtimeSource()
|
||||
appUpdateCache.Lock()
|
||||
defer appUpdateCache.Unlock()
|
||||
if !force && appUpdateCache.info != nil && time.Since(appUpdateCache.at) < remoteCacheTTL {
|
||||
return *appUpdateCache.info, nil
|
||||
}
|
||||
info, err := version.DefaultSourceFor(source).CheckUpdate(a.baseCtx(), version.Version)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
copyInfo := info
|
||||
appUpdateCache.at = time.Now()
|
||||
appUpdateCache.info = ©Info
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// OpenURL opens an HTTPS link in the host's default browser.
|
||||
func (a *App) OpenURL(raw string) error {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
if !strings.HasPrefix(trimmed, "https://") {
|
||||
return fmt.Errorf("refusing to open non-HTTPS URL")
|
||||
}
|
||||
if a.ctx == nil {
|
||||
return errors.New("window context not ready")
|
||||
}
|
||||
wailsRuntime.BrowserOpenURL(a.ctx, trimmed)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package app
|
||||
|
||||
// First launch: the user picks the data folder before anything else is written
|
||||
// (runtimes, VMs, installers and caches all live under it).
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// DataRootChoice is a suggested data folder on one drive.
|
||||
type DataRootChoice struct {
|
||||
Path string `json:"path"`
|
||||
FreeGB float64 `json:"free_gb"`
|
||||
System bool `json:"system"`
|
||||
External bool `json:"external"` // USB disk: may be unplugged while a VM runs
|
||||
Recommended bool `json:"recommended"`
|
||||
}
|
||||
|
||||
// DataRootCheck describes a folder the user is about to choose.
|
||||
type DataRootCheck struct {
|
||||
Path string `json:"path"`
|
||||
FreeGB float64 `json:"free_gb"`
|
||||
System bool `json:"system"`
|
||||
External bool `json:"external"`
|
||||
HasConfig bool `json:"has_config"` // an earlier reims-go data folder: its VMs are kept
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// SuggestDataRoots offers <drive>\Data\reims-go on each fixed drive, the
|
||||
// non-system drive with the most free space first.
|
||||
func (a *App) SuggestDataRoots() []DataRootChoice {
|
||||
var out []DataRootChoice
|
||||
for _, d := range host.ListDrives() {
|
||||
out = append(out, DataRootChoice{
|
||||
Path: filepath.Join(d.Root, "Data", "reims-go"),
|
||||
FreeGB: d.FreeGB,
|
||||
System: d.System,
|
||||
External: d.External,
|
||||
})
|
||||
}
|
||||
// Internal non-system drives first, then the system drive, USB disks last;
|
||||
// most free space first within each. A USB disk is never recommended.
|
||||
rank := func(c DataRootChoice) int {
|
||||
switch {
|
||||
case c.External:
|
||||
return 2
|
||||
case c.System:
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
if rank(out[i]) != rank(out[j]) {
|
||||
return rank(out[i]) < rank(out[j])
|
||||
}
|
||||
return out[i].FreeGB > out[j].FreeGB
|
||||
})
|
||||
if len(out) > 0 && !out[0].External {
|
||||
out[0].Recommended = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// CheckDataRoot reports free space and whether dir already holds reims-go data.
|
||||
func (a *App) CheckDataRoot(dir string) DataRootCheck {
|
||||
dir = strings.TrimSpace(dir)
|
||||
c := DataRootCheck{Path: dir}
|
||||
if err := validateDataRoot(dir); err != nil {
|
||||
c.Error = err.Error()
|
||||
return c
|
||||
}
|
||||
c.FreeGB, _ = host.FreeGB(existingAncestor(dir))
|
||||
c.System = isSystemVolume(dir)
|
||||
vol := strings.ToUpper(filepath.VolumeName(dir))
|
||||
for _, d := range host.ListDrives() {
|
||||
if strings.EqualFold(d.Root[:2], vol) {
|
||||
c.External = d.External
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "reims-go.json")); err == nil {
|
||||
c.HasConfig = true
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// CompleteSetup makes dir the data folder: creates its layout, keeps an
|
||||
// existing reims-go config there (its runtimes and VMs), records the choice for
|
||||
// the next launch and leaves first-launch setup.
|
||||
func (a *App) CompleteSetup(dir string) error {
|
||||
dir = filepath.Clean(strings.TrimSpace(dir))
|
||||
if err := validateDataRoot(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
locale := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
cfg, err := config.Load(cfgPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
}
|
||||
cfg.DataRoot = dir
|
||||
if _, statErr := os.Stat(cfgPath); statErr != nil {
|
||||
cfg.Locale = locale // a new folder keeps the language picked on this screen
|
||||
}
|
||||
if err := cfg.EnsureDirs(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writable(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := config.Save(cfgPath, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := config.SaveLocation(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.cfg = cfg
|
||||
a.needsSetup = false
|
||||
a.mu.Unlock()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDataRoot(dir string) error {
|
||||
if dir == "" {
|
||||
return errors.New("choose a folder")
|
||||
}
|
||||
if !filepath.IsAbs(dir) {
|
||||
return fmt.Errorf("%s is not a full path", dir)
|
||||
}
|
||||
if filepath.Clean(dir) == filepath.VolumeName(dir)+string(filepath.Separator) || filepath.Dir(dir) == dir {
|
||||
return errors.New("choose a folder, not a whole drive")
|
||||
}
|
||||
if strings.ContainsAny(dir, ",") {
|
||||
// reims-ctl passes kext paths to reims-util as "PATH,MIN,MAX" and refuses ','
|
||||
// (upstream 3731afd reims_util.rs:308-317); the data folder holds them.
|
||||
return errors.New("the folder path can't contain ','")
|
||||
}
|
||||
if info, err := os.Stat(dir); err == nil && !info.IsDir() {
|
||||
return fmt.Errorf("%s is a file", dir)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// existingAncestor is dir or its nearest existing parent (for free-space checks
|
||||
// before the folder exists).
|
||||
func existingAncestor(dir string) string {
|
||||
for d := dir; ; d = filepath.Dir(d) {
|
||||
if _, err := os.Stat(d); err == nil {
|
||||
return d
|
||||
}
|
||||
if filepath.Dir(d) == d {
|
||||
return d
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isSystemVolume(dir string) bool {
|
||||
sys := os.Getenv("SystemDrive")
|
||||
vol := filepath.VolumeName(dir)
|
||||
return sys != "" && vol != "" && strings.EqualFold(sys, vol)
|
||||
}
|
||||
|
||||
func writable(dir string) error {
|
||||
f, err := os.CreateTemp(dir, ".write-test-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't write to %s: %w", dir, err)
|
||||
}
|
||||
name := f.Name()
|
||||
f.Close()
|
||||
return os.Remove(name)
|
||||
}
|
||||