Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c71ac8482 | ||
|
|
78d76f7353 | ||
|
|
5096d162cc | ||
|
|
29e9153d64 | ||
|
|
90a3509aaa | ||
|
|
354450ddcb | ||
|
|
8969c53644 | ||
|
|
f0b69c252c | ||
|
|
913dbdc6d9 | ||
|
|
af39c861e8 | ||
|
|
0afeac693c | ||
|
|
181c616909 | ||
|
|
007f2ac93c | ||
|
|
86d2da4a04 | ||
|
|
f30d901b7f | ||
|
|
15bc097a94 | ||
|
|
b9d4544a4d | ||
|
|
c70a760603 | ||
|
|
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 |
No files matched your search
@@ -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: 使用场景、交互设想或参考案例。
|
||||
|
Before Width: | Height: | Size: 62 KiB After Width: | Height: | Size: 78 KiB |
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 48 KiB |
|
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 41 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 45 KiB |
|
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 46 KiB |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 26 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
|
||||
@@ -1,47 +1,44 @@
|
||||
# AGENTS.md(reims-go)
|
||||
# AGENTS.md(Reims-Go)
|
||||
|
||||
> 面向在本仓库工作的 AI Agent 与协作者。遵循上级 [`D:\Build\AGENTS.md`](../AGENTS.md) 与 [`D:\Build\DISK-LAYOUT.md`](../DISK-LAYOUT.md)。
|
||||
> 面向在本仓库工作的 AI Agent 与协作者。
|
||||
|
||||
## 仓库定位
|
||||
|
||||
**`reims-go`** 是面向 Windows x86-64 的 **免编译、一站式 `reims-vgpu` macOS 虚拟机桌面启动器与工程工作台**(Go + Wails,GUI 与 CLI 共用内核)。
|
||||
**`reims-go`** 是面向 Windows x86-64 的免编译 `reims-vgpu` macOS 虚拟机桌面启动器与工作台(Go + Wails,GUI 与 CLI 共用核心)。
|
||||
|
||||
它与上游 [steelbrain/reims-vgpu](https://github.com/steelbrain/reims-vgpu) 及研究仓 [`D:\Build\macos-vm-lab`](../macos-vm-lab) 的分工:
|
||||
- `reims-vgpu`:上游底层引擎(QEMU 分支、`reims-graphics-pci`、`metal2vulkan`、`reims-ctl`、`reims-util`)。
|
||||
- `macos-vm-lab`:内核/图形深度研究、M0–M5 实验记录与基准数据。
|
||||
- `reims-go`(本仓库):产品化一站式桌面应用与便携运行时打包/分发流水线,让用户在无需安装 MSYS2、Rust、Git 或本地编译的前提下,开箱运行带 GPU 加速的 macOS 虚拟机(时间目标见 `docs/roadmap.md` 的 M2 DoD),并提供 CoW 派生、快照、P-Core 绑核、QMP/SSH 自动化等工程能力。
|
||||
与上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的分工:
|
||||
- **`reims-vgpu`**:底层引擎(QEMU 分支、`reims-graphics-pci`、`metal2vulkan`、`reims-ctl`、`reims-util`)。
|
||||
- **`reims-go`(本仓库)**:桌面应用、命令行包装与便携运行时打包/分发流水线,提供开箱即用的环境体检、离线装机、硬件调优、Guest Tools、恢复点与 CoW 派生能力。
|
||||
|
||||
## 存储与路径硬约束
|
||||
## 存储与产物边界
|
||||
|
||||
1. **代码与文档放仓库**:Go 后端、Wails 前端、打包脚本、CI workflow 与文档位于 `D:\Build\reims-go\`。
|
||||
2. **大体积文件严禁入库**:预编译 QEMU 运行时包(~900 MB 解压 / ~250 MB 压缩)、macOS 镜像、`.qcow2` 磁盘、快照统一放 **`D:\Data\reims-go\`**(开发联调时可复用 `D:\Data\macos-vm-lab\reims\`),**严禁写入 `C:` 或 `F:`**。
|
||||
3. **临时文件放 `D:\Build\Temp\`**:打包草稿、一次性测试目录用完即清。
|
||||
4. **Go 缓存**:本机已配置 `GOPATH=D:\DevCache\go`、`GOBIN=D:\DevTools\go-bin`,直接沿用即可。
|
||||
1. **大体积文件严禁入库**:便携运行时包、macOS 安装包、`.qcow2` 磁盘与快照一律保存在用户或开发者本地指定的 `<DataRoot>`(推荐非系统盘),不得提交到仓库。
|
||||
2. **临时文件及时清理**:打包草稿、一次性测试目录使用完后清理,不留在仓库工作区。
|
||||
|
||||
## 事实核验与安全规则
|
||||
|
||||
1. **上游行为以一手源码为准**:引用 `reims-ctl` / `reims-vgpu` 行为时附上游 commit 与 `文件:行号`;未实测项显式标「待验证」。
|
||||
2. **不绕过系统安全与人工确认**:UAC 提权启用 WHPX、重启 Windows、macOS GUI 安装向导、发布 Release 等操作由人确认触发。
|
||||
1. **上游行为以一手源码为准**:引用 `reims-ctl` / `reims-vgpu` 行为时核对对应上游 commit 与 `文件:行号`;未实测项显式标注「待验证」。
|
||||
2. **人工确认红线**:UAC 提权启用 WHPX、重启 Windows、macOS 图形安装向导、向上游提交 PR、将运行时升级为 `stable` 正式发布,均须由人确认触发。自动化例外:[`.github/workflows/build-runtime.yml`](.github/workflows/build-runtime.yml) 每日从上游构建,通过 `alpha` 准入检查后自动发布为 GitHub 预发布(`alpha` 通道),并自动清理较旧的未升级 `alpha` 预发布。
|
||||
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 节)。
|
||||
7. **配置只通过 `reims-ctl set` 写入**:不直接改 `vm.toml`,让上游的校验和 OpenCore 重建逻辑生效(`docs/shell-design.md`)。
|
||||
4. **对上游的修改只走补丁队列**:不长期维护 fork。补丁放 [`patches/`](patches/),顺序与状态统一在 [`patches/series.txt`](patches/series.txt) 与 [`patches/README.md`](patches/README.md) 维护,目标是清零。补丁打不上就停下报告,不要自动改写补丁。
|
||||
5. **运行时包如实声明来源**:`manifest.json` 必须写清上游各仓库 commit 与实际应用的全部补丁;带补丁的包不得宣称为纯上游构建。
|
||||
6. **默认用户只拿 `stable` 通道**:CI 产物先入 `alpha`,经真实宿主冒烟并人工确认后才升为 `stable`(见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md))。
|
||||
7. **配置写入只走 `reims-ctl set`**:不直接改写 `vm.toml`,保证上游校验与 OpenCore 重建生效(见 [`docs/design-guidelines.md`](docs/design-guidelines.md))。
|
||||
8. **文档维护纪律**:`docs/` 只存放当前生效的长期文档,使用单一事实来源;不写私人本机路径、日期补丁式叙事、易过时的伪代码/ASCII 草图;一次性排查、审视与排期记录留在 Issue 或 PR 中。
|
||||
|
||||
## 开源合规边界
|
||||
|
||||
- `reims-go` 自身代码(Go 后端 + 前端外壳)采用 **MIT** 协议,见 [`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`。
|
||||
- `reims-go` 自身代码(Go 后端与前端外壳)采用 [Apache-2.0](LICENSE) 协议。
|
||||
- 运行时组件(QEMU、`reims-ctl` / `reims-vgpu` / `metal2vulkan` 及 MSYS2 CLANG64 / libva 动态库)以独立子进程和独立压缩包形式集成。公开仓库通过 GitHub Release 分发运行时时,每个运行时 Release **必须**同处附带对应源码包(含本地补丁与 MSYS2 copyleft 源码)及完整许可证文本([`NOTICE.md`](NOTICE.md) / `licenses/`),详见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md)。
|
||||
- 不打包、不托管任何 Apple 系统文件;macOS 安装包与恢复镜像均由用户端直连 Apple 服务器获取或本地导入。
|
||||
|
||||
## 文档导航
|
||||
|
||||
- [`README.md`](README.md) — 项目总览、核心特性与差异化定位
|
||||
- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时剥离实测结论、目录规范与 CI 打包设计
|
||||
- [`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 兼容补丁)
|
||||
- [`docs/roadmap.md`](docs/roadmap.md) — M0–M4 里程碑与验收标准
|
||||
- [`README.md`](README.md) / [`README.en.md`](README.en.md) — 项目总览、核心特性与快速开始(中英双语)
|
||||
- [`CHANGELOG.md`](CHANGELOG.md) — 应用版本更新日志
|
||||
- [`docs/roadmap.md`](docs/roadmap.md) — 公开路线图与近期重点
|
||||
- [`docs/architecture.md`](docs/architecture.md) — 系统架构、模块职责与安全边界
|
||||
- [`docs/design-guidelines.md`](docs/design-guidelines.md) — 产品与界面设计规范(配置原语、状态模型、视觉与文案)
|
||||
- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时打包、发布通道与合规规范
|
||||
- [`docs/plugin-architecture.md`](docs/plugin-architecture.md) — 插件系统架构与扩展接口规范
|
||||
- [`patches/README.md`](patches/README.md) — 上游临时补丁队列与 PR 跟踪
|
||||
@@ -0,0 +1,165 @@
|
||||
# 更新日志
|
||||
|
||||
本文件只记录 Reims-Go 桌面应用的变化。便携运行时(`runtime-*`)的版本另见 [Releases](https://github.com/Nwflower/Reims-Go/releases)。
|
||||
|
||||
## v0.2.8 — 2026-11-29
|
||||
|
||||
### 优化与修复
|
||||
|
||||
- 修复 Windows 10 22H2 等环境下系统自带 `tar.exe` 缺少 `zstd` 解压器导致在线下载或导入本地 `.tar.zst` 运行时包失败的问题([#5](https://github.com/Nwflower/Reims-Go/issues/5)),改为内置纯 Go 解压 `.tar.zst`。
|
||||
- 新增真实 Vulkan 1.3 能力探测与显卡兼容性分级:启动器与 `reims-go doctor` 直接通过 `vulkan-1.dll` 核验 Vulkan 版本、PCI ID 与必需扩展,自动标记不满足门槛的老显卡及 Windows 下存在上游黑屏/设备丢失风险的 AMD Vega/Polaris([#4](https://github.com/Nwflower/Reims-Go/issues/4))与 RX 6600 XT 型号,并在向导与设置页支持一键改用 `VMware SVGA`。
|
||||
- 修复 `ClassifyGPU` 对 AMD 核显(`AMD Radeon Graphics` / `680M/780M/890M` / `Vega`)与 Intel Core Ultra 集成 Arc 显卡的识别,过滤已失效的注册表 ICD 路径;新建虚拟机默认显卡改为 `auto`,避免升级显卡驱动后因 `DriverStore` 路径变化导致配置失效。
|
||||
- 启动虚拟机前预先检查 WHPX 虚拟化平台状态,未开启虚拟化时给出明确中文/英文指引,不再因 QEMU 返回 `-ENOSPC` 误报磁盘空间不足;同时识别启动日志中的 `ERROR_DEVICE_LOST` 与 Vulkan 门槛拒绝并在排障包中记录 GPU 诊断结论。
|
||||
|
||||
## v0.2.7 — 2026-11-29
|
||||
|
||||
### 新功能
|
||||
|
||||
- 全新插件系统上线:新增独立「插件」页面与 `reims-go plugin` 命令行工具,支持内置扩展实时启停、本地插件包导入、开发者目录热重载与安全模式恢复(`--safe-mode`)。
|
||||
- 新增可选内置插件「虚拟机窗口安装引导」(`builtin.install-guide`,来自 [#3](https://github.com/Nwflower/Reims-Go/pull/3)):在虚拟机窗口旁悬浮展示离线安装、在线恢复与内置恢复分步引导,支持一键键入命令、退出恢复模式并重启续接、折叠及跟随明暗主题;停用后零残留回退为主界面内置恢复卡片。
|
||||
- 新增应用内自动更新与独立「关于」页面:自动检查正式版更新,支持在侧栏更新卡片或关于页中下载、续传、`SHA256SUMS.txt` 强校验并一键替换重启;原程序若保留发布文件名则自动更新为新版本名称。
|
||||
- 支持主题插件热重载、配色方案编辑器与 UI 契约校验,并支持通过插件扩展多语种语言包。
|
||||
- 首次启动自动跟随系统语言,新增英文 README,标题栏菜单补充交流群入口。
|
||||
|
||||
### 优化与修复
|
||||
|
||||
- 内置核心整合为始终启用的 `builtin.core`(保留 WHPX 降级与 Win10 冷重启排障开关);Guest Tools 传输服务、剪贴板互通、宿主输入服务与窗口安装引导均可独立启停,停用后彻底停止监听与后台钩子。
|
||||
- 修复 Windows 回调泄漏,新增 WebView2 界面健康看门狗与崩溃恢复提示,并加固插件与运行时内部处理逻辑。
|
||||
- 本地化配置校验与 CLI 错误提示,清理文档结构与残留草稿。
|
||||
|
||||
## v0.2.6 — 2026-11-29
|
||||
|
||||
### 新功能
|
||||
|
||||
- 可为每台虚拟机单独指定使用的 CPU 核心(自动、全部核心、性能核、避开低功耗核或自定义),运行中修改立即生效。
|
||||
- 虚拟机停机后可创建、回滚和删除恢复点。
|
||||
- 新增 SSH 快捷操作:记住用户名,一键打开终端、写入 `~/.ssh/config` 或用 VS Code 远程连接。
|
||||
- 运行中可一键把虚拟机窗口带到前台,或复制当前全分辨率截图到剪贴板。
|
||||
- 把文件拖进应用窗口即可直接传到虚拟机的共享文件夹。
|
||||
- 可在标题处直接给虚拟机起一个显示名称,底层目录和命令名保持不变;宽窗口下预览与配置信息并排显示。
|
||||
- 新增标题栏菜单和侧栏折叠(`Ctrl+B`),侧栏虚拟机支持右键菜单,底部状态栏更简洁。
|
||||
- 系统托盘菜单改版:每台虚拟机有独立子菜单和状态圆点,跟随 Windows 浅色/深色主题,截图和后台出错时弹出系统通知。
|
||||
- 侧栏和未截屏预览按 macOS 大版本显示对应图标;「安装包」页按大版本归组并折叠旧版本,加载失败可直接重试。
|
||||
|
||||
### 优化
|
||||
|
||||
- 虚拟机页按状态突出主要操作,并把实时负载、磁盘和 Guest Tools 状态收进摘要区。
|
||||
- 生成 4K 屏幕预览的内存占用大幅下降,删除虚拟机或长时间运行后及时清理后台资源与过期任务。
|
||||
- 界面各页面和弹窗改为按需加载,减少无谓刷新和显卡开销。
|
||||
- 修复空间分布统计,正确计入虚拟机文件以及数据目录中的其余数据。
|
||||
- Reims-Go 本体开源协议由 MIT 变更为 Apache-2.0;发布时同时提供 `.zip` 压缩包和独立 `.exe`。
|
||||
|
||||
## v0.2.5 — 2026-11-29
|
||||
|
||||
### 新功能
|
||||
|
||||
- 运行时下载与更新检查新增 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` §6):
|
||||
|
||||
1. **reims-vgpu / reims-ctl**
|
||||
- Upstream: https://github.com/steelbrain/reims-vgpu
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
<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>
|
||||
|
||||
<h1 align="center">Reims-Go</h1>
|
||||
|
||||
<p align="center">
|
||||
Run a GPU-accelerated macOS virtual machine on Windows — prebuilt, ready out of the box.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/Nwflower/Reims-Go/releases"><strong>Download</strong></a> ·
|
||||
<a href="#quick-start">Quick Start</a> ·
|
||||
<a href="#screenshots">Screenshots</a> ·
|
||||
<a href="./docs/roadmap.md">Roadmap</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="./README.md">简体中文</a> · <strong>English</strong>
|
||||
</p>
|
||||
|
||||
<br />
|
||||
|
||||
<p align="center">
|
||||
<img src="./.github/readme/hero.webp" width="100%" alt="Reims-Go main window showing the VM page in light mode and the Engine page in dark mode" />
|
||||
</p>
|
||||
|
||||
<br />
|
||||
|
||||
Reims-Go is a Windows desktop app and CLI wrapper for [reims-vgpu](https://github.com/steelbrain/reims-vgpu). Host checks, runtime installation, macOS downloads, VM creation, and day-to-day management all happen in one window.
|
||||
|
||||
> Early active development — features and UI are still being refined.
|
||||
|
||||
<br />
|
||||
|
||||
## Features
|
||||
|
||||
### Out of the Box
|
||||
|
||||
- **No compilation required** — Download and verify the portable runtime in one click, without installing MSYS2 or Rust. Automatically falls back to the GitCode mirror if GitHub is unreachable, and honors Windows system proxy settings.
|
||||
- **Check before you start** — First launch inspects virtualization (WHPX), Vulkan GPUs, and host memory; if Hypervisor Platform is off, enable it with one click.
|
||||
- **Keep C: clean** — Runtimes, installers, virtual disks, and temporary files all live in the data folder you choose.
|
||||
|
||||
### Installing macOS
|
||||
|
||||
- **Direct downloads from Apple** — Download full offline macOS installers on Windows with pause and resume; no network is required during installation.
|
||||
- **No manual typing** — One click types the install command straight into macOS Recovery Terminal to erase the disk and start installation automatically.
|
||||
- **Tuned for your PC** — Suggests memory based on available Windows commit memory and recommends crisp HiDPI resolutions for your display and DPI scaling.
|
||||
- **Pre-configured system language** — Choose your macOS language up front so Recovery and Setup Assistant launch in your preferred language.
|
||||
- **Import existing disks** — Reuse an existing `.qcow2`, VMDK, or RAW disk when creating a VM.
|
||||
|
||||
### Everyday Use
|
||||
|
||||
- **Windows interoperability** — Bidirectional clipboard (including images), shared folders with drag-and-drop file delivery, and optional read-only sharing of Windows drives to macOS Finder.
|
||||
- **Native IME & Unicode input** — Type CJK characters, emoji, and Windows IME text directly into the VM.
|
||||
- **Live status at a glance** — Screen preview plus live CPU, memory, and disk usage; copy a VM screenshot in one click.
|
||||
- **System tray integration** — Closing the window keeps clipboard and shared folders running in the background; start, stop, or keep macOS awake from the tray.
|
||||
- **Edit settings anytime** — Change VM settings even while running; the UI clearly shows whether changes apply immediately or on next start. Enter or exit Recovery mode in one click.
|
||||
- **Light & dark appearance, English & Chinese UI** — Automatically detects your Windows display language on first launch.
|
||||
|
||||
### Performance
|
||||
|
||||
- **GPU acceleration** — Accelerate macOS Metal graphics with your Windows discrete Vulkan GPU.
|
||||
- **Performance-core scheduling** — Automatically pins VMs to P-cores on hybrid CPUs to reduce stutter, or configure per-VM processor affinity live without restarting.
|
||||
- **Pre-start memory check** — Warns before starting if Windows commit memory is too low to allocate the VM.
|
||||
|
||||
### Power Features
|
||||
|
||||
- **Instant CoW clones** — Derive an independent copy-on-write clone from any stopped VM in seconds with near-zero initial disk overhead.
|
||||
- **Restore points** — Save an offline qcow2 snapshot before OS updates or major changes, and roll back with one click.
|
||||
- **Disk management** — Grow virtual disks or reclaim unused sparse space from stopped VMs.
|
||||
- **SSH helpers** — Port forwarding, one-click terminal launch, `~/.ssh/config` writer, and VS Code Remote-SSH integration.
|
||||
- **Built-in CLI** — Run host diagnostics, manage runtimes, download installers, and create, configure, start, or stop VMs from scripts.
|
||||
- **Diagnostics & Win10 compatibility** — Export a redacted diagnostics archive (`.zip`) in one click; seamless cold-reboot handling on Windows 10 when macOS restarts itself.
|
||||
|
||||
<br />
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Requirements
|
||||
|
||||
- Windows 10 / 11 (64-bit) with CPU virtualization enabled in BIOS (Intel VT-x / AMD-V)
|
||||
- Discrete Vulkan-capable GPU (NVIDIA RTX series recommended)
|
||||
- 16 GB+ RAM recommended
|
||||
- 150 GB+ free disk space recommended, 60 GB minimum (an offline installer is ~20 GB and virtual disks grow with use); an internal non-system drive is recommended
|
||||
|
||||
### Installation
|
||||
|
||||
Download the single-file `reims-go.exe` from [Releases](https://github.com/Nwflower/Reims-Go/releases) and double-click to run.
|
||||
|
||||
<details>
|
||||
<summary>Build from source</summary>
|
||||
|
||||
Requires [Go](https://go.dev/dl/), [Node.js](https://nodejs.org), [pnpm](https://pnpm.io), and [Wails](https://wails.io/docs/gettingstarted/installation):
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/Nwflower/Reims-Go
|
||||
cd Reims-Go
|
||||
wails build
|
||||
```
|
||||
|
||||
The binary is written to `build\bin\reims-go.exe`.
|
||||
|
||||
</details>
|
||||
|
||||
### Getting Started
|
||||
|
||||
1. **Initial setup** — Pick a data folder on first launch, check host readiness (enable WHPX with one click and reboot Windows if needed), and install the runtime online.
|
||||
2. **Create a VM** — Click **+** in the sidebar, choose **Offline installer** (or pre-download one on the **Installers** page), and configure CPU, memory, and disk size.
|
||||
3. **Install macOS** — Start the VM and follow the on-screen Recovery guide: open Terminal in Recovery and click the keyboard icon to type the install command automatically; once Setup Assistant appears, click **Exit recovery mode**.
|
||||
4. **Install Guest Tools** — On the macOS desktop, click **Install…** on the Guest Tools row in Reims-Go and run the command shown in macOS Terminal to enable clipboard sync, shared folders, and IME input.
|
||||
5. **Daily management** — Settings, restore points, and SSH tools are on the VM page; the **More** menu provides Send text, Recovery mode, CoW cloning, and diagnostics export.
|
||||
|
||||
### Command Line
|
||||
|
||||
The CLI lives inside the same `reims-go.exe`: running it with no arguments opens the window, while passing a subcommand executes in the terminal.
|
||||
|
||||
```powershell
|
||||
reims-go doctor | Out-Host # Inspect host environment
|
||||
reims-go runtime fetch | Out-Host # Install portable runtime online
|
||||
reims-go installer download tahoe | Out-Host # Download offline installer (resumable)
|
||||
reims-go vm create macos-tahoe | Out-Host # Create a VM
|
||||
reims-go vm start macos-tahoe | Out-Host # Start the VM
|
||||
reims-go vm stop macos-tahoe | Out-Host # Shut down the VM
|
||||
```
|
||||
|
||||
In interactive PowerShell or cmd, pipe to `| Out-Host` so the terminal waits for the command to finish and returns its exit code. Run `reims-go help` to view all commands; pass `--lang en-US` or `--lang zh-CN` to override the output language.
|
||||
|
||||
<br />
|
||||
|
||||
## Screenshots
|
||||
|
||||
<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="Engine page" />
|
||||
</picture>
|
||||
<p align="center"><sub>Engine</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="Virtual machine page" />
|
||||
</picture>
|
||||
<p align="center"><sub>Virtual Machine</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="VM settings" />
|
||||
</picture>
|
||||
<p align="center"><sub>VM Settings</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="New virtual machine wizard" />
|
||||
</picture>
|
||||
<p align="center"><sub>New Virtual Machine</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<br />
|
||||
|
||||
## License & Notice
|
||||
|
||||
- **Open-source license**: Reims-Go itself is licensed under [Apache-2.0](./LICENSE). Bundled runtime components such as QEMU are distributed as separate executables; see [`NOTICE.md`](./NOTICE.md) for third-party licenses. Every runtime release ships with its corresponding source archive.
|
||||
- **About macOS**: Reims-Go does not include or distribute any Apple system files; installers are downloaded directly from Apple on the user's machine. **The macOS Software License Agreement permits virtualization only on Apple-branded hardware** — evaluate your own compliance responsibilities on non-Apple hardware. This project is not affiliated with Apple Inc.; macOS is a registered trademark of Apple Inc.
|
||||
|
||||
## Links
|
||||
|
||||
- [LINUX DO](https://linux.do/) — Community forum
|
||||
|
||||
<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,125 +1,191 @@
|
||||
<p align="center">
|
||||
<a href="https://github.com/Nwflower/reims-go">
|
||||
<img src="./assets/logo.png" width="80" height="80" alt="reims-go 图标" />
|
||||
<a href="https://github.com/Nwflower/Reims-Go">
|
||||
<img src="./assets/logo.png" width="76" height="76" alt="Reims-Go" />
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<h1 align="center">reims-go</h1>
|
||||
|
||||
<p align="center">在 Windows 上开一台带 GPU 加速的 macOS 虚拟机,不用自己编译。</p>
|
||||
<h1 align="center">Reims-Go</h1>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/Nwflower/reims-go/releases"><strong>下载</strong></a> ·
|
||||
<a href="#安装">安装</a> ·
|
||||
<a href="#使用">使用</a> ·
|
||||
在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。
|
||||
</p>
|
||||
|
||||
<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>
|
||||
|
||||
<p align="center">
|
||||
<img src="./.github/readme/hero.webp" width="100%" alt="reims-go 主窗口:前面是浅色外观下正在运行的 macos-tahoe 虚拟机详情页,后面是深色外观下的宿主与运行时页" />
|
||||
<strong>简体中文</strong> · <a href="./README.en.md">English</a>
|
||||
</p>
|
||||
|
||||
reims-go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows 桌面应用。装好之后,检查电脑、下载 macOS、创建和启动虚拟机都在一个窗口里完成,不需要自己配环境或敲命令。
|
||||
<br />
|
||||
|
||||
> 早期开发中,功能和界面还会变。
|
||||
<p align="center">
|
||||
<img src="./.github/readme/hero.webp" width="100%" alt="Reims-Go 主窗口:浅色外观下的虚拟机页与深色外观下的内核页" />
|
||||
</p>
|
||||
|
||||
## 功能
|
||||
<br />
|
||||
|
||||
- **开箱即用。** 运行时已经预先编译好,在应用里点一下就能安装,不用装任何开发工具。
|
||||
- **电脑体检。** 一屏看清虚拟化是否开启、CPU、内存、显卡和剩余空间。虚拟化没开的话可以一键开启。
|
||||
- **下载 macOS。** 在 Windows 上直接下载 macOS 完整安装包,带进度条,可以暂停,断了能接着下。
|
||||
- **新建向导。** 五步建好一台虚拟机:选系统来源、CPU 与内存、存储、图形,最后确认。
|
||||
- **随时调整。** 设置按 macOS 系统设置的方式分类。虚拟机开着也能改,每一项都会告诉你什么时候生效。
|
||||
- **不占 C 盘。** 虚拟机、安装包和运行时都放在你选的数据目录里。
|
||||
- **浅色和深色外观**,界面支持中文和英文。
|
||||
Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows 桌面应用。从检查电脑、安装运行时、下载 macOS,到创建和日常使用虚拟机,都在一个窗口里完成。
|
||||
|
||||
## 安装
|
||||
> 早期迭代中,功能与界面仍在持续打磨。
|
||||
|
||||
<br />
|
||||
|
||||
## 特性
|
||||
|
||||
### 开箱即用
|
||||
|
||||
- **不用编译** — 运行时在应用里一键下载安装,不用装 MSYS2、Rust,也不用自己编译。GitHub 连不上时自动改从 GitCode 国内镜像下载,并沿用 Windows 的系统代理设置。
|
||||
- **先检查再开工** — 首次打开会检查虚拟化、显卡和内存;虚拟化没开的话可以一键开启。
|
||||
- **不占 C 盘** — 运行时、安装包、虚拟磁盘和临时文件都放在你选的数据目录里。
|
||||
|
||||
### 装机
|
||||
|
||||
- **安装包直接从 Apple 下载** — 在 Windows 上下载完整安装包,可以暂停和续传;装机过程不用联网。
|
||||
- **不用手敲命令** — 装机命令点一下就自动键入到 macOS 的恢复终端,抹盘和安装都会自动完成。
|
||||
- **按本机配置推荐** — 内存大小按电脑的空闲内存推荐,分辨率按显示器和缩放推荐清晰的 HiDPI 档位。
|
||||
- **装机界面用中文** — 可以提前选好 macOS 系统语言,恢复模式和设置助理不再只有英文。
|
||||
- **导入已有磁盘** — 新建时可以直接用现成的 VMDK 或 RAW 磁盘。
|
||||
|
||||
### 日常使用
|
||||
|
||||
- **和 Windows 互通** — 双向剪贴板(包括图片)和共享文件夹,把文件拖到窗口里就能传进 macOS;还可以把 Windows 磁盘以只读方式共享给 macOS。
|
||||
- **直接打中文** — 中文、emoji 和 Windows 输入法都能直接输入到虚拟机。
|
||||
- **一眼看清状态** — 页面上有屏幕预览,以及 CPU、内存、磁盘的实时占用;一键截屏并复制。
|
||||
- **常驻托盘** — 关掉窗口后剪贴板和共享照常工作,可以从托盘启动或关闭虚拟机,也可以让 macOS 保持唤醒。
|
||||
- **随时修改设置** — 虚拟机运行时也能改设置,界面会说明改动是立即生效还是下次启动生效;一键进入或退出恢复模式。
|
||||
- **浅色、深色外观,中英双语** — 首次启动自动识别 Windows 系统语言。
|
||||
|
||||
### 性能
|
||||
|
||||
- **显卡加速** — 用 Windows 上的独立显卡加速 macOS 的图形显示。
|
||||
- **自动挑选性能核** — 在大小核处理器上,虚拟机自动跑在性能核上,减少卡顿;也可以给每台虚拟机单独指定用哪些核,运行中修改立即生效。
|
||||
- **启动前检查内存** — 内存不够时会先提示,避免启动到一半失败。
|
||||
|
||||
### 进阶
|
||||
|
||||
- **秒级派生副本** — 已关机的虚拟机可以秒级派生出一台独立副本,副本只记录与原机的差异,刚派生时几乎不占额外空间。
|
||||
- **恢复点** — 升级系统或大改环境前留一个恢复点,出问题时一键回滚。
|
||||
- **磁盘管理** — 关机后可以给虚拟磁盘扩容,或回收没有用到的空间。
|
||||
- **SSH** — 端口转发,一键打开终端、写入 `~/.ssh/config` 或用 VS Code 远程连接。
|
||||
- **命令行** — 检查环境、安装运行时、下载安装包,以及新建、修改、启动和关闭虚拟机,都能在命令行里完成,方便写脚本。
|
||||
- **排障** — 一键导出已去掉隐私信息的日志包;Windows 10 上 macOS 自己重启时也能正常回到系统。
|
||||
|
||||
<br />
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Windows 11 64 位
|
||||
- 一块支持 Vulkan 的独立显卡,推荐 NVIDIA RTX 系列
|
||||
- 建议留出 150 GB 以上的可用空间,用来放 macOS 安装包和虚拟磁盘
|
||||
- Windows 10 / 11(64 位),处理器支持虚拟化,并已在 BIOS 里开启 Intel VT-x / AMD-V
|
||||
- 支持 Vulkan 的独立显卡(推荐 NVIDIA RTX 系列)
|
||||
- 内存建议 16 GB 以上
|
||||
- 可用磁盘空间建议 150 GB 以上,至少 60 GB(一个安装包约 20 GB,虚拟磁盘会随使用增长);最好不要放在系统盘或外置盘
|
||||
|
||||
### 下载
|
||||
### 安装
|
||||
|
||||
打包好的安装程序还没有发布,目前需要从源码构建。先装好 [Go](https://go.dev/dl/)、[Node.js](https://nodejs.org)、[pnpm](https://pnpm.io) 和 [Wails](https://wails.io/docs/gettingstarted/installation),然后运行:
|
||||
前往 [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
|
||||
git clone https://github.com/Nwflower/Reims-Go
|
||||
cd Reims-Go
|
||||
wails build
|
||||
```
|
||||
|
||||
构建完成后,双击 `build\bin\reims-go.exe` 启动。
|
||||
产物位于 `build\bin\reims-go.exe`。
|
||||
|
||||
## 使用
|
||||
</details>
|
||||
|
||||
1. **选择数据目录。** 第一次打开时,应用会推荐一个空间充足、不在 C 盘的位置。
|
||||
2. **检查电脑并安装运行时。** 进入「宿主与运行时」页,确认各项都是「就绪」。虚拟化没开的话点「启用」,按提示重启一次电脑。然后在「运行时」里点「在线安装」。
|
||||
3. **新建虚拟机。** 点侧边栏的 **+**,按向导选好 macOS 版本、CPU、内存和磁盘大小。
|
||||
4. **启动并安装 macOS。** 点「启动」,会弹出虚拟机窗口。照着虚拟机页上的提示操作:先在「磁盘工具」里把磁盘抹掉成 APFS,再选「重新安装 macOS」。进入 macOS 桌面后,点「弹出安装盘」。
|
||||
5. **调整配置。** 点齿轮图标打开设置。
|
||||
### 上手步骤
|
||||
|
||||
> 在线安装目前还没有正式版运行时可选。在这之前,可以在「宿主与运行时」页打开「接收候选版」,或者用「导入运行时包」导入本地的运行时。
|
||||
1. **初始化** — 首次打开时按引导选好数据目录,完成电脑检查(虚拟化没开可以一键开启,之后需要重启 Windows),再在线安装运行时。
|
||||
2. **新建虚拟机** — 点侧边栏的 **+**,安装来源选「离线安装包」(也可以先到「安装包」页下载好),再设好 CPU、内存和磁盘。
|
||||
3. **安装 macOS** — 启动虚拟机,按页面上的装机引导操作:在恢复终端里点键盘图标,装机命令会自动键入,抹盘和安装随即开始;看到「设置助理」后点「退出恢复模式」。
|
||||
4. **安装 Guest Tools** — 进入 macOS 桌面后,在虚拟机页 Guest Tools 一行点「安装…」,再到 macOS 终端里运行页面给出的命令。装好后剪贴板、共享文件夹和中文输入就能用了。
|
||||
5. **日常管理** — 设置、恢复点和 SSH 都在虚拟机页上;「更多」菜单里还有发送文本、进入恢复模式、派生副本、导出排障日志等操作。
|
||||
|
||||
### 命令行
|
||||
|
||||
不想用图形界面的话,同样的功能也可以用命令行完成:
|
||||
命令行就在同一个 `reims-go.exe` 里:不带参数会打开窗口,带上子命令就在终端里执行。
|
||||
|
||||
```powershell
|
||||
reims-go doctor # 检查电脑
|
||||
reims-go runtime fetch # 安装运行时
|
||||
reims-go installer download tahoe # 下载 macOS 安装包
|
||||
reims-go vm create macos-tahoe # 新建虚拟机
|
||||
reims-go vm start macos-tahoe # 启动
|
||||
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 # 关闭虚拟机
|
||||
```
|
||||
|
||||
运行 `reims-go help` 查看全部命令,加 `--lang en-US` 切换成英文输出。
|
||||
在 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="宿主与运行时页:虚拟化、处理器、内存、可用空间四张卡片,下面是运行时和数据目录" />
|
||||
<img src="./.github/readme/host-light.webp" alt="内核页" />
|
||||
</picture>
|
||||
<p align="center"><sub>电脑体检与运行时</sub></p>
|
||||
<p align="center"><sub>内核</sub></p>
|
||||
</td>
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/vm-dark.webp" />
|
||||
<img src="./.github/readme/vm-light.webp" alt="关于此虚拟机页:名称、处理器、图形、内存、存储、网络和显示器" />
|
||||
<img src="./.github/readme/vm-light.webp" alt="虚拟机页" />
|
||||
</picture>
|
||||
<p align="center"><sub>关于此虚拟机</sub></p>
|
||||
<p align="center"><sub>虚拟机</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/settings-dark.webp" />
|
||||
<img src="./.github/readme/settings-light.webp" alt="虚拟机设置:左侧是分类,右侧是 CPU 核数选择" />
|
||||
<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="新建虚拟机向导:系统来源、CPU 与内存、存储、图形与外设、确认五步" />
|
||||
<img src="./.github/readme/wizard-light.webp" alt="新建虚拟机向导" />
|
||||
</picture>
|
||||
<p align="center"><sub>新建虚拟机</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 许可证
|
||||
<br />
|
||||
|
||||
reims-go 使用 [MIT](./LICENSE) 许可证。它调用的运行时组件有各自的开源许可证,见 [`NOTICE.md`](./NOTICE.md)。
|
||||
## 许可与声明
|
||||
|
||||
## 关于 macOS
|
||||
- **开源协议**: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. 注册商标。
|
||||
|
||||
reims-go 不包含、也不分发任何 Apple 系统文件,macOS 安装包由你的电脑直接从 Apple 服务器下载。
|
||||
## 友情链接
|
||||
|
||||
**macOS 的软件许可协议只允许在 Apple 硬件上运行虚拟机。** 在其他硬件上使用是否合规,需要你自己判断并承担责任。reims-go 与 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,621 +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"`
|
||||
// NeedsSetup is true on first launch, until a data folder is chosen (setup.go).
|
||||
NeedsSetup bool `json:"needs_setup"`
|
||||
}
|
||||
|
||||
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
|
||||
needsSetup bool
|
||||
}
|
||||
|
||||
func NewApp() *App {
|
||||
cfg, needsSetup, err := config.Resolve()
|
||||
if err != nil {
|
||||
cfg = config.Default()
|
||||
}
|
||||
return &App{
|
||||
cfg: cfg,
|
||||
needsSetup: needsSetup,
|
||||
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...)
|
||||
}
|
||||
needsSetup := a.needsSetup
|
||||
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,
|
||||
NeedsSetup: needsSetup,
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
if err == nil {
|
||||
err = config.SaveLocation(dir)
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -1,342 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"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"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(os.Args[1:]); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(args []string) error {
|
||||
fs := flag.NewFlagSet("reims-go", flag.ContinueOnError)
|
||||
langFlag := fs.String("lang", "", "UI/CLI language: zh-CN | en-US")
|
||||
dataRootFlag := fs.String("data-root", "", "Override reims-go data root directory")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cfgPath := ""
|
||||
if *dataRootFlag != "" {
|
||||
cfgPath = filepath.Join(*dataRootFlag, "reims-go.json")
|
||||
}
|
||||
cfg, err := config.Load(cfgPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *dataRootFlag != "" {
|
||||
cfg.DataRoot = *dataRootFlag
|
||||
}
|
||||
if *langFlag != "" {
|
||||
cfg.Locale = i18n.Normalize(*langFlag)
|
||||
}
|
||||
loc := cfg.Locale
|
||||
|
||||
rest := fs.Args()
|
||||
if len(rest) == 0 {
|
||||
printUsage(loc)
|
||||
return nil
|
||||
}
|
||||
|
||||
switch rest[0] {
|
||||
case "doctor":
|
||||
return cmdDoctor(cfg, loc, rest[1:])
|
||||
case "runtime":
|
||||
return cmdRuntime(cfg, loc, rest[1:])
|
||||
case "vm":
|
||||
return cmdVM(cfg, loc, rest[1:])
|
||||
case "installer":
|
||||
return cmdInstaller(cfg, loc, rest[1:])
|
||||
case "help", "-h", "--help":
|
||||
printUsage(loc)
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unknown command %q", rest[0])
|
||||
}
|
||||
}
|
||||
|
||||
func printUsage(loc i18n.Locale) {
|
||||
if loc == i18n.ZhCN {
|
||||
fmt.Println("reims-go - Windows 一站式免编译 reims-vgpu 启动器与 CLI")
|
||||
fmt.Println("\n用法:")
|
||||
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <命令> [参数]")
|
||||
fmt.Println("\n命令:")
|
||||
fmt.Println(" doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)")
|
||||
fmt.Println(" runtime available 列出 GitHub 上发布的运行时(--candidate 含候选版)")
|
||||
fmt.Println(" runtime fetch [commit] 在线下载、校验并安装运行时(默认最新;Ctrl+C 暂停,再次运行续传)")
|
||||
fmt.Println(" runtime install <archive> 导入并校验本地运行时包(.tar.zst 或 .zip)")
|
||||
fmt.Println(" runtime list 查看已安装的便携运行时版本")
|
||||
fmt.Println(" runtime use <commit> 切换当前激活运行时")
|
||||
fmt.Println(" vm list 列出已创建的虚拟机")
|
||||
fmt.Println(" vm create [options] <name> 创建 macOS 虚拟机(可指定目录/核数/内存/硬盘/显卡)")
|
||||
fmt.Println(" vm set [options] <name> 修改虚拟机配置(下次启动生效)")
|
||||
fmt.Println(" vm start|stop|eject <name> 启动 / 停止 / 弹出安装盘")
|
||||
fmt.Println(" installer list 列出 Apple 提供的离线安装包版本(需联网)")
|
||||
fmt.Println(" installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)")
|
||||
fmt.Println(" installer cached 查看已下载的安装包及占用空间")
|
||||
fmt.Println(" installer delete <文件名> 删除已下载的安装包(正在使用或下载中的会被拒绝)")
|
||||
return
|
||||
}
|
||||
fmt.Println("reims-go - Portable one-stop reims-vgpu launcher & CLI for Windows")
|
||||
fmt.Println("\nUsage:")
|
||||
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <command> [args]")
|
||||
fmt.Println("\nCommands:")
|
||||
fmt.Println(" doctor Inspect host (WHPX / Vulkan GPUs / P-E cores / disk / runtime)")
|
||||
fmt.Println(" runtime available List runtimes published on GitHub (--candidate includes candidates)")
|
||||
fmt.Println(" runtime fetch [commit] Download, verify and install a runtime (newest by default; Ctrl+C pauses)")
|
||||
fmt.Println(" runtime install <archive> Verify and install a local runtime package (.tar.zst or .zip)")
|
||||
fmt.Println(" runtime list List installed portable runtimes")
|
||||
fmt.Println(" runtime use <commit> Activate an installed runtime version")
|
||||
fmt.Println(" vm list List virtual machines")
|
||||
fmt.Println(" vm create [options] <name> Create a macOS VM (custom dir, CPUs, RAM, disk size, GPU)")
|
||||
fmt.Println(" vm set [options] <name> Update VM settings (applies on next start)")
|
||||
fmt.Println(" vm start|stop|eject <name> Start / stop / eject installer")
|
||||
fmt.Println(" installer list List offline macOS installers Apple offers (needs network)")
|
||||
fmt.Println(" installer download <ver> Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)")
|
||||
fmt.Println(" installer cached List downloaded installers and the space they take")
|
||||
fmt.Println(" installer delete <name> Delete a downloaded installer (refused if in use or downloading)")
|
||||
}
|
||||
|
||||
func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
fs := flag.NewFlagSet("doctor", flag.ContinueOnError)
|
||||
asJSON := fs.Bool("json", false, "Output JSON")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
rep := host.Inspect(cfg.DataRoot)
|
||||
active, _ := rt.ResolveActive(cfg)
|
||||
|
||||
if *asJSON {
|
||||
payload := map[string]any{
|
||||
"host": rep,
|
||||
"config": cfg,
|
||||
"runtime": active,
|
||||
}
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
return enc.Encode(payload)
|
||||
}
|
||||
|
||||
fmt.Printf("=== %s ===\n", i18n.T(loc, "doctor.title"))
|
||||
fmt.Printf("%-36s: %s/%s\n", i18n.T(loc, "doctor.os"), rep.OS, rep.Arch)
|
||||
fmt.Printf("%-36s: %dC / %dT\n", i18n.T(loc, "doctor.cpu"), rep.PhysicalCores, rep.LogicalCPUs)
|
||||
if rep.HasHybridCores {
|
||||
fmt.Printf("%-36s: %d cores, mask %s (CPUs %v)\n", i18n.T(loc, "doctor.pcores"), rep.PCoreCount, rep.PCoreMaskHex, rep.PCoreLogicalCPUs)
|
||||
fmt.Printf("%-36s: %d cores (CPUs %v)\n", i18n.T(loc, "doctor.ecores"), rep.ECoreCount, rep.ECoreLogicalCPUs)
|
||||
}
|
||||
if rep.TotalRAMGB > 0 {
|
||||
fmt.Printf("%-36s: %.1f GB total / %.1f GB avail\n", i18n.T(loc, "doctor.ram"), rep.TotalRAMGB, rep.AvailRAMGB)
|
||||
}
|
||||
if rep.FreeDiskGB > 0 {
|
||||
fmt.Printf("%-36s: %.1f GB (%s)\n", i18n.T(loc, "doctor.disk"), rep.FreeDiskGB, rep.DataRoot)
|
||||
}
|
||||
|
||||
whpxKey := "doctor.whpx.unsupported"
|
||||
switch rep.WHPX {
|
||||
case host.WHPXReady:
|
||||
whpxKey = "doctor.whpx.ok"
|
||||
case host.WHPXNoHypervisor:
|
||||
whpxKey = "doctor.whpx.no_hv"
|
||||
case host.WHPXMissing:
|
||||
whpxKey = "doctor.whpx.missing"
|
||||
}
|
||||
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.whpx"), i18n.T(loc, whpxKey))
|
||||
|
||||
if len(rep.GPUs) == 0 {
|
||||
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.gpu"), i18n.T(loc, "doctor.gpu.none"))
|
||||
} else {
|
||||
fmt.Printf("%s:\n", i18n.T(loc, "doctor.gpu"))
|
||||
for _, g := range rep.GPUs {
|
||||
rec := ""
|
||||
if rep.RecommendedGPU != nil && rep.RecommendedGPU.VulkanICD == g.VulkanICD {
|
||||
rec = " [" + i18n.T(loc, "doctor.gpu.recommended") + "]"
|
||||
}
|
||||
fmt.Printf(" - [%s] %s%s\n ICD: %s\n", g.Kind, g.Name, rec, g.VulkanICD)
|
||||
}
|
||||
}
|
||||
|
||||
if active == nil {
|
||||
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.none"))
|
||||
} else {
|
||||
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.active", active.Commit, active.Dir))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: reims-go runtime <available|fetch|install|list|use>")
|
||||
}
|
||||
switch args[0] {
|
||||
case "install":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go runtime install <archive.tar.zst|zip>")
|
||||
}
|
||||
inst, err := rt.InstallFromArchive(cfg, args[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.ActiveRuntime = inst.Commit
|
||||
if err := config.Save("", cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(i18n.T(loc, "runtime.installed", inst.Commit, inst.Dir))
|
||||
return nil
|
||||
case "list":
|
||||
list, err := rt.List(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(list) == 0 {
|
||||
fmt.Println(i18n.T(loc, "runtime.empty"))
|
||||
return nil
|
||||
}
|
||||
for _, item := range list {
|
||||
mark := " "
|
||||
if item.Active {
|
||||
mark = "*"
|
||||
}
|
||||
fmt.Printf("%s %s %s (%s)\n", mark, item.Commit, item.Manifest.QemuVersion, item.Dir)
|
||||
}
|
||||
return nil
|
||||
case "use":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go runtime use <commit>")
|
||||
}
|
||||
list, err := rt.List(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, item := range list {
|
||||
if item.Commit == args[1] {
|
||||
cfg.ActiveRuntime = item.Commit
|
||||
if err := config.Save("", cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(i18n.T(loc, "runtime.activated", item.Commit))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("runtime %q not found", args[1])
|
||||
case "available":
|
||||
return cmdRuntimeAvailable(cfg, loc, args[1:])
|
||||
case "fetch":
|
||||
return cmdRuntimeFetch(cfg, loc, args[1:])
|
||||
default:
|
||||
return fmt.Errorf("unknown runtime subcommand %q", args[0])
|
||||
}
|
||||
}
|
||||
|
||||
func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|eject>")
|
||||
}
|
||||
active, err := rt.ResolveActive(cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s", i18n.T(loc, "err.runtime_not_installed"))
|
||||
}
|
||||
client := reims.NewClient(cfg, *active)
|
||||
ctx := context.Background()
|
||||
|
||||
switch args[0] {
|
||||
case "list":
|
||||
vms, err := client.ListRaw(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(vms) == 0 {
|
||||
fmt.Println(i18n.T(loc, "vm.empty"))
|
||||
return nil
|
||||
}
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
return enc.Encode(vms)
|
||||
case "create":
|
||||
fs := flag.NewFlagSet("vm create", flag.ContinueOnError)
|
||||
dir := fs.String("dir", "", "Custom VM directory")
|
||||
macos := fs.String("macos", "tahoe", "macOS version (e.g. tahoe)")
|
||||
cpus := fs.Int("cpus", 8, "vCPU count")
|
||||
mem := fs.String("memory", "16G", "RAM size (e.g. 8G, 16G)")
|
||||
diskSize := fs.String("disk-size", "128G", "New disk size (e.g. 128G)")
|
||||
gpu := fs.String("gpu", "auto", "GPU selector or Vulkan ICD JSON path")
|
||||
logs := fs.Bool("logs", true, "Keep graphics and serial logs")
|
||||
start := fs.Bool("start", false, "Start VM immediately after creation")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm create [flags] <name>")
|
||||
}
|
||||
name := fs.Arg(0)
|
||||
opts := reims.CreateOpts{
|
||||
Name: name,
|
||||
Dir: *dir,
|
||||
MacOS: *macos,
|
||||
CPUs: *cpus,
|
||||
Memory: *mem,
|
||||
DiskSize: *diskSize,
|
||||
GPU: *gpu,
|
||||
Logs: logs,
|
||||
Start: *start,
|
||||
}
|
||||
if err := client.Create(ctx, opts, os.Stdout, os.Stderr); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("\n" + i18n.T(loc, "vm.install_guide.title"))
|
||||
fmt.Println(i18n.T(loc, "vm.install_guide.step1"))
|
||||
fmt.Println(i18n.T(loc, "vm.install_guide.step2"))
|
||||
fmt.Println(i18n.T(loc, "vm.install_guide.step3", name))
|
||||
return nil
|
||||
case "set":
|
||||
fs := flag.NewFlagSet("vm set", flag.ContinueOnError)
|
||||
cpus := fs.Int("cpus", 0, "vCPU count")
|
||||
mem := fs.String("memory", "", "RAM size")
|
||||
gpu := fs.String("gpu", "", "GPU selector or Vulkan ICD JSON")
|
||||
res := fs.String("resolution", "", "Window resolution WIDTHxHEIGHT")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm set [flags] <name>")
|
||||
}
|
||||
return client.Set(ctx, reims.SetOpts{
|
||||
Name: fs.Arg(0),
|
||||
CPUs: *cpus,
|
||||
Memory: *mem,
|
||||
GPU: *gpu,
|
||||
Resolution: *res,
|
||||
}, os.Stdout, os.Stderr)
|
||||
case "start":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm start <name>")
|
||||
}
|
||||
return client.Start(ctx, args[1], os.Stdout, os.Stderr)
|
||||
case "stop":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm stop <name>")
|
||||
}
|
||||
return client.Stop(ctx, args[1], os.Stdout, os.Stderr)
|
||||
case "eject":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm eject <name>")
|
||||
}
|
||||
return client.Eject(ctx, args[1], os.Stdout, os.Stderr)
|
||||
default:
|
||||
return fmt.Errorf("unknown vm subcommand %q", strings.Join(args, " "))
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,129 +1,119 @@
|
||||
# 系统架构设计(Architecture)
|
||||
# 系统架构(Architecture)
|
||||
|
||||
> 技术栈:**Go + Wails**(Windows x86-64 优先,GUI 与 CLI 共用核心逻辑)
|
||||
> 技术栈:**Go + Wails(React / TypeScript)**,面向 Windows x86-64,桌面界面与命令行共用同一份 Go 核心。
|
||||
|
||||
## 1. 设计目标与原则
|
||||
---
|
||||
|
||||
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 中自动化调用。
|
||||
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)或远程宿主模式。
|
||||
## 1. 设计原则
|
||||
|
||||
## 2. 总体分层架构
|
||||
1. **免编译开箱**:用户仅需单个 `reims-go.exe`,由应用内完成宿主机体检、便携运行时下载、离线安装包获取与虚拟机管理。
|
||||
2. **包装而非重写引擎**:通过受控子进程调用上游 `reims-ctl`、`reims-util` 与 `qemu-img`,不手写易随上游演进失效的 QEMU 启动参数拼接逻辑。
|
||||
3. **GUI 与 CLI 单文件同源**:所有业务逻辑下沉在 `internal/`。无参数启动 Wails 桌面窗口,带子命令(`reims-go <subcommand>`)进入命令行模式,供终端、脚本与自动化工具调用。
|
||||
4. **数据目录隔离**:运行时、下载缓存、虚拟机磁盘、快照与临时文件全部落在用户选定的 `<DataRoot>` 下,不污染系统盘。
|
||||
5. **原生中英双语**:前后端内置 `zh-CN` / `en-US` 双语字典,自动跟随系统语言并支持运行时切换。
|
||||
6. **跨平台开发友好**:所有 Windows 原生 API(WHPX、注册表、处理器拓扑、进程亲和性、系统代理、托盘)严格隔离在 `*_windows.go`,提供 `*_other.go` 桩实现,确保非 Windows 环境也能执行 `go build` 与 `go test ./...`。
|
||||
|
||||
---
|
||||
|
||||
## 2. 总体分层
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph UI["交互层"]
|
||||
GUI["Wails 桌面界面\n(React / Vite + WebView2)"]
|
||||
CLI["CLI 子命令\n(reims-go doctor/runtime/vm/clone/exec)"]
|
||||
GUI["Wails 桌面界面\n(frontend/src, React + Vite)"]
|
||||
CLI["命令行模式\n(internal/cli, 与 GUI 同 exe)"]
|
||||
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截屏与状态监控)"]
|
||||
Orchestration["app/ & vmstart/\n编排、任务、监控、启动准备"]
|
||||
Host["host/ & netproxy/\nWHPX/内存/GPU/大小核体检、代理"]
|
||||
Assets["runtime/ & installer/\n便携运行时与离线安装包管理"]
|
||||
Engine["driver/reims/ & opencore/\nreims-ctl/qemu-img 包装与引导预设"]
|
||||
Bridge["qmp/ guesttools/ thumb/ tray/\n键入/截屏/冷重启、剪贴板/WebDAV、托盘"]
|
||||
end
|
||||
|
||||
subgraph External["外部运行时(独立子进程,全部在 DataRoot 下)"]
|
||||
subgraph External["独立子进程运行时 (<DataRoot>/runtimes/)"]
|
||||
ReimsCtl["reims-ctl.exe + reims-util.exe"]
|
||||
QEMU["qemu-system-x86_64.exe + qemu-img.exe\n(含 reims-graphics-pci + 71 DLLs)"]
|
||||
QEMU["qemu-system-x86_64.exe + qemu-img.exe"]
|
||||
end
|
||||
|
||||
GUI --> Preflight & RuntimeMgr & InstallerMgr & VMMgr & Control
|
||||
CLI --> Preflight & RuntimeMgr & InstallerMgr & VMMgr & Control
|
||||
InstallerMgr --> ReimsCtl
|
||||
VMMgr --> ReimsCtl
|
||||
VMMgr --> QEMU
|
||||
Control --> QEMU
|
||||
GUI --> Orchestration
|
||||
CLI --> Orchestration & Host & Assets & Engine
|
||||
Orchestration --> Host & Assets & Engine & Bridge
|
||||
Assets --> ReimsCtl
|
||||
Engine --> ReimsCtl & QEMU
|
||||
Bridge --> QEMU
|
||||
ReimsCtl --> QEMU
|
||||
```
|
||||
|
||||
## 3. 核心模块设计
|
||||
---
|
||||
|
||||
### 3.1 `internal/host` — 宿主机体检与自动硬件调优
|
||||
- **WHPX 检测与引导**:
|
||||
- 直接加载 `WinHvPlatform.dll` 调用 `WHvGetCapability`(与 `reims-ctl` 逻辑一致),同时查询 `Win32_OptionalFeature`(`HypervisorPlatform` / `VirtualMachinePlatform`),**无需管理员权限即可准确判断**。
|
||||
- 仅在检测到未启用时,GUI 提供「开启 Hypervisor Platform(需要 UAC)」按钮,调用 `ShellExecuteW(..., "runas", ...)` 弹出标准桌面 UAC 并提示重启。
|
||||
- **提交内存(Commit Limit)实时预检(2026-11-28 实测沉淀)**:
|
||||
- 实测 32 GB 宿主在开启日常软件后,剩余可提交内存可能仅 `14.7 GiB`,QEMU 启动时 `CreateFileMapping` 一次性提交 `16G` 直接报错退出。
|
||||
- `internal/host` 通过 `GlobalMemoryStatusEx` 同时采集物理内存与当前可用提交内存(`AvailPageFile`),建机向导默认预留 ≥ 2.5–3 GiB 给宿主机并推荐安全档位(32 GB 宿主默认推荐 `8G–12G`);启动 VM 前若可用提交内存不足,GUI 直接拦截并给出「一键调小内存」或「关闭宿主机程序后重试」。
|
||||
- **GPU / Vulkan ICD 自动选卡**:
|
||||
- 读取注册表显示适配器类键下的 `VulkanDriverName` 与 `DriverDesc`,自动区分独立显卡(NVIDIA/AMD)、核显(Intel UHD)与虚拟显示适配器(ToDesk / GameViewer 等),默认推荐并可一键锁定独显 ICD 传给 `reims-ctl --gpu <json>`。
|
||||
- **Alder Lake / 异构大小核 P-Core 绑核**:
|
||||
- 通过 `GetLogicalProcessorInformationEx(RelationProcessorCore)` 解析 `EfficiencyClass`,计算 P-Core 逻辑 CPU 亲和性掩码(如 i7-12700K 的 `0xFFFF`)。
|
||||
- VM 启动后,自动将对应 `qemu-system-x86_64.exe` 进程设置 `SetProcessAffinityMask` 到 P-Core(支持按 VM 开关)。
|
||||
## 3. 模块与目录职责
|
||||
|
||||
### 3.2 `internal/runtime` — 便携运行时管理
|
||||
- 维护 `<DataRoot>\runtimes\` 下的多版本便携运行时包:
|
||||
- **可选 CDN / 镜像端点 + 环境自动探测**:支持配置多下载端点(`GitHub 官方`、可选国内加速镜像或用户自定义镜像前缀)及「导入本地 `.tar.zst` 包」离线安装;拉取前对已启用端点并行发轻量 `HEAD` 探测(2 秒超时),按延迟自动择优,也允许用户在设置中手动锁定端点;
|
||||
- 校验 `manifest.json` 与 SHA256 后解压至 `<commit>.tmp` 再原子重命名,失败不破坏现有版本;
|
||||
- 统一构造子进程环境(`XDG_*`、`REIMS_CTL_QEMU`、`PATH`),彻底消除对用户全局环境变量与 C 盘的依赖;
|
||||
- **可承接上游未来官方发布**:运行时源采用清单化拉取协议,若上游 `steelbrain/reims-vgpu` 日后提供官方 Windows 预编译包,可直接切换源承接。
|
||||
| 路径 | 职责 |
|
||||
| :--- | :--- |
|
||||
| `main.go`、`console_*.go` | 统一入口:无参数启动 Wails GUI,带子命令进入 `internal/cli`;处理 GUI 子系统下的父控制台句柄接管 |
|
||||
| `internal/app` | Wails 绑定与桌面编排(启停、安装、快照、CoW 派生、磁盘扩容/回收、SSH、脱敏排障包、任务状态、运行监视) |
|
||||
| `internal/vmstart` | GUI 与 CLI 共用的启动前准备:提交内存预检、离线辅助盘、恢复模式引导、客体语言重放、WHPX 兼容处理、启动后 CPU 绑核 |
|
||||
| `internal/cli` | 命令行子命令实现、单实例参数解析与向界面进程交接 `vm start` |
|
||||
| `internal/host` | 宿主机体检与硬件调优:WHPX 检测与 UAC 启用、提交内存预检、Vulkan ICD 扫描、三层大小核拓扑与实时绑核、显示器 HiDPI 推荐、音频与磁盘总线探测、窗口置前、IME 文本钩子 |
|
||||
| `internal/runtime` | 便携运行时拉取(GitHub 主源 + GitCode 国内镜像回退)、原子解压、多版本切换与子进程环境变量构造 |
|
||||
| `internal/fetch` | 发布附件下载:HTTP `Range` 续传与按发布页 `SHA256SUMS.txt` 强制校验,运行时安装与应用内更新共用 |
|
||||
| `internal/selfupdate` | 应用内更新:把已校验的新版 `reims-go.exe` 换入运行中程序的位置、重新拉起与残留清理 |
|
||||
| `internal/installer` | 包装 `reims-util --json` 实现 macOS 离线安装包查询、宿主机直连下载、断点续传、互斥锁保护与缓存清理 |
|
||||
| `internal/driver/reims` | `reims-ctl` 与 `qemu-img` 受控子进程包装、输出解析、快照/派生/导入操作、日志与配置脱敏 |
|
||||
| `internal/qmp` | QMP 客户端:键盘键入、截屏与 Win10 冷重启监视 |
|
||||
| `internal/guesttools` | 本地回环鉴权 HTTP/WebDAV 服务:图文双向剪贴板、共享目录、Windows 盘符只读共享、防休眠开关与 `REIMSTOOLS` 辅助盘生成 |
|
||||
| `internal/opencore` | 改写 OpenCore 镜像中的 `prev-lang:kbd`,实现系统外预设 macOS 语言 |
|
||||
| `internal/netproxy` | 统一 HTTP Transport:优先环境变量代理,回退读取 Windows 系统代理配置 |
|
||||
| `internal/config`、`internal/i18n` | 应用配置持久化(`reims-go.json`)与 Go 端双语消息/结构化错误码 |
|
||||
| `internal/thumb`、`internal/tray`、`internal/version` | 4K 截屏行级缩放预览、Windows 系统托盘常驻、版本信息与新版本检查 |
|
||||
| `frontend/src` | 桌面界面:`components/`(页面与对话框)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
|
||||
| `patches/` | 上游临时补丁队列与 PR 跟踪,见 [`patches/README.md`](../patches/README.md) |
|
||||
| `scripts/` | 便携运行时打包、二进制裁剪与符号分离、MSYS2 源码归档、`alpha` 准入与冒烟脚本 |
|
||||
|
||||
### 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、零断流),直连受限时自动回退系统代理。
|
||||
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 时前置预警。
|
||||
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` → ③ 装完点击「弹出安装盘并恢复网络」。
|
||||
---
|
||||
|
||||
### 3.4 `internal/driver/reims` — `reims-ctl` 受控包装器
|
||||
- 包装 `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 实测**。
|
||||
- **配置写入只用 `set`**:`reims-ctl set` 的修改在**下次启动**时生效(`cli.rs:73`);改图形会在 VM 停止时重建 OpenCore 镜像(`cli.rs:242`)。可改字段见 `cli.rs:551-616`,外壳如何呈现见 [`shell-design.md`](shell-design.md)。
|
||||
## 4. 关键机制与安全边界
|
||||
|
||||
### 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` 提供命令执行通道。
|
||||
### 4.1 启动编排与单实例交接
|
||||
- `internal/vmstart` 承载 GUI 与 CLI 共用的启动步骤;只有常驻进程才能维持的能力(Guest Tools 桥接、Win10 冷重启监视)由界面进程托管。
|
||||
- CLI 执行 `vm start` 时,默认交由桌面进程启动:界面已在运行时通过 Wails 单实例锁(`WM_COPYDATA`)发消息不弹窗拉起;未运行时以 `--background` 启动隐藏到托盘的后台界面进程,结果经 `<DataRoot>\tmp\cli-start-*.json` 回传并带退出码返回。
|
||||
- 仅在 CLI 显式指定 `--data-root` 时由命令进程直接启动,此时不包含 Guest Tools 桥接与 Win10 冷重启监视。
|
||||
- `reims-go.exe` 编译为 Windows GUI 子系统程序,命令行模式下保留调用方管道/文件句柄,缺失时通过 `AttachConsole` 挂载父控制台;在交互式 PowerShell/cmd 中加 `| Out-Host` 可等待命令执行完毕。
|
||||
|
||||
## 4. 建议代码目录结构
|
||||
### 4.2 两条隔离的 QMP 通道
|
||||
- **短连接控制通道**:上游 `reims-ctl` 为每台 VM 创建 Winsock `AF_UNIX` 套接字 `qmp.sock`。由于 QEMU 单个 `-qmp` 同一时间只服务一个客户端,键入(`qmp.TypeIntoVM`)与截屏(`qmp.Screendump`)按 VM 串行复用短连接,键入期间暂停截屏。
|
||||
- **Win10 冷重启监视通道**:Windows 10 19045 缺少 `WHvResetPartition`,客体热重启会导致 WHPX 退出异常。在 Win10 宿主上,启动时附加 `-no-reboot` 并另开一条独立的 `AF_UNIX` QMP 通道监听重启退出事件,干净退出后自动重新拉起。使用 `AF_UNIX` 而非 TCP,避免客体经 SLIRP 的 `10.0.2.2` 访问宿主机监控接口。
|
||||
|
||||
```text
|
||||
reims-go/
|
||||
├── cmd/
|
||||
│ └── reims-go/ # 主入口(无参启动 Wails GUI,带子命令走 CLI 模式)
|
||||
├── internal/
|
||||
│ ├── config/ # reims-go.json(含 locale: zh-CN|en-US、DataRoot、P-Core 开关)
|
||||
│ ├── i18n/ # Go 端中英双语消息字典与结构化错误码
|
||||
│ ├── host/ # WHPX、提交内存预检、Vulkan ICD、P/E 核拓扑、进程亲和性(*_windows.go + *_other.go)
|
||||
│ ├── runtime/ # 便携运行时下载/导入、校验、解压、环境构造
|
||||
│ ├── installer/ # reims-util --json 离线安装包下载、断点续传、缓存管理
|
||||
│ ├── driver/
|
||||
│ │ └── reims/ # reims-ctl 子进程包装与 JSON/日志解析
|
||||
│ ├── qmp/ # 独立 QMP TCP 客户端
|
||||
│ └── vm/ # VM 编排、CoW 派生、向导状态机
|
||||
├── frontend/ # Wails 前端(轻量 React + Vite + TypeScript + zh-CN/en-US i18n)
|
||||
├── patches/ # 上游临时补丁队列(合入即退役)
|
||||
├── scripts/
|
||||
│ └── pack-runtime.ps1 # 从本地构建打包便携运行时(tar.zst + manifest)
|
||||
└── docs/
|
||||
```
|
||||
### 4.3 Guest Tools 与宿客安全边界
|
||||
- Guest Tools 服务仅监听 `127.0.0.1`,每台虚拟机分配独立的 256-bit 随机 Token(Bearer / Basic 鉴权)。
|
||||
- WebDAV 共享目录(`/dav/<vm>/`)严格校验路径防目录穿越;Windows 盘符只读共享(`/dav/<vm>/drives/<盘符>/`)默认全部关闭,服务端同时限制 HTTP 写方法与只读打开标志、校验持久化 Volume GUID 防盘符漂移、限制 `PROPFIND Depth` 并校验 Junction/符号链接解析目标仍在授权盘符内。
|
||||
|
||||
## 5. 与 `Reims-GUI-Win` 的核心差异
|
||||
### 4.4 宿主机体检与硬件调优
|
||||
- **免提权 WHPX 检测**:通过 `WinHvPlatform.dll`(`WHvGetCapability`)与系统功能查询判断状态,仅在缺失且用户确认时通过 `ShellExecuteW(..., "runas", ...)` 触发 UAC 启用。
|
||||
- **提交内存预检**:通过 `GlobalMemoryStatusEx` 检查可用提交内存(`AvailPageFile`),因为 QEMU 在 Windows 上会一次性提交整块客体内存;建机时推荐安全档位,启动前余量不足时提前拦截。
|
||||
- **GPU 与大小核**:扫描注册表 Vulkan ICD 并过滤虚拟显示适配器;解析 `GetLogicalProcessorInformationEx` 识别 P / E / LP-E 三层混合核心,支持按 VM 实时调整进程亲和性,避免超售卡顿。
|
||||
|
||||
> 本节关于 `Reims-GUI-Win` 的数据(Release 约 1.68 GB、PySide6 + PowerShell 7、双套 QEMU)没有附来源,按事实核验规则标为**待验证**。另外注意,上游 `reims-ctl` 自带一个终端界面,有创建和编辑表单(`crates/reims-ctl/src/tui.rs`、`form.rs`)。`reims-go` 的 GUI 要比它多出价值,而不是重做一遍,见 [`shell-design.md`](shell-design.md) 第 5 节。
|
||||
### 4.5 应用内更新
|
||||
- 界面启动后检查一次新版本,之后每 6 小时检查一次(后端缓存 10 分钟),只看 `vX.Y.Z` 正式版,忽略草稿与预发布。有新版本时侧栏顶部显示更新胶囊卡片,关于页提供同样的操作。
|
||||
- 下载作为 `app-update` 任务进行,落在 `<DataRoot>\downloads\app\`,支持取消后续传。发布页没有 `SHA256SUMS.txt`、或文件与其中记录不符时拒绝安装;安装前再次校验,防止下载后被改动。
|
||||
- 安装不依赖独立的更新程序:Windows 不允许覆盖运行中的 exe,但允许重命名,因此把运行中的程序改名为 `<exe>.old`,把新文件放到原路径(失败即回滚),再以 `--wait-pid=<旧进程 PID>` 拉起新程序后退出。新进程先等旧进程退出再占用单实例锁,启动后清理 `.old` 与下载文件。程序文件名若仍是发布时的带版本号名称(`reims-go-vX.Y.Z-windows-amd64.exe`),更新后改为新版本的名称;其他名称(如 `reims-go.exe`)保持不变,指向它的快捷方式继续有效。
|
||||
- 虚拟机是独立进程,更新期间继续运行;Guest Tools 桥接与输入法桥接在新界面启动后自动恢复。Win10 冷重启监视不会接回已在运行的虚拟机,这些虚拟机下次客体重启后需要手动启动,确认对话框会提示。
|
||||
- 开发构建(`wails dev`,`dev` 标签)与非 Windows 平台不支持应用内更新;程序所在目录不可写(如未提权的 `Program Files`)时提示改为手动更新。
|
||||
|
||||
| 维度 | `Reims-GUI-Win`(社区参考) | `reims-go`(本设计) |
|
||||
### 4.6 资源回收与内存约束
|
||||
- 按 VM 生命周期分配的状态(缩略图锁、Guest Tools 注册与 WebDAV handler、进程采样、绑核记录、文本队列与 worker)在删除 VM 或轮询发现外部删除时立即回收。
|
||||
- 日志监视器对单行无换行输出设 **64 KiB** 内存上限(原始日志文件完整保留);已结束任务在 10 分钟后从前后端状态中清理。
|
||||
- 4K 屏幕预览采用按行流式缩放降低单帧分配;手动复制截图仍保留全分辨率。不在热路径中人为调用 `debug.FreeOSMemory`。
|
||||
|
||||
---
|
||||
|
||||
## 5. 与上游 `reims-vgpu` 的边界
|
||||
|
||||
| 层次 | 归属 | 职责 |
|
||||
| :--- | :--- | :--- |
|
||||
| 外壳与体积 | Python + PySide6 + PowerShell 7 + 双套 QEMU(Release ~1.68 GB) | Go + Wails(WebView2 原生)+ 单套 `zstd` 便携运行时(实测运行时仅 `160.4 MB`) |
|
||||
| 上游耦合方式 | 手写 PowerShell 拼 QEMU 参数与 `fatsync` 改 OpenCore | 直接包装 `reims-ctl` / `reims-util`,上游升级只需替换运行时包 |
|
||||
| 装机下载体验 | 依赖 Recovery 在线下载或手工准备镜像 | GUI 内置 `reims-util --json` 离线包下载器(宿主机直连、断点续传、缓存复用) |
|
||||
| 硬件调优与防呆 | CPU 预设 + SMBIOS 伪装 | WHPX + 提交内存预检 + 过滤虚拟显卡锁定独显 ICD + 异构大小核 P-Core 绑核 |
|
||||
| 开发者能力 | 基础创建/启停,`taskkill` 强杀 | GUI + CLI 双模、串口日志流、CoW 派生、独立 QMP/SSH 自动化接口 |
|
||||
| **虚拟化引擎与内核** | 上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) | vGPU 设备、`metal2vulkan`、Guest Kexts、OpenCore 引导、QEMU WHPX 补丁、`reims-ctl` / `reims-util` 核心 CLI。底层缺陷以临时补丁记录并优先向上游提交 PR。 |
|
||||
| **桌面产品与便携分发** | 本仓库 `reims-go` | Windows 免编译便携运行时打包与 `alpha`→`stable` 通道筛选、数据目录隔离、硬件体检与自动调优、离线安装包管理器、桌面界面与命令行外壳、Guest Tools、恢复点与 CoW 工程工作流。 |
|
||||
|
||||
## 6. 与上游 `reims-vgpu` 的演进边界
|
||||
|
||||
| 层次 | 归属方 | 具体职责 |
|
||||
| :--- | :--- | :--- |
|
||||
| **引擎与内核层** | 上游 `steelbrain/reims-vgpu` | vGPU 设备、Metal2Vulkan、Guest Kexts、OpenCore/Ambrosia 引导、QEMU WHPX/KVM 补丁、`reims-ctl` / `reims-util` 核心 CLI。本仓发现的底层 Bug(如 Win10 WHPX 崩溃、Win10 `kernel-irqchip`)优先向上游提 PR。 |
|
||||
| **便携与产品工作台层** | 本仓库 `reims-go` | Windows 免编译便携运行时分发(`stable` 冒烟通道)、C 盘零污染隔离、WHPX/提交内存/GPU/P-Core 自动体检与调优、GUI 离线包断点续传下载器、对齐 macOS 的设置与向导、CoW 秒级派生与独立 QMP/SSH 工程工作流。 |
|
||||
> 关于面向第三方扩展的插件系统演进构想,另见草案 [`docs/plugin-architecture.md`](plugin-architecture.md)。
|
||||
@@ -0,0 +1,117 @@
|
||||
# 产品与界面设计规范(Design Guidelines)
|
||||
|
||||
> 本文定义 Reims-Go 桌面外壳的交互原语、配置模型、视觉规则与文案约束。设计令牌的具体数值以 [`frontend/src/styles/tokens.css`](../frontend/src/styles/tokens.css) 为准,本文只记录长期生效的设计原则。
|
||||
|
||||
---
|
||||
|
||||
## 1. 设计定位
|
||||
|
||||
Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台工艺**」:
|
||||
|
||||
- **结构与概念对齐 macOS**:配置分类与命名参考 Apple [Virtualization.framework](https://developer.apple.com/documentation/virtualization) 的 `VZVirtualMachineConfiguration`(平台、引导、CPU、内存、存储、网络、图形与显示器、音频、键盘与指针、串口);交互结构参考 macOS 人机界面规范(侧栏选实例、右侧看详情、分步新建向导、分页式设置面板)。
|
||||
- **渲染与系统行为对齐 Windows**:适配 Windows DirectWrite 字体渲染与多档 DPI 缩放(100% / 125% / 150%),窗口控件位于右上角,支持浅色、深色与跟随系统外观。
|
||||
- **宿主与客体边界清晰**:Windows 专有能力(WHPX 启用、处理器计划、Vulkan ICD、运行时通道与数据目录)集中在「内核」与「设置」页,不混入单台虚拟机的配置表单。
|
||||
|
||||
---
|
||||
|
||||
## 2. 配置原语
|
||||
|
||||
| 原语 | 规范 |
|
||||
| :--- | :--- |
|
||||
| **声明式配置** | 一台虚拟机对应一份声明式配置,界面只编辑配置项,不让用户直接拼 QEMU 命令行参数。 |
|
||||
| **先校验,后保存** | 保存前在 Go 端完成前置校验(CPU 核数、可用提交内存上限、Vulkan ICD 路径存在性、切换磁盘控制器前是否已弹出安装盘),非法值在提交前拦截。 |
|
||||
| **随时可编辑,标明生效时机** | 无论虚拟机运行与否,设置面板均可打开编辑;每项设置明确标注生效时机。运行中保存「下次启动生效」的修改时,详情页汇总待生效项并提供「重启以应用」。 |
|
||||
|
||||
**写入约束**:凡属于上游 `reims-ctl` 管理的配置项,一律通过 `reims-ctl set` 写入,不直接改写 `vm.toml`,确保上游校验与 OpenCore 重建逻辑照常生效。
|
||||
|
||||
---
|
||||
|
||||
## 3. 配置分类与生效时机
|
||||
|
||||
| 类别 | 界面配置项 | 生效时机 | 约束与说明 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **平台** | Mac 机型、序列号、MLB、UUID、ROM | 只读 | 界面仅展示是否已配置,不展示原始敏感值;日志与排障包一律脱敏 |
|
||||
| **引导** | 系统语言(`prev-lang:kbd`)、重建 OpenCore、恢复模式切换 | 停机时 / 下次启动 | 预设语言会在重建 OpenCore 与启动前自动重放 |
|
||||
| **系统来源** | Apple 离线安装包、本地安装器、导入 VMDK / RAW | 仅创建时 | 安装完成后引导弹出安装盘(`eject`)并恢复网络 |
|
||||
| **CPU** | 核心数、CPU 亲和性策略(自动/全部/性能核/避开低功耗核/自定义) | 核心数下次启动;亲和性立即生效 | 亲和性由 Reims-Go 在宿主机侧实时绑定 |
|
||||
| **内存** | 客体内存大小 | 下次启动 | 按宿主机可用提交内存推荐安全档位,启动前拦截超额配置 |
|
||||
| **存储** | 磁盘控制器(NVMe / VirtIO / SATA)、停机扩容、空间回收、恢复点 | 停机时 / 下次启动 | 切换控制器前须先弹出安装盘;扩容与空间回收仅在停机状态执行 |
|
||||
| **网络** | 网络开关、SSH 端口转发、MAC 地址 | 下次启动 | MAC 属于敏感字段,默认隐藏 |
|
||||
| **图形与显示器** | 显卡后端、显示器数量(1–4)、分辨率 / HiDPI / 全屏、宿主 GPU | 下次启动(改后端需停机) | GPU 列表自动过滤虚拟显示适配器;按主屏分辨率与 DPI 推荐清晰 HiDPI 档位 |
|
||||
| **音频** | 音频开关、音频后端 | 下次启动 | 展示宿主播放/录音设备可用状态 |
|
||||
| **键盘与指针** | 点击窗口捕获键鼠 | 下次启动 | 按实际图形后端展示准确的快捷键提示 |
|
||||
| **串口与日志** | 日志开关与级别 | 下次启动 | 原始输出与串口日志统一收在底部日志抽屉 |
|
||||
| **高级** | 关机等待时间、额外 QEMU 参数、环境变量 | 下次启动 | Reims-Go 内部注入参数与用户自定义 `--extra-args` 隔离合并,互不覆盖 |
|
||||
| **宿客协作** | Guest Tools 剪贴板、共享文件夹、Windows 盘符只读共享、防休眠 | 立即生效 | 仅本机回环鉴权;盘符共享默认全部关闭,系统盘展示隐私提示 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 虚拟机状态模型
|
||||
|
||||
在上游 `reims-ctl list --json` 的三种基础状态(`stopped`、`running`、`broken`)之上,补充 Reims-Go 发起操作时的过渡态:
|
||||
|
||||
| 显示状态 | 触发来源 | 页头主操作(每视图至多 1 个) | 允许的次要操作 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **正在创建** | 创建流程进行中 | 无(展示分步进度) | 取消创建 |
|
||||
| **已停止** | 上游 `stopped` | **启动** | 设置、恢复点、更多(派生副本、扩容/回收、打开目录、删除) |
|
||||
| **正在启动** | 发起 `start` 至 `running` | 启动中(忙碌态,禁用) | 设置、强制关机 |
|
||||
| **运行中** | 上游 `running` | **显示 VM 窗口** | 关机、截屏、设置、更多(重启、强制关机、发送文本、进入/退出恢复模式、导出排障包) |
|
||||
| **正在停止** | 发起 `stop` 至 `stopped` | 停止中(忙碌态,禁用) | 强制关机 |
|
||||
| **配置损坏** | 上游 `broken` | **查看问题** | 打开目录、删除 |
|
||||
|
||||
- 暂不提供暂停或运行中热快照状态(`paused` / `saving` / `restoring`),直到上游验证 `reims-vgpu` 显存与设备状态序列化。
|
||||
- 禁用按钮不占据主操作位置;状态变化时直接切换为当前最合适的主操作。
|
||||
|
||||
---
|
||||
|
||||
## 5. 布局与信息层级
|
||||
|
||||
### 5.1 窗口框架
|
||||
- **可折叠侧栏**(`Ctrl+B`):展示虚拟机列表(按 macOS 大版本显示图标,支持右键菜单与键盘上下选择)、新建入口(`+` / `Ctrl+N`)以及底部的「安装包」「内核」「设置」入口。
|
||||
- **主内容区**:虚拟机页的操作区位于详情页头而非全局顶栏,避免切换非 VM 页面时按钮跳动。页面遵循「视觉预览与名称 → 一行核心摘要与主操作 → 上下文提示(待生效修改/装机引导) → 连接与资源分组 → 折叠的技术信息 → 底部快捷键脚注」的自上而下层次。
|
||||
- **常驻状态栏 + 底部日志抽屉**:状态栏左侧显示活动任务进度(空载时显示宿主机内存、磁盘与运行中 VM 摘要),右侧显示错误计数徽标与日志抽屉开关(`Ctrl+L`)。
|
||||
|
||||
### 5.2 防堆叠约束
|
||||
- **每条事实只说一次**:同一项规格或状态不在一页内重复展示。
|
||||
- **每个操作只有一个出口**:同屏不重复摆放相同动作按钮;破坏性操作(删除、强制关机)仅出现在菜单与确认弹窗中。
|
||||
- **边框最多一层**:用分组容器或留白表达层级,二选一,禁止卡片套卡片。
|
||||
- **原生与自绘统一**:表单选择控件统一使用自绘弹出选择器(`PopupSelect`),避免混入风格割裂的系统原生 `<select>`。
|
||||
|
||||
---
|
||||
|
||||
## 6. 视觉、图标与无障碍基线
|
||||
|
||||
- **样式令牌化**:所有颜色、字号、间距(4 px 网格)、圆角与阴影统一引用 [`frontend/src/styles/tokens.css`](../frontend/src/styles/tokens.css) 中的 CSS 变量,禁止在组件内联写死颜色或字号。
|
||||
- **字体**:内嵌开源 Inter Variable 作为拉丁字体,并针对 Windows DirectWrite 特性显式映射中文字体字重,避免正文过细或中英混排断层。
|
||||
- **按钮层级**:每视图至多 1 个实底主按钮;常用操作用次按钮或图标按钮;破坏性操作仅用红字出现在菜单与确认框。
|
||||
- **纯图标按钮边界**:仅当图标含义通用(启动、停止、设置、更多、新建、复制、关闭、刷新、日志)且既非主操作也非破坏性操作时才允许纯图标;所有纯图标按钮必须具备悬停 Tooltip(含快捷键)、`aria-label` 与 ≥ 28×28 px 的点击热区。领域专有操作(如「弹出安装盘」「显示 VM 窗口」「重启以应用」)必须保留文字。
|
||||
- **键盘与缩放**:所有可交互项必须为原生 `<button>` 或带完整 ARIA 语义的 Radix 基件,提供 `:focus-visible` 焦点环;全局快捷键包括 `Ctrl+N`(新建)、`Ctrl+B`(折叠侧栏)、`Ctrl+,`(设置)、`Ctrl+L`(日志)。最小窗口尺寸 960×640,需在 100% / 125% / 150% DPI 下无文字截断。
|
||||
|
||||
---
|
||||
|
||||
## 7. 文案、人话化与反馈规则
|
||||
|
||||
### 7.1 内容人话化
|
||||
主视图只展示用户能直接理解的信息,上游原始字符串、路径与内部标识统一收进「技术信息」折叠区并提供一键复制:
|
||||
|
||||
| 原始值 | 主视图展示 | 原始值去向 |
|
||||
| :--- | :--- | :--- |
|
||||
| Vulkan ICD 完整路径 | 显卡名称(如「NVIDIA GeForce RTX 4070 Ti」) | 技术信息 |
|
||||
| `Skylake-Client-noTSX-IBRS` | 不在主视图展示 | 技术信息 |
|
||||
| `x86-64 macOS guest (q35 and OpenCore, WHPX)` | 本地化简述(如「macOS · Intel · WHPX 加速」) | 技术信息 |
|
||||
| `user (MAC configured), ssh on 127.0.0.1:2222` | 「NAT · SSH 2222」 | 技术信息 |
|
||||
| 环境变量或底层参数名(如 `REIMS_VGPU_LOG`) | 用效果命名标题,不把变量名放进标题 | 描述或技术信息 |
|
||||
| 内部错误原始文本 | 本地化的一句话说明 + 下一步建议 | 详情折叠区 / 日志 |
|
||||
|
||||
格式化逻辑统一集中在 [`frontend/src/lib/format.ts`](../frontend/src/lib/format.ts),不在组件中零散拼接。
|
||||
|
||||
### 7.2 文案风格
|
||||
- **克制直接**:标题用名词;按钮用 2–5 字动词;描述控制在清晰的一句话;不使用「请」「您」「成功」和感叹号;按钮和短提示末尾不加句号。
|
||||
- **不写内部引用**:面向用户的文案中严禁出现仓库路径、内部文档名、PR 编号或开发者术语。
|
||||
- **英文统一句首大写(Sentence case)**,避免每词首字母大写。
|
||||
- **去重复标题**:设置窗口标题只写实例名,分组标题与行标题不同名,不写自明标题(如「配置概览」)。
|
||||
|
||||
### 7.3 进度、日志与操作反馈
|
||||
- **进度归进度,日志归日志**:下载、建机、扩容等耗时任务统一通过结构化任务事件推送到状态栏;日志抽屉默认收起,**绝不因新日志到达而自动弹出**,仅在出错时通过 Toast 提醒并附「查看日志」入口。
|
||||
- **即时反馈**:每次点击操作立即进入忙碌态防重复触发;成功时给出简洁 Toast(「对象 + 结果」,如「macos-tahoe 已关机」),失败时说明原因与恢复动作。
|
||||
- **破坏性确认**:删除虚拟机等不可逆操作一律使用自定义确认对话框(含影响范围与「保留磁盘文件」选项),不使用浏览器原生 `window.confirm`。
|
||||
@@ -0,0 +1,446 @@
|
||||
# 插件系统架构(Plugin Architecture)
|
||||
|
||||
> 状态:**核心内核、内置扩展、主题引擎、Sidecar 托管与 CLI/GUI 管理已落地**;市场远端索引与 L2 脚本层按需迭代。
|
||||
> 关联文档:[`architecture.md`](architecture.md) · [`design-guidelines.md`](design-guidelines.md) · [`portable-runtime-spec.md`](portable-runtime-spec.md) · [`patches/README.md`](../patches/README.md)
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标、约束与非目标
|
||||
|
||||
### 1.1 目标插件类型
|
||||
|
||||
| 类型 | 典型形态 |
|
||||
| :--- | :--- |
|
||||
| **主题与美化** | 宿主**不提供主题包,只提供主题扩展接口**;接口须能承载多套配色、字体、部件级样式、状态驱动装饰与交互增强并存的复杂主题(以 DSH 主题 dsh-claude-style 为参照) |
|
||||
| **运行时** | 自定义构建或镜像源的 `reims-vgpu` 运行时、上游 QEMU/OVMF 等其他运行时种类 |
|
||||
| **非 macOS 虚拟机** | 以 Linux 虚拟机为代表的客体平台驱动,复用体检、内存预检、绑核、QMP、任务与托盘能力 |
|
||||
| **Hook 与自动化** | 体检、建机、启停前后的拦截与观察;自定义命令;排障采集器;宿主侧桥接与兼容补偿 |
|
||||
|
||||
### 1.2 硬约束
|
||||
|
||||
| 约束 | 要求 |
|
||||
| :--- | :--- |
|
||||
| **第三方代码不进主进程** | 除编译期内置扩展外,任何插件代码都不在 `reims-go.exe` 进程内执行;插件崩溃、死循环或内存失控不得拖垮主窗口与运行中的 VM |
|
||||
| **零外部运行时依赖** | 用户无需安装 Node.js / Bun / Python / MSYS2 即可使用任一官方插件层级 |
|
||||
| **数据目录隔离** | 插件包、私有数据、日志与第三方运行时全部位于 `<DataRoot>` 下 |
|
||||
| **许可证防火墙** | Apache-2.0 本体与 GPL/LGPL 组件只经独立子进程 + 协议通信协作,禁止静态链接或进程内耦合 |
|
||||
| **配置写入铁律** | 对 `reims-ctl` 管理的 VM,插件只能提交「意图」,由宿主统一经 `reims-ctl set` 落盘,严禁直改 `vm.toml` |
|
||||
| **人工确认红线** | UAC 提权、重启 Windows、macOS 图形安装向导等不提供任何插件权限,插件只能请求宿主弹出确认 |
|
||||
| **敏感字段零外泄** | 序列号、MLB、UUID、ROM、MAC 不进入任何插件可读的数据面;插件贡献的排障内容必经宿主脱敏 |
|
||||
| **GUI 与 CLI 同源** | 插件管理、驱动路由、Hook 管线位于 `internal/`,桌面与 `reims-go <subcommand>` 行为一致 |
|
||||
|
||||
### 1.3 非目标
|
||||
|
||||
- 不采用 Go 原生 `plugin` 包(不支持 Windows,且强耦合编译器与依赖版本),不进程内加载第三方 DLL。
|
||||
- 不把核心拆成「万物皆插件」的全动态微内核:体检、单实例托盘、Wails 窗口与 CLI 路由保持静态编译。
|
||||
- 不用插件、DLL 注入或 API Hook 替代上游引擎补丁(见 §5.5)。
|
||||
- 不发布官方主题插件包:除内置浅色/深色外不提供任何主题,但完整保留主题扩展接口(§5.1)。
|
||||
- 不托管、不分发任何 Apple 专有文件;插件市场拒收此类包。
|
||||
|
||||
---
|
||||
|
||||
## 2. 参考系统与取舍
|
||||
|
||||
| 维度 | Magpie(Go 宿主 + Bun 插件宿主) | DSH(Cordis「万物皆插件」) | Reims-Go 取舍 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| 内核 | 编译期内置插件注册表(`Requires/Provides/Apply/OnDispose`)+ 社区插件管理器,两者在扩展点交汇 | 极小 DI 内核,所有功能皆插件,依赖就绪自动激活、缺失级联卸载 | 取 Magpie 的**单注册表、两种来源**;取 DSH 的**可逆副作用**与依赖驱动激活;不做全动态微内核 |
|
||||
| 执行隔离 | 按能力分层:进程内 JS(µs 级热路径,无 I/O,严格时限)/ 共享 Bun 子进程 / 沙箱 iframe | 全部进程内同权限,`node:vm` 与同源 iframe 明确声明非安全边界 | Reims-Go **无微秒级热路径**,进程内脚本收益不足以抵消风险 → 所有插件代码进程外执行,且**每插件独立进程** |
|
||||
| 失败策略 | 每个扩展点显式 fail-open / fail-closed | 可选插件失败继续、必需清单失败退出;UI 单元格错误边界 | 扩展点契约中写明分发模式与失败策略 |
|
||||
| UI | `sandbox=allow-scripts` iframe + `connect-src 'none'` + bridge + 服务端二次校验 + 主题变量 | 类型化 Slot(声明即占有)+ 主题令牌 + SVG 校验;共享 React 实例随宿主升级易碎 | 声明式贡献由宿主原生渲染为主;iframe 面板为逃生舱;不共享前端依赖 |
|
||||
| 分发 | npm/git/本地 + 带 sha512 的兜底分发分支;远端索引 + 内嵌副本 | 事务安装(快照回滚、包名版本核对、下载前兼容预检)、安全模式恢复;无签名 | 事务安装 + 下载前预检 + SHA-256 + 签名分级 + 远端索引与内嵌兜底 |
|
||||
| 已知教训 | Windows 上包管理器并发写丢失;孤儿进程(需按进程树终止);`Origin: null` 绕过 CORS;空列表保存抹掉全部插件;嵌入引擎无内存上限 | 进程内插件一个未捕获异常拖垮宿主;整段配置替换难用 | 不引入包管理器;Job Object;严格 Origin 校验;状态文件「读失败即报错」;内存上限靠进程级限制 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 总体架构
|
||||
|
||||
### 3.1 一个注册表 + 分层执行
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Exe["reims-go.exe(可信核心)"]
|
||||
Reg["扩展点注册表\n依赖解析 · 可逆副作用 · Reconcile"]
|
||||
Builtin["内置扩展(编译期注册)\n核心:reims 驱动 · 默认主题 · 启动准备 · 兼容补偿\n可选:宿客桥接 · 剪贴板 · 输入服务 · 窗口安装引导 · reims-vgpu 运行时种类"]
|
||||
Mgr["插件管理器\n清单校验 · 事务安装 · 状态 · 安全模式"]
|
||||
Broker["Host API 代理\n权限校验 · 脱敏 · 限流 · 审计"]
|
||||
Sup["进程监管器\nJob Object · 重启退避 · 健康检查"]
|
||||
Asset["插件资源路由\nCSP · 路径校验 · Origin 校验"]
|
||||
end
|
||||
subgraph L1["L1 声明层(纯数据)"]
|
||||
D1["主题 · 图标 · 语言 · VM 模板 · 运行时源 · 规则 Hook"]
|
||||
end
|
||||
subgraph RT["运行时包(原生二进制)"]
|
||||
R1["仅由驱动以子进程调用"]
|
||||
end
|
||||
subgraph L2["L2 脚本宿主(预留)"]
|
||||
S1["reims-go 隐藏子命令进程\n内嵌 JS 引擎 · 进程级内存/CPU 上限"]
|
||||
end
|
||||
subgraph L3["L3 Sidecar(任意语言 exe)"]
|
||||
X1["Linux 驱动 · 代码 Hook · 命令 · 排障采集"]
|
||||
end
|
||||
subgraph L4["L4 UI"]
|
||||
U1["声明式贡献(原生渲染)· 沙箱 iframe 面板(后置)"]
|
||||
end
|
||||
Builtin --> Reg
|
||||
Mgr --> Reg
|
||||
L1 --> Mgr
|
||||
RT --> Mgr
|
||||
L2 & L3 <-->|"JSON-RPC 2.0 / stdio"| Sup --> Broker --> Reg
|
||||
L4 <-->|"bridge"| Asset --> Broker
|
||||
```
|
||||
|
||||
| 层 | 执行机制 | 隔离 | 宿主可强制的约束 | 典型插件 |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| **Builtin** | Go 代码,编译期注册到同一注册表 | 可信 | 全部 | reims 驱动、宿客桥接、兼容补偿、默认主题 |
|
||||
| **L1 声明层** | JSON + 静态资源,由宿主解析 | 无代码 | 全部(Schema 白名单) | 主题、图标、语言、VM 模板、运行时源、规则 Hook |
|
||||
| **运行时包** | 原生二进制,**只被驱动以子进程调用**,自身不注册扩展点 | 进程级 | 来源、哈希、签名 | `reims-vgpu` 变体、Linux 用 QEMU/OVMF |
|
||||
| **L2 脚本宿主(预留)** | 由 `reims-go.exe` 以隐藏子命令拉起的独立进程,内嵌纯 Go JS 引擎运行单文件脚本;无文件/网络能力,仅宿主注入的 API | 进程级 + 引擎沙箱 | 全部;Job Object 限制内存与 CPU | 轻量 Hook、体检规则、日志告警 |
|
||||
| **L3 Sidecar** | 独立 exe,每插件一个进程,双向 JSON-RPC 2.0 | 进程级;**OS 权限等同当前用户** | 仅 Host API 访问面 | Linux 驱动、代码 Hook、CLI 命令、排障采集 |
|
||||
| **L4 UI** | 声明式贡献由宿主原生组件渲染;复杂交互用沙箱 iframe | 强 | 全部 | 驱动专属表单、菜单项、状态卡片、自定义面板 |
|
||||
|
||||
**L2 的定位**:Hook 发生在秒级的 VM 生命周期上,没有 Magpie 那样的微秒级热路径,因此不把脚本引擎嵌入主进程。若出现「低信任 + 需要逻辑」的刚需,复用同一个 `reims-go.exe` 以隐藏子命令拉起脚本宿主进程:既不增加分发物、不要求用户装运行时,又获得进程级崩溃隔离与 Job Object 内存上限(纯 Go JS 引擎本身没有堆上限)。在此之前,L1 规则 Hook 与 L3 Sidecar 覆盖需求。
|
||||
|
||||
**多合一包**:一个插件可在 `contributes` 中同时声明多种能力,例如 Linux 插件同时提供 L3 驱动、运行时源、规则 Hook 与创建向导 Schema。
|
||||
|
||||
### 3.2 内置功能先插件化
|
||||
|
||||
扩展点先由内置功能使用一遍再对外开放。内置功能分两类,判断标准是用户关掉它之后,是「少了一项功能」还是「已有功能坏掉」:
|
||||
|
||||
- **核心** `builtin.core`:Reims-Go 离开它就无法运行 macOS 虚拟机的部分,包括 reims 驱动(驱动 id 仍为 `builtin.driver.reims-macos`)、默认主题(主题 id 仍为 `builtin.theme.default`)、启动准备(离线辅助盘、恢复模式引导切换、引导语言重放)与宿主兼容补偿(WHPX 降级、Win10 冷重启)。它是**系统插件**:始终启用,不能停用或卸载,插件页显示为一行「始终启用」,不参与「使用中」检查。两项兼容补偿作为核心的应用级设置保留开关,仅供排障。启动准备在同一个 `vm.beforeStart` 处理器里按固定顺序执行,引导语言重放必须在恢复模式切换(可能重建 OpenCore)之后。
|
||||
- **可选内置扩展**:Guest Tools 传输服务、剪贴板互通、宿主输入服务、虚拟机窗口安装引导。经同一注册表注册、可独立启停、停用后零残留,停用即真正停止(不被其他调用方重新拉起)。首批示例为默认开启的剪贴板互通(见 §5.4)。
|
||||
|
||||
核心由曾经拆开的七个内置插件合并而来(`builtin.RetiredIDs`)。启动时删除 `state.json` 中这些旧 ID 的记录,关闭过的兼容补偿转为对应的核心设置;启动 VM 时,参数归属账本中旧 ID 名下的片段移交给核心,继续沿用而不是被当作已卸载插件的残留剥离。
|
||||
|
||||
---
|
||||
|
||||
## 4. 内核机制
|
||||
|
||||
### 4.1 注册表与可逆副作用
|
||||
|
||||
- 每个已启用插件(含内置)拥有一个作用域,所有注册行为(提供服务、贡献扩展点、订阅事件、后台服务、Win32 钩子、QMP 监视)都登记一个释放函数;停用、卸载或升级时**逆序释放**,激活中途失败则回滚已登记项。
|
||||
- 插件声明 `requires` / `provides`(服务名 + 版本范围)。Reconcile 先关后开:先释放不再需要的插件及依赖其服务的插件,再按依赖求不动点激活。状态为 `off / pending / active / degraded / failed`。
|
||||
- **使用中不可移除**:仍有 VM 归属的驱动、仍被 VM 使用的运行时,不可停用或卸载;使用情况查询失败按「使用中」处理。
|
||||
- 内置扩展通过 `pluginApi` 版本做兼容检查;激活 panic 转为 `failed` 并回滚。
|
||||
|
||||
### 4.2 扩展点目录
|
||||
|
||||
| 扩展点 | 来源层 | 基数 | 失败策略 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `themes`(令牌、配色方案、字体、图标、背景、提示音、样式表、状态装饰) | Builtin · L1 | 按 id,同一时刻仅一个主题包生效 | 回退内置默认主题 |
|
||||
| `uiScripts`(交互主题脚本) | 主窗口受信任脚本 | 随所属主题包 | 单个功能出错只停用该功能;整体失败回退到无脚本的主题 |
|
||||
| `locales`(多语种语言包:`locale` / `label` / `fallback` / `file` / `backendFile` / `messages` / `backend`) | Builtin · L1(纯 JSON,免高危权限) | 按 BCP-47 语种合并,自动出现在设置语言下拉框 | 缺失词条回退 `fallback` / 内置英语;停用插件后自动回退内置语言 |
|
||||
| `inputFilters` | Builtin · L1(仅声明式规则) | 有序列表 | 规则非法即忽略;宿主输入服务异常时卸载钩子、放行原始输入 |
|
||||
| `vmTemplates` | Builtin · L1 | 列表 | 跳过非法项 |
|
||||
| `runtimeSources` | Builtin · L1 | 列表 | 跳过该源,回退其他源 |
|
||||
| `runtimeKinds` / `runtimes` | Builtin · 运行时包 | 按种类 | 不激活,相关 VM 提示运行时不可用 |
|
||||
| `guestDrivers` | Builtin · L3 | 按 id | 该驱动的 VM 标记「驱动不可用」,其他 VM 不受影响 |
|
||||
| `hooks` | Builtin · L1 · L2 · L3 | 有序列表 | 按事件模式(§4.3) |
|
||||
| `commands` | Builtin · L2 · L3 | 按 id | 报错并提示 |
|
||||
| `menus` / `vmCards` / `settingsPages` / `statusItems` | 声明式 | 列表,设数量上限 | 隐藏该项 |
|
||||
| `panels` | L4 iframe | 限定槽位 | 错误占位 + 重试 |
|
||||
| `diagnostics` | Builtin · L3 | 列表 | 跳过;输出强制脱敏 |
|
||||
|
||||
UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`、`settings.plugin`,后续按真实需求再增加 `sidebar.footer`、`statusbar.right`、`create.source`;插件只能向已声明槽位贡献。
|
||||
|
||||
### 4.3 Hook 事件与分发模式
|
||||
|
||||
分发模式与失败策略是事件契约的一部分:
|
||||
|
||||
| 事件 | 触发位置 | 模式 | 时限 | 失败策略 |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| `host.preflight` | 体检完成后 | 收集:追加优化建议/警告 | 500 ms | 丢弃该插件结果 |
|
||||
| `vm.beforeCreate` | 校验通过后、创建前 | 拦截:校验错误或默认值补丁 | 2 s | 补丁丢弃、放行 |
|
||||
| `vm.afterCreate` | 创建成功后 | 观察 | 异步 30 s | 只记录 |
|
||||
| `vm.beforeStart` | 启动准备阶段 | 拦截:返回启动意图(§4.4) | 每插件 2 s,链路 10 s | 意图丢弃、放行;仅声明 `blocking` 且用户启用的守卫可阻断 |
|
||||
| `vm.afterStart` | 拿到 PID / QMP / SSH 端口后 | 观察:注册后台监视、通知 | 异步 | 只记录 |
|
||||
| `vm.beforeStop` / `vm.afterStop` / `vm.deleted` | 关机/删除前后 | 观察 | 异步 | 只记录 |
|
||||
| `log.onLine` | VM 日志行进入监视器 | 观察:里程碑、告警、修复建议 | 批量投递,超时丢弃 | 背压时丢弃,绝不阻塞日志 |
|
||||
| `command.invoke` | 菜单点击或 CLI 调用 | 请求/响应 | 30 s | 报错 |
|
||||
|
||||
同一事件的处理器按「内置 → 用户排序」执行;连续超时或异常达阈值的插件自动降级为 `degraded` 并在插件页提示原因,不阻断 VM 启停。
|
||||
|
||||
### 4.4 启动意图与参数归属账本
|
||||
|
||||
`vm.beforeStart` 处理器不能直接调用 `reims-ctl`,只能返回启动意图:
|
||||
|
||||
| 意图项 | 约束 |
|
||||
| :--- | :--- |
|
||||
| QEMU 参数片段 | 带归属(插件 id);只允许宿主白名单内的选项族;同一选项多方设置时按优先级取一并告警 |
|
||||
| 子进程环境变量 | 仅限插件命名空间前缀,或宿主白名单变量 |
|
||||
| 前置检查 | 人话化的警告或阻断理由 |
|
||||
| 启动后动作 | 由宿主执行的受控动作(打开端口转发、注册监视等) |
|
||||
|
||||
宿主合并所有意图后,对 `reims-ctl` 管理的 VM **一次**经 `reims-ctl set --extra-args` 写入,并在 VM 目录维护**参数归属账本**,记录每个片段的归属。插件停用或卸载时按账本精确剥离其片段;现有按功能各写一对合并/剥离函数的做法(离线辅助盘、Guest Tools、`kernel-irqchip=off`、Win10 冷重启 QMP 通道)统一迁到账本之上。用户在「高级」中手写的 `--extra-args` 不属于任何插件,永不被自动剥离。
|
||||
|
||||
---
|
||||
|
||||
## 5. 四类插件专项设计
|
||||
|
||||
### 5.1 主题与美化(宿主只提供接口)
|
||||
|
||||
除内置浅色/深色外,Reims-Go 不发布主题包,但主题扩展接口按能承载 dsh-claude-style 级复杂主题设计。该主题在 DSH 上的实践表明:宿主没有稳定契约时,主题只能依附带哈希的类名、自建页面观察总线与帧管线、按结构写覆盖层,宿主改版即失效,样式匹配性能也受拖累。Reims-Go 由宿主主动提供这些契约。
|
||||
|
||||
**UI 契约(`uiApi`,随 `pluginApi` 版本化,由前端构建生成 `ui-contract.json` 供主题作者校验)**
|
||||
|
||||
| 契约 | 内容 |
|
||||
| :--- | :--- |
|
||||
| 设计令牌 | 单一来源(令牌数据同时生成 CSS 变量与前端常量),覆盖颜色、字体排印、形状、阴影、动效时长与缓动、层级;动效档位(含系统「减少动态效果」)在一处解析为文档属性,样式与脚本读同一个值 |
|
||||
| 部件 | 关键区域与控件挂稳定的部件类名(如 `rg-p-sidebar`、`rg-p-vm-header`、`rg-p-statusbar`),每个部件一个独立类名,便于浏览器按类名分桶匹配;主题选择器只允许使用部件、状态属性与令牌,不得依赖内部类名或界面文字 |
|
||||
| 状态属性 | 文档与区域上的只读状态:外观、当前视图、VM 显示状态、忙碌态、是否有错误、侧栏折叠 |
|
||||
| 槽位锚点 | 装饰与扩展内容的挂载点(如侧栏底部、VM 预览四角、状态栏、空状态区) |
|
||||
|
||||
契约内的部件、状态属性与令牌的重命名或删除属于 `uiApi` 主版本变更;前端构建检查契约中的每个部件仍由某个组件输出。
|
||||
|
||||
**三档主题能力**
|
||||
|
||||
| 档位 | 能力 | 层级与信任 | 对应复杂主题的典型需求 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **令牌主题** | 配色方案集合:少量种子色 + 声明式派生规则(按浅/深外观对种子做亮度、色度、透明度偏移)生成整套表面/文字/边框色阶;用户在宿主提供的编辑器中改种子、新建/复制/重命名/删除方案。字体(包内字体或用户字体目录)、图标与品牌标记替换、背景、按事件配置的提示音 | L1,宿主校验 | 多套配色预设与方案管理、自带字体、品牌标记、提示音 |
|
||||
| **样式主题** | 面向部件契约的样式表(宿主以 `@layer` 固定层叠顺序:基础 → 主题 → 用户);声明式状态装饰(按状态表达式切换精灵图/动画帧,锚定槽位,如随 VM 启停与任务进度变化的吉祥物) | L1,宿主校验与清洗 | 窗框/侧栏/排印样式、状态动画吉祥物 |
|
||||
| **交互主题** | 主窗口内运行的受信任 UI 脚本,只经宿主 UI SDK 工作 | 高信任(`ui:script`) | 滚动、折叠、悬停预览等交互增强 |
|
||||
|
||||
**UI SDK**(交互主题的唯一受支持接口):
|
||||
|
||||
- 生命周期:主题脚本导出装载函数,所有订阅、计时器与挂载都登记释放函数;切换或停用主题时逆序拆除,单个功能抛错不影响其余功能。
|
||||
- 只读状态订阅:非敏感的 VM 摘要、任务进度、当前视图、外观;不提供原始路径与敏感字段。
|
||||
- 宿主提供的页面观察总线、帧读写管线与按部件查询:主题不自建节点观察者,也不整页查询文档。
|
||||
- 槽位挂载:框架无关的 DOM 挂载,不共享宿主的 React 实例,避免随宿主依赖升级断裂。
|
||||
- 受限动作:仅开放非破坏性界面动作(折叠侧栏、打开设置、前置 VM 窗口等);启停、删除、配置写入不在 SDK 中。
|
||||
- 主题设置:由 `settings` Schema 定义,宿主渲染设置页。
|
||||
|
||||
**边界**:
|
||||
|
||||
- 主窗口同一 JS 环境内的脚本不是安全边界(可操作 DOM),交互主题按高信任处理:需 `ui:script` 权限与显式确认,`community` 级默认不可启用;宿主在加载主题脚本前收起 Wails 绑定的全局对象,SDK 是唯一受支持的接口。
|
||||
- 样式清洗:禁止外部 `url()` 与远程 `@import`,资源只能引用包内清单中的文件;窗口拖拽区、焦点环与最小点击热区等可用性属性由宿主在更高层保留,不被主题覆盖。
|
||||
- 同一时刻只启用一个主题包,切换时先停用旧主题再装载新主题;安全模式一律回到内置主题。
|
||||
- 首帧前按当前主题内联令牌防闪烁;无边框窗口的标题栏由前端绘制,可随主题变化。
|
||||
- 主题只改视觉与交互呈现,不改文案、信息层级与操作入口([`design-guidelines.md`](design-guidelines.md) 的主操作与破坏性操作约束由宿主守住)。
|
||||
- 需要读写用户文件或常驻服务的主题,以同包 L3 Sidecar 实现。
|
||||
- 开发支持:`reims-go plugin link` 链接本地目录并热重载;`reims-go plugin doctor` 校验样式只使用契约内的部件、状态属性与令牌。
|
||||
|
||||
### 5.2 运行时(运行时种类 + 运行时包)
|
||||
|
||||
- `internal/runtime` 从单一 `reims-vgpu` 泛化为**运行时种类注册表**:内置 `reims-vgpu` 种类;插件可提供新种类(如上游 QEMU + OVMF)或同种类的社区构建。
|
||||
- 运行时 `manifest.json` 在 schema 2 基础上增加:`kind`;`runtime_api`(驱动依赖的命令行契约版本,含 `reims-ctl` 子命令集与输出格式);`capabilities`(补丁与特性标识,替代按补丁名子串判断)。
|
||||
- 驱动声明所需运行时种类与 `runtime_api` 范围;不兼容时禁止启动并给出人话提示。
|
||||
- 存量布局 `runtimes/<commit>/` 保持不变,视为 `reims-vgpu` 种类;新种类安装到 `runtimes/<kind>/<version>/`,避免迁移存量数据。
|
||||
- 复用现有下载、续传、`SHA256SUMS.txt` 强校验、原子解压与多版本切换;第三方运行时不进入官方 `stable` 通道,安装前展示来源、许可证与补丁清单,并要求提供对应源码包(GPL 义务由分发者承担,市场审核把关)。
|
||||
|
||||
### 5.3 非 macOS 虚拟机(客体驱动,L3)
|
||||
|
||||
**驱动抽象**:当前 `internal/app`、`internal/vmstart`、`internal/cli` 直接依赖 `internal/driver/reims` 的具体类型。抽象后:
|
||||
|
||||
| 层 | 内容 |
|
||||
| :--- | :--- |
|
||||
| 通用 VM 模型 | 驱动 id + 名称、状态(`stopped / running / broken` 与过渡态)、CPU / 内存 / 磁盘摘要、目录、能力位 |
|
||||
| 驱动专有数据 | 不透明扩展字段 + 驱动提供的创建/设置 JSON Schema(宿主原生渲染,标注生效时机) |
|
||||
| 能力位 | `snapshot`、`cow_clone`、`resize`、`qmp`、`ssh`、`guest_tools`、`affinity`、`opencore`、`recovery`、`cloud_init`、`uefi_iso` 等;UI 与 CLI 按能力位显隐操作 |
|
||||
| 驱动动作 | `List / Show / ValidateCreate / Create / ValidateSet / Set / Start / Stop / Delete`,可选快照、派生、扩容与通用 `InvokeAction` |
|
||||
|
||||
- **VM 归属**:VM 目录内标记文件记录驱动 id;无标记的存量 VM 自动归属 `builtin.driver.reims-macos`,零迁移。CLI 增加 `vm create --driver <id>`,其余 `vm` 子命令按归属自动路由。
|
||||
- **宿主共享服务**(驱动经反向调用复用):体检报告、提交内存预检、大小核绑核、QMP 截屏与键入、缩略图、Guest Tools 注册、进程退出监视、任务进度、日志通道、托盘菜单。
|
||||
- **VM 进程归宿主托管**:驱动不直接派生 QEMU,而是请求宿主代为启动并返回 PID。这样 VM 进程不随驱动进程的 Job Object 被回收(驱动崩溃或重启不误杀 VM),绑核、退出监视与冷重启补偿也只在宿主实现一份。
|
||||
- **配置写入**:`reims-ctl set` 铁律约束 reims 管理的 VM;Linux 驱动自管配置文件,同样不允许 UI 拼接原始命令行。
|
||||
- **Linux 驱动的自身难点**:WHPX 直接启动与 Win10 冷重启补偿复用;显示路径(QEMU 窗口或 virtio-gpu,3D 加速**待验证**);cloud-init seed 生成;发行版镜像下载与校验;客体代理(qemu-guest-agent 或 Guest Tools Linux 版)。上游 `reims-ctl` 是否支持非 macOS 客体**待验证**;若将来支持,Linux 驱动可退化为其薄封装。
|
||||
- 官方 Linux 驱动作为独立仓库的一方插件交付,用于验证驱动抽象;主程序不为它写特例代码。
|
||||
|
||||
### 5.4 Hook 与自动化
|
||||
|
||||
- **L1 规则 Hook**:条件 + 动作的声明式规则,条件只能引用宿主定义的事实(Windows 版本、GPU、驱动、能力位、运行时能力),动作只能产出 §4.4 的意图或受控动作,不图灵完备。覆盖「某宿主条件下追加参数」「启动后打开 SSH 终端」等大多数场景。
|
||||
- **L3 代码 Hook**:Sidecar 订阅事件,经同一意图通道生效;`log.onLine` 以批量形式投递。
|
||||
- **L2 脚本 Hook**:预留,启用条件见 §3.1。
|
||||
|
||||
#### 首批示例插件
|
||||
|
||||
| 示例 | 形态 | 默认 | 演示的机制 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **剪贴板互通** `builtin.bridge.clipboard` | 内置 Go 扩展 | 开启 | 服务依赖(依赖 Guest Tools 传输服务)、运行中启停与完整拆除、按 VM 设置立即生效、宿主与客体的功能协商、隐私(内容不入日志) |
|
||||
|
||||
**剪贴板互通**
|
||||
|
||||
- 拆分 Guest Tools:回环 HTTP 鉴权、客体代理、`REIMSTOOLS` 辅助盘与 VM 注册作为内置「Guest Tools 传输服务」,对外提供路由注册与客体功能协商;剪贴板、共享文件夹、盘符只读共享、防休眠与文本输入是其上的功能扩展,剪贴板第一个迁出。
|
||||
- 激活时向传输服务注册剪贴板路由并启动宿主剪贴板监视,停用时二者随作用域释放;客体代理从配置接口得知功能关闭后停止轮询,旧版代理请求已关闭的路由时得到明确的「功能关闭」应答并退避。
|
||||
- 设置:全局开关 + 按 VM 覆盖;方向(双向 / 仅宿主到客体 / 仅客体到宿主);是否同步图片与大小上限;均立即生效。
|
||||
- `vm.card` 显示连接状态;排障包只记录次数与错误,不记录剪贴板内容。
|
||||
|
||||
#### 其余内置扩展(由现有模块迁入)
|
||||
|
||||
| 内置扩展 | 对应现有模块 | 使用的扩展点 |
|
||||
| :--- | :--- | :--- |
|
||||
| `builtin.bridge.guest-tools` | `internal/guesttools`、`guesttools_flow.go` | 提供传输服务 + `vm.beforeStart`(注入桥接参数与环境变量)+ `vm.afterStart` + `vm.card`;共享文件夹、盘符共享、防休眠逐步拆为功能扩展 |
|
||||
| `builtin.input` | `host/ime_hook_windows.go` | 提供输入服务与 `inputFilters`;IME 桥成为其上的功能,停用时卸载钩子线程 |
|
||||
| `builtin.install-guide` | `internal/installguide`、`internal/app/install_guide.go` | 提供 `ui.install-guide` 服务 + `vm.afterStop` / `vm.deleted` 观察钩子;在虚拟机窗口悬浮展示安装与恢复引导,停用时立即关闭全部浮层并回退主界面恢复卡片 |
|
||||
| `builtin.core`(系统插件) | `driver/reims_adapter.go`、`vmstart.Prepare` 各步骤、`app.go` 冷重启监视 | `guestDrivers` + `themes` + `host.preflight` + 一个按序执行全部启动准备的 `vm.beforeStart`(离线辅助盘 → 恢复模式引导 → 引导语言 → WHPX 降级 → Win10 冷重启)+ `vm.afterStart` / `vm.afterStop`(冷重启监视);设置 `whpx_fallback`、`win10_cold_reboot` |
|
||||
|
||||
### 5.5 与上游补丁队列的边界
|
||||
|
||||
| 类别 | 归属 | 原则 |
|
||||
| :--- | :--- | :--- |
|
||||
| 引擎内部崩溃与 Hypervisor 层修复(WHPX 兼容、协程、构建锁文件等) | [`patches/`](../patches/)(编译期) | 外部插件无法等价替代;坚持上游 PR,合入即退役 |
|
||||
| 窗口内部消息循环拦截(如 SDL 窗口内字符消息) | `patches/`,宿主侧做部分补偿 | 跨进程拦截需 DLL 注入,杀软误报风险高,不做成插件 |
|
||||
| 宿主侧绕过、兜底补偿与宿客桥接 | 内置扩展(§5.4) | 运行时缺少对应补丁时平滑降级;依据运行时 `capabilities` 判断 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 插件包与清单
|
||||
|
||||
### 6.1 包格式与目录
|
||||
|
||||
- 插件包为 zip 归档,根目录含 `plugin.json`、`SHA256SUMS` 与可选签名(ed25519,签名覆盖 `SHA256SUMS`)。
|
||||
|
||||
| 路径(位于 `<DataRoot>/plugins/`) | 用途 |
|
||||
| :--- | :--- |
|
||||
| `state.json` | 启用状态、版本钉选、已批准权限快照、冲突偏好;写入用临时文件 + rename + `.bak`;**读取失败即报错,绝不视为空表** |
|
||||
| `pkgs/<id>/<version>/` | 解压后的只读包体,多版本并存,回滚即切换 |
|
||||
| `data/<id>/` | 插件私有可写目录,同时是 Sidecar 的工作目录 |
|
||||
| `logs/<id>.log` | 插件 stderr 与宿主审计记录,限额轮转 |
|
||||
| `index-cache.json` | 市场索引缓存(另有内嵌兜底副本) |
|
||||
|
||||
### 6.2 清单字段(`plugin.json`)
|
||||
|
||||
| 字段 | 说明 |
|
||||
| :--- | :--- |
|
||||
| `schema` | 清单格式版本 |
|
||||
| `id` / `version` | 反向域名 id;SemVer |
|
||||
| `name` / `description` | `zh-CN` / `en-US` 本地化文本,**无需执行插件代码即可读取** |
|
||||
| `publisher` / `license` / `homepage` | 来源与许可,市场审核依据 |
|
||||
| `engines` | `reims-go` 版本范围与 `pluginApi` 范围,**下载前预检** |
|
||||
| `platforms` | 如 `windows-x64` |
|
||||
| `entry` | Sidecar 可执行文件、脚本文件、面板 HTML 根目录;层级由内容推导,不信任自报 |
|
||||
| `contributes` | 各扩展点贡献(§4.2) |
|
||||
| `requires` / `provides` | 服务与运行时依赖、提供的服务 |
|
||||
| `permissions` | Host API 能力(§7.1) |
|
||||
| `activation` | `onStartup` / `onVMEvent` / `onCommand` / `onPanel`,默认惰性激活 |
|
||||
| `settings` | JSON Schema;扩展标注 `x-secret`(不回显、不进日志)、`x-effect`(立即生效 / 下次启动生效)与 `x-scope`(`app` 全局 / `vm` 按虚拟机,后者渲染在 VM 设置对应分组) |
|
||||
| `defaultEnabled` | 安装或首次启动时的默认启用状态;仅内置扩展与随主程序附带的插件可为 `true` |
|
||||
| `provenance` | **运行时包必填**:上游仓库与 commit、补丁清单与哈希、源码包文件名 |
|
||||
|
||||
---
|
||||
|
||||
## 7. 权限、信任与安全边界
|
||||
|
||||
### 7.1 权限分级
|
||||
|
||||
| 等级 | 权限 | 审批 |
|
||||
| :--- | :--- | :--- |
|
||||
| **低** | `vm:read`(通用模型,不含敏感字段)、`ui:notify`、`task:progress`、`fs:plugin_data`、`log:read` | 启用时展示说明 |
|
||||
| **中** | `vm:intent`、`runtime:source`、`net:<origin>`(经宿主代理发出)、`ui:slot`、`input:filter`(声明输入过滤规则) | 首次启用逐项确认 |
|
||||
| **高** | `driver:vm`、`runtime:provider`、`process:spawn`、`vm:control`、`qmp:write`、`fs:vm_dir`、`fs:shared`、`host:clipboard`、`ui:script` | 强提示(展示可执行文件或脚本路径、SHA-256、发布者、许可证)并显式勾选;升级新增高危权限时暂停并要求重新批准 |
|
||||
| **不存在** | 敏感字段读取、UAC 提权、重启 Windows、直写 `vm.toml` | 插件只能请求宿主发起人工确认流程 |
|
||||
|
||||
### 7.2 如实声明的信任边界
|
||||
|
||||
- L1、L2、L4 的权限由宿主强制。**L3 是原生代码,OS 层面无法约束**,权限只约束其对 Host API 的访问;安装与启用 L3 插件时明确告知「此插件能以你的账户身份执行任意操作」。
|
||||
- 信任等级:`official`(官方密钥签名)、`verified`(审核 + 发布者签名)、`community`(仅哈希)、`dev`(本地链接,需开启开发者模式)。`community` 级 L3 插件默认不可启用,需二次确认。
|
||||
- 以 AppContainer 或低完整性级别运行 Sidecar 作为后续增强项评估。
|
||||
|
||||
### 7.3 UI 与本地接口安全
|
||||
|
||||
- 插件资源经 Wails AssetServer 的独立路由提供,路径带每次运行随机生成的令牌,校验目录穿越,附 `X-Content-Type-Options: nosniff` 与 CSP;SVG 一律禁脚本。
|
||||
- iframe 面板(后置):`sandbox="allow-scripts"`、`connect-src 'none'`;bridge 只应答来源窗口为自身 iframe 的消息,所有读取在 Go 侧按 `permissions` 二次校验并限流;主题令牌经 bridge 下发。
|
||||
- 宿主本地 HTTP 接口(如 Guest Tools)拒绝 `Origin: null`、跨站请求与 `Sec-Fetch-Dest: iframe` 请求,防止被沙箱 iframe 或外部网页借道调用。
|
||||
|
||||
---
|
||||
|
||||
## 8. 进程监管与通信协议
|
||||
|
||||
- **协议**:stdin/stdout 双向 JSON-RPC 2.0,采用 `Content-Length` 分帧(LSP 风格);握手交换 `pluginApi` 版本与能力;stdout 只走协议帧,日志一律走 stderr 并由宿主采集。截图、磁盘镜像等大对象不进 JSON,经插件数据目录内的文件路径传递。
|
||||
- **进程模型**:每个 L3 插件独立进程;全部放入设置 `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` 的 Job Object,宿主退出或崩溃时进程树一并回收;L2 脚本宿主额外设置进程内存与 CPU 时间上限。
|
||||
- **健壮性**:单写协程 + 有界队列提供背压;所有请求可取消;回收依据进程句柄而非管道 EOF;子进程不继承协议管道,工作目录固定为 `data/<id>/`;崩溃后指数退避重启,连续失败熔断为 `failed`;升级与配置变更采用「先起新进程、旧进程处理完在途请求再退出」。
|
||||
- **惰性与回收**:按 `activation` 惰性拉起;空闲超时回收;托盘常驻模式下只保留有活动 VM 或后台服务的 Sidecar。
|
||||
- **GUI / CLI**:插件宿主位于核心包。需要常驻进程的能力(Sidecar、后台服务)由界面进程托管,与 Guest Tools 一致;CLI 经现有单实例交接走界面进程,`--data-root` 直连模式按需临时拉起所需 Sidecar,命令结束即回收。
|
||||
|
||||
### 8.1 资源预算(零外部插件零开销)
|
||||
|
||||
未安装任何外部插件时,插件系统不得明显增加占用。以引入插件系统前的版本为基线,在同一宿主上对比:
|
||||
|
||||
| 指标 | 预算 |
|
||||
| :--- | :--- |
|
||||
| 常驻内存(空闲、托盘常驻) | 增加 ≤ 3 MB |
|
||||
| 冷启动到主窗口可交互 | 增加 ≤ 20 ms |
|
||||
| 常驻进程、后台轮询与全局输入钩子 | 不新增 |
|
||||
| `reims-go.exe` 体积 | 增加 ≤ 1.5 MB |
|
||||
| 前端主包 | 插件管理页与 Schema 表单渲染器按需加载,不计入主包 |
|
||||
| VM 启动前的 `reims-ctl set` 调用 | 不多于改造前(意图合并后至多一次) |
|
||||
|
||||
保障预算的实现纪律:
|
||||
|
||||
- 事件只在有订阅者时分发,无订阅者时不构造事件对象(尤其是 `log.onLine`)。
|
||||
- 不引入状态轮询:Reconcile 只由安装、启停、设置变更触发;文件监视仅在开发者模式的本地链接上启用。
|
||||
- 不预热:Sidecar、脚本宿主、iframe 面板与市场索引均在首次使用时创建或拉取。
|
||||
- 只使用内置主题时不注入额外样式,UI SDK 仅在启用交互主题时加载。
|
||||
- 体积较大的依赖(如嵌入式 JS 引擎)不默认编入主程序,引入前单独评估体积代价。
|
||||
|
||||
---
|
||||
|
||||
## 9. 分发、更新与恢复
|
||||
|
||||
- **安装来源**:本地包导入(首批)、市场索引(后续)、开发者模式本地目录链接。
|
||||
- **随主程序附带的插件**:需要时可以标准插件包形式嵌入 `reims-go.exe`,信任等级为 `official`,版本跟随主程序;可启用/停用,不可卸载。
|
||||
- **事务安装**:下载到 `tmp` → 校验 `SHA256SUMS` 与签名 → 核对包内 `id` / `version` 与预期一致(防偷换)→ 兼容预检 → 原子 rename 到 `pkgs/<id>/<version>` → 提交 `state.json`。任一步失败都不改变现状。
|
||||
- **市场索引**:独立仓库发布静态 `index.json`(GitHub 主源 + GitCode 镜像,复用运行时下载源的回退与代理逻辑),含版本、`engines`、下载地址、SHA-256 与签名者;主程序内嵌兜底副本。
|
||||
- **更新与回滚**:新旧版本并存、切换指针,保留最近若干版本;插件同样区分 `alpha` / `stable` 通道,默认只取 `stable`。
|
||||
- **安全模式**:`reims-go --safe-mode` 跳过全部第三方插件,界面顶部显示横幅与插件管理入口;以启动哨兵文件检测上次插件初始化阶段异常退出,下次启动询问是否进入安全模式。
|
||||
- **市场红线**:拒收含 Apple 专有文件、SMBIOS 真值或闭源固件的包;运行时包必须附源码与许可证。
|
||||
|
||||
---
|
||||
|
||||
## 10. GUI 与 CLI 接入
|
||||
|
||||
| 入口 | 内容 |
|
||||
| :--- | :--- |
|
||||
| CLI | `reims-go plugin list / install / link <dir> / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor / run <id> <command>`;`vm create --driver <id>` |
|
||||
| 应用设置 → 插件 | 分组展示内置插件与第三方插件:核心置顶、显示「始终启用」且无开关;其余显示来源与信任标签、权限摘要、启用开关、故障状态与日志入口;本地包导入 |
|
||||
| 插件设置页 | 由 `settings` Schema 渲染,复用现有设置控件,标注生效时机 |
|
||||
| VM 页面 | 按能力位显隐操作;`vm.toolbar` 菜单项支持 `when` 条件;`vm.card` 展示驱动或插件提供的键值信息 |
|
||||
| 创建向导 | 先选驱动,再按驱动 `CreateSchema` 渲染专属表单 |
|
||||
|
||||
所有插件文案遵守 [`design-guidelines.md`](design-guidelines.md) §7,插件贡献的按钮与菜单不得占用页头主操作位。
|
||||
|
||||
---
|
||||
|
||||
## 11. 技术难点
|
||||
|
||||
1. **驱动抽象重构**:VM 详情模型与前端(VM 页、设置面板、托盘、CLI)深度耦合 macOS / reims 字段,需在不回归现有功能的前提下拆出通用模型与能力位,是工作量最大的一步。
|
||||
2. **意图合并与参数归属**:多插件意图的冲突仲裁、账本与 `reims-ctl set` 的一致性、OpenCore 重建后重放(如客体语言)的时序。
|
||||
3. **运行时契约脆弱**:`reims-ctl show` 目前为文本解析,第三方运行时若改变输出即破坏驱动;需以 `runtime_api` 严格版本化,并推动上游提供结构化输出。
|
||||
4. **Windows 进程管理**:Job Object 与 VM 进程归属分离、孤儿进程、未签名 Sidecar 被杀软或 SmartScreen 拦截、非 ASCII 用户名路径。
|
||||
5. **原生插件安全**:L3 无法沙箱化,只能依靠签名、审核、信任分级与透明告知。
|
||||
6. **UI 一致性与自由度**:严格设计规范下以声明式贡献为主,iframe 面板需同步主题令牌、DPI、焦点与快捷键。
|
||||
7. **UI 契约维护**:部件类名、状态属性与令牌成为公共 API 后,前端重构须连同 `uiApi` 版本与契约检查一起演进;交互主题脚本在主窗口内运行,只能靠信任分级与 SDK 约束,无法物理隔离。
|
||||
8. **全局输入钩子**:低级鼠标钩子影响整个系统的输入延迟,回调必须极短且按需安装;SDL 捕获模式下的行为与杀软启发式误报需真机验证。
|
||||
9. **公共 API 稳定性**:v0.x 核心演进快,首批扩展点必须克制并版本化,保持对上一 `pluginApi` 主版本的兼容窗口。
|
||||
10. **Linux 客体图形与集成**:Windows 上缺少与 `reims-vgpu` 等价的 Linux 加速路径,cloud-init 与客体代理需要额外工程。
|
||||
11. **合规**:第三方运行时的源码义务、插件许可证声明、插件排障内容的强制脱敏。
|
||||
12. **资源占用**:惰性激活、空闲回收与面板释放,守住 §8.1 的资源预算与现有内存约束。
|
||||
|
||||
---
|
||||
|
||||
## 12. 分阶段演进与验收标准
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
P0["Phase 0\n内部抽象\n(不对外)"] --> P1["Phase 1\n插件底座 + L1\n(主题/模板/运行时源/规则 Hook)"]
|
||||
P1 --> P2["Phase 2\n运行时种类"]
|
||||
P1 --> P3["Phase 3\nL3 Sidecar + Host API"]
|
||||
P3 --> P4["Phase 4\n官方 Linux 驱动"]
|
||||
P3 --> P5["Phase 5\n生态:签名/市场/iframe/L2"]
|
||||
```
|
||||
|
||||
| 阶段 | 范围 | 验收标准 |
|
||||
| :--- | :--- | :--- |
|
||||
| **Phase 0** | 注册表与可逆作用域;驱动抽象(reims 为内置驱动);启动准备与宿客桥接迁为内置扩展;Guest Tools 拆出传输服务与**剪贴板互通示例**;输入服务(IME 键盘钩子迁入);参数归属账本;UI 契约 v1(令牌单一来源、部件类名、状态属性) | `go test ./...` 与前端构建通过;存量 VM 零迁移、行为零回归;剪贴板互通可在 VM 运行中开关且关闭后零残留(无残留路由与剪贴板监视);可选内置扩展同样可独立停用且零残留,核心始终启用;满足 §8.1 资源预算 |
|
||||
| **Phase 1** | 插件包与清单、事务安装、`state.json`、安全模式;插件管理页与 `reims-go plugin`;`inputFilters`;令牌主题与样式主题接口;图标、VM 模板、运行时源、规则 Hook | 以不发布的测试主题与示例声明式插件验证配色方案、字体、部件样式、状态装饰与启停零残留;损坏包与不兼容包在落盘前被拒绝;仍满足 §8.1 资源预算 |
|
||||
| **Phase 2** | 运行时种类注册表、`runtime_api` 与 `capabilities`、来源展示 | 第二种运行时与官方运行时并存切换;不兼容组合被拦截并给出提示 |
|
||||
| **Phase 3** | JSON-RPC 协议 v1、进程监管、反向 Host API、权限审批、代码 Hook、插件命令、排障采集、轻量 Go SDK | 死循环或崩溃的示例 Sidecar 不影响主窗口与运行中 VM;退出或禁用后无孤儿进程 |
|
||||
| **Phase 4** | 独立仓库的官方 Linux 驱动 | 不修改主程序源码,经 GUI 与 CLI 完成 Linux VM 创建、WHPX 启动、绑核、截屏、SSH 与快照;真机验证 |
|
||||
| **Phase 5** | 签名体系与市场索引、iframe 面板、交互主题 UI SDK、按需引入 L2 脚本宿主 | 第三方插件经审核上架;iframe 面板无法越权读取或联网;参照 dsh-claude-style 的功能清单逐项确认可由三档主题能力承载或列出缺口 |
|
||||
|
||||
---
|
||||
|
||||
## 13. 待决事项
|
||||
|
||||
1. **L2 脚本宿主是否需要**:仅当出现 L1 规则无法表达、又不适合要求作者交付原生 exe 的真实需求时引入;届时在纯 Go JS 引擎与 WASM 之间选型。
|
||||
2. **市场形态与审核责任**:首批仅本地包导入;社区索引的维护者、审核流程与签名密钥托管方式待定。
|
||||
3. **Sidecar 原生沙箱**:AppContainer / 低完整性级别的兼容性与维护成本待评估。
|
||||
4. **上游结构化输出**:是否向上游提议 `reims-ctl show --json`,以及非 macOS 客体支持的计划,需核对上游实际进展(待验证)。
|
||||
@@ -1,56 +1,30 @@
|
||||
# 便携运行时规范(Portable Runtime Spec)
|
||||
|
||||
> 实测日期:2026-11-28
|
||||
> 基准上游:`steelbrain/reims-vgpu` commit `3731afd9b13416a24f74ec27a90b3913aef2dcc0`(QEMU `11.1.90`,`reims-util 0.1.0`)
|
||||
> **本地补丁**:本机实测用的 QEMU **不是纯上游构建**。`vendor/qemu`(`4571bc5`)的 `target/i386/whpx/whpx-all.c` 带着一个未提交的修改,内容与 [`macos-vm-lab/patches/qemu-whpx-win10-compat.patch`](../../macos-vm-lab/patches/qemu-whpx-win10-compat.patch)(SHA256 `3eed7895…0304b8`,无 BOM、LF 行尾)一致。没有它,Win10 19045 上 VM 起不来。见第 5 节。
|
||||
> 本文定义 Reims-Go Windows x86-64 便携运行时的打包结构、目录隔离、CI 自动构建、`alpha` → `stable` 发布通道以及开源合规义务。
|
||||
|
||||
## 1. 脱离 MSYS2 / Rust / 源码仓库的实测结论
|
||||
---
|
||||
|
||||
2026-11-28 在本机(Windows 10 19045 x64 + i7-12700K + RTX 4070 Ti)构造了纯净临时环境:
|
||||
- `PATH` 仅保留便携 `bin\` 与 Windows 系统目录(`System32` / `Wbem` / `WindowsPowerShell`),**完全不含** `MSYS2`、`Cargo/Rust`、`Git`、`reims-vgpu` 源码目录。
|
||||
- 通过 `XDG_CONFIG_HOME`、`XDG_DATA_HOME`、`XDG_CACHE_HOME` 将所有读写重定向至隔离目录。
|
||||
## 1. 自包含前提与上游耦合
|
||||
|
||||
实测结果:
|
||||
`reims-vgpu` 的 Windows 运行时在二进制层面可以脱离 MSYS2、Rust 工具链与源码树独立运行:
|
||||
|
||||
| 检查项 | 结果 | 说明 |
|
||||
| :--- | :--- | :--- |
|
||||
| `qemu-system-x86_64.exe -device help` | ✅ PASS | 正确列出 `reims-graphics-pci`(71 个 CLANG64/libva DLL 已由上游 `install-ctl.sh:783-797` 随 `bin\` 打包) |
|
||||
| `reims-util.exe --version` | ✅ PASS | 输出 `reims-util 0.1.0` |
|
||||
| `reims-ctl.exe list --json` | ✅ PASS | 输出 `[]`,无报错 |
|
||||
| `reims-ctl.exe doctor` — `host` / `files` / `qemu` / `audio` / `hypervisor platform` / `vulkan` / `sound` / `desktop` / `reims-util` | ✅ 9/9 PASS | 全部 `ok`,正确识别 RTX 4070 Ti(`nv-vk64.json`)与 XDG 数据路径 |
|
||||
| `reims-ctl.exe doctor` — `checkout` | ❌ FAIL(预期内) | 见第 2 节源码分析:仅因 `install.toml` 缺少必填 `repo` 字段,且 `checkout` 仅用于 `reims-ctl update` |
|
||||
- **内嵌引导与驱动资源**:`reims-ctl.exe` 编译时已内嵌 `ReimsGraphics.rom` 与 Guest Kexts,运行时按内容哈希释放到 `<XDG_DATA_HOME>/reims-ctl/prebuilt/`。
|
||||
- **XDG 路径重定向**:传入 Windows 绝对路径格式的 `XDG_CONFIG_HOME`、`XDG_DATA_HOME`、`XDG_CACHE_HOME` 后,`reims-ctl` 与 `reims-util` 均遵守重定向,不写入 `%USERPROFILE%`(仅短路径 socket 使用 `%TEMP%\reims-ctl`)。
|
||||
- **QEMU 定位优先级**:`reims-ctl` 优先使用 `REIMS_CTL_QEMU` 指定的 `qemu-system-x86_64.exe`,并在同级目录定位 `qemu-img.exe`。
|
||||
- **版本强耦合约束**:`reims-ctl.exe`、`reims-util.exe` 与 `qemu/` 必须来自同一个上游 commit,作为单个版本目录原子安装与回滚,避免协议或内嵌 kext 错配。
|
||||
|
||||
**结论**:`reims-vgpu` 的 Windows 运行时在二进制层面**已经自包含,可以脱离 MSYS2 与编译环境独立运行**。
|
||||
---
|
||||
|
||||
**限定条件**:这次实测的 `qemu/` 带着第 5 节的 Win10 补丁。纯上游构建在 Win10 19045 上已于 2026-11-28 实测必现两处崩溃(见第 5 节证据)。所以运行时包必须说明自己带了哪些补丁,不能写成「纯上游 `3731afd`」。
|
||||
## 2. 运行时包与用户目录规范
|
||||
|
||||
## 2. 上游源码关键发现(`3731afd`)
|
||||
|
||||
1. **Option ROM 与 Guest Kext 已内嵌**(`crates/reims-ctl/src/prebuilt.rs:1-32`):
|
||||
- `reims-ctl.exe` 编译时已将 `ReimsGraphics.rom` 与 `guest/prebuilt/set.toml` 内的全部 kext 嵌入二进制,运行时按内容哈希释放到 `<XDG_DATA_HOME>/reims-ctl/prebuilt/`,不依赖源码树。
|
||||
2. **XDG 路径重定向在 Windows 原生生效**(`crates/reims-ctl/src/paths.rs:54-77`):
|
||||
- 只要传入 Windows 绝对路径格式的 `XDG_CONFIG_HOME`、`XDG_DATA_HOME`、`XDG_CACHE_HOME`,`reims-ctl` 与 `reims-util` 均遵守重定向,不会写入 `%USERPROFILE%`。
|
||||
- 唯一仍在系统盘的是临时运行目录 `%TEMP%\reims-ctl`(用于短路径 socket,体积极小)。
|
||||
- 上游另有两个专用变量,优先级高于 XDG:`REIMS_CTL_CONFIG_DIR`(`paths.rs:61-66`)和 `REIMS_CTL_DATA_DIR`(`paths.rs:68-73`)。它们直接给出 `reims-ctl` 的目录,不再拼 `reims-ctl` 子目录。缓存目录没有专用变量,只认 `XDG_CACHE_HOME`(`paths.rs:75-77`)。`reims-util` 是否认这两个变量**待验证**,所以 `reims-go` 先继续注入 XDG 三件套。
|
||||
3. **QEMU 定位优先级**(`crates/reims-ctl/src/install.rs:85-101`):
|
||||
- 优先读取环境变量 `REIMS_CTL_QEMU`(`qemu-img.exe` 自动从其同级目录查找);
|
||||
- 未设置时回退到 `<XDG_DATA_HOME>\reims-ctl\qemu\current\bin\qemu-system-x86_64.exe`。
|
||||
4. **`install.toml` 的 `repo` 字段**(`crates/reims-ctl/src/install.rs:34-50`):
|
||||
- `Install.repo` 没有 `#[serde(default)]`,省略会导致 `Install::load()` 返回 `None`,令 `doctor` 报 `FAIL checkout`。
|
||||
- `reims-go` **不调用 `reims-ctl update`**,而是由自带的 Runtime Manager 下载新版预编译包并原子切换版本目录;自检模块直接消费 `reims-go` 的健康检查,不依赖 `checkout` 项。
|
||||
|
||||
## 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 的十分之一)。
|
||||
|
||||
### 3.1 运行时发布包结构(`reims-runtime-win-x64-<commit>.tar.zst`)
|
||||
### 2.1 运行时压缩包结构(`reims-runtime-win-x64-<commit>.tar.zst`)
|
||||
|
||||
```text
|
||||
reims-runtime-<commit>/
|
||||
├── manifest.json # 上游 commit、vendor/qemu commit、补丁清单与哈希、通道、构建日期、各文件 SHA256
|
||||
├── NOTICE.md # 上游源码链接与第三方许可声明
|
||||
├── licenses/ # GPL-2.0、LGPL-3.0 等许可证原文
|
||||
├── patches/ # 本包打上的补丁原文(与 manifest.json 的补丁清单一一对应)
|
||||
├── manifest.json # 上游各仓库 commit、补丁清单与哈希、构建通道、可执行文件 SHA-256、符号包索引
|
||||
├── NOTICE.md # 上游来源与第三方许可声明
|
||||
├── licenses/ # GPL-2.0、LGPL-3.0 等许可证全文
|
||||
├── patches/ # 实际应用的全部补丁原文(与 manifest.json 一一对应)
|
||||
├── bin/
|
||||
│ ├── reims-ctl.exe
|
||||
│ └── reims-util.exe
|
||||
@@ -59,100 +33,102 @@ reims-runtime-<commit>/
|
||||
│ ├── qemu-system-x86_64.exe
|
||||
│ ├── qemu-img.exe
|
||||
│ ├── reims-vgpu-compile.exe
|
||||
│ └── *.dll # 71 个自包含 CLANG64 + libva/vaon12 DLL
|
||||
└── share/ # QEMU pc-bios / edk2 / keymaps 等数据文件
|
||||
│ └── *.dll # 自包含 CLANG64 与 libva/vaon12 运行库
|
||||
└── share/ # x64 pc-bios / edk2 / keymaps 等数据文件
|
||||
```
|
||||
|
||||
> **版本耦合约束**:`reims-ctl.exe`、`reims-util.exe` 与 `qemu/` 必须来自**同一个上游 commit**,作为单一版本目录原子安装与回滚,避免协议或内嵌 kext 版本错配。
|
||||
### 2.2 裁剪与调试符号分离
|
||||
|
||||
### 3.2 用户数据目录结构(由用户在向导中选择,默认非系统盘如 `D:\Data\reims-go\`)
|
||||
打包脚本 [`scripts/stage-runtime-binaries.ps1`](../scripts/stage-runtime-binaries.ps1) 执行两项体积优化,在缩小下载体积的同时保留完整调试能力:
|
||||
|
||||
1. **裁剪非必要工具与异架构固件**:仅移除 Windows x64 启动器不会调用的 `qemu-system-x86_64w.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` 从 5 个主可执行文件(`reims-ctl.exe`、`reims-util.exe`、`qemu-system-x86_64.exe`、`qemu-img.exe`、`reims-vgpu-compile.exe`)提取 `.debug` 符号并写入 GNU debug link,打包为同 Release 下的 `reims-runtime-symbols-<commit>.tar.zst`(客户端默认不下载符号包)。`manifest.json` 记录最终剥离后可执行文件的 SHA-256。
|
||||
|
||||
### 2.3 用户数据目录与子进程环境
|
||||
|
||||
用户首次启动时自选非系统盘数据目录 `<DataRoot>`:
|
||||
|
||||
```text
|
||||
<DataRoot>/
|
||||
├── reims-go.json # reims-go 自身配置(数据目录、默认硬件参数、镜像加速等)
|
||||
├── reims-go.json # 应用配置(数据目录、语言、外观、代理与通道设置等)
|
||||
├── runtimes/
|
||||
│ ├── <commit>/ # 解压后的便携运行时(含 bin/ 与 qemu/)
|
||||
│ └── current -> <commit> # 当前激活版本(目录联接或配置文件指向)
|
||||
├── config/ # 注入为 XDG_CONFIG_HOME(含 reims-ctl/vms.toml)
|
||||
├── data/ # 注入为 XDG_DATA_HOME(含 reims-ctl/vms/、installers/、prebuilt/)
|
||||
├── cache/ # 注入为 XDG_CACHE_HOME
|
||||
└── images/ # Golden Images 与 CoW backing files(M3)
|
||||
│ ├── <commit>/ # 解压后的便携运行时
|
||||
│ └── current # 当前激活版本指向
|
||||
├── config/ # 注入为 XDG_CONFIG_HOME(含 reims-ctl/vms.toml)
|
||||
├── data/ # 注入为 XDG_DATA_HOME(含 reims-ctl/vms/、installers/、prebuilt/)
|
||||
├── cache/ # 注入为 XDG_CACHE_HOME
|
||||
├── shared/ # Guest Tools 共享目录
|
||||
├── reports/ # 导出的脱敏排障日志包
|
||||
└── tmp/ # 临时文件与 CLI 启动回传状态
|
||||
```
|
||||
|
||||
调用 `reims-ctl.exe` 时,`reims-go` 在子进程环境变量中统一注入:
|
||||
调用 `reims-ctl.exe` / `reims-util.exe` 时,由 `internal/runtime` 统一注入隔离环境变量:
|
||||
- `XDG_CONFIG_HOME=<DataRoot>\config`
|
||||
- `XDG_DATA_HOME=<DataRoot>\data`
|
||||
- `XDG_CACHE_HOME=<DataRoot>\cache`
|
||||
- `REIMS_CTL_QEMU=<DataRoot>\runtimes\<active>\qemu\bin\qemu-system-x86_64.exe`
|
||||
- `PATH=<DataRoot>\runtimes\<active>\bin;<System32>...`(确保 `reims-ctl` 能直接找到同目录的 `reims-util.exe`)
|
||||
- `PATH=<DataRoot>\runtimes\<active>\bin;<System32>...`
|
||||
|
||||
## 4. 打包与发布流水线(M0 / M4)
|
||||
---
|
||||
|
||||
- **本地打包验证(M0)**:编写 `scripts/pack-runtime.ps1`,直接从本机已编译的 `reims-vgpu` 产物生成 `reims-runtime-win-x64-3731afd.tar.zst` 与 `manifest.json`(含 SHA256),验证纯净解压启动。
|
||||
- **本地打包与发布(2026-11-28 起)**:`pwsh -File scripts/pack-runtime.ps1 -Channel candidate` 一次产出三个文件:运行时包、对应源码包 `reims-runtime-src-<commit>.tar.zst`、覆盖两者的 `SHA256SUMS.txt`。
|
||||
- **打包前的检查**:脚本先核对每个补丁是否与构建目录里的 diff 完全一致;不一致、或者构建目录里有未登记的改动,就直接停止,不会自动修改补丁。
|
||||
- **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 的预发布对应 `candidate`,正式发布对应 `stable`。三个附件缺任何一个,客户端就不会列出这个版本。
|
||||
- **客户端安装**(`internal/runtime/remote.go`):从 GitHub API 列出版本 → 下载运行时包,支持续传 → 对照 `SHA256SUMS.txt` 校验,不一致就丢弃 → 用原有的导入流程解压并激活 → 删除下载的压缩包。
|
||||
- **已发布**:`runtime-3731afd`,候选版。实测从 GitHub 下载 169 MB、校验、解压、激活,全程约 75 秒。
|
||||
- **自动化 CI(M4)**:在 GitHub Actions `windows-latest` runner 上使用 MSYS2 CLANG64,先打上第 5 节的补丁队列,再执行上游构建脚本,产出 `reims-runtime-win-x64-<commit>.tar.zst`、`SHA256SUMS.txt` 和对应源码包(第 7 节)。CI 产物只进 `candidate` 通道,不直接发给用户(第 6 节)。
|
||||
- **CI 测不到 Win10**:`windows-latest` 是 Windows Server 2022/2025,复现不了第 5 节的 Win10 问题,而且 GitHub 托管 runner 一般不提供 WHPX。CI 只能保证「能构建、`-device help` 列出 `reims-graphics-pci`」,能不能启动 VM 要靠第 6 节的本机冒烟测试。
|
||||
## 3. 打包与 CI 自动构建
|
||||
|
||||
## 5. 补丁队列(把上游当内核来优化的方式)
|
||||
### 3.1 本地打包
|
||||
运行 `pwsh -File scripts/pack-runtime.ps1 -Channel alpha` 一次产出以下发布附件:
|
||||
1. `reims-runtime-win-x64-<commit>.tar.zst`(运行时主体)
|
||||
2. `reims-runtime-symbols-<commit>.tar.zst`(独立调试符号包)
|
||||
3. `reims-runtime-src-<commit>.tar.zst`(上游源码 + 补丁原文 + 重建说明)
|
||||
4. `reims-runtime-msys2-src-<commit>.tar.zst`(MSYS2 copyleft DLL 源码包,由 [`scripts/pack-msys2-sources.ps1`](../scripts/pack-msys2-sources.ps1) 生成)
|
||||
5. `SHA256SUMS.txt`(覆盖上述压缩包的统一校验清单)
|
||||
|
||||
原则:**不长期维护 fork,补丁数以清零为目标。** 每个补丁都要经过「本地带着发 → 由人向上游提 PR → 上游合并后删掉本地副本」这个周期。
|
||||
打包前脚本会核对构建目录的 `git diff` 是否与声明的补丁逐字节一致;存在未声明修改或补丁不匹配时立即停止。
|
||||
|
||||
| 补丁 | 作用对象 | 解决的问题 | 状态 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `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(由人操作) |
|
||||
### 3.2 每日 CI 构建
|
||||
[`.github/workflows/build-runtime.yml`](../.github/workflows/build-runtime.yml) 每日定时(也支持手动指定 commit)在 `windows-latest`(MSYS2 CLANG64)执行:
|
||||
1. 读取上游默认分支 `HEAD`;若已存在 `runtime-<commit>` Release(不论 `alpha` 或 `stable`)则跳过。
|
||||
2. 由 [`scripts/apply-patch-series.ps1`](../scripts/apply-patch-series.ps1) 按 [`patches/series.txt`](../patches/series.txt) 顺序打补丁:可正常应用的直接应用;已合入上游的自动跳过并开 Issue 提醒退役;遇到冲突则中止构建。
|
||||
3. 执行上游 `scripts/install-ctl.sh --yes` 编译,调用 `scripts/pack-runtime.ps1 -Channel alpha` 打包。
|
||||
4. 运行 [`scripts/check-runtime-alpha.ps1`](../scripts/check-runtime-alpha.ps1) 校验 5 个附件、`SHA256SUMS.txt`、`manifest.json` 哈希一致、许可证齐全,以及在不含 MSYS2 的纯净 `PATH` 下验证 vGPU 设备枚举、CLI 版本与 `qcow2` 创建读取。
|
||||
5. 通过后发布为 GitHub 预发布(`alpha`),并自动清理超过保留上限(最近 7 个)的旧 `alpha` 预发布;正式版不受影响。
|
||||
|
||||
### 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。
|
||||
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 节)。
|
||||
> **CI 边界**:GitHub 托管的 Windows Server runner 不提供 WHPX,也无法复现 Windows 10 兼容性问题。CI 只验证可编译与控制面基本可用,实际能否启动 macOS 桌面必须经过第 5 节的真机冒烟。
|
||||
|
||||
规则:
|
||||
1. 补丁原文的权威副本放在 `reims-go/patches/`。macos-vm-lab 的那份是研究时的原始记录。
|
||||
2. 每次跟进上游 commit 时,先 `git apply --check`。打不上就停在 `candidate`,不要自动改补丁。
|
||||
3. 补丁文件必须是**无 BOM、LF 行尾**,由 `.gitattributes` 的 `*.patch -text` 保证。用 PowerShell 5.1 的 `Out-File` 或 `>` 生成的补丁会带 BOM 和 CRLF,`git apply` 不认(2026-11-28 实测,原始副本就是这样)。
|
||||
4. 上游合并之后,在表里记下合并 commit,然后删掉补丁。
|
||||
### 3.3 客户端下载与安装
|
||||
`internal/runtime` 默认从 GitHub Releases(tag `runtime-<commit>`)拉取,并支持官方镜像源 [GitCode `Nwflower/Reims-Go`](https://gitcode.com/Nwflower/Reims-Go) 自动回退(`auto` / `github` / `gitcode`),沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。
|
||||
|
||||
## 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**,而是分两级:
|
||||
## 4. 补丁队列
|
||||
|
||||
| 通道 | 来源 | 进入条件 |
|
||||
本仓库不维护长期 fork,所有尚未合入上游的最小兼容性补丁统一维护在 [`patches/`](../patches/)。补丁清单、作用对象、上游化进展与退役检查表见:
|
||||
- 机器清单:[`patches/series.txt`](../patches/series.txt)
|
||||
- 维护文档:[`patches/README.md`](../patches/README.md)
|
||||
|
||||
运行时包的 `manifest.json` 必须如实列出所有实际应用的补丁与哈希,带补丁的构建不得标注为纯上游版本。
|
||||
|
||||
---
|
||||
|
||||
## 5. 发布通道(`alpha` → `stable`)
|
||||
|
||||
上游提交频率高且无稳定 Release,默认用户不能直接暴露在未验证的上游 `HEAD` 下。运行时采用两级通道:
|
||||
|
||||
| 通道 | GitHub Release 形态 | 准入条件 |
|
||||
| :--- | :--- | :--- |
|
||||
| `candidate` | CI 按指定上游 commit 构建并打补丁 | 能构建;`qemu-system-x86_64.exe -device help` 列出 `reims-graphics-pci`;SHA256 清单齐全 |
|
||||
| `stable` | 从 `candidate` 升级 | 在一台真实 Win10 或 Win11 宿主上跑通冒烟测试:`doctor` 的运行时检查全部通过,用 golden 镜像启动到 macOS 桌面,截一张屏,正常关机。由人确认后升级 |
|
||||
| **`alpha`** | 预发布(Pre-release) | CI 每日自动构建并通过 `scripts/check-runtime-alpha.ps1` 全部校验 |
|
||||
| **`stable`** | 正式发布(Release) | 从 `alpha` 晋升:在真实 Windows 10/11 宿主运行 [`scripts/smoke-runtime.ps1`](../scripts/smoke-runtime.ps1),验证纯净目录 `doctor`、启动至 macOS 桌面、截屏与正常关机,经人工确认后晋升 |
|
||||
|
||||
`reims-go` 客户端默认只拉 `stable`,`candidate` 要用户主动打开。这层筛选是 `reims-go` 相对于「自己跑上游安装脚本」的主要价值之一。
|
||||
- 客户端默认仅获取 `stable` 通道;`alpha` 需用户在界面开启「接收 Alpha 版」或在 CLI 传入 `--alpha`。
|
||||
- 晋升 `stable` 不重新打包,仅将既有 GitHub 预发布转为正式发布,确保用户下载的二进制与冒烟验证的资产完全一致(因此包内 `manifest.json` 的构建通道字段保持 `alpha`,客户端以 Release 状态区分通道)。
|
||||
|
||||
升级记录:
|
||||
---
|
||||
|
||||
| 运行时 | 候选版发布 | 冒烟测试 | 升为稳定版 |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| `runtime-3731afd` | 2026-11-28 | 真实宿主 Windows 10 19045,启动到 macOS 桌面并正常关机,由人确认通过 | 2026-11-28 |
|
||||
## 6. 许可证与源码分发义务
|
||||
|
||||
升级不重新打包,只把 GitHub Release 从预发布改为正式发布,所以用户拿到的文件与冒烟测试用的完全相同。包内 `manifest.json` 的 `channel` 字段记录的是构建时的通道,会一直是 `candidate`;客户端只看 Release 的发布状态。
|
||||
Reims-Go 本体(Go 后端与前端外壳)采用 [Apache-2.0](../LICENSE) 协议,仅通过独立子进程调用运行时组件,不进行静态或动态链接。
|
||||
|
||||
## 7. 许可证与源码义务
|
||||
由于便携运行时包含 GPLv2(QEMU)、`GPL-2.0-or-later OR LGPL-3.0-or-later`(`reims-vgpu` / `reims-ctl` / `metal2vulkan`)以及 MSYS2 CLANG64 / libva 动态库,每个公开运行时 Release **必须同处附带完整对应源码与许可证文本**:
|
||||
|
||||
发布二进制,就要同时提供对应的源码。只给上游链接不够,因为本地补丁不在上游。每个运行时 Release 附带:
|
||||
- `reims-vgpu`(含 `reims-ctl`)、`qemu-reims-vgpu`(**含本地补丁**)、`metal2vulkan`、`reims-util` 在所用 commit 的源码包;
|
||||
- 运行时里 MSYS2 CLANG64 DLL 对应的包名、版本,以及其中 LGPL/GPL 组件(如 glib)的源码或获取方式(具体清单**待 M0.1 打包时列出**);
|
||||
- `licenses/` 里的许可证全文。
|
||||
|
||||
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` 外壳用 MIT,前提是它和这些组件只通过独立进程交互,不链接它们。
|
||||
1. **上游源码包(`reims-runtime-src-<commit>.tar.zst`)**:导出所用 commit 的四个上游仓库源码树、构建所需的 QEMU meson 子项目、`patches/` 中的全部补丁原文及重建说明。
|
||||
2. **MSYS2 copyleft 源码包(`reims-runtime-msys2-src-<commit>.tar.zst`)**:由 [`scripts/pack-msys2-sources.ps1`](../scripts/pack-msys2-sources.ps1) 根据本机 pacman 元数据自动筛选全部无宽松替代协议的 GPL / LGPL / MPL 依赖包,下载官方 `.src.tar.zst` 并使用 `gpgv` 与 MSYS2 密钥逐一验签,同时附带 `MSYS2-PACKAGES.txt` 说明全部 DLL 归属与许可。
|
||||
3. **许可证与声明**:运行时包根目录内置 [`NOTICE.md`](../NOTICE.md) 与 `licenses/` 全文。
|
||||
4. **不含 Apple 专有文件**:任何仓库目录或运行时 Release 均不包含 macOS 安装包、恢复镜像、解密固件或 SMC 密钥;系统安装包均由用户端直连 Apple 服务器获取。
|
||||
@@ -1,117 +1,75 @@
|
||||
# 开发路线图与里程碑(Roadmap)
|
||||
# 路线图(Roadmap)
|
||||
|
||||
> 原则:先打通“最小可用闭环”(本地打包便携运行时 → Go 核心驱动 → Wails GUI),再扩展自动化与 CI 自动发版。每个里程碑均有明确的可验证验收标准(DoD)。
|
||||
> Reims-Go 的规划从真实用户任务出发:先让用户在 Windows 上顺畅装到桌面、稳定用于日常开发、改坏环境可回退,再按需补齐进阶开发工作流。
|
||||
|
||||
```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 周)"]
|
||||
```
|
||||
## 口径说明
|
||||
|
||||
- **已实现**:代码或脚本已合并进主分支并随版本发布,不代表已覆盖所有 Windows 版本、显卡和 macOS 版本的真机组合。
|
||||
- **真机验收**:需要在明确记录的 Windows、GPU、运行时和 macOS 组合上完成端到端任务验证;单元测试和 CI 编译通过不替代真机验证。
|
||||
|
||||
---
|
||||
|
||||
## M0:便携运行时打包与纯净验证
|
||||
## 已实现能力(截至 v0.2.6)
|
||||
|
||||
**目标**:把本机已验证可用的 `reims-vgpu` 产出一份标准、可复现、可校验的便携运行时压缩包,并在纯净目录中验证完整建机/启动闭环。
|
||||
### 1. 免编译与环境初始化
|
||||
- **便携运行时体系**:剥离 MSYS2 / Rust / 源码仓库依赖,支持 GitHub Release(含 GitCode 国内镜像回退与系统代理)在线下载、断点续传、SHA-256 校验、原子切换与本地 `.tar.zst` 导入。
|
||||
- **宿主机体检与引导**:免提权检测 WHPX(缺失时支持 UAC 一键开启)、物理与可用提交内存预检、Vulkan 独立显卡识别、大小核(P/E/LP-E)拓扑与处理器计划检查、数据盘总线类型风险提示。
|
||||
- **统一发布物**:桌面界面与命令行共用单个 `reims-go.exe`,支持浅色/深色外观与中英双语。
|
||||
|
||||
- [ ] **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` 通过)。
|
||||
### 2. 装机与虚拟机管理
|
||||
- **离线安装包管理器**:宿主机直连 Apple 目录下载完整 macOS 安装包,支持断点续传、空间预检、缓存复用与可视化清理。
|
||||
- **装机引导与自动化**:离线辅助盘自动抹盘与安装、QMP 一键键入恢复终端命令、系统外预设 macOS 界面语言(`prev-lang:kbd`)、对称的「进入/退出恢复模式」、VMDK / RAW 磁盘导入。
|
||||
- **设置与运维**:运行中可编辑配置并标明生效时机(立即生效或下次启动生效)、待生效变更汇总与一键重启应用、停机扩容与空间回收、CoW 秒级派生、停机恢复点(创建/回滚/删除)、脱敏排障日志包导出。
|
||||
|
||||
**DoD**:
|
||||
- 存在可重复生成的便携运行时包及其 SHA256 清单;
|
||||
- 脱离 MSYS2 后实测可成功引导 macOS Tahoe 桌面,且 C 盘无新增 reims 文件。
|
||||
### 3. 日常使用与宿客互通
|
||||
- **显示与性能**:按屏幕分辨率与缩放推荐 HiDPI 档位、无边框全屏、按 VM 自定义 CPU 亲和性(自动/全部/性能核/避开低功耗核/自定义,运行中立即生效)、VM 屏幕预览与全分辨率截图复制、前置 VM 窗口。
|
||||
- **Guest Tools**:纯本地回环鉴权的双向图文剪贴板、WebDAV 挂载式共享文件夹(含文件拖入投递与按盘符开启的 Windows 只读共享)、防休眠守护、Windows IME 中文与表情输入转发。
|
||||
- **常驻与远程连接**:系统托盘常驻与每台 VM 独立子菜单、SSH 快捷键(记住用户名、打开终端、写入 `~/.ssh/config`、VS Code Remote-SSH)。
|
||||
|
||||
---
|
||||
|
||||
## M1:Go 核心层与 CLI(`reims-go` 无界面闭环)
|
||||
## 近期重点(P0)
|
||||
|
||||
**目标**:先用纯 Go 打通所有底层能力与单元测试,确保 CLI 单独就能跑完整个生命周期。
|
||||
优先打磨和验证已有能力,在 P0 任务稳定前不堆砌新子系统。
|
||||
|
||||
- [ ] **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 ./...`)。
|
||||
- [x] **M1.2**:`internal/runtime` — 实现便携运行时导入(本地 `.tar.zst` 与 HTTP 下载)、SHA256 校验、原子解压、版本切换与子进程环境变量构造(`XDG_*` + `REIMS_CTL_QEMU`)。
|
||||
- 2026-11-28:补上在线安装,运行时从本仓库的 GitHub Release 下载(`runtime-<commit>` tag,候选版和稳定版两个通道),支持续传,并对照 `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 <文件名>`。
|
||||
- GUI 绑定:`ListOfflineReleases`、`DownloadInstaller`、`ListInstallers`、`DeleteInstaller`;下载进度通过任务事件推送(见 `ui-redesign.md` B1)。
|
||||
- 依据上游 `3731afd` 的 `crates/reims-ctl/src/reims_util.rs` 和 `downloads.rs`:
|
||||
- 参数顺序是 `reims-util --json offline-installer <版本> -o <目录>`,`--json` 放在子命令前面;
|
||||
- 事件格式见 `reims_util.rs:423-431`;
|
||||
- 暂停就是结束进程,再次运行同一条命令会接着下载(`reims_util.rs:30-31`);
|
||||
- 删除走 `reims-ctl downloads delete NAME --yes`,VM 正在使用或正在下载的文件会被拒绝(`downloads.rs:108-123`)。
|
||||
- 与 reims-ctl 互斥:下载期间对 `installers/.lock` 持有排他锁,Windows 上用 `LockFileEx`,和 Rust 的 `File::try_lock` 相同。已实测:reims-go 持锁时,真实的 `reims-ctl downloads delete` 会以「正在下载」拒绝。测试是 `internal/installer` 的 `TestLockExcludesReimsCtl`,需要设置 `REIMS_GO_TEST_CTL`。
|
||||
- 实测(2026-11-28,reims-util 0.1.0):
|
||||
- `offline-installer list` 读取 Apple 的目录约需 10 秒,返回字段为 product、title、version、build、posted、size、url、integrity_url、digest;
|
||||
- 下载一开始就会创建一个与完整镜像同样大小的 `.part` 文件(26.7.3 为 19.7 GB),**磁盘可用空间当场减少约 20 GB**;M2.2 的下载管理器要在开始前检查剩余空间;
|
||||
- 暂停后重新开始,会从中断处继续,不会从头下载。
|
||||
- 未实测:
|
||||
- 完整跑完一次离线安装包下载(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` 与中英双语输出。
|
||||
### 1. 首次装机与发版闭环
|
||||
- 在 GitHub Actions 上实跑 `build-runtime.yml` 每日构建与 `alpha` 准入流程,验证公开资产的 `manifest.json`、补丁队列与源码包一致性。
|
||||
- 在多种受支持的 Windows 10 / 11、GPU 与 macOS 组合上跑通完整开箱流程(干净目录 → 体检 → 安装运行时 → 下载离线包 → 装机 → 退出恢复模式)。
|
||||
- 完善中断与异常场景的故障恢复(断网续传、磁盘不足、取消 UAC、运行时损坏),确保失败后可安全重试且不残留半配置虚拟机。
|
||||
|
||||
**DoD**:
|
||||
- 在一个从未 dot-source `reims-env.ps1` 的全新 PowerShell 中,仅运行 `reims-go` CLI 即可完成体检、导入运行时、断点续传下载离线包、启动/查看 VM;
|
||||
- `go test ./...` 全通过。
|
||||
### 2. 日常主力体验与上游性能跟进
|
||||
- 持续跟进上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的 Windows 图形与窗口改进(热切全屏、无黑边窗口缩放、原生 Windows Vulkan 后端、首帧延迟优化、自由指针 `Win → Command` 映射),合入后经 `alpha` 冒烟升级至 `stable`(跟踪明细见 [patches/README.md](../patches/README.md))。
|
||||
- 推动当前本地兼容性补丁上游化,并逐步清零 `patches/` 队列。
|
||||
- 在真实宿主完成长时间开发负载验证(编译、浏览器、多任务、图文剪贴板、WebDAV 挂载、Windows 盘符只读共享、音频/麦克风与休眠唤醒恢复)。
|
||||
|
||||
### 3. 恢复点与磁盘操作可靠性
|
||||
- 对停机恢复点(创建/回滚/删除)、CoW 派生启动、大容量 VMDK 转换以及停机扩容/空间回收完成真机中断与边界测试,确保空间不足或中途中断不会破坏原盘与 backing file 链。
|
||||
- 补充数据目录离线备份与迁移说明(明确快照不等于跨盘备份)。
|
||||
|
||||
---
|
||||
|
||||
## M2:Wails 桌面 GUI MVP(一站式开箱体验)
|
||||
## 下一步计划(P1)
|
||||
|
||||
**目标**:做成真正给普通开发者/自己点几下就能用的轻量桌面应用。
|
||||
|
||||
- [ ] **M2.1**:**首次启动向导(中英双语实时切换)** — 自动识别系统语言(支持顶部一键切换 `中文 / English`);展示环境体检卡片(WHPX、**提交内存与推荐 RAM**、显卡、磁盘);WHPX 未开时提供「一键提权启用并重启」按钮;引导选择非 C 盘数据目录并一键安装/导入便携运行时。
|
||||
- 2026-11-28 已完成一部分。首次启动先选数据目录:推荐有空间的非系统盘,USB 外置盘排在最后并标出风险,也可以手填路径;选好后进入运行时在线安装,这一步可以跳过。已有安装会被直接沿用,不再询问。选择结果记在 `%APPDATA%\reims-go\location.json`(只有这一个小文件放在数据目录之外)。环境体检卡片和一键启用 WHPX 还没并进这个流程。
|
||||
- [ ] **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`(验证体积与冷启动速度)。
|
||||
- 2026-11-28:`wails build -trimpath` 产出 12.7 MB 的单文件,命令行版 7.7 MB,作为 [v0.1.0](https://github.com/Nwflower/reims-go/releases/tag/v0.1.0) 发布。没有代码签名,首次运行会被 SmartScreen 拦截一次。冷启动时间还没测。
|
||||
- [ ] **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 节)。
|
||||
|
||||
**DoD**:
|
||||
- 双击 `reims-go.exe` 即可走完「体检 → 导入运行时 → GUI 断点续传下载离线安装包 → 创建/启动 VM → 离线装完并弹出安装盘」全流程,无需打开命令行。
|
||||
- VM 运行中修改 CPU / 内存 / 显示器数量并保存,重启后 `reims-ctl show` 显示新值;非法输入(如内存超过宿主可用提交内存、ICD 文件不存在)在保存前被拦下。
|
||||
- **可测量的时间目标**:从首次双击到出现 macOS 安装界面 ≤ 10 分钟。不计入:开启 WHPX 后的重启、运行时下载、从 Apple 下载离线安装包。macOS 离线安装本身的耗时单独实测记录(**待验证**),不作为 DoD。
|
||||
### 开发者网络与工作流增强
|
||||
- 支持自定义多条宿客 TCP 端口转发(含端口冲突检测),无需手写 `--extra-args`。
|
||||
- 在 Guest Tools 中提供可选的宿主机代理快捷开关(显式开启、一键清除),方便客体内的 Homebrew / Xcode / npm 下载。
|
||||
|
||||
---
|
||||
|
||||
## M3:硬件自动调优与开发者进阶能力
|
||||
## 按需评估
|
||||
|
||||
**目标**:补齐现有社区 GUI 的空白,对接 `macos-vm-lab` 的工程化需求。
|
||||
以下能力仅在有明确场景和可验证方案后才进入版本排期:
|
||||
|
||||
- [ ] **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`。
|
||||
|
||||
**DoD**:
|
||||
- P-Core 绑核、QMP 连接、CoW 派生在本机均有实测通过记录。
|
||||
|
||||
---
|
||||
|
||||
## M4:GitHub Actions 自动化构建与发布
|
||||
|
||||
**目标**:彻底自动化上游跟进,用户点「检查更新」即可拉取新版运行时与外壳。
|
||||
|
||||
- [ ] **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;合并后从队列删除。
|
||||
|
||||
**DoD**:
|
||||
- 触发一次 tag/手动 workflow 即可产出完整的 `candidate`(App + Runtime + SHA256 + 源码包);冒烟通过并经人确认后升为 `stable`;在干净目录下载 `stable` 后,按 M2 的时间目标跑通。
|
||||
- **扩展与插件体系**:架构草案见 [docs/plugin-architecture.md](plugin-architecture.md),待核心体验稳定后分阶段评估。
|
||||
- **Windows USB 设备直通**:依赖 WinUSB / UsbDk 驱动替换,签名与稳定性风险较高,仅在确有 iPhone 真机调试或硬件密钥刚需时做最小原型评估。
|
||||
- **独立导出/迁移与备份调度**:先验证数据目录离线备份方案是否足够,再评估独立归档格式与恢复校验。
|
||||
|
||||
---
|
||||
|
||||
## 不做的事
|
||||
|
||||
- **不维护长期 fork**:对上游的改动只走补丁队列,目标是清零(见 `portable-runtime-spec.md` 第 5 节)。
|
||||
- **不跟踪上游最新 commit**:用户只拿到冒烟过的 `stable`。
|
||||
- **暂不实现 `vphone` 等其他 `Engine`**:接口位置先留着,等 x86 macOS 主线稳定后再说。
|
||||
- **不长期维护上游 fork**:对 `reims-vgpu` / QEMU 的改动只走临时补丁队列,上游合入即退役。
|
||||
- **不向默认用户分发未验证的上游最新提交**:CI 产物先进入 `alpha` 预发布,经真机冒烟并人工确认后才升级为 `stable`。
|
||||
- **暂不做 TAP / 虚拟网卡驱动安装器**:维护与驱动签名成本高,优先做好用户态网络、端口转发与 Guest Tools。
|
||||
- **暂不做运行中内存热快照(`savevm`)**:在 `reims-vgpu` 显存与设备状态序列化未获上游验证前,以停机恢复点和 CoW 派生为准。
|
||||
- **不兼容已淘汰的旧图形栈**:不引入 `apple-gfx` 等旧后端,不为堆砌参数列表而增加复杂界面。
|
||||
@@ -1,101 +0,0 @@
|
||||
# 外壳设计原语(对齐 macOS)
|
||||
|
||||
> 2026-11-28 起草。上游行为引自 `steelbrain/reims-vgpu` commit `3731afd`,路径相对 `crates/reims-ctl/src/`。
|
||||
|
||||
## 1. 「对齐 macOS」指什么
|
||||
|
||||
两层意思,都要做到:
|
||||
|
||||
1. **配置模型对齐 Apple 的虚拟化概念**。界面上的分类、字段名和校验方式,以 Apple [Virtualization.framework](https://developer.apple.com/documentation/virtualization) 的 [`VZVirtualMachineConfiguration`](https://developer.apple.com/documentation/virtualization/vzvirtualmachineconfiguration) 为词表:平台、引导、CPU、内存、存储、网络、图形与显示器、音频、键盘与指针、串口。macOS 用户和做 macOS 开发的人对这套分类最熟悉,以后做 arm64 宿主或者对接 Apple 宿主时,也能直接对上。
|
||||
2. **交互对齐 macOS 的人机界面规范**([Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines)):
|
||||
- 主窗口:左边侧边栏列出 VM,右边是详情,顶部工具栏放常用操作;
|
||||
- 创建:用分步助手;
|
||||
- 修改:设置面板按类别分页,像 macOS 的「系统设置」。
|
||||
|
||||
外壳跑在 Windows 上:**结构和术语按 macOS 来做**(侧边栏、分步助手、设置分页、VZ 词表),**渲染层面按 Windows 平台来做**(字体用 Segoe UI / 微软雅黑,窗口控件放右上角,适配 Windows 的 DPI 缩放)。2026-11-28 按 [`ui-redesign.md`](ui-redesign.md) 第 9 节 D4 修订,原先的写法是「视觉也按 macOS」。Windows 特有的部分(UAC、WHPX、Vulkan ICD)集中放在「宿主」页,不混进 VM 设置。
|
||||
|
||||
## 2. 三条原语
|
||||
|
||||
| 原语 | 含义 | 来源 |
|
||||
| :--- | :--- | :--- |
|
||||
| **配置是一份声明式文档** | 一台 VM 等于一份配置,界面只编辑它,不直接拼 QEMU 参数 | 对应 `VZVirtualMachineConfiguration`;上游落到 `vm.toml` |
|
||||
| **先校验,后保存** | 保存前在 Go 里检查一遍(CPU 数、内存上限、GPU ICD 文件是否存在、磁盘控制器切换前是否已弹出安装盘),不合法就不提交 | 对应 `VZVirtualMachineConfiguration.validate()` |
|
||||
| **随时可编辑,标明生效时机** | 不管 VM 运行与否,设置面板都能打开、能改。每个字段标出何时生效;VM 正在运行时,保存后显示「下次启动生效」和「重启以应用」按钮 | 上游所有 `set` 修改都在下次启动时生效(`cli.rs:73`) |
|
||||
|
||||
写入一律通过 `reims-ctl set`,不直接改 `vm.toml`。这样上游的校验和「改图形时重建 OpenCore 镜像」(`cli.rs:242`)都会照常执行。
|
||||
|
||||
## 3. 配置项映射
|
||||
|
||||
生效时机分三种:**下次启动**;**停机时**(只能在 VM 停止时修改,或者修改会触发额外操作);**仅创建时**。
|
||||
|
||||
| 类别(对齐 VZ) | 界面字段 | `reims-ctl` 参数(`cli.rs:551-616`) | 生效时机 | 备注 |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| 平台 | Mac 机型、序列号、MLB、UUID、ROM | 存在 OpenCore 的 `config.plist`,`update-opencore` 时保留(`cli.rs:236-248`) | 只读 | 界面只显示是否已设置,**不显示具体值**;日志和排障包里一律脱敏 |
|
||||
| 引导 | OpenCore 镜像、启动选择 | `update-opencore`、`--boot-selection` | 停机时 | 「重建引导镜像」放在高级操作里 |
|
||||
| 系统来源 | 下载 Apple 版本 / 本地安装器 / 已有磁盘 | `create --macos`、`--installer`、`--disk`、`--disk-mode` | 仅创建时 | 装好后提示「弹出安装盘」(`eject`) |
|
||||
| CPU | 核数 | `--cpus` | 下次启动 | 推荐 4 或 8;绑 P 核的开关属于 `reims-go` 自己的功能 |
|
||||
| 内存 | 大小 | `--memory` | 下次启动 | 上限按宿主物理内存校验 |
|
||||
| 存储 | 磁盘控制器(SATA / NVMe / virtio) | `--disk-controller` | 下次启动 | 切换前必须先弹出安装盘,否则 OpenCore 可能又从安装盘启动(`cli.rs` 中该参数的说明) |
|
||||
| 存储 | 磁盘大小 | `create --disk-size` | 仅创建时 | 创建后能否扩容**待验证** |
|
||||
| 网络 | 开关、SSH 端口转发、MAC | `--network`、`--ssh-port`、`--mac` | 下次启动 | MAC 属于敏感值,默认隐藏 |
|
||||
| 图形与显示器 | 显卡类型、显示器数量(1–4)、分辨率、无边框全屏、宿主 GPU | `--graphics`、`--displays`、`--resolution`、`--borderless`、`--gpu` | 下次启动;改显卡类型要停机 | GPU 下拉框由 `reims-go` 扫描 ICD 后生成,过滤掉虚拟显示适配器 |
|
||||
| 音频 | 开关、后端 | `--audio`、`--audio-backend` | 下次启动 | Windows 上的可选后端**待验证** |
|
||||
| 键盘与指针 | 点击窗口时捕获键鼠 | `--capture` | 下次启动 | — |
|
||||
| 串口与日志 | 日志开关、日志级别 | `--logs`、`--log-level` | 下次启动 | 日志在详情页抽屉里实时查看 |
|
||||
| 高级 | 关机等待时间、额外 QEMU 参数、环境变量 | `--stop-timeout`、`--extra-args`、`--env` | 下次启动 | `reims-go` 自己注入的 QMP 参数要和用户填的分开存放、合并写入,不能互相覆盖 |
|
||||
| (VZ 有,上游没有) | 共享目录、剪贴板、vsock | 无 | — | 先不做,界面上也不放占位 |
|
||||
|
||||
## 4. 状态模型
|
||||
|
||||
上游 `list --json` 只给三种状态:`running`、`stopped`、`broken`(`cli.rs:816-830`)。
|
||||
|
||||
`reims-go` 在此基础上加上自己发起操作时的过渡状态,名称对齐 `VZVirtualMachine.State`:
|
||||
|
||||
| 显示状态 | 来源 | 可用操作 |
|
||||
| :--- | :--- | :--- |
|
||||
| 已停止 | 上游 `stopped` | 启动、设置、复制派生、删除 |
|
||||
| 正在启动 | `reims-go` 发起 `start` 到出现 `running` 之间 | 查看日志 |
|
||||
| 运行中 | 上游 `running` | 关机、强制关机、截屏、弹出安装盘、设置(下次启动生效) |
|
||||
| 正在停止 | `reims-go` 发起 `stop` 到出现 `stopped` 之间 | 强制关机 |
|
||||
| 配置损坏 | 上游 `broken` | 打开排障、删除 |
|
||||
|
||||
暂停、保存和恢复状态(VZ 的 `paused`、`saving`、`restoring`)**先不提供**,因为上游没有文档化快照功能,QMP `savevm` 在 reims-vgpu 下能否用**待验证**。
|
||||
|
||||
状态每秒刷新一次,和上游 TUI 的做法一样(`tui.rs:1-6`),这样在 CLI 里或直接关掉 VM 窗口造成的变化也能及时反映出来。
|
||||
|
||||
## 5. 界面结构
|
||||
|
||||
```text
|
||||
┌ 标题栏:reims-go ─ □ ✕ ┐
|
||||
├──────────────┬───────────────────────────────────────────────────────────────┤
|
||||
│ 虚拟机 [+] │ m0 ● 运行中 [主操作] ■ ⚙ ⋯ │
|
||||
│ ● m0 │ 概览:CPU / 内存 / 磁盘、GPU、SSH 端口 │
|
||||
│ ○ golden │ 待生效的修改(有才显示):cpus 8→12 [重启以应用] │
|
||||
│ ○ run-01 │ 日志抽屉:QEMU 输出 / 串口 │
|
||||
│ ───────── │ │
|
||||
│ 宿主 │ │
|
||||
└──────────────┴───────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- **VM 操作放在详情页页头,不放顶部工具栏**:操作离对象近,切到宿主页时也不会出现整排按钮消失、布局跳动的问题。主操作随状态切换,其余操作是纯图标按钮或收进「⋯」菜单(2026-11-28 按 `ui-redesign.md` D1 修订)。
|
||||
- **新建助手**(弹出式分步):① 系统来源 → ② CPU 与内存 → ③ 存储 → ④ 图形与 GPU → ⑤ 摘要与校验 → 创建。每一步都能返回,最后一步列出将要执行的 `reims-ctl create` 命令。
|
||||
- **设置面板**:左边是第 3 节的类别列表,右边是表单。顶部显示 VM 当前状态,以及这一页修改的生效时机。
|
||||
- **宿主页**:WHPX 状态和启用按钮(UAC)、GPU 与 ICD 列表、P/E 核拓扑、数据目录与空间、运行时版本和通道。
|
||||
|
||||
和上游 TUI 相比,`reims-go` 多出这些东西:
|
||||
- 「待生效修改」对比和一键重启以应用;
|
||||
- 保存前在 Go 里预先校验;
|
||||
- GPU 列表过滤掉虚拟显示适配器;
|
||||
- 绑 P 核;
|
||||
- 复制派生(CoW);
|
||||
- 截屏;
|
||||
- 运行时通道管理。
|
||||
|
||||
基础的创建和编辑表单,上游已经有了(`tui.rs`、`form.rs`),不需要再做一套新逻辑,GUI 只换一种呈现方式。
|
||||
|
||||
## 6. 待验证
|
||||
|
||||
- `reims-ctl show` 能不能输出 JSON;不能的话,读取配置要解析文本或直接读 `vm.toml`(只读)。
|
||||
- 磁盘创建后能否扩容。
|
||||
- Windows 上可用的 `--audio-backend` 取值。
|
||||
- `reims-go` 注入的 `-qmp tcp:` 与用户的 `--extra-args` 合并后,上游会不会原样传给 QEMU。
|
||||
@@ -1,351 +0,0 @@
|
||||
# 前端改版方案(VM 主面板)
|
||||
|
||||
> 2026-11-28 起草。针对 M2 GUI 当前实现(`frontend/src/App.tsx`、`styles.css`)的体验问题提出改版。交互结构仍遵循 [`shell-design.md`](shell-design.md);本文只改「怎么呈现」,不改配置模型和状态模型。
|
||||
> 标「待决策」的项需要人拍板;标「待验证」的项尚未实测。
|
||||
|
||||
## 1. 现状问题(改版要解决什么)
|
||||
|
||||
| # | 问题 | 现象(截图 / 代码) |
|
||||
| :-- | :-- | :-- |
|
||||
| P1 | 主角错位 | VM 在运行,页面主体却是一份只读配置清单;没有「显示 VM 窗口」、运行时长、连接方式等用户真正关心的信息 |
|
||||
| P2 | 操作重复、层级乱 | 「弹出安装盘」出现 3 次,「串口日志」2 次,「运行中」2 次;工具栏有两个主按钮;被禁用的「启动」仍占主按钮位;正常步骤用黄色警告样式;「删除」常驻页头 |
|
||||
| P3 | 实现细节外泄 | 主视图出现 ICD 路径 `C:\Windows\System32\DriverStore\...\nv-vk64.json`、`Skylake-Client-noTSX-IBRS`、`runtime 3731afd` |
|
||||
| P4 | 本地化只做一半 | 中文界面里,副标题 `x86-64 macOS guest (...)` 和全部日志是英文(后端原样透传) |
|
||||
| P5 | 用日志冒充进度 | 下载 OpenCore 时每 1% 打一行;每条日志都强制展开抽屉(`App.tsx:54`),抽屉截断内容;日志不自动滚到底,看到的是最早的行 |
|
||||
| P6 | 操作无反馈 | `runAction` 没有忙碌态;错误直接 `String(e)`;删除用原生 `window.confirm`,且永远 `keepFiles=false`(`App.tsx:262`),后端支持保留文件但界面没给入口 |
|
||||
| P7 | 没有视觉系统 | 字号有 11 / 11.5 / 12 / 12.5 / 12.8 / 13 / 13.5 七档;内联样式到处都是;字体栈首选 SF Pro / PingFang,在 Windows 上实际落到雅黑;只有暗色 |
|
||||
| P8 | 交互基本功缺失 | 侧边栏是 `div onClick`,不能用键盘操作,没有焦点样式;没有空状态、损坏态页面;没有快捷键、右键菜单 |
|
||||
| P9 | 代码结构 | 一个 400 行的 `App.tsx` 同时承担布局、状态、动作、日志;零 UI 依赖,Dialog / Menu / Toast / Progress 全部手搓或缺失 |
|
||||
|
||||
## 2. 设计原则
|
||||
|
||||
1. **一个视图只有一个主操作。** 主操作跟着状态走:停止时是「启动」,运行时是「显示 VM 窗口」。其余操作降级为次要按钮或收进「更多」菜单。
|
||||
2. **每个操作只有一个出口。** 同一个动作在同一屏里只出现一次。引导文案可以提到按钮,但不再复制按钮。
|
||||
3. **默认说人话,细节可展开。** 主视图只显示用户能理解的值(「RTX 4070 Ti」「16 GB」「8 核」)。路径、哈希、QEMU 内部名放进「技术信息」折叠区,并提供复制按钮。
|
||||
4. **进度归进度,日志归日志。** 长任务用进度条和任务状态呈现,日志只是排障工具,默认收起,出错时才提醒。
|
||||
5. **颜色只表达语义。** 强调色只用于主操作和选中态;绿 / 黄 / 红 / 灰只用于状态;破坏性操作的红色只出现在菜单项和确认框里。
|
||||
6. **每次点击都有回应。** 任何操作在 100 ms 内给出视觉反馈(按钮进入忙碌态或状态点变化),完成或失败时给出 Toast。
|
||||
7. **文案克制,通用操作用图标。** 含义通用的次要操作只放图标;界面已经表达清楚的事不再用文字解释。图标的边界和文案规则见 4.5。
|
||||
|
||||
## 3. 信息架构
|
||||
|
||||
### 3.1 窗口框架
|
||||
|
||||
```text
|
||||
┌ 标题栏 40px ─────────────────────────────────────────────────────── ─ □ ✕ ┐
|
||||
│ [R] reims-go │
|
||||
├──────────────┬───────────────────────────────────────────────────────────┤
|
||||
│ 虚拟机 [+] │ VM 页头:名称 · 状态 · 运行时长 [主操作] [⚙] [⋯] │
|
||||
│ ● macos-tahoe│ ───────────────────────────────────────────────────────── │
|
||||
│ ○ golden │ 内容区(随状态切换,见 3.2) │
|
||||
│ ◐ run-01 45% │ │
|
||||
│ │ │
|
||||
│ ──────────── │ │
|
||||
│ ⚙ 宿主与运行时│ │
|
||||
│ ● 就绪 │ │
|
||||
├──────────────┴───────────────────────────────────────────────────────────┤
|
||||
│ 状态栏 28px:⟳ OpenCore 1.0.8 ▓▓▓▓░░ 45% ⚠ 2 >_ │
|
||||
└──────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
与现状相比的变化:
|
||||
|
||||
- **工具栏的 VM 操作移到 VM 页头。** 标题栏只保留品牌和窗口控件。原因:操作作用于当前选中的 VM,放在页头离对象最近;切到「宿主」页时也不会出现整排按钮突然消失、布局跳动的问题。(`shell-design.md` 第 5 节画的是顶部工具栏,这里是对它的修订,见第 9 节待决策 D1。)
|
||||
- **「新建」改成侧边栏标题旁的 `+`**,和列表放在一起,同时保留 `Ctrl+N`。
|
||||
- **中英切换移到「宿主与运行时 → 偏好设置」**。首次启动向导里仍然保留切换(M2.1)。
|
||||
- **侧边栏底部的 `runtime 3731afd` 改为「宿主与运行时」条目下的一行状态**(「就绪」/「需要处理」),哈希放进宿主页。
|
||||
- **底部日志抽屉改为常驻状态栏**,见第 5 节。
|
||||
|
||||
### 3.2 VM 详情页:按状态切换内容
|
||||
|
||||
| 状态 | 页头主操作 | 页头次要 | 「⋯」菜单 | 内容区 |
|
||||
| :-- | :-- | :-- | :-- | :-- |
|
||||
| 正在创建 | — | — | 取消创建(待验证) | 创建步骤进度:创建磁盘 → 下载 OpenCore → 生成引导镜像 → 完成 |
|
||||
| 已停止 | **启动** | 设置 | 打开所在文件夹、复制派生(M3)、删除… | 概要卡片 + 详细配置(折叠) |
|
||||
| 正在启动 | 启动中…(忙碌态,不可点) | 设置 | 强制关机 | 同上,状态点闪烁 |
|
||||
| 运行中 | **显示 VM 窗口** | 关机、设置 | 重启、强制关机、截屏(M3)、打开所在文件夹 | 待生效修改横幅(有才显示)→ 装机引导(有安装盘才显示)→ 连接信息 → 概要卡片 → 详细配置(折叠) |
|
||||
| 正在停止 | 停止中…(忙碌态) | — | 强制关机 | 同上 |
|
||||
| 配置损坏 | **查看问题** | — | 打开所在文件夹、删除… | 错误说明 + 原始输出 + 建议操作 |
|
||||
|
||||
「删除」只在「⋯」菜单里出现,不再常驻页头。
|
||||
|
||||
### 3.3 运行中 + 装机阶段的页面草图
|
||||
|
||||
```text
|
||||
macos-tahoe ● 运行中 · 12 分钟 [▣ 显示 VM 窗口] ■ ⚙ ⋯
|
||||
|
||||
┌──────────────────────────────────────────────────────────────── 2 / 3 ┐
|
||||
│ ✓ 抹掉磁盘 ─── ● 安装 macOS ─── ○ 弹出安装盘 │
|
||||
│ │
|
||||
│ 在 VM 窗口中选择「重新安装 macOS」 │
|
||||
│ ‹ [继续 →] │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
|
||||
>_ ssh -p 2222 <用户名>@127.0.0.1 ⧉
|
||||
|
||||
▦ 8 核 ▤ 16 GB ⛁ 64 GB · SATA ▣ RTX 4070 Ti · 1080p
|
||||
|
||||
▸ 技术信息
|
||||
```
|
||||
|
||||
(`■` `⚙` `⋯` `⧉` 是纯图标按钮,悬停显示「关机」「设置」「更多」「复制」。概要行每一项悬停时显示全称,如「处理器」。第 3 步的内容区只有一个「⏏ 弹出安装盘」主按钮。)
|
||||
|
||||
要点:
|
||||
|
||||
- **装机引导做成步骤条,替代三行纯文本。** 前两步在宿主侧无法检测,由用户手动点「下一步」推进;进度按 VM 存在 reims-go 自己的配置里,不写 `vm.toml`。「弹出安装盘」只在第 3 步出现一次,页头和横幅里不再放。引导文案以 roadmap M2.3 为准,注意那里写的是离线脚本 `install-macos.sh`,和截图里的「重新安装」两个版本需要统一。
|
||||
- **「显示 VM 窗口」**把 QEMU 的显示窗口置前;如果窗口被最小化,就先还原再置前。需要后端新增接口(第 6 节 B5)。
|
||||
- **概要改成一行「图标 + 数值」**,不再用四张带标题的卡片;取值全部人话化(规则见 4.3)。「已用 21 GB」「已绑定性能核」这类运行时信息在后端支持之前先不显示,不放占位;支持之后放进对应项的 Tooltip。
|
||||
- **详细配置默认折叠**,展开后是现在的那张清单,加上复制按钮。
|
||||
|
||||
### 3.4 其他状态页
|
||||
|
||||
- **空状态**(还没有 VM):一个插图,一句「创建第一台 macOS 虚拟机」,一个主按钮「新建虚拟机」。运行时没装或 WHPX 没开时,主按钮换成「先完成环境检查 →」并跳到宿主页,不再弹出 `noRuntimeAlert` 横幅。
|
||||
- **正在创建**:侧边栏立刻出现这台 VM,状态显示「创建中 45%」;详情页显示分步进度。
|
||||
- **配置损坏**:讲清楚是哪份文件、哪一行出了问题(上游能给多少就给多少),附原始输出折叠区,以及「打开所在文件夹」「删除」两个出口。
|
||||
|
||||
## 4. 视觉与内容规范
|
||||
|
||||
### 4.1 设计令牌(`src/styles/tokens.css`)
|
||||
|
||||
| 类别 | 取值 |
|
||||
| :-- | :-- |
|
||||
| 字体 | 正文 `"Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", sans-serif`;等宽 `"Cascadia Mono", Consolas, monospace`。不再把 SF Pro、PingFang 放在首位,以 Windows 上的实际渲染为准 |
|
||||
| 字阶(只用整数) | 12 说明 / 13 次要正文 / 14 正文 / 16 小标题 / 20 页标题 / 24 空状态标题。中文正文不小于 13 |
|
||||
| 字重 | 400 / 600 两档 |
|
||||
| 间距 | 4 的倍数:4、8、12、16、24、32 |
|
||||
| 圆角 | 4 小控件 / 6 按钮与输入框 / 8 卡片 / 12 对话框 |
|
||||
| 表面 | `--surface-0` 底色、`--surface-1` 卡片、`--surface-2` 浮层,三级,深浅两套 |
|
||||
| 语义色 | `--accent`(主操作、选中)、`--status-running`、`--status-busy`、`--status-error`、`--status-idle`、`--danger`。状态色不用于按钮底色 |
|
||||
| 动效 | 120 ms 状态切换,200 ms 面板展开;遵守 `prefers-reduced-motion` |
|
||||
|
||||
所有组件只引用令牌,禁止内联 `style={{...}}` 写颜色、字号和间距。
|
||||
|
||||
### 4.2 按钮层级
|
||||
|
||||
| 层级 | 用途 | 每个视图的数量 |
|
||||
| :-- | :-- | :-- |
|
||||
| 主按钮(强调色实底) | 当前状态下最该做的事 | ≤ 1 |
|
||||
| 次按钮(描边) | 其他常用操作 | ≤ 3 |
|
||||
| 幽灵按钮 / 图标按钮 | 设置、更多、复制 | 不限 |
|
||||
| 破坏性(红字) | 删除、强制关机 | 只在菜单和确认框里出现 |
|
||||
|
||||
禁用的按钮不占主按钮的位置:状态不满足时,直接换成当前状态下合适的主操作。
|
||||
|
||||
### 4.3 内容人话化规则
|
||||
|
||||
| 原始值 | 主视图显示 | 原始值去向 |
|
||||
| :-- | :-- | :-- |
|
||||
| Vulkan ICD 路径 | 用 `host.gpus[].vulkan_icd` 反查出显卡名称,如「NVIDIA GeForce RTX 4070 Ti」 | 技术信息 |
|
||||
| `Skylake-Client-noTSX-IBRS` | 不显示 | 技术信息 |
|
||||
| `16G` | 「16 GB」 | — |
|
||||
| `disk.qcow2 (qcow2, SATA)` + `AHCI` | 「64 GB · SATA」(容量待后端提供) | 技术信息 |
|
||||
| `x86-64 macOS guest (q35 and OpenCore, WHPX)` | 「macOS · Intel · WHPX 加速」,按语言翻译 | 技术信息 |
|
||||
| `runtime 3731afd` | 「运行时:就绪」 | 宿主页 |
|
||||
| `String(e)` | 本地化的一句话 + 建议操作 +「详情」折叠 | 详情折叠区、日志 |
|
||||
|
||||
格式化函数统一放在 `src/lib/format.ts`,不在组件里拼字符串。
|
||||
|
||||
### 4.5 图标与文案
|
||||
|
||||
**纯图标按钮的条件**(三条同时满足):
|
||||
|
||||
1. 含义通用,在主流桌面软件里已经约定俗成:▶ 启动、■ 关机、⚙ 设置、⋯ 更多、+ 新建、⧉ 复制、✕ 关闭、文件夹、刷新、展开 / 收起、日志;
|
||||
2. 不是当前视图的主操作;
|
||||
3. 不是破坏性操作。
|
||||
|
||||
纯图标按钮必须带三样东西:
|
||||
|
||||
- 悬停 400 ms 后出现的 Tooltip,写名称,有快捷键的附上快捷键,例如「设置 Ctrl+,」;
|
||||
- `aria-label`;
|
||||
- 不小于 28 × 28 的点击区域。
|
||||
|
||||
**必须保留文字的情况:**
|
||||
|
||||
- **主操作**:图标加文字。用户第一眼要知道最该做什么。
|
||||
- **领域专有操作**:弹出安装盘、显示 VM 窗口、重启以应用。这些没有通用图标,只放图标就只能靠猜。
|
||||
- **破坏性操作**:删除、强制关机。它们只出现在菜单里,菜单项一律图标加文字。
|
||||
- **状态**:不能只靠颜色区分。侧边栏用形状区分(● 运行、○ 停止、◐ 进行中、⚠ 出错),配 Tooltip;状态文字只在页头写一次。
|
||||
- **首次流程**:新建助手、空状态、宿主页的环境检查。用户还不熟悉界面,文字不能省。
|
||||
|
||||
**用数值代替标签**:值自带单位时不写标签。「8 核」「16 GB」前面放图标即可,不写「处理器」「内存」,悬停时显示全称。内存和磁盘都用 GB,靠图标区分。
|
||||
|
||||
**文案规则:**
|
||||
|
||||
| 规则 | 反例(现状) | 正例 |
|
||||
| :-- | :-- | :-- |
|
||||
| 界面已经表达的不再用文字解释 | 「当前挂载了 macOS 安装盘。完成系统安装并进入桌面后,请点击上方『弹出安装盘』。」 | 删掉,步骤条已经表达了 |
|
||||
| 按钮用动词,2–5 字 | 「已进入桌面,弹出安装盘 →」 | 「继续」「弹出安装盘」 |
|
||||
| 不用「请」「您」「成功」和感叹号;按钮与短提示不加句号 | 「请点击」「操作成功!」 | 「已关机」 |
|
||||
| 提示只写一句,中文不超过 25 字 | 装机步骤每步两三个分句 | 「在 VM 窗口中选择『重新安装 macOS』」 |
|
||||
| 安抚性说明只在有风险的那一刻出现一次 | 装机步骤里写「不会影响本机 Windows 数据」 | 只在新建助手选择数据目录时写一次 |
|
||||
| 错误写「发生了什么 + 怎么办」,最多两句 | `exit status 1` | 「启动失败:WHPX 未启用。前往宿主页启用」 |
|
||||
| Toast 写「对象 + 结果」 | 「macos-tahoe 关机操作已成功完成」 | 「macos-tahoe 已关机」 |
|
||||
| 不写自明的分组标题 | 「配置概览」 | 删掉,用间距分组 |
|
||||
| 状态词统一用两三个字 | 「运行中」「Running」混用 | 运行中、已停止、启动中、停止中、出错 |
|
||||
|
||||
英文文案同样遵守这些规则,统一用句首大写(sentence case),不用每词首字母大写(Title Case)。
|
||||
|
||||
### 4.6 主题
|
||||
|
||||
跟随系统的深色 / 浅色(`prefers-color-scheme`),偏好设置里可以手动指定。Windows 用户里浅色模式占比不低,只有暗色会显得像个开发工具。(待决策 D3)
|
||||
|
||||
## 5. 进度、日志与反馈
|
||||
|
||||
### 5.1 状态栏(常驻,28 px)
|
||||
|
||||
- **左侧**:当前任务,形如「⟳ OpenCore 1.0.8 ▓▓▓░ 45%」。任务所属的 VM 和完整描述放在 Tooltip 里。同时有多个任务时显示「⟳ 2」,点开是任务列表。
|
||||
- **右侧**:警告和错误计数徽标,加上一个纯图标的日志开关。
|
||||
|
||||
### 5.2 日志面板
|
||||
|
||||
- **默认收起,不再因为来了新日志就自动展开。** 只有出现错误时才弹 Toast,Toast 上带「查看日志」按钮。
|
||||
- 面板高度可拖动,默认 240 px,记住用户上次的高度。
|
||||
- 三个页签:
|
||||
- **活动**:结构化的里程碑,例如「已创建磁盘」「OpenCore 下载完成」「已启动」;
|
||||
- **输出**:原始输出,可按 VM 和级别筛选;
|
||||
- **串口**:当前 VM 的串口日志。
|
||||
- **自动跟随到底部**:用户手动往上翻时暂停跟随,并出现「跳到最新」按钮。
|
||||
- **进度行合并**:同一个下载任务的 `x% of y MB` 只占一行并原地更新,不再一行一个百分比。
|
||||
- 保留最近 2000 行,超过就截断;行数多了再考虑虚拟滚动。
|
||||
|
||||
### 5.3 操作反馈
|
||||
|
||||
- 每个 VM 操作都通过 `useVMAction` 发起,返回 `pending` 状态。按钮进入忙碌态(转圈 + 禁用),防止重复点击。
|
||||
- 操作成功:轻量 Toast(「macos-tahoe 已关机」),3 秒后自动消失。
|
||||
- 操作失败:Toast 显示本地化的错误 + 建议操作 + 「查看日志」。不再用红色横幅占住内容区顶部。
|
||||
- 删除改用自定义确认框(Radix AlertDialog),内容包括:
|
||||
- 将删除的内容和磁盘占用;
|
||||
- 勾选项「保留磁盘文件」,对应后端已有的 `keepFiles` 参数;
|
||||
- 「此操作无法撤销」的提示。
|
||||
|
||||
## 6. 后端配合改动
|
||||
|
||||
改版需要后端补的接口。按优先级排列,P0 列标「是」的属于第一阶段。
|
||||
|
||||
| # | 改动 | 说明 | P0 |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| B1 | 结构化任务事件 `reims:task` | `{id, vm, kind, phase, percent, done_bytes, total_bytes, status, error_code}`。由 `logWriter` 解析上游的进度行生成;上游输出格式出自哪个文件、哪一行**待验证**,拿到上游 commit 和行号后再写解析器 | 已完成(2026-11-28,见表下说明) |
|
||||
| B2 | 日志带级别和类别 | `LogEntry` 增加 `level`(info / warn / error)和 `kind`(milestone / progress / raw) | 否 |
|
||||
| B3 | 用户可见文案改成发 i18n 键 | `emitLog` 里的 `"Starting "+name` 这类拼接改为 `{key, params}`,由前端翻译;上游原始输出保持原样,归入 `raw` | 否 |
|
||||
| B4 | 结构化错误 | 错误返回 `{code, message, hint}`,`message` 和 `hint` 已经本地化 | 否 |
|
||||
| B5 | `FocusVMWindow(name)` | 按 QEMU 的 PID 枚举顶层窗口,还原并置前(Win32 `EnumWindows` + `SetForegroundWindow`)。系统的前台锁限制下能否成功**待验证** | 否 |
|
||||
| B6 | 运行时信息 | `uptime`(来自进程启动时间)、是否已绑核、磁盘虚拟容量与实际占用(`qemu-img info`,现有 `VMDetail` 只有文件名)。CPU / 内存占用留到 M3.2 的 QMP | 否 |
|
||||
| B7 | 「正在创建」状态 | `CreateVM` 开始时写入 `transitions[name]="creating"`,侧边栏立刻出现这台 VM | 否 |
|
||||
| B8 | `OpenVMFolder(name)` | 在资源管理器中打开 VM 目录 | 是(很简单) |
|
||||
|
||||
前端在 P0 阶段先自己处理 B1、B2 能覆盖的部分:用正则把进度行合并成一行,按 `error` 关键字粗略分级。等 B1、B2 上线后删掉这段兼容代码。
|
||||
|
||||
**B1 已完成(2026-11-28)**:
|
||||
|
||||
- **后端**:`tasks.go` 维护任务列表,通过 `reims:task` 事件推送。字段有 `kind`、`subject`、`step`、`done`、`total`、`percent`、`rate`、`status`、`cancelable`。每个任务的进度事件最多每 200 ms 发一次,步骤变化和结束状态总是立即发出。
|
||||
- **进度来源**:
|
||||
- 安装包下载直接读 reims-util 的 JSON 事件;
|
||||
- 创建 VM 时,把 reims-ctl 输出里的进度行转成任务进度。进度行格式见上游 `3731afd` 的 `reims_util.rs:480-488`。日志里每个步骤只记一行。
|
||||
- **前端**:用正则合并进度行的兼容代码已删除。状态栏显示当前任务的中文标题和百分比;Tooltip 里是上游原文的步骤、已下载 / 总量和速度。下载可以暂停。
|
||||
- **验证情况**:在实际界面中验证过下载进度、暂停、续传和暂停提示。创建 VM 时的任务进度只有单元测试覆盖。
|
||||
|
||||
## 7. 前端工程
|
||||
|
||||
### 7.1 依赖(待决策 D2)
|
||||
|
||||
| 依赖 | 用途 | 理由 |
|
||||
| :-- | :-- | :-- |
|
||||
| `@radix-ui/react-*`(Dialog、AlertDialog、DropdownMenu、ContextMenu、Tooltip、Toast、Tabs、Progress、Collapsible) | 无样式的交互基件 | 焦点管理、键盘操作、无障碍都现成,样式完全由我们的令牌控制 |
|
||||
| `lucide-react` | 图标 | 替代手写的 `Icons.tsx`,风格统一 |
|
||||
| `zustand` | 状态 | 把 `App.tsx` 里的十几个 `useState` 拆成 store,事件订阅集中管理 |
|
||||
|
||||
不引入 Tailwind,也不引入完整组件库(MUI、Ant Design 之类),保持体积小、外观可控。
|
||||
|
||||
### 7.2 目录结构
|
||||
|
||||
```text
|
||||
src/
|
||||
app/ AppShell, TitleBar, Sidebar, StatusBar
|
||||
features/
|
||||
vm/ VMPage, VMHeader, VMActionsMenu, InstallGuide, SummaryRow, TechDetails, BrokenState, EmptyState
|
||||
create/ CreateWizard(沿用现有逻辑,换成新组件)
|
||||
settings/ SettingsModal(同上)
|
||||
host/ HostView, Preferences
|
||||
tasks/ taskStore, TaskIndicator
|
||||
logs/ logStore, LogPanel, useStickToBottom
|
||||
ui/ Button, IconButton, Badge, StatusDot, Card, Dialog, Menu, Toast, Tooltip, Progress, Tabs(对 Radix 的封装)
|
||||
lib/ format.ts, i18n.ts, errors.ts
|
||||
store/ appStore(state, selection, 事件订阅)
|
||||
styles/ tokens.css, base.css
|
||||
```
|
||||
|
||||
### 7.3 键盘与无障碍
|
||||
|
||||
- 侧边栏做成 listbox:`↑` / `↓` 选择,`Enter` 进入;右键菜单与「⋯」菜单内容一致。
|
||||
- 快捷键:
|
||||
- `Ctrl+N` 新建
|
||||
- `Ctrl+,` 设置
|
||||
- `Ctrl+L` 日志
|
||||
- `Ctrl+Enter` 执行当前主操作
|
||||
- 所有可交互元素都是真正的 `<button>` 或带 role 的元素,并有 `:focus-visible` 焦点环。
|
||||
|
||||
### 7.4 窗口与 DPI
|
||||
|
||||
- 最小窗口尺寸 960 × 640。
|
||||
- 内容区最大宽度 960,概要卡片用 `grid-template-columns: repeat(auto-fit, minmax(180px, 1fr))` 自动换行。
|
||||
- 在 100% / 125% / 150% 缩放下逐一检查,不允许出现截断。
|
||||
|
||||
## 8. 分阶段计划
|
||||
|
||||
### 阶段 0:修硬伤(1–2 天,不改后端,除了 B8)
|
||||
|
||||
> 2026-11-28 已完成,B8 也已上线(`OpenVMFolder`)。以下内容原属阶段 1,这次提前做了,避免在旧结构上返工:
|
||||
> - VM 页头和「⋯」菜单(D1);
|
||||
> - Toast;
|
||||
> - 概要行(图标 + 数值)和技术信息折叠区;
|
||||
> - 引入 Radix 和 lucide。
|
||||
>
|
||||
> 装机步骤条还是静态的三步列表,可交互、能记住进度的步骤条留到阶段 1。
|
||||
|
||||
- 去掉重复的操作出口(工具栏里的弹出安装盘、页头的删除、配置概览旁的串口日志)。
|
||||
- 日志抽屉不再自动展开、自动跟随到底部、合并进度行。
|
||||
- 显卡名称反查,隐藏 ICD 路径、CPU 型号和运行时哈希。
|
||||
- 操作按钮加忙碌态;删除改为自定义确认框,并提供「保留磁盘文件」。
|
||||
- 引入 `tokens.css`、统一字阶和 Windows 字体栈;清掉内联样式。
|
||||
- 按 4.5 精简文案:次要操作改成纯图标按钮并加 Tooltip,删掉安装盘横幅和「配置概览」标题,统一状态词。
|
||||
- 侧边栏支持键盘操作,补上焦点样式。
|
||||
|
||||
**完成标准**:
|
||||
|
||||
- 截图里列出的 P2、P3、P5、P6 现象全部消失;
|
||||
- 同一屏里任何操作只出现一次;
|
||||
- 主视图不出现路径、哈希或 QEMU 内部名。
|
||||
|
||||
### 阶段 1:结构改版(约 1 周,需要 B1–B4、B7)
|
||||
|
||||
- 引入 Radix、lucide、zustand,按 7.2 拆分目录。
|
||||
- 实现新页头(按状态切换主操作)、「⋯」菜单、右键菜单。
|
||||
- 状态栏 + 任务进度 + 三页签日志面板。
|
||||
- 装机步骤条、概要卡片、技术信息折叠区。
|
||||
- 空状态、正在创建、配置损坏三个状态页。
|
||||
- 后端文案全部 i18n,错误结构化。
|
||||
|
||||
**完成标准**:
|
||||
|
||||
- 中文界面下除原始日志以外没有英文;
|
||||
- 任一操作点击后 100 ms 内有视觉反馈;
|
||||
- 只用键盘就能走完「选中 VM → 启动 → 打开设置」;
|
||||
- 125% 和 150% 缩放下没有截断。
|
||||
|
||||
### 阶段 2:体验补全(与 M3 并行)
|
||||
|
||||
- 「显示 VM 窗口」(B5)、运行时长与绑核状态(B6)。
|
||||
- 浅色主题。
|
||||
- 截屏缩略图(依赖 M3.2 的 QMP)、复制派生入口(M3.3)。
|
||||
- 一键导出排障包入口(M3.4)。
|
||||
|
||||
## 9. 决策记录
|
||||
|
||||
2026-11-28:D1–D4 全部按推荐方案采纳;`shell-design.md` 第 1 节和第 5 节已同步修订。D2 中的 Radix 和 lucide 在阶段 0 就引入,用来实现删除确认框、菜单和 Tooltip,避免先手写一遍再重做;zustand 和目录拆分仍放在阶段 1。
|
||||
|
||||
| # | 问题 | 推荐(已采纳) | 备选 |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| D1 | VM 操作放在顶部工具栏,还是放在 VM 页头 | **页头**:操作离对象近,切页时布局不跳。若采纳,同步修订 `shell-design.md` 第 5 节 | 保留工具栏,但只放当前状态的主操作,加一个「⋯」 |
|
||||
| D2 | 是否引入 Radix、lucide、zustand | **引入**:Dialog、菜单、Toast、焦点管理自己写成本高,而且容易做不完整 | 继续零依赖,手写这些基件 |
|
||||
| D3 | 主题 | **跟随系统,深浅两套** | 只做暗色 |
|
||||
| D4 | 「对齐 macOS」的边界 | **结构和术语对齐 macOS**(侧边栏、分步助手、设置分页、VZ 词表),**渲染层面按 Windows 平台来**(字体、窗口控件、DPI)。若采纳,修订 `shell-design.md` 第 1 节「视觉按 macOS 来做」这句 | 视觉也继续模仿 macOS |
|
||||
@@ -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,15 +1,17 @@
|
||||
{
|
||||
"name": "reims-go-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.8",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"build": "tsc --noEmit && vite build && node scripts/check-ui-contract.mjs",
|
||||
"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
|
||||
fd01023ab020f4fa559696be6708a9a3
|
||||
@@ -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,61 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
const rootDir = path.resolve(__dirname, '..')
|
||||
const srcDir = path.join(rootDir, 'src')
|
||||
|
||||
const contractSrc = fs.readFileSync(path.join(srcDir, 'styles', 'ui-contract.ts'), 'utf8')
|
||||
const tokensCss = fs.readFileSync(path.join(srcDir, 'styles', 'tokens.css'), 'utf8')
|
||||
|
||||
function extractArray(name) {
|
||||
const re = new RegExp(`export const ${name} = \\[([\\s\\S]*?)\\] as const`)
|
||||
const m = contractSrc.match(re)
|
||||
if (!m) throw new Error(`Could not parse ${name} from ui-contract.ts`)
|
||||
return [...m[1].matchAll(/'([^']+)'/g)].map((x) => x[1])
|
||||
}
|
||||
|
||||
const apiMatch = contractSrc.match(/UI_API_VERSION\s*=\s*'([^']+)'/)
|
||||
const uiApi = apiMatch ? apiMatch[1] : '1.0.0'
|
||||
const parts = extractArray('UI_CONTRACT_PARTS')
|
||||
const stateAttrs = extractArray('UI_CONTRACT_STATE_ATTRS')
|
||||
const slots = extractArray('UI_CONTRACT_SLOTS')
|
||||
const tokens = extractArray('UI_CONTRACT_TOKENS')
|
||||
|
||||
// Collect all React component TSX source text (excluding contract/SDK/theme helpers)
|
||||
// and verify every declared part class is emitted as a distinct class token (§5.1, M17).
|
||||
function readComponentTsx(dir) {
|
||||
let buf = ''
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) buf += readComponentTsx(full)
|
||||
else if (entry.name.endsWith('.tsx')) buf += '\n' + fs.readFileSync(full, 'utf8')
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
const allTsx = readComponentTsx(srcDir)
|
||||
const missingParts = parts.filter((p) => {
|
||||
const re = new RegExp(`(?<![a-zA-Z0-9_-])${p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![a-zA-Z0-9_-])`)
|
||||
return !re.test(allTsx)
|
||||
})
|
||||
const missingTokens = tokens.filter((tk) => !tokensCss.includes(`${tk}:`))
|
||||
|
||||
if (missingParts.length > 0) {
|
||||
console.error('[ui-contract] ERROR: contract parts not emitted by any component:', missingParts.join(', '))
|
||||
process.exit(1)
|
||||
}
|
||||
if (missingTokens.length > 0) {
|
||||
console.error('[ui-contract] ERROR: contract tokens missing in tokens.css:', missingTokens.join(', '))
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const out = { uiApi, tokens, parts, stateAttrs, slots }
|
||||
const jsonText = JSON.stringify(out, null, 2) + '\n'
|
||||
fs.writeFileSync(path.join(rootDir, 'ui-contract.json'), jsonText, 'utf8')
|
||||
const distDir = path.join(rootDir, 'dist')
|
||||
if (fs.existsSync(distDir)) {
|
||||
fs.writeFileSync(path.join(distDir, 'ui-contract.json'), jsonText, 'utf8')
|
||||
}
|
||||
console.log(`[ui-contract] OK (uiApi=${uiApi}, parts=${parts.length}, tokens=${tokens.length}, slots=${slots.length})`)
|
||||
@@ -0,0 +1,221 @@
|
||||
import { Copy, Download, ExternalLink, RotateCw } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
import { AppUpdateInfo, Locale, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
import { REPO_URL } from './TitleMenus'
|
||||
import type { UpdatePhase } from './UpdateCapsule'
|
||||
|
||||
const QQ_GROUP_ID = '1136042744'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
appVersion?: string
|
||||
/** Latest update check, shared with the sidebar's update button. */
|
||||
appUpdate: AppUpdateInfo | null
|
||||
onAppUpdate: (info: AppUpdateInfo) => void
|
||||
updatePhase: UpdatePhase
|
||||
updateTask: Task | null
|
||||
/** The swap has started and the app is about to restart. */
|
||||
installing: boolean
|
||||
onDownloadUpdate: () => void
|
||||
onCancelUpdate: () => void
|
||||
onInstallUpdate: () => void
|
||||
onCopy?: (text: string) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/** About page: version and updates, project links and the community group. */
|
||||
export const AboutPage: React.FC<Props> = ({
|
||||
locale, appVersion, appUpdate, onAppUpdate, updatePhase, updateTask, installing,
|
||||
onDownloadUpdate, onCancelUpdate, onInstallUpdate, onCopy, onError,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [checkingUpdate, setCheckingUpdate] = useState(false)
|
||||
const [updateErr, setUpdateErr] = useState('')
|
||||
const [qqInstalled, setQQInstalled] = useState<boolean | null>(null)
|
||||
const [openingQQ, setOpeningQQ] = useState(false)
|
||||
const [qqLaunchErr, setQQLaunchErr] = useState('')
|
||||
|
||||
const runUpdateCheck = async (force: boolean) => {
|
||||
setCheckingUpdate(true)
|
||||
setUpdateErr('')
|
||||
try {
|
||||
onAppUpdate(await api.CheckAppUpdate(force))
|
||||
} catch (e) {
|
||||
setUpdateErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
setCheckingUpdate(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!appUpdate) void runUpdateCheck(false)
|
||||
let cancelled = false
|
||||
api.CanOpenQQGroup()
|
||||
.then((ok) => { if (!cancelled) setQQInstalled(!!ok) })
|
||||
.catch(() => { if (!cancelled) setQQInstalled(false) })
|
||||
return () => { cancelled = true }
|
||||
}, [])
|
||||
|
||||
const openURL = (url: string) => {
|
||||
api.OpenURL(url).catch((e) => onError(tr('failGeneric'), e))
|
||||
}
|
||||
|
||||
const openQQGroup = async () => {
|
||||
setOpeningQQ(true)
|
||||
setQQLaunchErr('')
|
||||
try {
|
||||
await api.OpenQQGroup()
|
||||
} catch (e) {
|
||||
const msg = String(e).replace(/^Error:\s*/, '')
|
||||
if (/qq not installed/i.test(msg)) {
|
||||
setQQInstalled(false)
|
||||
} else {
|
||||
setQQLaunchErr(msg)
|
||||
}
|
||||
} finally {
|
||||
setOpeningQQ(false)
|
||||
}
|
||||
}
|
||||
|
||||
const version = appVersion ?? appUpdate?.current ?? ''
|
||||
const pct = updateTask && updateTask.percent >= 0 ? Math.round(updateTask.percent) : null
|
||||
|
||||
let updateSub: React.ReactNode = null
|
||||
if (updatePhase === 'downloading') {
|
||||
updateSub = (
|
||||
<>
|
||||
<div className="row-sub">{tr('updateDownloadingSub', { v: appUpdate?.latest ?? '' })}{updateTask && taskDetail(updateTask) ? ` · ${taskDetail(updateTask)}` : ''}</div>
|
||||
<span className="progress about-update-progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${(pct ?? 0) / 100})` }} />
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
} else if (updatePhase === 'ready') {
|
||||
updateSub = <div className="row-sub">{tr('updateReadySub', { v: appUpdate?.latest ?? '' })}</div>
|
||||
} else if (updatePhase === 'failed') {
|
||||
updateSub = <div className="row-sub warn-text" title={updateTask?.error}>{tr('updateFailedSub')}</div>
|
||||
} else if (appUpdate?.has_update) {
|
||||
updateSub = <div className="row-sub">{tr('appUpdateAvailable', { v: appUpdate.latest })}</div>
|
||||
} else if (updateErr) {
|
||||
updateSub = <div className="row-sub" title={updateErr}>{tr('appUpdateLookupFailed')}</div>
|
||||
}
|
||||
|
||||
let updateAction: React.ReactNode
|
||||
if (updatePhase === 'downloading') {
|
||||
updateAction = <Button onClick={onCancelUpdate}>{tr('updateCancel')}</Button>
|
||||
} else if (updatePhase === 'ready') {
|
||||
updateAction = <Button variant="primary" busy={installing} onClick={onInstallUpdate}>{tr('updateRestart')}</Button>
|
||||
} else if (updatePhase === 'failed') {
|
||||
updateAction = <Button variant="primary" icon={<RotateCw size={14} aria-hidden="true" />} onClick={onDownloadUpdate}>{tr('updateRetry')}</Button>
|
||||
} else if (updatePhase === 'available') {
|
||||
updateAction = <Button variant="primary" icon={<Download size={14} aria-hidden="true" />} onClick={onDownloadUpdate}>{tr('updateDownloadInstall')}</Button>
|
||||
} else {
|
||||
updateAction = <Button busy={checkingUpdate} onClick={() => void runUpdateCheck(true)}>{tr('appCheckUpdate')}</Button>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page about-page">
|
||||
<header className="about-hero">
|
||||
<img className="about-hero-mark" src="/logo.svg" alt="" aria-hidden="true" />
|
||||
<div className="about-hero-text">
|
||||
<h1>Reims-Go</h1>
|
||||
<p>{tr('aboutTagline')}</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="section">
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('appVersionTitle')} <span className="mono">{version}</span>
|
||||
{appUpdate && !appUpdate.has_update && (
|
||||
<span className="badge badge-ok">{tr('appUpToDate')}</span>
|
||||
)}
|
||||
</div>
|
||||
{updateSub}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{appUpdate?.has_update && appUpdate.page_url && (
|
||||
<Button variant="ghost" icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(appUpdate.page_url!)}>
|
||||
{tr('updateReleaseNotes')}
|
||||
</Button>
|
||||
)}
|
||||
{updateAction}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('aboutCommunity')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('helpProjectPage')}</div>
|
||||
<div className="row-sub">{tr('aboutProjectSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(REPO_URL)}>
|
||||
{tr('openShort')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('helpReportIssue')}</div>
|
||||
<div className="row-sub">{tr('aboutIssueSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(`${REPO_URL}/issues`)}>
|
||||
{tr('openShort')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('aboutQQGroup')} <span className="mono">{QQ_GROUP_ID}</span>
|
||||
{qqInstalled === false && (
|
||||
<span className="badge">{tr('aboutQQNotInstalled')}</span>
|
||||
)}
|
||||
</div>
|
||||
{qqInstalled === false ? (
|
||||
<div className="row-sub">{tr('aboutQQNotInstalledSub')}</div>
|
||||
) : qqLaunchErr ? (
|
||||
<div className="row-sub" title={qqLaunchErr}>{tr('aboutQQLaunchFailed')}</div>
|
||||
) : (
|
||||
<div className="row-sub">{tr('aboutQQGroupSub')}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{qqInstalled && !qqLaunchErr ? (
|
||||
<>
|
||||
{onCopy && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('aboutCopyQQGroup')}
|
||||
icon={<Copy size={14} aria-hidden="true" />}
|
||||
onClick={() => onCopy(QQ_GROUP_ID)}
|
||||
/>
|
||||
)}
|
||||
<Button busy={openingQQ} icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => void openQQGroup()}>
|
||||
{tr('aboutJoinQQGroup')}
|
||||
</Button>
|
||||
</>
|
||||
) : onCopy ? (
|
||||
<Button icon={<Copy size={14} aria-hidden="true" />} onClick={() => onCopy(QQ_GROUP_ID)}>
|
||||
{tr('aboutCopyQQGroup')}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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,142 @@
|
||||
import React from 'react'
|
||||
import { getLocaleOptions, I18nKey, t } from '../i18n'
|
||||
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
import { AppState, Locale, ResolvedLocalePack } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { PopupSelect, Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
export type ThemeMode = 'light' | 'dark' | 'system'
|
||||
|
||||
interface Props {
|
||||
state: AppState
|
||||
locale: Locale
|
||||
locales?: ResolvedLocalePack[]
|
||||
themeMode: ThemeMode
|
||||
canLight?: boolean
|
||||
canDark?: boolean
|
||||
onThemeMode: (mode: ThemeMode) => void
|
||||
onSetLocale: (l: Locale) => void
|
||||
onRefresh: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
export const AppSettingsPage: React.FC<Props> = ({
|
||||
state, locale, locales, themeMode, canLight = true, canDark = true, onThemeMode, onSetLocale, onRefresh, onError,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { host, config, optimizations } = state
|
||||
|
||||
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
|
||||
|
||||
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 rg-p-settings">
|
||||
<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>
|
||||
{(!canDark || !canLight) && (
|
||||
<div className="row-sub">{tr(!canDark ? 'themePluginDarkDisabled' : 'themePluginLightDisabled')}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Segmented
|
||||
label={tr('themeLabel')}
|
||||
value={themeMode}
|
||||
onChange={onThemeMode}
|
||||
options={[
|
||||
{ value: 'light', label: tr('themeLight'), disabled: !canLight },
|
||||
{ value: 'dark', label: tr('themeDark'), disabled: !canDark },
|
||||
{ value: 'system', label: tr('themeSystem'), disabled: !canLight || !canDark },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('language')}</div>
|
||||
<div className="row-sub">{tr('languageSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<PopupSelect
|
||||
label={tr('language')}
|
||||
value={locale}
|
||||
onChange={onSetLocale}
|
||||
options={getLocaleOptions(locales)}
|
||||
/>
|
||||
</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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import React from 'react'
|
||||
import { events } from '../wails'
|
||||
|
||||
interface State {
|
||||
error: Error | null
|
||||
stack: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Top-level React error boundary: prevents any uncaught render/lifecycle error
|
||||
* from unmounting the entire tree into an unrecoverable blank white screen,
|
||||
* reports the stack trace to the Go backend log, and offers a one-click reload.
|
||||
*/
|
||||
export class ErrorBoundary extends React.Component<{ children: React.ReactNode }, State> {
|
||||
state: State = { error: null, stack: '' }
|
||||
|
||||
static getDerivedStateFromError(error: Error): Partial<State> {
|
||||
return { error }
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: React.ErrorInfo): void {
|
||||
const stack = [error.stack, info.componentStack].filter(Boolean).join('\n').trim()
|
||||
this.setState({ stack })
|
||||
events.emitUIError(`ReactErrorBoundary: ${error.message}\n${stack.slice(0, 1500)}`)
|
||||
}
|
||||
|
||||
render(): React.ReactNode {
|
||||
const { error, stack } = this.state
|
||||
if (!error) return this.props.children
|
||||
|
||||
const isZh = (document.documentElement.lang || '').toLowerCase().startsWith('zh')
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
height: '100%',
|
||||
padding: 24,
|
||||
background: 'var(--surface-canvas, #1c1c1e)',
|
||||
color: 'var(--text, #f5f5f7)',
|
||||
fontFamily: 'var(--font-sans, system-ui, sans-serif)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
maxWidth: 560,
|
||||
width: '100%',
|
||||
padding: 20,
|
||||
borderRadius: 12,
|
||||
border: '1px solid var(--border, rgba(128,128,128,0.25))',
|
||||
background: 'var(--surface-1, rgba(128,128,128,0.08))',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 12,
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: 0, fontSize: 16 }}>
|
||||
{isZh ? '界面发生异常' : 'Interface encountered an error'}
|
||||
</h2>
|
||||
<p style={{ margin: 0, fontSize: 13, opacity: 0.85 }}>
|
||||
{isZh
|
||||
? '渲染过程出现未捕获异常,虚拟机和后台服务不受影响。你可以重新加载界面。'
|
||||
: 'An unexpected UI error occurred. Running VMs and background services are unaffected.'}
|
||||
</p>
|
||||
<pre
|
||||
style={{
|
||||
margin: 0,
|
||||
padding: 10,
|
||||
borderRadius: 8,
|
||||
fontSize: 12,
|
||||
maxHeight: 180,
|
||||
overflow: 'auto',
|
||||
background: 'var(--surface-0, rgba(0,0,0,0.2))',
|
||||
border: '1px solid var(--border, rgba(128,128,128,0.2))',
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-word',
|
||||
}}
|
||||
>
|
||||
{error.message || String(error)}
|
||||
{stack ? `\n\n${stack}` : ''}
|
||||
</pre>
|
||||
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={() => window.location.reload()}
|
||||
>
|
||||
{isZh ? '重新加载界面' : 'Reload UI'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,38 @@
|
||||
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, Task } from '../types'
|
||||
import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format'
|
||||
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: (candidate: boolean) => void
|
||||
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, runtimeTask, onChannel, onInstallRuntime, onCancelTask }) => {
|
||||
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, onError, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask }) => {
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
const [storage, setStorage] = useState<StorageBreakdown | null>(null)
|
||||
const { host, config, runtimes } = 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 whpx = {
|
||||
ready: { short: tr('whpxReady'), hint: '', tone: 'ok' },
|
||||
no_hypervisor: { short: tr('whpxNoHvShort'), hint: tr('whpxNoHv'), tone: 'warn' },
|
||||
@@ -42,20 +51,15 @@ 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)
|
||||
})
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -74,31 +78,91 @@ 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')}
|
||||
@@ -109,81 +173,26 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
<div className="list">
|
||||
<RuntimeOnline
|
||||
locale={locale}
|
||||
channel={config.runtime_channel === 'candidate' ? 'candidate' : 'stable'}
|
||||
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}
|
||||
/>
|
||||
</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>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('hostSystem')}</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>
|
||||
</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>
|
||||
<div className="row-right"><Button onClick={pickDataRoot}>{tr('choose')}</Button></div>
|
||||
</div>
|
||||
{host.has_hybrid_cores && (
|
||||
<div className="row">
|
||||
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
|
||||
<div className="row" key={rt.commit}>
|
||||
<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-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">
|
||||
<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>
|
||||
<Button onClick={guard(() => api.UseRuntime(rt.commit))}>{tr('activate')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -193,36 +202,48 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
{realGPUs.length === 0 ? (
|
||||
<div className="row"><span className="row-sub">—</span></div>
|
||||
) : (
|
||||
realGPUs.map((g) => (
|
||||
<div className="row" key={g.vulkan_icd}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{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>}
|
||||
realGPUs.map((g, idx) => {
|
||||
const meta = gpuMetaLine(g)
|
||||
const hint = gpuCompatHint(locale, g)
|
||||
const isRec = sameGPU(host.recommended_gpu, g)
|
||||
return (
|
||||
<div className="row" key={gpuKey(g, idx)}>
|
||||
<div className="row-main">
|
||||
<div className="row-title" title={g.vulkan_icd}>
|
||||
{g.name}
|
||||
<span className={`badge ${g.kind === 'discrete' ? 'badge-accent' : ''}`}>{gpuKind(g.kind)}</span>
|
||||
{g.compat === 'unsupported' && <span className="badge badge-warn">{tr('gpuCompatUnsupported')}</span>}
|
||||
{g.compat === 'warn' && <span className="badge badge-warn">{tr('gpuCompatWarn')}</span>}
|
||||
{isRec && g.compat !== 'warn' && g.compat !== 'unsupported' && <span className="badge badge-ok">{tr('gpuRecommended')}</span>}
|
||||
</div>
|
||||
{meta && <div className="row-sub">{meta}</div>}
|
||||
{hint && <div className="row-sub warn-text">{hint}</div>}
|
||||
</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('offlineListFailedDetail', { err: 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">
|
||||
<div className="logbar">
|
||||
{task && (
|
||||
<div className="logs rg-p-logpanel">
|
||||
{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 rg-p-statusbar">
|
||||
{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,33 @@ 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} />
|
||||
)}
|
||||
<span className="rg-slot-inline" data-rg-slot="statusbar.right" />
|
||||
{!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,125 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { Locale, PanelContribution } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
import { locText } from './SchemaForm'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
panel: PanelContribution
|
||||
assetToken: string
|
||||
appearance: 'light' | 'dark'
|
||||
}
|
||||
|
||||
/**
|
||||
* Sandboxed L4 iframe panel with strict bridge verification (§4.2, §7.3):
|
||||
* - `sandbox="allow-scripts"` (no allow-same-origin, no top-navigation)
|
||||
* - Only responds to postMessage where `event.source === iframe.contentWindow`
|
||||
* - Routes all Host API calls through Go `PanelBridgeCall` for permission & rate checks
|
||||
* - Syncs theme tokens into iframe and provides error placeholder + retry.
|
||||
*/
|
||||
const RE_SAFE_TOKEN = /^[a-f0-9]+$/
|
||||
const RE_SAFE_PLUGIN_ID = /^[a-z0-9][a-z0-9._-]*$/
|
||||
const RE_SAFE_ENTRY_SEG = /^[a-zA-Z0-9._@ -]+$/
|
||||
|
||||
function buildSafePanelSrc(assetToken: string, pluginId: string | undefined, entry: string | undefined): string | null {
|
||||
if (!assetToken || !RE_SAFE_TOKEN.test(assetToken)) return null
|
||||
if (!pluginId || !RE_SAFE_PLUGIN_ID.test(pluginId) || pluginId.includes('..')) return null
|
||||
const raw = (entry || 'index.html').trim().replace(/^\/+/, '')
|
||||
if (!raw || raw.includes('\\') || raw.includes('?') || raw.includes('#') || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(raw)) {
|
||||
return null
|
||||
}
|
||||
const segs = raw.split('/')
|
||||
for (const seg of segs) {
|
||||
if (!seg || seg === '.' || seg === '..' || !RE_SAFE_ENTRY_SEG.test(seg)) return null
|
||||
}
|
||||
return `/plugin-assets/${encodeURIComponent(assetToken)}/${encodeURIComponent(pluginId)}/${segs.map(encodeURIComponent).join('/')}`
|
||||
}
|
||||
|
||||
export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, appearance }) => {
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null)
|
||||
const [failed, setFailed] = useState(false)
|
||||
const [nonce, setNonce] = useState(0)
|
||||
|
||||
const src = buildSafePanelSrc(assetToken, panel.pluginId, panel.entry)
|
||||
|
||||
const syncTheme = () => {
|
||||
const win = iframeRef.current?.contentWindow
|
||||
if (!win) return
|
||||
const cs = getComputedStyle(document.documentElement)
|
||||
const tokens: Record<string, string> = {}
|
||||
for (const k of ['--surface-0', '--surface-1', '--text', '--text-2', '--border', '--accent', '--font-sans']) {
|
||||
tokens[k] = cs.getPropertyValue(k).trim()
|
||||
}
|
||||
win.postMessage({ type: 'reims:theme', appearance, locale, tokens }, '*')
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
syncTheme()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [appearance, locale])
|
||||
|
||||
useEffect(() => {
|
||||
if (!src) return
|
||||
let cancelled = false
|
||||
|
||||
const onMessage = async (e: MessageEvent) => {
|
||||
const win = iframeRef.current?.contentWindow
|
||||
// Strict origin + window identity check for sandbox="allow-scripts" opaque origin (§7.3).
|
||||
if (!win || e.source !== win || e.origin !== 'null') return
|
||||
const msg = e.data
|
||||
if (!msg || typeof msg !== 'object' || msg.type !== 'reims:rpc' || typeof msg.id !== 'string' || typeof msg.method !== 'string') return
|
||||
const rawParams = msg.params
|
||||
const params: Record<string, unknown> =
|
||||
rawParams && typeof rawParams === 'object' && !Array.isArray(rawParams)
|
||||
? (rawParams as Record<string, unknown>)
|
||||
: {}
|
||||
try {
|
||||
const result = await api.PanelBridgeCall(panel.pluginId ?? '', msg.method, params)
|
||||
if (cancelled || iframeRef.current?.contentWindow !== win) return
|
||||
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result }, '*')
|
||||
} catch (err) {
|
||||
if (cancelled || iframeRef.current?.contentWindow !== win) return
|
||||
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: false, error: String(err) }, '*')
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('message', onMessage)
|
||||
return () => {
|
||||
cancelled = true
|
||||
window.removeEventListener('message', onMessage)
|
||||
}
|
||||
}, [panel.pluginId, nonce, src])
|
||||
|
||||
if (failed || !src) {
|
||||
return (
|
||||
<div className="plugin-panel-error">
|
||||
<span>{t(locale, 'panelLoadFailed')}</span>
|
||||
{src && (
|
||||
<Button onClick={() => { setFailed(false); setNonce((n) => n + 1) }}>
|
||||
{t(locale, 'installersRetry')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="plugin-panel-wrap">
|
||||
<div className="plugin-panel-head">{locText(panel.title, locale, panel.id)}</div>
|
||||
<iframe
|
||||
key={nonce}
|
||||
ref={iframeRef}
|
||||
className="plugin-panel-frame"
|
||||
title={locText(panel.title, locale, panel.id)}
|
||||
src={src}
|
||||
sandbox="allow-scripts"
|
||||
referrerPolicy="no-referrer"
|
||||
style={{ height: Math.max(120, Math.min(480, panel.height || 220)) }}
|
||||
onLoad={syncTheme}
|
||||
onError={() => setFailed(true)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,739 @@
|
||||
import {
|
||||
AlertTriangle, BadgeCheck, Boxes, Clipboard, Code2, Compass, Cpu, Disc3, FolderOpen, Keyboard,
|
||||
Layers, Monitor, PackagePlus, Palette, Puzzle, RefreshCw, RotateCcw, Search,
|
||||
Settings2, Shield, ShieldAlert, ShieldCheck, Sparkles, Terminal, Trash2,
|
||||
} from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import {
|
||||
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions,
|
||||
} from '../types'
|
||||
import { Button, IconButton, Tip } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { PopupSelect, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
import { PluginPanelFrame } from './PluginPanelFrame'
|
||||
import { SchemaForm, locText } from './SchemaForm'
|
||||
|
||||
// Search only earns its space once the list is long enough to scan.
|
||||
const SEARCH_THRESHOLD = 12
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
appearance: 'light' | 'dark'
|
||||
safeMode?: boolean
|
||||
onRefresh: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onThemeChanged?: () => void
|
||||
}
|
||||
|
||||
interface PluginVisual {
|
||||
tone: string
|
||||
icon: React.ReactNode
|
||||
}
|
||||
|
||||
function resolvePluginVisual(p: PluginInfo): PluginVisual {
|
||||
if (p.system) return { tone: 'indigo', icon: <Boxes size={19} aria-hidden="true" /> }
|
||||
const id = p.id.toLowerCase()
|
||||
const perms = new Set((p.permissions ?? []).map((x) => x.name))
|
||||
if (id.includes('theme') || perms.has('ui:script')) {
|
||||
return { tone: 'purple', icon: <Palette size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('driver') || perms.has('driver:vm') || perms.has('runtime:provider')) {
|
||||
return { tone: 'indigo', icon: <Monitor size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('clipboard') || perms.has('host:clipboard')) {
|
||||
return { tone: 'sky', icon: <Clipboard size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('ime') || id.includes('input') || id.includes('wheel') || perms.has('input:filter')) {
|
||||
return { tone: 'rose', icon: <Keyboard size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('reboot')) {
|
||||
return { tone: 'amber', icon: <RotateCcw size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('whpx') || id.includes('irq')) {
|
||||
return { tone: 'emerald', icon: <Cpu size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('guide')) {
|
||||
return { tone: 'teal', icon: <Compass size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('offline') || id.includes('installer') || id.includes('helper')) {
|
||||
return { tone: 'teal', icon: <Disc3 size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (p.tier === 'L3') {
|
||||
return { tone: 'slate', icon: <Layers size={19} aria-hidden="true" /> }
|
||||
}
|
||||
return { tone: 'purple', icon: <Puzzle size={19} aria-hidden="true" /> }
|
||||
}
|
||||
|
||||
// The plugin settings dialog shows app-scope fields only; per-VM fields live in
|
||||
// each VM's settings. Same scope rule as SchemaForm.
|
||||
function hasAppSettings(p: PluginInfo): boolean {
|
||||
const schema = p.settings
|
||||
if (!schema) return false
|
||||
return Object.values(schema.properties ?? {}).some((prop) => (prop['x-scope'] || schema['x-scope'] || 'app') === 'app')
|
||||
}
|
||||
|
||||
/**
|
||||
* Dedicated top-level Plugins & Themes management page (§5.1, §8.1, §10).
|
||||
* Grouped inset list, same pattern as the installers page.
|
||||
*/
|
||||
export const PluginsPage: React.FC<Props> = ({
|
||||
locale, appearance, safeMode, onRefresh, onError, onThemeChanged,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [query, setQuery] = useState('')
|
||||
const [plugins, setPlugins] = useState<PluginInfo[]>([])
|
||||
const [contribs, setContribs] = useState<PluginUIContributions | null>(null)
|
||||
const [activeTheme, setActiveTheme] = useState<ActiveThemePayload | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [busyID, setBusyID] = useState('')
|
||||
const [approveTarget, setApproveTarget] = useState<PluginInfo | null>(null)
|
||||
const [approveChecked, setApproveChecked] = useState(false)
|
||||
const [settingsTarget, setSettingsTarget] = useState<PluginInfo | null>(null)
|
||||
const [settingsValues, setSettingsValues] = useState<Record<string, unknown>>({})
|
||||
const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null)
|
||||
const [removeTarget, setRemoveTarget] = useState<PluginInfo | null>(null)
|
||||
const [deleteSchemeTarget, setDeleteSchemeTarget] = useState<CustomThemeScheme | null>(null)
|
||||
|
||||
// Theme scheme editor state (§5.1)
|
||||
const [schemeEditorOpen, setSchemeEditorOpen] = useState(false)
|
||||
const [schemeName, setSchemeName] = useState('')
|
||||
const [seedAccent, setSeedAccent] = useState('#007aff')
|
||||
const [seedSurface, setSeedSurface] = useState('')
|
||||
|
||||
const reload = async () => {
|
||||
try {
|
||||
const [list, ui, th] = await Promise.all([
|
||||
api.ListPlugins(),
|
||||
api.GetPluginUIContributions(),
|
||||
api.GetActiveTheme(),
|
||||
])
|
||||
setPlugins(list ?? [])
|
||||
setContribs(ui)
|
||||
setActiveTheme(th)
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailLoad'), e)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => { void reload() }, [safeMode])
|
||||
|
||||
const togglePlugin = async (p: PluginInfo, enable: boolean) => {
|
||||
if (enable && p.needs_approval) {
|
||||
setApproveChecked(false)
|
||||
setApproveTarget(p)
|
||||
return
|
||||
}
|
||||
setBusyID(p.id)
|
||||
try {
|
||||
if (enable) await api.EnablePlugin(p.id, false)
|
||||
else await api.DisablePlugin(p.id)
|
||||
await reload()
|
||||
onRefresh()
|
||||
onThemeChanged?.()
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailToggle'), e)
|
||||
} finally {
|
||||
setBusyID('')
|
||||
}
|
||||
}
|
||||
|
||||
const confirmApprove = async () => {
|
||||
if (!approveTarget || !approveChecked) return
|
||||
const target = approveTarget
|
||||
setApproveTarget(null)
|
||||
setBusyID(target.id)
|
||||
try {
|
||||
await api.EnablePlugin(target.id, true)
|
||||
await reload()
|
||||
onRefresh()
|
||||
onThemeChanged?.()
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailEnable'), e)
|
||||
} finally {
|
||||
setBusyID('')
|
||||
}
|
||||
}
|
||||
|
||||
const importLocalZip = async () => {
|
||||
try {
|
||||
const path = await api.PickFile(tr('pluginImportTitle'), '*.zip')
|
||||
if (!path) return
|
||||
await api.InstallPluginArchive(path)
|
||||
await reload()
|
||||
onRefresh()
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailImport'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const linkDevDir = async () => {
|
||||
try {
|
||||
const dir = await api.PickDirectory(tr('pluginLinkDevTitle'))
|
||||
if (!dir) return
|
||||
await api.LinkPluginDev(dir)
|
||||
await reload()
|
||||
onRefresh()
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailLinkDev'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const removePlugin = async (p: PluginInfo) => {
|
||||
setBusyID(p.id)
|
||||
try {
|
||||
await api.RemovePlugin(p.id, false)
|
||||
await reload()
|
||||
onRefresh()
|
||||
onThemeChanged?.()
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailRemove'), e)
|
||||
} finally {
|
||||
setBusyID('')
|
||||
}
|
||||
}
|
||||
|
||||
const openPluginSettings = async (p: PluginInfo) => {
|
||||
try {
|
||||
const vals = await api.GetPluginSettings(p.id, '')
|
||||
setSettingsValues((vals ?? {}) as Record<string, unknown>)
|
||||
setSettingsTarget(p)
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailLoadSettings'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const savePluginSettings = async (next: Record<string, unknown>) => {
|
||||
setSettingsValues(next)
|
||||
if (!settingsTarget) return
|
||||
try {
|
||||
await api.SetPluginSettings(settingsTarget.id, '', next)
|
||||
onRefresh()
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailSaveSettings'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const openPluginLog = async (p: PluginInfo) => {
|
||||
try {
|
||||
const txt = await api.ReadPluginLog(p.id)
|
||||
setLogTarget({ id: p.id, text: txt || tr('pluginLogEmpty') })
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailReadLog'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const selectTheme = async (themeID: string, schemeID = '') => {
|
||||
try {
|
||||
await api.SetActiveTheme(themeID, schemeID)
|
||||
await reload()
|
||||
onThemeChanged?.()
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailSwitchTheme'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const saveScheme = async () => {
|
||||
if (!activeTheme || !schemeName.trim()) return
|
||||
const id = `custom-${Date.now()}`
|
||||
const scheme: CustomThemeScheme = {
|
||||
id,
|
||||
theme_id: activeTheme.theme_id,
|
||||
name: schemeName.trim(),
|
||||
appearance,
|
||||
seeds: {
|
||||
accent: seedAccent,
|
||||
...(seedSurface.trim() ? { surface: seedSurface.trim() } : {}),
|
||||
},
|
||||
}
|
||||
try {
|
||||
await api.SaveCustomThemeScheme(scheme)
|
||||
await api.SetActiveTheme(activeTheme.theme_id, id)
|
||||
setSchemeEditorOpen(false)
|
||||
setSchemeName('')
|
||||
setSeedSurface('')
|
||||
await reload()
|
||||
onThemeChanged?.()
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailSaveScheme'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const deleteScheme = async (schemeID: string) => {
|
||||
try {
|
||||
await api.DeleteCustomThemeScheme(schemeID)
|
||||
await reload()
|
||||
onThemeChanged?.()
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailDeleteScheme'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const q = query.trim().toLowerCase()
|
||||
const matchesFilter = (p: PluginInfo) => {
|
||||
if (!q) return true
|
||||
const name = locText(p.name, locale, p.id).toLowerCase()
|
||||
const desc = locText(p.description, locale, '').toLowerCase()
|
||||
return name.includes(q) || desc.includes(q) || p.id.toLowerCase().includes(q)
|
||||
}
|
||||
|
||||
// The always-on core goes first; the optional builtins keep backend order.
|
||||
const builtins = useMemo(
|
||||
() => plugins.filter((p) => p.source === 'builtin').sort((a, b) => Number(!!b.system) - Number(!!a.system)),
|
||||
[plugins],
|
||||
)
|
||||
const external = useMemo(() => plugins.filter((p) => p.source !== 'builtin'), [plugins])
|
||||
const filteredBuiltins = useMemo(() => builtins.filter(matchesFilter), [builtins, q, locale])
|
||||
const filteredExternal = useMemo(() => external.filter(matchesFilter), [external, q, locale])
|
||||
const themes = contribs?.themes ?? []
|
||||
const settingsPanels = (contribs?.panels ?? []).filter((p) => p.slot === 'settings.plugin')
|
||||
const presetSchemes = activeTheme?.theme?.schemes ?? []
|
||||
const customSchemes = (activeTheme?.custom_schemes ?? []).filter((s) => s.theme_id === activeTheme?.theme_id)
|
||||
const activeCount = useMemo(() => plugins.filter((p) => p.state === 'active').length, [plugins])
|
||||
|
||||
const activeThemeObj = themes.find((th) => th.id === (activeTheme?.theme_id || 'builtin.theme.default')) ?? themes[0]
|
||||
const activeSchemeSeeds = useMemo(() => {
|
||||
const base = { ...(activeTheme?.theme?.seeds ?? {}) }
|
||||
if (activeTheme?.active_scheme) {
|
||||
const custom = customSchemes.find((s) => s.id === activeTheme.active_scheme)
|
||||
const preset = presetSchemes.find((s) => s.id === activeTheme.active_scheme)
|
||||
if (custom?.seeds) return { ...base, ...custom.seeds }
|
||||
if (preset?.seeds) return { ...base, ...preset.seeds }
|
||||
}
|
||||
return base
|
||||
}, [activeTheme, customSchemes, presetSchemes])
|
||||
|
||||
const trustMeta = (trLevel: string) => {
|
||||
if (trLevel === 'official') return { label: tr('pluginTrustOfficial'), cls: 'is-official', icon: <BadgeCheck size={12} aria-hidden="true" /> }
|
||||
if (trLevel === 'verified') return { label: tr('pluginTrustVerified'), cls: 'is-verified', icon: <ShieldCheck size={12} aria-hidden="true" /> }
|
||||
if (trLevel === 'dev') return { label: tr('pluginTrustDev'), cls: 'is-dev', icon: <Code2 size={12} aria-hidden="true" /> }
|
||||
return { label: tr('pluginTrustCommunity'), cls: 'is-community', icon: <Shield size={12} aria-hidden="true" /> }
|
||||
}
|
||||
|
||||
// The switch already says on/off, so only surface states that need attention.
|
||||
const stateBadge = (p: PluginInfo) => {
|
||||
if (p.state === 'degraded') return <span className="badge badge-warn">{tr('pluginStateDegraded')}</span>
|
||||
if (p.state === 'failed') return <span className="badge badge-warn">{tr('pluginStateFailed')}</span>
|
||||
if (p.state === 'pending' && p.enabled) return <span className="badge">{tr('pluginStatePending')}</span>
|
||||
return null
|
||||
}
|
||||
|
||||
const renderRow = (p: PluginInfo) => {
|
||||
const visual = resolvePluginVisual(p)
|
||||
const isBuiltin = p.source === 'builtin'
|
||||
const trust = trustMeta(p.trust)
|
||||
const perms = p.permissions ?? []
|
||||
const highPerms = perms.filter((x) => x.level === 'high')
|
||||
const desc = locText(p.description, locale, '')
|
||||
const fault = p.error || p.degraded_reason
|
||||
const alert = fault || (p.needs_approval && highPerms.length > 0 ? tr('pluginHighRiskNotice') : '')
|
||||
|
||||
return (
|
||||
<div className={`row plugin-row${p.enabled ? ' is-enabled' : ''}`} key={p.id}>
|
||||
<div className={`plugin-app-icon tone-${visual.tone}`}>{visual.icon}</div>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="plugin-row-name">{locText(p.name, locale, p.id)}</span>
|
||||
{stateBadge(p)}
|
||||
</div>
|
||||
{desc && <div className="row-sub plugin-row-desc" title={desc}>{desc}</div>}
|
||||
{!isBuiltin && (
|
||||
<div className="row-sub plugin-row-meta">
|
||||
<span className={`plugin-trust ${trust.cls}`}>{trust.icon}{p.publisher || trust.label}</span>
|
||||
<span className="mono">v{p.version}</span>
|
||||
{perms.length > 0 && (
|
||||
<Tip label={tr('pluginPermissionsLabel', { list: perms.map((x) => x.name).join(', ') })}>
|
||||
<span>{tr('pluginPermCount', { count: perms.length })}</span>
|
||||
</Tip>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{alert && (
|
||||
<div className="row-sub plugin-row-alert">
|
||||
{fault ? <AlertTriangle size={12} aria-hidden="true" /> : <ShieldAlert size={12} aria-hidden="true" />}
|
||||
<span>{alert}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{hasAppSettings(p) && (
|
||||
<IconButton label={tr('pluginSettings')} icon={<Settings2 size={15} />} onClick={() => void openPluginSettings(p)} />
|
||||
)}
|
||||
{p.log_path && (
|
||||
<IconButton label={tr('pluginViewLog')} icon={<Terminal size={15} />} onClick={() => void openPluginLog(p)} />
|
||||
)}
|
||||
{p.removable && (
|
||||
<IconButton
|
||||
disabled={p.in_use || busyID === p.id}
|
||||
label={p.in_use ? tr('pluginInUse') : tr('pluginRemove')}
|
||||
icon={<Trash2 size={15} />}
|
||||
onClick={() => setRemoveTarget(p)}
|
||||
/>
|
||||
)}
|
||||
{p.system ? (
|
||||
// Locked on: a disabled switch keeps the column aligned; the
|
||||
// wrapper lets the tooltip work on a disabled control.
|
||||
<Tip label={tr('pluginAlwaysOn')}>
|
||||
<span className="plugin-row-locked" tabIndex={0}>
|
||||
<Switch label={locText(p.name, locale, p.id)} checked disabled onChange={() => {}} />
|
||||
</span>
|
||||
</Tip>
|
||||
) : (
|
||||
<Switch
|
||||
label={locText(p.name, locale, p.id)}
|
||||
disabled={busyID === p.id || (p.enabled && p.in_use) || (!!safeMode && !isBuiltin)}
|
||||
checked={p.enabled}
|
||||
onChange={(checked) => void togglePlugin(p, checked)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const showThemeHero = themes.length > 1 && !q
|
||||
const showSearch = plugins.length > SEARCH_THRESHOLD
|
||||
const noMatches = !loading && !!q && filteredBuiltins.length === 0 && filteredExternal.length === 0
|
||||
|
||||
const previewAccent = activeSchemeSeeds.accent || 'var(--accent)'
|
||||
const previewSurface = activeSchemeSeeds.surface || 'var(--surface-canvas)'
|
||||
|
||||
return (
|
||||
<div className="page plugins-page">
|
||||
<header className="page-head">
|
||||
<div className="page-title plugins-page-title">
|
||||
<h1>{tr('sidebarPlugins')}</h1>
|
||||
{!loading && <span>{tr('pluginActiveCount', { active: activeCount, total: plugins.length })}</span>}
|
||||
</div>
|
||||
<div className="actions">
|
||||
{showSearch && (
|
||||
<div className="plugins-search-wrap">
|
||||
<Search size={13} className="plugins-search-icon" aria-hidden="true" />
|
||||
<input
|
||||
type="search"
|
||||
className="input plugins-search"
|
||||
aria-label={tr('pluginSearchPlaceholder')}
|
||||
placeholder={tr('pluginSearchPlaceholder')}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<IconButton label={tr('refresh')} icon={<RefreshCw size={16} />} onClick={() => void reload()} />
|
||||
<IconButton label={tr('pluginLinkDevBtn')} icon={<FolderOpen size={16} />} onClick={linkDevDir} />
|
||||
<Button variant="primary" icon={<PackagePlus size={14} aria-hidden="true" />} onClick={importLocalZip}>
|
||||
{tr('pluginImportBtn')}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{showThemeHero && (
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('pluginThemeSection')}</div>
|
||||
<div className="theme-hero-card">
|
||||
<div className="theme-mini-preview" style={{ background: previewSurface }} aria-hidden="true">
|
||||
<div className="theme-mini-chrome">
|
||||
<span className="theme-mini-dot" />
|
||||
<span className="theme-mini-dot" />
|
||||
<span className="theme-mini-dot" />
|
||||
</div>
|
||||
<div className="theme-mini-body">
|
||||
<div className="theme-mini-sidebar">
|
||||
<span className="theme-mini-pill" style={{ background: previewAccent }} />
|
||||
<span className="theme-mini-line" />
|
||||
<span className="theme-mini-line short" />
|
||||
</div>
|
||||
<div className="theme-mini-main">
|
||||
<div className="theme-mini-bar" />
|
||||
<div className="theme-mini-cta" style={{ background: previewAccent }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="theme-hero-info">
|
||||
<div className="theme-hero-top">
|
||||
<div>
|
||||
<div className="theme-hero-kicker">
|
||||
<Sparkles size={12} aria-hidden="true" />
|
||||
{tr('pluginActiveTheme')}
|
||||
</div>
|
||||
<div className="theme-hero-title">
|
||||
{activeThemeObj ? locText(activeThemeObj.name, locale, activeThemeObj.id) : tr('pluginSchemeDefault')}
|
||||
</div>
|
||||
<div className="row-sub">
|
||||
{safeMode ? tr('pluginThemeSafeModeHint') : tr('pluginThemeHint')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="hstack">
|
||||
<PopupSelect
|
||||
label={tr('pluginThemePackLabel')}
|
||||
value={activeTheme?.theme_id || 'builtin.theme.default'}
|
||||
options={themes.map((th) => ({
|
||||
value: th.id,
|
||||
label: locText(th.name, locale, th.id),
|
||||
disabled: !!safeMode && th.id !== 'builtin.theme.default',
|
||||
}))}
|
||||
onChange={(id) => { if (!safeMode) void selectTheme(id) }}
|
||||
/>
|
||||
{activeTheme && activeTheme.theme_id !== 'builtin.theme.default' && (
|
||||
<Button icon={<Palette size={14} aria-hidden="true" />} onClick={() => setSchemeEditorOpen(true)}>
|
||||
{tr('pluginNewScheme')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{activeTheme && activeTheme.theme_id !== 'builtin.theme.default' ? (
|
||||
<div className="theme-scheme-strip">
|
||||
<span className="muted" style={{ fontSize: 'var(--fs-12)' }}>{tr('pluginColorSchemes')}</span>
|
||||
<div className="theme-scheme-chips">
|
||||
<button
|
||||
type="button"
|
||||
className={`plugin-cat-pill${!activeTheme.active_scheme ? ' is-active' : ''}`}
|
||||
onClick={() => void selectTheme(activeTheme.theme_id, '')}
|
||||
>
|
||||
{tr('pluginSchemeDefault')}
|
||||
</button>
|
||||
{presetSchemes.map((s) => (
|
||||
<button
|
||||
key={s.id}
|
||||
type="button"
|
||||
className={`plugin-cat-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
|
||||
onClick={() => void selectTheme(activeTheme.theme_id, s.id)}
|
||||
>
|
||||
{s.seeds?.accent && <span className="plugins-scheme-dot" style={{ background: s.seeds.accent }} aria-hidden="true" />}
|
||||
{locText(s.name, locale, s.id)}
|
||||
</button>
|
||||
))}
|
||||
{customSchemes.map((s) => (
|
||||
<span className="hstack" style={{ gap: 2 }} key={s.id}>
|
||||
<button
|
||||
type="button"
|
||||
className={`plugin-cat-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
|
||||
onClick={() => void selectTheme(activeTheme.theme_id, s.id)}
|
||||
>
|
||||
{s.seeds?.accent && <span className="plugins-scheme-dot" style={{ background: s.seeds.accent }} aria-hidden="true" />}
|
||||
{s.name}
|
||||
</button>
|
||||
<IconButton small label={tr('pluginDeleteScheme')} icon={<Trash2 size={12} />} onClick={() => setDeleteSchemeTarget(s)} />
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="row-sub">{tr('pluginThemeEmptyHint')}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{noMatches && <div className="plugins-empty">{tr('pluginSearchEmpty')}</div>}
|
||||
|
||||
{filteredExternal.length > 0 && (
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
<span>{tr('pluginExternalSection')}</span>
|
||||
<span className="section-count">{filteredExternal.length}</span>
|
||||
</div>
|
||||
<div className="list">{filteredExternal.map(renderRow)}</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{(loading || filteredBuiltins.length > 0) && (
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
<span>{tr('pluginBuiltinSection')}</span>
|
||||
{!loading && <span className="section-count">{filteredBuiltins.length}</span>}
|
||||
</div>
|
||||
{loading ? (
|
||||
<div className="list"><div className="row plugin-row"><span className="muted">…</span></div></div>
|
||||
) : (
|
||||
<div className="list">{filteredBuiltins.map(renderRow)}</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{settingsPanels.length > 0 && contribs?.asset_token ? (
|
||||
<section className="section" data-rg-slot="settings.plugin">
|
||||
<div className="section-title">{tr('pluginPanelsSection')}</div>
|
||||
{settingsPanels.map((panel) => (
|
||||
<PluginPanelFrame
|
||||
key={`${panel.pluginId}:${panel.id}`}
|
||||
locale={locale}
|
||||
panel={panel}
|
||||
assetToken={contribs.asset_token!}
|
||||
appearance={appearance}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
) : (
|
||||
<div className="rg-slot-anchor" data-rg-slot="settings.plugin" />
|
||||
)}
|
||||
|
||||
{approveTarget && (
|
||||
<Modal
|
||||
title={tr('pluginApproveTitle')}
|
||||
subtitle={locText(approveTarget.name, locale, approveTarget.id)}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setApproveTarget(null)}
|
||||
>
|
||||
<div className="stack-3" style={{ padding: 'var(--sp-4)' }}>
|
||||
{(approveTarget.tier === 'L3' || (approveTarget.permissions ?? []).some((p) => p.name === 'ui:script')) && (
|
||||
<div className="notice notice-warn">
|
||||
<ShieldAlert size={15} aria-hidden="true" style={{ marginRight: 6, verticalAlign: '-2px' }} />
|
||||
{tr('pluginApproveL3Warn')}
|
||||
</div>
|
||||
)}
|
||||
<div className="list">
|
||||
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginPublisherLicense')}</div><div className="row-sub">{approveTarget.publisher || '—'} · {approveTarget.license || '—'}</div></div></div>
|
||||
{approveTarget.entry_path && (
|
||||
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginEntryPath')}</div><div className="row-sub mono selectable">{approveTarget.entry_path}</div></div></div>
|
||||
)}
|
||||
{approveTarget.entry_hash && (
|
||||
<div className="row"><div className="row-main"><div className="row-title">SHA-256</div><div className="row-sub mono selectable">{approveTarget.entry_hash}</div></div></div>
|
||||
)}
|
||||
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginRequestedPerms')}</div><div className="row-sub mono">{(approveTarget.permissions ?? []).length > 0 ? (approveTarget.permissions ?? []).map((p) => `${p.name} (${p.level})`).join(', ') : '—'}</div></div></div>
|
||||
</div>
|
||||
<label className="hstack" style={{ cursor: 'pointer' }}>
|
||||
<input type="checkbox" checked={approveChecked} onChange={(e) => setApproveChecked(e.target.checked)} />
|
||||
<span>{tr('pluginApproveCheckbox')}</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => setApproveTarget(null)}>{tr('cancel')}</Button>
|
||||
<Button variant="primary" disabled={!approveChecked} onClick={() => void confirmApprove()}>
|
||||
{tr('pluginApproveConfirm')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{settingsTarget && settingsTarget.settings && (
|
||||
<Modal
|
||||
title={locText(settingsTarget.name, locale, settingsTarget.id)}
|
||||
subtitle={tr('pluginGlobalSettings')}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setSettingsTarget(null)}
|
||||
>
|
||||
<div style={{ padding: 'var(--sp-4)' }}>
|
||||
<SchemaForm
|
||||
locale={locale}
|
||||
schema={settingsTarget.settings}
|
||||
values={settingsValues}
|
||||
scopeFilter="app"
|
||||
onChange={(next) => void savePluginSettings(next)}
|
||||
/>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<Button variant="primary" onClick={() => setSettingsTarget(null)}>{tr('pluginDone')}</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{removeTarget && (
|
||||
<Modal
|
||||
title={tr('pluginRemove')}
|
||||
subtitle={locText(removeTarget.name, locale, removeTarget.id)}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setRemoveTarget(null)}
|
||||
>
|
||||
<div style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
|
||||
<span className="mono">{removeTarget.id}@{removeTarget.version}</span>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => setRemoveTarget(null)}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
onClick={() => {
|
||||
const target = removeTarget
|
||||
setRemoveTarget(null)
|
||||
void removePlugin(target)
|
||||
}}
|
||||
>
|
||||
{tr('pluginRemove')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{deleteSchemeTarget && (
|
||||
<Modal
|
||||
title={tr('pluginDeleteScheme')}
|
||||
subtitle={deleteSchemeTarget.name}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setDeleteSchemeTarget(null)}
|
||||
>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => setDeleteSchemeTarget(null)}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
onClick={() => {
|
||||
const target = deleteSchemeTarget
|
||||
setDeleteSchemeTarget(null)
|
||||
void deleteScheme(target.id)
|
||||
}}
|
||||
>
|
||||
{tr('pluginDeleteScheme')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{logTarget && (
|
||||
<Modal
|
||||
title={tr('pluginLogTitle', { id: logTarget.id })}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setLogTarget(null)}
|
||||
>
|
||||
<pre className="mono selectable" style={{ padding: 'var(--sp-4)', maxHeight: 360, overflow: 'auto', margin: 0 }}>
|
||||
{logTarget.text}
|
||||
</pre>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{schemeEditorOpen && (
|
||||
<Modal
|
||||
title={tr('pluginSchemeModalTitle')}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setSchemeEditorOpen(false)}
|
||||
>
|
||||
<div className="stack-3" style={{ padding: 'var(--sp-4)' }}>
|
||||
<label className="stack-1">
|
||||
<span>{tr('pluginSchemeName')}</span>
|
||||
<input className="input" value={schemeName} onChange={(e) => setSchemeName(e.target.value)} placeholder={tr('pluginSchemePlaceholder')} />
|
||||
</label>
|
||||
<label className="hstack">
|
||||
<span>{tr('pluginAccentSeed')}</span>
|
||||
<input type="color" value={seedAccent} onChange={(e) => setSeedAccent(e.target.value)} />
|
||||
<span className="mono">{seedAccent}</span>
|
||||
</label>
|
||||
<label className="stack-1">
|
||||
<span>{tr('pluginSurfaceSeed')}</span>
|
||||
<input className="input mono" value={seedSurface} onChange={(e) => setSeedSurface(e.target.value)} placeholder="#1d1e23" />
|
||||
</label>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => setSchemeEditorOpen(false)}>{tr('cancel')}</Button>
|
||||
<Button variant="primary" disabled={!schemeName.trim()} onClick={() => void saveScheme()}>{tr('save')}</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,65 +1,91 @@
|
||||
import { Download, LoaderCircle, Pause } from 'lucide-react'
|
||||
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, Task } from '../types'
|
||||
import { InstalledRuntime, Locale, RemoteRuntime, RuntimeSource, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { backend } from '../wails'
|
||||
import { Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
channel: 'stable' | 'candidate'
|
||||
channel: 'stable' | 'alpha'
|
||||
source: RuntimeSource
|
||||
installed: InstalledRuntime[]
|
||||
task: Task | null
|
||||
onChannel: (candidate: boolean) => void
|
||||
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`)
|
||||
|
||||
/** Online runtime install: newest release on the channel, its install button or progress. */
|
||||
export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, task, onChannel, onInstall, onCancel }) => {
|
||||
/** "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('')
|
||||
backend.listRemoteRuntimes()
|
||||
api.ListRemoteRuntimes()
|
||||
.then((list) => { if (live) setRemote(list ?? []) })
|
||||
.catch((e) => { if (live) setError(String(e).replace(/^Error:\s*/, '')) })
|
||||
return () => { live = false }
|
||||
}, [channel, task?.status === 'done'])
|
||||
}, [channel, source, task?.status === 'done', reload])
|
||||
|
||||
const active = installed.find((i) => i.active) ?? installed[0]
|
||||
const latest = remote?.[0]
|
||||
const isInstalled = (c: string) => installed.some((i) => i.commit.startsWith(c) || c.startsWith(i.commit))
|
||||
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 body: React.ReactNode
|
||||
let sub: React.ReactNode
|
||||
if (running && task) {
|
||||
body = (
|
||||
sub = (
|
||||
<div className="row-sub task-inline">
|
||||
<LoaderCircle size={14} className="spin" />
|
||||
{task.percent >= 0 && <span className="progress"><div style={{ width: `${task.percent}%` }} /></span>}
|
||||
<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) {
|
||||
body = <div className="row-sub" title={error}>{tr('runtimeLookupFailed')}</div>
|
||||
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) {
|
||||
body = <div className="row-sub">…</div>
|
||||
sub = <div className="row-sub">…</div>
|
||||
} else if (!latest) {
|
||||
body = <div className="row-sub">{tr('runtimeNoneOnChannel')}</div>
|
||||
sub = <div className="row-sub">{tr('runtimeNoneOnChannel')}</div>
|
||||
} else {
|
||||
body = (
|
||||
const srcLabel = latest.source === 'gitcode' ? 'GitCode' : latest.source === 'github' ? 'GitHub' : ''
|
||||
sub = (
|
||||
<div className="row-sub">
|
||||
<span className="mono">{tr('runtimeLatest', { v: latest.commit })}</span>
|
||||
{active ? tr('runtimeNewer', { v: latest.commit }) : tr('runtimeLatest', { v: latest.commit })}
|
||||
{' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)}
|
||||
{' · '}{gb(latest.archive_size)}
|
||||
{' · '}{latest.published_at.slice(0, 10)}
|
||||
{srcLabel ? ` · ${srcLabel}` : ''}
|
||||
{latest.archive_size > 0 ? ` · ${gb(latest.archive_size)}` : ''}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -68,33 +94,51 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
<>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('runtimeOnline')}</div>
|
||||
{body}
|
||||
<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 && (
|
||||
{running && task?.cancelable ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => onCancel(task.id)} />
|
||||
)}
|
||||
{!running && latest && (isInstalled(latest.commit)
|
||||
? <span className="badge badge-ok">{tr('runtimeUpToDate')}</span>
|
||||
: <Button variant="primary" icon={<Download size={14} />} onClick={() => onInstall(latest.commit)}>{tr('runtimeInstall')}</Button>)}
|
||||
) : !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('runtimeCandidate')}</div>
|
||||
<div className="row-sub">{tr('runtimeCandidateHint')}</div>
|
||||
<div className="row-title">{tr('runtimeSource')}</div>
|
||||
<div className="row-sub">{tr('runtimeSourceHint')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<label className="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={tr('runtimeCandidate')}
|
||||
checked={channel === 'candidate'}
|
||||
onChange={(e) => onChannel(e.target.checked)}
|
||||
/>
|
||||
<span className="slider" />
|
||||
</label>
|
||||
<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,157 @@
|
||||
import React from 'react'
|
||||
import { locText, t } from '../i18n'
|
||||
import { Locale, SettingProperty, SettingsSchema } from '../types'
|
||||
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
|
||||
export { locText }
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
schema: SettingsSchema
|
||||
values: Record<string, unknown>
|
||||
scopeFilter?: 'app' | 'vm'
|
||||
groupFilter?: string
|
||||
onChange: (next: Record<string, unknown>) => void
|
||||
hideGroupHeader?: boolean
|
||||
}
|
||||
|
||||
const SECRET_MASK = '••••••••'
|
||||
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
|
||||
|
||||
/** Lazy-loaded JSON Schema form renderer supporting x-secret, x-effect, x-scope (§6.2, §8.1, §10). */
|
||||
export const SchemaForm: React.FC<Props> = ({
|
||||
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader,
|
||||
}) => {
|
||||
const propsMap = schema.properties ?? {}
|
||||
const keys = (schema['x-order'] && schema['x-order'].length > 0
|
||||
? schema['x-order'].filter((k) => !FORBIDDEN_KEYS.has(k) && Object.prototype.hasOwnProperty.call(propsMap, k))
|
||||
: Object.keys(propsMap).filter((k) => !FORBIDDEN_KEYS.has(k))
|
||||
).filter((k) => {
|
||||
const prop = propsMap[k]
|
||||
const effScope = prop['x-scope'] || schema['x-scope'] || 'app'
|
||||
const effGroup = prop['x-group'] || schema['x-group'] || ''
|
||||
if (scopeFilter && effScope !== scopeFilter) return false
|
||||
if (groupFilter && effGroup !== groupFilter) return false
|
||||
return true
|
||||
})
|
||||
|
||||
if (keys.length === 0) return null
|
||||
|
||||
const setKey = (k: string, v: unknown) => {
|
||||
const next: Record<string, unknown> = {}
|
||||
for (const [ek, ev] of Object.entries(values)) {
|
||||
if (propsMap[ek]?.['x-secret'] && ev === SECRET_MASK) continue
|
||||
next[ek] = ev
|
||||
}
|
||||
next[k] = v
|
||||
onChange(next)
|
||||
}
|
||||
|
||||
const effectBadge = (prop: SettingProperty) => {
|
||||
const eff = prop['x-effect']
|
||||
if (!eff) return null
|
||||
const label = t(locale, eff === 'immediate' ? 'effectImmediate' : 'effectNextStart')
|
||||
return <span className={`badge ${eff === 'immediate' ? 'badge-ok' : ''}`}>{label}</span>
|
||||
}
|
||||
|
||||
const renderControl = (k: string, prop: SettingProperty) => {
|
||||
const cur = values[k] ?? prop.default
|
||||
const label = locText(prop.title, locale, k)
|
||||
|
||||
if (prop.type === 'boolean') {
|
||||
return (
|
||||
<Switch
|
||||
label={label}
|
||||
checked={Boolean(cur)}
|
||||
onChange={(checked) => setKey(k, checked)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (prop.enum && prop.enum.length > 0) {
|
||||
const options = prop.enum.map((val, idx) => ({
|
||||
value: val,
|
||||
label: locText(prop['x-enumLabels']?.[idx], locale, val),
|
||||
}))
|
||||
if (options.length <= 3) {
|
||||
return (
|
||||
<Segmented
|
||||
label={label}
|
||||
value={String(cur ?? prop.enum[0])}
|
||||
options={options}
|
||||
onChange={(val) => setKey(k, val)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<PopupSelect
|
||||
label={label}
|
||||
value={String(cur ?? prop.enum[0])}
|
||||
options={options}
|
||||
onChange={(val) => setKey(k, val)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (prop.type === 'integer' || prop.type === 'number') {
|
||||
const numVal = Number(cur ?? 0)
|
||||
return (
|
||||
<NumberField
|
||||
label={label}
|
||||
value={Number.isFinite(numVal) ? numVal : 0}
|
||||
min={prop.minimum ?? 0}
|
||||
max={prop.maximum ?? 65535}
|
||||
step={prop.type === 'number' ? 0.1 : 1}
|
||||
onChange={(n) => setKey(k, n)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (prop['x-secret']) {
|
||||
const isMasked = cur === SECRET_MASK
|
||||
return (
|
||||
<input
|
||||
type="password"
|
||||
className="input"
|
||||
aria-label={label}
|
||||
autoComplete="new-password"
|
||||
placeholder={isMasked ? SECRET_MASK : undefined}
|
||||
value={isMasked ? '' : String(cur ?? '')}
|
||||
onChange={(e) => setKey(k, e.target.value)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
className="input"
|
||||
aria-label={label}
|
||||
value={String(cur ?? '')}
|
||||
onChange={(e) => setKey(k, e.target.value)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const rows = keys.map((k) => {
|
||||
const prop = propsMap[k]
|
||||
const title = locText(prop.title, locale, k)
|
||||
const desc = locText(prop.description, locale)
|
||||
const badge = effectBadge(prop)
|
||||
return (
|
||||
<SetRow
|
||||
key={k}
|
||||
title={title}
|
||||
desc={badge || desc ? <span className="hstack">{badge}{desc ? <span>{desc}</span> : null}</span> : undefined}
|
||||
control={renderControl(k, prop)}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
if (hideGroupHeader) return <>{rows}</>
|
||||
return (
|
||||
<SetGroup title={locText(schema.title, locale, t(locale, 'pluginSettings'))}>
|
||||
{rows}
|
||||
</SetGroup>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
import { FolderOpen, HardDrive } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { AppState, DataRootCheck, DataRootChoice, Locale, Task } from '../types'
|
||||
import { getLocaleOptions, I18nKey, joinNotices, t } from '../i18n'
|
||||
import { AppState, DataRootCheck, DataRootChoice, Locale, ResolvedLocalePack, RuntimeSource, Task } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { backend } from '../wails'
|
||||
import { PopupSelect } from '../ui/settings'
|
||||
import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format'
|
||||
import { api } from '../wails'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
locales?: ResolvedLocalePack[]
|
||||
state: AppState
|
||||
stage: 'folder' | 'runtime'
|
||||
runtimeTask: Task | null
|
||||
@@ -15,7 +18,8 @@ interface Props {
|
||||
onFolderDone: () => void
|
||||
onFinish: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onChannel: (candidate: boolean) => void
|
||||
onChannel: (alpha: boolean) => void
|
||||
onSource: (source: RuntimeSource) => void
|
||||
onInstallRuntime: (commit: string) => void
|
||||
onCancelTask: (id: string) => void
|
||||
onImportRuntime: () => void
|
||||
@@ -37,7 +41,7 @@ export const Setup: React.FC<Props> = (p) => {
|
||||
|
||||
type StepProps = Props & { tr: (k: I18nKey, v?: Record<string, string | number>) => string }
|
||||
|
||||
const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, onError }) => {
|
||||
const FolderStep: React.FC<StepProps> = ({ locale, locales, tr, onLocale, onFolderDone, onError }) => {
|
||||
const [choices, setChoices] = useState<DataRootChoice[]>([])
|
||||
const [custom, setCustom] = useState('')
|
||||
const [customMode, setCustomMode] = useState(false)
|
||||
@@ -46,7 +50,7 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
backend.suggestDataRoots().then((list) => {
|
||||
api.SuggestDataRoots().then((list) => {
|
||||
const l = list ?? []
|
||||
setChoices(l)
|
||||
const rec = l.find((c) => c.recommended) ?? l[0]
|
||||
@@ -57,19 +61,19 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
|
||||
useEffect(() => {
|
||||
if (!selected) { setCheck(null); return }
|
||||
let live = true
|
||||
backend.checkDataRoot(selected).then((c) => { if (live) setCheck(c) }).catch(() => {})
|
||||
api.CheckDataRoot(selected).then((c) => { if (live) setCheck(c) }).catch(() => {})
|
||||
return () => { live = false }
|
||||
}, [selected])
|
||||
|
||||
const browse = async () => {
|
||||
const dir = await backend.pickDirectory(tr('setupTitle')).catch(() => '')
|
||||
const dir = await api.PickDirectory(tr('setupTitle')).catch(() => '')
|
||||
if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) }
|
||||
}
|
||||
|
||||
const next = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await backend.completeSetup(selected)
|
||||
await api.CompleteSetup(selected)
|
||||
onFolderDone()
|
||||
} catch (e) {
|
||||
onError(tr('failGeneric'), e)
|
||||
@@ -119,6 +123,8 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
|
||||
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()) }}
|
||||
@@ -130,38 +136,110 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
|
||||
)}
|
||||
</div>
|
||||
{notices.length > 0 && (
|
||||
<div className={check?.error ? 'notice notice-error' : 'hint warn'}>{notices.join(';')}</div>
|
||||
<div className={check?.error ? 'notice notice-error' : 'hint warn'}>{joinNotices(locale, notices)}</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">
|
||||
<div className="segmented" role="group" aria-label={tr('language')}>
|
||||
<button type="button" aria-pressed={locale === 'zh-CN'} onClick={() => onLocale('zh-CN')}>中文</button>
|
||||
<button type="button" aria-pressed={locale === 'en-US'} onClick={() => onLocale('en-US')}>English</button>
|
||||
</div>
|
||||
<PopupSelect
|
||||
label={tr('language')}
|
||||
value={locale}
|
||||
onChange={onLocale}
|
||||
options={getLocaleOptions(locales)}
|
||||
/>
|
||||
<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, onInstallRuntime, onCancelTask, onImportRuntime, onFinish }) => {
|
||||
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 gpuHint = gpuCompatHint(locale, gpu)
|
||||
const gpuOK = !!gpu && gpu.compat !== 'warn' && gpu.compat !== 'unsupported'
|
||||
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>
|
||||
{gpuHint && <div className="row-sub warn-text">{gpuHint}</div>}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<span className={`badge ${gpuOK ? 'badge-ok' : 'badge-warn'}`}>
|
||||
{tr(
|
||||
gpuOK
|
||||
? 'whpxReady'
|
||||
: gpu?.compat === 'unsupported'
|
||||
? 'gpuCompatUnsupported'
|
||||
: gpu?.compat === 'warn'
|
||||
? 'gpuCompatWarn'
|
||||
: '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 === 'candidate' ? 'candidate' : 'stable'}
|
||||
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}
|
||||
/>
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import { Cpu, Monitor, Plus } from 'lucide-react'
|
||||
import * as Ctx from '@radix-ui/react-context-menu'
|
||||
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Play, Plus, Power, Puzzle, 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 PLUGINS_ID = '__plugins__'
|
||||
export const SETTINGS_ID = '__settings__'
|
||||
export const ABOUT_ID = '__about__'
|
||||
|
||||
/** Pages that are not VMs; everything else selectable in the sidebar is a VM name. */
|
||||
export const PAGE_IDS: readonly string[] = [HOST_ID, INSTALLERS_ID, PLUGINS_ID, SETTINGS_ID, ABOUT_ID]
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -13,12 +23,30 @@ 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
|
||||
/** Safe mode is active (third-party plugins skipped). */
|
||||
safeMode?: boolean
|
||||
/** Update capsule card shown under the brand (null when nothing to show). */
|
||||
updateCard?: React.ReactNode
|
||||
/** A newer release exists: dot on the About entry. */
|
||||
updateDot?: 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, safeMode, updateCard, updateDot,
|
||||
}) => {
|
||||
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, PLUGINS_ID, HOST_ID, SETTINGS_ID, ABOUT_ID]
|
||||
|
||||
// Listbox keyboard model: ↑/↓/Home/End move selection and focus together.
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
@@ -34,13 +62,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 = (
|
||||
const navBtn = (
|
||||
id: string,
|
||||
label: string,
|
||||
icon: React.ReactNode,
|
||||
badgeClass: string,
|
||||
stateLabel: string,
|
||||
kind: ReturnType<typeof statusKind>,
|
||||
kind: ReturnType<typeof statusKind> | null,
|
||||
onDoubleClick?: () => void,
|
||||
dot?: boolean,
|
||||
) => (
|
||||
<button
|
||||
key={id}
|
||||
@@ -49,41 +79,155 @@ 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 ? t(locale, 'sidebarItemAria', { label, state: stateLabel }) : label}
|
||||
tabIndex={selected === id ? 0 : -1}
|
||||
onClick={() => onSelect(id)}
|
||||
onDoubleClick={onDoubleClick}
|
||||
>
|
||||
<span className={`nav-icon-badge ${badgeClass}`} aria-hidden="true">{icon}</span>
|
||||
<span className="nav-label">{label}</span>
|
||||
<Tip label={stateLabel} side="right">
|
||||
<span className="hstack"><StatusShape kind={kind} /></span>
|
||||
</Tip>
|
||||
{dot && <span className="nav-dot" aria-hidden="true" />}
|
||||
{kind && (
|
||||
<Tip label={stateLabel} side="right">
|
||||
<span className="hstack"><StatusShape kind={kind} /></span>
|
||||
</Tip>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="sidebar-wrap">
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-head">
|
||||
<span>{t(locale, 'sidebarVMs')}</span>
|
||||
<IconButton small label={t(locale, 'newVM')} shortcut="Ctrl+N" icon={<Plus size={15} />} onClick={onNew} tipSide="right" />
|
||||
<aside className="sidebar rg-p-sidebar">
|
||||
<div className="sidebar-brand">
|
||||
<img className="sidebar-brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
|
||||
<span className="sidebar-brand-name">Reims-Go</span>
|
||||
</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>}
|
||||
{updateCard}
|
||||
<div className="sidebar-head rg-p-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 rg-p-nav" role="listbox" aria-label={tr('sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
|
||||
<div className="nav-group nav-vms" role="group" aria-label={tr('sidebarVMs')}>
|
||||
{vms.length === 0 && <div className="nav-empty rg-p-empty" data-rg-slot="empty.state">{tr('emptyVMs')}</div>}
|
||||
{vms.map((vm) => {
|
||||
const st = transitions[vm.name] ?? vm.state
|
||||
return item(vm.name, vm.name, <Monitor size={13} />, 'nav-icon-vm', t(locale, `state_${st}` as I18nKey), statusKind(st))
|
||||
const running = st === 'running'
|
||||
const stopped = st === 'stopped'
|
||||
const transitioning = st === 'starting' || st === 'stopping'
|
||||
const label = displayNames[vm.name] || vm.name
|
||||
const trigger = navBtn(
|
||||
vm.name,
|
||||
label,
|
||||
<VersionArt shape="tile" major={macosMajors[vm.name] ?? null} name={label} />,
|
||||
'nav-icon-art',
|
||||
t(locale, `state_${st}` as I18nKey),
|
||||
statusKind(st),
|
||||
onActivate ? () => onActivate(vm.name) : undefined,
|
||||
)
|
||||
if (!onVMContextAction) return trigger
|
||||
return (
|
||||
<Ctx.Root key={vm.name}>
|
||||
<Ctx.Trigger asChild>{trigger}</Ctx.Trigger>
|
||||
<Ctx.Portal>
|
||||
<Ctx.Content className="menu">
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'start')}>
|
||||
<Play size={14} /> {tr('start')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
{running && (
|
||||
<>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'focus')}>
|
||||
<AppWindow size={14} /> {tr('showWindow')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'screenshot')}>
|
||||
<Camera size={14} /> {tr('copyScreenshot')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'stop')}>
|
||||
<Square size={14} /> {tr('stop')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'restart')}>
|
||||
<RotateCw size={14} /> {tr('restart')}
|
||||
</Ctx.Item>
|
||||
</>
|
||||
)}
|
||||
{(running || transitioning) && (
|
||||
<Ctx.Item className="menu-item danger" onSelect={() => onVMContextAction(vm.name, 'forceStop')}>
|
||||
<Power size={14} /> {tr('forceStop')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'settings')}>
|
||||
<Settings size={14} /> {tr('settingsEllipsis')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openSharedFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openSharedFolder')}
|
||||
</Ctx.Item>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'cloneVM')}>
|
||||
<CopyPlus size={14} /> {tr('cloneVM')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openFolder')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item danger" disabled={running || transitioning} onSelect={() => onVMContextAction(vm.name, 'delete')}>
|
||||
<Trash size={14} /> {tr('delete')}
|
||||
</Ctx.Item>
|
||||
</Ctx.Content>
|
||||
</Ctx.Portal>
|
||||
</Ctx.Root>
|
||||
)
|
||||
})}
|
||||
<div className="sidebar-sep" role="presentation" />
|
||||
{item(
|
||||
</div>
|
||||
<div className="nav-group nav-system" role="group" aria-label={tr('sidebarSystem')}>
|
||||
{navBtn(
|
||||
INSTALLERS_ID,
|
||||
tr('sidebarInstallers'),
|
||||
<Download size={13} />,
|
||||
'nav-icon-installers',
|
||||
downloading ? tr('state_starting') : '',
|
||||
downloading ? 'busy' : null,
|
||||
)}
|
||||
{navBtn(
|
||||
PLUGINS_ID,
|
||||
tr('sidebarPlugins'),
|
||||
<Puzzle size={13} />,
|
||||
'nav-icon-plugins',
|
||||
safeMode ? tr('pluginSafeModeShort') : '',
|
||||
safeMode ? 'warn' : null,
|
||||
)}
|
||||
{navBtn(
|
||||
HOST_ID,
|
||||
t(locale, 'sidebarHost'),
|
||||
tr('sidebarHost'),
|
||||
<Cpu size={13} />,
|
||||
'nav-icon-host',
|
||||
t(locale, hostReady ? 'hostReady' : 'hostNeedsAction'),
|
||||
tr(hostReady ? 'hostReady' : 'hostNeedsAction'),
|
||||
hostReady ? 'running' : 'warn',
|
||||
)}
|
||||
{navBtn(
|
||||
SETTINGS_ID,
|
||||
tr('sidebarSettings'),
|
||||
<Settings size={13} />,
|
||||
'nav-icon-settings',
|
||||
'',
|
||||
null,
|
||||
)}
|
||||
{navBtn(
|
||||
ABOUT_ID,
|
||||
tr('settingsAbout'),
|
||||
<Info size={13} />,
|
||||
'nav-icon-about',
|
||||
'',
|
||||
null,
|
||||
undefined,
|
||||
updateDot,
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rg-slot-anchor" data-rg-slot="sidebar.footer" />
|
||||
</aside>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
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 { ABOUT_ID, HOST_ID, INSTALLERS_ID, PLUGINS_ID, SETTINGS_ID } from './Sidebar'
|
||||
import { VMAction } from './VMPage'
|
||||
|
||||
export const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
sidebarOpen: boolean
|
||||
onToggleSidebar: () => void
|
||||
logsOpen: boolean
|
||||
onToggleLogs: () => void
|
||||
themeMode: ThemeMode
|
||||
canLight?: boolean
|
||||
canDark?: boolean
|
||||
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, canLight = true, canDark = true, 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}
|
||||
disabled={(m === 'light' && !canLight) || (m === 'dark' && !canDark) || (m === 'system' && (!canLight || !canDark))}
|
||||
>
|
||||
<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('sidebarPlugins'), () => onNavigate(PLUGINS_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(ABOUT_ID))}
|
||||
{item(tr('helpAbout'), () => onNavigate(ABOUT_ID))}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
<Menu.Label className="menu-group-label">Reims-Go {appVersion}</Menu.Label>
|
||||
</>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { ArrowDownToLine, RotateCw, X } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, Task } from '../types'
|
||||
import { Tip } from '../ui/controls'
|
||||
|
||||
/** Where an available update is: offered, downloading, verified and ready, or failed. */
|
||||
export type UpdatePhase = 'none' | 'available' | 'downloading' | 'ready' | 'failed'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
phase: UpdatePhase
|
||||
latest: string
|
||||
task?: Task | null
|
||||
/** Opens the About page with the full update details. */
|
||||
onOpen: () => void
|
||||
onDownload: () => void
|
||||
onCancel: () => void
|
||||
onInstall: () => void
|
||||
/** Hides the card until the next release ("remind me later"). */
|
||||
onDismiss: () => void
|
||||
}
|
||||
|
||||
/** Capsule card under the sidebar brand: the update's state and one action. */
|
||||
export const UpdateCapsule: React.FC<Props> = ({
|
||||
locale, phase, latest, task, onOpen, onDownload, onCancel, onInstall, onDismiss,
|
||||
}) => {
|
||||
if (phase === 'none') return null
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const pct = task && task.percent >= 0 ? Math.round(task.percent) : null
|
||||
|
||||
let title: string
|
||||
let action: React.ReactNode = null
|
||||
let close: React.ReactNode = null
|
||||
if (phase === 'downloading') {
|
||||
title = pct === null ? tr('updateCapsuleDownloading') : tr('updateCapsuleDownloadingPct', { p: pct })
|
||||
close = (
|
||||
<Tip label={tr('updateCancel')} side="right">
|
||||
<button type="button" className="update-capsule-x" aria-label={tr('updateCancel')} onClick={onCancel}><X size={12} /></button>
|
||||
</Tip>
|
||||
)
|
||||
} else if (phase === 'ready') {
|
||||
title = tr('updateCapsuleReady', { v: latest })
|
||||
action = <button type="button" className="update-capsule-btn is-primary" onClick={onInstall}>{tr('updateRestart')}</button>
|
||||
} else if (phase === 'failed') {
|
||||
title = tr('updateCapsuleFailed')
|
||||
action = (
|
||||
<button type="button" className="update-capsule-btn" onClick={onDownload}>
|
||||
<RotateCw size={11} aria-hidden="true" />{tr('updateRetry')}
|
||||
</button>
|
||||
)
|
||||
} else {
|
||||
title = tr('updateCapsuleAvailable', { v: latest })
|
||||
action = <button type="button" className="update-capsule-btn" onClick={onDownload}>{tr('updateDownload')}</button>
|
||||
close = (
|
||||
<Tip label={tr('updateLater')} side="right">
|
||||
<button type="button" className="update-capsule-x" aria-label={tr('updateLater')} onClick={onDismiss}><X size={12} /></button>
|
||||
</Tip>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`update-capsule is-${phase}`} role="status">
|
||||
<button type="button" className="update-capsule-main" onClick={onOpen} title={tr('updateCapsuleOpen')}>
|
||||
<span className="update-capsule-icon" aria-hidden="true"><ArrowDownToLine size={12} /></span>
|
||||
<span className="update-capsule-title">{title}</span>
|
||||
</button>
|
||||
{action}
|
||||
{close}
|
||||
{phase === 'downloading' && (
|
||||
<span className="update-capsule-bar" aria-hidden="true">
|
||||
<span className={pct === null ? 'is-indeterminate' : ''} style={pct === null ? undefined : { width: `${pct}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</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).
|
||||
// Human-readable values for the main view (docs/design-guidelines.md §7.1).
|
||||
// Raw values stay available under "Technical details".
|
||||
|
||||
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 null
|
||||
const n = Number(m[1])
|
||||
const unit = (m[2] ?? 'M').toUpperCase()
|
||||
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 m = /^\s*(\d+(?:\.\d+)?)\s*([KMGT])?(?:i?B)?\s*$/i.exec(raw ?? '')
|
||||
if (!m) return raw
|
||||
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
|
||||
const gb = parseMemoryGB(raw)
|
||||
if (gb === null) return raw
|
||||
const rounded = gb >= 10 ? Math.round(gb) : Math.round(gb * 10) / 10
|
||||
return `${rounded} GB`
|
||||
}
|
||||
@@ -24,9 +62,63 @@ export function controllerLabel(raw: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function findGPU(host: HostReport, icd: string): GPUInfo | undefined {
|
||||
const norm = (s: string) => s.replace(/\//g, '\\').toLowerCase()
|
||||
return (host.gpus ?? []).find((g) => norm(g.vulkan_icd) === norm(icd))
|
||||
const normPath = (s: string) => s.replace(/\//g, '\\').toLowerCase()
|
||||
|
||||
export function gpuKey(g: GPUInfo, idx = 0): string {
|
||||
const pci = g.vendor_id && g.device_id ? `${g.vendor_id}:${g.device_id}` : ''
|
||||
return `${pci}|${normPath(g.vulkan_icd || '')}|${g.name}|${idx}`
|
||||
}
|
||||
|
||||
export function sameGPU(a?: GPUInfo, b?: GPUInfo): boolean {
|
||||
if (!a || !b) return false
|
||||
if (a.vendor_id && a.device_id && b.vendor_id && b.device_id) {
|
||||
return a.vendor_id === b.vendor_id && a.device_id === b.device_id
|
||||
}
|
||||
return !!a.vulkan_icd && normPath(a.vulkan_icd) === normPath(b.vulkan_icd) && a.name === b.name
|
||||
}
|
||||
|
||||
/** Stable `--gpu` value for a GPU: its ICD path when unique, else its name (for shared AMD ICDs). */
|
||||
export function gpuOptionValue(g: GPUInfo, all: GPUInfo[]): string {
|
||||
if (g.vulkan_icd) {
|
||||
const target = normPath(g.vulkan_icd)
|
||||
const shared = all.filter((o) => o.vulkan_icd && normPath(o.vulkan_icd) === target).length > 1
|
||||
if (!shared) return g.vulkan_icd
|
||||
}
|
||||
return g.name
|
||||
}
|
||||
|
||||
export function findGPU(host: HostReport, value: string | undefined): GPUInfo | undefined {
|
||||
if (!value || value === 'auto') return host.recommended_gpu
|
||||
const norm = normPath(value)
|
||||
return (host.gpus ?? []).find(
|
||||
(g) => (g.vulkan_icd && normPath(g.vulkan_icd) === norm) || g.name.toLowerCase() === value.toLowerCase(),
|
||||
)
|
||||
}
|
||||
|
||||
export function gpuMetaLine(g: GPUInfo): string {
|
||||
const parts: string[] = []
|
||||
if (g.vendor_id && g.device_id) parts.push(`${g.vendor_id}:${g.device_id}`)
|
||||
if (g.vulkan_version) parts.push(`Vulkan ${g.vulkan_version}`)
|
||||
if (g.driver_version) parts.push(g.driver_version)
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
export function gpuCompatHint(locale: Locale, g?: GPUInfo): string {
|
||||
if (!g) return ''
|
||||
switch (g.compat_code) {
|
||||
case 'amd_legacy_win_driver':
|
||||
return t(locale, 'gpuWarnAmdLegacy', { ref: g.compat_detail || 'steelbrain/reims-vgpu#181' })
|
||||
case 'amd_rdna2_device_lost':
|
||||
return t(locale, 'gpuWarnAmdRdna2', { ref: g.compat_detail || 'steelbrain/reims-vgpu#173' })
|
||||
case 'vulkan_too_old':
|
||||
return t(locale, 'gpuErrVulkanTooOld', { ver: g.compat_detail || g.vulkan_version || '?' })
|
||||
case 'vulkan_missing_extensions':
|
||||
return t(locale, 'gpuErrMissingExt', { ext: g.compat_detail || '' })
|
||||
case 'vulkan_cpu':
|
||||
return t(locale, 'gpuErrVulkanCpu')
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop vendor boilerplate: "NVIDIA GeForce RTX 4070 Ti" → "RTX 4070 Ti". */
|
||||
@@ -46,15 +138,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 +158,157 @@ 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.toLowerCase().startsWith('zh')) {
|
||||
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 {
|
||||
const l = locale.toLowerCase()
|
||||
if (l === 'zh-tw' || l === 'zh-hk' || l === 'zh-mo' || l.startsWith('zh-hant')) return 'zh-Hant:0'
|
||||
if (l.startsWith('zh')) return 'zh-Hans:0'
|
||||
if (l.startsWith('ja')) return 'ja-JP:0'
|
||||
if (l.startsWith('ko')) return 'ko-KR:0'
|
||||
return 'en-US: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.toLowerCase().startsWith('zh') ? 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)}`
|
||||
}
|
||||
@@ -11,15 +11,18 @@ export const MAX_LOG_LINES = 2000
|
||||
|
||||
// Progress no longer reaches the log: the backend turns it into tasks
|
||||
// (tasks.go, "reims:task"). Levels are still guessed from the text until the
|
||||
// backend tags them (docs/ui-redesign.md §6 B2).
|
||||
// backend tags them explicitly.
|
||||
const ERROR_RE = /\b(error|failed|fatal|panic)\b/i
|
||||
const WARN_RE = /\bwarn(ing)?\b/i
|
||||
|
||||
let nextId = 1
|
||||
|
||||
export function classify(entry: LogEntry): LogLine {
|
||||
const level: LogLevel = ERROR_RE.test(entry.line) ? 'error' : WARN_RE.test(entry.line) ? 'warn' : 'info'
|
||||
return { ...entry, id: nextId++, level }
|
||||
const ts = typeof entry?.ts === 'string' ? entry.ts : ''
|
||||
const source = typeof entry?.source === 'string' ? entry.source : ''
|
||||
const line = typeof entry?.line === 'string' ? entry.line : String(entry?.line ?? '')
|
||||
const level: LogLevel = ERROR_RE.test(line) ? 'error' : WARN_RE.test(line) ? 'warn' : 'info'
|
||||
return { ts, source, line, id: nextId++, level }
|
||||
}
|
||||
|
||||
export function appendLog(prev: LogLine[], entry: LogEntry): LogLine[] {
|
||||
|
||||
@@ -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,8 +32,10 @@ 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 })
|
||||
case 'app-update': return t(locale, 'taskAppUpdate', { v: task.subject })
|
||||
default: return task.subject
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
// Three-tier Theme Engine (docs/plugin-architecture.md §5.1):
|
||||
// - Builtin theme: zero extra CSS injected, zero UI SDK loaded (§8.1).
|
||||
// - Tier 1 (Token theme): seed colors + declarative lightness/chroma/alpha derivation,
|
||||
// bundled fonts, brand mark, background, and event sounds.
|
||||
// - Tier 2 (Style theme): sanitized stylesheet wrapped in `@layer theme` +
|
||||
// declarative state-driven slot decorations.
|
||||
// - Tier 3 (Interactive theme): lazy-loads `./uiSdk` only when a trusted `ui_script_url` is active.
|
||||
|
||||
import { UI_CONTRACT_TOKENS } from '../styles/ui-contract'
|
||||
import type { ActiveThemePayload, ThemeDecoration, ThemeDecorationState, TokenDeriveRule } from '../types'
|
||||
|
||||
const LEGACY_CACHE_KEY = 'reims-go-theme-tokens-v1'
|
||||
const THEME_CACHE_KEY = 'reims-go-theme-tokens-v2'
|
||||
const PREPAINT_EL_ID = 'rg-theme-prepaint'
|
||||
const STYLE_EL_ID = 'rg-active-theme-style'
|
||||
const FONT_EL_ID = 'rg-active-theme-fonts'
|
||||
|
||||
const ALLOWED_CONTRACT_TOKENS = new Set<string>(UI_CONTRACT_TOKENS)
|
||||
const RE_FONT_WEIGHT = /^[0-9a-zA-Z -]+$/
|
||||
const RE_FONT_STYLE = /^(normal|italic|oblique( +-?[0-9]+(\.[0-9]+)?deg)?)$/
|
||||
const RE_UNICODE_RANGE = /^[U+0-9a-fA-F?, -]+$/
|
||||
const RE_SAFE_ASSET_REL = /^[a-zA-Z0-9._/@ -]+$/
|
||||
const RE_ASSET_BASE_URL = /^\/plugin-assets\/[a-f0-9]+\/[a-z0-9][a-z0-9._-]*\/$/
|
||||
const RE_SCHEME = /^[a-zA-Z][a-zA-Z0-9+.-]*:/
|
||||
const FORBIDDEN_FOCUS_RING_VALUES = new Set(['none', '0', '0px', 'transparent', 'initial', 'unset', 'revert', 'revert-layer'])
|
||||
|
||||
interface ThemeTokenCache {
|
||||
themeId: string
|
||||
activeScheme: string
|
||||
light?: Record<string, string>
|
||||
dark?: Record<string, string>
|
||||
}
|
||||
|
||||
export interface UIStateSnapshot {
|
||||
appearance: 'light' | 'dark'
|
||||
motion: 'full' | 'reduced'
|
||||
view: string
|
||||
vmName: string
|
||||
vmState: string
|
||||
busy: boolean
|
||||
hasError: boolean
|
||||
sidebarCollapsed: boolean
|
||||
safeMode: boolean
|
||||
vms: Array<{ name: string; state: string }>
|
||||
}
|
||||
|
||||
export interface ThemeSDKHostActions {
|
||||
toggleSidebar: () => void
|
||||
openSettings: () => void
|
||||
focusVMWindow: (name: string) => void
|
||||
}
|
||||
|
||||
let activeUIScriptCleanup: (() => void) | null = null
|
||||
let activeUIScriptURL = ''
|
||||
let applyGeneration = 0
|
||||
|
||||
function decodeCSSEscapes(s: string): string {
|
||||
if (!s.includes('\\')) return s
|
||||
let out = ''
|
||||
for (let i = 0; i < s.length; ) {
|
||||
if (s[i] === '\\' && i + 1 < s.length) {
|
||||
i++
|
||||
const hexMatch = /^[0-9a-fA-F]{1,6}(?:\r\n|[ \t\n\r\f])?/.exec(s.slice(i))
|
||||
if (hexMatch) {
|
||||
const cp = parseInt(hexMatch[0].trim(), 16)
|
||||
out += cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : '\uFFFD'
|
||||
i += hexMatch[0].length
|
||||
} else {
|
||||
out += s[i]
|
||||
i++
|
||||
}
|
||||
} else {
|
||||
out += s[i]
|
||||
i++
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Validates a token key+value against the UI Contract whitelist and CSS injection rules (B5). */
|
||||
export function sanitizeTokenValue(key: string, value: string): string | null {
|
||||
if (!ALLOWED_CONTRACT_TOKENS.has(key)) return null
|
||||
if (typeof value !== 'string') return null
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed || /[\r\n\0{};]/.test(trimmed) || trimmed.endsWith('\\')) return null
|
||||
if (trimmed.includes('/*') || trimmed.includes('*/')) return null
|
||||
const decoded = decodeCSSEscapes(trimmed).toLowerCase()
|
||||
if (/[\r\n\0{};]/.test(decoded)) return null
|
||||
for (const bad of ['</style', 'url(', 'src(', 'image-set(', '-webkit-image-set(', 'expression(', '@import', 'javascript:', 'data:', 'http://', 'https://', '//']) {
|
||||
if (decoded.includes(bad)) return null
|
||||
}
|
||||
if (key === '--focus-ring' && (FORBIDDEN_FOCUS_RING_VALUES.has(decoded) || /\btransparent\b/.test(decoded))) {
|
||||
return null
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
function sanitizeRelativeAssetPath(rel: string): string | null {
|
||||
if (typeof rel !== 'string') return null
|
||||
const cleaned = rel.trim().replace(/^\/+/, '')
|
||||
if (!cleaned || /["'\\;{}()\r\n\0]/.test(cleaned) || !RE_SAFE_ASSET_REL.test(cleaned)) return null
|
||||
if (RE_SCHEME.test(cleaned)) return null
|
||||
for (const seg of cleaned.split('/')) {
|
||||
if (seg === '..') return null
|
||||
}
|
||||
return cleaned
|
||||
}
|
||||
|
||||
/** Verifies stylesheet has balanced braces and no unclosed strings/comments so it cannot escape `@layer theme` (B5). */
|
||||
export function isBalancedThemeCSS(css: string): boolean {
|
||||
if (css.toLowerCase().includes('</style')) return false
|
||||
let depth = 0
|
||||
const n = css.length
|
||||
for (let i = 0; i < n; ) {
|
||||
const c = css[i]
|
||||
if (c === '/' && i + 1 < n && css[i + 1] === '*') {
|
||||
const end = css.indexOf('*/', i + 2)
|
||||
if (end < 0) return false
|
||||
i = end + 2
|
||||
continue
|
||||
}
|
||||
if (c === '"' || c === "'") {
|
||||
const q = c
|
||||
i++
|
||||
let closed = false
|
||||
while (i < n) {
|
||||
if (css[i] === '\\') {
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
if (css[i] === '\n' || css[i] === '\r') return false
|
||||
if (css[i] === q) {
|
||||
i++
|
||||
closed = true
|
||||
break
|
||||
}
|
||||
i++
|
||||
}
|
||||
if (!closed) return false
|
||||
continue
|
||||
}
|
||||
if (c === '\\') {
|
||||
// Backslash escapes the next char (e.g. `\{` or `\}`) outside strings so it cannot affect brace depth.
|
||||
if (i + 1 >= n) return false
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
if (c === '{') depth++
|
||||
else if (c === '}') {
|
||||
depth--
|
||||
if (depth < 0) return false
|
||||
}
|
||||
i++
|
||||
}
|
||||
return depth === 0
|
||||
}
|
||||
|
||||
function resolveInitialAppearance(): 'light' | 'dark' {
|
||||
try {
|
||||
const saved = localStorage.getItem('reims-go-theme')
|
||||
if (saved === 'dark' || saved === 'light') return saved
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
}
|
||||
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
||||
}
|
||||
|
||||
function clearLegacyInlineCache(): void {
|
||||
try {
|
||||
const raw = localStorage.getItem(LEGACY_CACHE_KEY)
|
||||
if (raw) {
|
||||
const prev = JSON.parse(raw) as Record<string, string>
|
||||
if (prev && typeof prev === 'object') {
|
||||
for (const k of Object.keys(prev)) {
|
||||
if (k.startsWith('--')) document.documentElement.style.removeProperty(k)
|
||||
}
|
||||
}
|
||||
localStorage.removeItem(LEGACY_CACHE_KEY)
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
function buildTokenVarLines(tokens: Record<string, string>): string {
|
||||
const lines: string[] = []
|
||||
for (const [k, v] of Object.entries(tokens)) {
|
||||
const safe = sanitizeTokenValue(k, v)
|
||||
if (safe) lines.push(` ${k}: ${safe};`)
|
||||
}
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies cached theme tokens via a `@layer theme` `<style>` element (never
|
||||
* inline `element.style`, B8) keyed by appearance to avoid FOUC (§5.1).
|
||||
*/
|
||||
export function applyCachedThemeTokensSync(): void {
|
||||
clearLegacyInlineCache()
|
||||
try {
|
||||
const raw = localStorage.getItem(THEME_CACHE_KEY)
|
||||
if (!raw) return
|
||||
const cache = JSON.parse(raw) as ThemeTokenCache
|
||||
if (!cache || typeof cache !== 'object') return
|
||||
const appearance = resolveInitialAppearance()
|
||||
const tokens = cache[appearance]
|
||||
if (!tokens || typeof tokens !== 'object') return
|
||||
const varLines = buildTokenVarLines(tokens)
|
||||
if (!varLines) return
|
||||
let el = document.getElementById(PREPAINT_EL_ID) as HTMLStyleElement | null
|
||||
if (!el) {
|
||||
el = document.createElement('style')
|
||||
el.id = PREPAINT_EL_ID
|
||||
document.head.appendChild(el)
|
||||
}
|
||||
el.textContent = `@layer theme {\n:root {\n${varLines}\n}\n}`
|
||||
} catch {
|
||||
// ignore corrupt cache
|
||||
}
|
||||
}
|
||||
|
||||
function clearDynamicThemeStyles(): void {
|
||||
document.getElementById(PREPAINT_EL_ID)?.remove()
|
||||
document.getElementById(STYLE_EL_ID)?.remove()
|
||||
document.getElementById(FONT_EL_ID)?.remove()
|
||||
clearLegacyInlineCache()
|
||||
try {
|
||||
localStorage.removeItem(THEME_CACHE_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
/** Parses a #RGB or #RRGGBB hex string into [h (0..360), s (0..1), l (0..1)]. */
|
||||
function hexToHSL(hex: string): [number, number, number] | null {
|
||||
const clean = hex.trim().replace(/^#/, '')
|
||||
let r = 0, g = 0, b = 0
|
||||
if (clean.length === 3) {
|
||||
r = parseInt(clean[0] + clean[0], 16) / 255
|
||||
g = parseInt(clean[1] + clean[1], 16) / 255
|
||||
b = parseInt(clean[2] + clean[2], 16) / 255
|
||||
} else if (clean.length === 6) {
|
||||
r = parseInt(clean.slice(0, 2), 16) / 255
|
||||
g = parseInt(clean.slice(2, 4), 16) / 255
|
||||
b = parseInt(clean.slice(4, 6), 16) / 255
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) return null
|
||||
const max = Math.max(r, g, b)
|
||||
const min = Math.min(r, g, b)
|
||||
const l = (max + min) / 2
|
||||
if (max === min) return [0, 0, l]
|
||||
const d = max - min
|
||||
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
|
||||
let h = 0
|
||||
if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6
|
||||
else if (max === g) h = ((b - r) / d + 2) / 6
|
||||
else h = ((r - g) / d + 4) / 6
|
||||
return [h * 360, s, l]
|
||||
}
|
||||
|
||||
function clamp01(x: number): number {
|
||||
return Math.max(0, Math.min(1, x))
|
||||
}
|
||||
|
||||
/** Derives CSS variable values from seed colors using declarative rules (§5.1). */
|
||||
export function deriveTokensFromSeeds(
|
||||
seeds: Record<string, string>,
|
||||
rules: TokenDeriveRule[] | undefined,
|
||||
appearance: 'light' | 'dark',
|
||||
): Record<string, string> {
|
||||
const out: Record<string, string> = {}
|
||||
if (seeds.accent) {
|
||||
const hsl = hexToHSL(seeds.accent)
|
||||
out['--accent'] = seeds.accent
|
||||
if (hsl) {
|
||||
const [h, s, l] = hsl
|
||||
out['--accent-hover'] = `hsl(${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(clamp01(l + (appearance === 'dark' ? 0.06 : -0.06)) * 100)}%)`
|
||||
out['--accent-soft'] = `hsla(${Math.round(h)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%, ${appearance === 'dark' ? 0.2 : 0.12})`
|
||||
out['--accent-soft-text'] = `hsl(${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(clamp01(appearance === 'dark' ? Math.max(l, 0.66) : Math.min(l, 0.42)) * 100)}%)`
|
||||
out['--focus-ring'] = `0 0 0 3px hsla(${Math.round(h)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%, ${appearance === 'dark' ? 0.45 : 0.30})`
|
||||
}
|
||||
}
|
||||
if (seeds.surface) {
|
||||
out['--surface-0'] = seeds.surface
|
||||
out['--surface-canvas'] = seeds.surface
|
||||
}
|
||||
if (seeds.text) {
|
||||
out['--text'] = seeds.text
|
||||
}
|
||||
for (const rule of rules ?? []) {
|
||||
if (rule.appearance && rule.appearance !== appearance) continue
|
||||
if (!ALLOWED_CONTRACT_TOKENS.has(rule.token)) continue
|
||||
const seedVal = seeds[rule.fromSeed]
|
||||
if (!seedVal) continue
|
||||
const hsl = hexToHSL(seedVal)
|
||||
if (!hsl) continue
|
||||
const h = Math.round(hsl[0])
|
||||
const s = Math.round(clamp01(rule.chroma && rule.chroma > 0 ? hsl[1] * rule.chroma : hsl[1]) * 100)
|
||||
const l = Math.round(clamp01(hsl[2] + (rule.lightness ?? 0)) * 100)
|
||||
if (rule.alpha && rule.alpha > 0 && rule.alpha < 1) {
|
||||
out[rule.token] = `hsla(${h}, ${s}%, ${l}%, ${rule.alpha.toFixed(3)})`
|
||||
} else {
|
||||
out[rule.token] = `hsl(${h} ${s}% ${l}%)`
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Evaluates a declarative ThemeDecoration state expression (e.g. "vmState==running"). */
|
||||
export function matchDecorationState(
|
||||
decoration: ThemeDecoration,
|
||||
snap: UIStateSnapshot,
|
||||
): ThemeDecorationState | null {
|
||||
let fallback: ThemeDecorationState | null = null
|
||||
for (const st of decoration.states ?? []) {
|
||||
const expr = (st.when || '').trim()
|
||||
if (!expr || expr === 'default') {
|
||||
fallback = st
|
||||
continue
|
||||
}
|
||||
const [rawKey, rawVal] = expr.split('==').map((s) => s.trim())
|
||||
if (!rawKey) continue
|
||||
const map: Record<string, string> = {
|
||||
vmState: snap.vmState,
|
||||
view: snap.view,
|
||||
theme: snap.appearance,
|
||||
busy: String(snap.busy),
|
||||
hasError: String(snap.hasError),
|
||||
sidebarCollapsed: String(snap.sidebarCollapsed),
|
||||
}
|
||||
if (map[rawKey] === rawVal) return st
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
/** Applies the active theme payload to the document, tearing down any previous theme first. */
|
||||
export async function applyActiveTheme(
|
||||
payload: ActiveThemePayload | null,
|
||||
appearance: 'light' | 'dark',
|
||||
getState: () => UIStateSnapshot,
|
||||
actions: ThemeSDKHostActions,
|
||||
): Promise<void> {
|
||||
const gen = ++applyGeneration
|
||||
|
||||
// Always drop prepaint & legacy inline tokens so live theme/builtin always wins (B8).
|
||||
document.getElementById(PREPAINT_EL_ID)?.remove()
|
||||
clearLegacyInlineCache()
|
||||
|
||||
// Always tear down previous interactive theme script if URL changed or disabled.
|
||||
const nextScriptURL = payload?.ui_script_url ?? ''
|
||||
if (activeUIScriptCleanup && activeUIScriptURL !== nextScriptURL) {
|
||||
try { activeUIScriptCleanup() } catch {}
|
||||
activeUIScriptCleanup = null
|
||||
activeUIScriptURL = ''
|
||||
}
|
||||
|
||||
// Builtin default theme (or safe mode) -> zero extra CSS injected (§8.1).
|
||||
if (!payload || !payload.theme || payload.theme_id === 'builtin.theme.default') {
|
||||
clearDynamicThemeStyles()
|
||||
return
|
||||
}
|
||||
|
||||
const th = payload.theme
|
||||
const rawBaseURL = payload.asset_base_url ?? ''
|
||||
const baseURL = RE_ASSET_BASE_URL.test(rawBaseURL) && !rawBaseURL.includes('..') ? rawBaseURL : ''
|
||||
|
||||
// 1. Resolve active seed colors (custom scheme -> built-in scheme -> theme default seeds).
|
||||
let seeds: Record<string, string> = { ...(th.seeds ?? {}) }
|
||||
if (payload.active_scheme) {
|
||||
const custom = (payload.custom_schemes ?? []).find((s) => s.id === payload.active_scheme && s.theme_id === payload.theme_id)
|
||||
const preset = (th.schemes ?? []).find((s) => s.id === payload.active_scheme)
|
||||
if (custom?.seeds) seeds = { ...seeds, ...custom.seeds }
|
||||
else if (preset?.seeds) seeds = { ...seeds, ...preset.seeds }
|
||||
}
|
||||
|
||||
// 2. Compute derived + explicit tokens and filter strictly through UI Contract whitelist (B5).
|
||||
const rawTokens: Record<string, string> = {
|
||||
...deriveTokensFromSeeds(seeds, th.deriveRules, appearance),
|
||||
...(th.tokens ?? {}),
|
||||
...(appearance === 'dark' ? (th.darkTokens ?? {}) : {}),
|
||||
}
|
||||
const sanitizedTokens: Record<string, string> = {}
|
||||
for (const [k, v] of Object.entries(rawTokens)) {
|
||||
const safe = sanitizeTokenValue(k, v)
|
||||
if (safe) sanitizedTokens[k] = safe
|
||||
}
|
||||
|
||||
// 3. Inject validated bundled @font-face declarations (B5).
|
||||
let fontCSS = ''
|
||||
for (const f of th.fonts ?? []) {
|
||||
const family = typeof f.family === 'string' ? f.family.trim() : ''
|
||||
if (!family || /["'\\;{}\r\n\0]/.test(family) || family.toLowerCase().includes('</style')) continue
|
||||
const safeFile = sanitizeRelativeAssetPath(f.file)
|
||||
if (!safeFile || !baseURL) continue
|
||||
const safeURL = baseURL + safeFile
|
||||
const weight = f.weight && RE_FONT_WEIGHT.test(f.weight) ? `font-weight:${f.weight};` : ''
|
||||
const style = f.style && RE_FONT_STYLE.test(f.style.trim()) ? `font-style:${f.style.trim()};` : ''
|
||||
const range = f.unicodeRange && RE_UNICODE_RANGE.test(f.unicodeRange) ? `unicode-range:${f.unicodeRange};` : ''
|
||||
fontCSS += `@font-face{font-family:"${family}";src:url("${safeURL}");font-display:swap;${weight}${style}${range}}\n`
|
||||
}
|
||||
if (fontCSS) {
|
||||
let el = document.getElementById(FONT_EL_ID) as HTMLStyleElement | null
|
||||
if (!el) {
|
||||
el = document.createElement('style')
|
||||
el.id = FONT_EL_ID
|
||||
document.head.appendChild(el)
|
||||
}
|
||||
el.textContent = fontCSS
|
||||
} else {
|
||||
document.getElementById(FONT_EL_ID)?.remove()
|
||||
}
|
||||
|
||||
// 4. Write validated token CSS + Tier-2 stylesheet wrapped inside `@layer theme` (§5.1, B5/B7).
|
||||
const varLines = buildTokenVarLines(sanitizedTokens)
|
||||
let bgCSS = ''
|
||||
if (th.background && baseURL) {
|
||||
const safeBg = sanitizeRelativeAssetPath(th.background)
|
||||
if (safeBg) {
|
||||
bgCSS = `.rg-p-shell { background-image: url("${baseURL}${safeBg}"); background-size: cover; }\n`
|
||||
}
|
||||
}
|
||||
const rawThemeCSS = payload.css && isBalancedThemeCSS(payload.css) ? payload.css : ''
|
||||
const fullCSS = `@layer theme {\n:root {\n${varLines}\n}\n${bgCSS}${rawThemeCSS}\n}`
|
||||
|
||||
let styleEl = document.getElementById(STYLE_EL_ID) as HTMLStyleElement | null
|
||||
if (!styleEl) {
|
||||
styleEl = document.createElement('style')
|
||||
styleEl.id = STYLE_EL_ID
|
||||
document.head.appendChild(styleEl)
|
||||
}
|
||||
styleEl.textContent = fullCSS
|
||||
|
||||
// Persist appearance-keyed cache for prepaint (B8).
|
||||
try {
|
||||
let nextCache: ThemeTokenCache = {
|
||||
themeId: payload.theme_id,
|
||||
activeScheme: payload.active_scheme ?? '',
|
||||
}
|
||||
const prevRaw = localStorage.getItem(THEME_CACHE_KEY)
|
||||
if (prevRaw) {
|
||||
const prev = JSON.parse(prevRaw) as ThemeTokenCache
|
||||
if (prev && prev.themeId === nextCache.themeId && prev.activeScheme === nextCache.activeScheme) {
|
||||
nextCache = { ...prev }
|
||||
}
|
||||
}
|
||||
nextCache[appearance] = sanitizedTokens
|
||||
localStorage.setItem(THEME_CACHE_KEY, JSON.stringify(nextCache))
|
||||
} catch {
|
||||
// ignore storage quota
|
||||
}
|
||||
|
||||
// 5. Tier 3: lazy-load UI SDK ONLY when an approved interactive theme script is present (§8.1).
|
||||
if (nextScriptURL && nextScriptURL !== activeUIScriptURL) {
|
||||
try {
|
||||
const { mountInteractiveThemeScript } = await import('./uiSdk')
|
||||
if (gen !== applyGeneration) return
|
||||
const cleanup = await mountInteractiveThemeScript(nextScriptURL, getState, actions)
|
||||
if (gen !== applyGeneration) {
|
||||
try { cleanup() } catch {}
|
||||
return
|
||||
}
|
||||
activeUIScriptCleanup = cleanup
|
||||
activeUIScriptURL = nextScriptURL
|
||||
} catch {
|
||||
if (gen === applyGeneration) {
|
||||
// Fallback gracefully to the scriptless style/token theme (§4.2).
|
||||
activeUIScriptCleanup = null
|
||||
activeUIScriptURL = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Plays a theme-configured sound for an event if present (fail-silent). */
|
||||
export function playThemeSound(payload: ActiveThemePayload | null, eventName: string): void {
|
||||
const file = payload?.theme?.sounds?.[eventName]
|
||||
if (!file || !payload?.asset_base_url) return
|
||||
const safe = sanitizeRelativeAssetPath(file)
|
||||
if (!safe) return
|
||||
try {
|
||||
const audio = new Audio(payload.asset_base_url + safe)
|
||||
audio.volume = 0.35
|
||||
void audio.play().catch(() => {})
|
||||
} catch {
|
||||
// ignore audio decode/autoplay errors
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
// Lazy-loaded Tier-3 Interactive Theme UI SDK (docs/plugin-architecture.md §5.1).
|
||||
// Loaded ONLY when a trusted interactive theme with `ui:script` is enabled (§8.1).
|
||||
|
||||
import { UI_API_VERSION, UI_CONTRACT_PARTS, UI_CONTRACT_SLOTS, type UIContractPart, type UIContractSlot } from '../styles/ui-contract'
|
||||
import { hideWailsGlobals } from '../wails'
|
||||
import type { ThemeSDKHostActions, UIStateSnapshot } from './themeEngine'
|
||||
|
||||
export interface ReimsUISDK {
|
||||
readonly uiApi: string
|
||||
/** Registers a cleanup callback run in LIFO order on theme switch/disable. */
|
||||
onDispose: (fn: () => void) => void
|
||||
/** Runs a named feature isolated so errors disable only that feature. */
|
||||
feature: (name: string, setup: (dispose: (fn: () => void) => void) => void) => void
|
||||
/** Read-only non-sensitive state snapshot & subscription. */
|
||||
getState: () => UIStateSnapshot
|
||||
subscribeState: (cb: (snap: UIStateSnapshot) => void) => () => void
|
||||
/** Queries elements strictly by contract part class (`rg-p-*`). */
|
||||
queryPart: (part: UIContractPart) => HTMLElement | null
|
||||
/** Shared MutationObserver bus scoped to a contract part. */
|
||||
observePart: (part: UIContractPart, cb: () => void) => () => void
|
||||
/** Shared RAF read/write batch pipeline to avoid layout thrashing. */
|
||||
scheduleRead: (fn: () => void) => void
|
||||
scheduleWrite: (fn: () => void) => void
|
||||
/** Framework-agnostic DOM mounting into a declared slot anchor. */
|
||||
mountSlot: (slot: UIContractSlot, node: HTMLElement) => () => void
|
||||
/** Restricted non-destructive UI actions only (no start/stop/delete/config write). */
|
||||
actions: ThemeSDKHostActions
|
||||
}
|
||||
|
||||
const stateListeners = new Set<(snap: UIStateSnapshot) => void>()
|
||||
|
||||
export function notifyThemeSDKState(snap: UIStateSnapshot): void {
|
||||
if (stateListeners.size === 0) return
|
||||
for (const cb of stateListeners) {
|
||||
try { cb(snap) } catch {}
|
||||
}
|
||||
}
|
||||
|
||||
// Shared RAF read/write pipeline.
|
||||
let readQueue: Array<() => void> = []
|
||||
let writeQueue: Array<() => void> = []
|
||||
let rafScheduled = false
|
||||
|
||||
function flushFrame() {
|
||||
rafScheduled = false
|
||||
const reads = readQueue
|
||||
const writes = writeQueue
|
||||
readQueue = []
|
||||
writeQueue = []
|
||||
for (const r of reads) { try { r() } catch {} }
|
||||
for (const w of writes) { try { w() } catch {} }
|
||||
}
|
||||
|
||||
function scheduleRAF() {
|
||||
if (rafScheduled) return
|
||||
rafScheduled = true
|
||||
requestAnimationFrame(flushFrame)
|
||||
}
|
||||
|
||||
export async function mountInteractiveThemeScript(
|
||||
scriptURL: string,
|
||||
getState: () => UIStateSnapshot,
|
||||
actions: ThemeSDKHostActions,
|
||||
): Promise<() => void> {
|
||||
if (!scriptURL.startsWith('/plugin-assets/') || scriptURL.includes('..')) {
|
||||
throw new Error('Refused to load theme script outside /plugin-assets/')
|
||||
}
|
||||
let disposed = false
|
||||
const disposers = new Set<() => void>()
|
||||
const partSet = new Set<string>(UI_CONTRACT_PARTS)
|
||||
const slotSet = new Set<string>(UI_CONTRACT_SLOTS)
|
||||
|
||||
const addDisposer = (fn: () => void) => {
|
||||
if (disposed) return
|
||||
disposers.add(fn)
|
||||
}
|
||||
|
||||
const disposeAll = () => {
|
||||
if (disposed) return
|
||||
disposed = true
|
||||
const list = Array.from(disposers).reverse()
|
||||
disposers.clear()
|
||||
for (const fn of list) {
|
||||
try { fn() } catch {}
|
||||
}
|
||||
}
|
||||
|
||||
const sdk: ReimsUISDK = {
|
||||
uiApi: UI_API_VERSION,
|
||||
onDispose: addDisposer,
|
||||
feature: (_name, setup) => {
|
||||
if (disposed) return
|
||||
const localDisposers: Array<() => void> = []
|
||||
const localDispose = () => {
|
||||
while (localDisposers.length > 0) {
|
||||
try { localDisposers.pop()?.() } catch {}
|
||||
}
|
||||
}
|
||||
addDisposer(localDispose)
|
||||
try {
|
||||
setup((fn) => localDisposers.push(fn))
|
||||
} catch {
|
||||
// Feature-isolated error: tear down only this feature (§4.2, §5.1).
|
||||
localDispose()
|
||||
}
|
||||
},
|
||||
getState: () => {
|
||||
const s = getState()
|
||||
return { ...s, vms: s.vms.map((v) => ({ ...v })) }
|
||||
},
|
||||
subscribeState: (cb) => {
|
||||
if (disposed) return () => {}
|
||||
stateListeners.add(cb)
|
||||
const off = () => {
|
||||
stateListeners.delete(cb)
|
||||
disposers.delete(off)
|
||||
}
|
||||
addDisposer(off)
|
||||
return off
|
||||
},
|
||||
queryPart: (part) => {
|
||||
if (disposed || !partSet.has(part)) return null
|
||||
return document.querySelector<HTMLElement>(`.${part}`)
|
||||
},
|
||||
observePart: (part, cb) => {
|
||||
if (disposed || !partSet.has(part)) return () => {}
|
||||
const target = document.querySelector<HTMLElement>(`.${part}`)
|
||||
if (!target) return () => {}
|
||||
const obs = new MutationObserver(() => {
|
||||
if (disposed) return
|
||||
try { cb() } catch {}
|
||||
})
|
||||
obs.observe(target, { attributes: true, childList: true, subtree: false })
|
||||
const off = () => {
|
||||
obs.disconnect()
|
||||
disposers.delete(off)
|
||||
}
|
||||
addDisposer(off)
|
||||
return off
|
||||
},
|
||||
scheduleRead: (fn) => {
|
||||
if (disposed) return
|
||||
readQueue.push(() => { if (!disposed) fn() })
|
||||
scheduleRAF()
|
||||
},
|
||||
scheduleWrite: (fn) => {
|
||||
if (disposed) return
|
||||
writeQueue.push(() => { if (!disposed) fn() })
|
||||
scheduleRAF()
|
||||
},
|
||||
mountSlot: (slot, node) => {
|
||||
if (disposed || !slotSet.has(slot)) return () => {}
|
||||
const host = document.querySelector<HTMLElement>(`[data-rg-slot="${CSS.escape(slot)}"]`)
|
||||
if (!host) return () => {}
|
||||
host.appendChild(node)
|
||||
const off = () => {
|
||||
node.remove()
|
||||
disposers.delete(off)
|
||||
}
|
||||
addDisposer(off)
|
||||
return off
|
||||
},
|
||||
actions: {
|
||||
toggleSidebar: actions.toggleSidebar,
|
||||
openSettings: actions.openSettings,
|
||||
focusVMWindow: actions.focusVMWindow,
|
||||
},
|
||||
}
|
||||
|
||||
// Hide Wails binding globals from `window` before executing any theme script,
|
||||
// and shadow bridge identifiers inside its closure (§5.1, B6). Note: scripts
|
||||
// in the main window still run in the same DOM realm, so `ui:script` remains
|
||||
// a high-trust permission requiring explicit user approval.
|
||||
hideWailsGlobals()
|
||||
|
||||
const resp = await fetch(scriptURL, { credentials: 'same-origin' })
|
||||
if (!resp.ok) throw new Error(`Failed to fetch theme script (${resp.status})`)
|
||||
const source = await resp.text()
|
||||
const runner = new Function('sdk', 'go', 'runtime', 'WailsInvoke', 'wails', `"use strict";\n${source}`)
|
||||
try {
|
||||
runner(sdk, undefined, undefined, undefined, undefined)
|
||||
} catch (err) {
|
||||
disposeAll()
|
||||
throw err
|
||||
}
|
||||
return disposeAll
|
||||
}
|
||||
@@ -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,10 +1,45 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import { App } from './App'
|
||||
import { ErrorBoundary } from './components/ErrorBoundary'
|
||||
import { applyCachedThemeTokensSync } from './lib/themeEngine'
|
||||
import './styles/app.css'
|
||||
import { events } from './wails'
|
||||
|
||||
// Inline cached theme tokens before first paint to prevent FOUC (§5.1).
|
||||
applyCachedThemeTokensSync()
|
||||
|
||||
let lastReportedErr = ''
|
||||
let lastReportedAt = 0
|
||||
|
||||
function reportUIError(msg: string) {
|
||||
const trimmed = msg.trim()
|
||||
if (!trimmed) return
|
||||
// Benign Chromium ResizeObserver delivery notice fired during rapid layout/resize.
|
||||
if (trimmed.includes('ResizeObserver loop completed with undelivered notifications') || trimmed.includes('ResizeObserver loop limit exceeded')) {
|
||||
return
|
||||
}
|
||||
const now = Date.now()
|
||||
if (trimmed === lastReportedErr && now - lastReportedAt < 5000) return
|
||||
lastReportedErr = trimmed
|
||||
lastReportedAt = now
|
||||
events.emitUIError(trimmed.slice(0, 1500))
|
||||
}
|
||||
|
||||
window.addEventListener('error', (e) => {
|
||||
const msg = e.error instanceof Error ? `${e.error.message}\n${e.error.stack ?? ''}` : (e.message || 'Unknown window error')
|
||||
reportUIError(`window.error: ${msg}`)
|
||||
})
|
||||
window.addEventListener('unhandledrejection', (e) => {
|
||||
const r = e.reason
|
||||
const msg = r instanceof Error ? `${r.message}\n${r.stack ?? ''}` : String(r ?? 'Unknown rejection')
|
||||
reportUIError(`unhandledrejection: ${msg}`)
|
||||
})
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
<ErrorBoundary>
|
||||
<App />
|
||||
</ErrorBoundary>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
@@ -1,25 +1,70 @@
|
||||
/* Design tokens — macOS Tahoe System Settings aesthetic (Light default, Dark optional). */
|
||||
/* 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;
|
||||
}
|
||||
|
||||
/* 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). */
|
||||
@layer base {
|
||||
:root {
|
||||
color-scheme: light;
|
||||
|
||||
/* Type */
|
||||
--font-sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
|
||||
--font-mono: "SF Mono", "Cascadia Mono", "JetBrains Mono", Consolas, monospace;
|
||||
/* 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: 400;
|
||||
--fw-medium: 500;
|
||||
--fw-strong: 600;
|
||||
--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;
|
||||
|
||||
@@ -32,88 +77,112 @@
|
||||
/* Surfaces (macOS Tahoe Light) */
|
||||
--surface-0: #ffffff;
|
||||
--surface-canvas: #ffffff;
|
||||
--surface-sidebar: linear-gradient(180deg, #eff5fc 0%, #eaf2fa 100%);
|
||||
--surface-sidebar-border: rgba(15, 23, 42, 0.07);
|
||||
--surface-sidebar-shadow: 0 2px 14px rgba(15, 23, 42, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.8);
|
||||
--surface-chrome: rgba(255, 255, 255, 0.88);
|
||||
--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.96);
|
||||
--surface-2: rgba(255, 255, 255, 0.94);
|
||||
--surface-input: #ffffff;
|
||||
--surface-hover: rgba(15, 23, 42, 0.05);
|
||||
--surface-active: rgba(15, 23, 42, 0.09);
|
||||
--border: rgba(15, 23, 42, 0.075);
|
||||
--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);
|
||||
--shadow-overlay: 0 20px 56px rgba(15, 23, 42, 0.18), 0 0 0 1px rgba(15, 23, 42, 0.06);
|
||||
--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: #1d1d1f;
|
||||
--text-2: #515154;
|
||||
--text-3: #86868b;
|
||||
--text-2: #424247;
|
||||
--text-3: #6e6e73;
|
||||
--text-code: #2c2c30;
|
||||
|
||||
/* Semantics (Apple System Colours) */
|
||||
--accent: #007aff;
|
||||
--accent-hover: #006be6;
|
||||
--accent-text: #ffffff;
|
||||
--accent-soft: rgba(0, 122, 255, 0.12);
|
||||
--accent-soft: rgba(0, 122, 255, 0.11);
|
||||
--accent-soft-text: #0066d6;
|
||||
--focus-ring: 0 0 0 3px rgba(0, 122, 255, 0.3);
|
||||
--focus-ring: 0 0 0 3px rgba(0, 122, 255, 0.30);
|
||||
|
||||
--status-running: #28cd41;
|
||||
--status-busy: #ff9f0a;
|
||||
--status-error: #ff3b30;
|
||||
--status-idle: #aeaeb2;
|
||||
|
||||
--ok-soft: rgba(40, 205, 65, 0.13);
|
||||
--ok-text: #188c2c;
|
||||
--warn-soft: rgba(255, 159, 10, 0.14);
|
||||
--warn-text: #a86200;
|
||||
|
||||
--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.11);
|
||||
--notice-border: rgba(255, 159, 10, 0.32);
|
||||
--notice-soft: rgba(255, 159, 10, 0.10);
|
||||
--notice-border: rgba(255, 159, 10, 0.28);
|
||||
|
||||
/* Motion */
|
||||
--dur-fast: 120ms;
|
||||
--dur: 200ms;
|
||||
--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: 42px;
|
||||
--logbar-h: 32px;
|
||||
--sidebar-w: 244px;
|
||||
--page-max: 700px;
|
||||
--sidebar-w: 248px;
|
||||
--page-max: 632px;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
|
||||
--surface-0: #1e1e22;
|
||||
--surface-canvas: #1e1e22;
|
||||
--surface-sidebar: linear-gradient(180deg, #27282e 0%, #23242a 100%);
|
||||
--surface-sidebar-border: rgba(255, 255, 255, 0.08);
|
||||
--surface-sidebar-shadow: 0 4px 18px rgba(0, 0, 0, 0.32), inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
||||
--surface-chrome: rgba(28, 28, 32, 0.92);
|
||||
--surface-1: rgba(255, 255, 255, 0.05);
|
||||
--surface-card-elevated: rgba(255, 255, 255, 0.07);
|
||||
--surface-2: #2b2c32;
|
||||
--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.07);
|
||||
--surface-hover: rgba(255, 255, 255, 0.075);
|
||||
--surface-active: rgba(255, 255, 255, 0.12);
|
||||
--border: rgba(255, 255, 255, 0.09);
|
||||
--border: rgba(255, 255, 255, 0.085);
|
||||
--border-strong: rgba(255, 255, 255, 0.16);
|
||||
--scrim: rgba(0, 0, 0, 0.55);
|
||||
--shadow-btn: 0 1px 2px rgba(0, 0, 0, 0.28);
|
||||
--shadow-overlay: 0 24px 64px rgba(0, 0, 0, 0.55), 0 0 0 1px rgba(255, 255, 255, 0.08);
|
||||
--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: #b4b4bc;
|
||||
--text-3: #86868e;
|
||||
--text-2: #c2c2ca;
|
||||
--text-3: #92929c;
|
||||
--text-code: #d4d6e0;
|
||||
|
||||
--accent: #0a84ff;
|
||||
--accent-hover: #2492ff;
|
||||
--accent-text: #ffffff;
|
||||
--accent-soft: rgba(10, 132, 255, 0.22);
|
||||
--accent-soft: rgba(10, 132, 255, 0.20);
|
||||
--accent-soft-text: #64b0ff;
|
||||
--focus-ring: 0 0 0 3px rgba(10, 132, 255, 0.45);
|
||||
|
||||
@@ -122,16 +191,58 @@
|
||||
--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.16);
|
||||
--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.11);
|
||||
--notice-border: rgba(255, 214, 10, 0.30);
|
||||
--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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// Single source of truth for UI Contract v1 (docs/plugin-architecture.md §5.1).
|
||||
// Renaming or removing any part, state attribute, or token here is a uiApi major bump.
|
||||
|
||||
export const UI_API_VERSION = '1.0.0' as const
|
||||
|
||||
export const UI_CONTRACT_PARTS = [
|
||||
'rg-p-shell',
|
||||
'rg-p-titlebar',
|
||||
'rg-p-brand',
|
||||
'rg-p-workspace',
|
||||
'rg-p-sidebar',
|
||||
'rg-p-sidebar-head',
|
||||
'rg-p-nav',
|
||||
'rg-p-main',
|
||||
'rg-p-vm-page',
|
||||
'rg-p-vm-header',
|
||||
'rg-p-vm-preview',
|
||||
'rg-p-vm-summary',
|
||||
'rg-p-statusbar',
|
||||
'rg-p-logpanel',
|
||||
'rg-p-settings',
|
||||
'rg-p-empty',
|
||||
] as const
|
||||
|
||||
export type UIContractPart = (typeof UI_CONTRACT_PARTS)[number]
|
||||
|
||||
export const UI_CONTRACT_STATE_ATTRS = [
|
||||
'data-theme',
|
||||
'data-motion',
|
||||
'data-view',
|
||||
'data-vm-state',
|
||||
'data-busy',
|
||||
'data-has-error',
|
||||
'data-sidebar-collapsed',
|
||||
'data-safe-mode',
|
||||
] as const
|
||||
|
||||
export const UI_CONTRACT_SLOTS = [
|
||||
'sidebar.footer',
|
||||
'statusbar.right',
|
||||
'vm.toolbar',
|
||||
'vm.card',
|
||||
'settings.plugin',
|
||||
'vm.preview.tl',
|
||||
'vm.preview.tr',
|
||||
'vm.preview.bl',
|
||||
'vm.preview.br',
|
||||
'empty.state',
|
||||
] as const
|
||||
|
||||
export type UIContractSlot = (typeof UI_CONTRACT_SLOTS)[number]
|
||||
|
||||
export const UI_CONTRACT_TOKENS = [
|
||||
'--font-sans', '--font-mono',
|
||||
'--fs-11', '--fs-12', '--fs-13', '--fs-14', '--fs-15', '--fs-16', '--fs-20', '--fs-24',
|
||||
'--fw-regular', '--fw-medium', '--fw-strong',
|
||||
'--sp-1', '--sp-2', '--sp-3', '--sp-4', '--sp-5', '--sp-6', '--sp-8',
|
||||
'--r-sm', '--r-md', '--r-lg', '--r-xl',
|
||||
'--surface-0', '--surface-canvas', '--surface-sidebar-rail', '--surface-sidebar',
|
||||
'--surface-sidebar-border', '--surface-sidebar-shadow', '--surface-chrome',
|
||||
'--surface-statusbar', '--surface-1', '--surface-card-elevated', '--surface-2',
|
||||
'--surface-input', '--surface-hover', '--surface-active',
|
||||
'--border', '--border-strong', '--highlight-top', '--scrim',
|
||||
'--shadow-btn', '--shadow-card', '--shadow-overlay',
|
||||
'--blur-chrome', '--blur-overlay',
|
||||
'--text', '--text-2', '--text-3', '--text-code',
|
||||
'--accent', '--accent-hover', '--accent-text', '--accent-soft', '--accent-soft-text', '--focus-ring',
|
||||
'--status-running', '--status-busy', '--status-error', '--status-idle',
|
||||
'--ok-soft', '--ok-text', '--warn-soft', '--warn-text',
|
||||
'--danger', '--danger-soft', '--danger-border', '--danger-text',
|
||||
'--notice-soft', '--notice-border', '--seg-thumb',
|
||||
'--ease-out', '--ease-in-out', '--ease-spring',
|
||||
'--dur-press', '--dur-fast', '--dur', '--dur-modal', '--dur-toast',
|
||||
'--titlebar-h', '--logbar-h', '--sidebar-w', '--page-max',
|
||||
] as const
|
||||
|
||||
export const UI_CONTRACT = {
|
||||
uiApi: UI_API_VERSION,
|
||||
parts: [...UI_CONTRACT_PARTS],
|
||||
stateAttrs: [...UI_CONTRACT_STATE_ATTRS],
|
||||
slots: [...UI_CONTRACT_SLOTS],
|
||||
tokens: [...UI_CONTRACT_TOKENS],
|
||||
}
|
||||
@@ -1,244 +1,151 @@
|
||||
export type Locale = 'zh-CN' | 'en-US'
|
||||
// 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, driver, host, installer, plugin, reims, runtime, version } from '../wailsjs/go/models'
|
||||
|
||||
export interface Config {
|
||||
data_root: string
|
||||
/** A generated class as a plain data shape (no convertValues helper). */
|
||||
type Model<T> = Omit<T, 'convertValues'>
|
||||
|
||||
export type BuiltinLocale = 'zh-CN' | 'en-US'
|
||||
export type Locale = BuiltinLocale | (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' | 'candidate' | ''
|
||||
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 GPUCompat = 'supported' | 'warn' | 'unsupported' | 'unknown'
|
||||
|
||||
export type GPUInfo = Omit<Model<host.GPUInfo>, 'compat'> & {
|
||||
kind: 'discrete' | 'integrated' | 'virtual' | 'unknown'
|
||||
compat?: GPUCompat
|
||||
}
|
||||
|
||||
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[]>
|
||||
/** First launch: no data folder chosen yet (setup.go). */
|
||||
needs_setup: boolean
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
export type LocalizedText = plugin.LocalizedText
|
||||
export type PermissionSpec = plugin.PermissionSpec
|
||||
export type SettingProperty = plugin.SettingProperty
|
||||
export type SettingsSchema = plugin.SettingsSchema
|
||||
export type PluginInfo = plugin.PluginInfo
|
||||
export type DoctorFinding = plugin.DoctorFinding
|
||||
export type TokenDeriveRule = plugin.TokenDeriveRule
|
||||
export type ThemeScheme = plugin.ThemeScheme
|
||||
export type ThemeDecoration = plugin.ThemeDecoration
|
||||
export type ThemeDecorationState = plugin.ThemeDecorationState
|
||||
export type ThemeContribution = plugin.ThemeContribution
|
||||
export type CustomThemeScheme = plugin.CustomThemeScheme
|
||||
export type ActiveThemePayload = plugin.ActiveThemePayload
|
||||
export type ResolvedLocalePack = plugin.ResolvedLocalePack
|
||||
export type MenuContribution = plugin.MenuContribution
|
||||
export type VMCardContribution = plugin.VMCardContribution
|
||||
export type PanelContribution = plugin.PanelContribution
|
||||
export type StatusItemContribution = plugin.StatusItemContribution
|
||||
export type PluginUIContributions = app.PluginUIContributions
|
||||
export type DriverSummary = driver.DriverSummary
|
||||
export type DriverCreateRequest = driver.CreateRequest
|
||||
export type RuntimeKindSpec = runtime.KindSpec
|
||||
|
||||
/** 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
|
||||
}
|
||||
|
||||
/** A published runtime (GitHub Release, internal/runtime/remote.go). */
|
||||
export interface RemoteRuntime {
|
||||
commit: string
|
||||
tag: string
|
||||
channel: 'stable' | 'candidate'
|
||||
published_at: string
|
||||
page_url: string
|
||||
archive_name: string
|
||||
archive_url: string
|
||||
archive_size: number
|
||||
sums_url: string
|
||||
source_name?: string
|
||||
source_url?: string
|
||||
}
|
||||
|
||||
export interface DataRootChoice {
|
||||
path: string
|
||||
free_gb: number
|
||||
system: boolean
|
||||
external: boolean
|
||||
recommended: boolean
|
||||
}
|
||||
|
||||
export interface DataRootCheck {
|
||||
path: string
|
||||
free_gb: number
|
||||
system: boolean
|
||||
external: boolean
|
||||
has_config: boolean
|
||||
error?: 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,418 @@
|
||||
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/design-guidelines.md §2–3):
|
||||
// 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"]')
|
||||
const next = el ? { x: el.offsetLeft, w: el.offsetWidth } : null
|
||||
setThumb((prev) => {
|
||||
if (!prev && !next) return prev
|
||||
if (prev && next && prev.x === next.x && prev.w === next.w) return prev
|
||||
return next
|
||||
})
|
||||
}
|
||||
useLayoutEffect(measure, [value, options])
|
||||
useEffect(() => {
|
||||
if (!box.current || typeof ResizeObserver === 'undefined') return
|
||||
let raf = 0
|
||||
const ro = new ResizeObserver(() => {
|
||||
if (raf) cancelAnimationFrame(raf)
|
||||
raf = requestAnimationFrame(() => {
|
||||
raf = 0
|
||||
measure()
|
||||
})
|
||||
})
|
||||
ro.observe(box.current)
|
||||
return () => {
|
||||
if (raf) cancelAnimationFrame(raf)
|
||||
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,119 +1,165 @@
|
||||
// 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.
|
||||
//
|
||||
// At module boot we privately capture `window.go.app.App` and `window.runtime`
|
||||
// so `hideWailsGlobals()` can remove them from `window` before running any
|
||||
// Tier-3 interactive theme script without breaking the app's own calls (§5.1, B6).
|
||||
import * as Go from '../wailsjs/go/app/App'
|
||||
import {
|
||||
AppState,
|
||||
CachedInstaller,
|
||||
DataRootCheck,
|
||||
DataRootChoice,
|
||||
RemoteRuntime,
|
||||
Release,
|
||||
Task,
|
||||
CreateOpts,
|
||||
InstalledRuntime,
|
||||
LogEntry,
|
||||
SetOpts,
|
||||
ValidationIssue,
|
||||
VMDetail,
|
||||
EventsEmit as RawEventsEmit,
|
||||
EventsOn as RawEventsOn,
|
||||
OnFileDrop as RawOnFileDrop,
|
||||
OnFileDropOff as RawOnFileDropOff,
|
||||
WindowMinimise as RawWindowMinimise,
|
||||
WindowToggleMaximise as RawWindowToggleMaximise,
|
||||
} from '../wailsjs/runtime/runtime'
|
||||
import type {
|
||||
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
|
||||
LogEntry, PluginInfo, PluginUIContributions, RemoteRuntime, RuntimeKindSpec,
|
||||
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>
|
||||
SuggestDataRoots(): Promise<DataRootChoice[] | null>
|
||||
CheckDataRoot(dir: string): Promise<DataRootCheck>
|
||||
CompleteSetup(dir: string): Promise<void>
|
||||
ListRemoteRuntimes(): Promise<RemoteRuntime[] | null>
|
||||
SetRuntimeChannel(channel: string): Promise<void>
|
||||
InstallRuntimeOnline(commit: string): Promise<string>
|
||||
}
|
||||
}
|
||||
}
|
||||
runtime?: {
|
||||
EventsOn(event: string, cb: (...args: any[]) => void): () => void
|
||||
WindowMinimise(): void
|
||||
WindowToggleMaximise(): void
|
||||
Quit(): void
|
||||
}
|
||||
type AnyFn = (...args: never[]) => unknown
|
||||
|
||||
interface WailsWindow {
|
||||
go?: { app?: { App?: Record<string, AnyFn> } }
|
||||
runtime?: Record<string, AnyFn>
|
||||
}
|
||||
|
||||
const wailsWin = window as unknown as WailsWindow
|
||||
const capturedGoApp: Record<string, AnyFn> = wailsWin.go?.app?.App ? { ...wailsWin.go.app.App } : {}
|
||||
const capturedRuntime: Record<string, AnyFn> = wailsWin.runtime ? { ...wailsWin.runtime } : {}
|
||||
let globalsHidden = false
|
||||
|
||||
const boundGo = {} as typeof Go
|
||||
for (const key of Object.keys(Go) as Array<keyof typeof Go>) {
|
||||
const fn = capturedGoApp[key as string]
|
||||
;(boundGo as Record<string, unknown>)[key as string] = fn
|
||||
? (...args: never[]) => fn(...args)
|
||||
: Go[key]
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides Wails binding globals (`window.go` and unsafe `window.runtime` methods)
|
||||
* before mounting an interactive theme script (§5.1, B6). Only `ResolveFilePaths`
|
||||
* (required internally by Wails's native drag-and-drop bridge) is retained on a
|
||||
* frozen runtime stub.
|
||||
*/
|
||||
export function hideWailsGlobals(): void {
|
||||
if (globalsHidden) return
|
||||
globalsHidden = true
|
||||
try {
|
||||
delete wailsWin.go
|
||||
Object.defineProperty(window, 'go', {
|
||||
value: undefined,
|
||||
writable: false,
|
||||
configurable: false,
|
||||
enumerable: false,
|
||||
})
|
||||
} catch {
|
||||
// non-configurable in some test environments
|
||||
}
|
||||
try {
|
||||
const minimalRuntime = typeof capturedRuntime.ResolveFilePaths === 'function'
|
||||
? Object.freeze({ ResolveFilePaths: capturedRuntime.ResolveFilePaths })
|
||||
: undefined
|
||||
delete wailsWin.runtime
|
||||
Object.defineProperty(window, 'runtime', {
|
||||
value: minimalRuntime,
|
||||
writable: false,
|
||||
configurable: false,
|
||||
enumerable: false,
|
||||
})
|
||||
} catch {
|
||||
// ignore if non-configurable
|
||||
}
|
||||
}
|
||||
|
||||
function app() {
|
||||
const api = window.go?.main?.App
|
||||
if (!api) {
|
||||
throw new Error('Wails backend not attached')
|
||||
export function OnFileDrop(
|
||||
callback: (x: number, y: number, paths: string[]) => void,
|
||||
useDropTarget: boolean,
|
||||
): void {
|
||||
if (typeof capturedRuntime.OnFileDrop === 'function') {
|
||||
;(capturedRuntime.OnFileDrop as (cb: typeof callback, useTarget: boolean) => void)(callback, useDropTarget)
|
||||
return
|
||||
}
|
||||
return api
|
||||
RawOnFileDrop(callback, useDropTarget)
|
||||
}
|
||||
|
||||
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),
|
||||
suggestDataRoots: () => app().SuggestDataRoots(),
|
||||
checkDataRoot: (dir: string) => app().CheckDataRoot(dir),
|
||||
completeSetup: (dir: string) => app().CompleteSetup(dir),
|
||||
listRemoteRuntimes: () => app().ListRemoteRuntimes(),
|
||||
setRuntimeChannel: (channel: string) => app().SetRuntimeChannel(channel),
|
||||
installRuntimeOnline: (commit: string) => app().InstallRuntimeOnline(commit),
|
||||
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 function OnFileDropOff(): void {
|
||||
if (typeof capturedRuntime.OnFileDropOff === 'function') {
|
||||
;(capturedRuntime.OnFileDropOff as () => void)()
|
||||
return
|
||||
}
|
||||
RawOnFileDropOff()
|
||||
}
|
||||
|
||||
export function WindowMinimise(): void {
|
||||
if (typeof capturedRuntime.WindowMinimise === 'function') {
|
||||
;(capturedRuntime.WindowMinimise as () => void)()
|
||||
return
|
||||
}
|
||||
RawWindowMinimise()
|
||||
}
|
||||
|
||||
export function WindowToggleMaximise(): void {
|
||||
if (typeof capturedRuntime.WindowToggleMaximise === 'function') {
|
||||
;(capturedRuntime.WindowToggleMaximise as () => void)()
|
||||
return
|
||||
}
|
||||
RawWindowToggleMaximise()
|
||||
}
|
||||
|
||||
function eventsOn<T>(eventName: string, cb: (data: T) => void): () => void {
|
||||
if (typeof capturedRuntime.EventsOnMultiple === 'function') {
|
||||
return (capturedRuntime.EventsOnMultiple as (name: string, fn: (data: T) => void, max: number) => () => void)(
|
||||
eventName,
|
||||
cb,
|
||||
-1,
|
||||
)
|
||||
}
|
||||
return RawEventsOn(eventName, cb)
|
||||
}
|
||||
|
||||
function eventsEmit(eventName: string, ...args: unknown[]): void {
|
||||
try {
|
||||
if (typeof capturedRuntime.EventsEmit === 'function') {
|
||||
;(capturedRuntime.EventsEmit as (name: string, ...data: unknown[]) => void)(eventName, ...args)
|
||||
return
|
||||
}
|
||||
;(RawEventsEmit as (name: string, ...data: unknown[]) => void)(eventName, ...args)
|
||||
} catch {
|
||||
// ignore if Wails runtime is unavailable (e.g. standalone preview)
|
||||
}
|
||||
}
|
||||
|
||||
export const api = {
|
||||
...boundGo,
|
||||
GetState: boundGo.GetState as () => Promise<AppState>,
|
||||
GetTasks: boundGo.GetTasks as () => Promise<Task[]>,
|
||||
GetVMAffinity: boundGo.GetVMAffinity as (name: string) => Promise<VMAffinityStatus>,
|
||||
SetVMAffinity: boundGo.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
|
||||
ListInstallers: boundGo.ListInstallers as () => Promise<CachedInstaller[] | null>,
|
||||
ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
|
||||
SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
|
||||
ListPlugins: boundGo.ListPlugins as () => Promise<PluginInfo[] | null>,
|
||||
GetPluginUIContributions: boundGo.GetPluginUIContributions as () => Promise<PluginUIContributions>,
|
||||
GetActiveTheme: boundGo.GetActiveTheme as () => Promise<ActiveThemePayload>,
|
||||
ListDrivers: boundGo.ListDrivers as () => Promise<DriverSummary[] | null>,
|
||||
ListRuntimeKinds: boundGo.ListRuntimeKinds as () => Promise<RuntimeKindSpec[] | null>,
|
||||
}
|
||||
|
||||
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),
|
||||
// Renderer health watchdog & crash reporting (internal/app/ui_health.go).
|
||||
onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb),
|
||||
emitUIPong: () => eventsEmit('reims:ui-pong'),
|
||||
emitUIError: (detail: string) => eventsEmit('reims:ui-error', detail),
|
||||
emitTheme: (theme: 'light' | 'dark') => eventsEmit('reims:theme', theme),
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
{
|
||||
"uiApi": "1.0.0",
|
||||
"tokens": [
|
||||
"--font-sans",
|
||||
"--font-mono",
|
||||
"--fs-11",
|
||||
"--fs-12",
|
||||
"--fs-13",
|
||||
"--fs-14",
|
||||
"--fs-15",
|
||||
"--fs-16",
|
||||
"--fs-20",
|
||||
"--fs-24",
|
||||
"--fw-regular",
|
||||
"--fw-medium",
|
||||
"--fw-strong",
|
||||
"--sp-1",
|
||||
"--sp-2",
|
||||
"--sp-3",
|
||||
"--sp-4",
|
||||
"--sp-5",
|
||||
"--sp-6",
|
||||
"--sp-8",
|
||||
"--r-sm",
|
||||
"--r-md",
|
||||
"--r-lg",
|
||||
"--r-xl",
|
||||
"--surface-0",
|
||||
"--surface-canvas",
|
||||
"--surface-sidebar-rail",
|
||||
"--surface-sidebar",
|
||||
"--surface-sidebar-border",
|
||||
"--surface-sidebar-shadow",
|
||||
"--surface-chrome",
|
||||
"--surface-statusbar",
|
||||
"--surface-1",
|
||||
"--surface-card-elevated",
|
||||
"--surface-2",
|
||||
"--surface-input",
|
||||
"--surface-hover",
|
||||
"--surface-active",
|
||||
"--border",
|
||||
"--border-strong",
|
||||
"--highlight-top",
|
||||
"--scrim",
|
||||
"--shadow-btn",
|
||||
"--shadow-card",
|
||||
"--shadow-overlay",
|
||||
"--blur-chrome",
|
||||
"--blur-overlay",
|
||||
"--text",
|
||||
"--text-2",
|
||||
"--text-3",
|
||||
"--text-code",
|
||||
"--accent",
|
||||
"--accent-hover",
|
||||
"--accent-text",
|
||||
"--accent-soft",
|
||||
"--accent-soft-text",
|
||||
"--focus-ring",
|
||||
"--status-running",
|
||||
"--status-busy",
|
||||
"--status-error",
|
||||
"--status-idle",
|
||||
"--ok-soft",
|
||||
"--ok-text",
|
||||
"--warn-soft",
|
||||
"--warn-text",
|
||||
"--danger",
|
||||
"--danger-soft",
|
||||
"--danger-border",
|
||||
"--danger-text",
|
||||
"--notice-soft",
|
||||
"--notice-border",
|
||||
"--seg-thumb",
|
||||
"--ease-out",
|
||||
"--ease-in-out",
|
||||
"--ease-spring",
|
||||
"--dur-press",
|
||||
"--dur-fast",
|
||||
"--dur",
|
||||
"--dur-modal",
|
||||
"--dur-toast",
|
||||
"--titlebar-h",
|
||||
"--logbar-h",
|
||||
"--sidebar-w",
|
||||
"--page-max"
|
||||
],
|
||||
"parts": [
|
||||
"rg-p-shell",
|
||||
"rg-p-titlebar",
|
||||
"rg-p-brand",
|
||||
"rg-p-workspace",
|
||||
"rg-p-sidebar",
|
||||
"rg-p-sidebar-head",
|
||||
"rg-p-nav",
|
||||
"rg-p-main",
|
||||
"rg-p-vm-page",
|
||||
"rg-p-vm-header",
|
||||
"rg-p-vm-preview",
|
||||
"rg-p-vm-summary",
|
||||
"rg-p-statusbar",
|
||||
"rg-p-logpanel",
|
||||
"rg-p-settings",
|
||||
"rg-p-empty"
|
||||
],
|
||||
"stateAttrs": [
|
||||
"data-theme",
|
||||
"data-motion",
|
||||
"data-view",
|
||||
"data-vm-state",
|
||||
"data-busy",
|
||||
"data-has-error",
|
||||
"data-sidebar-collapsed",
|
||||
"data-safe-mode"
|
||||
],
|
||||
"slots": [
|
||||
"sidebar.footer",
|
||||
"statusbar.right",
|
||||
"vm.toolbar",
|
||||
"vm.card",
|
||||
"settings.plugin",
|
||||
"vm.preview.tl",
|
||||
"vm.preview.tr",
|
||||
"vm.preview.bl",
|
||||
"vm.preview.br",
|
||||
"empty.state"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
// 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 {driver} from '../models';
|
||||
import {plugin} from '../models';
|
||||
import {runtime} from '../models';
|
||||
import {installer} from '../models';
|
||||
import {http} 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 CanOpenQQGroup():Promise<boolean>;
|
||||
|
||||
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 CreateVMWithDriver(arg1:driver.CreateRequest):Promise<void>;
|
||||
|
||||
export function DeleteCustomThemeScheme(arg1:string):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 DisablePlugin(arg1:string):Promise<void>;
|
||||
|
||||
export function DismissTask(arg1:string):Promise<void>;
|
||||
|
||||
export function DoctorPlugin(arg1:string):Promise<Array<plugin.DoctorFinding>>;
|
||||
|
||||
export function DownloadAndAttachOnlineRecovery(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function DownloadAppUpdate():Promise<string>;
|
||||
|
||||
export function DownloadInstaller(arg1:string):Promise<string>;
|
||||
|
||||
export function EjectInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function EnablePlugin(arg1:string,arg2:boolean):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 GetActiveTheme():Promise<plugin.ActiveThemePayload>;
|
||||
|
||||
export function GetPluginSettings(arg1:string,arg2:string):Promise<Record<string, any>>;
|
||||
|
||||
export function GetPluginUIContributions():Promise<app.PluginUIContributions>;
|
||||
|
||||
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 GetVMPluginSettings(arg1:string):Promise<Record<string, Record<string, any>>>;
|
||||
|
||||
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 InstallAppUpdate():Promise<void>;
|
||||
|
||||
export function InstallPluginArchive(arg1:string):Promise<plugin.PluginInfo>;
|
||||
|
||||
export function InstallRuntimeArchive(arg1:string):Promise<runtime.Installed>;
|
||||
|
||||
export function InstallRuntimeOnline(arg1:string):Promise<string>;
|
||||
|
||||
export function InvokePluginCommand(arg1:string,arg2:string,arg3:Record<string, any>):Promise<any>;
|
||||
|
||||
export function LinkPluginDev(arg1:string):Promise<plugin.PluginInfo>;
|
||||
|
||||
export function ListDrivers():Promise<Array<driver.DriverSummary>>;
|
||||
|
||||
export function ListInstallers():Promise<Array<installer.Cached>>;
|
||||
|
||||
export function ListOfflineReleases():Promise<Array<installer.Release>>;
|
||||
|
||||
export function ListPlugins():Promise<Array<plugin.PluginInfo>>;
|
||||
|
||||
export function ListRemoteRuntimes():Promise<Array<runtime.Remote>>;
|
||||
|
||||
export function ListRuntimeKinds():Promise<Array<runtime.KindSpec>>;
|
||||
|
||||
export function ListSnapshots(arg1:string):Promise<Array<reims.DiskSnapshot>>;
|
||||
|
||||
export function OpenProcessorScheduling():Promise<void>;
|
||||
|
||||
export function OpenQQGroup():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 PanelBridgeCall(arg1:string,arg2:string,arg3:Record<string, any>):Promise<any>;
|
||||
|
||||
export function PickDirectory(arg1:string):Promise<string>;
|
||||
|
||||
export function PickFile(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function PluginAssetHandler():Promise<http.Handler>;
|
||||
|
||||
export function PreviewCreate(arg1:reims.CreateOpts):Promise<string>;
|
||||
|
||||
export function QuitApp():Promise<void>;
|
||||
|
||||
export function ReadPluginLog(arg1:string):Promise<string>;
|
||||
|
||||
export function ReadVMLogs(arg1:string,arg2:boolean):Promise<string>;
|
||||
|
||||
export function RemovePlugin(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
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 SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise<void>;
|
||||
|
||||
export function SetActiveTheme(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 SetPluginSettings(arg1:string,arg2:string,arg3:Record<string, any>):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,435 @@
|
||||
// @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 CanOpenQQGroup() {
|
||||
return window['go']['app']['App']['CanOpenQQGroup']();
|
||||
}
|
||||
|
||||
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 CreateVMWithDriver(arg1) {
|
||||
return window['go']['app']['App']['CreateVMWithDriver'](arg1);
|
||||
}
|
||||
|
||||
export function DeleteCustomThemeScheme(arg1) {
|
||||
return window['go']['app']['App']['DeleteCustomThemeScheme'](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 DisablePlugin(arg1) {
|
||||
return window['go']['app']['App']['DisablePlugin'](arg1);
|
||||
}
|
||||
|
||||
export function DismissTask(arg1) {
|
||||
return window['go']['app']['App']['DismissTask'](arg1);
|
||||
}
|
||||
|
||||
export function DoctorPlugin(arg1) {
|
||||
return window['go']['app']['App']['DoctorPlugin'](arg1);
|
||||
}
|
||||
|
||||
export function DownloadAndAttachOnlineRecovery(arg1, arg2) {
|
||||
return window['go']['app']['App']['DownloadAndAttachOnlineRecovery'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DownloadAppUpdate() {
|
||||
return window['go']['app']['App']['DownloadAppUpdate']();
|
||||
}
|
||||
|
||||
export function DownloadInstaller(arg1) {
|
||||
return window['go']['app']['App']['DownloadInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EjectInstaller(arg1) {
|
||||
return window['go']['app']['App']['EjectInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EnablePlugin(arg1, arg2) {
|
||||
return window['go']['app']['App']['EnablePlugin'](arg1, arg2);
|
||||
}
|
||||
|
||||
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 GetActiveTheme() {
|
||||
return window['go']['app']['App']['GetActiveTheme']();
|
||||
}
|
||||
|
||||
export function GetPluginSettings(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetPluginSettings'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetPluginUIContributions() {
|
||||
return window['go']['app']['App']['GetPluginUIContributions']();
|
||||
}
|
||||
|
||||
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 GetVMPluginSettings(arg1) {
|
||||
return window['go']['app']['App']['GetVMPluginSettings'](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 InstallAppUpdate() {
|
||||
return window['go']['app']['App']['InstallAppUpdate']();
|
||||
}
|
||||
|
||||
export function InstallPluginArchive(arg1) {
|
||||
return window['go']['app']['App']['InstallPluginArchive'](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 InvokePluginCommand(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['InvokePluginCommand'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function LinkPluginDev(arg1) {
|
||||
return window['go']['app']['App']['LinkPluginDev'](arg1);
|
||||
}
|
||||
|
||||
export function ListDrivers() {
|
||||
return window['go']['app']['App']['ListDrivers']();
|
||||
}
|
||||
|
||||
export function ListInstallers() {
|
||||
return window['go']['app']['App']['ListInstallers']();
|
||||
}
|
||||
|
||||
export function ListOfflineReleases() {
|
||||
return window['go']['app']['App']['ListOfflineReleases']();
|
||||
}
|
||||
|
||||
export function ListPlugins() {
|
||||
return window['go']['app']['App']['ListPlugins']();
|
||||
}
|
||||
|
||||
export function ListRemoteRuntimes() {
|
||||
return window['go']['app']['App']['ListRemoteRuntimes']();
|
||||
}
|
||||
|
||||
export function ListRuntimeKinds() {
|
||||
return window['go']['app']['App']['ListRuntimeKinds']();
|
||||
}
|
||||
|
||||
export function ListSnapshots(arg1) {
|
||||
return window['go']['app']['App']['ListSnapshots'](arg1);
|
||||
}
|
||||
|
||||
export function OpenProcessorScheduling() {
|
||||
return window['go']['app']['App']['OpenProcessorScheduling']();
|
||||
}
|
||||
|
||||
export function OpenQQGroup() {
|
||||
return window['go']['app']['App']['OpenQQGroup']();
|
||||
}
|
||||
|
||||
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 PanelBridgeCall(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['PanelBridgeCall'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
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 PluginAssetHandler() {
|
||||
return window['go']['app']['App']['PluginAssetHandler']();
|
||||
}
|
||||
|
||||
export function PreviewCreate(arg1) {
|
||||
return window['go']['app']['App']['PreviewCreate'](arg1);
|
||||
}
|
||||
|
||||
export function QuitApp() {
|
||||
return window['go']['app']['App']['QuitApp']();
|
||||
}
|
||||
|
||||
export function ReadPluginLog(arg1) {
|
||||
return window['go']['app']['App']['ReadPluginLog'](arg1);
|
||||
}
|
||||
|
||||
export function ReadVMLogs(arg1, arg2) {
|
||||
return window['go']['app']['App']['ReadVMLogs'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RemovePlugin(arg1, arg2) {
|
||||
return window['go']['app']['App']['RemovePlugin'](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 SaveCustomThemeScheme(arg1) {
|
||||
return window['go']['app']['App']['SaveCustomThemeScheme'](arg1);
|
||||
}
|
||||
|
||||
export function SetActiveTheme(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetActiveTheme'](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 SetPluginSettings(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetPluginSettings'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
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,76 +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 CheckDataRoot(arg1:string):Promise<main.DataRootCheck>;
|
||||
|
||||
export function CompleteSetup(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 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 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 SetRuntimeChannel(arg1:string):Promise<void>;
|
||||
|
||||
export function StartVM(arg1:string):Promise<void>;
|
||||
|
||||
export function StopVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function SuggestDataRoots():Promise<Array<main.DataRootChoice>>;
|
||||
|
||||
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,143 +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 CheckDataRoot(arg1) {
|
||||
return window['go']['main']['App']['CheckDataRoot'](arg1);
|
||||
}
|
||||
|
||||
export function CompleteSetup(arg1) {
|
||||
return window['go']['main']['App']['CompleteSetup'](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 InstallRuntimeOnline(arg1) {
|
||||
return window['go']['main']['App']['InstallRuntimeOnline'](arg1);
|
||||
}
|
||||
|
||||
export function ListInstallers() {
|
||||
return window['go']['main']['App']['ListInstallers']();
|
||||
}
|
||||
|
||||
export function ListOfflineReleases() {
|
||||
return window['go']['main']['App']['ListOfflineReleases']();
|
||||
}
|
||||
|
||||
export function ListRemoteRuntimes() {
|
||||
return window['go']['main']['App']['ListRemoteRuntimes']();
|
||||
}
|
||||
|
||||
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 SetRuntimeChannel(arg1) {
|
||||
return window['go']['main']['App']['SetRuntimeChannel'](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 SuggestDataRoots() {
|
||||
return window['go']['main']['App']['SuggestDataRoots']();
|
||||
}
|
||||
|
||||
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,10 @@ module github.com/Nwflower/reims-go
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/klauspost/compress v1.20.5
|
||||
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 +36,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
|
||||
)
|
||||
@@ -16,6 +16,8 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e h1:Q3+PugElBCf4PFpxhErSzU3/PY5sFL5Z6rfv4AbGAck=
|
||||
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
|
||||
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
|
||||
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/labstack/echo/v4 v4.16.1 h1:h05NuF1GvNu6jSAZxOv++AdjD/NJK+mZdGy0thiiuns=
|
||||
github.com/labstack/echo/v4 v4.16.1/go.mod h1:V/EQaTVHYJH92QhbQe7kFQ4mjgcjxLQQUQtAN87zZdw=
|
||||
github.com/labstack/gommon v0.5.0 h1:6VSQ2NOzsnEJ5W6+84E0RbcaDDmgB6NIAzWCczTEe6c=
|
||||
@@ -52,6 +54,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,211 @@
|
||||
package app
|
||||
|
||||
// In-app update: download the new release's Windows executable as a tracked
|
||||
// task, check it against the release's SHA256SUMS.txt, then swap it in and
|
||||
// restart (internal/selfupdate). Running VMs are separate processes and keep
|
||||
// running; Guest Tools reconnects once the new window is up.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/cli"
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
"github.com/Nwflower/reims-go/internal/selfupdate"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
// appUpdateTaskKind is the task kind the frontend watches for update progress.
|
||||
const appUpdateTaskKind = "app-update"
|
||||
|
||||
// appUpdateReady is the verified download InstallAppUpdate swaps in.
|
||||
var appUpdateReady struct {
|
||||
sync.Mutex
|
||||
version string
|
||||
path string
|
||||
sha256 string
|
||||
}
|
||||
|
||||
func (a *App) locale() i18n.Locale {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.cfg.Locale
|
||||
}
|
||||
|
||||
func (a *App) updateErr(key string, args ...any) error {
|
||||
return errors.New(i18n.T(a.locale(), key, args...))
|
||||
}
|
||||
|
||||
func (a *App) updateSupported() error {
|
||||
if err := selfupdate.Supported(); err != nil {
|
||||
if errors.Is(err, selfupdate.ErrDevBuild) {
|
||||
return a.updateErr("err.update_dev_build")
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func appUpdateDir(dataRoot string) string {
|
||||
return filepath.Join(dataRoot, "downloads", "app")
|
||||
}
|
||||
|
||||
// DownloadAppUpdate downloads the newest stable release in the background and
|
||||
// returns the task ID ("app-update", subject = the release tag). Canceling it
|
||||
// keeps the partial file, and the next download continues from there. A
|
||||
// download that already finished and still verifies completes at once.
|
||||
func (a *App) DownloadAppUpdate() (string, error) {
|
||||
if err := a.updateSupported(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.mu.Lock()
|
||||
if a.needsSetup {
|
||||
a.mu.Unlock()
|
||||
return "", errors.New("choose a data folder first")
|
||||
}
|
||||
dataRoot := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
|
||||
info, err := a.CheckAppUpdate(false)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
switch {
|
||||
case !info.HasUpdate:
|
||||
return "", a.updateErr("err.update_none")
|
||||
case info.DownloadURL == "" || info.AssetName == "":
|
||||
return "", a.updateErr("err.update_no_asset")
|
||||
case info.SumsURL == "":
|
||||
return "", a.updateErr("err.update_no_sums")
|
||||
}
|
||||
for _, t := range tasks.list() {
|
||||
if t.Kind == appUpdateTaskKind && t.Status == TaskRunning {
|
||||
return t.ID, nil
|
||||
}
|
||||
}
|
||||
|
||||
a.ensureTaskEmitter()
|
||||
ctx, cancel := context.WithCancel(a.baseCtx())
|
||||
id := tasks.start(appUpdateTaskKind, info.Latest, "", cancel)
|
||||
go func() {
|
||||
defer cancel()
|
||||
path, sum, err := downloadAppUpdate(ctx, info, appUpdateDir(dataRoot), func(done, total int64) {
|
||||
tasks.update(id, installer.Update{
|
||||
Kind: installer.KindProgress, Step: "downloading " + info.AssetName,
|
||||
Done: done, Total: total, Percent: percent(done, total),
|
||||
})
|
||||
})
|
||||
switch {
|
||||
case err == nil:
|
||||
appUpdateReady.Lock()
|
||||
appUpdateReady.version, appUpdateReady.path, appUpdateReady.sha256 = info.Latest, path, sum
|
||||
appUpdateReady.Unlock()
|
||||
a.emitLog("app", fmt.Sprintf("Update %s downloaded and verified (SHA-256 %s)", info.Latest, sum))
|
||||
tasks.finish(id, info.Latest, nil)
|
||||
case ctx.Err() != nil:
|
||||
tasks.finish(id, "", context.Canceled)
|
||||
default:
|
||||
a.emitLog("app", "Update download error: "+err.Error())
|
||||
tasks.finish(id, "", err)
|
||||
}
|
||||
}()
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// downloadAppUpdate fetches info's executable into dir and checks it against
|
||||
// the release's SHA256SUMS.txt. It returns the file and its hash.
|
||||
func downloadAppUpdate(ctx context.Context, info version.UpdateInfo, dir string, onProgress fetch.Progress) (string, string, error) {
|
||||
client := netproxy.NewClient()
|
||||
want, err := fetch.ExpectedSum(ctx, client, info.SumsURL, info.AssetName)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
path, err := fetch.Resume(ctx, client, info.DownloadURL, filepath.Join(dir, info.AssetName), info.AssetSize, want, onProgress)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return path, want, nil
|
||||
}
|
||||
|
||||
// InstallAppUpdate swaps the downloaded update in for the running executable,
|
||||
// starts it, and quits this window. The new window waits for this process to
|
||||
// exit before it opens. Running VMs are not touched.
|
||||
func (a *App) InstallAppUpdate() error {
|
||||
if err := a.updateSupported(); err != nil {
|
||||
return err
|
||||
}
|
||||
appUpdateReady.Lock()
|
||||
ver, path, want := appUpdateReady.version, appUpdateReady.path, appUpdateReady.sha256
|
||||
appUpdateReady.Unlock()
|
||||
if path == "" {
|
||||
return a.updateErr("err.update_not_ready")
|
||||
}
|
||||
// The file sat in the data folder since the download: check it again.
|
||||
if got, err := fetch.FileSHA256(path); err != nil || !strings.EqualFold(got, want) {
|
||||
appUpdateReady.Lock()
|
||||
appUpdateReady.path = ""
|
||||
appUpdateReady.Unlock()
|
||||
return a.updateErr("err.update_changed")
|
||||
}
|
||||
|
||||
exe, err := selfupdate.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := selfupdate.Writable(filepath.Dir(exe)); err != nil {
|
||||
return a.updateErr("err.update_not_writable", filepath.Dir(exe))
|
||||
}
|
||||
// A file still named after a release takes the new release's name.
|
||||
target := selfupdate.Target(exe, filepath.Base(path))
|
||||
if err := selfupdate.Swap(exe, target, path); err != nil {
|
||||
return err
|
||||
}
|
||||
a.emitLog("app", fmt.Sprintf("Installed update %s at %s; restarting", ver, target))
|
||||
|
||||
a.uiHealth.mu.Lock()
|
||||
hidden := a.uiHealth.windowHidden
|
||||
a.uiHealth.mu.Unlock()
|
||||
args := cli.WindowArgs{Background: hidden, WaitPID: uint32(os.Getpid())}.Args()
|
||||
if err := selfupdate.Launch(target, args); err != nil {
|
||||
a.emitLog("app", "Could not start the updated Reims-Go: "+err.Error())
|
||||
return a.updateErr("err.update_relaunch")
|
||||
}
|
||||
// Return to the frontend first, then quit for real (not to the tray).
|
||||
go func() {
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
a.QuitApp()
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// finishAppUpdate runs at startup: removes what an earlier swap left next to
|
||||
// the executable and, after an update restart, the downloaded installer files.
|
||||
func (a *App) finishAppUpdate() {
|
||||
exe, err := selfupdate.Executable()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
selfupdate.Cleanup(exe)
|
||||
if a.launch.WaitPID == 0 {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
dataRoot := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
if dataRoot != "" {
|
||||
_ = os.RemoveAll(appUpdateDir(dataRoot))
|
||||
}
|
||||
a.emitLog("app", "Reims-Go updated to "+version.Version)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
func TestDownloadAppUpdateVerifiesAgainstSums(t *testing.T) {
|
||||
body := []byte("reims-go v9.9.9 build")
|
||||
h := sha256.Sum256(body)
|
||||
good := hex.EncodeToString(h[:])
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/SHA256SUMS.txt":
|
||||
fmt.Fprintf(w, "%s reims-go-v9.9.9-windows-amd64.exe\n", good)
|
||||
case "/bad/SHA256SUMS.txt":
|
||||
fmt.Fprintf(w, "%s reims-go-v9.9.9-windows-amd64.exe\n", strings.Repeat("0", 64))
|
||||
case "/app.exe":
|
||||
_, _ = w.Write(body)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
info := version.UpdateInfo{
|
||||
Latest: "v9.9.9", HasUpdate: true,
|
||||
AssetName: "reims-go-v9.9.9-windows-amd64.exe", AssetSize: int64(len(body)),
|
||||
DownloadURL: srv.URL + "/app.exe", SumsURL: srv.URL + "/SHA256SUMS.txt",
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
path, sum, err := downloadAppUpdate(context.Background(), info, dir, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sum != good || filepath.Dir(path) != dir {
|
||||
t.Fatalf("path %s sum %s", path, sum)
|
||||
}
|
||||
|
||||
info.SumsURL = srv.URL + "/bad/SHA256SUMS.txt"
|
||||
if _, _, err := downloadAppUpdate(context.Background(), info, t.TempDir(), nil); err == nil || !strings.Contains(err.Error(), "SHA256 mismatch") {
|
||||
t.Fatalf("a hash mismatch must fail, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallAppUpdateGuards(t *testing.T) {
|
||||
cfg := config.Default()
|
||||
cfg.Locale = i18n.EnUS
|
||||
a := &App{cfg: cfg}
|
||||
|
||||
appUpdateReady.Lock()
|
||||
appUpdateReady.version, appUpdateReady.path, appUpdateReady.sha256 = "", "", ""
|
||||
appUpdateReady.Unlock()
|
||||
if err := a.InstallAppUpdate(); err == nil || !strings.Contains(err.Error(), "Download the update first") {
|
||||
t.Fatalf("nothing downloaded: got %v", err)
|
||||
}
|
||||
|
||||
// A file that no longer matches its verified hash is refused before any swap.
|
||||
f := filepath.Join(t.TempDir(), "reims-go-v9.9.9-windows-amd64.exe")
|
||||
if err := os.WriteFile(f, []byte("swapped after download"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
appUpdateReady.Lock()
|
||||
appUpdateReady.version, appUpdateReady.path, appUpdateReady.sha256 = "v9.9.9", f, strings.Repeat("a", 64)
|
||||
appUpdateReady.Unlock()
|
||||
if err := a.InstallAppUpdate(); err == nil || !strings.Contains(err.Error(), "changed on disk") {
|
||||
t.Fatalf("changed file: got %v", err)
|
||||
}
|
||||
appUpdateReady.Lock()
|
||||
cleared := appUpdateReady.path == ""
|
||||
appUpdateReady.Unlock()
|
||||
if !cleared {
|
||||
t.Fatal("a changed download must be forgotten")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
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.ValidateCreateLocalized(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, cfgCopy.Locale)
|
||||
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("%s", i18n.T(cfgCopy.Locale, "validate.name_taken", 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,175 @@
|
||||
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"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
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
|
||||
PluginDiagnostics []plugin.DiagnosticsEntry
|
||||
}
|
||||
|
||||
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 code, detail := reims.DiagnoseGPULog(b.QEMULog); code != "" {
|
||||
hostSummary["gpu_diagnosis"] = map[string]string{
|
||||
"code": code,
|
||||
"detail": detail,
|
||||
}
|
||||
}
|
||||
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 len(b.PluginDiagnostics) > 0 {
|
||||
if err := addJSON("plugin-diagnostics.json", b.PluginDiagnostics); 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,
|
||||
PluginDiagnostics: a.collectPluginDiagnostics(context.Background(), name),
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||