Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6cb6467a3c | ||
|
|
d55c965e6d | ||
|
|
8df8663932 | ||
|
|
a312ff4567 | ||
|
|
8d94d7976c | ||
|
|
d573104072 | ||
|
|
ae253be3e1 | ||
|
|
f26f5be4c3 | ||
|
|
3281bfed12 | ||
|
|
bc59aca9e5 | ||
|
|
5c6735ada1 | ||
|
|
fd48130c32 | ||
|
|
5a8014864e | ||
|
|
03dc4cbe4c | ||
|
|
16fe93defd | ||
|
|
b493b395e4 | ||
|
|
593a8d92a3 | ||
|
|
6eca802ddd | ||
|
|
fbfe376403 | ||
|
|
4b12b435ed | ||
|
|
49659193fa | ||
|
|
3c75181fbc | ||
|
|
d11ea85b73 | ||
|
|
2fde035993 | ||
|
|
ee5c02f54f | ||
|
|
6fbcd6422e | ||
|
|
a1b8e96c3d | ||
|
|
5e12d5511b | ||
|
|
3b33e3b6bf | ||
|
|
dfa1372f9c | ||
|
|
3ab04c3627 | ||
|
|
8721f3de70 | ||
|
|
6bac79b346 | ||
|
|
c8b792b316 | ||
|
|
563b5a45bb | ||
|
|
aacaec535d | ||
|
|
8887771bec | ||
|
|
97597d5334 | ||
|
|
07ec5f9543 | ||
|
|
f8943ea78c | ||
|
|
aabe0cf29f | ||
|
|
974389f56b | ||
|
|
b1eec6050b | ||
|
|
30db99fc71 | ||
|
|
0bb1e1a8a6 | ||
|
|
f0207315b6 | ||
|
|
de1eb1f92f | ||
|
|
1fdbefd9c9 | ||
|
|
cbcbec7f83 | ||
|
|
6628da21ff | ||
|
|
e62742f65d | ||
|
|
7672925cac | ||
|
|
e7a6dd7a5b | ||
|
|
0e8454d494 | ||
|
|
c2c168da4e | ||
|
|
8150b4aee3 | ||
|
|
80bc11f1c2 | ||
|
|
e6c8388c37 | ||
|
|
5f96f4ab08 | ||
|
|
43d793ec36 | ||
|
|
4a2bffd5d2 | ||
|
|
fc19631676 | ||
|
|
059c1a3b76 | ||
|
|
2d5ee45163 | ||
|
|
c125fb2510 | ||
|
|
0d6a153621 | ||
|
|
003821a28a | ||
|
|
5f8d96a401 | ||
|
|
1c5e5484b9 | ||
|
|
a32fe323ab | ||
|
|
f622a3a5b0 | ||
|
|
061e65bc52 | ||
|
|
4cc4b6c02c | ||
|
|
790a42912e | ||
|
|
552d6e4cad | ||
|
|
2596728789 | ||
|
|
347840490e | ||
|
|
585669e0b3 | ||
|
|
f96d78be14 | ||
|
|
8270597fe2 | ||
|
|
c1b33c9c4f | ||
|
|
05ddd2b6f3 | ||
|
|
847d447d81 | ||
|
|
9eb8d95443 | ||
|
|
2235195587 | ||
|
|
827f942238 | ||
|
|
84f42a7604 | ||
|
|
e83cce28e6 | ||
|
|
93c981ff01 | ||
|
|
b6fde8fd4b | ||
|
|
8b6ca5c719 | ||
|
|
71fb8bb458 | ||
|
|
74be2f73a9 | ||
|
|
7ba5e3fa9c | ||
|
|
890ca4c5ad | ||
|
|
25766a9cdb | ||
|
|
59aaf36eb5 | ||
|
|
9204b58987 | ||
|
|
5cbd7bceac | ||
|
|
d7e1091074 | ||
|
|
6dcf33f71b | ||
|
|
2ffddf94b4 | ||
|
|
5e39b11566 | ||
|
|
fe139def0c | ||
|
|
e259833b5f | ||
|
|
809ce68cf3 | ||
|
|
8ff80090d8 | ||
|
|
f4993fa333 | ||
|
|
18acc57209 | ||
|
|
e62f6127fe | ||
|
|
957da43b2d | ||
|
|
9baa1e341c | ||
|
|
dc534b72b4 | ||
|
|
6e7c5e602a | ||
|
|
9bd4ac67ef | ||
|
|
2b8ea23074 | ||
|
|
371eb11629 | ||
|
|
655f015038 | ||
|
|
e8c9186a76 | ||
|
|
de523c5323 | ||
|
|
3ce0000215 | ||
|
|
1e80caa255 | ||
|
|
bcfedf5d36 | ||
|
|
9e9ae6f19b | ||
|
|
5a5977f93e | ||
|
|
2513513470 | ||
|
|
ceeb483cfb | ||
|
|
5c647308f4 | ||
|
|
14f72889dd | ||
|
|
66da194b05 | ||
|
|
fd23e88679 | ||
|
|
18df9e5c49 | ||
|
|
e800d55f9f | ||
|
|
7582fd2cfb | ||
|
|
ceeec602be | ||
|
|
21eef18f7b | ||
|
|
d085734c58 | ||
|
|
2a87c8d3b0 | ||
|
|
c91f5901a7 | ||
|
|
0802f77705 | ||
|
|
464ff5683f | ||
|
|
1eb7ac949a | ||
|
|
f20bb61724 | ||
|
|
7b023e5c82 | ||
|
|
5e67d50012 | ||
|
|
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 |
No files matched your search
@@ -1,2 +1,3 @@
|
||||
*.patch -text
|
||||
*.diff -text
|
||||
internal/guesttools/file_sync.sh text eol=lf
|
||||
@@ -1,32 +1,57 @@
|
||||
name: Bug 反馈
|
||||
description: 报告启动失败、安装异常或界面问题
|
||||
name: Bug Report / Bug 反馈
|
||||
description: Report a crash, startup failure, install error, or UI issue / 报告崩溃、启动失败、装机异常或界面问题
|
||||
title: "[Bug]: "
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thank you for reporting an issue! Both **English** and **Chinese (中文)** are welcome.
|
||||
感谢反馈!支持使用 **中文** 或 **English** 填写,请勿附带真实序列号、MAC 地址、SMC OSK 或任何 Apple 系统镜像。
|
||||
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: Area / 问题所属阶段或模块
|
||||
description: Select the closest area where the issue occurs / 选择最接近的问题模块
|
||||
options:
|
||||
- Host check & WHPX / 宿主机体检与 WHPX
|
||||
- Portable runtime install & update / 便携运行时安装与更新
|
||||
- macOS installer download & setup / 镜像下载与装机
|
||||
- VM startup, GPU & display / 虚拟机启动、显卡与显示
|
||||
- Performance & disk I/O / 性能与磁盘 I/O
|
||||
- Guest Tools (clipboard, shared folder, sleep) / Guest Tools(剪贴板、共享目录、防休眠)
|
||||
- Plugins, UI & CLI / 插件、界面与命令行
|
||||
- Other / 其他
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: 问题描述
|
||||
description: 简述遇到了什么问题,以及预期行为。
|
||||
label: What happened? / 问题描述
|
||||
description: Describe the actual behavior and what you expected / 简述实际现象以及你的预期行为
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: env
|
||||
attributes:
|
||||
label: 宿主机环境
|
||||
description: 建议附带 `reims-go doctor` 输出(请勿包含序列号、MAC 地址或 OSK 等敏感信息)。
|
||||
label: Host & Runtime Environment / 宿主机与运行时环境
|
||||
description: Paste `reims-go doctor` output or fill in the summary below (redact any sensitive info) / 建议粘贴 `reims-go doctor` 输出或填写以下信息
|
||||
placeholder: |
|
||||
- Windows 版本:例如 Windows 11 24H2 / Windows 10 22H2
|
||||
- CPU / 显卡:例如 i7-12700K / RTX 4070 Ti
|
||||
- Reims-Go 版本:例如 v0.2.0
|
||||
- 运行时版本:例如 runtime-3731afd
|
||||
- Windows: e.g. Windows 11 24H2 / Windows 10 22H2 (Build 19045)
|
||||
- CPU / GPU: e.g. i7-12700K / RTX 4070 Ti (Driver version)
|
||||
- Reims-Go: e.g. v0.2.8
|
||||
- Runtime: e.g. runtime-3731afd (stable / alpha)
|
||||
- macOS guest: e.g. macOS 26.x
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: 复现步骤
|
||||
label: Steps to Reproduce / 复现步骤
|
||||
placeholder: |
|
||||
1. ...
|
||||
2. ...
|
||||
@@ -34,5 +59,8 @@ body:
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: 相关日志(可选)
|
||||
label: Logs or Redacted Diagnostics Bundle / 日志或脱敏排障包(可选)
|
||||
description: |
|
||||
You can attach the redacted diagnostics archive exported from the app, or paste relevant QEMU / console logs here.
|
||||
可直接拖入应用导出的「脱敏排障包」,或粘贴相关 QEMU / 日志片段。
|
||||
render: text
|
||||
@@ -1,5 +1,8 @@
|
||||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: 开发路线图(Roadmap)
|
||||
- name: Roadmap / 开发路线图
|
||||
url: https://github.com/Nwflower/Reims-Go/blob/main/docs/roadmap.md
|
||||
about: 查看当前进度与已规划功能,避免重复提问
|
||||
about: Check current progress and planned features before opening a duplicate / 查看当前进度与已规划功能,避免重复提问
|
||||
- name: Documentation / 使用文档(中文 · English)
|
||||
url: https://github.com/Nwflower/Reims-Go/blob/main/README.en.md
|
||||
about: Quick start, requirements, and troubleshooting guides / 快速开始、环境要求与常见问题排查
|
||||
@@ -1,16 +1,24 @@
|
||||
name: 功能建议
|
||||
description: 提出新功能想法或体验改进建议
|
||||
name: Feature Request / 功能建议
|
||||
description: Propose a new feature or UX improvement / 提出新功能想法或体验改进建议
|
||||
title: "[Feature]: "
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Both **English** and **Chinese (中文)** are welcome. Feel free to check the [Roadmap](https://github.com/Nwflower/Reims-Go/blob/main/docs/roadmap.md) first.
|
||||
支持使用 **中文** 或 **English** 填写,建议先查阅 [开发路线图](https://github.com/Nwflower/Reims-Go/blob/main/docs/roadmap.md) 确认是否已在规划中。
|
||||
|
||||
- type: textarea
|
||||
id: summary
|
||||
attributes:
|
||||
label: 你希望解决什么问题或新增什么功能?
|
||||
label: Problem or Feature Idea / 你希望解决什么问题或新增什么功能?
|
||||
description: Describe the workflow or pain point this would improve / 说明具体使用场景、痛点或期望能力
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: details
|
||||
attributes:
|
||||
label: 补充说明(可选)
|
||||
description: 使用场景、交互设想或参考案例。
|
||||
label: Proposed Design or References (Optional) / 交互设想或参考案例(可选)
|
||||
description: Mockups, CLI examples, or similar tools / 可附草图、CLI 用法设想或参考产品
|
||||
@@ -0,0 +1,51 @@
|
||||
name: Hardware Compatibility Report / 硬件兼容性反馈
|
||||
description: Share GPU, CPU, or Windows 10/11 vGPU compatibility test results / 反馈显卡、CPU 或 Windows 10/11 的 vGPU 实测兼容情况
|
||||
title: "[Compat]: "
|
||||
labels: ["compatibility"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Help improve the Windows hardware compatibility matrix (GPU Vulkan drivers, hybrid CPUs, Windows 10/11 WHPX). Both **English** and **Chinese (中文)** are welcome.
|
||||
欢迎提交你的宿主机硬件实测结果(NVIDIA / AMD / Intel Arc 显卡驱动、混合架构 CPU、Win10/Win11 WHPX),帮助完善兼容性分级。
|
||||
|
||||
- type: dropdown
|
||||
id: result
|
||||
attributes:
|
||||
label: Result / 实测结果
|
||||
options:
|
||||
- Works cleanly with reims-vgpu / reims-vgpu 硬件加速正常可用
|
||||
- Boots with issues (artifacts, device lost, sleep/reboot issue) / 可启动但存在异常(花屏、设备丢失、休眠或重启异常)
|
||||
- Fails on reims-vgpu, works on VMware SVGA / reims-vgpu 不可用,切换 VMware SVGA 后正常
|
||||
- Fails to boot (WHPX / CPU / kernel-irqchip issue) / 无法启动(WHPX、CPU 或中断控制器问题)
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: hardware
|
||||
attributes:
|
||||
label: Hardware & OS Details / 硬件与系统信息
|
||||
description: Paste `reims-go doctor` output (recommended) or fill in the fields below / 建议直接粘贴 `reims-go doctor` 输出,或按模板填写
|
||||
placeholder: |
|
||||
- Windows: e.g. Windows 11 24H2 (Build 26100) / Windows 10 22H2 (Build 19045)
|
||||
- CPU: e.g. Intel Core Ultra 9 285H / Ryzen 7 7840HS
|
||||
- GPU & Driver: e.g. AMD Radeon 780M / RTX 4070 Ti (Driver xx.x.x, Vulkan 1.x)
|
||||
- Reims-Go & Runtime: e.g. v0.2.8 + runtime-3731afd (stable / alpha)
|
||||
- macOS Guest & Controller: e.g. macOS 26.x, 8 vCPU, 16G RAM, NVMe / VirtIO
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: notes
|
||||
attributes:
|
||||
label: Observations & Workarounds / 现象说明与有效绕过方式
|
||||
description: Note whether kernel-irqchip, P-core pinning, or a specific driver version made a difference / 说明是否开启了 kernel-irqchip、P 核绑定,或切换特定显卡驱动后的差异
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Relevant Logs (Optional) / 相关日志片段(可选)
|
||||
description: Redact serial numbers or MAC addresses before posting / 粘贴前请确保不含序列号或 MAC 地址
|
||||
render: text
|
||||
@@ -0,0 +1,68 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 743 180" width="743" height="180" role="img" aria-label="Reims-Go"><svg x="0" y="0" width="180" height="180" viewBox="0 0 1024 1024">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#3b8cff"/>
|
||||
<stop offset="0.55" stop-color="#2f5bea"/>
|
||||
<stop offset="1" stop-color="#3b1fb8"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="gloss" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#ffffff" stop-opacity="0.28"/>
|
||||
<stop offset="0.45" stop-color="#ffffff" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#6d5dfc"/>
|
||||
<stop offset="0.45" stop-color="#ff7a9a"/>
|
||||
<stop offset="0.8" stop-color="#ffb86b"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="lake" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#2f6bff"/>
|
||||
<stop offset="1" stop-color="#1a2a8f"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="bolt" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#ffe14d"/>
|
||||
<stop offset="1" stop-color="#ff9f0a"/>
|
||||
</linearGradient>
|
||||
<clipPath id="screen">
|
||||
<rect x="252" y="372" width="520" height="318" rx="26"/>
|
||||
</clipPath>
|
||||
<filter id="shadow" x="-20%" y="-20%" width="140%" height="150%">
|
||||
<feDropShadow dx="0" dy="22" stdDeviation="26" flood-color="#0b0d3a" flood-opacity="0.35"/>
|
||||
</filter>
|
||||
<filter id="iconShadow" x="-10%" y="-10%" width="120%" height="125%">
|
||||
<feDropShadow dx="0" dy="14" stdDeviation="16" flood-color="#000000" flood-opacity="0.22"/>
|
||||
</filter>
|
||||
</defs>
|
||||
|
||||
<!-- squircle base -->
|
||||
<g filter="url(#iconShadow)">
|
||||
<rect x="80" y="80" width="864" height="864" rx="200" fill="url(#bg)"/>
|
||||
<rect x="80" y="80" width="864" height="864" rx="200" fill="url(#gloss)"/>
|
||||
</g>
|
||||
|
||||
<!-- VM window -->
|
||||
<g filter="url(#shadow)">
|
||||
<rect x="220" y="268" width="584" height="454" rx="52" fill="#f7f8fc"/>
|
||||
</g>
|
||||
<circle cx="280" cy="322" r="17" fill="#ff5f57"/>
|
||||
<circle cx="332" cy="322" r="17" fill="#febc2e"/>
|
||||
<circle cx="384" cy="322" r="17" fill="#28c840"/>
|
||||
|
||||
<!-- guest display: a lake at dusk -->
|
||||
<g clip-path="url(#screen)">
|
||||
<rect x="252" y="372" width="520" height="318" fill="url(#sky)"/>
|
||||
<circle cx="600" cy="540" r="44" fill="#fff3d6" opacity="0.9"/>
|
||||
<path d="M252 560 L340 470 L400 520 L480 430 L560 505 L620 465 L700 530 L772 480 L772 600 L252 600 Z" fill="#2b2d7a"/>
|
||||
<path d="M252 585 L330 530 L420 575 L500 520 L590 570 L672 535 L772 580 L772 610 L252 610 Z" fill="#1c1f5e"/>
|
||||
<rect x="252" y="598" width="520" height="92" fill="url(#lake)"/>
|
||||
<rect x="560" y="616" width="80" height="6" rx="3" fill="#fff3d6" opacity="0.7"/>
|
||||
<rect x="574" y="636" width="52" height="6" rx="3" fill="#fff3d6" opacity="0.5"/>
|
||||
<rect x="586" y="656" width="28" height="6" rx="3" fill="#fff3d6" opacity="0.35"/>
|
||||
</g>
|
||||
|
||||
<!-- GPU acceleration badge -->
|
||||
<g filter="url(#shadow)">
|
||||
<circle cx="776" cy="724" r="128" fill="#16182e"/>
|
||||
</g>
|
||||
<circle cx="776" cy="724" r="128" fill="none" stroke="#ffffff" stroke-opacity="0.92" stroke-width="16"/>
|
||||
<path d="M800 628 L708 744 L768 744 L748 822 L846 700 L784 700 Z" fill="url(#bolt)" stroke="#ffcf3a" stroke-width="6" stroke-linejoin="round"/>
|
||||
</svg><g transform="translate(206 126)"><defs><linearGradient id="wm" gradientUnits="userSpaceOnUse" x1="376" y1="0" x2="531" y2="0"><stop offset="0" stop-color="#3b8cff"/><stop offset="0.5" stop-color="#6d5dfc"/><stop offset="1" stop-color="#ff7a9a"/></linearGradient><linearGradient id="wmb" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ff9f0a"/></linearGradient></defs><g fill="none" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"><path d="M7.5 -7.5V-36A24 28.5 0 0 1 31.5 -64.5" stroke="#f4f5fa"/><path d="M50.5 -36H107.5A28.5 28.5 0 1 0 100.18 -16.93" stroke="#f4f5fa"/><path d="M133.5 -64.5V-7.5" stroke="#f4f5fa"/><circle cx="133.5" cy="-94" r="9" fill="#ff7a9a"/><path d="M159.5 -7.5V-36A22 28.5 0 0 1 203.5 -36V-7.5M203.5 -36A22 28.5 0 0 1 247.5 -36V-7.5" stroke="#f4f5fa"/><path d="M311.05 -59.02A21 14.25 0 0 0 273.5 -50.25A21 14.25 0 0 0 294.5 -36A21 14.25 0 0 1 315.5 -21.75A21 14.25 0 0 1 277.95 -12.98" stroke="#f4f5fa"/><path d="M340.5 -36H358.5" stroke="#5d6382"/><path d="M440.5 -36A28.5 28.5 0 1 1 440.5 -36.01" stroke="url(#wm)"/><path d="M440.5 -64.5V0A28.5 22.5 0 0 1 387.32 11.25" stroke="url(#wm)"/><path d="M523.5 -36A28.5 28.5 0 1 1 523.5 -36.01" stroke="url(#wm)"/></g></g></svg>
|
||||
|
After Width: | Height: | Size: 4.5 KiB |
@@ -0,0 +1,68 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 743 180" width="743" height="180" role="img" aria-label="Reims-Go"><svg x="0" y="0" width="180" height="180" viewBox="0 0 1024 1024">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#3b8cff"/>
|
||||
<stop offset="0.55" stop-color="#2f5bea"/>
|
||||
<stop offset="1" stop-color="#3b1fb8"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="gloss" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#ffffff" stop-opacity="0.28"/>
|
||||
<stop offset="0.45" stop-color="#ffffff" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#6d5dfc"/>
|
||||
<stop offset="0.45" stop-color="#ff7a9a"/>
|
||||
<stop offset="0.8" stop-color="#ffb86b"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="lake" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#2f6bff"/>
|
||||
<stop offset="1" stop-color="#1a2a8f"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="bolt" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#ffe14d"/>
|
||||
<stop offset="1" stop-color="#ff9f0a"/>
|
||||
</linearGradient>
|
||||
<clipPath id="screen">
|
||||
<rect x="252" y="372" width="520" height="318" rx="26"/>
|
||||
</clipPath>
|
||||
<filter id="shadow" x="-20%" y="-20%" width="140%" height="150%">
|
||||
<feDropShadow dx="0" dy="22" stdDeviation="26" flood-color="#0b0d3a" flood-opacity="0.35"/>
|
||||
</filter>
|
||||
<filter id="iconShadow" x="-10%" y="-10%" width="120%" height="125%">
|
||||
<feDropShadow dx="0" dy="14" stdDeviation="16" flood-color="#000000" flood-opacity="0.22"/>
|
||||
</filter>
|
||||
</defs>
|
||||
|
||||
<!-- squircle base -->
|
||||
<g filter="url(#iconShadow)">
|
||||
<rect x="80" y="80" width="864" height="864" rx="200" fill="url(#bg)"/>
|
||||
<rect x="80" y="80" width="864" height="864" rx="200" fill="url(#gloss)"/>
|
||||
</g>
|
||||
|
||||
<!-- VM window -->
|
||||
<g filter="url(#shadow)">
|
||||
<rect x="220" y="268" width="584" height="454" rx="52" fill="#f7f8fc"/>
|
||||
</g>
|
||||
<circle cx="280" cy="322" r="17" fill="#ff5f57"/>
|
||||
<circle cx="332" cy="322" r="17" fill="#febc2e"/>
|
||||
<circle cx="384" cy="322" r="17" fill="#28c840"/>
|
||||
|
||||
<!-- guest display: a lake at dusk -->
|
||||
<g clip-path="url(#screen)">
|
||||
<rect x="252" y="372" width="520" height="318" fill="url(#sky)"/>
|
||||
<circle cx="600" cy="540" r="44" fill="#fff3d6" opacity="0.9"/>
|
||||
<path d="M252 560 L340 470 L400 520 L480 430 L560 505 L620 465 L700 530 L772 480 L772 600 L252 600 Z" fill="#2b2d7a"/>
|
||||
<path d="M252 585 L330 530 L420 575 L500 520 L590 570 L672 535 L772 580 L772 610 L252 610 Z" fill="#1c1f5e"/>
|
||||
<rect x="252" y="598" width="520" height="92" fill="url(#lake)"/>
|
||||
<rect x="560" y="616" width="80" height="6" rx="3" fill="#fff3d6" opacity="0.7"/>
|
||||
<rect x="574" y="636" width="52" height="6" rx="3" fill="#fff3d6" opacity="0.5"/>
|
||||
<rect x="586" y="656" width="28" height="6" rx="3" fill="#fff3d6" opacity="0.35"/>
|
||||
</g>
|
||||
|
||||
<!-- GPU acceleration badge -->
|
||||
<g filter="url(#shadow)">
|
||||
<circle cx="776" cy="724" r="128" fill="#16182e"/>
|
||||
</g>
|
||||
<circle cx="776" cy="724" r="128" fill="none" stroke="#ffffff" stroke-opacity="0.92" stroke-width="16"/>
|
||||
<path d="M800 628 L708 744 L768 744 L748 822 L846 700 L784 700 Z" fill="url(#bolt)" stroke="#ffcf3a" stroke-width="6" stroke-linejoin="round"/>
|
||||
</svg><g transform="translate(206 126)"><defs><linearGradient id="wm" gradientUnits="userSpaceOnUse" x1="376" y1="0" x2="531" y2="0"><stop offset="0" stop-color="#3b8cff"/><stop offset="0.5" stop-color="#6d5dfc"/><stop offset="1" stop-color="#ff7a9a"/></linearGradient><linearGradient id="wmb" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ff9f0a"/></linearGradient></defs><g fill="none" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"><path d="M7.5 -7.5V-36A24 28.5 0 0 1 31.5 -64.5" stroke="#16182e"/><path d="M50.5 -36H107.5A28.5 28.5 0 1 0 100.18 -16.93" stroke="#16182e"/><path d="M133.5 -64.5V-7.5" stroke="#16182e"/><circle cx="133.5" cy="-94" r="9" fill="#ff7a9a"/><path d="M159.5 -7.5V-36A22 28.5 0 0 1 203.5 -36V-7.5M203.5 -36A22 28.5 0 0 1 247.5 -36V-7.5" stroke="#16182e"/><path d="M311.05 -59.02A21 14.25 0 0 0 273.5 -50.25A21 14.25 0 0 0 294.5 -36A21 14.25 0 0 1 315.5 -21.75A21 14.25 0 0 1 277.95 -12.98" stroke="#16182e"/><path d="M340.5 -36H358.5" stroke="#a3a8bf"/><path d="M440.5 -36A28.5 28.5 0 1 1 440.5 -36.01" stroke="url(#wm)"/><path d="M440.5 -64.5V0A28.5 22.5 0 0 1 387.32 11.25" stroke="url(#wm)"/><path d="M523.5 -36A28.5 28.5 0 1 1 523.5 -36.01" stroke="url(#wm)"/></g></g></svg>
|
||||
|
After Width: | Height: | Size: 4.5 KiB |
|
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 |
@@ -1,251 +0,0 @@
|
||||
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
|
||||
|
||||
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 }}
|
||||
steps:
|
||||
- id: r
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
WANT: ${{ inputs.upstream_commit }}
|
||||
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?
|
||||
skip=false
|
||||
for tag in $(gh release list -R "$GITHUB_REPOSITORY" --limit 1000 --json tagName -q '.[].tagName' | grep '^runtime-' || true); do
|
||||
case "$commit" in "${tag#runtime-}"*) skip=true; echo "Upstream $commit is already released as $tag";; esac
|
||||
done
|
||||
echo "skip=$skip" >> "$GITHUB_OUTPUT"
|
||||
|
||||
build:
|
||||
needs: resolve
|
||||
if: needs.resolve.outputs.skip != 'true'
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 150
|
||||
outputs:
|
||||
short: ${{ steps.patches.outputs.short }}
|
||||
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 HEAD).Trim()
|
||||
"short=$short" >> $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
|
||||
"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 `
|
||||
-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:SHORT_COMMIT `
|
||||
-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.SHORT_COMMIT }}-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:SHORT_COMMIT
|
||||
$dir = Join-Path $env:RUNNER_TEMP 'releases'
|
||||
$assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", 'SHA256SUMS.txt') |
|
||||
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, built automatically from upstream [steelbrain/reims-vgpu@$c](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
|
||||
|
||||
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: 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
|
||||
@@ -26,12 +26,32 @@ jobs:
|
||||
cache: pnpm
|
||||
cache-dependency-path: frontend/pnpm-lock.yaml
|
||||
|
||||
- name: Frontend build
|
||||
- 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 test & build
|
||||
shell: pwsh
|
||||
run: |
|
||||
pnpm --dir frontend install --frozen-lockfile
|
||||
pnpm --dir frontend test
|
||||
pnpm --dir frontend build
|
||||
|
||||
- name: Debug workspace hygiene check & self-test
|
||||
shell: pwsh
|
||||
run: |
|
||||
node scripts/debug/check.mjs
|
||||
node --test scripts/debug/debug.test.mjs
|
||||
|
||||
- name: Go test & vet
|
||||
shell: pwsh
|
||||
run: |
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
name: Dev Release (Rolling)
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths-ignore:
|
||||
- "docs/**"
|
||||
- "README.md"
|
||||
- "README.en.md"
|
||||
- "AGENTS.md"
|
||||
- ".github/ISSUE_TEMPLATE/**"
|
||||
- ".github/readme/**"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: dev-release-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
dev-release:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- 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 rolling dev version
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
function Parse-StableSemVer([string]$v) {
|
||||
if ($v -match '^v([0-9]+)\.([0-9]+)\.([0-9]+)$') {
|
||||
return [PSCustomObject]@{
|
||||
Tag = $v
|
||||
Major = [int]$Matches[1]
|
||||
Minor = [int]$Matches[2]
|
||||
Patch = [int]$Matches[3]
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Compare-SemVer($a, $b) {
|
||||
if ($a.Major -ne $b.Major) { return [Math]::Sign($a.Major - $b.Major) }
|
||||
if ($a.Minor -ne $b.Minor) { return [Math]::Sign($a.Minor - $b.Minor) }
|
||||
return [Math]::Sign($a.Patch - $b.Patch)
|
||||
}
|
||||
|
||||
$shortSha = (git rev-parse --short=7 HEAD).Trim()
|
||||
if ([string]::IsNullOrWhiteSpace($shortSha)) {
|
||||
throw 'Could not resolve HEAD short commit SHA'
|
||||
}
|
||||
|
||||
$stableTags = @(
|
||||
git tag --list 'v*' |
|
||||
ForEach-Object { Parse-StableSemVer $_.Trim() } |
|
||||
Where-Object { $_ -ne $null } |
|
||||
Sort-Object Major, Minor, Patch -Descending
|
||||
)
|
||||
$latestStable = if ($stableTags.Count -gt 0) { $stableTags[0] } else { $null }
|
||||
|
||||
$codeVer = $null
|
||||
$verFile = Get-Content -Raw -LiteralPath 'internal/version/version.go'
|
||||
if ($verFile -match 'var\s+Version\s*=\s*"(v[0-9]+\.[0-9]+\.[0-9]+)"') {
|
||||
$codeVer = Parse-StableSemVer $Matches[1]
|
||||
}
|
||||
|
||||
if ($latestStable) {
|
||||
if ($codeVer -and (Compare-SemVer $codeVer $latestStable) -gt 0) {
|
||||
$nextBase = $codeVer.Tag
|
||||
} else {
|
||||
$nextBase = "v$($latestStable.Major).$($latestStable.Minor).$($latestStable.Patch + 1)"
|
||||
}
|
||||
$baseStableTag = $latestStable.Tag
|
||||
} elseif ($codeVer) {
|
||||
$nextBase = $codeVer.Tag
|
||||
$baseStableTag = ''
|
||||
} else {
|
||||
$nextBase = 'v0.0.1'
|
||||
$baseStableTag = ''
|
||||
}
|
||||
|
||||
$devVersion = "$nextBase-dev-$shortSha"
|
||||
"DEV_VERSION=$devVersion" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
"DEV_COMMIT=$shortSha" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
"BASE_STABLE_TAG=$baseStableTag" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
Write-Host "Resolved DEV_VERSION=$devVersion (commit=$shortSha, baseStable=$baseStableTag)"
|
||||
|
||||
- name: Generate dev release notes
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$devVersion = $env:DEV_VERSION
|
||||
$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-dev.md"
|
||||
& ./scripts/build-release-notes.ps1 `
|
||||
-Tag $devVersion `
|
||||
-Channel dev `
|
||||
-PrevTag $env:BASE_STABLE_TAG `
|
||||
-Commit $env:DEV_COMMIT `
|
||||
-Repo $env:GITHUB_REPOSITORY `
|
||||
-StableRuntimeTag $runtimeTag `
|
||||
-StableRuntimeTitle $runtimeTitle `
|
||||
-OutFile $notesFile
|
||||
"RELEASE_NOTES_FILE=$notesFile" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
Write-Host "Generated dev release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $devVersion"
|
||||
|
||||
- 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'
|
||||
$ver = $env:DEV_VERSION
|
||||
$dist = 'dist-release'
|
||||
New-Item -ItemType Directory -Force -Path $dist | Out-Null
|
||||
$verPkg = 'github.com/Nwflower/reims-go/internal/version'
|
||||
$guiOut = Join-Path $dist "reims-go-$ver-windows-amd64.exe"
|
||||
wails build -s -trimpath -ldflags "-s -w -X $verPkg.Version=$ver" -o "reims-go-$ver-windows-amd64.exe"
|
||||
if ($LASTEXITCODE) { throw "wails build failed ($LASTEXITCODE)" }
|
||||
Copy-Item (Join-Path 'build\bin' "reims-go-$ver-windows-amd64.exe") $guiOut
|
||||
$zipOut = [IO.Path]::ChangeExtension($guiOut, '.zip')
|
||||
Compress-Archive -LiteralPath @($guiOut, 'LICENSE', 'NOTICE.md') -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: Update rolling dev GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$releaseTag = 'dev'
|
||||
$ver = $env:DEV_VERSION
|
||||
$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"
|
||||
}
|
||||
$title = "Reims-Go Dev ($ver)"
|
||||
$files = @(Get-ChildItem -LiteralPath 'dist-release' -File | Select-Object -ExpandProperty FullName)
|
||||
$keepNames = @($files | ForEach-Object { [IO.Path]::GetFileName($_) })
|
||||
|
||||
# Point the fixed 'dev' tag to the commit being built.
|
||||
git tag -f $releaseTag $env:GITHUB_SHA
|
||||
if ($LASTEXITCODE -ne 0) { throw "git tag -f $releaseTag failed ($LASTEXITCODE)" }
|
||||
git push --force origin "refs/tags/$releaseTag"
|
||||
if ($LASTEXITCODE -ne 0) { throw "git push --force refs/tags/$releaseTag failed ($LASTEXITCODE)" }
|
||||
|
||||
$exists = $true
|
||||
$existingAssets = @()
|
||||
try {
|
||||
$relJson = gh release view $releaseTag --json assets 2>$null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
$exists = $false
|
||||
} else {
|
||||
$existingAssets = @(($relJson | ConvertFrom-Json).assets)
|
||||
}
|
||||
} catch {
|
||||
$exists = $false
|
||||
}
|
||||
|
||||
if ($exists) {
|
||||
# Upload new assets first so the release is never left empty if upload fails.
|
||||
gh release upload $releaseTag @files --clobber
|
||||
if ($LASTEXITCODE -ne 0) { throw "gh release upload failed ($LASTEXITCODE)" }
|
||||
foreach ($asset in $existingAssets) {
|
||||
if ($keepNames -notcontains $asset.name) {
|
||||
Write-Host "Removing stale dev asset $($asset.name)"
|
||||
gh release delete-asset $releaseTag $asset.name --yes
|
||||
if ($LASTEXITCODE -ne 0) { throw "gh release delete-asset $($asset.name) failed ($LASTEXITCODE)" }
|
||||
}
|
||||
}
|
||||
gh release edit $releaseTag `
|
||||
--target $env:GITHUB_SHA `
|
||||
--prerelease `
|
||||
--title $title `
|
||||
--notes-file $notesFile
|
||||
if ($LASTEXITCODE -ne 0) { throw "gh release edit failed ($LASTEXITCODE)" }
|
||||
} else {
|
||||
gh release create $releaseTag @files `
|
||||
--target $env:GITHUB_SHA `
|
||||
--prerelease `
|
||||
--title $title `
|
||||
--notes-file $notesFile
|
||||
if ($LASTEXITCODE -ne 0) { throw "gh release create failed ($LASTEXITCODE)" }
|
||||
}
|
||||
@@ -7,7 +7,7 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Release tag to build & publish (e.g. v0.2.1)"
|
||||
description: "Release tag to build & publish (e.g. v0.2.9 or v0.2.9-alpha.1)"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
@@ -18,6 +18,9 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || '' }}
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
@@ -33,12 +36,57 @@ jobs:
|
||||
cache: pnpm
|
||||
cache-dependency-path: frontend/pnpm-lock.yaml
|
||||
|
||||
- name: Resolve version tag
|
||||
- name: Resolve version tag and channel
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$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" }
|
||||
$tag = $tag.Trim()
|
||||
if ($tag -match '^v[0-9]+\.[0-9]+\.[0-9]+$') {
|
||||
$channel = 'stable'
|
||||
} elseif ($tag -match '^v[0-9]+\.[0-9]+\.[0-9]+-alpha(?:[.-][0-9A-Za-z.-]+)?$') {
|
||||
$channel = 'alpha'
|
||||
} else {
|
||||
throw "Release tag must be stable (vX.Y.Z) or alpha test (vX.Y.Z-alpha[.N]), got: $tag"
|
||||
}
|
||||
"RELEASE_TAG=$tag" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
"RELEASE_CHANNEL=$channel" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
Write-Host "Resolved tag=$tag channel=$channel"
|
||||
|
||||
- name: Generate release notes
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tag = $env:RELEASE_TAG
|
||||
$channel = $env:RELEASE_CHANNEL
|
||||
$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 `
|
||||
-Channel $channel `
|
||||
-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 $channel release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $tag"
|
||||
|
||||
- name: Build frontend
|
||||
shell: pwsh
|
||||
@@ -67,8 +115,11 @@ jobs:
|
||||
# One executable: the window without arguments, command-line mode with a command.
|
||||
$guiOut = Join-Path $dist "reims-go-$tag-windows-amd64.exe"
|
||||
wails build -s -trimpath -ldflags "-s -w -X $verPkg.Version=$tag" -o "reims-go-$tag-windows-amd64.exe"
|
||||
if ($LASTEXITCODE) { throw "wails build failed ($LASTEXITCODE)" }
|
||||
Copy-Item (Join-Path 'build\bin' "reims-go-$tag-windows-amd64.exe") $guiOut
|
||||
$lines = @(Get-ChildItem -LiteralPath $dist -File | Sort-Object Name | ForEach-Object {
|
||||
$zipOut = [IO.Path]::ChangeExtension($guiOut, '.zip')
|
||||
Compress-Archive -LiteralPath @($guiOut, 'LICENSE', 'NOTICE.md') -DestinationPath $zipOut -CompressionLevel Optimal -Force
|
||||
$lines = @(Get-Item -LiteralPath $guiOut, $zipOut | ForEach-Object {
|
||||
$h = (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLowerInvariant()
|
||||
"$h $($_.Name)"
|
||||
})
|
||||
@@ -82,18 +133,74 @@ jobs:
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tag = $env:RELEASE_TAG
|
||||
$channel = $env:RELEASE_CHANNEL
|
||||
$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"
|
||||
}
|
||||
$title = if ($channel -eq 'alpha') { "Reims-Go $tag (Alpha)" } else { "Reims-Go $tag" }
|
||||
$files = @(Get-ChildItem -LiteralPath 'dist-release' -File | Select-Object -ExpandProperty FullName)
|
||||
$exists = $true
|
||||
$existingBody = ''
|
||||
try {
|
||||
gh release view $tag *> $null
|
||||
if ($LASTEXITCODE -ne 0) { $exists = $false }
|
||||
$relJson = gh release view $tag --json body 2>$null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
$exists = $false
|
||||
} else {
|
||||
$existingBody = (($relJson | ConvertFrom-Json).body | Out-String).Trim()
|
||||
}
|
||||
} catch {
|
||||
$exists = $false
|
||||
}
|
||||
if ($exists) {
|
||||
gh release upload $tag @files --clobber
|
||||
if ($LASTEXITCODE -ne 0) { throw "gh release upload failed ($LASTEXITCODE)" }
|
||||
$editArgs = @('release', 'edit', $tag, '--title', $title)
|
||||
if ($channel -eq 'alpha') {
|
||||
$editArgs += '--prerelease'
|
||||
} else {
|
||||
$editArgs += @('--prerelease=false', '--latest')
|
||||
}
|
||||
# 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) {
|
||||
$editArgs += @('--notes-file', $notesFile)
|
||||
}
|
||||
& gh @editArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "gh release edit failed ($LASTEXITCODE)" }
|
||||
} else {
|
||||
gh release create $tag @files `
|
||||
--title "Reims-Go $tag" `
|
||||
--generate-notes
|
||||
$createArgs = @('release', 'create', $tag) + $files + @('--title', $title, '--notes-file', $notesFile)
|
||||
if ($channel -eq 'alpha') {
|
||||
$createArgs += '--prerelease'
|
||||
} else {
|
||||
$createArgs += '--latest'
|
||||
}
|
||||
& gh @createArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "gh release create failed ($LASTEXITCODE)" }
|
||||
}
|
||||
|
||||
- name: Delete all published alpha test releases after stable release
|
||||
if: env.RELEASE_CHANNEL == 'stable'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
# Only delete app alpha prereleases (vX.Y.Z-alpha*); never touch runtime-* or the rolling dev release.
|
||||
$rels = gh release list -R $env:GITHUB_REPOSITORY --limit 1000 --json tagName,isPrerelease,isDraft | ConvertFrom-Json
|
||||
$alphas = @($rels | Where-Object {
|
||||
$_.isPrerelease -and
|
||||
-not $_.isDraft -and
|
||||
$_.tagName -match '^v[0-9]+\.[0-9]+\.[0-9]+-alpha(?:[.-][0-9A-Za-z.-]+)?$'
|
||||
})
|
||||
if ($alphas.Count -eq 0) {
|
||||
Write-Host "No published alpha test releases to clean up."
|
||||
exit 0
|
||||
}
|
||||
foreach ($rel in $alphas) {
|
||||
Write-Host "Deleting alpha test release $($rel.tagName)"
|
||||
gh release delete $rel.tagName -R $env:GITHUB_REPOSITORY --yes --cleanup-tag
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Failed to delete alpha test release $($rel.tagName) (exit $LASTEXITCODE)"
|
||||
}
|
||||
}
|
||||
@@ -28,3 +28,6 @@ Thumbs.db
|
||||
*.log
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# Local debugging scratch, work orders, run logs, caches, scratch worktrees
|
||||
.debug/
|
||||
@@ -1,47 +1,77 @@
|
||||
# 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>`(推荐非系统盘),不得提交到仓库,也不放入 `.debug/`。
|
||||
2. **禁止使用系统临时目录存放任务中间产物**:开发与排查产生的临时脚本、截图、日志、构建/测试缓存与隔离运行产物一律写入仓库根目录的 `.debug/`(已加入 `.gitignore`,严禁提交),不读写系统临时目录(`%TEMP%` / `/tmp`)。
|
||||
3. **临时文件及时退役**:任务完成后清理草稿与会话目录;值得长期保留的探针沉淀为正式单元测试(`*_test.go`)或 `scripts/` 下的工具脚本,不留在 `.debug/`。
|
||||
|
||||
## 调试目录与临时产物纪律(`.debug/`)
|
||||
|
||||
1. **顶层目录白名单**:`.debug/` 顶层只允许 [`scripts/debug/paths.mjs`](scripts/debug/paths.mjs) 声明的 5 个子目录,任何工具与脚本必须写入其中之一,`node scripts/debug/check.mjs` 会拒绝顶层出现其他杂项:
|
||||
- `.debug/tmp/` — 一次性会话临时产物,由 `scripts/debug/tmp.mjs` 创建、记录属主 PID 并回收。
|
||||
- `.debug/work/` — 跨会话工单与交接材料(含 `refs/`、`shots/`、`tmp/` 与 `work.md`),由 `scripts/debug/work.mjs` 管理。
|
||||
- `.debug/cache/` — 可由源码树重建的本地工具缓存。
|
||||
- `.debug/runs/` — 本地运行输出(日志、抓包、报告、追踪与隔离运行目录)。
|
||||
- `.debug/worktrees/` — 临时 Git 工作树,由 `scripts/debug/worktree.mjs` 管理(移除前先解除 Windows Junction / 符号链接,避免误删主树 `frontend/node_modules`)。
|
||||
2. **脚本与命令行红线**:
|
||||
- **禁止在命令行内联长多行脚本**:需要多行脚本时,先写入 `.debug/tmp/`(或所属工单的 `tmp/`)再执行。
|
||||
- **作者修改走编辑工具**:新逻辑、文案与规则变更直接通过编辑工具修改;跨文件机械改造(重命名、批量改路径、语法迁移)可将脚本放在 `.debug/tmp/` 运行,执行后通读完整 `git diff` 并通过全部校验,脚本不得编写新逻辑。
|
||||
3. **一次性临时目录与工单分工**:
|
||||
- 范围明确、当前会话可完成的小修改、只读检查和一次性试验直接进行,不建工单;无中间产物时不创建临时目录。
|
||||
- 用户显式要求工单,或任务需要跨会话恢复、多人/多 Agent 交接、持续积累验收证据时,再通过 `work.mjs` 建立或复用工单。
|
||||
- 一次性产物用 `node scripts/debug/tmp.mjs new <label>` 或 `run <label> -- <command>`(向子进程注入 `REIMS_TMP_DIR`):正常结束(退出码 0)自动删除目录,失败保留证据供排查;超期(24 小时)且属主进程已退出的残留由 `gc --yes` 回收,存活进程与符号链接/Junction 受保护。
|
||||
- 工单按 `draft → active → review → close` 流转;`close` 校验通过后删除整个工单目录。
|
||||
- **持久文档零引用**:`README.md`、`README.en.md`、`CHANGELOG.md`、`AGENTS.md` 与 `docs/` 严禁引用具体工单 ID 或 `.debug/tmp/` 会话实例路径。
|
||||
|
||||
| 命令 | 用途 |
|
||||
| :--- | :--- |
|
||||
| `node scripts/debug/tmp.mjs new <label>` | 在 `.debug/tmp/` 创建带属主记录的会话目录并打印路径 |
|
||||
| `node scripts/debug/tmp.mjs run <label> -- <cmd>` | 注入 `REIMS_TMP_DIR` 执行命令;成功自动删除,失败保留证据 |
|
||||
| `node scripts/debug/tmp.mjs list \| close <id> \| gc [--yes]` | 查看、关闭或回收已退出且超期的临时会话目录 |
|
||||
| `node scripts/debug/work.mjs new <slug> --title "…"` | 在 `.debug/work/` 创建工单及 `refs/`、`shots/`、`tmp/` |
|
||||
| `node scripts/debug/work.mjs start \| verify \| review \| close <id>` | 推进工单状态;`close` 校验后删除工单目录 |
|
||||
| `node scripts/debug/work.mjs path <id> [tmp\|refs\|shots]` | 打印工单材料目录绝对路径;`paths <id>` 打印工单声明的文件列表 |
|
||||
| `node scripts/debug/worktree.mjs add\|remove <path> [ref]` | 在 `.debug/worktrees/` 安全创建或移除临时工作树 |
|
||||
| `node scripts/debug/check.mjs` | 校验 `.debug/` 顶层白名单、临时会话、工单与持久文档引用 |
|
||||
|
||||
## 事实核验与安全规则
|
||||
|
||||
1. **上游行为以一手源码为准**:引用 `reims-ctl` / `reims-vgpu` 行为时附上游 commit 与 `文件:行号`;未实测项显式标「待验证」。
|
||||
2. **不绕过系统安全与人工确认**:UAC 提权启用 WHPX、重启 Windows、macOS GUI 安装向导、发布正式 Release 等操作由人确认触发。唯一例外(2026-11-28 决定):`build-runtime.yml` 每天从上游自动构建,通过 alpha 准入检查后可以自动发布为 GitHub **预发布**(`alpha` 通道),也会自动删除较旧的、未升级的 alpha 预发布。升为 `stable`(正式发布)始终由人触发。
|
||||
1. **上游行为以一手源码为准**:引用 `reims-ctl` / `reims-vgpu` 行为时核对对应上游 commit 与 `文件:行号`;未实测项显式标注「待验证」。
|
||||
2. **人工确认红线**:UAC 提权启用 WHPX、重启 Windows、macOS 图形安装向导、向上游提交 PR、将运行时升级为 `stable` 正式发布,均须由人确认触发。自动化例外:Reims vGPU fork 的 Preview 工作流每天构建,通过 `alpha` 准入检查后在运行时仓库发布 GitHub 预发布。
|
||||
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 产物只进 `alpha`(2026-11-28 前叫 `candidate`),经真实宿主冒烟测试并由人确认后才升级(`portable-runtime-spec.md` 第 6 节)。
|
||||
7. **配置只通过 `reims-ctl set` 写入**:不直接改 `vm.toml`,让上游的校验和 OpenCore 重建逻辑生效(`docs/shell-design.md`)。
|
||||
4. **构建职责**:本仓库构建并发布客户端。便携运行时的编译、打包、依赖补丁和 Preview 发布由 [Reims vGPU fork 的 CI](https://github.com/yxc0915/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) 负责。
|
||||
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 中。
|
||||
9. **禁止空 `catch` 吞错**:严禁编写带有空代码块(含仅注释或空语句)的 `catch` 语句或空回调(如 `catch {}`、`catch (e) {}`、`.catch(() => {})`、`.then(..., () => {})`)把失败静默包装成成功;捕获异常后必须执行明确的错误处理(上报/展示错误、记录诊断告警、分类过滤预期错误并重抛其余异常,或显式回退状态)。该约束由 [`frontend/scripts/test-no-empty-catch.mjs`](frontend/scripts/test-no-empty-catch.mjs) 在 `pnpm --dir frontend test` 中强制校验。
|
||||
|
||||
## 开源合规边界
|
||||
|
||||
- `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 **必须**附带对应源码包和许可证文本,缺一不可。新包先进 `alpha`(GitHub 预发布,由 CI 每天从上游自动构建),经真实宿主冒烟并由人确认后才升为 `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/) — 对上游的补丁队列,清单见 `patches/README.md`
|
||||
- [`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/pr-review-guidelines.md`](docs/pr-review-guidelines.md) — PR 变更归属、跨仓交付与客户端独立性审查
|
||||
- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时打包、发布通道与合规规范
|
||||
- [`docs/plugin-architecture.md`](docs/plugin-architecture.md) — 插件系统架构与扩展接口规范
|
||||
- [`docs/guest-plugin-migration.md`](docs/guest-plugin-migration.md) — 客体插件化与 macOS 剥离的迁移路径
|
||||
- [运行时补丁与上游跟踪](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) — 运行时源码入口与依赖补丁
|
||||
@@ -0,0 +1,224 @@
|
||||
# 更新日志
|
||||
|
||||
本文件只记录 Reims-Go 桌面应用的变化。便携运行时(`runtime-*`)的版本另见 [Releases](https://github.com/Nwflower/Reims-Go/releases)。
|
||||
|
||||
## v0.2.11 — 2026-12-01
|
||||
|
||||
### 新功能
|
||||
|
||||
- **Intel 虚拟机挂起与瞬间恢复**([#37](https://github.com/Nwflower/Reims-Go/pull/37)):支持在虚拟机运行中挂起保存内存与图形状态并在下次启动秒级恢复,采用事务化状态保存、异常回滚与多通道直接 I/O 优化。
|
||||
- **自定义共享文件夹与 WebDAV 路径隔离**([#38](https://github.com/Nwflower/Reims-Go/pull/38)、[#39](https://github.com/Nwflower/Reims-Go/pull/39)):Guest Tools 升级至 v8,支持按虚拟机配置自定义宿主机共享文件夹(含卷校验与设置页管理),并统一基于 `os.Root` 收紧 WebDAV 与回退文件同步的路径边界。
|
||||
- **内置并行下载器插件与可扩展下载器接口**([#24](https://github.com/Nwflower/Reims-Go/pull/24)、[#52](https://github.com/Nwflower/Reims-Go/pull/52)):离线安装包与镜像下载支持多线程分片并行加速,并开放 `downloaders` 插件扩展点。
|
||||
- **可插拔「镜像」页面与内置 macOS 镜像源**:将原安装包页升级为支持多插件镜像源切换的「镜像」页(`images.source` 扩展点),内置 macOS 镜像插件并接入品牌描边加载动画与服务可用性提示。
|
||||
- **插件 UI / 桥接契约锁定与主题能力升级(uiApi 2.0 / bridgeApi 1.0)**:冻结插件契约,新增主题插槽(slots)、全窗装饰层(layers)、布局选项(侧栏位置/模式、界面紧凑度、标题栏高度)以及图标与品牌标志覆写。
|
||||
- **虚拟机硬件、显示与交互增强**:
|
||||
- 支持按虚拟机配置 Windows 修饰键重映射及 `Win` 键映射为 macOS `Command`([#53](https://github.com/Nwflower/Reims-Go/pull/53))。
|
||||
- 支持一键轮换 OpenCore SMBIOS 硬件标识([#47](https://github.com/Nwflower/Reims-Go/pull/47))及可选同步宿主机 SMBIOS Type 17 内存规格([#44](https://github.com/Nwflower/Reims-Go/pull/44))。
|
||||
- 支持 `qcow2` `extended_l2` 磁盘性能优化、快照改写保护与 Windows Defender 排除项引导([#56](https://github.com/Nwflower/Reims-Go/pull/56))。
|
||||
- 全屏模式与客体分辨率解耦以支持 1.5x HiDPI 缩放([#22](https://github.com/Nwflower/Reims-Go/pull/22));新增关机模式选择与一键强制退出([#51](https://github.com/Nwflower/Reims-Go/pull/51))、虚拟机关闭确认弹窗及「关于」页 Discord 社区入口([#57](https://github.com/Nwflower/Reims-Go/pull/57))。
|
||||
- 支持停用内置 macOS 客体插件并按驱动隔离虚拟机生命周期路由。
|
||||
|
||||
### 优化与修复
|
||||
|
||||
- **统一插件前端组件与视觉样式**:合并已安装列表、插件市场与首次向导中的插件图标块、信任徽标、胶囊筛选按钮与搜索框(补齐语言包图标识别与 RTL 逻辑属性),将插件危险确认弹窗、表单、复选框、错误提示条与加载骨架屏收敛至全局基础组件。
|
||||
- **修复 Apple 在线恢复镜像鉴权与离线路径展开**([#34](https://github.com/Nwflower/Reims-Go/pull/34)):修复恢复镜像下载鉴权、分区 chunklist 校验及 `reims-ctl show` 主目录路径展开问题。
|
||||
- **修复剪贴板互通与文件同步可靠性**([#28](https://github.com/Nwflower/Reims-Go/pull/28)、[#33](https://github.com/Nwflower/Reims-Go/pull/33)):加固 Windows 剪贴板锁与 DIB/PNG 回声抑制,修复回退同步删除传播、Windows 驱动器挂载认证及 CLI 直接启动时保留 Guest Tools 的问题。
|
||||
- **修复 Vulkan 诊断与 GPU 驱动发现**([#21](https://github.com/Nwflower/Reims-Go/pull/21)、[#46](https://github.com/Nwflower/Reims-Go/pull/46)):清理失效的 GPU 驱动缓存文件,从活动显示驱动包中发现缺失的 Vulkan ICD 并在向导与 `doctor` 中展示探测诊断。
|
||||
- **界面性能与工程健壮性加固**([#57](https://github.com/Nwflower/Reims-Go/pull/57)):消除软件合成模式下的弹窗卡顿,修复插件状态判定、列表错误上报与休眠虚拟机停用驱动插件问题,全面禁止空 `catch` 吞错并加入静态门禁测试;运行时发布源切换至独立的 Reims vGPU / QEMU fork 通道。
|
||||
|
||||
## v0.2.10 — 2026-11-30
|
||||
|
||||
### 新功能
|
||||
|
||||
- 插件市场默认索引切换至 `reims-go/plugins` 组织仓库并新增 jsDelivr CDN 备选镜像自动回退;新增内置 `ed25519` 公钥环验签机制(`internal/plugin/keyring.go`)与 `reims-go plugin pack` 打包签名命令(自动执行静态门禁、生成 `SHA256SUMS` 与可选 `SHA256SUMS.sig`)。
|
||||
|
||||
### 优化与修复
|
||||
|
||||
- 修复虚拟机键盘打字时偶发字符重复/错序(如 `ABC` 变为 `ABCC`/`ABCAC`/`ABCAB`)及中文拼音首字连发(如 `h` 跳出两个 `h` 变为 `h好的`)的问题([#14](https://github.com/Nwflower/Reims-Go/issues/14)):在运行时补丁中改用 `WM_CHAR` 硬件扫描码区分物理与非物理字符,并在客户端按能力门控 `REIMS_GO_INPUT_URL`(同时受「宿主输入服务与 IME 桥接」插件开关控制),使已安装 `runtime-3731afd-p3` 的用户升级应用后即可直接恢复。
|
||||
- 修复标题栏菜单切换闪烁与浮层焦点提示竞争问题([#16](https://github.com/Nwflower/Reims-Go/pull/16))。
|
||||
- 将界面繁体中文(`zh-TW`)语言标签调整为更中性的表述。
|
||||
|
||||
## v0.2.9 — 2026-11-30
|
||||
|
||||
### 新功能
|
||||
|
||||
- 全新多语种与本地化架构(i18n / L10n v2,来自 [#10](https://github.com/Nwflower/Reims-Go/pull/10)):重构 7 域语言目录、零依赖 ICU 复数/格式引擎与区域回退链,支持系统语言自动跟随与完整第三方语言包插件协议(新增 `reims-go plugin locale init|check` 工具链);全面本地化系统托盘、文件选择器及高 DPI 悬浮安装引导,并为错误信息加入错误码与自动脱敏诊断详情。
|
||||
- 应用内更新新增通道切换:「关于」页支持选择 `stable`(正式版)、`alpha`(测试版)或 `dev`(开发构建)更新通道;切换至测试通道更新时自动保留上一版本备份以便随时回滚。
|
||||
- 完善插件静态安全准入与插件市场能力:
|
||||
- 新增统一静态安全扫描与硬拦截门禁(`internal/plugin/scanner.go`):拦截 L1/L4 插件夹带可执行文件或系统脚本、L3 插件未声明二进制、SVG `<script>`/`on*`/`javascript:` 主动内容、主题/交互脚本宿主逃逸(`window.go`/`window.runtime`/`eval`/`Function`)及未声明网络调用;针对 L3 Sidecar 原生程序如实声明完整 Windows 账户权限并展示可执行文件 SHA-256 与通俗能力说明。
|
||||
- 新增惰性插件市场客户端(`internal/plugin/market.go`):支持静态远程 `index.json` 拉取(环境变量 `REIMS_GO_PLUGIN_MARKET_URL` 自定义镜像或离线模式)、内存/磁盘双层缓存与内嵌离线兜底、软撤回(`withdrawn`)拦截与替代提示、下载前 `engines`/`platforms` 兼容预检与 SHA-256 强校验。
|
||||
- CLI 新增 `reims-go plugin search`、`reims-go plugin update`、`reims-go plugin install <id>` 及支持 `.zip`/`--json` 三段式安全报告的 `reims-go plugin doctor`;界面「插件」页新增「插件市场」标签页、本地包导入前静态安全报告弹窗与已安装插件安全扫描入口。
|
||||
- 支持清理未激活的旧版便携运行时:在「内核」页及命令行均可一键删除不再使用的历史运行时以释放磁盘空间。
|
||||
- 新增宿主侧 CoW backing 链深度体检(无须提权):当虚拟系统盘 CoW 派生链深度 ≥ 2 层或父镜像缺失时,在 `reims-go doctor`、宿主机体检及虚拟机详情/存储设置页一致展示提示。
|
||||
- 「关于」页新增第三方开源许可证查看器,随应用内置完整第三方开源许可证文本。
|
||||
- 新增三层系统盘小文件 I/O 基准与采样工具套件(`scripts/io-bench/`:`darwin/amd64` 客体基准、QMP `query-blockstats` / 延迟直方图采样与语言无关 Windows `PhysicalDisk` 计数器采集),`internal/qmp` 补充通用 `Query` 与块层统计查询方法。
|
||||
|
||||
### 优化与修复
|
||||
|
||||
- OpenCore 引导阶段新增对 FileVault 预启动界面鼠标与数字键盘输入的支持([#6](https://github.com/Nwflower/Reims-Go/pull/6))。
|
||||
- 修复新建虚拟机向导中下载 macOS 安装包时与「安装包」页进度不同步的问题([#13](https://github.com/Nwflower/Reims-Go/pull/13))。
|
||||
- 修复虚拟机重启流程:重启前等待 QEMU 进程完全退出并回收已提交内存,避免连续重启时内存占用叠加或启动失败。
|
||||
- 统一 `qcow2` 建盘选项来源:空间回收(`CompactDisk`)与 CoW 派生(`CreateCoWOverlay`)自动读取源镜像的 `compat`、`cluster_size`、`lazy_refcounts`、`extended_l2`、`refcount_bits` 与 `compression_type` 并原样透传,导入转换统一使用与上游一致的默认选项。
|
||||
- 移除已停用的 GitCode 运行时镜像同步与下载源,并加固多语种插件信任边界、敏感信息脱敏、WCAG 对比度与窄窗口布局。
|
||||
|
||||
## 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,21 +1,200 @@
|
||||
MIT License
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
Copyright (c) 2026 Reims-Go contributors
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
1. Definitions.
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate acts) or agreed
|
||||
to in writing, shall any Contributor be liable to You for damages,
|
||||
including any direct, indirect, special, incidental, or consequential
|
||||
damages of any character arising as a result of this License or out of
|
||||
the use or inability to use the Work (including but not limited to damages
|
||||
for loss of goodwill, work stoppage, computer failure or malfunction, or
|
||||
any and all other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 Reims-Go contributors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,30 +1,64 @@
|
||||
# Third-Party Notices
|
||||
|
||||
`Reims-Go` itself (Go backend and desktop frontend) is licensed under the MIT
|
||||
License (see `LICENSE`). That license applies to Reims-Go's own code only and
|
||||
is separate from the portable runtime bundle it invokes as an external child
|
||||
process.
|
||||
`Reims-Go` itself (Go backend and desktop frontend) is licensed under the Apache
|
||||
License, Version 2.0 (see `LICENSE`). That license applies to Reims-Go's own code
|
||||
only and is separate from the portable runtime bundle it invokes as an external
|
||||
child process. Compatibility patches in the runtime repository are licensed
|
||||
under terms compatible with their target upstream projects (see [runtime patch
|
||||
licenses](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/LICENSE)).
|
||||
|
||||
The Reims-Go desktop executable also incorporates open-source Go and frontend
|
||||
libraries (including Wails, React, Radix UI, Lucide, Inter font, Go `golang.org/x`
|
||||
packages, `klauspost/compress`, and `ulikunitz/xz`) under permissive licenses
|
||||
(MIT, BSD, ISC, and SIL OFL 1.1); see `go.mod` and `frontend/package.json` for
|
||||
the complete dependency list.
|
||||
|
||||
### go-toml v2
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2021 - 2023 Thomas Pelletier
|
||||
|
||||
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:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
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.
|
||||
|
||||
## Portable runtime
|
||||
|
||||
The portable runtime bundle (`reims-runtime-win-x64-<commit>.tar.zst`) contains
|
||||
precompiled binaries built from the following upstream open-source projects.
|
||||
Each runtime release ships the matching source package, `NOTICE.md`, and
|
||||
`licenses/` (see `docs/portable-runtime-spec.md` §7):
|
||||
`licenses/` (see `docs/portable-runtime-spec.md` §6):
|
||||
|
||||
1. **reims-vgpu / reims-ctl**
|
||||
- Upstream: https://github.com/steelbrain/reims-vgpu
|
||||
- License: `GPL-2.0-or-later OR LGPL-3.0-or-later`
|
||||
2. **metal2vulkan / metal2vulkan-runtime**
|
||||
- Upstream: https://github.com/steelbrain/metal2vulkan
|
||||
- License: See upstream repository license
|
||||
- License: `GPL-2.0-or-later OR LGPL-3.0-or-later`
|
||||
3. **reims-util**
|
||||
- Upstream: https://github.com/steelbrain/reims-util
|
||||
- License: See upstream repository license
|
||||
- License: `GPL-2.0-or-later OR LGPL-3.0-or-later`
|
||||
4. **QEMU (qemu-reims-vgpu fork)**
|
||||
- Upstream: https://github.com/steelbrain/qemu-reims-vgpu
|
||||
- License: `GPL-2.0-only` / `GPL-2.0-or-later` (and component licenses in QEMU)
|
||||
5. **MSYS2 CLANG64 runtime libraries, libva, Mesa vaon12**
|
||||
- Upstream: https://github.com/msys2/MINGW-packages
|
||||
- License: Respective open-source licenses of each packaged DLL
|
||||
- License: Respective open-source licenses of each packaged DLL (bundled under `licenses/msys2/` in the runtime archive)
|
||||
|
||||
No Apple proprietary files, macOS installers, recovery images, or SMC keys are
|
||||
included in this repository or in any runtime bundle.
|
||||
@@ -0,0 +1,212 @@
|
||||
<p align="center">
|
||||
<a href="https://github.com/Nwflower/Reims-Go">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/banner-dark.svg" />
|
||||
<img src="./.github/readme/banner-light.svg" width="440" alt="Reims-Go" />
|
||||
</picture>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>A macOS virtual machine for Windows. GPU-accelerated, ready out of the box.</strong>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/macOS-Tahoe%2026-16182e?logo=apple&logoColor=white" alt="macOS Tahoe 26" />
|
||||
<img src="https://img.shields.io/badge/host-Windows%2010%20%7C%2011-0078D4?logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZmlsbD0id2hpdGUiIGQ9Ik0wIDMuNCA5LjggMnY5LjRIMHptMTEtMS42TDI0IDB2MTEuM0gxMXpNMCAxMi42aDkuOFYyMkwwIDIwLjZ6bTExIDBoMTNWMjRsLTEzLTEuOHoiLz48L3N2Zz4=" alt="Windows 10 | 11" />
|
||||
<a href="https://github.com/Nwflower/Reims-Go/releases"><img src="https://img.shields.io/github/v/release/Nwflower/Reims-Go?label=release&color=3b8cff" alt="release" /></a>
|
||||
<a href="https://github.com/Nwflower/Reims-Go/stargazers"><img src="https://img.shields.io/github/stars/Nwflower/Reims-Go?style=flat&label=stars&logo=github&color=ffb86b" alt="GitHub stars" /></a>
|
||||
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-ff7a9a" alt="license Apache-2.0" /></a>
|
||||
<a href="https://discord.gg/Tj682rW5rS"><img src="https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://qm.qq.com/q/TBmRJlVbSo"><img src="https://img.shields.io/badge/QQ%20Group-1136042744-12B7F5?logo=qq&logoColor=white" alt="QQ Group 1136042744" /></a>
|
||||
<!-- Go daily list: uncomment after making it; replace %23N with the rank
|
||||
<a href="https://github.com/trending/go?since=daily"><img src="https://img.shields.io/badge/Trending-%23N%20Go%20Repo%20of%20the%20Day-00ADD8?logo=go&logoColor=white" alt="GitHub Trending: Go Repo of the Day" /></a>
|
||||
-->
|
||||
</p>
|
||||
|
||||
<!-- Official Trendshift badge: uncomment once https://trendshift.io/api/badge/repositories/385884 loads
|
||||
<p align="center">
|
||||
<a href="https://trendshift.io/repositories/385884?utm_source=repository-badge&utm_medium=badge&utm_campaign=badge-repository-385884" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/385884" alt="Nwflower%2FReims-Go | Trendshift" width="250" height="55"/></a>
|
||||
</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="#plugin-development">Plugins</a> ·
|
||||
<a href="./docs/roadmap.md">Roadmap</a> ·
|
||||
<a href="#organization-and-community">Community</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 for [reims-vgpu](https://github.com/steelbrain/reims-vgpu). Installing the runtime, downloading macOS, creating VMs and using them day to day all happen in one window.
|
||||
|
||||
> Early development. Features and UI will keep changing.
|
||||
|
||||
## Highlights
|
||||
|
||||
- **GPU acceleration**: macOS Metal graphics run on your Windows GPU through Vulkan.
|
||||
- **Nothing to compile**: download one exe and run it. The app installs the runtime for you, with system proxy support and local archive import.
|
||||
- **No typing during install**: installers come straight from Apple. One click in Recovery types the install command, which erases the disk and starts installing.
|
||||
|
||||
Once macOS is running:
|
||||
|
||||
- Clipboard (including images) and shared folders work both ways; drop files on the window to send them to macOS
|
||||
- Type with Windows IMEs and emoji directly
|
||||
- Save a restore point before updates and roll back in one click; clone a stopped VM in seconds
|
||||
- Close the window and it stays in the tray, with clipboard and sharing still working
|
||||
- SSH port forwarding and VS Code Remote-SSH; common tasks also work from the command line
|
||||
|
||||
For everything else, see the [changelog](./CHANGELOG.md).
|
||||
|
||||
## 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>
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Requirements
|
||||
|
||||
- Windows 10 / 11 (64-bit) with Intel VT-x or AMD-V enabled in BIOS
|
||||
- A discrete Vulkan GPU, NVIDIA RTX series recommended
|
||||
- 16 GB of RAM or more
|
||||
- 150 GB of free disk space, 60 GB at minimum, ideally not on the system drive
|
||||
|
||||
### Install and set up
|
||||
|
||||
Download `reims-go.exe` from [Releases](https://github.com/Nwflower/Reims-Go/releases) and double-click it.
|
||||
|
||||
1. **First launch**: pick a data folder, check your PC and install the runtime. If virtualization is off, turn it on in one click and restart Windows.
|
||||
2. **Create a VM**: click **+** in the sidebar, choose **Offline installer**, and set CPU, memory and disk size.
|
||||
3. **Install macOS**: start the VM, then click the keyboard icon in Recovery Terminal to type the install command. When Setup Assistant appears, click **Exit recovery mode**.
|
||||
4. **Install Guest Tools**: on the macOS desktop, click **Install…** on the Guest Tools row of the VM page, then run the command it shows in macOS Terminal. Clipboard, shared folders and IME input work after that.
|
||||
|
||||
<details>
|
||||
<summary>Command line</summary>
|
||||
|
||||
Run `reims-go.exe` with no arguments to open the window, or with a subcommand to run it in the terminal:
|
||||
|
||||
```powershell
|
||||
reims-go doctor | Out-Host # Check your PC
|
||||
reims-go runtime fetch | Out-Host # Install the runtime
|
||||
reims-go installer download tahoe | Out-Host # Download an 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 PowerShell or cmd, add `| Out-Host` so the terminal waits for the command to finish. `reims-go help` lists every subcommand.
|
||||
|
||||
</details>
|
||||
|
||||
<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>
|
||||
|
||||
## Plugin Development
|
||||
|
||||
Reims-Go ships an out-of-process plugin system with zero external runtime dependencies. Browse and install plugins from the built-in **Plugins** page or import a local `.zip` archive; if a third-party plugin breaks startup, launch with `reims-go --safe-mode` to skip all third-party plugins.
|
||||
|
||||
- **L1 declarative plugins** (JSON + static assets): UI themes backed by the versioned [UI contract](./frontend/ui-contract.json), language packs (domain JSON + optional `.woff2` fonts), VM templates, runtime sources, input filters and rule hooks.
|
||||
- **L3 sidecar plugins** (standalone executables in any language): one isolated process per plugin speaking `Content-Length`-framed JSON-RPC 2.0 over stdin/stdout for custom guest drivers (such as non-macOS VMs), lifecycle hooks, custom commands and diagnostics; Go authors can use the zero-dependency SDK in [`pkg/pluginsdk`](./pkg/pluginsdk).
|
||||
- **Declarative UI extensions**: render native plugin settings from `settings` JSON Schema and contribute menu items, cards and status items to declared host slots.
|
||||
|
||||
<details>
|
||||
<summary>Plugin development CLI</summary>
|
||||
|
||||
```powershell
|
||||
reims-go plugin link <dir> | Out-Host # Link a local plugin directory for development
|
||||
reims-go plugin doctor --contract frontend/ui-contract.json <dir|zip> | Out-Host # Run static security, manifest and UI contract checks
|
||||
reims-go plugin locale init ja-JP --out <dir> | Out-Host # Scaffold a language pack
|
||||
reims-go plugin locale check <dir> | Out-Host # Validate language pack coverage and syntax
|
||||
reims-go plugin pack <dir> | Out-Host # Verify and pack a .zip with SHA256SUMS (optional --sign-key)
|
||||
reims-go plugin search | Out-Host # Browse the official plugin market
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
- Full architecture, `plugin.json` manifest reference, permission tiers and protocol spec: [`docs/plugin-architecture.md`](./docs/plugin-architecture.md)
|
||||
- Official plugin market index and submissions: [`reims-go/plugins`](https://github.com/reims-go/plugins)
|
||||
|
||||
## Organization and Community
|
||||
|
||||
- **GitHub Organization**: [`reims-go`](https://github.com/reims-go) — Maintains the official plugin market index ([`reims-go/plugins`](https://github.com/reims-go/plugins)) and ecosystem repositories; the desktop launcher repository lives at [`Nwflower/Reims-Go`](https://github.com/Nwflower/Reims-Go)
|
||||
- **Discord**: [Join the Discord server](https://discord.gg/Tj682rW5rS) — Bilingual chat, troubleshooting, hardware compatibility reports, alpha testing and plugin development
|
||||
- **QQ Group**: [1136042744](https://qm.qq.com/q/TBmRJlVbSo) — Chinese community chat and feedback
|
||||
|
||||
## License & Notice
|
||||
|
||||
- Reims-Go is licensed under [Apache-2.0](./LICENSE). Runtime components such as QEMU ship as separate programs; their licenses are in [`NOTICE.md`](./NOTICE.md), and every runtime release includes the matching source.
|
||||
- Reims-Go contains no Apple system files; installers are downloaded from Apple on your machine. **The macOS license only permits virtualization on Apple hardware**, so assess your own compliance on other 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,95 +1,75 @@
|
||||
<p align="center">
|
||||
<a href="https://github.com/Nwflower/Reims-Go">
|
||||
<img src="./assets/logo.png" width="76" height="76" alt="Reims-Go" />
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/banner-dark.svg" />
|
||||
<img src="./.github/readme/banner-light.svg" width="440" alt="Reims-Go" />
|
||||
</picture>
|
||||
</a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<strong>为 Windows 打造的 macOS 虚拟机。图形加速、开箱即用。</strong>
|
||||
</p>
|
||||
|
||||
<h1 align="center">Reims-Go</h1>
|
||||
|
||||
<p align="center">
|
||||
在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。
|
||||
<img src="https://img.shields.io/badge/macOS-Tahoe%2026-16182e?logo=apple&logoColor=white" alt="macOS Tahoe 26" />
|
||||
<img src="https://img.shields.io/badge/host-Windows%2010%20%7C%2011-0078D4?logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZmlsbD0id2hpdGUiIGQ9Ik0wIDMuNCA5LjggMnY5LjRIMHptMTEtMS42TDI0IDB2MTEuM0gxMXpNMCAxMi42aDkuOFYyMkwwIDIwLjZ6bTExIDBoMTNWMjRsLTEzLTEuOHoiLz48L3N2Zz4=" alt="Windows 10 | 11" />
|
||||
<a href="https://github.com/Nwflower/Reims-Go/releases"><img src="https://img.shields.io/github/v/release/Nwflower/Reims-Go?label=release&color=3b8cff" alt="release" /></a>
|
||||
<a href="https://github.com/Nwflower/Reims-Go/stargazers"><img src="https://img.shields.io/github/stars/Nwflower/Reims-Go?style=flat&label=stars&logo=github&color=ffb86b" alt="GitHub stars" /></a>
|
||||
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-ff7a9a" alt="license Apache-2.0" /></a>
|
||||
<a href="https://discord.gg/Tj682rW5rS"><img src="https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://qm.qq.com/q/TBmRJlVbSo"><img src="https://img.shields.io/badge/QQ%20群-1136042744-12B7F5?logo=qq&logoColor=white" alt="QQ 交流群 1136042744" /></a>
|
||||
<!-- Go 日榜:上榜后取消注释,把 %23N 改成名次
|
||||
<a href="https://github.com/trending/go?since=daily"><img src="https://img.shields.io/badge/Trending-%23N%20Go%20日榜-00ADD8?logo=go&logoColor=white" alt="GitHub Trending: Go 日榜" /></a>
|
||||
-->
|
||||
</p>
|
||||
|
||||
<!-- Trendshift 官方徽章:https://trendshift.io/api/badge/repositories/385884 能打开后取消注释
|
||||
<p align="center">
|
||||
<a href="https://trendshift.io/repositories/385884?utm_source=repository-badge&utm_medium=badge&utm_campaign=badge-repository-385884" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/385884" alt="Nwflower%2FReims-Go | Trendshift" width="250" height="55"/></a>
|
||||
</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>
|
||||
<a href="#插件与开发">插件与开发</a> ·
|
||||
<a href="./docs/roadmap.md">路线图</a> ·
|
||||
<a href="#项目组与社区">项目组与社区</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>简体中文</strong> · <a href="./README.en.md">English</a>
|
||||
</p>
|
||||
|
||||
<br />
|
||||
|
||||
<p align="center">
|
||||
<img src="./.github/readme/hero.webp" width="100%" alt="Reims-Go 主窗口:浅色外观下的虚拟机详情页与深色外观下的宿主与运行时页" />
|
||||
<img src="./.github/readme/hero.webp" width="100%" alt="Reims-Go 主窗口:浅色外观下的虚拟机页与深色外观下的内核页" />
|
||||
</p>
|
||||
|
||||
<br />
|
||||
|
||||
Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows 桌面应用。环境体检、运行时安装、下载 macOS 到创建并管理虚拟机,都在一个窗口里完成。
|
||||
Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows 桌面应用。装运行时、下载 macOS、建虚拟机和日常使用,都在一个窗口里完成。
|
||||
|
||||
> 早期迭代中,功能与界面仍在持续打磨。
|
||||
> 仍在早期迭代,功能和界面会继续调整。
|
||||
|
||||
<br />
|
||||
## 特点
|
||||
|
||||
## 特性
|
||||
- **显卡加速**:macOS 的 Metal 图形经 Vulkan 交给 Windows 独显执行。
|
||||
- **免编译**:下载一个 exe 就能用。运行时在应用里一键安装,支持系统代理和本地压缩包导入。
|
||||
- **装机不用敲命令**:安装包直接从 Apple 下载;在恢复模式里点一下,装机命令会自动键入,抹盘和安装随即开始。
|
||||
|
||||
- **开箱即用** — 预编译便携运行时一键在线安装,无需配置 MSYS2、Rust 或本地编译。
|
||||
- **体检与调优** — 一键启用 WHPX、启动前校验提交内存、混合架构智能绑核(P-Core / 避开 LP-E 核),新建默认 NVMe。
|
||||
- **离线装机** — 宿主机直连 Apple 断点续传下载;内置离线辅助盘与「粘贴为键入」,装机无需手敲长命令。
|
||||
- **随时调整** — 运行中即可修改配置并标明生效时机,支持一键进出恢复模式;全部数据留在指定目录,不占 C 盘。
|
||||
- **双端一致** — 浅色 / 深色外观与中英双语,GUI 与命令行共用同一套内核。
|
||||
装好之后:
|
||||
|
||||
<br />
|
||||
- 剪贴板(含图片)和共享文件夹与 Windows 互通,文件拖进窗口就能传进 macOS
|
||||
- 中文输入法和 emoji 可以直接输入
|
||||
- 升级系统前留个恢复点,出问题一键回滚;关机的虚拟机能秒级派生副本
|
||||
- 关掉窗口后常驻托盘,剪贴板和共享照常工作
|
||||
- 支持 SSH 端口转发和 VS Code 远程连接,常用操作也能在命令行里完成
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Windows 10 / 11(64 位),支持 WHPX 虚拟化
|
||||
- 支持 Vulkan 的独立显卡(推荐 NVIDIA RTX 系列)
|
||||
- 150 GB 以上可用磁盘空间(建议非 C 盘)
|
||||
|
||||
### 安装
|
||||
|
||||
前往 [Releases](https://github.com/Nwflower/Reims-Go/releases) 下载单文件 `reims-go.exe`,双击即可运行。
|
||||
|
||||
<details>
|
||||
<summary>从源码构建</summary>
|
||||
|
||||
需预先安装 [Go](https://go.dev/dl/)、[Node.js](https://nodejs.org)、[pnpm](https://pnpm.io) 与 [Wails](https://wails.io/docs/gettingstarted/installation):
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/Nwflower/Reims-Go
|
||||
cd Reims-Go
|
||||
wails build
|
||||
```
|
||||
|
||||
产物位于 `build\bin\reims-go.exe`。
|
||||
|
||||
</details>
|
||||
|
||||
### 上手步骤
|
||||
|
||||
1. **初始化** — 首次打开按引导选好数据目录、完成宿主机体检(未开 WHPX 可一键启用并重启),在线安装运行时。
|
||||
2. **新建虚拟机** — 点侧边栏 **+**,选择「离线安装包(推荐)」或先在「安装包」页下载镜像,设定 CPU、内存与磁盘。
|
||||
3. **安装 macOS** — 启动后在恢复终端点右侧键盘图标一键键入安装命令,脚本会自动抹盘并完成离线安装;看到「设置助理」后点「退出恢复模式」。
|
||||
4. **日常管理** — 点齿轮图标随时调整设置,或在「更多」菜单中使用「粘贴为键入」与「进入恢复模式」。
|
||||
|
||||
### 命令行
|
||||
|
||||
命令行模式就在同一个 `reims-go.exe` 里:不带参数打开窗口,带子命令就在终端里执行。
|
||||
|
||||
```powershell
|
||||
reims-go doctor | Out-Host # 环境体检
|
||||
reims-go runtime fetch | Out-Host # 在线安装运行时
|
||||
reims-go installer download tahoe | Out-Host # 下载离线安装包(支持续传)
|
||||
reims-go vm create macos-tahoe | Out-Host # 新建虚拟机
|
||||
reims-go vm start macos-tahoe | Out-Host # 启动虚拟机(交给托盘里的 Reims-Go,带剪贴板与共享目录)
|
||||
```
|
||||
|
||||
`reims-go.exe` 是窗口程序,交互式 PowerShell / cmd 不会等它结束;加 `| Out-Host`(或任何管道、重定向)就会等命令执行完并给出退出码。脚本和 Agent 通过管道调用,不受影响。运行 `reims-go help` 查看全部子命令,加 `--lang en-US` 切换英文输出。
|
||||
|
||||
<br />
|
||||
更多功能见[更新日志](./CHANGELOG.md)。
|
||||
|
||||
## 界面
|
||||
|
||||
@@ -98,16 +78,16 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机(交给托盘
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/host-dark.webp" />
|
||||
<img src="./.github/readme/host-light.webp" alt="宿主与运行时页" />
|
||||
<img src="./.github/readme/host-light.webp" alt="内核页" />
|
||||
</picture>
|
||||
<p align="center"><sub>宿主与运行时</sub></p>
|
||||
<p align="center"><sub>内核</sub></p>
|
||||
</td>
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/vm-dark.webp" />
|
||||
<img src="./.github/readme/vm-light.webp" alt="关于此虚拟机页" />
|
||||
<img src="./.github/readme/vm-light.webp" alt="虚拟机页" />
|
||||
</picture>
|
||||
<p align="center"><sub>关于此虚拟机</sub></p>
|
||||
<p align="center"><sub>虚拟机</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -128,13 +108,105 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机(交给托盘
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<br />
|
||||
## 快速开始
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Windows 10 / 11(64 位),BIOS 里已开启 Intel VT-x 或 AMD-V
|
||||
- 支持 Vulkan 的独立显卡,推荐 NVIDIA RTX 系列
|
||||
- 内存 16 GB 以上
|
||||
- 磁盘空间 150 GB 以上,最少 60 GB,最好不放在系统盘
|
||||
|
||||
### 安装与上手
|
||||
|
||||
从 [Releases](https://github.com/Nwflower/Reims-Go/releases) 下载 `reims-go.exe`,双击运行。
|
||||
|
||||
1. **初始化**:按引导选数据目录、检查电脑、安装运行时。虚拟化没开的话可以一键开启,之后重启 Windows。
|
||||
2. **新建虚拟机**:点侧边栏的 **+**,安装来源选「离线安装包」,设好 CPU、内存和磁盘。
|
||||
3. **安装 macOS**:启动虚拟机,在恢复终端里点键盘图标,装机命令自动键入。看到「设置助理」后点「退出恢复模式」。
|
||||
4. **安装 Guest Tools**:进入桌面后,在虚拟机页 Guest Tools 一行点「安装…」,再到 macOS 终端运行页面给出的命令。装好后剪贴板、共享文件夹和中文输入就能用了。
|
||||
|
||||
<details>
|
||||
<summary>命令行</summary>
|
||||
|
||||
不带参数运行 `reims-go.exe` 会打开窗口,带上子命令则在终端里执行:
|
||||
|
||||
```powershell
|
||||
reims-go doctor | Out-Host # 检查电脑环境
|
||||
reims-go runtime fetch | Out-Host # 安装运行时
|
||||
reims-go installer download tahoe | Out-Host # 下载安装包(支持续传)
|
||||
reims-go vm create macos-tahoe | Out-Host # 新建虚拟机
|
||||
reims-go vm start macos-tahoe | Out-Host # 启动虚拟机
|
||||
reims-go vm stop macos-tahoe | Out-Host # 关闭虚拟机
|
||||
```
|
||||
|
||||
在 PowerShell 或 cmd 里要加上 `| Out-Host`,终端才会等命令执行完再返回。`reims-go help` 列出全部子命令。
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>从源码构建</summary>
|
||||
|
||||
需要 [Go](https://go.dev/dl/)、[Node.js](https://nodejs.org)、[pnpm](https://pnpm.io) 和 [Wails](https://wails.io/docs/gettingstarted/installation):
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/Nwflower/Reims-Go
|
||||
cd Reims-Go
|
||||
wails build
|
||||
```
|
||||
|
||||
产物在 `build\bin\reims-go.exe`。
|
||||
|
||||
</details>
|
||||
|
||||
## 插件与开发
|
||||
|
||||
Reims-Go 内置进程外隔离的插件体系,零外部运行时依赖。可以在应用的「插件」页直接浏览安装官方市场插件或导入本地 `.zip` 包;如插件引发启动异常,可用 `reims-go --safe-mode` 跳过全部第三方插件恢复。
|
||||
|
||||
- **L1 声明式插件**(纯 JSON + 静态资源):界面主题(基于稳定的 [UI 契约](./frontend/ui-contract.json))、多语种语言包(分域 JSON 与可选 `.woff2` 字体)、虚拟机模板、运行时源、输入过滤与规则 Hook。
|
||||
- **L3 Sidecar 插件**(任意语言独立可执行文件):每插件独立进程,通过 stdin/stdout `Content-Length` 分帧 JSON-RPC 2.0 通信,可用于非 macOS 虚拟机驱动、生命周期 Hook、自定义命令与排障采集;Go 开发者可直接使用零依赖 SDK [`pkg/pluginsdk`](./pkg/pluginsdk)。
|
||||
- **声明式 UI 扩展**:通过 `settings` JSON Schema 原生渲染插件设置页,向宿主预定义槽位贡献菜单项、卡片与状态项。
|
||||
|
||||
<details>
|
||||
<summary>插件开发常用命令</summary>
|
||||
|
||||
```powershell
|
||||
reims-go plugin link <dir> | Out-Host # 链接本地插件目录用于开发调试
|
||||
reims-go plugin doctor --contract frontend/ui-contract.json <dir|zip> | Out-Host # 静态安全扫描与清单/UI 契约校验
|
||||
reims-go plugin locale init ja-JP --out <dir> | Out-Host # 生成多语种语言包脚手架
|
||||
reims-go plugin locale check <dir> | Out-Host # 校验语言包覆盖率与格式
|
||||
reims-go plugin pack <dir> | Out-Host # 校验并打包 .zip(自动生成 SHA256SUMS,支持 --sign-key)
|
||||
reims-go plugin search | Out-Host # 浏览官方插件市场
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
- 完整插件架构、清单字段(`plugin.json`)、权限分级与协议规范见 [`docs/plugin-architecture.md`](./docs/plugin-architecture.md)
|
||||
- 官方插件市场索引与投稿发布见 [`reims-go/plugins`](https://github.com/reims-go/plugins)
|
||||
|
||||
## 项目组与社区
|
||||
|
||||
- **GitHub 项目组**:[`reims-go`](https://github.com/reims-go) — 维护官方插件市场索引([`reims-go/plugins`](https://github.com/reims-go/plugins))及周边生态项目;桌面客户端主仓库位于 [`Nwflower/Reims-Go`](https://github.com/Nwflower/Reims-Go)
|
||||
- **Discord 社区**:[加入 Discord 服务器](https://discord.gg/Tj682rW5rS) — 中英双语交流、排障求助、硬件兼容性实测、Alpha 测试与插件开发
|
||||
- **QQ 交流群**:[1136042744](https://qm.qq.com/q/TBmRJlVbSo) — 中文日常交流与使用反馈
|
||||
|
||||
## 许可与声明
|
||||
|
||||
- **开源协议**:Reims-Go 本体采用 [MIT](./LICENSE) 协议;独立调用的便携运行时组件及其许可证见 [`NOTICE.md`](./NOTICE.md),每个运行时 Release 均附带对应源码包。
|
||||
- **关于 macOS**:Reims-Go 不包含、不分发任何 Apple 系统文件,安装包由本机直连 Apple 服务器获取。**macOS 软件许可协议仅允许在 Apple 硬件上虚拟化**,在非 Apple 硬件上使用请自行评估合规责任。本项目与 Apple Inc. 无关,macOS 为 Apple Inc. 注册商标。
|
||||
- Reims-Go 采用 [Apache-2.0](./LICENSE) 协议。运行时里的 QEMU 等组件作为独立程序随附,许可证见 [`NOTICE.md`](./NOTICE.md),每个运行时 Release 都附带对应源码。
|
||||
- Reims-Go 不包含、不分发任何 Apple 系统文件,安装包由本机直接从 Apple 下载。**macOS 软件许可协议只允许在 Apple 硬件上虚拟化**,在其他硬件上使用请自行评估。本项目与 Apple Inc. 无关,macOS 是 Apple Inc. 的注册商标。
|
||||
|
||||
## 友情链接
|
||||
|
||||
- [LINUX DO](https://linux.do/) — 新的理想型社区
|
||||
|
||||
<br />
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://www.star-history.com/#Nwflower/Reims-Go&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Nwflower/Reims-Go&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Nwflower/Reims-Go&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Nwflower/Reims-Go&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
@@ -1,985 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/cli"
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/tray"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
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"`
|
||||
Optimizations []host.Optimization `json:"optimizations"`
|
||||
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"`
|
||||
AppVersion string `json:"app_version"`
|
||||
}
|
||||
|
||||
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
|
||||
guestTools *guesttools.Server
|
||||
imeBridge *host.IMEBridge
|
||||
trayMgr *tray.Manager
|
||||
allowQuit bool
|
||||
lastVMs []reims.VMListItem
|
||||
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
|
||||
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
|
||||
diskPaths map[string]cachedDiskPath
|
||||
procSamples map[string]host.ProcessSample
|
||||
recentLogs []string
|
||||
needsSetup bool
|
||||
launch cli.WindowArgs // flags this window was started with (window_launch.go)
|
||||
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
|
||||
}
|
||||
|
||||
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),
|
||||
pollWake: make(chan struct{}, 1),
|
||||
diskPaths: make(map[string]cachedDiskPath),
|
||||
procSamples: make(map[string]host.ProcessSample),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) startup(ctx context.Context) {
|
||||
a.ctx = ctx
|
||||
pollCtx, cancel := context.WithCancel(ctx)
|
||||
a.stopPoll = cancel
|
||||
a.startTray()
|
||||
a.startIMEBridge()
|
||||
go a.registerExistingGuestTools(pollCtx)
|
||||
go a.pollVMs(pollCtx)
|
||||
a.afterStartup()
|
||||
}
|
||||
|
||||
func (a *App) startIMEBridge() {
|
||||
bridge, err := host.StartIMEBridge(func(target host.IMETarget, text string) {
|
||||
go a.injectRemoteText(target.VMName, target.VMDir, text)
|
||||
})
|
||||
if err != nil {
|
||||
a.emitLog("app", "Remote IME hook unavailable: "+err.Error())
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.imeBridge = bridge
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *App) beforeClose(ctx context.Context) bool {
|
||||
a.mu.Lock()
|
||||
allow := a.allowQuit
|
||||
toTray := a.cfg.ShouldMinimizeToTray()
|
||||
hasTray := a.trayMgr != nil
|
||||
a.mu.Unlock()
|
||||
if !allow && toTray && hasTray {
|
||||
wailsRuntime.WindowHide(ctx)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *App) shutdown(ctx context.Context) {
|
||||
if a.stopPoll != nil {
|
||||
a.stopPoll()
|
||||
}
|
||||
tasks.cancelAll()
|
||||
stopAllVMMonitors()
|
||||
a.mu.Lock()
|
||||
for name, entry := range a.rebootWatchers {
|
||||
entry.cancel()
|
||||
delete(a.rebootWatchers, name)
|
||||
}
|
||||
gt := a.guestTools
|
||||
ib := a.imeBridge
|
||||
tm := a.trayMgr
|
||||
a.imeBridge = nil
|
||||
a.trayMgr = nil
|
||||
a.mu.Unlock()
|
||||
if ib != nil {
|
||||
ib.Close()
|
||||
}
|
||||
if tm != nil {
|
||||
tm.Close()
|
||||
}
|
||||
if gt != nil {
|
||||
shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
_ = gt.Close(shutCtx)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// pollVMs refreshes the VM list every pollBusy while a VM is starting or
|
||||
// stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`.
|
||||
// Start, stop and delete call wakePoll so their result shows up at once.
|
||||
const (
|
||||
pollBusy = 2 * time.Second
|
||||
pollSteady = 5 * time.Second
|
||||
// polledMaxAge is how old lastVMs may be for polledVMs to reuse it. It sits
|
||||
// above pollSteady so a poll that runs a little late still counts.
|
||||
polledMaxAge = pollSteady + 3*time.Second
|
||||
)
|
||||
|
||||
func (a *App) pollVMs(ctx context.Context) {
|
||||
timer := time.NewTimer(pollBusy)
|
||||
defer timer.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 <-timer.C:
|
||||
case <-a.pollWake:
|
||||
}
|
||||
a.mu.Lock()
|
||||
next := pollSteady
|
||||
if len(a.transitions) > 0 {
|
||||
next = pollBusy
|
||||
}
|
||||
a.mu.Unlock()
|
||||
timer.Reset(next)
|
||||
vms, err := a.listVMsInternal(ctx)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
type pinCandidate struct {
|
||||
name string
|
||||
pid int
|
||||
}
|
||||
var toPin []pinCandidate
|
||||
a.mu.Lock()
|
||||
loc := a.cfg.Locale
|
||||
autoPin := a.cfg.AutoPinPCores
|
||||
a.lastVMs = append([]reims.VMListItem(nil), vms...)
|
||||
a.lastVMsAt = time.Now()
|
||||
tm := a.trayMgr
|
||||
runningCount := 0
|
||||
var b strings.Builder
|
||||
var imeTargets []host.IMETarget
|
||||
for _, vm := range vms {
|
||||
if vm.State == "running" {
|
||||
runningCount++
|
||||
if vm.PID != nil && *vm.PID > 0 {
|
||||
imeTargets = append(imeTargets, host.IMETarget{
|
||||
VMName: vm.Name,
|
||||
VMDir: vm.Dir,
|
||||
PID: uint32(*vm.PID),
|
||||
})
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
if autoPin && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
|
||||
if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 {
|
||||
pinnedPIDs[*vm.PID] = true
|
||||
toPin = append(toPin, pinCandidate{name: vm.Name, pid: *vm.PID})
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&b, "%s:%s:%s;", vm.Name, vm.State, a.transitions[vm.Name])
|
||||
}
|
||||
sig := b.String()
|
||||
ib := a.imeBridge
|
||||
a.mu.Unlock()
|
||||
if ib != nil {
|
||||
ib.SetTargets(imeTargets)
|
||||
}
|
||||
if tm != nil {
|
||||
if runningCount > 0 {
|
||||
if loc == i18n.ZhCN {
|
||||
tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d 台虚拟机运行中", runningCount))
|
||||
} else {
|
||||
tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d VM(s) running", runningCount))
|
||||
}
|
||||
} else {
|
||||
tm.UpdateTooltip("Reims-Go")
|
||||
}
|
||||
}
|
||||
for _, cand := range toPin {
|
||||
vmCPUs := 0
|
||||
if c, cerr := a.client(); cerr == nil {
|
||||
if det, derr := c.Show(ctx, cand.name); derr == nil {
|
||||
vmCPUs = det.CPUs
|
||||
}
|
||||
}
|
||||
a.emitLog(cand.name, vmstart.PinQEMU(loc, cachedHost, cand.pid, vmCPUs))
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
// polledVMs returns the list pollVMs saw last if it is at most polledMaxAge
|
||||
// old, so per-VM samplers (stats, thumbnails, heartbeats) don't each spawn
|
||||
// their own `reims-ctl list`. A stale or missing poll falls back to one.
|
||||
func (a *App) polledVMs(ctx context.Context) ([]reims.VMListItem, error) {
|
||||
a.mu.Lock()
|
||||
if !a.lastVMsAt.IsZero() && time.Since(a.lastVMsAt) <= polledMaxAge {
|
||||
vms := append([]reims.VMListItem(nil), a.lastVMs...)
|
||||
a.mu.Unlock()
|
||||
return vms, nil
|
||||
}
|
||||
a.mu.Unlock()
|
||||
return a.listVMsInternal(ctx)
|
||||
}
|
||||
|
||||
// polledVM looks name up in polledVMs.
|
||||
func (a *App) polledVM(name string) (reims.VMListItem, bool) {
|
||||
vms, err := a.polledVMs(context.Background())
|
||||
if err != nil {
|
||||
return reims.VMListItem{}, false
|
||||
}
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name {
|
||||
return vm, true
|
||||
}
|
||||
}
|
||||
return reims.VMListItem{}, false
|
||||
}
|
||||
|
||||
// wakePoll marks the polled list stale and runs pollVMs now. Call it after
|
||||
// anything that changes which VMs exist or run.
|
||||
func (a *App) wakePoll() {
|
||||
a.mu.Lock()
|
||||
a.lastVMsAt = time.Time{}
|
||||
a.mu.Unlock()
|
||||
select {
|
||||
case a.pollWake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// cachedDiskPath is one VM's disk path from `reims-ctl show`, kept for
|
||||
// diskPathTTL so GetVMStats doesn't run `show` every few seconds.
|
||||
type cachedDiskPath struct {
|
||||
path string
|
||||
at time.Time
|
||||
}
|
||||
|
||||
const diskPathTTL = time.Minute
|
||||
|
||||
// vmDiskPath resolves name's disk image path, reusing a recent answer. The
|
||||
// path only changes through `reims-ctl set`, so at worst the disk-usage
|
||||
// figure follows such a change a minute late.
|
||||
func (a *App) vmDiskPath(ctx context.Context, c *reims.Client, name string) string {
|
||||
a.mu.Lock()
|
||||
cur, ok := a.diskPaths[name]
|
||||
a.mu.Unlock()
|
||||
if ok && time.Since(cur.at) < diskPathTTL {
|
||||
return cur.path
|
||||
}
|
||||
d, err := c.Show(ctx, name)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
path := resolveVMDiskPath(d)
|
||||
a.mu.Lock()
|
||||
a.diskPaths[name] = cachedDiskPath{path: path, at: time.Now()}
|
||||
a.mu.Unlock()
|
||||
return path
|
||||
}
|
||||
|
||||
func (a *App) emitLog(source, line string) {
|
||||
redacted := reims.RedactLogLine(line)
|
||||
ts := time.Now().Format("15:04:05")
|
||||
a.mu.Lock()
|
||||
a.recentLogs = append(a.recentLogs, fmt.Sprintf("%s [%s] %s", ts, source, redacted))
|
||||
if len(a.recentLogs) > 1000 {
|
||||
a.recentLogs = a.recentLogs[len(a.recentLogs)-1000:]
|
||||
}
|
||||
for _, c := range a.logCaptures[source] {
|
||||
c.add(redacted)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if a.ctx == nil {
|
||||
return
|
||||
}
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:log", map[string]string{
|
||||
"ts": ts,
|
||||
"source": source,
|
||||
"line": redacted,
|
||||
})
|
||||
}
|
||||
|
||||
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())
|
||||
|
||||
var activePatches []string
|
||||
if active != nil {
|
||||
for _, p := range active.Manifest.Patches {
|
||||
activePatches = append(activePatches, p.Name)
|
||||
}
|
||||
}
|
||||
opts := host.EvaluateOptimizations(rep, activePatches)
|
||||
|
||||
return AppState{
|
||||
Config: &cfgCopy,
|
||||
Host: rep,
|
||||
Optimizations: opts,
|
||||
Runtimes: runtimes,
|
||||
ActiveRuntime: active,
|
||||
VMs: vms,
|
||||
Transitions: trCopy,
|
||||
PendingChanges: pcCopy,
|
||||
NeedsSetup: needsSetup,
|
||||
AppVersion: version.Version,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
d, err := c.Show(context.Background(), name)
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
d.RecoveryMode = isRecoveryModeActive(d)
|
||||
a.populateGuestToolsDetail(&d)
|
||||
a.populateGuestLangDetail(&d)
|
||||
return d, nil
|
||||
}
|
||||
|
||||
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) SetMinimizeToTray(enabled bool) error {
|
||||
a.mu.Lock()
|
||||
v := enabled
|
||||
a.cfg.MinimizeToTray = &v
|
||||
err := config.Save("", a.cfg)
|
||||
a.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
// ShowMainWindow restores and focuses the Wails window from the system tray.
|
||||
func (a *App) ShowMainWindow() {
|
||||
if a.ctx == nil {
|
||||
return
|
||||
}
|
||||
wailsRuntime.WindowUnminimise(a.ctx)
|
||||
wailsRuntime.WindowShow(a.ctx)
|
||||
}
|
||||
|
||||
// RequestClose handles the custom titlebar close button: hides to system tray
|
||||
// when MinimizeToTray is enabled, or quits the application otherwise.
|
||||
func (a *App) RequestClose() {
|
||||
if a.ctx == nil {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
toTray := a.cfg.ShouldMinimizeToTray()
|
||||
hasTray := a.trayMgr != nil
|
||||
a.mu.Unlock()
|
||||
if toTray && hasTray {
|
||||
wailsRuntime.WindowHide(a.ctx)
|
||||
return
|
||||
}
|
||||
a.QuitApp()
|
||||
}
|
||||
|
||||
// QuitApp exits Reims-Go completely (bypassing minimize-to-tray).
|
||||
func (a *App) QuitApp() {
|
||||
a.mu.Lock()
|
||||
a.allowQuit = true
|
||||
a.mu.Unlock()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.Quit(a.ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) startTray() {
|
||||
mgr, err := tray.Start(trayIconPNG, "Reims-Go", tray.Callbacks{
|
||||
OnShow: func() {
|
||||
a.ShowMainWindow()
|
||||
},
|
||||
OnStartVM: func(name string) {
|
||||
_ = a.StartVM(name)
|
||||
},
|
||||
OnStopVM: func(name string) {
|
||||
_ = a.StopVM(name, false)
|
||||
},
|
||||
OnOpenSharedDir: func(name string) {
|
||||
_ = a.OpenSharedFolder(name)
|
||||
},
|
||||
OnQuit: func() {
|
||||
a.QuitApp()
|
||||
},
|
||||
GetSnapshot: func() tray.Snapshot {
|
||||
a.mu.Lock()
|
||||
loc := a.cfg.Locale
|
||||
cached := append([]reims.VMListItem(nil), a.lastVMs...)
|
||||
a.mu.Unlock()
|
||||
if len(cached) == 0 {
|
||||
if vms, err := a.listVMsInternal(context.Background()); err == nil {
|
||||
cached = vms
|
||||
}
|
||||
}
|
||||
items := make([]tray.VMItem, 0, len(cached))
|
||||
for _, vm := range cached {
|
||||
items = append(items, tray.VMItem{
|
||||
Name: vm.Name,
|
||||
Running: vm.State == "running",
|
||||
})
|
||||
}
|
||||
return tray.Snapshot{
|
||||
LocaleZh: loc == i18n.ZhCN,
|
||||
VMs: items,
|
||||
}
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
a.emitLog("app", "Warning: system tray unavailable: "+err.Error())
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.trayMgr = mgr
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
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()
|
||||
issues := reims.ValidateCreate(opts, host.Inspect(root))
|
||||
// reims-ctl refuses a name already registered; say so before the create runs.
|
||||
if vms, err := a.listVMsInternal(context.Background()); err == nil {
|
||||
for _, vm := range vms {
|
||||
if strings.EqualFold(vm.Name, strings.TrimSpace(opts.Name)) {
|
||||
issues = append(issues, reims.ValidationIssue{Field: "name", Code: "name_taken", Message: "A VM named " + vm.Name + " already exists"})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
func (a *App) PreviewCreate(opts reims.CreateOpts) (string, error) {
|
||||
return reims.PreviewCreateCommand(opts)
|
||||
}
|
||||
|
||||
func (a *App) CreateVM(opts reims.CreateOpts) error {
|
||||
return a.createVMFlow(opts)
|
||||
}
|
||||
|
||||
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 := vmstart.LineWriter(func(line string) { a.emitLog(opts.Name, line) })
|
||||
if reims.HasCtlSetChanges(opts) {
|
||||
if err := c.Set(context.Background(), opts, w, w); err != nil {
|
||||
a.emitLog(opts.Name, "Set error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
}
|
||||
guestLangChanged := strings.TrimSpace(opts.GuestLang) != "" && strings.TrimSpace(opts.GuestLang) != cur.GuestLang
|
||||
if guestLangChanged {
|
||||
prep, err := a.prep(opts.Name)
|
||||
if err == nil {
|
||||
err = prep.ApplyGuestLang(context.Background(), cur.Directory, opts.GuestLang, cur.State == "running")
|
||||
}
|
||||
if err != nil {
|
||||
a.emitLog(opts.Name, "Guest language error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
} else if cur.State != "running" && opts.Graphics != "" && opts.Graphics != cur.Graphics {
|
||||
// Switching graphics rebuilds opencore.qcow2; replay any saved prev-lang:kbd.
|
||||
if prep, err := a.prep(opts.Name); err == nil {
|
||||
prep.ReplayGuestLang(context.Background(), cur.Directory)
|
||||
}
|
||||
}
|
||||
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 opts.Displays > 0 && opts.Displays != cur.Displays {
|
||||
diffs = append(diffs, PendingChange{Field: "displays", From: fmt.Sprintf("%d", cur.Displays), To: fmt.Sprintf("%d", opts.Displays)})
|
||||
}
|
||||
if opts.Borderless != nil && *opts.Borderless != cur.Borderless {
|
||||
diffs = append(diffs, PendingChange{Field: "borderless", From: fmt.Sprintf("%v", cur.Borderless), To: fmt.Sprintf("%v", *opts.Borderless)})
|
||||
}
|
||||
if opts.Audio != nil && *opts.Audio != cur.Audio {
|
||||
diffs = append(diffs, PendingChange{Field: "audio", From: fmt.Sprintf("%v", cur.Audio), To: fmt.Sprintf("%v", *opts.Audio)})
|
||||
}
|
||||
if opts.AudioBackend != "" && opts.AudioBackend != cur.AudioBackend {
|
||||
from := cur.AudioBackend
|
||||
if from == "" {
|
||||
from = "auto"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "audio_backend", From: from, To: opts.AudioBackend})
|
||||
}
|
||||
if guestLangChanged {
|
||||
from := cur.GuestLang
|
||||
if from == "" {
|
||||
from = "en-US:0"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "guest_lang", From: from, To: strings.TrimSpace(opts.GuestLang)})
|
||||
}
|
||||
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) 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()
|
||||
}()
|
||||
|
||||
reason, err := qmp.WatchShutdownReason(watchCtx, qmpAddr)
|
||||
if err != nil {
|
||||
if watchCtx.Err() == nil {
|
||||
a.emitLog(name, "Win10 WHPX cold-reboot monitor disconnected: "+err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
if reason != "guest-reset" {
|
||||
if reason != "" {
|
||||
a.emitLog(name, "Win10 WHPX cold-reboot: VM exited ("+reason+"), not restarting")
|
||||
}
|
||||
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 (guest-reset), 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 {
|
||||
prep, err := a.prep(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c := prep.Client
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
tmpDir := a.cfg.TempDir()
|
||||
a.mu.Unlock()
|
||||
rep := host.Inspect(root)
|
||||
curDetail, _ := c.Show(context.Background(), name)
|
||||
if err := prep.CheckMemory(curDetail.Memory, rep); err != nil {
|
||||
a.emitLog(name, "Start refused: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
|
||||
a.syncGuestTools(c, name, &curDetail)
|
||||
if env := a.inputBridgeEnv(name, curDetail.Directory); len(env) > 0 {
|
||||
c.Env = append(c.Env, env...)
|
||||
}
|
||||
prep.Prepare(context.Background(), name, rep, &curDetail)
|
||||
var qmpAddr string
|
||||
if rep.NeedsColdRebootWorkaround {
|
||||
sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name)
|
||||
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
|
||||
_ = os.Remove(sockPath)
|
||||
merged := qmp.MergeWin10RebootUnixArgs(curDetail.ExtraArgs, sockPath)
|
||||
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 = "unix:" + sockPath
|
||||
curDetail.ExtraArgs = merged
|
||||
}
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
a.transitions[name] = "starting"
|
||||
delete(a.pendingChanges, name)
|
||||
a.mu.Unlock()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
|
||||
startAt := time.Now()
|
||||
a.emitStartSummary(name, curDetail, rep, qmpAddr)
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
a.emitLog(name, "Starting "+name+"...")
|
||||
if err := c.StartWithCompat(context.Background(), name, w, w, func(msg string) {
|
||||
a.emitLog(name, msg)
|
||||
}); 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)
|
||||
}
|
||||
a.startVMMonitor(name, curDetail, startAt)
|
||||
a.wakePoll()
|
||||
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)
|
||||
stopVMMonitor(name)
|
||||
a.mu.Lock()
|
||||
a.transitions[name] = "stopping"
|
||||
a.mu.Unlock()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
|
||||
w := vmstart.LineWriter(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()
|
||||
a.wakePoll()
|
||||
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 := vmstart.LineWriter(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)
|
||||
stopVMMonitor(name)
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
a.emitLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
|
||||
if err := c.Delete(context.Background(), name, keepFiles, w, w); err != nil {
|
||||
a.emitLog(name, "Delete error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, name)
|
||||
delete(a.transitions, name)
|
||||
delete(a.diskPaths, name)
|
||||
a.mu.Unlock()
|
||||
a.wakePoll()
|
||||
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,50 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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 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 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 539 141" width="539" height="141" role="img" aria-label="Reims-Go"><g transform="translate(4 107)"><defs><linearGradient id="wm" gradientUnits="userSpaceOnUse" x1="376" y1="0" x2="531" y2="0"><stop offset="0" stop-color="#3b8cff"/><stop offset="0.5" stop-color="#6d5dfc"/><stop offset="1" stop-color="#ff7a9a"/></linearGradient><linearGradient id="wmb" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ff9f0a"/></linearGradient></defs><g fill="none" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"><path d="M7.5 -7.5V-36A24 28.5 0 0 1 31.5 -64.5" stroke="#f4f5fa"/><path d="M50.5 -36H107.5A28.5 28.5 0 1 0 100.18 -16.93" stroke="#f4f5fa"/><path d="M133.5 -64.5V-7.5" stroke="#f4f5fa"/><circle cx="133.5" cy="-94" r="9" fill="#ff7a9a"/><path d="M159.5 -7.5V-36A22 28.5 0 0 1 203.5 -36V-7.5M203.5 -36A22 28.5 0 0 1 247.5 -36V-7.5" stroke="#f4f5fa"/><path d="M311.05 -59.02A21 14.25 0 0 0 273.5 -50.25A21 14.25 0 0 0 294.5 -36A21 14.25 0 0 1 315.5 -21.75A21 14.25 0 0 1 277.95 -12.98" stroke="#f4f5fa"/><path d="M340.5 -36H358.5" stroke="#5d6382"/><path d="M440.5 -36A28.5 28.5 0 1 1 440.5 -36.01" stroke="url(#wm)"/><path d="M440.5 -64.5V0A28.5 22.5 0 0 1 387.32 11.25" stroke="url(#wm)"/><path d="M523.5 -36A28.5 28.5 0 1 1 523.5 -36.01" stroke="url(#wm)"/></g></g></svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 539 141" width="539" height="141" role="img" aria-label="Reims-Go"><g transform="translate(4 107)"><defs><linearGradient id="wm" gradientUnits="userSpaceOnUse" x1="376" y1="0" x2="531" y2="0"><stop offset="0" stop-color="#3b8cff"/><stop offset="0.5" stop-color="#6d5dfc"/><stop offset="1" stop-color="#ff7a9a"/></linearGradient><linearGradient id="wmb" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ff9f0a"/></linearGradient></defs><g fill="none" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"><path d="M7.5 -7.5V-36A24 28.5 0 0 1 31.5 -64.5" stroke="#16182e"/><path d="M50.5 -36H107.5A28.5 28.5 0 1 0 100.18 -16.93" stroke="#16182e"/><path d="M133.5 -64.5V-7.5" stroke="#16182e"/><circle cx="133.5" cy="-94" r="9" fill="#ff7a9a"/><path d="M159.5 -7.5V-36A22 28.5 0 0 1 203.5 -36V-7.5M203.5 -36A22 28.5 0 0 1 247.5 -36V-7.5" stroke="#16182e"/><path d="M311.05 -59.02A21 14.25 0 0 0 273.5 -50.25A21 14.25 0 0 0 294.5 -36A21 14.25 0 0 1 315.5 -21.75A21 14.25 0 0 1 277.95 -12.98" stroke="#16182e"/><path d="M340.5 -36H358.5" stroke="#a3a8bf"/><path d="M440.5 -36A28.5 28.5 0 1 1 440.5 -36.01" stroke="url(#wm)"/><path d="M440.5 -64.5V0A28.5 22.5 0 0 1 387.32 11.25" stroke="url(#wm)"/><path d="M523.5 -36A28.5 28.5 0 1 1 523.5 -36.01" stroke="url(#wm)"/></g></g></svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
@@ -1,135 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// CloneVMCoW derives a new VM instantaneously from a stopped source VM using a
|
||||
// qcow2 copy-on-write overlay (`qemu-img create -f qcow2 -b <src> -F qcow2`)
|
||||
// so the source golden disk is never mutated while the clone gets its own fresh
|
||||
// OpenCore identity (SMBIOS/serial/MAC) via `reims-ctl create --disk --disk-mode in-place`.
|
||||
func (a *App) CloneVMCoW(sourceName, cloneName string) error {
|
||||
cloneName = strings.TrimSpace(cloneName)
|
||||
if cloneName == "" {
|
||||
return fmt.Errorf("clone VM name is required")
|
||||
}
|
||||
if strings.EqualFold(sourceName, cloneName) {
|
||||
return fmt.Errorf("clone name must differ from source VM")
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
src, err := a.GetVMDetail(sourceName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, sourceName, src) {
|
||||
return fmt.Errorf("stop %s before deriving a CoW clone so the backing disk is clean", sourceName)
|
||||
}
|
||||
if src.HasInstaller {
|
||||
return fmt.Errorf("exit recovery mode on %s before deriving a CoW clone", sourceName)
|
||||
}
|
||||
srcDisk := src.Disk
|
||||
if srcDisk != "" && !filepath.IsAbs(srcDisk) && src.Directory != "" {
|
||||
srcDisk = filepath.Join(src.Directory, srcDisk)
|
||||
}
|
||||
if srcDisk == "" {
|
||||
return fmt.Errorf("source VM %s has no disk path", sourceName)
|
||||
}
|
||||
if _, err := os.Stat(srcDisk); err != nil {
|
||||
return fmt.Errorf("source disk not found (%s): %w", srcDisk, err)
|
||||
}
|
||||
|
||||
// Validate clone name and check for name collisions.
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
nameCheck := reims.ValidateCreate(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep)
|
||||
for _, iss := range nameCheck {
|
||||
if iss.Field == "name" {
|
||||
return fmt.Errorf("%s", iss.Message)
|
||||
}
|
||||
}
|
||||
if existing, err := c.List(ctx); err == nil {
|
||||
for _, vm := range existing {
|
||||
if strings.EqualFold(vm.Name, cloneName) {
|
||||
return fmt.Errorf("VM %q already exists", cloneName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
overlayPath := filepath.Join(cfgCopy.ImagesDir(), fmt.Sprintf("cow-%s.qcow2", cloneName))
|
||||
if _, err := os.Stat(overlayPath); err == nil {
|
||||
return fmt.Errorf("CoW overlay file already exists: %s", overlayPath)
|
||||
}
|
||||
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(cloneName, line) })
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
a.emitLog(cloneName, fmt.Sprintf("Creating CoW overlay for %s backed by %s...", cloneName, filepath.Base(srcDisk)))
|
||||
if err := reims.CreateCoWOverlay(ctx, active.QemuImgPath(), env, srcDisk, overlayPath, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
audio := src.Audio
|
||||
network := src.Network
|
||||
logs := src.Logs
|
||||
capture := src.Capture
|
||||
createOpts := reims.CreateOpts{
|
||||
Name: cloneName,
|
||||
SourceMode: "disk",
|
||||
Disk: overlayPath,
|
||||
DiskMode: "in-place",
|
||||
DiskController: src.DiskController,
|
||||
CPUs: src.CPUs,
|
||||
Memory: src.Memory,
|
||||
Graphics: src.Graphics,
|
||||
GPU: src.GPU,
|
||||
Resolution: src.Resolution,
|
||||
Displays: src.Displays,
|
||||
Capture: &capture,
|
||||
Audio: &audio,
|
||||
Network: &network,
|
||||
Logs: &logs,
|
||||
Start: false,
|
||||
}
|
||||
if err := c.Create(ctx, createOpts, w, w); err != nil {
|
||||
_ = os.Remove(overlayPath)
|
||||
return err
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(createOpts); ok {
|
||||
if serr := c.Set(ctx, postSet, w, w); serr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone settings: %v", serr))
|
||||
}
|
||||
}
|
||||
if src.GuestLang != "" {
|
||||
if cloned, serr := c.Show(ctx, cloneName); serr == nil && cloned.Directory != "" {
|
||||
prep, lerr := a.prep(cloneName)
|
||||
if lerr == nil {
|
||||
lerr = prep.ApplyGuestLang(ctx, cloned.Directory, src.GuestLang, false)
|
||||
}
|
||||
if lerr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone language (%s): %v", src.GuestLang, lerr))
|
||||
}
|
||||
}
|
||||
}
|
||||
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,327 @@
|
||||
// Command i18ngen compiles and validates the canonical JSON message catalogs
|
||||
// under locales/{zh-CN,en-US}/*.json, enforcing:
|
||||
// - 100% key parity between zh-CN and en-US in every domain
|
||||
// - valid lightweight ICU AST syntax across every entry
|
||||
// - identical {var} placeholder sets between zh-CN, en-US, and optional $params
|
||||
//
|
||||
// Outputs:
|
||||
// - internal/i18n/catalog_gen.go
|
||||
// - frontend/src/i18n/keys.gen.ts
|
||||
// - frontend/src/i18n/domains/{core,vm,wizard,settings,plugins}.gen.ts
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
var (
|
||||
allDomains = []string{"core", "vm", "wizard", "settings", "plugins", "native", "macos-glossary"}
|
||||
goDomains = []string{"native", "macos-glossary", "core"}
|
||||
feEagerDomains = []string{"core", "vm"}
|
||||
feLazyDomains = []string{"wizard", "settings", "plugins"}
|
||||
)
|
||||
|
||||
type parsedEntry struct {
|
||||
Message string
|
||||
Params []string
|
||||
Comment string
|
||||
MaxLength int
|
||||
}
|
||||
|
||||
func main() {
|
||||
root := "."
|
||||
if _, err := os.Stat("locales/zh-CN/core.json"); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "i18ngen: must be run from repository root: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
zhByDomain := make(map[string]map[string]parsedEntry)
|
||||
enByDomain := make(map[string]map[string]parsedEntry)
|
||||
keyOwnerDomain := make(map[string]string)
|
||||
|
||||
var validationErrors []string
|
||||
|
||||
for _, dom := range allDomains {
|
||||
zhPath := filepath.Join(root, "locales", "zh-CN", dom+".json")
|
||||
enPath := filepath.Join(root, "locales", "en-US", dom+".json")
|
||||
|
||||
zhMap, err := readCatalogFile(zhPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "i18ngen: read %s: %v\n", zhPath, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
enMap, err := readCatalogFile(enPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "i18ngen: read %s: %v\n", enPath, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
for k := range zhMap {
|
||||
if prevDom, exists := keyOwnerDomain[k]; exists {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("duplicate key %q across domains %q and %q", k, prevDom, dom))
|
||||
}
|
||||
keyOwnerDomain[k] = dom
|
||||
if _, ok := enMap[k]; !ok {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] key %q exists in zh-CN but missing in en-US", dom, k))
|
||||
}
|
||||
}
|
||||
for k := range enMap {
|
||||
if _, ok := zhMap[k]; !ok {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] key %q exists in en-US but missing in zh-CN", dom, k))
|
||||
}
|
||||
}
|
||||
|
||||
keys := sortedKeys(zhMap)
|
||||
for _, k := range keys {
|
||||
ze, ok := zhMap[k]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ee, ok := enMap[k]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
_, zhVars, zErr := i18n.ParseICU(ze.Message)
|
||||
if zErr != nil {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] zh-CN %q invalid ICU syntax: %v", dom, k, zErr))
|
||||
continue
|
||||
}
|
||||
_, enVars, eErr := i18n.ParseICU(ee.Message)
|
||||
if eErr != nil {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] en-US %q invalid ICU syntax: %v", dom, k, eErr))
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(zhVars, enVars) {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] placeholder mismatch for %q: zh-CN=%v vs en-US=%v", dom, k, zhVars, enVars))
|
||||
}
|
||||
if len(ze.Params) > 0 {
|
||||
decl := append([]string(nil), ze.Params...)
|
||||
sort.Strings(decl)
|
||||
if !reflect.DeepEqual(decl, zhVars) {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] zh-CN $params %v does not match template vars %v for %q", dom, ze.Params, zhVars, k))
|
||||
}
|
||||
}
|
||||
if len(ee.Params) > 0 {
|
||||
decl := append([]string(nil), ee.Params...)
|
||||
sort.Strings(decl)
|
||||
if !reflect.DeepEqual(decl, enVars) {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] en-US $params %v does not match template vars %v for %q", dom, ee.Params, enVars, k))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
zhByDomain[dom] = zhMap
|
||||
enByDomain[dom] = enMap
|
||||
}
|
||||
|
||||
if len(validationErrors) > 0 {
|
||||
for _, msg := range validationErrors {
|
||||
fmt.Fprintln(os.Stderr, "ERROR:", msg)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if err := writeGoCatalog(root, zhByDomain, enByDomain); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "i18ngen: write Go catalog: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := writeFrontendCatalogs(root, zhByDomain, enByDomain); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "i18ngen: write frontend catalogs: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println("i18ngen: OK")
|
||||
}
|
||||
|
||||
func readCatalogFile(path string) (map[string]parsedEntry, error) {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var rawMap map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &rawMap); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]parsedEntry, len(rawMap))
|
||||
for k, v := range rawMap {
|
||||
if strings.HasPrefix(k, "$") {
|
||||
continue
|
||||
}
|
||||
var plain string
|
||||
if err := json.Unmarshal(v, &plain); err == nil {
|
||||
out[k] = parsedEntry{Message: plain}
|
||||
continue
|
||||
}
|
||||
var meta struct {
|
||||
Message string `json:"message"`
|
||||
Params []string `json:"$params"`
|
||||
Comment string `json:"$comment"`
|
||||
MaxLength int `json:"$maxLength"`
|
||||
}
|
||||
if err := json.Unmarshal(v, &meta); err != nil {
|
||||
return nil, fmt.Errorf("key %q: %w", k, err)
|
||||
}
|
||||
out[k] = parsedEntry{
|
||||
Message: meta.Message,
|
||||
Params: meta.Params,
|
||||
Comment: meta.Comment,
|
||||
MaxLength: meta.MaxLength,
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func sortedKeys[V any](m map[string]V) []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
func writeGoCatalog(root string, zhByDom, enByDom map[string]map[string]parsedEntry) error {
|
||||
zhMerged := make(map[string]string)
|
||||
enMerged := make(map[string]string)
|
||||
params := make(map[string][]string)
|
||||
|
||||
for _, dom := range goDomains {
|
||||
for k, e := range zhByDom[dom] {
|
||||
zhMerged[k] = e.Message
|
||||
if len(e.Params) > 0 {
|
||||
params[k] = e.Params
|
||||
} else if ee := enByDom[dom][k]; len(ee.Params) > 0 {
|
||||
params[k] = ee.Params
|
||||
} else {
|
||||
_, vars, _ := i18n.ParseICU(e.Message)
|
||||
if len(vars) > 0 {
|
||||
params[k] = vars
|
||||
}
|
||||
}
|
||||
}
|
||||
for k, e := range enByDom[dom] {
|
||||
enMerged[k] = e.Message
|
||||
}
|
||||
}
|
||||
|
||||
keys := sortedKeys(zhMerged)
|
||||
var b bytes.Buffer
|
||||
b.WriteString("// Code generated by cmd/i18ngen; DO NOT EDIT.\n\npackage i18n\n\n")
|
||||
b.WriteString("var catalog = map[Locale]map[string]string{\n")
|
||||
b.WriteString("\tZhCN: {\n")
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(&b, "\t\t%q: %q,\n", k, zhMerged[k])
|
||||
}
|
||||
b.WriteString("\t},\n\tEnUS: {\n")
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(&b, "\t\t%q: %q,\n", k, enMerged[k])
|
||||
}
|
||||
b.WriteString("\t},\n}\n\n")
|
||||
|
||||
paramKeys := sortedKeys(params)
|
||||
b.WriteString("var paramOrder = map[string][]string{\n")
|
||||
for _, k := range paramKeys {
|
||||
p := params[k]
|
||||
quoted := make([]string, len(p))
|
||||
for i, name := range p {
|
||||
quoted[i] = fmt.Sprintf("%q", name)
|
||||
}
|
||||
fmt.Fprintf(&b, "\t%q: {%s},\n", k, strings.Join(quoted, ", "))
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
|
||||
return os.WriteFile(filepath.Join(root, "internal/i18n/catalog_gen.go"), b.Bytes(), 0o644)
|
||||
}
|
||||
|
||||
func writeFrontendCatalogs(root string, zhByDom, enByDom map[string]map[string]parsedEntry) error {
|
||||
feDir := filepath.Join(root, "frontend/src/i18n")
|
||||
domDir := filepath.Join(feDir, "domains")
|
||||
if err := os.MkdirAll(domDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Merge macos-glossary into frontend core domain as well so UI components can use official glossary keys.
|
||||
feDomains := []string{"core", "vm", "wizard", "settings", "plugins"}
|
||||
var allFEKeys []string
|
||||
|
||||
for _, dom := range feDomains {
|
||||
zhMap := make(map[string]string)
|
||||
enMap := make(map[string]string)
|
||||
for k, v := range zhByDom[dom] {
|
||||
zhMap[k] = v.Message
|
||||
}
|
||||
for k, v := range enByDom[dom] {
|
||||
enMap[k] = v.Message
|
||||
}
|
||||
if dom == "core" {
|
||||
for k, v := range zhByDom["macos-glossary"] {
|
||||
zhMap[k] = v.Message
|
||||
}
|
||||
for k, v := range enByDom["macos-glossary"] {
|
||||
enMap[k] = v.Message
|
||||
}
|
||||
}
|
||||
|
||||
keys := sortedKeys(zhMap)
|
||||
allFEKeys = append(allFEKeys, keys...)
|
||||
|
||||
isLazy := false
|
||||
for _, ld := range feLazyDomains {
|
||||
if ld == dom {
|
||||
isLazy = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
var b bytes.Buffer
|
||||
b.WriteString("// Code generated by cmd/i18ngen; DO NOT EDIT.\n")
|
||||
if isLazy {
|
||||
b.WriteString("import { registerBuiltinDomain } from '../runtime'\n\n")
|
||||
} else {
|
||||
b.WriteString("\n")
|
||||
}
|
||||
fmt.Fprintf(&b, "export const %sZh: Record<string, string> = {\n", dom)
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(&b, " %s: %s,\n", tsQuoted(k), tsQuoted(zhMap[k]))
|
||||
}
|
||||
b.WriteString("}\n\n")
|
||||
fmt.Fprintf(&b, "export const %sEn: Record<string, string> = {\n", dom)
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(&b, " %s: %s,\n", tsQuoted(k), tsQuoted(enMap[k]))
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
if isLazy {
|
||||
fmt.Fprintf(&b, "\nregisterBuiltinDomain(%sZh, %sEn)\n", dom, dom)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(filepath.Join(domDir, dom+".gen.ts"), b.Bytes(), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
sort.Strings(allFEKeys)
|
||||
var kb bytes.Buffer
|
||||
kb.WriteString("// Code generated by cmd/i18ngen; DO NOT EDIT.\n\n")
|
||||
kb.WriteString("export type I18nKey =\n")
|
||||
for i, k := range allFEKeys {
|
||||
sep := ""
|
||||
if i == len(allFEKeys)-1 {
|
||||
sep = ";"
|
||||
}
|
||||
fmt.Fprintf(&kb, " | %s%s\n", tsQuoted(k), sep)
|
||||
}
|
||||
return os.WriteFile(filepath.Join(feDir, "keys.gen.ts"), kb.Bytes(), 0o644)
|
||||
}
|
||||
|
||||
func tsQuoted(s string) string {
|
||||
raw, _ := json.Marshal(s)
|
||||
return string(raw)
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
package main
|
||||
|
||||
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)
|
||||
}
|
||||
if guestLang != "" {
|
||||
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)
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
package main
|
||||
|
||||
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
|
||||
}
|
||||
@@ -1,147 +1,137 @@
|
||||
# 系统架构设计(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 同源、同一个 exe**:所有核心能力落在 `internal/` Go 包中。只发布一个 `reims-go.exe`:双击(无参数)打开 Wails 桌面界面,带子命令(`reims-go <subcommand>`)走命令行模式,供终端、脚本、CI 和 Agent 调用。2026-11-28 起不再单独发布 `reims-go-cli.exe`。
|
||||
4. **C 盘零污染**:所有运行时、下载缓存、VM 磁盘与快照严格留在用户选定的 `<DataRoot>` 下。
|
||||
5. **Day-1 中英双语(`zh-CN` / `en-US`)**:前端界面、装机引导文案(默认贴合简体中文 macOS 恢复与安装界面术语,如「磁盘工具 → 抹掉为 APFS → 重新安装 macOS」)与 CLI 输出从第一天即内置双语字典,自动跟随系统语言并支持在界面顶部实时切换(持久化到 `reims-go.json`)。
|
||||
6. **跨平台开发友好**:虽然宿主机运行目标优先面向 Windows x86-64(WHPX),但所有 Windows 原生 API(`WinHvPlatform.dll`、注册表 Vulkan ICD、`GetLogicalProcessorInformationEx`、进程亲和性)严格隔离在 `*_windows.go` 构建标签中,提供 `*_other.go` 桩实现,确保在中文 macOS 开发环境上也能直接进行前端开发、`go build` 与 `go test ./...`。
|
||||
## 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. **同构多语言与语言包扩展**:单一事实源分域 JSON 词表(`locales/`)在编译期同时生成 Go 与 TypeScript 类型安全字典,前后端共用轻量 ICU 消息语法与多跳区域回退链;主程序内置 `zh-CN` 与 `en-US`(默认 `auto` 跟随系统并支持热切换),其他语种通过 L1 声明式语言包插件按需扩展并覆盖桌面界面、Win32 原生浮层、系统托盘与命令行。
|
||||
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["命令行模式(同一个 exe)\n(reims-go doctor/runtime/installer/vm)"]
|
||||
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["driver/reims 与 App 编排\n(创建、启停、eject、日志流、\nCoW 派生、磁盘扩容与回收)"]
|
||||
Control["qmp/ guesttools/ opencore/\n(QMP 键入与截屏、冷重启监视、\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\` 下的多版本便携运行时包:
|
||||
- **来源**:本仓库的 GitHub Release(tag `runtime-<commit>`,预发布为 `alpha`(CI 每天自动构建),正式发布为 `stable`),支持断点续传,并对照 `SHA256SUMS.txt` 校验;也可以导入本地 `.tar.zst` 包。下载端点只有这一个,没有镜像,也不测速选路;
|
||||
- 校验 `manifest.json` 与 SHA256 后解压至 `<commit>.tmp` 再原子重命名,失败不破坏现有版本;
|
||||
- 统一构造子进程环境(`XDG_*`、`REIMS_CTL_QEMU`、`PATH`),彻底消除对用户全局环境变量与 C 盘的依赖;
|
||||
| 路径 | 职责 |
|
||||
| :--- | :--- |
|
||||
| `main.go`、`console_*.go` | 统一入口:无参数启动 Wails GUI,带子命令进入 `internal/cli`;处理 GUI 子系统下的父控制台句柄接管 |
|
||||
| `internal/app` | Wails 绑定与桌面编排(启停、安装、快照、CoW 派生、磁盘扩容/回收、SSH、脱敏排障包、任务状态、运行监视) |
|
||||
| `internal/vmstart` | 通用启动辅助:提交内存等待、启动后 CPU 绑核、亲和性配置与命令行日志 |
|
||||
| `internal/macos/startprep` | macOS 启动前准备:WHPX/内存检查、离线辅助盘、恢复模式引导、客体语言重放与兼容处理 |
|
||||
| `internal/cli` | 命令行子命令实现、单实例参数解析与向界面进程交接 `vm start` |
|
||||
| `internal/host` | 宿主机体检与硬件调优:WHPX 检测与 UAC 启用、提交内存预检、Vulkan ICD 扫描、三层大小核拓扑与实时绑核、显示器 HiDPI 推荐、音频与磁盘总线探测、窗口置前、IME 文本钩子 |
|
||||
| `internal/runtime` | 便携运行时拉取(GitHub Releases)、原子解压、多版本切换与子进程环境变量构造 |
|
||||
| `internal/fetch` | 发布附件下载:HTTP `Range` 续传与按发布页 `SHA256SUMS.txt` 强制校验,运行时安装与应用内更新共用 |
|
||||
| `internal/selfupdate` | 应用内更新:把已校验的新版 `reims-go.exe` 换入运行中程序的位置、重新拉起与残留清理 |
|
||||
| `internal/macos/installer` | 包装 `reims-util --json` 实现 macOS 离线安装包查询、宿主机直连下载、断点续传、互斥锁保护与缓存清理 |
|
||||
| `internal/macos/reims` | `reims-ctl` 与 `qemu-img` 受控子进程包装、输出解析、快照/派生/导入操作、日志与配置脱敏 |
|
||||
| `internal/macos/macosdriver` | 把 `internal/macos/reims` 适配为通用 `driver.Driver`(内置驱动 `builtin.driver.reims-macos`) |
|
||||
| `internal/macos/guest` | 内置可选插件 `builtin.guest.macos`:静态驱动声明、宿主体检、启动与兼容 Hook、安装引导服务,以及数据布局 v2 的状态与参数账本迁移 |
|
||||
| `internal/macos/installguide` | 虚拟机窗口旁的 macOS 安装与恢复分步引导(Win32 浮层) |
|
||||
| `internal/qmp` | QMP 客户端:键盘键入、截屏与 Win10 冷重启监视 |
|
||||
| `internal/guesttools` | 本地回环鉴权 HTTP/WebDAV 服务:图文双向剪贴板、共享目录、Windows 盘符只读共享、防休眠开关与 `REIMSTOOLS` 辅助盘生成 |
|
||||
| `internal/macos/opencore` | 改写 OpenCore 镜像中的 `prev-lang:kbd`,实现系统外预设 macOS 语言 |
|
||||
| `internal/netproxy` | 统一 HTTP Transport:优先环境变量代理,回退读取 Windows 系统代理配置 |
|
||||
| `locales/`、`cmd/i18ngen` | 单一事实源分域 JSON 词表(含译者上下文 `$comment` 与 Apple macOS 官方多语种词汇表)及编译期前后端字典代码生成器 |
|
||||
| `internal/config`、`internal/i18n` | 应用配置持久化(`reims-go.json`)、轻量 ICU 格式化引擎、多跳语言回退链与带稳定排障码的结构化错误(`CodedError`) |
|
||||
| `internal/thumb`、`internal/tray`、`internal/version` | 4K 截屏行级缩放预览、Windows 系统托盘常驻、版本信息与新版本检查 |
|
||||
| `frontend/src` | 桌面界面:`components/`(页面与对话框)、`macos/`(macOS 专属页面与组件)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
|
||||
| `scripts/` | 便携运行时打包、二进制裁剪与符号分离、MSYS2 源码归档、`alpha` 准入与冒烟脚本,以及 `scripts/debug/` 本地调试目录管理与卫生校验脚本 |
|
||||
|
||||
### 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 系统包由 `reims-util` 从 Apple 软件更新目录拉取,并校验 chunklist,不接第三方镜像。`reims-go` 不做路由选择,`reims-util` 使用进程环境里的代理变量(2026-11-28 实测,国内直连 Apple 边缘节点稳定在 11.2 MiB/s)。
|
||||
3. **宿主机直连下载 + 结构化进度条**:调用 `reims-util.exe offline-installer <version> -o <DataRoot>\data\reims-ctl\installers --json`(或在建机时走 `reims-ctl create --macos <version> --offline --network false` 共享同一缓存目录)。`reims-util --json` 原生按行输出 JSON 进度事件,Go 后端实时解析并通过 Wails `EventsEmit` 推送进度百分比、已下载字节、速率与断流重试状态,无需脆弱正则匹配。
|
||||
4. **暂停 / 断点续传与空间预警**:`reims-util` 原生支持中断后重跑同命令自动断点续传;GUI 提供「暂停/取消」与「继续下载」按钮。`reims-util` 一开始就会创建与完整镜像同样大小的 `.part` 文件,所以下载前先检查剩余空间是否够安装包大小的 1.1 倍。
|
||||
5. **缓存复用与可视化清理**:已下载的离线镜像常驻 `<DataRoot>\data\reims-ctl\installers\`,GUI 包装 `reims-ctl downloads` 与 `reims-ctl downloads delete <NAME>` 展示体积并支持一键清理;后续新建 VM 直接通过 `--installer <path>` 复用本地镜像,零重复下载。
|
||||
6. **离线装机 3 步引导卡**:使用离线包创建 VM 时默认开启 `--network false`(遵从 `reims-ctl create --help` 建议,阻止安装器联网拉更新),并在 GUI 突出提示:① 磁盘工具抹掉最大 `QEMU HARDDISK Media` 为 APFS → ② 打开终端执行 `sh /Volumes/Installer/install-macos.sh` → ③ 装完点击「弹出安装盘并恢复网络」。
|
||||
---
|
||||
|
||||
### 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 通道**:上游 `reims-ctl` 给每台 VM 开一个 `qmp.sock`(Windows 上是 Winsock AF_UNIX,`crates/reims-ctl/src/qmp.rs:1-8`、`vm.rs:1000-1027`)。QEMU 的一个 `-qmp` 同一时间只接受一个客户端,第二个连接会一直等到超时(同上 `qmp.rs` 注释,引自 QEMU `chardev/char-socket.c`)。
|
||||
- 键入(`qmp.TypeIntoVM`)和截屏缩略图(`qmp.Screendump`)都是短连接,直接连 `qmp.sock`,并且按 VM 串行(`type_flow.go` 的 `typing`、`thumbnail_flow.go` 的 `thumbLocks`);键入期间不截屏。它们连着的时候,`reims-ctl stop` 要等它们断开,实际延迟**待验证**。
|
||||
- Win10 冷重启监视需要长连接,所以通过 `reims-ctl set --extra-args` 另开一个 AF_UNIX monitor(`qmp.RebootSocketPath`),不占用 `qmp.sock`。不用 TCP,是为了不让客体经 SLIRP 的 `10.0.2.2` 访问到这个 monitor。
|
||||
- **配置写入只用 `set`**:`reims-ctl set` 的修改在**下次启动**时生效(`cli.rs:73`);改图形会在 VM 停止时重建 OpenCore 镜像(`cli.rs:242`)。可改字段见 `cli.rs:551-616`,外壳如何呈现见 [`shell-design.md`](shell-design.md)。
|
||||
## 4. 关键机制与安全边界
|
||||
|
||||
### 3.5 启动编排:`internal/vmstart` 与 GUI 编排层
|
||||
- `internal/vmstart` 是 GUI 和 CLI 共用的启动步骤:提交内存预检、离线辅助盘、恢复模式引导菜单、客体语言重放、WHPX 嵌套虚拟化兼容,以及启动后的 P 核绑定。GUI 的 `StartVM`(`app.go`)调用它;CLI 的 `vm start`(`internal/cli/start.go`)通常把启动交给界面进程,只在指定了 `--data-root` 时自己调用它。
|
||||
- 只有界面进程做的两步:Guest Tools 桥接(`guesttools_flow.go`)和 Win10 冷重启监视(`app.go`)。这两步都需要启动后仍在运行的进程,而命令执行完就退出,所以 `vm start` 会把启动交给界面进程:
|
||||
- 界面已在运行:按 Wails 单实例协议(`options.SingleInstanceLock`,WM_COPYDATA)把 `--start-vm=<名称>` 发给它,不弹窗;
|
||||
- 界面没在运行:以 `--background` 拉起一个只在托盘里运行的界面进程(`StartHidden`)。拉起时与调用方的控制台和句柄分离,Agent 读的管道会随命令结束而关闭;
|
||||
- 两种情况都由界面调用 `StartVM`,再把结果写到 `<DataRoot>\tmp\cli-start-*.json`(只接受这个目录下的这类文件名),命令读到后带退出码返回。
|
||||
- 指定了 `--data-root` 的 `vm start` 仍在命令进程里启动,没有剪贴板和共享目录,Win10 上客体重启后不会自动拉起。
|
||||
- 单实例:同一用户只运行一个界面进程。再次双击会把已有窗口调到前台。`wails dev` 构建用另一个锁名(`internal/cli/instance_id_dev.go`),不会和已安装的 Reims-Go 互相抢。
|
||||
- 命令行模式与 Windows 子系统:`reims-go.exe` 是 GUI 子系统程序。命令行模式会保留调用方传入的句柄(管道、文件),缺失的才用 `AttachConsole` 接回父进程控制台(`console_windows.go`)。所以 Agent、脚本、管道调用都能正常拿到输出和退出码;在交互式 PowerShell / cmd 里,提示符会先返回,要等命令结束需加 `| Out-Host`。
|
||||
- GUI 的其余编排仍在根目录的 `App`(`app.go`)和各个 `*_flow.go` 里:CoW 派生(`clone_flow.go`)、磁盘扩容与回收(`disk_flow.go`)、运行监视与里程碑日志(`vm_monitor.go`)。
|
||||
- **CoW 派生**:先 `qemu-img create -f qcow2 -F qcow2 -b <golden> <overlay>`,再 `reims-ctl create --disk <overlay> --disk-mode in-place`,原盘不改。真机上从派生盘启动**待验证**。
|
||||
- **SSH**:只展示 `reims-ctl` 的 `--ssh-port` 转发端口,没有命令执行通道。
|
||||
### 4.1 启动编排与单实例交接
|
||||
- `internal/lifecycle` 统一 GUI、CLI 与窗口交接的 VM 列表、详情、设置、启动、停止、重启、删除、介质动作和日志读取:按 `VMRef` 解析所属驱动,先收集第三方 Hook,否决时不调用驱动,成功后再发事件。macOS 的启动前检查、参数账本与磁盘准备由 `internal/macos/macosdriver` 自己完成,准备失败即中止;`internal/vmstart` 保留共享检查与旧回退。只有常驻进程才能维持的能力(Guest Tools 桥接、Win10 冷重启监视)由界面进程托管。
|
||||
- CLI 执行 `vm start` 时,默认交由桌面进程启动:界面已在运行时通过 Wails 单实例锁(`WM_COPYDATA`)发消息不弹窗拉起;未运行时以 `--background` 启动隐藏到托盘的后台界面进程,结果经 `<DataRoot>\tmp\cli-start-*.json` 回传并带退出码返回。交接同时携带 `--start-driver=`,裸名称不再作为跨驱动的完整身份。
|
||||
- 仅在 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/
|
||||
├── main.go # 唯一入口:无参数启动 Wails 界面,带子命令走 internal/cli
|
||||
├── window_launch.go # 界面处理 --background / --start-vm 与第二次启动
|
||||
├── internal/
|
||||
│ ├── cli/ # 命令行模式:子命令、把 vm start 交给界面进程
|
||||
│ ├── config/ # reims-go.json(含 locale: zh-CN|en-US、DataRoot、P-Core 开关)
|
||||
│ ├── i18n/ # Go 端中英双语消息字典与结构化错误码
|
||||
│ ├── host/ # WHPX、提交内存预检、Vulkan ICD、P/E 核拓扑、进程亲和性(*_windows.go + *_other.go)
|
||||
│ ├── runtime/ # 便携运行时下载/导入、校验、解压、环境构造
|
||||
│ ├── installer/ # reims-util --json 离线安装包下载、断点续传、缓存管理
|
||||
│ ├── driver/
|
||||
│ │ └── reims/ # reims-ctl 子进程包装与 JSON/日志解析
|
||||
│ ├── qmp/ # QMP 客户端:键入、截屏、Win10 冷重启监视
|
||||
│ ├── vmstart/ # GUI 与 CLI 共用的启动前检查、准备与绑核
|
||||
│ ├── guesttools/ # 宿客剪贴板与 WebDAV 共享目录、REIMSTOOLS 辅助盘
|
||||
│ ├── opencore/ # 改写 OpenCore 镜像里的 prev-lang:kbd
|
||||
│ ├── thumb/ # 把截屏缩小成 JPEG
|
||||
│ ├── tray/ # 系统托盘
|
||||
│ └── version/ # 版本号与更新检查
|
||||
├── *.go # GUI 的 App 与各 *_flow.go 编排(package main)
|
||||
├── frontend/ # Wails 前端(轻量 React + Vite + TypeScript + zh-CN/en-US i18n)
|
||||
├── patches/ # 上游临时补丁队列(合入即退役)
|
||||
├── scripts/
|
||||
│ ├── pack-runtime.ps1 # 从本地构建打包便携运行时(tar.zst + manifest)
|
||||
│ ├── pack-msys2-sources.ps1 # 打包对应的 MSYS2 copyleft 源码
|
||||
│ └── smoke-runtime.ps1 # 生成 alpha → stable 冒烟报告
|
||||
└── docs/
|
||||
```
|
||||
### 4.3 Guest Tools 与宿客安全边界
|
||||
- Guest Tools 服务仅监听 `127.0.0.1`,每台虚拟机分配独立的 256-bit 随机 Token(Bearer / Basic 鉴权)。注册表、连接状态、剪贴板策略、文本输入与 WebDAV handler 按 `driver.VMRef.Key()` 隔离;token 认证同时识别驱动与名称,既有客体 URL 不变。
|
||||
- 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 实时调整进程亲和性,避免超售卡顿。宿主只评估通用硬件事实;`kernel_irqchip`、冷重启等 macOS/WHPX 建议由所属驱动的 `driver.OptimizationAdvisor` 提供,与启动准备共用运行时判定。
|
||||
|
||||
> 本节关于 `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 生命周期分配的状态(过渡态、待生效设置、冷重启监视、磁盘路径缓存、进程采样、缩略图与键入锁、文本队列与 worker)以 `driver.VMRef.Key()` 隔离,并在删除 VM 或轮询发现外部删除时立即回收;VM 日志来源也使用规范键。
|
||||
- 日志监视器对单行无换行输出设 **64 KiB** 内存上限(原始日志文件完整保留);已结束任务在 10 分钟后从前后端状态中清理。
|
||||
- 4K 屏幕预览采用按行流式缩放降低单帧分配;手动复制截图仍保留全分辨率。不在热路径中人为调用 `debug.FreeOSMemory`。
|
||||
|
||||
### 4.7 数据目录版本与迁移
|
||||
- `<DataRoot>\.reims-go-data.json` 记录数据布局版本 `data_version`,以及最后一次提升它的应用版本 `written_by`。它不放进 `reims-go.json`,因为配置每次保存都会按结构体整体重写,旧版本会丢掉不认识的字段。
|
||||
- 每个版本都带着从旧布局升到自身布局的全部迁移步骤(`internal/datamigrate`),GUI 与 CLI 启动时、读取数据之前按版本号依次执行。步骤必须可重复执行;某步失败时,版本号停在最后一个成功的步骤,下次启动从那里继续。用户可以从任意旧版本直接升到新版本。
|
||||
- GUI 启动、首次设置、切换数据目录与 CLI 都经 `internal/dataroot` 打开数据目录:先不加锁读取版本戳,需要迁移时才取 `<DataRoot>.reims-go.lock` 并在锁内重读版本戳,两个进程同时打开同一目录时迁移只执行一次。
|
||||
- 数据目录由更新版本写入、版本戳无法解析、迁移失败或另一进程长时间持锁时,以只读模式打开,不创建或修改任何文件(包括锁文件):GUI 不启动插件、不轮询虚拟机,以只读界面代替工作台;CLI 只放行 `version`、`help` 与 `doctor`。版本戳损坏时可由用户显式修复,从 v0 重新执行全部步骤。
|
||||
- 首次设置选定目录之前,宿主不写入默认建议目录:不迁移、不启动插件、不轮询,界面中的选择只保存在内存里,由 `CompleteSetup` 写入选定的目录。
|
||||
- 只有删除很老的迁移步骤之后,才需要「最低迁移版本」:新版本根据 `data_version` 判断,并提示先安装某个中间版本。这个判断看的是数据本身,所以直接下载新版本运行也会生效。
|
||||
- 现有步骤:v1 为 reims-ctl 管理的每台 VM(目录含 `vm.toml`)补写驱动归属标记,见 [plugin-architecture.md](plugin-architecture.md) 的「VM 归属」;v3 一次性把正式版 `builtin.core` 的设置、`builtin.install-guide` 的启停和已知参数账本条目迁入 `builtin.guest.macos`,把按裸 VM 名的插件设置键改为 `driverID:vmName`,并补扫无归属标记的 VM。`state.json` 只加载、保存一次,原始 `.bak` 不被中间布局覆盖;功能分支上的 v2 仍可直升,未公开发布过的旧插件 ID 不做长期迁移。
|
||||
|
||||
### 4.8 macOS 代码边界
|
||||
- macOS 专属代码集中在 `internal/macos/` 与 `frontend/src/macos/`,最终作为独立插件移出本仓库;宿主只应经驱动层(`driver.Router`)与宿主服务使用它。
|
||||
- 三个棘轮测试守住边界:`internal/archtest` 分别检查宿主到 macOS、macOS 到宿主私有 Go 包的依赖,`frontend/scripts/test-macos-boundary.mjs` 检查前端文件。只有列入清单的包或文件可以跨界;新增引用、或清单中的条目已不再引用时,测试都会失败,所以清单只能缩短。
|
||||
- 宿主到 macOS 的例外包括 GUI 与 CLI 的组装入口、数据布局 v2 的迁移,以及仍混有宿主与 macOS 逻辑、待拆分的 `internal/guesttools`。反向清单记录 macOS 对宿主私有包的现有依赖,随公开接口建设逐步清零。
|
||||
|
||||
---
|
||||
|
||||
## 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,120 @@
|
||||
# 产品与界面设计规范(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` | **查看问题** | 打开目录、删除 |
|
||||
|
||||
- 已挂起时,恢复或放弃挂起状态后才可修改配置、管理磁盘和安装或弹出 Guest Tools。切换到不支持挂起的内核时,禁用恢复并提示用户切换内核。放弃挂起状态须经破坏性操作确认框确认。
|
||||
- 禁用按钮不占据主操作位置;状态变化时直接切换为当前最合适的主操作。
|
||||
|
||||
---
|
||||
|
||||
## 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 作为拉丁字体,并通过动态 `<html lang dir>` 与 `:lang()` 选择器按区域分离东亚字体栈(简体、繁体、日文、韩文各自优先匹配对应系统 UI 字体,避免 Han Unification 异体字混用);繁体与日文正文采用 `400` 字重与更舒展的行高防止高笔画糊字,开启中西文自动盘古间距;Win32 原生引导浮层按脚本分级探测 GDI 字体并支持卡片宽度自适应与长按钮纵向堆叠。语言包插件可附带沙箱校验的 `.woff2` 字体补齐缺字宿主。
|
||||
- **按钮层级**:每视图至多 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`) | 用效果命名标题,不把变量名放进标题 | 描述或技术信息 |
|
||||
| 内部错误原始文本 | 本地化的一句话说明 + 稳定错误码徽标(如 `[E_VM_CLONE_RUNNING]`) | 详情折叠区保留原始英文技术输出并支持一键复制完整诊断信息 |
|
||||
|
||||
格式化逻辑统一集中在 [`frontend/src/lib/format.ts`](../frontend/src/lib/format.ts)(数字、列表与相对时间统一经原生 `Intl` API 按当前语种格式化),不在组件中零散拼接。跨宿主与客户机语言的安装引导提示(如宿主机中文操作英文 macOS 恢复环境)自动采用「宿主译名 (`Guest Term`)」双标,同语种则单标。开发模式下提供 `en-XA` 伪本地化语种用于排查硬编码与长词截断。
|
||||
|
||||
### 7.2 文案风格
|
||||
- **克制直接**:标题用名词;按钮用 2–5 字动词;描述控制在清晰的一句话;不使用「请」「您」「成功」和感叹号;按钮和短提示末尾不加句号。
|
||||
- **不写内部引用**:面向用户的文案中严禁出现仓库路径、内部文档名、PR 编号或开发者术语。
|
||||
- **英文统一句首大写(Sentence case)**,避免每词首字母大写。
|
||||
- **去重复标题**:设置窗口标题只写实例名,分组标题与行标题不同名,不写自明标题(如「配置概览」)。
|
||||
|
||||
### 7.3 进度、日志与操作反馈
|
||||
- **进度归进度,日志归日志**:下载、建机、扩容等耗时任务统一通过结构化任务事件推送到状态栏;日志抽屉默认收起,**绝不因新日志到达而自动弹出**,仅在出错时通过 Toast 提醒并附「查看日志」入口。
|
||||
- **即时反馈**:每次点击操作立即进入忙碌态防重复触发;成功时给出简洁 Toast(「对象 + 结果」,如「macos-tahoe 已关机」),失败时说明原因与恢复动作。
|
||||
- **破坏性确认**:删除虚拟机等不可逆操作一律使用自定义确认对话框(含影响范围与「保留磁盘文件」选项),不使用浏览器原生 `window.confirm`。
|
||||
@@ -0,0 +1,272 @@
|
||||
# 客体插件化与 macOS 剥离方案
|
||||
|
||||
> 状态:待评审。本文描述从现有代码走到"与客体无关的主程序 + macOS 外部插件"的路径。[plugin-architecture.md](plugin-architecture.md) 记录的是插件系统当前的权威设计;本文的每一步合入时,同步修改该文对应章节(§3.2、§5.3、§5.4、§12 等),两份文档不得长期并存矛盾。
|
||||
|
||||
## 1. 目标与边界
|
||||
|
||||
- **终态**:主程序是与客体无关的本地虚拟机工作台。macOS 能力作为外部插件(独立仓库、独立发布)提供;主程序的源码、文档、语言词表、发布物与运行时流水线不含 macOS 专属内容。
|
||||
- **过渡态**:macOS 先成为内置插件 `builtin.guest.macos`,仍随 `reims-go.exe` 编译。过渡期只保证两件事,以免外置时再做一次迁移:
|
||||
- **职责与数据按终态划分**:设置、参数账本、VM 归属、启动准备从一开始就归 macOS 插件与它的驱动所有。
|
||||
- **调用面按终态收敛**:macOS 代码只经驱动接口、Hook 与宿主服务使用宿主;它对宿主 Go 包的依赖逐步收敛到可公开的 `pkg/` 包(第 6 节的反向棘轮)。
|
||||
- 界面是唯一允许的例外:过渡期可挂载原生页面,步骤 5 替换。
|
||||
- **特权按角色而不是按 ID 前缀**:宿主内置插件(留在主程序的部分)保留现有特权;拥有某台 VM 的驱动,对该 VM 的启动参数拥有完整控制(含 `-drive`、`-chardev`、`-qmp` 等),无论它是内置还是外部。外部驱动本身是 L3 原生程序,拥有完整账户权限,这不构成提权;第三方 Hook 仍受现有脱敏、超时与参数族限制。
|
||||
- **Linux 驱动**用于验证接口通用性,按 plugin-architecture.md Phase 4 以独立仓库的 L3 插件实现。Android 只预留接口。
|
||||
- **不在本方案内**:常驻后台服务、OCI 分发、运行态热迁移、整盘导出导入、稳定 VM ID(第 8 节)。
|
||||
- 哪些内容构成法律风险、需剥离到什么程度,不由本文判断,见第 9 节。
|
||||
|
||||
## 2. 现状
|
||||
|
||||
macOS 代码已集中到 `internal/macos/`(`installer`、`opencore`、`installguide`、`reims`、`macosdriver`)与 `frontend/src/macos/`,宿主到 macOS 的 import 由两处棘轮测试守住([architecture.md](architecture.md) §4.8)。仍需解决的问题:
|
||||
|
||||
### 2.1 身份与数据
|
||||
|
||||
| 问题 | 现状 |
|
||||
| :--- | :--- |
|
||||
| 驱动 ID 与旧插件 ID 混用 | `builtin.driver.reims-macos` 同时列在 `builtin.RetiredIDs` 中,不能直接拿来做新插件 ID |
|
||||
| 设置迁移不原子 | `MigrateRetired` 先落盘删除旧记录,再单独落盘新设置;两次写盘之间退出会丢失用户关闭过的选项 |
|
||||
| 安装引导独立成插件 | `builtin.install-guide` 是独立可选插件,内容是纯 macOS 的安装与恢复引导 |
|
||||
| 使用中保护依赖静态声明 | 使用中检查经 `DeclaredDriverIDs` 读取清单的 `guestDrivers`;`builtin.core` 在激活时动态注册驱动,未静态声明。核心插件不可停用所以目前无害,macOS 插件可停用后会失效 |
|
||||
| VM 以裸名称索引 | `PluginRecord.VMSettings` 以 VM 名为键;宿主内存态(`transitions`、`pendingChanges`、`rebootWatchers`、`diskPaths`、`procSamples`)、Guest Tools 注册表、缩略图与键入锁、日志来源同样以名称索引;界面进程交接参数 `--start-vm=` 不带驱动 |
|
||||
| VM 目录只有一个根 | 路由与"驱动不可用"扫描只看 `<DataRoot>/data/reims-ctl/vms` |
|
||||
| 运行时只能选一个 | `config.ActiveRuntime` 是单个字符串;非默认种类直接取已安装列表第一项;已装多个 reims-vgpu 运行时且未选定时,所有依赖运行时的功能失败 |
|
||||
|
||||
### 2.2 数据目录写入
|
||||
|
||||
GUI 启动、首次设置、`SetDataRoot`、CLI 各自打开数据目录;迁移失败时 GUI 只记日志、CLI 只打印警告;`SetDataRoot` 先保存配置再迁移;首次设置完成前,宿主已把默认建议目录当作数据目录读写;版本戳损坏时按 v0 重跑;没有跨进程写锁。
|
||||
|
||||
### 2.3 启动链路
|
||||
|
||||
| 问题 | 现状 |
|
||||
| :--- | :--- |
|
||||
| 启动入口 | GUI 的 `App.StartVM` 直接取 reims 客户端、自做 WHPX 检查,启动事件写死 macOS 驱动 ID 与能力;CLI 有直接启动(`startVM`)与交给界面进程(`startInWindow`)两条路径 |
|
||||
| 启动准备放在公共 Hook | `builtin.core` 的 `vm.beforeStart` 依次执行离线辅助盘、恢复启动、引导语言、WHPX 兼容降级、Win10 冷重启五步;恢复与语言两步在回调里直接写恢复标记、改写 OpenCore 镜像,后续插件否决时磁盘已被改动 |
|
||||
| 特权按前缀 | `BuiltinOnlyQEMUOptionFamilies`(`-drive`、`-chardev`、`-qmp`、`-fw_cfg`、`-global`、`-object`)、宿主环境变量白名单与 `PostStart` 动作都按 `builtin.` 前缀放行;外部插件的 `vm.beforeStart` 拿不到 `VMDir`、`ExtraArgs`、`InstallerPath`,单个回调限时 2 秒 |
|
||||
| 驱动接口缺参数 | `Driver.Start` 只收 VM 名,不接收合并后的参数、环境变量与启动后动作;参数账本的合并结果在 `StartVM` 中经 `reims-ctl set --extra-args` 写入;`stripLegacyManagedExtraArgs` 在 `internal/app` 中直接调用 macOS 代码 |
|
||||
| 调优不分驱动 | `host.EvaluateOptimizations` 一次算出绑核、irqchip、冷重启、独显与 CoW 建议 |
|
||||
|
||||
### 2.4 路由与界面
|
||||
|
||||
列表、详情、设置、停止、删除、日志等十余处直接调用 reims 客户端;`Router.ListAllVMs` 没有调用方且按名称去重;`Router.ResolveVM` 返回第一个同名结果;CLI 只有 `vm create --driver` 走驱动层;前端类型直接使用 `reims.VMDetail`,`CreateWizard`、`SettingsModal`、`lib/tasks.ts` 含 OpenCore、恢复、引导语言、无边框、安装包等字段与交互(不经 import,棘轮看不到)。
|
||||
|
||||
### 2.5 外置障碍
|
||||
|
||||
| 问题 | 现状 |
|
||||
| :--- | :--- |
|
||||
| Go 可见性 | `internal/macos/*` 导入宿主的 `internal/config`、`host`、`i18n`、`driver`、`plugin`、`runtime`、`vmstart`;外部仓库不能导入别的模块的 `internal/` 包 |
|
||||
| SDK | `pkg/pluginsdk` 只有 JSON-RPC 骨架 |
|
||||
| 反向宿主接口 | Sidecar 只能调用 `notify`、`audit`、`vm.spawn`、`vm.stop`、`vm.isRunning`;没有运行时查询、内存预检、绑核、日志与任务、进程退出、窗口信息等服务 |
|
||||
| 外部界面 | 外部插件不能贡献整页界面;沙箱 iframe 没有文件选择、流式任务进度、弹窗与尺寸协调等桥接 |
|
||||
| 非 import 耦合 | 全局脱敏器(`i18n.SetDetailRedactor`、插件管理器 `RedactFn`、排障包、界面错误上报)都直接用 `reims.RedactText`;`internal/runtime` 内置 `DefaultKind = "reims-vgpu"`、`reims-ctl` / `reims-util` 路径、reims 专用环境变量、按补丁推断能力与发布源;`locales/*/macos-glossary.json` 与 `internal/i18n/glossary.go`,以及 `vm`、`wizard`、`settings` 等词表中的 macOS 文案;`internal/app/macos_release.go`(`.reims-go-macos`);数据目录禁止逗号源于 `reims-util`;`internal/host` 中面向 reims-vgpu / metal2vulkan 的显卡兼容判断;CLI 顶层 `installer` 子命令 |
|
||||
| 外围文件 | `patches/`、`.github/workflows/build-runtime.yml`、`scripts/` 中的运行时打包与补丁脚本、`docs/portable-runtime-spec.md` |
|
||||
|
||||
## 3. 身份模型
|
||||
|
||||
| 身份 | 作用 | 规则 |
|
||||
| :--- | :--- | :--- |
|
||||
| 插件 ID | 启停、设置、贡献、参数账本归属 | 过渡期 `builtin.guest.macos`;外部插件不可使用 `builtin.` 前缀,换新 ID,经声明式承接接收旧 ID 的数据(见下) |
|
||||
| 驱动 ID | 一台 VM 由谁管理,写在 VM 目录的 `.reims-go-driver` | 过渡期保留 `builtin.driver.reims-macos`;外部驱动换新 ID,并把旧 ID 声明为别名,已有标记不改写 |
|
||||
| 运行时种类 | 安装哪套可执行程序、驱动要求的接口版本 | 每种类单独选定活跃运行时(步骤 3.5) |
|
||||
| VM 引用 `VMRef` | 一次操作、一份设置或一项内存状态针对哪台 VM | `{驱动 ID, 驱动内名称}`,自步骤 2 起贯穿宿主;稳定 VM ID 见第 8 节 |
|
||||
| VM 目录根 | 驱动的 VM 放在哪里 | 驱动在清单中静态声明自己的 VM 根目录(相对 DataRoot);macOS 驱动声明现有的 `data/reims-ctl/vms`。停用的驱动清单仍可读,宿主据此扫描"驱动不可用"的 VM,两个驱动的同名 VM 不会在磁盘上冲突 |
|
||||
|
||||
**声明式承接**:外部插件在清单中声明 `replaces`(它承接的旧插件 ID)与驱动 `aliases`(它承接的旧驱动 ID)。宿主在**安装或首次激活该插件时**把旧 ID 名下的设置、参数账本条目与按 VM 设置转给它,并让带旧驱动 ID 标记的 VM 归它管理。约束:
|
||||
|
||||
- 宿主在旧插件消失后保留其 `state.json` 记录与账本条目,直到有插件承接,期间这些 VM 显示"驱动不可用"。
|
||||
- 承接 `builtin.*` ID 只允许信任等级为 `official` 的包,或经用户逐项确认,防止任意插件接管已有 VM。
|
||||
- 主程序不硬编码任何 macOS 新旧 ID 映射。数据迁移带入的 `driver.RenamedDriverIDs` 只用于主程序内部的内置驱动改名,外部插件改名一律走 `aliases`。
|
||||
|
||||
驱动 ID 从此与插件 ID 分开:步骤 1 将 `builtin.driver.reims-macos` 移出 `RetiredIDs`,只有正式发布过的旧记录进入迁移清单:`builtin.core` 的设置与账本,以及 `builtin.install-guide` 的启停。未公开发布过的独立 theme/driver、compat/prep 插件记录不迁移、不删除。
|
||||
|
||||
## 4. 分步方案
|
||||
|
||||
每一步单独合入、单独发布,完成后对应的棘轮例外缩短(第 6 节)。
|
||||
|
||||
### 步骤 0:数据目录写入保护
|
||||
|
||||
后续每一步的数据迁移都依赖它;不依赖第 3 节的任何决定,可以立即开始。
|
||||
|
||||
- **统一打开入口**:新增宿主包(暂名 `internal/dataroot`),GUI 启动(`config.Resolve`)、首次设置(`CompleteSetup`)、切换目录(`SetDataRoot`)与 CLI 都经它进入。顺序为:
|
||||
1. 不加锁读取版本戳。版本高于本程序、或版本戳无法解析时,以只读模式返回,**不创建锁文件、不写任何文件**。
|
||||
2. 需要迁移或即将写入时,才创建并获取写锁,**拿锁后重新读取版本戳**,再决定是否迁移。另一个进程已完成迁移时直接返回。
|
||||
3. 迁移完成、版本戳写入后释放写锁。
|
||||
- **写锁**:把 `internal/macos/installer` 中基于 `LockFileEx` 的文件锁上提为宿主公共实现(`internal/filelock`),锁文件放在数据目录内,只在迁移时持有。配置与 `state.json` 都以临时文件加改名的方式原子写入,单次写入不会留下残缺文件,因此不为单次写入加锁;GUI 与 CLI 同时修改同一份配置时的相互覆盖不在本步解决。
|
||||
- **只读诊断模式**:GUI 不启动插件、不轮询虚拟机,以只读界面代替工作台,说明原因与详细信息,可选择其他目录;版本记录损坏时提供显式"修复(从 v0 重新迁移)",另一进程升级中或升级失败时提供"重试"。CLI 只放行 `version`、`help` 与 `doctor`,其他命令以非零退出码拒绝。
|
||||
- **写入点清单**(只读模式与首次设置前全部拦截):`reims-go.json`、`plugins/state.json` 与其备份、市场索引缓存、版本戳、启动哨兵 `.startup-sentinel`、`cli-start-*.json`、界面健康日志 `logs/ui-health.log`、应用更新后对更新下载目录的清理、VM 目录内的参数账本与归属标记。`CompleteSetup` 对候选目录的可写性探测(`.write-test-*`)只针对用户已选定的目录,保留。
|
||||
- **首次设置前零写入**:`needsSetup` 期间不把默认建议目录当作数据目录,数据迁移、插件状态与配置保存都要等目录选定。`REIMS_GO_FIRST_RUN` 测试模式必须同时指定隔离的数据目录,否则拒绝启动。
|
||||
- **CLI 交给界面进程**:`location.json` 位于数据目录之外。CLI 未指定数据目录、经单实例交给界面进程时,以界面进程当前打开的目录为准;该目录处于只读模式时,写命令被拒绝并说明原因。
|
||||
- **`MigrateRetired` 一次落盘**:删除旧记录与写入新设置合并为一次 `state.json` 原子替换。
|
||||
|
||||
**验收**
|
||||
- 高版本或版本戳损坏的数据目录:GUI 进入只读模式、CLI 写命令被拒,目录内无任何文件(含锁文件)被创建或修改。
|
||||
- 首次设置测试模式与设置完成前,默认建议目录内无任何文件被创建或修改。
|
||||
- 在 `MigrateRetired` 两步之间模拟退出,重启后用户关闭的选项仍为关闭。
|
||||
- GUI 与 CLI 同时启动并触发迁移,迁移只执行一次,结果一致。
|
||||
|
||||
### 步骤 1:macOS 插件身份与元数据迁移(已落地,合并至 v3)
|
||||
|
||||
- 新增内置插件 `builtin.guest.macos`,注册代码放在 `internal/macos/guest` 内,由 GUI 与 CLI 组装入口注册。`builtin.core` 只保留客体无关的默认主题。过渡期 macOS 插件默认启用,以保留存量 VM 的升级行为。
|
||||
- **安装引导并入**:`builtin.install-guide` 并入 `builtin.guest.macos`,成为它的一个可开关功能;旧 ID 退役,用户原来的启用状态转为新插件的对应设置。外部 macOS 插件因此只是一个包。
|
||||
- **静态声明驱动**:新插件在清单 `guestDrivers` 中静态声明 `builtin.driver.reims-macos`,运行中检查才能阻止在 macOS VM 运行时停用它,使用中检查才能阻止在仍有 macOS VM 时卸载它。
|
||||
- **设置迁移**:`whpx_fallback`、`win10_cold_reboot` 从 `builtin.core` 转给新插件,合并顺序为"新插件显式值 → 旧插件显式值 → 默认值"。
|
||||
- **参数账本迁移**:每台 VM 的账本中,只把已知由 macOS 启动步骤写入的条目转给新插件;用户手动参数与其他插件的条目保持原所有者。无账本的旧 VM(老版本或 CLI 直接启动过)由 `stripLegacyManagedExtraArgs` 兜底,该函数随之迁入 macOS 代码。
|
||||
- **迁移方式**:在写锁下先备份受影响的小文件,一次替换 `state.json`,各步可重复执行,全部校验通过后才写版本戳 v3;与步骤 2a 的 VMRef 设置键转换共用一次 `state.json` 读取和写入,保留升级前原始备份。VM 目录、磁盘、快照、CoW 父盘与 `vm.toml` 不移动。
|
||||
- **反向棘轮**:新增"`internal/macos/` 只能导入列入清单的宿主包"的测试,清单从现状开始,只减不增。
|
||||
|
||||
**验收**
|
||||
- 从 v0.2.x 直升:用户关闭过的兼容选项与安装引导开关保持原值,手动设置的 `kernel-irqchip` 仍优先。
|
||||
- 迁移中途退出后重启,迁移可继续,结果与一次完成相同。
|
||||
- 同一台 VM 连续启动两次,参数不重复追加,辅助盘不重复挂载。
|
||||
|
||||
### 步骤 2:VM 引用与启动链路
|
||||
|
||||
**2a. `VMRef` 身份、内部索引与 list/start/stop 用户入口已落地**(原计划在步骤 3,提前是因为统一启动入口就要按归属解析 VM)
|
||||
|
||||
- 引入 `VMRef{DriverID, Name}`;`Router.ResolveVM` 遇到多个同名结果时返回歧义错误;`ListAllVMs` 不再按名称去重。
|
||||
- 驱动在清单中声明 VM 根目录(第 3 节),路由与"驱动不可用"扫描遍历所有已声明的根。
|
||||
- 宿主内存态、Guest Tools 注册表、缩略图与键入锁、日志来源改为按 `VMRef` 索引;对客体已经暴露的访问路径保留兼容。
|
||||
- `PluginRecord.VMSettings` 的键改为 `VMRef` 的规范字符串,与步骤 1 共用版本 v3 的一次写入:已有键全部归属 `builtin.driver.reims-macos`。
|
||||
- 界面进程交接参数增加驱动;只给名称且不重名时仍可用。
|
||||
|
||||
**2b. 驱动自有准备与第三方意图分开(已落地)**
|
||||
|
||||
- `Driver.Start` 改为接收启动请求:`VMRef`、第三方插件经 `vm.beforeStart` 给出的意图(参数片段、环境变量、启动后动作),以及日志输出。
|
||||
- 启动前检查(WHPX、运行时兼容)与启动准备由驱动自己完成。macOS 的离线辅助盘、恢复启动、引导语言、WHPX 兼容降级、Win10 冷重启、Guest Tools 辅助盘从 `vm.beforeStart` 移入 macOS 驱动的 `Start`,"先准备恢复环境,再写引导语言"的顺序由驱动保证。
|
||||
- 参数账本的合并与写入(对 reims 即 `reims-ctl set --extra-args`)由驱动执行,宿主以公共函数提供账本合并逻辑。
|
||||
- `vm.beforeStart` 只留给第三方插件,继续脱敏、限时、限参数族。驱动在完成全部第三方 Hook、无人否决之后才改动磁盘,因此不需要通用回滚:准备步骤保持可重复执行,任一步失败即中止启动并明确报错;用户选择恢复启动而准备失败时,不悄悄转为普通启动。
|
||||
- 特权按第 1 节的角色规则判定:驱动对自己的 VM 拥有完整参数控制;宿主内置插件保留现有白名单;其他插件按现有限制。
|
||||
|
||||
**2c. 统一入口与职责拆分(已落地)**
|
||||
|
||||
- 新增生命周期模块(暂名 `internal/lifecycle`),GUI 的 `StartVM` 与 CLI 的 `startVM` 都调用它,`startInWindow` 交给界面进程后同样进入它。宿主负责按 `VMRef` 解析驱动、串行化同一台 VM 的操作、派发事件(驱动 ID、运行时与能力取自该 VM)、任务与日志、进程退出监视。
|
||||
- **拆分 `vmstart`**:提交内存检查、P 核绑核、亲和性配置留在宿主;离线辅助盘、恢复标记与 OpenCore 相关步骤迁入 `internal/macos/`。
|
||||
- **拆分 Guest Tools**:传输、剪贴板与共享目录留在宿主(`guest-tools.transport` 服务),macOS 客体代理与辅助盘镜像(`BuildToolsDiskImage` 等)迁入 `internal/macos/`;镜像构建由 macOS 驱动在全部启动 Hook 通过后执行。
|
||||
- **拆分调优判定**:宿主只报告探测事实;驱动针对选中的 VM 结合运行时能力给出建议,设置页与实际启动共用同一份判定。`kernel-irqchip`、WHPX 兼容降级与冷重启补偿的策略归 macOS 驱动。
|
||||
|
||||
**验收**
|
||||
- 升级后用原有 macOS VM 验证:恢复引导、离线辅助盘、引导语言、冷重启监视、Guest Tools 与升级前行为一致;按 VM 的插件设置不丢失。
|
||||
- 第三方插件否决启动时,VM 目录与 OpenCore 镜像未被修改。
|
||||
- 测试驱动在相同宿主探测结果下,不会收到 OpenCore、辅助盘或冷重启参数。
|
||||
|
||||
### 步骤 3:其余入口统一路由(通用 App/CLI 已去 reims 直调,原生 macOS 流程按文件例外隔离)
|
||||
|
||||
- **后端**:VM 列表与轮询、详情、创建、设置、停止、重启、删除、日志、弹出安装介质,以及快照、克隆、磁盘、缩略图、统计、排障采集、亲和性等流程,全部经生命周期模块按 `VMRef` 路由。
|
||||
- **CLI**:`vm` 子命令全部走驱动层,重名时要求 `--driver`。顶层 `installer` 子命令改由 macOS 插件经 `commands` 扩展点贡献,宿主 CLI 提供插件命令转发。
|
||||
- **前端**:改用通用 VM 模型(名称、驱动、状态、CPU、内存、磁盘摘要、可用操作),按驱动能力位显示入口,后端执行时同样校验能力。`CreateWizard`、`SettingsModal` 中的 macOS 字段改为驱动的 `CreateSchema` / `SettingsSchema` 或插件页面。
|
||||
- **macOS 界面**:安装包页、在线恢复、版本图、OpenCore 设置由 macOS 插件贡献;过渡期经同一处注册表挂载 `frontend/src/macos/` 内的原生页面。
|
||||
|
||||
**验收**
|
||||
- 在测试装配中不注册 macOS 插件:工作台仍可用测试驱动完成"创建 → 启动 → 停止 → 删除"。
|
||||
- 两个驱动各有一台名为 `dev` 的 VM:两台都出现在列表、各自的按 VM 设置互不覆盖;停止其中一台只调用其所属驱动。
|
||||
- 恢复 macOS 插件后,原有 macOS VM 沿原路径启动,无需转换磁盘或重建配置。
|
||||
|
||||
### 步骤 3.5:宿主服务与按种类的运行时
|
||||
|
||||
Linux 驱动(步骤 4)与 macOS 外置(步骤 5)共同的前置条件,可在步骤 2 之后与步骤 3 并行开发。
|
||||
|
||||
- **按种类选定运行时**:配置改为每个运行时种类各记一个活跃运行时,随数据版本迁移现有的单值;只读操作在未选定时临时使用该种类最新安装的运行时、不写回配置,启动与创建前要求选定(待决,见第 9 节)。
|
||||
- **运行时与 reims 解耦**:`internal/runtime` 只保留按种类的通用安装、校验、切换与环境构造;reims-vgpu 的默认种类、`reims-ctl` / `reims-util` 路径、专用环境变量、按补丁推断能力与发布源,改由运行时种类声明提供(过渡期由 macOS 插件声明)。
|
||||
- **反向宿主接口扩充**(同时进入 `pkg/pluginsdk` 的公开类型):运行时查询(按种类返回路径与能力)、提交内存预检、绑核、日志与任务进度、进程退出通知、QMP 访问、VM 窗口信息与宿主明暗主题事件(安装引导浮层需要)。每项按权限校验。
|
||||
- **脱敏注册**:宿主提供通用脱敏层,插件可注册自己的脱敏规则;全局脱敏器、插件管理器、排障包与界面错误上报改用它。macOS 的规则由 macOS 插件注册。
|
||||
|
||||
### 步骤 4:Linux 最小驱动与驱动契约测试
|
||||
|
||||
- 新增与具体驱动无关的契约测试集(暂名 `internal/driver/drivertest`),对每个驱动运行同一组用例:生命周期调用的幂等与可重试边界、错误分类,以及"进程已启动 / 控制通道可用 / 客体已就绪"三种状态的区分。
|
||||
- Linux 驱动以独立仓库的 L3 插件实现,只依赖 `pkg/pluginsdk` 与反向宿主接口;先跑通一种镜像的创建、启动、停止与删除,再按 plugin-architecture.md Phase 4 的验收标准补齐。
|
||||
- 只有出现两份以上重复实现时,才从中提取磁盘或 QEMU 公共模块。
|
||||
|
||||
**验收**:契约测试同时覆盖 macOS 内置驱动与 Linux 驱动;Linux 驱动不修改主程序源码即可接入。
|
||||
|
||||
### 步骤 5:macOS 外置
|
||||
|
||||
前置条件:
|
||||
|
||||
- **外部插件页面**:整页插件页面(iframe,插件自带前端包,宿主提供主题令牌与到插件自身 Sidecar 的桥接)、创建向导步骤槽位、VM 详情分区槽位。桥接至少提供:宿主文件与目录选择(返回宿主路径交给插件 Sidecar,iframe 内不可见)、长任务的注册与流式进度(下载、取消、退出前拦截活跃任务)、由宿主绘制的对话框、iframe 高度自适应与焦点和快捷键传递。
|
||||
- **运行时需求声明**:插件在清单中声明需要的运行时种类与版本范围;缺少时宿主引导用户安装。运行时包不随插件安装事务自动拉取,插件之间的安装期依赖等出现真实用例再设计。
|
||||
- **语言与文案**:`macos-glossary.json`、`internal/i18n/glossary.go` 与各词表中的 macOS 文案迁入 macOS 插件的 `l10n`;第三方语言包对 macOS 文案的翻译改为针对该插件的 `pluginOverrides`。
|
||||
- **反向棘轮清零**:`internal/macos/` 不再导入任何宿主 `internal/` 包,只依赖 `pkg/`。
|
||||
- **声明式承接可用**:`replaces` 与 `aliases`(第 3 节)已实现并有测试。
|
||||
|
||||
外置本身:
|
||||
|
||||
- 迁出清单:`internal/macos/`、`frontend/src/macos/`、macOS 词表、`patches/`、`.github/workflows/build-runtime.yml`、`scripts/` 中的运行时打包与补丁脚本、`docs/portable-runtime-spec.md` 中 reims-vgpu 专属部分。用 `git filter-repo` 按清单生成 macOS 插件仓库,保留这部分历史;主仓库一次提交删除,并改写 README 与 AGENTS 中的产品定位。若历史本身也需剥离,改为反向拆分(第 9 节)。
|
||||
- 发布不含 macOS 的主程序:已有 macOS VM 因归属标记与 macOS 驱动声明的 VM 根仍在列表中,显示"需要安装对应驱动插件",由用户自行安装;主程序不自动安装、不默认推荐。用户安装外部 macOS 插件后,经声明式承接取回设置、账本与 VM 归属。
|
||||
|
||||
**验收**
|
||||
- 主仓库删除迁出清单后,构建、测试与两处棘轮全部通过;对 `macOS`、`OpenCore`、`reims`、`Apple` 等词的全仓检索只剩明确列出的例外(如"驱动不可用"提示中的通用说法)。
|
||||
- 安装外部 macOS 插件后,原有 macOS VM 无需转换即可启动,用户关闭过的选项保持关闭。
|
||||
|
||||
## 5. 顺序与并行
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
S0["步骤 0\n数据目录写入保护"] --> S1["步骤 1\nmacOS 插件身份\n与 v3 迁移"]
|
||||
S1 --> S2["步骤 2\nVMRef 与启动链路"]
|
||||
S2 --> S3["步骤 3\n其余入口统一路由"]
|
||||
S2 --> S35["步骤 3.5\n宿主服务与\n按种类的运行时"]
|
||||
S3 --> S4["步骤 4\nLinux 最小驱动"]
|
||||
S35 --> S4
|
||||
S3 --> S5["步骤 5\nmacOS 外置"]
|
||||
S35 --> S5
|
||||
P5["外部插件页面 · 承接机制\n语言迁出 · 反向棘轮清零"] --> S5
|
||||
```
|
||||
|
||||
- 步骤 0 不依赖其他决定,可以立即开始;步骤 1、2 开始前需定下第 3 节的身份模型与第 1 节的特权规则。
|
||||
- 步骤 3 与 3.5 可并行;外部插件页面、承接机制与语言迁出可在步骤 2 之后并行开发。
|
||||
- 以法律目标为准时,最快路径仍要经过步骤 1–3.5;跳过它们会让外置时再做一次数据与职责迁移。
|
||||
|
||||
## 6. 棘轮与检查
|
||||
|
||||
**宿主 → macOS**(现有,`internal/archtest` 与 `frontend/scripts/test-macos-boundary.mjs`):
|
||||
|
||||
| 例外 | 移除时机 |
|
||||
| :--- | :--- |
|
||||
| `internal/plugin/builtin`(仅源码的 Guest Tools 参数辅助) | 步骤 2:客体代理与辅助盘镜像迁出后移除;注册与测试例外已在步骤 1 移除 |
|
||||
| `internal/datamigrate` | 步骤 5:历史 v3 迁移改为不依赖 macOS 实现的通用数据迁移后移除 |
|
||||
| `internal/guesttools`(源码与测试) | 步骤 2:客体代理与辅助盘镜像迁出 |
|
||||
| `internal/plugin`(仅测试) | 步骤 3:Sidecar 测试改用通用测试替身 |
|
||||
| `internal/app`、`internal/cli` | 步骤 3:只剩一个组装文件注册 macOS 插件,例外细化到该文件 |
|
||||
| 前端 `App.tsx`、`Sidebar.tsx`、`VMPage.tsx` | 步骤 3:改为插件贡献 |
|
||||
| 组装文件 | 步骤 5:macOS 外置后删除 |
|
||||
|
||||
**macOS → 宿主 `internal/`**(步骤 1 新增):清单从现状开始,随步骤 2 与 3.5 把依赖改到 `pkg/`,步骤 5 前清零。
|
||||
|
||||
**非 import 耦合**:import 棘轮看不到第 2.5 节所列的词表、脱敏、运行时、前端字段等耦合。不为它们另建常驻检查;各自在所属步骤内迁移,步骤 5 以一次全仓检索作为验收。
|
||||
|
||||
## 7. 风险
|
||||
|
||||
| 风险 | 应对 |
|
||||
| :--- | :--- |
|
||||
| 迁移改坏用户数据 | 步骤 0 的写锁、只读模式与一次落盘;迁移前备份小文件;只动元数据,不动磁盘 |
|
||||
| 升级后 macOS VM 行为变化 | 每步以原有 macOS VM 做回归:恢复引导、辅助盘、引导语言、冷重启监视、Guest Tools、绑核 |
|
||||
| 特权模型改变引入越权 | "驱动对自己的 VM 拥有完整参数控制"只授予 VM 的所属驱动;`builtin.*` 的承接只允许 `official` 包或用户逐项确认;改动单独评审 |
|
||||
| `VMRef` 迁移遗漏某处按名索引的状态 | 步骤 2a 以"两台同名 VM"作为贯穿测试用例,覆盖设置、内存态、Guest Tools 与交接参数 |
|
||||
| 新旧版本混用 | 只读模式只保护新版本;降级支持的最低版本需明确公布(第 9 节) |
|
||||
| 步骤之间长期停留在半迁移状态 | 每步自成闭环、可单独发布;棘轮清单只减不增 |
|
||||
| 外部插件界面体验不及原生 | 过渡期保留原生页面;外置前以安装包页与恢复向导做可用性验收 |
|
||||
|
||||
## 8. 后续(不在本方案内)
|
||||
|
||||
触发条件出现时再立项:
|
||||
|
||||
- **稳定 VM ID**:VM 改名需要保持设置与历史、PID 复用或 CLI 超时重试出现实际问题时,引入 VM ID、一次开机的运行 ID 与一次长操作的操作 ID(参考 libvirt 的 UUID 与 containerd 将对象与运行分离的做法)。`VMRef` 届时作为人读入口保留。
|
||||
- **重新接管**:管理进程重启后重新连接正在运行的 VM,GUI 退出后 CLI 能找回同一次运行。
|
||||
- **常驻服务**:需要"GUI 退出后任务继续""多客户端订阅同一状态"或第三方程序调用时,再把生命周期模块放到用户级后台进程后,经 Windows 命名管道提供带版本的接口。
|
||||
- **整盘迁移**:换盘、换电脑做成停机导出与导入;验收为原数据目录完全不可访问时,目标机仍能从带 CoW 子盘的副本启动。
|
||||
- **升级交接**:进行中的创建、克隆、快照绑定发起时的驱动版本,运行中 VM 的控制权在重连验证后移交(参考 Magpie 插件宿主升级时的处理)。
|
||||
- **插件间安装期依赖**:出现"插件 A 必须与插件 B 一起安装"的真实用例后再设计,届时优先考虑只提示、不自动求解。
|
||||
|
||||
## 9. 待决事项
|
||||
|
||||
步骤 1 开始前需要定下:
|
||||
|
||||
1. **特权规则**:是否接受第 1 节"按角色授予特权"的规则,替代现有按 `builtin.` 前缀放行。
|
||||
2. **承接的信任要求**:承接 `builtin.*` ID 是只允许 `official` 包,还是也允许用户逐项确认。
|
||||
3. **过渡期 macOS 插件是否默认启用**:步骤 1 暂取默认启用,保证升级无感;默认关闭更贴近剥离方向,但存量用户升级后会看到"驱动不可用"。最终实现仍待评审。
|
||||
|
||||
可在后续步骤前决定:
|
||||
|
||||
4. **多运行时未选定时的行为**(步骤 3.5):建议只读操作临时使用最新安装的运行时、不写回配置,启动与创建前要求选定。
|
||||
5. **降级支持**(步骤 0 发布前):可安全退回的最低版本,以及只读模式的提示文案。
|
||||
6. **剥离范围**(步骤 5):法律风险具体涉及哪些内容(OpenCore 与 SMBIOS 处理、Apple 安装包下载、产品定位中的 macOS 字样、reims-vgpu 运行时),决定迁出清单的范围。
|
||||
7. **官方市场是否上架 macOS 插件**(步骤 5):上架方便用户,但官方索引仍与 macOS 产生关联。
|
||||
8. **代码历史**(步骤 5):只删除当前代码,还是让主程序以新仓库重新开始历史、本仓库保留为 macOS 插件仓库。
|
||||
@@ -0,0 +1,518 @@
|
||||
# 插件系统架构(Plugin Architecture)
|
||||
|
||||
> 状态:**核心内核、内置扩展、主题引擎、Sidecar 托管与 CLI/GUI 管理已落地**;市场远端索引与 L2 脚本层按需迭代。
|
||||
> 关联文档:[`architecture.md`](architecture.md) · [`design-guidelines.md`](design-guidelines.md) · [`portable-runtime-spec.md`](portable-runtime-spec.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核心:默认主题\n可选:macOS 客体驱动 · 宿客桥接 · 剪贴板 · 输入服务 · 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`:只保留客体无关的默认主题(主题 id 为 `builtin.theme.default`)。它是**系统插件**:始终启用,不能停用或卸载,不出现在插件页与 `plugin list` 中(按 ID 查询仍可见),不参与「使用中」检查。
|
||||
- **macOS 客体插件** `builtin.guest.macos`:注册代码位于 `internal/macos/guest`,静态声明 reims 驱动(驱动 id 仍为 `builtin.driver.reims-macos`)、宿主体检、启动准备、WHPX 降级、Win10 冷重启和安装引导。它是可停用插件,过渡期默认启用以保留升级行为;有 VM 运行时不能停用,停用后宿主内的 macOS 原生页面与流程(创建、设置、Guest Tools 挂载、安装与恢复等)一并拒绝执行,直到重新启用。安装引导保留独立应用级开关。启动准备暂经 `vm.beforeStart`,下一步改由驱动自己执行,见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 2。
|
||||
- **可选内置扩展**:Guest Tools 传输服务、剪贴板互通、宿主输入服务、虚拟机窗口安装引导。经同一注册表注册、可独立启停、停用后零残留,停用即真正停止(不被其他调用方重新拉起)。首批示例为默认开启的剪贴板互通(见 §5.4)。
|
||||
|
||||
旧版曾把 macOS 驱动、兼容补偿、安装引导与准备步骤拆成多个内置插件。数据布局 v2 的迁移删除这些旧 ID 的记录:显式设置与旧安装引导启停状态转入 `builtin.guest.macos`,参数账本中已知 macOS 条目也转给该插件;无关插件与宿主参数保持原所有者。
|
||||
|
||||
---
|
||||
|
||||
## 4. 内核机制
|
||||
|
||||
### 4.1 注册表与可逆副作用
|
||||
|
||||
- 每个已启用插件(含内置)拥有一个作用域,所有注册行为(提供服务、贡献扩展点、订阅事件、后台服务、Win32 钩子、QMP 监视)都登记一个释放函数;停用、卸载或升级时**逆序释放**,激活中途失败则回滚已登记项。
|
||||
- 插件声明 `requires` / `provides`(服务名 + 版本范围)。Reconcile 先关后开:先释放不再需要的插件及依赖其服务的插件,再按依赖求不动点激活。状态为 `off / pending / active / degraded / failed`。
|
||||
- **使用中不可移除**:仍有 VM 归属的驱动不可卸载,仍被 VM 使用的运行时不可删除;使用情况查询失败按「使用中」处理。
|
||||
- **运行中不可停用**:驱动的 VM 只要有一台处于停止、挂起或损坏以外的状态,就不能停用其插件;状态查询失败同样拒绝。VM 都已停止或挂起时可以停用:VM 文件与挂起状态保留,显示为「驱动不可用」,不能启动、恢复或修改,重新启用后恢复。插件页停用这类插件前先弹窗说明。
|
||||
- 内置扩展通过 `pluginApi` 版本做兼容检查;激活 panic 转为 `failed` 并回滚。
|
||||
|
||||
### 4.2 扩展点目录
|
||||
|
||||
| 扩展点 | 来源层 | 基数 | 失败策略 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `themes`(令牌、配色方案、字体、图标、背景、提示音、样式表、状态装饰) | Builtin · L1 | 按 id,同一时刻仅一个主题包生效 | 回退内置默认主题 |
|
||||
| `uiScripts`(交互主题脚本) | 主窗口受信任脚本 | 随所属主题包 | 单个功能出错只停用该功能;整体失败回退到无脚本的主题 |
|
||||
| `locales`(声明式语言包:分域 `files`、可选包内 `.woff2` 字体、`pluginOverrides` 跨插件翻译覆盖) | Builtin · L1(纯 JSON + WOFF2,免高危权限) | 按 BCP-47 语种与信任等级合并,覆盖 GUI、Win32 浮层、托盘与 CLI | 缺失词条沿有界多跳 `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,嵌在槽位内 | 限定槽位,限高 | 错误占位 + 重试 |
|
||||
| `views` | L4 iframe,整页或标签页(§5.6) | 按位置设数量上限 | 错误页 + 重试;不影响其他视图 |
|
||||
| `diagnostics` | Builtin · L3 | 列表 | 跳过;输出强制脱敏 |
|
||||
|
||||
UI 槽位采用「声明即占有」:插件只能向宿主槽位目录(§5.1)中的槽位贡献。目录中的每个槽位、每种视图位置都必须由宿主实际渲染,前端构建检查覆盖这一点;不能出现可以声明、界面上却不显示的位置(§6.3)。
|
||||
|
||||
### 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-shell`、`rg-p-titlebar`、`rg-p-sidebar`、`rg-p-nav`、`rg-p-main`、`rg-p-vm-page`、`rg-p-statusbar`、`rg-p-logpanel`、`rg-p-settings` 等;控件级:`rg-p-nav-group`、`rg-p-nav-item`、`rg-p-button`、`rg-p-icon-button`、`rg-p-card`、`rg-p-badge`、`rg-p-tabs`、`rg-p-tab`、`rg-p-menu`、`rg-p-menu-item`、`rg-p-dialog`、`rg-p-toast`、`rg-p-tooltip`、`rg-p-input`、`rg-p-switch`、`rg-p-progress`、`rg-p-vm-actions`、`rg-p-plugin-view` |
|
||||
| 状态属性 | 文档级只读状态:外观、动效档位、语种与书写方向、当前视图、侧栏折叠、安全模式、布局选项;逐项状态:导航项与 VM 区域带 `data-vm-state`、`data-driver`、`data-selected`、`data-busy`,按钮带 `data-variant`、`data-busy`,对话框与提示条带 `data-tone`。主题可据此为单个 VM 条目做动效,不必解析界面文字 |
|
||||
| 槽位目录 | 每个槽位声明上限与可挂内容(装饰、SDK 挂载、`panels`、`menus`、`statusItems`):`titlebar.center`、`sidebar.header`、`sidebar.footer`、`nav.item.trailing`(逐个 VM 条目)、`vm.header.trailing`、`vm.toolbar`、`vm.card`、`vm.preview.tl/tr/bl/br`、`statusbar.left`、`statusbar.right`、`empty.state`、`create.source`、`settings.plugin` |
|
||||
| 图层 | 全窗口背景层 `layer.background` 与前景装饰层 `layer.overlay`:不拦截指针、不参与焦点,「减少动态效果」时停播动画;用于动态壁纸、粒子与满屏吉祥物 |
|
||||
| 布局选项 | 主题清单的 `layout` 声明:侧栏位置(左/右)、侧栏形态(完整/图标窄栏/悬浮)、密度(紧凑/常规/宽松)、标题栏样式。只改摆放与尺寸,不能隐藏操作入口 |
|
||||
| 图标 | 宿主公开图标名清单(如 `start`、`stop`、`settings`、`plugin`、`vm.state.running`);主题以 `icons` 映射到包内单色 SVG,宿主按令牌着色 |
|
||||
|
||||
契约内的部件、状态属性、槽位、图层、布局选项、图标名与令牌的重命名或删除属于 `uiApi` 主版本变更;前端构建检查契约中的每个部件、槽位与图层都由某个组件输出(§6.3)。
|
||||
|
||||
**三档主题能力**
|
||||
|
||||
| 档位 | 能力 | 层级与信任 | 对应复杂主题的典型需求 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **令牌主题** | 配色方案集合:少量种子色 + 声明式派生规则(按浅/深外观对种子做亮度、色度、透明度偏移)生成整套表面/文字/边框色阶;用户在宿主提供的编辑器中改种子、新建/复制/重命名/删除方案。字体(包内字体或用户字体目录)、图标与品牌标记替换、背景、按事件配置的提示音 | L1,宿主校验 | 多套配色预设与方案管理、自带字体、品牌标记、提示音 |
|
||||
| **样式主题** | 面向部件契约的样式表(宿主以 `@layer` 固定层叠顺序:基础 → 主题 → 用户);声明式状态装饰(按状态表达式切换精灵图/动画帧,锚定槽位,如随 VM 启停与任务进度变化的吉祥物) | L1,宿主校验与清洗 | 窗框/侧栏/排印样式、状态动画吉祥物 |
|
||||
| **交互主题** | 主窗口内运行的受信任 UI 脚本,只经宿主 UI SDK 工作 | 高信任(`ui:script`) | 滚动、折叠、悬停预览等交互增强 |
|
||||
|
||||
**UI SDK**(交互主题的唯一受支持接口):
|
||||
|
||||
- 生命周期:主题脚本导出装载函数,所有订阅、计时器与挂载都登记释放函数;切换或停用主题时逆序拆除,单个功能抛错不影响其余功能。
|
||||
- 只读状态订阅:非敏感的 VM 摘要、任务进度、当前视图、外观;不提供原始路径与敏感字段。
|
||||
- 事件流:VM 状态变化(含过渡态)、任务开始/进度/结束、提示条出现、视图切换,供主题做转场动画,不必轮询状态。
|
||||
- 宿主提供的页面观察总线、帧读写管线与按部件查询:主题不自建节点观察者,也不整页查询文档。
|
||||
- 槽位挂载:框架无关的 DOM 挂载,不共享宿主的 React 实例,避免随宿主依赖升级断裂。按 VM 重复的槽位(`nav.item.trailing`)以 VM 引用为键挂载;全窗口图层另有专用挂载;按部件查询可取回重复部件的全部实例。
|
||||
- 声明式装饰与 SDK 挂载共用同一批槽位与图层;重复槽位里的装饰按所在 VM 自身的状态匹配。
|
||||
- 受限动作:仅开放非破坏性界面动作(折叠侧栏、打开设置、前置 VM 窗口等);启停、删除、配置写入不在 SDK 中。
|
||||
- 主题设置:由 `settings` Schema 定义,宿主渲染设置页。
|
||||
|
||||
**边界**:
|
||||
|
||||
- 主窗口同一 JS 环境内的脚本不是安全边界(可操作 DOM),交互主题按高信任处理:需 `ui:script` 权限与显式确认,`community` 级默认不可启用;宿主在加载主题脚本前收起 Wails 绑定的全局对象,SDK 是唯一受支持的接口。
|
||||
- 样式清洗:禁止外部 `url()` 与远程 `@import`,资源只能引用包内清单中的文件;窗口拖拽区、焦点环与最小点击热区等可用性属性由宿主在更高层保留,不被主题覆盖。
|
||||
- 同一时刻只启用一个主题包,切换时先停用旧主题再装载新主题;安全模式一律回到内置主题。
|
||||
- 首帧前按当前主题内联令牌防闪烁;无边框窗口的标题栏由前端绘制,可随主题变化。
|
||||
- 主题只改视觉与交互呈现,不改文案、信息层级与操作入口([`design-guidelines.md`](design-guidelines.md) 的主操作与破坏性操作约束由宿主守住)。布局选项可以挪动区域、改变侧栏形态,但 VM 列表、新建、设置与插件入口始终可达。
|
||||
- 主题不提供功能页面;需要自有界面的插件走 §5.6 的视图,不经 `ui:script`。
|
||||
- 需要读写用户文件或常驻服务的主题,以同包 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/macos/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`,可选 `SnapshotDriver`、`CloneDriver`、`DiskDriver` 与通用 `InvokeAction`;存储调用由生命周期先解析 `VMRef`,结果使用 `driver.DiskSnapshot / DiskResizeResult / DiskCompactResult` |
|
||||
|
||||
- **VM 归属**:VM 目录内的标记文件 `.reims-go-driver` 记录驱动 id;无标记的存量 VM 归属 `builtin.driver.reims-macos`,并由数据迁移补写标记([architecture.md](architecture.md) §4.7)。有标记的 VM 在其驱动缺席时仍以「驱动不可用」列出。驱动迁到另一个插件、id 随之改变时(市场插件不能使用 `builtin.` 前缀),在 `driver.RenamedDriverIDs` 登记旧 id 到新 id 的映射;标记文件不改写,降级后旧版本仍能识别。CLI 增加 `vm create --driver <id>`,其余 `vm` 子命令按归属自动路由。
|
||||
- **VM 引用与根目录**:`driver.VMRef{DriverID, Name}` 的规范键为 `driverID:vmName`;`Router.ListAllVMs` 按完整引用去重,裸名称解析遇到跨驱动同名时返回歧义错误,调用方须显式指定驱动。每个 `guestDrivers` 条目用 `vmRoots` 声明相对 `<DataRoot>` 的斜杠路径,绝对路径、反斜杠与 `..` 均被拒绝;路由遍历所有已声明根(包括停用驱动)以保留「驱动不可用」条目。按 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.guest.macos` | `internal/macos/guest`、`internal/macos/installguide`、`macosdriver`、`vmstart.Prepare` 各步骤 | 静态 `guestDrivers` + `host.preflight` + 驱动内启动准备与冷重启意图 + 条件提供的 `ui.install-guide` 服务;设置 `install_guide`、`whpx_fallback`、`win10_cold_reboot` |
|
||||
| `builtin.core`(系统插件) | `internal/plugin/builtin/core.go` | `themes`:默认主题 |
|
||||
|
||||
> 下一步:Guest Tools 的 macOS 客体代理与辅助盘镜像迁入 macOS 插件,传输服务留在宿主;启动准备改由驱动自己执行。见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 2。
|
||||
|
||||
### 5.5 与上游补丁队列的边界
|
||||
|
||||
| 类别 | 归属 | 原则 |
|
||||
| :--- | :--- | :--- |
|
||||
| 引擎内部崩溃与 Hypervisor 层修复(WHPX 兼容、协程、构建锁文件等) | [运行时源码与补丁](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md)(编译期) | 外部插件无法等价替代,修复交由运行时仓库维护 |
|
||||
| 窗口内部消息循环拦截(如 SDL 窗口内字符消息) | `patches/`,宿主侧做部分补偿 | 跨进程拦截需 DLL 注入,杀软误报风险高,不做成插件 |
|
||||
| 宿主侧绕过、兜底补偿与宿客桥接 | 内置扩展(§5.4) | 运行时缺少对应补丁时平滑降级;依据运行时 `capabilities` 判断 |
|
||||
|
||||
### 5.6 插件自有界面
|
||||
|
||||
插件需要界面时按以下顺序选择形式,能用前一种就不用后一种:
|
||||
|
||||
| 形式 | 适用 | 渲染与信任 |
|
||||
| :--- | :--- | :--- |
|
||||
| **声明式界面** | 应用与按 VM 设置、VM 卡片信息、工具栏按钮与菜单、状态栏项、通知、确认框、表单对话框、任务进度 | 宿主原生渲染,自动跟随主题、语种、键盘操作与无障碍;只需低、中危权限 |
|
||||
| **视图(`views`)与面板(`panels`)** | 自定义可视化、控制台、多步向导、需要自绘交互的页面 | 沙箱 iframe(不透明源),只经插件界面桥(bridge)与宿主通信,能力由权限约束 |
|
||||
| **交互主题脚本** | 仅限主题的视觉与交互增强 | 主窗口受信任脚本(`ui:script`);功能插件不得使用 |
|
||||
|
||||
**视图位置**(`views[].location`;面板仍按槽位嵌入,限高):
|
||||
|
||||
| 位置 | 呈现 | 上限 |
|
||||
| :--- | :--- | :--- |
|
||||
| `sidebar` | 侧栏「扩展」分组中的导航项,点击后在主区域整页打开;导航项的图标、标题、角标与选中态由宿主绘制 | 每插件 2 个;超出部分折叠进「更多」 |
|
||||
| `vm.tab` | VM 页内的标签页;以 `when` 限定驱动或能力位(如只对某驱动的 VM 显示控制台) | 每个 VM 页 4 个 |
|
||||
| `settings` | 设置中的独立分节,用于放不进 Schema 表单的复杂设置 | 每插件 1 个 |
|
||||
| `dialog` | 不常驻;由命令或 bridge 的 `ui.openView` 以模态打开,可返回结果 | 同一时刻 1 个 |
|
||||
|
||||
视图字段:`id`、`title`、`icon`(包内单色 SVG,宿主按令牌着色)、`location`、`entry`(包内 HTML)、`order`、`when`、`minWidth`。宿主负责外框:标题、返回、加载与错误占位、重试、尺寸、焦点进出与快捷键。视图惰性加载;同一时刻保持存活的视图有上限,切走的视图超过上限即卸载,插件停用时全部卸载。
|
||||
|
||||
**插件界面桥(`bridgeApi` 1.0)**:iframe 与宿主之间的请求/响应与事件消息,宿主只应答来源窗口为该 iframe 的消息,每个方法在 Go 侧按权限二次校验并限流。
|
||||
|
||||
| 命名空间 | 方法与事件 | 权限 |
|
||||
| :--- | :--- | :--- |
|
||||
| 握手 | `hello`:返回 `bridgeApi`、`features`、语种与书写方向、完整契约令牌、视图上下文(位置、所在 VM 的 `VMRef`) | 无 |
|
||||
| `ui` | `notify`、`confirm`(宿主原生确认框)、`showForm`(以 Schema 弹出原生表单并返回值)、`setTitle`、`setBadge`、`openView`、`close`(`dialog` 返回结果)、`navigate`(只限宿主路由白名单)、`openExternal`(宿主确认后用系统浏览器打开) | `ui:notify` / `ui:slot` |
|
||||
| `vm` | `list`、`get`(通用 VM 模型,不含敏感字段);事件 `vm.stateChanged` | `vm:read` |
|
||||
| `command` | `invoke`:只能调用本插件声明的命令;VM 启停等动作由命令处理方经 `vm:control` 执行 | `ui:slot` |
|
||||
| `settings` | 读写本插件的应用级与按 VM 设置 | 无(限本插件) |
|
||||
| `storage` | 本插件私有键值存储,位于 `data/<id>/`,有配额 | `fs:plugin_data` |
|
||||
| `file` | `pick` / `save` 弹出宿主文件对话框,只返回不透明句柄;按句柄分块读写,不暴露路径 | `fs:pick` |
|
||||
| `task` | 开始、更新、结束任务;在宿主任务区显示进度并可取消 | `task:progress` |
|
||||
| `net` | `fetch` 经宿主代理发出(iframe 自身 `connect-src 'none'`) | `net:<origin>` |
|
||||
| `events` | 订阅主题与语种变化、视图可见性、任务事件 | 无 |
|
||||
|
||||
大对象分块传输,单条消息设大小上限。宿主以 `/plugin-ui-kit/<uiApi>/` 提供界面套件(令牌样式表与常用控件样式),主题或语种变化时经 bridge 推送新令牌,插件界面因此与宿主外观一致,不必自带一套设计系统。
|
||||
|
||||
---
|
||||
|
||||
## 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` 及任意 BCP-47 扩展键),**无需执行插件代码即可读取** |
|
||||
| `l10n` | 可选的包内私有词表目录(如 `"locales"`),存放 `<locale>.json` 供插件自身 UI、iframe 面板与 Sidecar 使用;独立语言包可通过 `pluginOverrides` 在外部补充或覆盖任意第三方插件的清单字段与私有词条 |
|
||||
| `publisher` / `license` / `homepage` | 来源与许可,市场审核依据 |
|
||||
| `engines` | `reims-go` 版本范围,以及所依赖契约面的范围:`pluginApi`、`uiApi`(主题与面板样式)、`bridgeApi`(视图与面板);**下载前与激活前预检**(§6.3) |
|
||||
| `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、补丁清单与哈希、源码包文件名 |
|
||||
|
||||
### 6.3 契约版本与演进规则
|
||||
|
||||
公开契约分三个版本面,各自按 SemVer 演进,插件在 `engines` 中声明依赖范围:
|
||||
|
||||
| 版本面 | 范围 |
|
||||
| :--- | :--- |
|
||||
| `pluginApi` | 清单字段、扩展点、Hook 事件与载荷、权限名、Sidecar JSON-RPC 协议 |
|
||||
| `uiApi` | 主题可依赖的界面契约:令牌、部件、状态属性、槽位目录、图层、布局选项、图标名、UI SDK |
|
||||
| `bridgeApi` | 视图与面板的消息协议(§5.6) |
|
||||
|
||||
- **契约先于生态定全**:扩展点、槽位目录、视图位置与 bridge 方法在第三方插件依赖它们之前一次定全。目前生态只有语言包(只依赖 `pluginApi`),`uiApi` 与 `bridgeApi` 在首个第三方主题或界面插件出现前定稿为 `uiApi` 2.0 与 `bridgeApi` 1.0,定稿前可做不兼容清理。
|
||||
- **公开即实现**:每个公开的扩展点、槽位、视图位置、图层与 bridge 方法在发布前都要有宿主实现和契约测试。前端构建检查每个槽位、视图位置与图层都被渲染;Go 测试检查每个扩展点都有消费者。尚未落地的项标为实验性:清单校验接受它,`plugin doctor` 警告,不受兼容承诺约束,市场不允许稳定版插件依赖它;某项在实现它的同一次变更中转为稳定。哪些项仍是实验性,以契约文件为准:`frontend/src/styles/ui-contract.ts`、`frontend/src/lib/bridgeContract.ts` 与 `internal/plugin/contract.go`(构建产物 `ui-contract.json`、`bridge-contract.json` 中的 `experimental` 部分),Go 测试保证三者一致,新增的 `contributes` 字段必须先在目录中登记状态。
|
||||
- **主版本内只增不改**:新增字段一律可选,缺省时保持旧行为;新增枚举值(事件、视图位置、bridge 方法)只投递给声明了相应次版本的插件。改名、删除或改变语义只在主版本发生。
|
||||
- **按特性协商,不按版本号猜**:宿主在 Sidecar 握手、bridge 握手与 UI SDK 中下发 `features` 列表(如 `view.sidebar`、`bridge.file.pick`、`layer.overlay`),插件据此降级。
|
||||
- **未知字段**:宿主忽略清单中的未知字段并由 `plugin doctor` 警告,插件因此可以使用新字段同时兼容旧宿主;`engines` 下限高于宿主版本时拒绝安装与激活。
|
||||
- **命名空间**:`builtin.*` 插件 id、`rg-` 前缀的类名、`data-rg-` 属性与契约令牌归宿主;主题自定义的 CSS 变量使用 `--theme-` 前缀(视图与面板在各自 iframe 内,不受此限);命令 id 由宿主自动加上插件 id 前缀。
|
||||
- **弃用**:先在至少一个次版本中给出 `plugin doctor` 警告与替代项,下一个主版本再删除;契约文件(`ui-contract.json`、bridge 类型定义)随版本发布,作者可在本地校验。
|
||||
|
||||
---
|
||||
|
||||
## 7. 权限、信任与安全边界
|
||||
|
||||
### 7.1 权限分级
|
||||
|
||||
| 等级 | 权限 | 审批 |
|
||||
| :--- | :--- | :--- |
|
||||
| **低** | `vm:read`(通用模型,不含敏感字段)、`ui:notify`、`task:progress`、`fs:plugin_data`、`log:read` | 启用时展示说明 |
|
||||
| **中** | `vm:intent`、`runtime:source`、`net:<origin>`(经宿主代理发出)、`ui:slot`、`input:filter`(声明输入过滤规则)、`fs:pick`(经宿主文件对话框读写用户选中的文件) | 首次启用逐项确认 |
|
||||
| **高** | `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`(本地链接,需开启开发者模式)。`official` / `verified` 有两个来源:一是包内 ed25519 签名与内置密钥匹配;二是包从项目自有市场索引安装,该索引在本次会话经 HTTPS 从内置地址拉取(非过期缓存),且包的 SHA-256 与索引条目一致,此时沿用索引标注的等级。经 `REIMS_GO_PLUGIN_MARKET_URL` 指向的第三方索引不能担保信任,其条目在市场中一律显示为 `community`。其余情况为 `community`(仅哈希)。
|
||||
- 信任等级只用于标识来源,不豁免任何检查:所有安装包(含 `official`)都走同一套静态安全扫描、高危权限审批与 L3 可执行文件哈希确认;只有内置与随主程序附带的插件预先批准。
|
||||
- 以 AppContainer 或低完整性级别运行 Sidecar 作为后续增强项评估。
|
||||
|
||||
### 7.3 UI 与本地接口安全
|
||||
|
||||
- 插件资源经 Wails AssetServer 的独立路由提供,路径带每次运行随机生成的令牌,校验目录穿越,附 `X-Content-Type-Options: nosniff` 与 CSP;SVG 一律禁脚本。
|
||||
- iframe 视图与面板:`sandbox="allow-scripts"`(不加 `allow-same-origin`、`allow-popups`、`allow-top-navigation`)、`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` 版本、能力、当前生效语种(`locale` / `fallbackChain`)及合并后的插件私有词表(`l10nBundle`),运行期切换界面语言时向已运行 Sidecar 广播 `plugin/localeChanged` 通知(不唤醒休眠进程);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` 与预期一致(防偷换)→ 兼容预检 → 静态安全门禁(拦截 L1/L4 夹带可执行/系统脚本、L3 未声明二进制、SVG 主动脚本、`ui:script` 宿主逃逸或未声明联网、市场红线)→ 原子 rename 到 `pkgs/<id>/<version>` → 提交 `state.json`。任一步失败都不改变现状。对 L3 原生程序不声称“代码扫描安全”,仅核对清单完整性与 SHA-256 并向用户如实展示完整当前 Windows 账户权限说明。
|
||||
- **市场索引与软撤回**:独立仓库发布轻量静态 `index.json`(二进制包托管在 GitHub Releases,复用运行时下载与代理逻辑;可通过 `REIMS_GO_PLUGIN_MARKET_URL` 配置镜像或 `off` 强制离线),含版本、`engines`、`platforms`、下载地址、SHA-256、签名者与软撤回列表(`withdrawn`,阻止新装并对存量用户展示替代建议);首次打开市场或执行市场 CLI 命令时惰性拉取;唯一例外是首次启动设置页:系统语言不被内置 zh-CN / en-US 覆盖时,按系统语言查一次索引,若有匹配的语言包,就在设置页提供「同时安装」选项(默认勾选,选好数据目录后安装并启用)。索引条目可用 `locales` 显式声明语言包提供的语言,未声明时按标签与名称译文推断。使用内存 + `<DataRoot>/plugins/index-cache.json` 双层缓存与主程序内嵌兜底副本,网络失败不覆写有效缓存。
|
||||
- **更新与回滚**:新旧版本并存、切换指针,保留最近若干版本;插件同样区分 `alpha` / `stable` 通道,默认只取 `stable`。
|
||||
- **安全模式**:`reims-go --safe-mode` 跳过全部第三方插件,界面顶部显示横幅与插件管理入口;以启动哨兵文件检测上次插件初始化阶段异常退出,下次启动询问是否进入安全模式。
|
||||
- **市场红线**:拒收含 Apple 专有文件、SMBIOS 真值或闭源固件的包;运行时包必须附源码与许可证。
|
||||
|
||||
---
|
||||
|
||||
## 10. GUI 与 CLI 接入
|
||||
|
||||
| 入口 | 内容 |
|
||||
| :--- | :--- |
|
||||
| CLI | `reims-go plugin list / search / install <zip\|id> / update [id] / pack <dir> / link <dir> / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor [--json] [dir\|zip\|id] / locale <init\|check> / 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. 分阶段演进与验收标准
|
||||
|
||||
从现有代码走到这里所述的客体驱动形态、并将 macOS 外置为插件的具体路径,见 [guest-plugin-migration.md](guest-plugin-migration.md)。
|
||||
|
||||
```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** | 签名体系与市场索引、`uiApi` 2.0 与 `bridgeApi` 1.0 定稿(§5.1、§5.6、§6.3)、iframe 视图与面板、交互主题 UI SDK、按需引入 L2 脚本宿主 | 契约检查覆盖全部槽位、视图位置、图层与 bridge 方法,无「可声明但不渲染」项;第三方插件经审核上架;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,117 +33,100 @@ 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\`)
|
||||
运行时仓库的 [`stage-runtime-binaries.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/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 alpha` 一次产出三个文件:运行时包、对应源码包 `reims-runtime-src-<commit>.tar.zst`、覆盖两者的 `SHA256SUMS.txt`。补丁按 `patches/series.txt` 的顺序取,`-Patches` 可以只列实际打上的那几个。
|
||||
- **打包前的检查**:脚本先核对每个补丁是否与构建目录里的 diff 完全一致;不一致、或者构建目录里有补丁没涉及的文件被改动,就直接停止,不会自动修改补丁。允许改动的文件从补丁本身读出(2026-11-28 前写死为 `whpx-all.c`,带上 fiber 补丁就会误报)。
|
||||
- **manifest 版本 2**:比版本 1 多记录 `vendor_qemu_commit`、`util_commit`、`metal2vulkan_commit`、`patches`(名称、作用对象、SHA256)、`channel`、`source_package`。`dll_count` 改为按实际文件统计;版本 1 的统计有误,记为 0。
|
||||
- **发布位置**:运行时发布在 [`Nwflower/reims-go`](https://github.com/Nwflower/reims-go/releases) 的 GitHub Release。tag 为 `runtime-<commit>`,附件就是上面三个文件。GitHub 的预发布对应 `alpha`(2026-11-28 前叫 `candidate`),正式发布对应 `stable`。三个附件缺任何一个,客户端就不会列出这个版本。
|
||||
- **客户端安装**(`internal/runtime/remote.go`):从 GitHub API 列出版本 → 下载运行时包,支持续传 → 对照 `SHA256SUMS.txt` 校验,不一致就丢弃 → 用原有的导入流程解压并激活 → 删除下载的压缩包。
|
||||
- **已发布**:`runtime-3731afd`,先以候选版(即现在的 alpha)发布,同日升为稳定版。实测从 GitHub 下载 169 MB、校验、解压、激活,全程约 75 秒。
|
||||
- **自动化 CI(M4,2026-11-28 改为每日自动构建)**:[`build-runtime.yml`](../.github/workflows/build-runtime.yml) 每天 03:23 UTC 运行,也可手动触发并指定上游 commit。流程:
|
||||
1. 取上游默认分支的 HEAD。已有 `runtime-<commit>` 的 Release(alpha 或 stable)就跳过,所以上游不动时不消耗构建时间。
|
||||
2. 在 `windows-latest` 上用 MSYS2 CLANG64,由 `scripts/apply-patch-series.ps1` 按 `patches/series.txt` 逐个处理补丁:能打上就打;反向检查通过(上游已经包含)就跳过并提醒退役;两者都不行就停止,不改补丁(AGENTS.md 规则 4)。
|
||||
3. 执行上游 `scripts/install-ctl.sh --yes`,再用 `pack-runtime.ps1 -Channel alpha -Patches <实际打上的补丁>` 打包,manifest 只写实际打上的补丁(规则 5)。
|
||||
4. `scripts/check-runtime-alpha.ps1` 做 alpha 准入检查(第 6 节),通过后发布为 GitHub 预发布,附件四个缺一不可。
|
||||
5. 只保留最近 7 个未升级的 alpha 预发布,更早的连同 tag 删除;正式发布不受影响。
|
||||
6. 构建失败、或有补丁已被上游合并时,在本仓库开一个 issue(已有同名的未关闭 issue 就追加评论)。
|
||||
## 3. 打包与 CI 自动构建
|
||||
|
||||
CI 产物只进 `alpha` 通道,不直接发给用户(第 6 节)。注意 GitHub 会在仓库 60 天无活动后停用定时 workflow。
|
||||
- **CI 测不到 Win10**:`windows-latest` 是 Windows Server 2022/2025,复现不了第 5 节的 Win10 问题,而且 GitHub 托管 runner 一般不提供 WHPX。CI 只能保证「能构建、`-device help` 列出 `reims-graphics-pci`」,能不能启动 VM 要靠第 6 节的本机冒烟测试。
|
||||
### 3.1 运行时发布附件
|
||||
运行时仓库的 [`pack-runtime.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/pack-runtime.ps1) 产出以下发布附件。
|
||||
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 源码包,由 [`pack-msys2-sources.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/pack-msys2-sources.ps1) 生成)
|
||||
5. `SHA256SUMS.txt`(覆盖上述压缩包的统一校验清单)
|
||||
|
||||
## 5. 补丁队列(把上游当内核来优化的方式)
|
||||
打包前脚本会核对构建目录的 `git diff` 是否与声明的补丁逐字节一致;存在未声明修改或补丁不匹配时立即停止。
|
||||
|
||||
原则:**不长期维护 fork,补丁数以清零为目标。** 每个补丁都要经过「本地带着发 → 由人向上游提 PR → 上游合并后删掉本地副本」这个周期。
|
||||
### 3.2 每日 CI 构建
|
||||
Reims vGPU fork 的 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) 每日构建,也支持手动指定提交。工作流从运行时仓库读取打包脚本和依赖补丁,在 `windows-latest`(MSYS2 CLANG64)执行以下步骤。
|
||||
1. 读取 Reims vGPU fork 的运行时分支,并检出其中固定的 QEMU fork 提交。若该 Reims vGPU 提交已有运行时 Release,则跳过。
|
||||
2. 按 [`series.txt`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/series.txt) 顺序为固定的依赖版本应用补丁。已合入上游的补丁会跳过并报告,遇到冲突时中止构建。
|
||||
3. 运行 Reims vGPU 源码中的 `scripts/install-ctl.sh --yes` 编译,再调用运行时仓库的打包脚本。
|
||||
4. 运行 [`check-runtime-alpha.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/check-runtime-alpha.ps1) 校验附件哈希、许可证、挂起能力声明,以及在不含 MSYS2 的 `PATH` 下验证 vGPU 设备枚举、CLI 版本和 `qcow2` 创建读取。
|
||||
5. 通过后在 Reims vGPU fork 的 Releases 发布 Preview,标记为 GitHub 预发布(`alpha`)。手动构建可通过 `publish=false` 仅下载 CI 产物进行验证。
|
||||
|
||||
| 补丁 | 作用对象 | 解决的问题 | 状态 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `reims-vgpu-win32-unicode-input.patch` | `reims-vgpu` 的 `crates/reims-vgpu-window`(`native/windows.rs`、`native/sdl_thread/ui.rs`) | SDL3 窗口层未开启 TextInput 且只转发 `0x04..=0xE7` 物理扫描码,导致直接投递 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR` 或宿主机 IME 上屏的文字被吞;通过 `SDL_SetWindowsMessageHook` 仅在设置 `REIMS_GO_INPUT_URL`(仅限 `127.0.0.1`)时异步转发非物理按键字符给宿主机文本注入桥 | 2026-11-28 新增补丁,待编入下一版 alpha 运行时冒烟验证后提 PR |
|
||||
| `reims-vgpu-cargo-lock.patch` | 上游 `reims-vgpu`(`3731afd`)的 `Cargo.lock` | 不改代码。cargo 构建时会给 `metal2vulkan`、`metal2vulkan-air`、`metal2vulkan-runtime` 补上 `source = "git+…metal2vulkan?rev=0b0ac58…"`;带上这个补丁,源码包才和实际构建一致 | 不需要上游 PR;上游 `Cargo.lock` 补齐后删除 |
|
||||
| `qemu-whpx-win10-compat.patch` | `vendor/qemu` 的 `target/i386/whpx/whpx-all.c` | ① `whpx_tsc_deadline_refused()`(`3210-3230`)原实现在真实分区上建、删 vCPU 0,Win10 19045 上随后 `whpx_init_vcpu()` 再次创建 vCPU 0 时必现 `WHvCreateVirtualProcessor` 返回 `E_INVALIDARG`(`hr=80070057`),改为独立临时探测分区;② `whpx_set_registers()`(`534`)直接调用 `WHvResetPartition` 未判空,Win10 19045 的 `WinHvPlatform.dll` 不导出该接口导致重置阶段必现 `0xc0000005 at 0x0` 崩溃(已核对导出表,10 个 supplemental API 中仅此一处漏判空) | 2026-11-28 实测复现并修复,待提交上游 PR(由人操作) |
|
||||
| `qemu-whpx-win10-startup-ipis.patch` | 同上(在前一项之后应用) | Win10 开启内核 irqchip 时转发多核 INIT/SIPI,避免 XNU 从核启动停住 | 已合入补丁队列,客体冷重启待验证,待提交上游 PR |
|
||||
| `qemu-whpx-nested-virt-nonfatal.patch` | 同上(在前两项之后应用) | 部分 Win11 宿主 `WHvSetPartitionProperty(NestedVirtualization)` 返回 `hr=0x80370302`(`WHV_E_UNKNOWN_PROPERTY`)导致 QEMU 在 `whpx-all.c:3479-3483` 直接致命退出,改为非致命警告并清零 `Bank1.NestedVirtSupport`,保留 `kernel-irqchip=on` 内核态 x2APIC 加速 | 2026-11-28 新增补丁,待编入下一版 alpha 运行时并在 Win11 真机冒烟验证后提 PR |
|
||||
| `qemu-win32-coroutine-fiber-commit.patch` | `vendor/qemu` 的 `util/coroutine-windows.c` | 登录 Apple ID 等高并发 VA-API + 磁盘 I/O 场景下,`CreateFiber(1 MiB)` 预先提交整块 1 MiB 协程栈易耗尽 Windows Commit Charge 返回 `NULL`,未判空即调用 `SwitchToFiber(NULL)` 触发 `0xc0000005`(读 `0x0000000000000010`)崩溃;改用 `CreateFiberEx(64 KiB, 1 MiB, 0, ...)` 并将 `NULL` 与 `IsThreadAFiber()` 纳入显式处理 | 2026-11-28 符号化定位并新增补丁,待编入下一版 alpha 运行时实测验证后提 PR |
|
||||
> **CI 边界**:GitHub 托管的 Windows Server runner 不提供 WHPX,也无法复现 Windows 10 兼容性问题。CI 只验证可编译与控制面基本可用,实际能否启动 macOS 桌面必须经过第 5 节的真机冒烟。
|
||||
|
||||
### 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。
|
||||
- 最小 WHP 实验发现,同一从核首次启动并进入 `HLT` 后,第二次由客体发送的 SIPI 超时;经 `WHvRequestInterrupt` 转发可连续启动。[`qemu-whpx-win10-startup-ipis.patch`](../patches/qemu-whpx-win10-startup-ipis.patch) 只在 Win10、内核 irqchip 和多核同时启用时转发 INIT/SIPI。8 核两次冷启动和 12 核冷启动均已进入桌面,x2APIC、FileVault、SSH 和图形登录通过;默认启动及正常关机也通过。客体冷重启仍待验证。
|
||||
2. **Windows 提交内存(Commit Limit)硬拦截**:
|
||||
- 32 GB 物理内存宿主在开启常见软件后,实测可用提交内存(`FreeVirtualMemory`)仅 `14.7 GiB`(即使空闲物理内存仍有 `17.3 GiB`);QEMU 启动时一次性 `CreateFileMapping` 提交全部 Guest RAM,分配 `16G` 直接退出报 `Cannot set up guest memory 'ram': 系统资源不足`。`reims-go` 必须在体检与启动前检测提交内存并动态限位(详见 [`architecture.md`](architecture.md) 3.1 节)。
|
||||
3. **在线 Recovery 拉取 17 GB 极易因 Apple CDN 断流失败**:
|
||||
- 实测拉取 961 MB 恢复镜像期间 Apple CDN 即出现 6 次 `Peer disconnected`;在 Recovery 内经 QEMU 用户态 NAT(`slirp`)拉取 ~17 GB 系统包时,`OSISDownloadOperation` 抗断流能力差,易在接近完成(实测 `disk.qcow2` 已达 `16.95 GiB`)时失败。因此 `reims-go` GUI 默认改为宿主机调用 `reims-util offline-installer --json` 断点续传下载离线安装包(详见 [`architecture.md`](architecture.md) 3.3 节)。
|
||||
4. **登录 Apple ID 后 `SwitchToFiber(NULL)` 崩溃(`0xc0000005`,读 `0x10`)**:
|
||||
- 2026-11-28 对真实崩溃栈在 `runtime-3731afd` 上符号化定位:`whpx_vcpu_run` → `execute_ncq_command`(`hw/ide/ahci.c:1096`)→ `blk_aio_prwv`(`block/block-backend.c:1624`)→ `qemu_aio_coroutine_enter`(`util/qemu-coroutine.c:298`)→ `qemu_coroutine_switch`(`util/coroutine-windows.c:59`)→ `KERNELBASE!SwitchToFiber`(`movq 0x10(%rcx), %rax`)。
|
||||
- 根因是 `util/coroutine-windows.c:78` 调用 `CreateFiber(COROUTINE_STACK_SIZE, ...)` 预提交整块 1 MiB 栈,在 VA-API HEVC 批量解码 + iCloud/AHCI 并发读盘叠加导致 Commit Charge 见底时返回 `NULL`,且未判空直接传给 `SwitchToFiber`。补丁 [`qemu-win32-coroutine-fiber-commit.patch`](../patches/qemu-win32-coroutine-fiber-commit.patch) 改用 `CreateFiberEx(64 KiB, 1 MiB, 0, ...)` 并补齐空指针诊断与 `IsThreadAFiber()` 保护。
|
||||
### 3.3 客户端下载与安装
|
||||
`internal/runtime` 从 `yxc0915/reims-vgpu` 的 GitHub Releases 查找 `runtime-<commit>`。默认列出正式运行时,开启内核 Alpha 后同时列出 Preview。下载沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。
|
||||
|
||||
规则:
|
||||
1. 补丁原文的权威副本放在 `reims-go/patches/`。macos-vm-lab 的那份是研究时的原始记录。
|
||||
2. 每次跟进上游 commit 时,先 `git apply --check`(CI 中由 `scripts/apply-patch-series.ps1` 执行)。打不上就停下,不发布 alpha,不要自动改补丁。
|
||||
3. 补丁文件必须是**无 BOM、LF 行尾**,由 `.gitattributes` 的 `*.patch -text` 保证。用 PowerShell 5.1 的 `Out-File` 或 `>` 生成的补丁会带 BOM 和 CRLF,`git apply` 不认(2026-11-28 实测,原始副本就是这样)。
|
||||
4. 上游合并之后,在表里记下合并 commit,然后删掉补丁。
|
||||
5. `patches/series.txt` 是补丁队列的唯一清单,规定作用对象和应用顺序;CI 和 `pack-runtime.ps1` 都从它读取。加、删补丁只改这个文件和本节的表。
|
||||
---
|
||||
|
||||
## 6. 发布通道(已验证通道)
|
||||
## 4. 补丁队列
|
||||
|
||||
上游变动非常快(2026-11-21 到 11-28 有 100 多个提交,截至 2026-11-28 没有任何 GitHub Release),出现过某个提交弄坏 `reims-ctl` 安装的情况([issue #138](https://github.com/steelbrain/reims-vgpu/issues/138))。所以用户默认拿到的运行时**不跟上游最新 commit**,而是分两级:CI 每天把上游最新 commit 构建成 `alpha`,人从 alpha 中挑一个冒烟通过的升为 `stable`。
|
||||
Reims vGPU 和 QEMU 的修改由各自的 fork 维护。Reims vGPU fork 的 [依赖补丁目录](https://github.com/yxc0915/reims-vgpu/tree/master/packaging/windows-runtime/patches) 保存构建时应用的补丁与维护说明。
|
||||
|
||||
| 通道 | 来源 | 进入条件 |
|
||||
运行时包的 `manifest.json` 记录源码仓库、提交、运行时能力及打包时应用的依赖补丁和哈希。
|
||||
|
||||
---
|
||||
|
||||
## 5. 发布通道(`alpha` → `stable`)
|
||||
|
||||
上游提交频率高且无稳定 Release,默认用户不能直接暴露在未验证的上游 `HEAD` 下。运行时采用两级通道:
|
||||
|
||||
| 通道 | GitHub Release 形态 | 准入条件 |
|
||||
| :--- | :--- | :--- |
|
||||
| `alpha` | CI 每天从上游最新 commit 自动构建并打补丁(2026-11-28 前叫 `candidate`,当时是人工指定 commit) | 由 `scripts/check-runtime-alpha.ps1` 自动检查:能构建;四个附件齐全;`SHA256SUMS.txt` 覆盖三个压缩包且校验一致;manifest 的 commit、通道、补丁与实际一致;在不含 MSYS2 的 PATH 下 `qemu-system-x86_64.exe -device help` 列出 `reims-graphics-pci` |
|
||||
| `stable` | 从 `alpha` 升级 | 在一台真实 Win10 或 Win11 宿主上跑通冒烟测试:`doctor` 的运行时检查全部通过,用 golden 镜像启动到 macOS 桌面,截一张屏,正常关机。由人确认后升级 |
|
||||
| **`alpha`** | 预发布(Pre-release) | 运行时 CI 自动构建并通过 Alpha 准入检查 |
|
||||
| **`stable`** | 正式发布(Release) | 从 `alpha` 晋升。在真实 Windows 10/11 宿主运行 [`smoke-runtime.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/smoke-runtime.ps1),验证纯净目录 `doctor`、启动至 macOS 桌面、截屏与正常关机,经人工确认后晋升 |
|
||||
|
||||
`reims-go` 客户端默认只拉 `stable`,`alpha` 要用户主动打开(界面开关「接收 Alpha 版」,CLI `--alpha`)。旧配置里的 `runtime_channel: "candidate"` 读作 `alpha`,CLI 的 `--candidate` 保留为 `--alpha` 的别名。这层筛选是 `reims-go` 相对于「自己跑上游安装脚本」的主要价值之一。
|
||||
- 客户端默认仅获取 `stable` 通道;`alpha` 需用户在界面开启「接收 Alpha 版」或在 CLI 传入 `--alpha`。
|
||||
- 晋升 `stable` 时,在运行时仓库将已通过冒烟的 Preview 改为正式 Release,并移除标题中的 Alpha 标记。保留原资产、校验清单和 `manifest.json` 的构建通道。
|
||||
|
||||
升级记录:
|
||||
---
|
||||
|
||||
| 运行时 | alpha 发布 | 冒烟测试 | 升为稳定版 |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| `runtime-3731afd` | 2026-11-28 | 真实宿主 Windows 10 19045,启动到 macOS 桌面并正常关机,由人确认通过 | 2026-11-28 |
|
||||
## 6. 许可证与源码分发义务
|
||||
|
||||
升级不重新打包,只把 GitHub Release 从预发布改为正式发布,所以用户拿到的文件与冒烟测试用的完全相同。包内 `manifest.json` 的 `channel` 字段记录的是构建时的通道,会一直是 `alpha`(2026-11-28 前的包是 `candidate`);客户端只看 Release 的发布状态。alpha 预发布只保留最近 7 个,正在冒烟的那个如果被挤出,可以用手动触发重新构建同一 commit。
|
||||
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`)**:由 [`pack-msys2-sources.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/pack-msys2-sources.ps1) 根据本机 pacman 元数据自动筛选全部无宽松替代协议的 GPL / LGPL / MPL 依赖包,下载官方 `.src.tar.zst` 并使用 `gpgv` 与 MSYS2 密钥逐一验签,同时附带 `MSYS2-PACKAGES.txt` 说明全部 DLL 归属与许可。
|
||||
3. **许可证与声明**:运行时包根目录内置 [`NOTICE.md`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/NOTICE.md) 与 `licenses/` 全文。
|
||||
4. **不含 Apple 专有文件**:任何仓库目录或运行时 Release 均不包含 macOS 安装包、恢复镜像、解密固件或 SMC 密钥;系统安装包均由用户端直连 Apple 服务器获取。
|
||||
@@ -0,0 +1,53 @@
|
||||
# PR 变更归属审查
|
||||
|
||||
> 以产生行为的实现为准。先定位改动发生在哪个组件,再决定提交仓库和验证范围。桌面或 CLI 是否有入口,只决定客户端是否也需要改动。
|
||||
|
||||
## 1. 确认归属
|
||||
|
||||
以 PR 实际目标分支与提交的差异为准。使用 GitHub 的「Files changed」或本地 `git diff <base>...<head>`,同时检查生成文件对应的源文件、补丁目标、依赖锁定和 CI 变更。先从用户入口沿调用链找到行为的实现,再按下表归属。
|
||||
|
||||
| 类别 | 行为或改动 | 实现归属 |
|
||||
| :--- | :--- | :--- |
|
||||
| 客户端 | GUI、CLI、虚拟机流程编排、宿主机体检及窗口集成、Guest Tools、运行时下载和安装 | `Reims-Go`。主要入口和模块见[系统架构](architecture.md)。 |
|
||||
| 客户端运行时适配 | 构造命令和环境、调用已发布的 CLI / QMP 接口、解析结果以及处理版本、能力或错误 | `Reims-Go`。生效行为仍由被调用的组件实现。 |
|
||||
| Reims vGPU 内核及控制工具 | `reims-ctl` 的配置、启动与参数语义,`reims-restore` 的恢复流程,Reims 的宿主图形、原生 VM 窗口及输入实现 | [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)。运行时所用改动以 [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu) 的实际构建提交为准。 |
|
||||
| QEMU 虚拟化层 | WHPX / TCG、客体机器与设备模型、`reims-graphics-pci` 的 PCI 设备侧、QMP 命令实现、`qcow2` 格式与迁移机制 | [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)。核对构建提交中的 `vendor/qemu` gitlink 及其来源。 |
|
||||
| 独立上游工具 | `reims-util` 内的引导资源生成、安装镜像处理和工具自身的参数语义 | [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。按运行时锁定的提交定位。 |
|
||||
| 独立图形依赖 | Metal 到 Vulkan 的命令、资源和着色器转换实现 | [`steelbrain/metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。按运行时锁定的提交定位。 |
|
||||
| 其他独立引擎 | 引擎自身的执行、翻译和固件实现 | 对应引擎的源代码仓库。客户端的驱动注册、启动参数适配和状态展示仍归 `Reims-Go`。 |
|
||||
| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`yxc0915/reims-vgpu`](https://github.com/yxc0915/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时规范](portable-runtime-spec.md)。 |
|
||||
|
||||
同一项功能可以涉及多个仓库。窗口安装引导调用已有运行时能力时,浮层、进度和流程编排属于客户端。若同时调整 Reims 原生窗口的事件语义,窗口实现属于 `reims-vgpu`,调用和交互留在客户端。挂起功能同理,GUI / CLI 和任务状态属于客户端,QEMU 的迁移或设备状态实现属于 QEMU;运行时再负责选取具备该能力的版本。
|
||||
|
||||
## 2. 审查客户端独立性
|
||||
|
||||
- **构建与发布**:客户端 CI 仅从 `Reims-Go` 源码检出完成前端构建、Go 检查和应用产物构建。运行时源码、编译工具链和运行时发布产物由运行时仓库管理。客户端自行发布应用,并在虚拟机运行前下载、校验或导入兼容的独立运行时。
|
||||
- **接口边界**:客户端通过约定的子进程接口和协议调用运行时。配置写入沿用 [`reims-ctl set`](design-guidelines.md#2-配置原语)。需要新增命令、参数、字段或能力时,在负责组件实现,并在客户端附上对应接口证据。
|
||||
- **运行时兼容**:客户端 PR 写明验证使用的运行时与最低要求。若依赖新能力,优先使用运行时明确声明的能力或版本,在旧版、缺失运行时和不支持该能力的场景下明确禁用、提示或保留既有流程。客户端合入与运行时发布各自按其流程验收,用户默认仍走受支持的 `stable` 通道。
|
||||
- **跨仓交付**:按归属拆分 PR。客户端 PR 链接底层 PR、提交或运行时版本,列出合并顺序和兼容路径。临时依赖补丁由运行时仓库记录,注明目标仓库、适用提交和退役条件。跨仓定位以源码、依赖锁定和产物清单为证据。
|
||||
|
||||
## 3. PR 描述与合并检查
|
||||
|
||||
提交者在 PR 描述中附上以下信息。纯文档或纯客户端改动可将无关字段写为「不适用」。
|
||||
|
||||
```markdown
|
||||
## 变更归属
|
||||
|
||||
- 用户可见行为
|
||||
- 变更位置与责任仓库
|
||||
- 上游证据(仓库、commit、文件及行号)
|
||||
- 跨仓依赖(关联 PR、合并顺序、运行时要求)
|
||||
- 旧版或缺失运行时的表现
|
||||
|
||||
## 验证
|
||||
|
||||
- 已通过的检查及运行时版本
|
||||
- 待验证场景及其影响
|
||||
```
|
||||
|
||||
审查者在合并前核对以下各项。
|
||||
|
||||
- [ ] 差异中的客户端、内核、独立依赖和分发变更均已注明归属。跨仓实现已拆分并可追溯。
|
||||
- [ ] 客户端能独立通过其 CI。行为变更已按影响验证 GUI、CLI 或两者的正常入口。
|
||||
- [ ] 底层或打包改动有负责仓库的验证证据。涉及运行时发布时,核对 `manifest.json` 中的来源提交、补丁与能力声明,以及相应的 [`alpha` 准入与 `stable` 冒烟要求](portable-runtime-spec.md#5-发布通道alpha--stable)。
|
||||
- [ ] 上游行为已定位到对应提交和源码行号。真机或兼容性覆盖不足的场景标明「待验证」,合并前明确其对客户端发布和能力开放的影响。
|
||||
@@ -1,266 +1,76 @@
|
||||
# 开发路线图与里程碑(Roadmap)
|
||||
# 路线图(Roadmap)
|
||||
|
||||
> 原则:先打通“最小可用闭环”(本地打包便携运行时 → Go 核心驱动 → Wails GUI),再扩展自动化与 CI 自动发版。每个里程碑均有明确的可验证验收标准(DoD)。
|
||||
>
|
||||
> 后续规划从用户任务出发:先让用户装得上、用得稳、改坏了能恢复,再减少开发工作流中的手工步骤。功能数量、参数覆盖率和竞品对标不单独构成立项理由。
|
||||
> Reims-Go 的规划从真实用户任务出发:先让用户在 Windows 上顺畅装到桌面、稳定用于日常开发、改坏环境可回退,再按需补齐进阶开发工作流。
|
||||
|
||||
## 规划与验收口径
|
||||
## 口径说明
|
||||
|
||||
- **[x] 只表示代码或脚本已经实现**,不自动表示已进入公开 Release,也不代表真机验收通过;是否达成 DoD 以各里程碑的状态说明和实测记录为准。
|
||||
- **已发布**:用户能从公开 `stable` Release 获得,且应用、运行时、manifest、补丁与源码包描述一致。
|
||||
- **已验收**:在记录清楚的 Windows、GPU、运行时和 macOS 版本组合上完成真实用户任务,并留下可复核结果;单元测试或 CI 构建成功不能代替这一步。
|
||||
- **后续条目必须先回答**:服务哪类用户、解决哪一步阻塞、现有替代办法是什么、怎样验收、失败如何恢复。没有这些内容的点子留在候选池,不占版本计划。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M0["M0 便携包与环境验证\n(2–3 天)"] --> M1["M1 Go 核心层与 CLI\n(1 周)"]
|
||||
M1 --> M2["M2 Wails 桌面 GUI MVP\n(1–2 周)"]
|
||||
M2 --> M3["M3 硬件调优与 CoW/QMP\n(1–2 周)"]
|
||||
M3 --> M4["M4 CI 自动构建与发版"]
|
||||
M4 --> M5["M5 macOS 日常主力体验\n(v0.2.2+)"]
|
||||
```
|
||||
- **已实现**:代码或脚本已合并进主分支并随版本发布,不代表已覆盖所有 Windows 版本、显卡和 macOS 版本的真机组合。
|
||||
- **真机验收**:需要在明确记录的 Windows、GPU、运行时和 macOS 组合上完成端到端任务验证;单元测试和 CI 编译通过不替代真机验证。
|
||||
|
||||
---
|
||||
|
||||
## M0:便携运行时打包与纯净验证
|
||||
## 已实现能力(截至 v0.2.6)
|
||||
|
||||
**目标**:把本机已验证可用的 `reims-vgpu` 产出一份标准、可复现、可校验的便携运行时压缩包,并在纯净目录中验证完整建机/启动闭环。
|
||||
### 1. 免编译与环境初始化
|
||||
- **便携运行时体系**:剥离 MSYS2 / Rust / 源码仓库依赖,支持 GitHub Release(含系统代理)在线下载、断点续传、SHA-256 校验、原子切换与本地 `.tar.zst` 导入。
|
||||
- **宿主机体检与引导**:免提权检测 WHPX(缺失时支持 UAC 一键开启)、物理与可用提交内存预检、Vulkan 独立显卡识别、大小核(P/E/LP-E)拓扑与处理器计划检查、数据盘总线类型风险提示。
|
||||
- **统一发布物**:桌面界面与命令行共用单个 `reims-go.exe`,支持浅色/深色外观与中英双语。
|
||||
|
||||
- [x] **M0.0**:把 Win10 补丁的来龙去脉记清楚:在 `vendor/qemu` 里 `git diff` 与 `patches/qemu-whpx-win10-compat.patch` 比对一致;并在 `patches/README.md` 与 `docs/upstream-pr-prep.md` 归档复现与修复证据。
|
||||
- [x] **M0.1**:编写 `scripts/pack-runtime.ps1`,从本地 `reims-vgpu` 安装产物打包 `reims-runtime-win-x64-<commit>.tar.zst`、`manifest.json`(含 SHA256、`vendor/qemu` commit、补丁清单与哈希)、`patches/`、`NOTICE.md` 与 `licenses/`,并附 `pack-msys2-sources.ps1` 打包对应 MSYS2 copyleft 源码。
|
||||
- [x] **M0.2**:在独立路径解压并发布稳定版运行时 `runtime-3731afd`,验证在不依赖 MSYS2 / Rust / 源码仓库的条件下可正常 `list --json`、`doctor` 并拉起 macOS 桌面。
|
||||
- [x] **M0.3**:初始化 `go.mod` 与 Wails v2 工具链并完成可执行文件构建。
|
||||
### 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 任务稳定前不堆砌新子系统。
|
||||
|
||||
- [x] **M1.1**:`internal/config` + `internal/i18n` — 实现配置持久化(`locale: zh-CN | en-US`、`data_root`)与双语消息字典;`internal/host` 实现 Windows 原生体检(`*_windows.go`:含 WHPX、**物理内存与可用提交内存 `FreeVirtualMemory` 安全档位推荐**、Vulkan ICD、三层 P/E/LP-E 核拓扑、磁盘总线类型探测)与非 Windows 桩(`*_other.go`)。
|
||||
- [x] **M1.2**:`internal/runtime` — 实现便携运行时导入(本地 `.tar.zst` 与 HTTP 下载)、SHA256 校验、原子解压、版本切换与子进程环境变量构造(`XDG_*` + `REIMS_CTL_QEMU`)。
|
||||
- 2026-11-28:补上在线安装,运行时从本仓库的 GitHub Release 下载(`runtime-<commit>` tag,alpha 和稳定版两个通道;alpha 在 2026-11-28 前叫候选版),支持续传,并对照 `SHA256SUMS.txt` 校验。CLI 用 `reims-go runtime available` 和 `reims-go runtime fetch [commit]`;界面在宿主页和首次启动页。细节见 `portable-runtime-spec.md` 第 4 节。
|
||||
- [x] **M1.3**:`internal/installer` — 封装 `reims-util offline-installer list --json`、`reims-util offline-installer <ver> -o <DataRoot>\data\reims-ctl\installers --json` 与 `reims-ctl downloads`:实现结构化 JSON 进度流解析、取消/断点续传与缓存清理。
|
||||
- 2026-11-28 完成。
|
||||
- CLI:`reims-go installer list | download <版本> | cached | delete <文件名>`。
|
||||
- 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` 字段(代码按可选处理)。
|
||||
- [x] **M1.4**:`internal/driver/reims` — 封装 `reims-ctl` 的 `list --json`、`show`、`create`、`start`、`stop`、`set`、`insert`、`eject`、`update-opencore`、`delete`、`logs`、`downloads` 与 `qemu-img` 转换/CoW 派生,带单元测试。
|
||||
- [x] **M1.5**:命令行模式(2026-11-28 起从 `cmd/reims-go` 移到 `internal/cli`,并入 `reims-go.exe`)— 提供 `doctor`、`runtime available/fetch/install/list/use`、`installer list/download/cached/delete`、`vm list/create/set/start/stop/eject/type`、`version` 子命令,支持 `--lang zh-CN|en-US` 与中英双语输出。
|
||||
### 1. 首次装机与发版闭环
|
||||
- 在运行时仓库的 [Preview CI](https://github.com/yxc0915/reims-vgpu/actions/workflows/runtime-preview.yml) 验证公开资产的 `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`。跟踪明细见[运行时补丁文档](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md)。
|
||||
- 推动当前本地兼容性补丁上游化,并逐步清零 `patches/` 队列。
|
||||
- 在真实宿主完成长时间开发负载验证(编译、浏览器、多任务、图文剪贴板、WebDAV 挂载、Windows 盘符只读共享、音频/麦克风与休眠唤醒恢复)。
|
||||
- 修复 WebDAV 共享目录可经 Junction 逃逸的路径校验缺陷,并把共享目录与只读盘统一到基于 `os.Root` 的路径安全层;随后按测量结果推进小文件 I/O 优化。
|
||||
|
||||
### 3. 恢复点与磁盘操作可靠性
|
||||
- 对停机恢复点(创建/回滚/删除)、CoW 派生启动、大容量 VMDK 转换以及停机扩容/空间回收完成真机中断与边界测试,确保空间不足或中途中断不会破坏原盘与 backing file 链。
|
||||
- 补充数据目录离线备份与迁移说明(明确快照不等于跨盘备份)。
|
||||
|
||||
---
|
||||
|
||||
## M2:Wails 桌面 GUI MVP(一站式开箱体验)
|
||||
## 下一步计划(P1)
|
||||
|
||||
**目标**:做成真正给普通开发者/自己点几下就能用的轻量桌面应用。
|
||||
|
||||
- [x] **M2.1**:**首次启动向导(中英双语实时切换)** — 自动识别系统语言(支持切换 `中文 / English`);引导选择非 C 盘数据目录(外置盘风险提示)、展示环境体检(WHPX 一键提权启用、Vulkan 显卡、提交内存推荐值)并一键在线安装/导入便携运行时。
|
||||
- [x] **M2.2**:**离线安装包下载管理器(核心体验)** — 调用 `reims-util --json` 展示可选 macOS Tahoe 精确版本,在 GUI 内直接触发宿主机直连下载、实时显示进度条 / 速率 / 已下体积 / 自动重试状态、支持「暂停/取消」与「断点续传」,并可视化管理 `<DataRoot>\data\reims-ctl\installers` 缓存。
|
||||
- 2026-11-28(v0.2):侧边栏新增「安装包」页。上半部分是已下载的安装包:可以继续未下载完的、删除(两步确认,删除走 `reims-ctl downloads delete`)。下半部分是 Apple 提供的版本:下载、进度、暂停。下载前检查剩余空间(按安装包大小加 10% 计,因为一开始就会占满整个镜像的空间)。速率显示在进度的悬停提示里。暂停后再次下载会接着下。
|
||||
- [x] **M2.3**:**VM 主面板与创建/装机引导(贴合简体中文 / 英文 macOS 界面术语)** — 实例列表、实时状态、一键启停与串口/图形日志抽屉;新建默认推荐复用本地离线包 + 默认 `NVMe` 磁盘控制器,启动前校验提交内存;离线安装通过纯 Go HFS+ 辅助盘 `REIMSHELP` 自动绕过 macOS 26.7.3 缺 `pkgutil` / `installer -target` 失效,支持空白盘自动 APFS 抹盘 + QMP 一键键入;提供对称的「进入/退出恢复模式」切换与约 1 GB 在线恢复镜像兜底拉取。
|
||||
- [x] **M2.4**:打包为单文件 `reims-go.exe`(~13.3 MB)。无代码签名,冷启动时间待量化实测。
|
||||
- 2026-11-28:不再单独发布命令行版 `reims-go-cli.exe`,命令行模式并入同一个 exe:带子命令即走命令行;`vm start` 把启动交给界面进程(没在运行就以 `--background` 拉起到托盘),因此命令行启动的 VM 也有剪贴板、共享目录和 Win10 冷重启。细节见 [`architecture.md`](architecture.md) 3.5 节。
|
||||
- [x] **M2.5**:**设置面板(对齐 macOS)** — 按 [`shell-design.md`](shell-design.md) 类别分页;VM 运行中可改并标出生效时机;保存前在 Go 侧校验提交内存与 ICD,写入仅走 `reims-ctl set`。
|
||||
- [x] **M2.6**:**待生效修改** — 详情页列出「已保存、下次启动才生效」的修改并提供「重启以应用」按钮。
|
||||
- [x] **M2.7**:**主窗口结构** — 侧边栏 + 详情 + 工具栏,分步新建助手并在最后一步预览完整 `reims-ctl` 命令。
|
||||
|
||||
**DoD**:
|
||||
- 双击 `reims-go.exe` 即可走完「体检 → 导入运行时 → GUI 断点续传下载离线安装包 → 创建/启动 VM → 离线装完并退出恢复模式」全流程,无需打开命令行。
|
||||
- VM 运行中修改 CPU / 内存 / 显示器数量并保存,重启后 `reims-ctl show` 显示新值;非法输入(如内存超过宿主可用提交内存、ICD 文件不存在)在保存前被拦下。
|
||||
- **可测量的时间目标**:从首次双击到出现 macOS 安装界面 ≤ 10 分钟(不计入开启 WHPX 重启、运行时下载与 Apple 安装包下载)。macOS 离线安装第二阶段耗时受宿主磁盘与 `kernel-irqchip` 影响,继续实测记录。
|
||||
### 开发者网络与工作流增强
|
||||
- 支持自定义多条宿客 TCP 端口转发(含端口冲突检测),无需手写 `--extra-args`。
|
||||
- 在 Guest Tools 中提供可选的宿主机代理快捷开关(显式开启、一键清除),方便客体内的 Homebrew / Xcode / npm 下载。
|
||||
|
||||
---
|
||||
|
||||
## M3:硬件自动调优、宿客互通与开发者进阶能力
|
||||
## 按需评估
|
||||
|
||||
**目标**:补齐硬件调优、宿客互通、安全边界与工程化能力。M3 的功能随 v0.2.1 发布。
|
||||
以下能力仅在有明确场景和可验证方案后才进入版本排期:
|
||||
|
||||
- [x] **M3.1**:**三层大小核防超售绑核与 WHPX 兼容自愈** — 识别三层混合架构(P + E + LP-E,如 Intel Core Ultra 200 无超线程 CPU),`vCPU < P 核逻辑线程数` 时绑 P 核,超出时自动改绑 `P + E`(仅排除慢速 LP-E 核)避免自旋锁超售卡顿;自动探测 Win11 `hr=0x80370302` 嵌套虚拟化属性并预置/补丁化处理;新建 VM 默认 `NVMe` 控制器。
|
||||
- [x] **M3.2**:**安全 AF_UNIX QMP 通道与键入** — Win10 冷重启辅助 QMP 通道已迁至 Windows `AF_UNIX` 套接字(杜绝 SLIRP 下 `10.0.2.2:<port>` 宿主机逃逸风险,自动清理旧 TCP 参数);已基于 `reims-ctl` 的 `qmp.sock` 实现 QMP 键盘一键键入。后续按需补齐优雅关机增强与 QMP 截屏。
|
||||
- [x] **M3.3**:**安全鉴权 Guest Tools(双向剪贴板 + 共享目录)** — 内置仅监听 `127.0.0.1` 的纯 Go HTTP 宿客桥接(每台 VM 独立 256-bit 随机 Bearer Token + 严格共享目录路径隔离),通过纯 Go HFS+ 辅助盘 `REIMSTOOLS` 一键安装免 Xcode/Python 的 macOS LaunchAgent,支持双向 UTF-8 剪贴板与 `~/Desktop/ReimsShare` ↔ `<DataRoot>/shared/<vm>` 双向文件同步。**(macOS 桌面端真机联调待验证)**
|
||||
- [x] **M3.4**:**退出恢复模式自动升级 `NVMe` + 存储/内存性能诊断** — 对旧 `AHCI` VM 在退出恢复模式时自动切至 `NVMe`,并在 VM 主页提供一键升级按钮;自动检测外置 USB/网络盘(`GetDriveTypeW` + `IOCTL_STORAGE_QUERY_PROPERTY` `BusTypeUsb`)与高内存负载(≥ 85%)并展示可操作提示。
|
||||
- [x] **M3.5**:**一键导出脱敏排障日志包(`.zip`)** — 收集体检报告、运行时清单、VM 配置、自动脱敏(序列号/MAC/SMC OSK/Bearer Token)的 QEMU、串口与应用日志,一键导出到 `<DataRoot>/reports/` 并定位目录(已通过单测验证零敏感信息泄漏)。
|
||||
- [x] **M3.6**:**磁盘导入增强(VMDK / RAW 自动转 qcow2)** — 复用便携运行时内置 `qemu-img convert`,新建向导支持直接选择 `.vmdk` / `.raw` 并自动转为 `.qcow2` 导入。**(真机大容量 VMDK 转换待验证)**
|
||||
- [x] **M3.7**:**Golden Image 与 CoW 秒级派生** — 已停止的已装系统 VM 支持在「更多」里通过 `qemu-img create -f qcow2 -b <golden> -F qcow2` + `reims-ctl create --disk --disk-mode in-place` 秒级派生独立身份副本,原盘只读不改。**(真机 CoW 派生启动待验证)**
|
||||
|
||||
**DoD**:
|
||||
- 三层大小核防超售绑核、`AF_UNIX` QMP、Guest Tools 剪贴板与共享目录、CoW 派生在真实宿主均有实测通过记录。
|
||||
|
||||
**状态**:功能都已实现,但 DoD 还没达成。M3.3(Guest Tools 真机联调)、M3.6(大容量 VMDK 转换)、M3.7(CoW 派生启动)还没有真机实测记录。
|
||||
|
||||
---
|
||||
|
||||
## M4:上游性能/窗口跟进与 CI 自动发布
|
||||
|
||||
**目标**:自动化跟进上游 Windows 性能与窗口体验改进,建立 `alpha` → `stable` 冒烟发布闭环。
|
||||
|
||||
- [ ] **M4.1**:**上游窗口与性能 PR 跟进(运行时升级,持续跟踪)** — 已建立跟踪清单 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md),跟踪上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 关键 Windows PR(`#153`、`#152`、`#107`、`#123`、`#172` 与 Win→Command)合入后由 `build-runtime.yml` 的每日构建自动产出 `alpha` 运行时。
|
||||
- [x] **M4.2**:编写 GitHub Actions workflow([ci.yml](../.github/workflows/ci.yml) + [build-runtime.yml](../.github/workflows/build-runtime.yml)):CI 自动先构建前端再跑 `go test` / `go vet` 并编译 CLI 与 GUI;运行时构建 workflow 每天从上游最新 commit 自动构建(2026-11-28 起;已发布过的 commit 跳过),在 `windows-latest` 上通过 MSYS2 CLANG64 拉取 `vendor/qemu`、按 `patches/series.txt` 应用补丁(已被上游合并的跳过并开 issue 提醒,冲突就停止)、调用上游 `scripts/install-ctl.sh --yes`、执行 `scripts/pack-runtime.ps1`,经 `scripts/check-runtime-alpha.ps1` 准入检查后发布 `alpha` 预发布包与对应源码包,并只保留最近 7 个 alpha。**(GitHub Actions 运行时编译待首次手动触发实跑验证)**
|
||||
- [x] **M4.3**:**`alpha` → `stable` 冒烟脚本** — 已编写 [scripts/smoke-runtime.ps1](../scripts/smoke-runtime.ps1),支持校验 SHA-256、在干净隔离目录(无 MSYS2 PATH)解压并跑 `reims-ctl doctor` / `list --json` 与合规文件核查,产出供人工评审的 Markdown 冒烟报告。
|
||||
- [x] **M4.4**:**客户端自动发布与在线更新检查** — 已新增 [.github/workflows/release.yml](../.github/workflows/release.yml)(打 `v*` tag 自动跑测、构建 `reims-go-<tag>-windows-amd64.exe` + `SHA256SUMS.txt`(2026-11-28 前还附带 `reims-go-cli-<tag>-windows-amd64.exe`) 并发布 GitHub Release);客户端与 CLI 接入 `internal/version` 版本号与稳定版在线更新检查(`HostView` 一键检查/跳转下载,运行时支持多版本回滚切换);合规文件(`NOTICE.md`、`LICENSE`、运行时源码包与 `MSYS2-PACKAGES.txt`)已随构建脚本落盘。
|
||||
- [ ] **M4.5**:**补丁上游化(人工提交 PR)** — 已在 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md) 整理好 4 个 QEMU 补丁的根因、复现步骤与实测证据,待人工向上游提 PR 并合入后从 `patches/` 队列清零。
|
||||
|
||||
**DoD**:
|
||||
- 触发一次 tag/手动 workflow 即可产出完整的 `alpha`(App + Runtime + SHA256 + 源码包);冒烟通过并经人确认后升为 `stable`;在干净目录下载 `stable` 后,按 M2 的时间目标跑通。
|
||||
|
||||
**状态**:客户端 Release(`release.yml`)已随 v0.2.1 跑通;运行时构建(`build-runtime.yml`)还没在 GitHub Actions 上实跑过,所以 DoD 还没达成。
|
||||
|
||||
---
|
||||
|
||||
## M5(v0.2.2+):macOS 日常主力体验与性能优化
|
||||
|
||||
**目标**:让 macOS 虚拟机真正脱离「仅供测试与点亮」,在图形/磁盘性能、窗口与键鼠直觉、宿客无缝协作和长期运维安全性上达到可作为日常主力/开发机使用的水准。本阶段优先验收已有能力;除“可反悔的停机快照”外,不因竞品具有类似功能就新增独立子系统。
|
||||
|
||||
### 核心体验的实现与跟进清单
|
||||
|
||||
- [ ] **M5.1(上游运行时联动)**:**沉浸全屏、无黑边缩放与 GPU 性能升级**
|
||||
- 本仓已完成:VM 详情页与设置页/新建向导补齐「无边框全屏启动」一键开关(走 `reims-ctl set --borderless`,支持运行中变更进入待生效列表)与 `Ctrl+Alt+Enter` / `Ctrl+Alt+G` 热切快捷键提示条;
|
||||
- 待上游跟进:待 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md) 中上游 `reims-vgpu` PR 合入后由 `build-runtime.yml` 产出新 `alpha`,冒烟后升为 `stable`:`#123`(`Ctrl+Alt+Enter` 运行中热切全屏)、`#172`(Windows 拖动窗口动态贴合、消除黑边)、`#152`(原生 Windows Vulkan 后端)、`#153`(NVIDIA MAILBOX/FIFO 首帧优化)、`#107`(采样纹理回读就地消费)。
|
||||
- [ ] **M5.2(本仓 + 上游)**:**HiDPI 智能推荐与 Mac 键位习惯适配**
|
||||
- 本仓已完成:`internal/host` 新增原生 Windows 物理显示器与 DPI 缩放探测(`EnumDisplayMonitors` + `EnumDisplaySettingsW` + `GetDpiForMonitor`),按主屏分辨率与 DPI 缩放自动推荐 1× / 2× HiDPI 预设(2K/2.5K/4K/16:10),并在宿主页、新建向导第 4 步与设置页展示智能推荐与多屏引导;设置页键盘分类补齐 Mac 键位提示;
|
||||
- 待验证:自由指针模式下 `Win` 键映射 macOS `Command`(优先随上游 PR 落地,避免维护私有分叉)。
|
||||
- [x] **M5.3(本仓)**:**Guest Tools 2.0(图片剪贴板 + 真挂载式共享目录)**
|
||||
- 剪贴板 2.0:Windows 端支持原生 `"PNG"` 与 32-bit `CF_DIB` 双向图片剪贴板编解码(纯 Go,零外部依赖),服务端基于 `GetClipboardSequenceNumber()` 实现低延迟长轮询事件唤醒(`?since=&wait=&accept=image`),Guest POSIX 脚本使用 macOS 原生 `osascript` + `sips` 实现零 Xcode/Python 的文本 + PNG 截图双向剪贴板;
|
||||
- 共享目录 2.0:在 `reims-go` 内置仅监听 `127.0.0.1`、带 per-VM 256-bit Basic/Bearer Token 鉴权与严格目录防穿越的纯 Go **WebDAV 服务**(`/dav/<vm>/`),Guest 侧优先 `mount_webdav` 实时零双份挂载到 `~/Desktop/ReimsShare` 并在不可用时自动回退同步模式;
|
||||
- Windows 盘符只读共享:每台 VM 在「存储与网络」设置中独立开启内部固定盘符,默认全部关闭,系统盘显示敏感信息提示;新增 `/dav/<vm>/drives/<盘符>/`,由服务端同时限制 HTTP 写方法和文件打开标志,持久化并复核 Volume GUID 防止盘符重绑定,限制 `PROPFIND Depth` 避免整盘递归,并验证 Junction / 符号链接解析后的目标仍在授权盘符内。Guest Tools 4 根据 `/v1/config` 自动挂载/卸载 `Windows C` 等 Finder 卷,关闭开关立即拒绝新请求。**(macOS Finder 真机挂载、只读兼容与重连待验证)**
|
||||
- UI 升级:主界面实时显示 Guest Tools 连接状态、`WebDAV 挂载` / `文件同步` 模式徽章、旧版工具升级提示与「投递文件到 macOS」快捷入口。**(macOS 桌面端真机 WebDAV 挂载与图片剪贴板联调待验证)**
|
||||
- [x] **M5.4(本仓)**:**防休眠守护、系统托盘驻留与资源状态条**
|
||||
- 防休眠守护:Guest Tools 2.0 支持由宿主机 UI 一键实时开关 `caffeinate -dims`(免 sudo,通过 `/v1/config` 实时下发),并在 `REIMSTOOLS` 附带可选 `Apply-Prevent-Sleep-pmset.command`;
|
||||
- Windows 系统托盘驻留:新增纯 Go Win32 `internal/tray`(`Shell_NotifyIconW` + 动态中英文右键菜单,含 VM 状态/快捷启停/打开共享目录/显示窗口/退出),默认关闭主窗口最小化到托盘(可在宿主页开关),保障后台 Guest Tools 桥接不断线;
|
||||
- VM 实时资源条:新增 `internal/host` 进程 CPU%/内存采样与纯 Go `.qcow2` 实际占用 vs 逻辑容量解析,在 VM 详情页每 3 秒轻量展示 QEMU CPU、宿主机内存、磁盘占比与运行时长。
|
||||
|
||||
- [x] **M5.5(本仓 + 上游化)**:**系统外预设 macOS 系统语言(`prev-lang:kbd`)**
|
||||
- 根因:`reims-util@7867384`(`src/opencore/config.rs:216-228`)在生成 `opencore.qcow2` 时将 `NVRAM > Add/Delete > prev-lang:kbd` 硬编码为 `en-US:0`,导致每次进入恢复模式、设置助理和登录界面均强制回退为英文。
|
||||
- 本仓已实现:新增纯 Go `internal/opencore`(直读/原地改写 `opencore.qcow2` / `opencore.img` 的 GPT+FAT32 `EFI/OC/config.plist` 中 `NVRAM > Add/Delete > prev-lang:kbd`,必要时自动回退 `qemu-img` 原子转换);新建向导、VM 设置「通用」页、VM 详情页与 CLI(`--guest-lang`)均已支持预设(默认跟随界面语言,如 `zh-Hans:0` / `zh-Hans:252` / `zh-Hant:0` / `en-US:0` / `ja-JP:0` / `ko-KR:0`),偏好持久化到 `.reims-go-guest-lang` 并在 `update-opencore`、显卡切换、CoW 克隆与 `StartVM` 前自动重放(`zh-Hans:0` vs `zh-Hans:252` 在 Tahoe Recovery 下的真机键盘布局表现**待验证**)。
|
||||
- 长期上游化:向 `reims-util` / `reims-ctl` 提议支持 `opencore --lang` 并在 `update-opencore` 重建时保留原有 `prev-lang:kbd`(登记在 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md))。
|
||||
|
||||
### 运维与开发工作流的实现清单
|
||||
|
||||
- [x] **M5.6(本仓)**:**磁盘 I/O 进阶调优与空间生命周期管理**
|
||||
- 已实现:封装 `qemu-img resize` 停机扩容(支持 `+32G`/`+64G`/`+128G`/`256G` 等增量与绝对目标,防误缩容,完成后自动生成不依赖盘符序号的 macOS `diskutil repairDisk` + `apfs resizeContainer` 一键扩展命令);封装停机「回收未用空间」(校验非 CoW overlay 与剩余空间后重写稀疏 `.qcow2` 并通过 `qemu-img check` 完整性校验再原子替换);补齐 `NVMe` / `VirtIO-blk` / `SATA` 控制器说明并接入设置页「存储与网络」与 CLI(`vm resize` / `vm compact`);
|
||||
- 待验证:已装 macOS 26 真机下 `nvme` vs `virtio-blk` 实际编译/读写基准对比。
|
||||
- [ ] **M5.7(本仓)**:**可视化停机快照与一键回滚**
|
||||
- 基于 M3.7 已落地的 CoW / Golden Image 基础设施,提供命名停机检查点(如「升级 macOS 26.8 前」)、历史列表与一键回滚,确保日常环境改坏或 OTA 失败可秒级恢复。
|
||||
- [ ] **M5.8(本仓)**:**多端口转发与开发者工作流直连**
|
||||
- 网络设置页支持自定义多条宿客 TCP 端口转发(如 `3000→3000`、`8080→8080`,安全合并至 `--extra-args` 或跟进上游多 `hostfwd`);
|
||||
- 详情页提供「打开 SSH 终端」、一键写入 `~/.ssh/config`(`Host reims-<vm>`)与 VS Code / Cursor Remote-SSH 直连入口;
|
||||
- Guest Tools 提供可选「宿主机代理快捷配置」(经 `10.0.2.2:<port>` 显式开启/一键清除,方便 Homebrew / Xcode / npm 下载)。
|
||||
- [x] **M5.9(本仓 + 上游验证)**:**音频延迟与麦克风链路打磨**
|
||||
- 已实现:`internal/host` 接入原生 Win32 `winmm.dll`(`waveOutGetNumDevs` / `waveInGetNumDevs` + 设备名枚举,与上游 `reims-ctl` `sound_devices()` 探测一致);修复 `ParseShow` 在指定显式 `--audio-backend`(如 `dsound`/`none`)时误判音频关闭的 Bug;设置页「输入与音频」与 CLI(`vm set --audio-backend`)支持切换音频后端(`自动(dsound)` / `DirectSound` / `静音设备`),实时展示宿主播放与录音设备状态(无输出/无麦克风时明确提示上游 `reims-ctl` 路由到 `none` 的行为)及 48 kHz / P-Core / 麦克风权限排查指引;
|
||||
- 待验证:真实 macOS 桌面下 DirectSound 播放延迟与麦克风会议录音实测记录。
|
||||
|
||||
### 按需评估的能力
|
||||
|
||||
- [ ] **M5.10(按需评估)**:**Windows USB 设备直通可行性评估** — 上游 `crates/reims-ctl/src/usb.rs` 当前仅枚举 Linux sysfs,Windows 需依赖 WinUSB / UsbDk 驱动替换,复杂度与风险较高;仅在核心体验稳定后评估作为可选高级功能(用于 iPhone 真机调试 / 硬件密钥)。
|
||||
- [ ] **M5.11(按需评估)**:**QMP 实时缩略图与自动化脚本接口** — 复用现有 QMP 通道补齐 VM 画面缩略图预览与 CLI 自动化操作。
|
||||
|
||||
**DoD(v0.2.2 验收标准)**:
|
||||
- 在真实 Windows 宿主上,使用 `reims-go` 启动 macOS 可完成:**新建/恢复阶段即可外部预设中文语言(`prev-lang:kbd`)、热切沉浸全屏/无黑边缩放、清晰 HiDPI 显示、图文双向剪贴板、零双份占用的挂载式共享目录、托盘后台常驻不掉线**,且持续高负载开发(编译/浏览器/多任务)稳定无明显卡顿或意外断连。
|
||||
|
||||
---
|
||||
|
||||
## 后续执行顺序:按用户任务验收
|
||||
|
||||
上面的 M5.x 是实现索引,不代表执行顺序,也不构成持续增加功能的承诺。后续迭代按下面的用户任务排序;同一任务优先修复和验证已有能力,只有现有路径确实无法完成任务时才新增功能。P0 表示任务优先级,不表示全部塞进同一个版本;每轮只选择能够完整验收的范围。
|
||||
|
||||
### U1(P0):第一次使用就能装到桌面,失败也知道怎么处理
|
||||
|
||||
**用户故事**:我只按向导操作,不需要理解 WHPX、Vulkan、OpenCore 或 QEMU 参数,就能得到可用的 macOS 桌面;下载中断、磁盘不足或提权取消时,可以安全重试。
|
||||
|
||||
**实现范围**:
|
||||
|
||||
1. 先完成 M4 的发布闭环:实跑运行时 CI;确保公开资产的 manifest、补丁和源码包一致;冒烟报告记录最终资产完整 SHA-256,发布后替换资产必须退回 `alpha` 重新验收。
|
||||
2. 用公开应用和运行时,在声明支持的 Windows / GPU / macOS 组合上跑「干净用户目录 → 体检 → 下载/导入 → 创建 → 安装 → 退出恢复模式」完整流程,而不是只跑 `doctor` 和单元测试。
|
||||
3. 针对用户真实会遇到的中断做故障注入:暂停/断网后续传、磁盘不足、UAC 取消、运行时损坏、安装进程退出。界面说明发生了什么、数据是否保留以及下一步怎么做。
|
||||
|
||||
**验收证据**:每个受支持组合都有版本、耗时、结果和日志记录;失败后可以重试或安全清理,不留下无法解释的半配置 VM;公开文档描述与用户实际下载的稳定资产一致。
|
||||
|
||||
**不扩大范围**:不为了增加“支持数量”贸然承诺未测试的 GPU、Windows 或 macOS 版本,也不把高级参数暴露给首次使用者。
|
||||
|
||||
### U2(P0):一天开发工作不被显示、输入和宿客协作打断
|
||||
|
||||
**用户故事**:我在 macOS 里使用 IDE、浏览器和构建工具,同时与 Windows 交换文字、图片和文件;全屏、HiDPI、快捷键、声音和共享目录应当稳定,不需要反复重连或调整底层参数。
|
||||
|
||||
**实现范围**:
|
||||
|
||||
1. 集中验收 M5.1–M5.5 和 M5.9 的已有实现;上游图形 PR 只有在能改善可测的全屏、缩放、帧率、首帧延迟或稳定性时才进入新运行时。
|
||||
2. 在真实宿主完成一个完整工作日(8 小时)的编译、浏览器、多任务、图文剪贴板和共享目录混合负载,并覆盖窗口尺寸/DPI 变化、宿主睡眠唤醒、Guest Tools 重连和音频/麦克风场景。
|
||||
3. 资源条和诊断信息用于解释卡顿、内存压力、磁盘压力和断连,不继续增加没有明确排障用途的指标。
|
||||
|
||||
**验收证据**:记录宿主硬件、运行时和 macOS 版本,以及卡顿、断连、延迟和恢复结果;未通过的组合明确限制或降级,不把“有开关”写成“体验已完成”。
|
||||
|
||||
**不扩大范围**:现有剪贴板和 WebDAV 能完成任务时,不另做一套拖放协议、共享文件系统或无缝窗口模式。
|
||||
|
||||
### U3(P0):升级系统和调整环境之前,用户可以反悔
|
||||
|
||||
**用户故事**:在 macOS OTA、开发环境大改或磁盘整理之前,我能留下一个有名字的恢复点;改坏后可以回到之前状态,操作中断也不会弄坏原盘。
|
||||
|
||||
**实现范围**:
|
||||
|
||||
1. 将 M5.7 的**停机快照与一键回滚**作为本任务的核心新增能力:名称、说明、创建时间、历史列表、删除和带确认的回滚;不要求运行中内存热快照。
|
||||
2. 校验可用空间、VM 停机状态和 CoW backing file 链;创建、删除、回滚及磁盘 compact/resize 都要考虑进程中断和空间不足,禁止误删仍被派生盘依赖的基盘。
|
||||
3. 明确“快照不是备份”。先验证数据目录的离线备份与恢复说明;只有用户确实需要跨机器迁移或自动保留策略时,才评估独立导出格式和调度功能。
|
||||
|
||||
**验收证据**:真实执行“创建恢复点 → 修改/升级系统 → 回滚 → 启动并核对应用与文件”;对创建和回滚过程做中断测试,原盘与可用恢复点均不受损。
|
||||
|
||||
**不扩大范围**:在显存和设备状态序列化未经上游验证前,不做运行中内存快照、快照树花哨可视化或 instant clone 承诺。
|
||||
|
||||
### U4(P1):Windows 与 macOS 开发工具可以直接接起来
|
||||
|
||||
**用户故事**:我在 Windows 编辑代码,在 macOS 构建和签名,再从 Windows 浏览器或 IDE 访问客体服务;常用连接可以保存,重启 VM 后仍可使用。
|
||||
|
||||
**实现范围**:
|
||||
|
||||
1. 围绕一条完整链路实现 M5.8:多 TCP 端口转发、端口冲突检测、SSH 终端与 SSH config、VS Code / Cursor Remote-SSH,以及明确开关和一键清除的宿主代理配置。
|
||||
2. 复用已经验收的剪贴板、文件投递和共享目录,把连接入口放在用户执行任务的页面,而不是再增加一个堆满网络参数的“高级中心”。
|
||||
3. 默认仅绑定需要的宿主地址,清楚展示暴露端口和代理状态;CLI 只补这条工作流需要的命令,不追求完整封装所有 QMP 能力。
|
||||
|
||||
**验收证据**:不手写 `--extra-args` 或网络命令,完成「Windows 编辑 → macOS 构建 → Windows 浏览器预览 → 取回日志/产物」,并在 VM 重启后验证连接恢复。
|
||||
|
||||
**不扩大范围**:不为对标通用虚拟机而引入桥接网络、虚拟交换机等子系统;SLIRP 无法覆盖具体任务时再重新评估。
|
||||
|
||||
### U5(按需候选):只有明确场景和验证路径,才进入版本计划
|
||||
|
||||
- **iPhone 真机调试 / 硬件密钥**:先确认目标用户和现有替代办法,再评估 M5.10 的 Windows USB 原型、驱动签名与恢复风险;不直接扩展成全量 USB 直通。
|
||||
- **自动化脚本接口**:先有一个会反复执行的真实流程,例如每日创建干净测试机、运行测试并回收,再设计最小 CLI/API;不为“自动化能力完整”封装全部上游命令。
|
||||
- **独立备份、迁移和保留策略**:先证明离线备份说明不够,再确定格式、兼容与恢复验收;不能只实现“导出”而没有“恢复”测试。
|
||||
- **拖放、无缝窗口、更多客户机系统、企业管理**:暂不排期。只有现有方案被真实任务证明不足,且收益高于维护成本时才重新讨论。
|
||||
|
||||
### 新功能进入迭代前的统一门槛
|
||||
|
||||
1. 写明用户故事、受阻步骤、当前替代办法和不做的后果。
|
||||
2. 优先复用现有 GUI、CLI、Guest Tools 与上游能力,说明为什么不能只靠文档或默认配置解决。
|
||||
3. 同时设计校验、失败恢复、隐私与安全边界;涉及磁盘和身份配置的操作必须可回退或可重建。
|
||||
4. 写明真实用户任务 DoD、测试矩阵和证据形式;只有单元测试的功能保持“已实现”,不得写成“已验收”。
|
||||
5. 发布时核对用户实际获得的稳定资产和文档。P0 任务未通过时,不用新增 P1 功能代替修复。
|
||||
- **扩展与插件体系**:架构草案见 [docs/plugin-architecture.md](plugin-architecture.md),待核心体验稳定后分阶段评估。
|
||||
- **Windows USB 设备直通**:依赖 WinUSB / UsbDk 驱动替换,签名与稳定性风险较高,仅在确有 iPhone 真机调试或硬件密钥刚需时做最小原型评估。
|
||||
- **独立导出/迁移与备份调度**:先验证数据目录离线备份方案是否足够,再评估独立归档格式与恢复校验。
|
||||
|
||||
---
|
||||
|
||||
## 不做的事
|
||||
|
||||
- **不为功能列表更好看而做功能**:不盲目扩张企业管理、多平台、多客户机或全量 QMP/API 封装;所有新增能力先经过上面的用户任务与验收门槛。
|
||||
- **不维护长期 fork**:对上游的改动只走补丁队列,目标是清零(见 `portable-runtime-spec.md` 第 5 节)。
|
||||
- **不跟踪上游最新 commit**:用户只拿到冒烟过的 `stable`。
|
||||
- **暂不做 TAP / Wi-Fi MacNAT 虚拟网卡驱动安装器**:维护与签名风险高,优先服务好 SLIRP + 多端口转发 + Guest Tools 共享目录。
|
||||
- **暂不强推运行中内存热快照(`savevm`)**:在未验证 `reims-vgpu` 显存与设备状态序列化前,以可靠的停机快照与 CoW 派生为准。
|
||||
- **暂不兼容已淘汰的 `apple-gfx` 旧图形栈**,暂不实现 `vphone` 等其他 `Engine`(接口位置保留)。
|
||||
- **不长期维护上游 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 参数要和用户填的分开存放、合并写入,不能互相覆盖 |
|
||||
| 宿客协作(Reims-Go 扩展) | ReimsShare、Windows 盘符只读共享、剪贴板 | Guest Tools HTTP/WebDAV,无对应 `reims-ctl` 参数 | 立即生效 | 每台 VM 独立配置;盘符共享默认全部关闭,仅枚举内部固定磁盘,系统盘提示敏感信息风险 |
|
||||
|
||||
## 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,100 +0,0 @@
|
||||
# UI 审视(2026-11-28)
|
||||
|
||||
> 标准:[dickwu/apple-design-skill](https://github.com/dickwu/apple-design-skill)(MIT;其中 `references/hig/*.md` 为 Apple HIG 原文镜像,版权归 Apple)。按它的五个视角依次看:无障碍 → 平台惯例 → 视觉与工艺 → 交互 → 文案。每条标严重度(Critical / High / Medium / Low),写清现状、依据、改法。
|
||||
> 范围:VM 主页、VM 设置、宿主与运行时、安装包、新建向导。截图取自 `wails dev`,1280×820,浅色与深色两种外观。
|
||||
|
||||
## 结论:需要改进(Needs work)
|
||||
|
||||
没有 Critical。High 有 5 条,集中在两点:
|
||||
|
||||
- **主页什么都想放**。同一份配置在一页里出现三到四次,功能介绍也写在页面上。
|
||||
- **上游原始字符串直接给人看**。
|
||||
|
||||
留白不够,主要不是间距数值的问题,而是内容太多,又层层套框。
|
||||
|
||||
## High
|
||||
|
||||
**H1 · VM 主页信息重复,层级是平的**
|
||||
- 现状:一页从上到下堆了 9 块:标题栏、iMac 主视觉、资源条、提示条、装机引导、Guest Tools 卡片、SSH 行、规格清单、macOS 分组、显示器分组、快捷键条、技术信息。
|
||||
- CPU 型号出现 2 次,「类型」2 次,分辨率 2 次。
|
||||
- 网络在规格清单里写一次(原始字符串),在 SSH 行又写一次。
|
||||
- 依据:`layout.md > Best practices`:把最重要的放在最上方;用留白和分组表达关系;用渐进披露代替堆叠。
|
||||
- 改法:按「关于本机」的模式重排。
|
||||
- 第一屏只留四样:主视觉、名称、一行规格、主操作。
|
||||
- 规格只说一次。
|
||||
- 连接相关(SSH、Guest Tools、共享文件夹)收成一个分组列表。
|
||||
- 原始值全部收进底部的「技术信息」折叠区。
|
||||
|
||||
**H2 · Guest Tools 卡片写成了功能介绍**
|
||||
- 现状:
|
||||
- 第一句是 80 多字的卖点:「免 Xcode/Python 的 Guest Tools 2.0:支持文本 + PNG 截图双向剪贴板(长轮询低延迟)、WebDAV 零双份挂载……」。
|
||||
- 卡片里又套了一层带边框的开关行,下面还有三个并排按钮。
|
||||
- 依据:
|
||||
- `writing.md`:说清楚,删掉多余的字。
|
||||
- `layout.md`:用容器或留白分组,二选一,不要层层套框。
|
||||
- 改法:
|
||||
- 卡片改成分组列表里的普通行:状态写在描述里,操作放右侧。
|
||||
- 安装命令只在工具盘已插入时出现。
|
||||
- 功能介绍删掉,交给 README。
|
||||
|
||||
**H3 · 上游原始字符串直接展示**
|
||||
- 现状:
|
||||
- 网络显示 `user (MAC configured), ssh on 127.0.0.1:2222`。
|
||||
- 类型显示 `x86-64 macOS guest (q35 and OpenCore, WHPX)`。
|
||||
- 设置项标题里直接带 `(REIMS_VGPU_LOG)`、`kernel-irqchip`。
|
||||
- 依据:`writing.md`:标签描述效果,不描述实现。
|
||||
- 改法:
|
||||
- 主界面只用人话:「NAT · SSH 2222」。
|
||||
- 环境变量和参数名放进描述或「技术信息」,标题只保留名词。
|
||||
|
||||
**H4 · 系统原生下拉框和自绘控件混在一起**
|
||||
- 现状:设置「通用」页和新建向导里的 `<select>` 一展开就是 Windows 原生黑底列表,和周围的分段控件、卡片完全不搭(用户截图)。
|
||||
- 依据:`pop-up-buttons.md`:弹出按钮用于一组互斥选项,要给默认值,标签要让人不展开也能预判。
|
||||
- 改法:
|
||||
- 做一个与 macOS 弹出按钮同形的 `PopupSelect`:当前值加 ⌃⌄ 箭头;菜单里当前项带 ✓;次要信息(键盘布局、构建号)用灰字跟在后面。
|
||||
- 全局替换所有 `<select>`。
|
||||
|
||||
**H5 · 窗口和分组标题重复**
|
||||
- 现状:
|
||||
- 设置窗口标题是「macos-tahoe 设置」。
|
||||
- 「通用」页的分组标题「macOS 系统语言」下面,行标题还是「macOS 系统语言」。
|
||||
- 主页标题「关于此虚拟机」正下方是一个更大的「macos-tahoe」。
|
||||
- 依据:
|
||||
- `settings.md`:多页设置窗口的标题就是当前那一页。
|
||||
- `writing.md`:删掉多余的字。
|
||||
- 改法:
|
||||
- 设置窗口标题只写实例名,副标题写状态。
|
||||
- 分组标题和行标题不能同名。
|
||||
- 主页去掉「关于此虚拟机」。
|
||||
|
||||
## Medium
|
||||
|
||||
- **M1 文案没有统一风格**:同一层级里,有的写短语,有的写两三句并用分号连接,还有的夹着 `#123`、`docs/upstream-pr-prep.md` 这种开发者引用。
|
||||
- 规则:标题是名词;描述一句话,说开启后的效果;不写「需支持……的运行时」这类条件链,条件放进禁用原因。
|
||||
- **M2 字号层级太多**:同一页里用了 22 / 16 / 13.5 / 13 / 12 / 11.5 / 11 七档。
|
||||
- 对齐 macOS 文字样式:Large Title 26、Title 3 15、Body 13、Callout 12、Subheadline 11。主页只用其中四档。
|
||||
- **M3 状态说了三遍**:侧栏圆点、主视觉下的胶囊、主按钮文字都在表达同一个状态。保留侧栏和副标题两处即可。
|
||||
- **M4 卡片里再套卡片**:Guest Tools 卡片里的开关行、命令行各自有边框。全局规定框最多一层。
|
||||
- **M5 宿主页**:四个指标卡加五个分组,每组都带灰色提示,看起来很满。指标卡可以保留,提示文字要压到一行以内。
|
||||
- **M6 新建向导**:每个字段下面都有一两行灰字,例如「留空则使用数据目录」这种可以改成占位文字的说明。
|
||||
|
||||
## Low
|
||||
|
||||
- 快捷键条只是普通信息,却装在一个框里。改成页面底部的一行脚注。
|
||||
- 安装包页的「正在读取 Apple 的版本列表…」也放在列表框里,看上去像是一条数据。
|
||||
|
||||
## 做得好的
|
||||
|
||||
- 侧栏图标、分段控件、开关已经有 macOS 的样子;深色和浅色外观都完整。
|
||||
- 设置窗口刚改成分组行加依赖置灰,`pop-up` 以外的控件已经统一。
|
||||
- 主操作每个状态只有一个,符合 `buttons.md`「每个视图一到两个主按钮」。
|
||||
|
||||
## 改版落地
|
||||
|
||||
| 项 | 处理 |
|
||||
| --- | --- |
|
||||
| H1、H2、H3、M3、M4、Low-1 | 重写 `VMPage`:主视觉 → 一行规格 → 操作按钮 → 上下文提示 → 「连接」分组 → 「技术信息」折叠 → 快捷键脚注 |
|
||||
| H4 | 新增 `ui/settings.tsx > PopupSelect`,替换设置和向导中的 `<select>` |
|
||||
| H5、M1 | 设置窗口标题只用实例名;分组标题去重;精简设置、主页、向导文案 |
|
||||
| M2 | 主页只用 26 / 15 / 13 / 12 四档 |
|
||||
| M5、M6、Low-2 | 本轮不做,留作后续 |
|
||||
@@ -1,353 +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 目录结构
|
||||
|
||||
> 现状:没有照这个结构拆分,zustand 也没有引入。实际目录是 `components/`(页面与对话框)、`ui/`(基件封装)、`lib/`(格式化、日志、任务)、`styles/`,状态仍集中在 `App.tsx`。下面是原计划,保留作参考。
|
||||
|
||||
```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 拆分目录。(Radix 和 lucide 已在阶段 0 引入;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 |
|
||||
@@ -1,81 +0,0 @@
|
||||
# 上游 PR 跟进与补丁上游化准备(M4.1 / M4.5)
|
||||
|
||||
> 遵循 [`AGENTS.md`](../AGENTS.md) 规则 4:本仓库不维护长期 fork,所有对上游的改动仅以补丁队列存于 [`patches/`](../patches/),向上游提交 PR 由人工确认执行。
|
||||
|
||||
---
|
||||
|
||||
## 一、上游 Windows 重点 PR 跟踪清单(M4.1)
|
||||
|
||||
目标上游仓库:[`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)(当前稳定运行时基准 commit:`3731afd`)。
|
||||
|
||||
| 上游 PR | 方向 | 价值与影响 | 建议动作 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `#153` | 图形呈现 | Windows NVIDIA MAILBOX 经 FIFO 首帧优化,改善高帧率与首帧延迟 | 合入后 `build-runtime.yml` 每日构建自动产出 `alpha`,再跑冒烟 |
|
||||
| `#152` | 平台层 | 原生 Windows Vulkan 后端,减少 Windows 图形适配开销 | 合入后升级运行时并对比帧率/稳定性 |
|
||||
| `#107` | 图形内存 | 采样纹理回读就地消费,降低显存/内存拷贝开销 | 合入后随运行时一并纳入 |
|
||||
| `#123` | 窗口体验 | `Ctrl+Alt+Enter` 热切全屏 | 合入后在前端文档/帮助提示同步快捷键 |
|
||||
| `#172` | 窗口体验 | Windows 拖动窗口贴合,消除缩放黑边 | 合入后验证高 DPI 与多显示器缩放 |
|
||||
| Win → Command | 键位映射 | 自由指针下 Windows 键映射为 macOS Command | 优先向上游提议/提交 PR,避免长期维护私有补丁 |
|
||||
| `reims-util` `--lang` / `prev-lang:kbd` | 客体语言预设 | `reims-util@7867384` `src/opencore/config.rs:216-228` 硬编码 `prev-lang:kbd=en-US:0` 并置于 `NVRAM > Delete`,导致恢复模式/设置助理强制回退英文 | 短期本仓停机改写 `opencore.qcow2` 并在 `update-opencore` 后重放;长期向上游提议 `opencore --lang` 与重建保留 |
|
||||
|
||||
---
|
||||
|
||||
## 二、待提交上游 PR 的本地补丁证据汇总(M4.5)
|
||||
|
||||
目标上游仓库:[`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)(基准 commit:`4571bc5`),修改文件均为 `target/i386/whpx/whpx-all.c`。
|
||||
|
||||
### PR 1:`whpx: probe TSC deadline on throwaway partition and guard WHvResetPartition`
|
||||
|
||||
- **补丁文件**:[`patches/qemu-whpx-win10-compat.patch`](../patches/qemu-whpx-win10-compat.patch)
|
||||
- **影响环境**:Windows 10 22H2(Build 19045)启用 WHPX 的 x86-64 宿主。
|
||||
- **复现与根因**:
|
||||
1. `whpx_tsc_deadline_refused()`(`target/i386/whpx/whpx-all.c:3211`)在正式 `whpx_global.partition` 上临时创建并删除 vCPU 0;Windows 10 19045 上随后 `whpx_init_vcpu()` 再次为 vCPU 0 调用 `WHvCreateVirtualProcessor` 必现失败,返回 `E_INVALIDARG (0x80070057)`。
|
||||
2. `whpx_set_registers()`(`target/i386/whpx/whpx-all.c:530`)在复位状态直接调用 `whp_dispatch.WHvResetPartition`,但该 API 在 Windows 11 才新增;Windows 10 上函数指针为空,引发空指针解引用崩溃(`0xc0000005`)。
|
||||
- **最小修复**:
|
||||
1. 改在一次性探测 partition 上测试 `WHvX64RegisterTscDeadline`,测完即销毁探测 partition;
|
||||
2. 调用 `WHvResetPartition` 前判断 `whp_dispatch.WHvResetPartition != NULL`。
|
||||
- **实测证据**:已在 Windows 10 19045 真机通过多轮冷启动与日常使用验证(见 `runtime-3731afd` 稳定版运行时)。
|
||||
|
||||
### PR 2:`whpx: forward INIT/SIPI via WHvRequestInterrupt on legacy Windows 10 with kernel-irqchip`
|
||||
|
||||
- **补丁文件**:[`patches/qemu-whpx-win10-startup-ipis.patch`](../patches/qemu-whpx-win10-startup-ipis.patch)(依赖 PR 1)
|
||||
- **影响环境**:Windows 10 19045 开启 `kernel-irqchip=on` 且多核(`smp.max_cpus > 1`)的 macOS 客体。
|
||||
- **复现与根因**:
|
||||
- Win10 上开启 WHPX 内核态 APIC 仿真后,XNU 启动从核(AP)发出的 INIT/SIPI 可能无法唤醒已 halt 的从核,导致客体卡在多核拉起阶段。
|
||||
- **最小修复**:
|
||||
- 仅在 `whpx_is_legacy_os() && whpx_irqchip_in_kernel() && ms->smp.max_cpus > 1` 且宿主支持 `X64ApicInitSipiExitTrap` 时开启捕获,并在 `WHvRunVpExitReasonX64ApicInitSipiTrap` 退出中通过 `WHvRequestInterrupt` 转发 INIT/SIPI(忽略 INIT level deassert)。
|
||||
- **实测证据**:Win10 19045 上 8 核两次冷启动、12 核冷启动均验证 x2APIC、FileVault、SSH 与图形登录通过;客体软重启仍由外层 `AF_UNIX` QMP 监控兜底(待进一步观测纯补丁下软重启行为)。
|
||||
|
||||
### PR 3:`whpx: make nested virtualization property failure non-fatal`
|
||||
|
||||
- **补丁文件**:[`patches/qemu-whpx-nested-virt-nonfatal.patch`](../patches/qemu-whpx-nested-virt-nonfatal.patch)(依赖 PR 1 & PR 2)
|
||||
- **影响环境**:部分 Windows 11 宿主(如 24H2 / Home 或 Core Ultra 200 系列)。
|
||||
- **复现与根因**:
|
||||
- `WHvGetCapability` 返回 `Bank1.NestedVirtSupport = 1`,但实际调用 `WHvSetPartitionProperty(WHvPartitionPropertyCodeNestedVirtualization)` 时返回 `hr=0x80370302`(`WHV_E_UNKNOWN_PROPERTY`)。
|
||||
- 上游原代码(`target/i386/whpx/whpx-all.c:3533-3545`)将该错误当作致命错误直接 `goto error` 中止 VM 启动,迫使用户退回 `kernel-irqchip=off`(损失 Hyper-V 内核态 x2APIC / SynIC 加速)。
|
||||
- **最小修复**:
|
||||
- 将 `error_report` + `goto error` 改为 `warn_report` 并将 `processor_features.Bank1.NestedVirtSupport` 清零,继续保留完整 `kernel-irqchip=on` 启动。
|
||||
- **实测状态**:已在 `Reims-Go` 宿主探测逻辑(`internal/host/whpx_probe_windows.go`)复现 `hr=0x80370302`;带该补丁的 `alpha` 运行时需经真机编译冒烟验证后再提上游 PR(**待验证**)。
|
||||
|
||||
### PR 4:`util/coroutine-windows: reserve 1 MiB stack with 64 KiB initial commit and check fiber creation`
|
||||
|
||||
- **补丁文件**:[`patches/qemu-win32-coroutine-fiber-commit.patch`](../patches/qemu-win32-coroutine-fiber-commit.patch)(独立于 PR 1–3,修改 `util/coroutine-windows.c`)
|
||||
- **影响环境**:Windows 10 / 11 宿主在高并发磁盘 I/O + GPU/VA-API 显存提交叠加场景(如登录 Apple ID 触发 iCloud/Spotlight 并发读盘与 HEVC 硬解)。
|
||||
- **复现与根因**:
|
||||
1. `runtime-3731afd` 真机崩溃日志在 `CPU 0/WHPX` 线程触发 `0xc0000005`(read of `0x0000000000000010`),符号化调用栈为 `execute_ncq_command`(`hw/ide/ahci.c:1096`)→ `blk_aio_prwv`(`block/block-backend.c:1624`)→ `qemu_aio_coroutine_enter`(`util/qemu-coroutine.c:298`)→ `qemu_coroutine_switch`(`util/coroutine-windows.c:58`)→ `KERNELBASE!SwitchToFiber`(`movq 0x10(%rcx), %rax`)。
|
||||
2. `qemu_coroutine_new()`(`util/coroutine-windows.c:78`)调用 `CreateFiber(COROUTINE_STACK_SIZE, ...)`,Windows 会将 `1 MiB` 全部作为初始 Commit Size 立即扣除系统 Commit Charge;当提交内存见底时 `CreateFiber` 返回 `NULL`,原代码未判空即返回并在 `SwitchToFiber(NULL)` 崩溃。
|
||||
3. 同时 `qemu_coroutine_self()`(`util/coroutine-windows.c:99`)直接调用 `ConvertThreadToFiber(NULL)`,若线程已被外部库转为 Fiber 会返回 `NULL`(`ERROR_ALREADY_FIBER`)且同样未检查。
|
||||
- **最小修复**:
|
||||
1. 改用 `CreateFiberEx(64 * 1024, COROUTINE_STACK_SIZE, 0, ...)`,保留完整 1 MiB 栈空间但将每个协程初始提交降为 64 KiB(提交开销降低 16 倍);
|
||||
2. 在 `qemu_coroutine_self()` 中通过 `IsThreadAFiber()` 复用现有 Fiber;
|
||||
3. 对 `co->fiber == NULL` 与 `leader->fiber == NULL` 打印 `GetLastError()` 并显式 `abort()`,杜绝静默空指针解引用。
|
||||
- **实测状态**:补丁已通过 `git apply --check`(基于 `4571bc5`);需编入下一版 `alpha` 运行时并在真机验证登录后高负载场景(**待验证**)。
|
||||
|
||||
---
|
||||
|
||||
## 三、补丁退役检查表
|
||||
|
||||
每当上游合入对应 PR(每日构建会跳过该补丁,并开 issue「Patch queue: patches already upstream」提醒)后:
|
||||
1. 移除 `patches/` 下对应 `.patch` 文件,并同步更新 `patches/series.txt` 与 `patches/README.md`;
|
||||
2. 等下一次每日构建,或手动触发 `.github/workflows/build-runtime.yml`,产出新 `alpha`;
|
||||
3. 在真机运行 `scripts/smoke-runtime.ps1` 并人工确认通过后升级为 `stable`。
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"bridgeApi": "1.0.0",
|
||||
"methods": [
|
||||
"hello",
|
||||
"i18n.getBundle",
|
||||
"ui.notify",
|
||||
"vm.list",
|
||||
"command.invoke"
|
||||
],
|
||||
"events": [
|
||||
"theme.changed",
|
||||
"locale.changed"
|
||||
],
|
||||
"experimental": {
|
||||
"methods": [
|
||||
"ui.confirm",
|
||||
"ui.showForm",
|
||||
"ui.setTitle",
|
||||
"ui.setBadge",
|
||||
"ui.openView",
|
||||
"ui.close",
|
||||
"ui.navigate",
|
||||
"ui.openExternal",
|
||||
"vm.get",
|
||||
"settings.get",
|
||||
"settings.set",
|
||||
"storage.get",
|
||||
"storage.set",
|
||||
"storage.list",
|
||||
"storage.delete",
|
||||
"file.pick",
|
||||
"file.save",
|
||||
"file.read",
|
||||
"file.write",
|
||||
"task.start",
|
||||
"task.update",
|
||||
"task.finish",
|
||||
"net.fetch",
|
||||
"events.subscribe",
|
||||
"events.unsubscribe"
|
||||
],
|
||||
"events": [
|
||||
"vm.stateChanged",
|
||||
"view.visibilityChanged",
|
||||
"task.updated"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<html dir="ltr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
{
|
||||
"name": "reims-go-frontend",
|
||||
"private": true,
|
||||
"version": "0.2.3",
|
||||
"version": "0.2.11",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"test": "node --test scripts/test-i18n.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs",
|
||||
"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 @@
|
||||
f71dbd21d10dd124677343ad731d7f59
|
||||
d5f2fdb982362b7c1d77e7244b0a024f
|
||||
@@ -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,172 @@
|
||||
// Checks the UI and bridge contracts (docs/plugin-architecture.md §5.1, §5.6, §6.3)
|
||||
// and writes ui-contract.json / bridge-contract.json for plugin authors.
|
||||
//
|
||||
// Rule "public means implemented": every stable part, state attribute, slot and
|
||||
// layer must be emitted by the host, and an experimental entry the host already
|
||||
// emits must be promoted to stable in the same change.
|
||||
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 bridgeSrc = fs.readFileSync(path.join(srcDir, 'lib', 'bridgeContract.ts'), 'utf8')
|
||||
const tokensCss = fs.readFileSync(path.join(srcDir, 'styles', 'tokens.css'), 'utf8')
|
||||
const appCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8')
|
||||
|
||||
function extractArray(src, name) {
|
||||
const re = new RegExp(`export const ${name} = \\[([\\s\\S]*?)\\] as const`)
|
||||
const m = src.match(re)
|
||||
if (!m) throw new Error(`Could not parse ${name}`)
|
||||
return [...m[1].matchAll(/'([^']+)'/g)].map((x) => x[1])
|
||||
}
|
||||
function extractVersion(src, name) {
|
||||
const m = src.match(new RegExp(`${name}\\s*=\\s*'([^']+)'`))
|
||||
if (!m) throw new Error(`Could not parse ${name}`)
|
||||
return m[1]
|
||||
}
|
||||
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
|
||||
const uiApi = extractVersion(contractSrc, 'UI_API_VERSION')
|
||||
const stable = {
|
||||
parts: extractArray(contractSrc, 'UI_CONTRACT_PARTS'),
|
||||
stateAttrs: extractArray(contractSrc, 'UI_CONTRACT_STATE_ATTRS'),
|
||||
itemStates: extractArray(contractSrc, 'UI_CONTRACT_ITEM_STATES'),
|
||||
slots: extractArray(contractSrc, 'UI_CONTRACT_SLOTS'),
|
||||
layers: extractArray(contractSrc, 'UI_CONTRACT_LAYERS'),
|
||||
layoutOptions: extractArray(contractSrc, 'UI_CONTRACT_LAYOUT_OPTIONS'),
|
||||
icons: extractArray(contractSrc, 'UI_CONTRACT_ICONS'),
|
||||
viewLocations: extractArray(contractSrc, 'UI_CONTRACT_VIEW_LOCATIONS'),
|
||||
sdkEvents: extractArray(contractSrc, 'UI_CONTRACT_SDK_EVENTS'),
|
||||
tokens: extractArray(contractSrc, 'UI_CONTRACT_TOKENS'),
|
||||
}
|
||||
const experimental = {
|
||||
parts: extractArray(contractSrc, 'UI_CONTRACT_PARTS_EXPERIMENTAL'),
|
||||
stateAttrs: extractArray(contractSrc, 'UI_CONTRACT_STATE_ATTRS_EXPERIMENTAL'),
|
||||
itemStates: extractArray(contractSrc, 'UI_CONTRACT_ITEM_STATES_EXPERIMENTAL'),
|
||||
slots: extractArray(contractSrc, 'UI_CONTRACT_SLOTS_EXPERIMENTAL'),
|
||||
layers: extractArray(contractSrc, 'UI_CONTRACT_LAYERS_EXPERIMENTAL'),
|
||||
layoutOptions: extractArray(contractSrc, 'UI_CONTRACT_LAYOUT_OPTIONS_EXPERIMENTAL'),
|
||||
icons: extractArray(contractSrc, 'UI_CONTRACT_ICONS_EXPERIMENTAL'),
|
||||
viewLocations: extractArray(contractSrc, 'UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL'),
|
||||
sdkEvents: extractArray(contractSrc, 'UI_CONTRACT_SDK_EVENTS_EXPERIMENTAL'),
|
||||
}
|
||||
const bridgeApi = extractVersion(bridgeSrc, 'BRIDGE_API_VERSION')
|
||||
const bridge = {
|
||||
methods: extractArray(bridgeSrc, 'BRIDGE_METHODS'),
|
||||
events: extractArray(bridgeSrc, 'BRIDGE_EVENTS'),
|
||||
experimentalMethods: extractArray(bridgeSrc, 'BRIDGE_METHODS_EXPERIMENTAL'),
|
||||
experimentalEvents: extractArray(bridgeSrc, 'BRIDGE_EVENTS_EXPERIMENTAL'),
|
||||
}
|
||||
|
||||
// Host source the contract is emitted from (contract/SDK definitions excluded).
|
||||
function readSources(dir, exts) {
|
||||
let buf = ''
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) buf += readSources(full, exts)
|
||||
else if (exts.some((e) => entry.name.endsWith(e)) && !/ui-contract\.ts$|bridgeContract\.ts$|\.gen\.ts$/.test(entry.name)) {
|
||||
buf += '\n' + fs.readFileSync(full, 'utf8')
|
||||
}
|
||||
}
|
||||
return buf
|
||||
}
|
||||
const allTsx = readSources(srcDir, ['.tsx'])
|
||||
const allCode = readSources(srcDir, ['.ts', '.tsx'])
|
||||
// Per-file sources, for checks that need two things in the same component.
|
||||
function sourceFiles(dir, out = []) {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) sourceFiles(full, out)
|
||||
else if (entry.name.endsWith('.tsx')) out.push(fs.readFileSync(full, 'utf8'))
|
||||
}
|
||||
return out
|
||||
}
|
||||
const tsxFiles = sourceFiles(srcDir)
|
||||
|
||||
const hasClass = (p) => new RegExp(`(?<![a-zA-Z0-9_-])${esc(p)}(?![a-zA-Z0-9_-])`).test(allTsx)
|
||||
const camel = (attr) => attr.replace(/^data-/, '').replace(/-([a-z])/g, (_, c) => c.toUpperCase())
|
||||
const hasAttr = (a) => allCode.includes(a) || new RegExp(`dataset\\.${camel(a)}\\b`).test(allCode)
|
||||
const hasSlot = (s) => allTsx.includes(`data-rg-slot="${s}"`)
|
||||
const hasLayer = (l) => allTsx.includes(`data-rg-layer="${l}"`)
|
||||
|
||||
const errors = []
|
||||
const fail = (msg, list) => { if (list.length) errors.push(`${msg}: ${list.join(', ')}`) }
|
||||
|
||||
fail('stable parts not emitted by any component', stable.parts.filter((p) => !hasClass(p)))
|
||||
fail('stable state attributes never set', stable.stateAttrs.filter((a) => !hasAttr(a)))
|
||||
fail('stable slots without a data-rg-slot anchor', stable.slots.filter((s) => !hasSlot(s)))
|
||||
fail('stable layers without a data-rg-layer element', stable.layers.filter((l) => !hasLayer(l)))
|
||||
fail('stable tokens missing in tokens.css', stable.tokens.filter((tk) => !tokensCss.includes(`${tk}:`)))
|
||||
// An item state counts as emitted when one component carries both the part and the attribute.
|
||||
fail('stable item states not emitted together with their part', stable.itemStates.filter((s) => {
|
||||
const [part, attr] = s.split(':')
|
||||
return !tsxFiles.some((src) => new RegExp(`(?<![a-zA-Z0-9_-])${esc(part)}(?![a-zA-Z0-9_-])`).test(src) && src.includes(`${attr}=`))
|
||||
}))
|
||||
// Layout values other than the defaults need CSS that implements them.
|
||||
const LAYOUT_ATTR = { sidebarPosition: 'data-layout-sidebar', sidebarMode: 'data-layout-sidebar-mode', density: 'data-layout-density', titlebar: 'data-layout-titlebar' }
|
||||
const LAYOUT_DEFAULTS = ['sidebarPosition=left', 'sidebarMode=full', 'density=regular', 'titlebar=standard']
|
||||
fail('stable layout options without CSS in app.css', stable.layoutOptions.filter((o) => {
|
||||
if (LAYOUT_DEFAULTS.includes(o)) return false
|
||||
const [opt, val] = o.split('=')
|
||||
return !LAYOUT_ATTR[opt] || !appCss.includes(`[${LAYOUT_ATTR[opt]}="${val}"]`)
|
||||
}))
|
||||
fail('layout options with an unknown option name', [...stable.layoutOptions, ...experimental.layoutOptions].filter((o) => !LAYOUT_ATTR[o.split('=')[0]]))
|
||||
// Every stable icon name is rendered through <HostIcon name="..."> (or the status-shape map).
|
||||
const controlsSrc = fs.readFileSync(path.join(srcDir, 'ui', 'controls.tsx'), 'utf8')
|
||||
fail('stable icon names never rendered through HostIcon', stable.icons.filter((n) =>
|
||||
!allTsx.includes(`HostIcon name="${n}"`) && !(n.startsWith('vm.state.') && controlsSrc.includes(`'${n}'`))))
|
||||
// Every stable SDK event has an emitter.
|
||||
fail('stable SDK events never emitted', stable.sdkEvents.filter((e) => !allCode.includes(`emitThemeEvent('${e}'`)))
|
||||
|
||||
fail('experimental parts already emitted (promote them to UI_CONTRACT_PARTS)', experimental.parts.filter(hasClass))
|
||||
fail('experimental slots already anchored (promote them to UI_CONTRACT_SLOTS)', experimental.slots.filter(hasSlot))
|
||||
fail('experimental layers already rendered (promote them to UI_CONTRACT_LAYERS)', experimental.layers.filter(hasLayer))
|
||||
|
||||
const overlap = (a, b) => a.filter((x) => b.includes(x))
|
||||
fail('entries listed as both stable and experimental (parts)', overlap(stable.parts, experimental.parts))
|
||||
fail('entries listed as both stable and experimental (state attributes)', overlap(stable.stateAttrs, experimental.stateAttrs))
|
||||
fail('entries listed as both stable and experimental (slots)', overlap(stable.slots, experimental.slots))
|
||||
fail('entries listed as both stable and experimental (layers)', overlap(stable.layers, experimental.layers))
|
||||
fail('entries listed as both stable and experimental (item states)', overlap(stable.itemStates, experimental.itemStates))
|
||||
fail('entries listed as both stable and experimental (layout options)', overlap(stable.layoutOptions, experimental.layoutOptions))
|
||||
fail('entries listed as both stable and experimental (icons)', overlap(stable.icons, experimental.icons))
|
||||
fail('entries listed as both stable and experimental (view locations)', overlap(stable.viewLocations, experimental.viewLocations))
|
||||
fail('entries listed as both stable and experimental (SDK events)', overlap(stable.sdkEvents, experimental.sdkEvents))
|
||||
fail('bridge methods listed as both stable and experimental', overlap(bridge.methods, bridge.experimentalMethods))
|
||||
fail('bridge events listed as both stable and experimental', overlap(bridge.events, bridge.experimentalEvents))
|
||||
|
||||
const knownParts = [...stable.parts, ...experimental.parts]
|
||||
fail('item states on unknown parts', [...stable.itemStates, ...experimental.itemStates].filter((s) => !knownParts.includes(s.split(':')[0])))
|
||||
for (const [name, list] of Object.entries({ ...stable, ...experimental, ...bridge })) {
|
||||
const dupes = list.filter((x, i) => list.indexOf(x) !== i)
|
||||
fail(`duplicate entries in ${name}`, dupes)
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
for (const e of errors) console.error(`[ui-contract] ERROR: ${e}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const write = (file, data) => {
|
||||
const text = JSON.stringify(data, null, 2) + '\n'
|
||||
fs.writeFileSync(path.join(rootDir, file), text, 'utf8')
|
||||
const distDir = path.join(rootDir, 'dist')
|
||||
if (fs.existsSync(distDir)) fs.writeFileSync(path.join(distDir, file), text, 'utf8')
|
||||
}
|
||||
write('ui-contract.json', { uiApi, ...stable, experimental })
|
||||
write('bridge-contract.json', {
|
||||
bridgeApi,
|
||||
methods: bridge.methods,
|
||||
events: bridge.events,
|
||||
experimental: { methods: bridge.experimentalMethods, events: bridge.experimentalEvents },
|
||||
})
|
||||
console.log(
|
||||
`[ui-contract] OK (uiApi=${uiApi}, parts=${stable.parts.length}+${experimental.parts.length}x, ` +
|
||||
`tokens=${stable.tokens.length}, slots=${stable.slots.length}+${experimental.slots.length}x, layers=${stable.layers.length}, ` +
|
||||
`icons=${stable.icons.length}, sdkEvents=${stable.sdkEvents.length}, ` +
|
||||
`bridgeApi=${bridgeApi}, methods=${bridge.methods.length}+${bridge.experimentalMethods.length}x)`,
|
||||
)
|
||||
@@ -0,0 +1,408 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
const rootDir = path.resolve(__dirname, '..')
|
||||
const srcDir = path.join(rootDir, 'src')
|
||||
const localesDir = path.resolve(rootDir, '..', 'locales', 'en-US')
|
||||
|
||||
// Resolve esbuild from Vite's dependency tree (zero extra npm dependencies per §8.1).
|
||||
const requireFromRoot = createRequire(path.join(rootDir, 'package.json'))
|
||||
const vitePkgPath = requireFromRoot.resolve('vite/package.json')
|
||||
const requireFromVite = createRequire(vitePkgPath)
|
||||
const esbuild = requireFromVite('esbuild')
|
||||
|
||||
async function loadBundledTS(entrySource) {
|
||||
const result = await esbuild.build({
|
||||
stdin: {
|
||||
contents: entrySource,
|
||||
resolveDir: srcDir,
|
||||
sourcefile: 'test-entry.ts',
|
||||
loader: 'ts',
|
||||
},
|
||||
bundle: true,
|
||||
write: false,
|
||||
format: 'esm',
|
||||
platform: 'browser',
|
||||
target: 'es2022',
|
||||
})
|
||||
const code = result.outputFiles[0].text
|
||||
const dataUrl = `data:text/javascript;base64,${Buffer.from(code, 'utf8').toString('base64')}`
|
||||
return import(dataUrl)
|
||||
}
|
||||
|
||||
function walkFiles(dir, exts) {
|
||||
const out = []
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) out.push(...walkFiles(full, exts))
|
||||
else if (exts.some((ext) => entry.name.endsWith(ext))) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
test('Static Guard (CRITICAL-1): lazy i18n domain keys are always backed by domain .gen imports', () => {
|
||||
const lazyDomains = ['wizard', 'settings', 'plugins']
|
||||
const keyToDomain = new Map()
|
||||
for (const dom of ['core', 'vm', ...lazyDomains]) {
|
||||
const raw = JSON.parse(fs.readFileSync(path.join(localesDir, `${dom}.json`), 'utf8'))
|
||||
for (const k of Object.keys(raw)) {
|
||||
if (!k.startsWith('$')) keyToDomain.set(k, dom)
|
||||
}
|
||||
}
|
||||
|
||||
// Known lazy-loaded chunk entry trees (loaded via React.lazy or dynamic import in App.tsx)
|
||||
const lazyEntryBasenames = new Set([
|
||||
'CreateWizard.tsx',
|
||||
'SettingsModal.tsx',
|
||||
'AffinityDialog.tsx',
|
||||
'Setup.tsx',
|
||||
'RuntimeOnline.tsx',
|
||||
'HostView.tsx',
|
||||
'ImagesPage.tsx',
|
||||
'InstallersPage.tsx',
|
||||
'PluginsPage.tsx',
|
||||
'PluginMarket.tsx',
|
||||
'PluginParts.tsx',
|
||||
'AppSettingsPage.tsx',
|
||||
'AboutPage.tsx',
|
||||
'PluginPanelFrame.tsx',
|
||||
'SchemaForm.tsx',
|
||||
'optimizations.ts',
|
||||
])
|
||||
|
||||
for (const file of walkFiles(srcDir, ['.ts', '.tsx'])) {
|
||||
const rel = path.relative(srcDir, file).replace(/\\/g, '/')
|
||||
if (rel.startsWith('i18n/')) continue
|
||||
const base = path.basename(file)
|
||||
const src = fs.readFileSync(file, 'utf8')
|
||||
|
||||
// Match string literals passed to t(..., 'key'), tr('key'), labelKey: 'key', detailKey: 'key', titleKey: 'key', descKey: 'key'
|
||||
const referencedLazyDomains = new Set()
|
||||
const callMatches = [
|
||||
...src.matchAll(/\b(?:tr|t)\(\s*(?:[a-zA-Z0-9_$.]+\s*,\s*)?'([a-zA-Z0-9_.]+)'/g),
|
||||
...src.matchAll(/\b(?:labelKey|detailKey|titleKey|descKey)\s*:\s*'([a-zA-Z0-9_.]+)'/g),
|
||||
]
|
||||
for (const m of callMatches) {
|
||||
const dom = keyToDomain.get(m[1])
|
||||
if (dom && lazyDomains.includes(dom)) {
|
||||
referencedLazyDomains.add(`${dom}:${m[1]}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (referencedLazyDomains.size === 0) continue
|
||||
|
||||
assert.ok(
|
||||
lazyEntryBasenames.has(base),
|
||||
`Eager module ${rel} references lazy domain keys (${[...referencedLazyDomains].join(', ')})! Either move keys to core/vm or lazy-load the module.`,
|
||||
)
|
||||
|
||||
for (const item of referencedLazyDomains) {
|
||||
const [dom, key] = item.split(':')
|
||||
// Sub-dialogs rendered exclusively inside lazy parent chunks inherit their parent's domain registration
|
||||
if (base === 'AffinityDialog.tsx' && dom === 'settings') continue
|
||||
if (base === 'RuntimeOnline.tsx' && (dom === 'wizard' || dom === 'settings')) continue
|
||||
assert.match(
|
||||
src,
|
||||
new RegExp(`i18n/domains/${dom}\\.gen`),
|
||||
`Module ${rel} uses ${dom} key "${key}" without importing i18n/domains/${dom}.gen`,
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('Static Guard (CRITICAL-2): every stack-*, notice-*, error-boundary*, and toast-* class in TSX exists in CSS', () => {
|
||||
const css =
|
||||
fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') +
|
||||
'\n' +
|
||||
fs.readFileSync(path.join(srcDir, 'styles', 'tokens.css'), 'utf8')
|
||||
|
||||
const prefixes = ['stack-', 'notice-', 'error-boundary', 'toast-']
|
||||
const used = new Set()
|
||||
for (const file of walkFiles(srcDir, ['.tsx'])) {
|
||||
const src = fs.readFileSync(file, 'utf8')
|
||||
for (const m of src.matchAll(/className\s*=\s*(?:"([^"]+)"|'([^']+)'|\{`([^`]+)`\})/g)) {
|
||||
const raw = (m[1] || m[2] || m[3] || '').replace(/\$\{[^}]+\}/g, ' ')
|
||||
for (const tok of raw.split(/\s+/)) {
|
||||
if (prefixes.some((p) => tok.startsWith(p))) used.add(tok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const cls of used) {
|
||||
const escaped = cls.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
assert.match(css, new RegExp(`\\.${escaped}(?![a-zA-Z0-9_-])`), `Missing CSS rule for .${cls}`)
|
||||
}
|
||||
})
|
||||
|
||||
test('Static Guard (CRITICAL-3): Radix Presence .menu/.tooltip animations never replay on close', () => {
|
||||
const rawCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8')
|
||||
const css = rawCss.replace(/\/\*[\s\S]*?\*\//g, '')
|
||||
const titleMenus = fs.readFileSync(path.join(srcDir, 'components', 'TitleMenus.tsx'), 'utf8')
|
||||
|
||||
// Unconditional `.menu` / `.tooltip` animation (including animation-name inside
|
||||
// comma-separated selector lists or reduced-motion media queries) causes Radix
|
||||
// Presence to detect an animationName change on close and flash for 160ms.
|
||||
for (const m of css.matchAll(/([^{}@]+)\{([^{}]+)\}/g)) {
|
||||
const selectors = m[1].split(',').map((s) => s.trim()).filter(Boolean)
|
||||
const decls = m[2]
|
||||
if (!/\banimation(?:-name)?\s*:(?!\s*none\b)/.test(decls)) continue
|
||||
for (const sel of selectors) {
|
||||
assert.doesNotMatch(
|
||||
sel,
|
||||
/\.menu(?![a-zA-Z0-9_-])(?!\[data-state="open"\])/,
|
||||
`Non-open .menu selector "${sel}" must not apply an active animation`,
|
||||
)
|
||||
assert.doesNotMatch(
|
||||
sel,
|
||||
/\.tooltip(?![a-zA-Z0-9_-])(?!\[data-state="delayed-open"\])/,
|
||||
`Non-delayed-open .tooltip selector "${sel}" must not apply an active animation`,
|
||||
)
|
||||
}
|
||||
}
|
||||
assert.match(
|
||||
css,
|
||||
/\.menu\[data-state="open"\]\s*\{[^}]*animation\s*:/,
|
||||
'.menu[data-state="open"] must define the menu enter animation',
|
||||
)
|
||||
assert.match(
|
||||
css,
|
||||
/\.menu\[data-state="open"\]\[data-menubar-switch="true"\][^\{]*\{[^}]*animation\s*:\s*none/,
|
||||
'.menu[data-state="open"][data-menubar-switch="true"] must disable enter animation',
|
||||
)
|
||||
assert.match(
|
||||
css,
|
||||
/\.menu\[data-state="closed"\][^\{]*\{[^}]*animation\s*:\s*none/,
|
||||
'.menu[data-state="closed"] must explicitly disable animation so Radix Presence unmounts immediately',
|
||||
)
|
||||
assert.match(
|
||||
css,
|
||||
/\.tooltip\[data-state="closed"\][^\{]*\{[^}]*animation\s*:\s*none/,
|
||||
'.tooltip[data-state="closed"] must explicitly disable animation',
|
||||
)
|
||||
assert.match(
|
||||
css,
|
||||
/@media\s*\(\s*prefers-reduced-motion\s*:\s*reduce\s*\)\s*\{[\s\S]*?\.toast\[data-state="closed"\][^{]*\{[^}]*animation-name\s*:\s*fade-out/,
|
||||
'Reduced-motion .toast[data-state="closed"] must use fade-out',
|
||||
)
|
||||
assert.doesNotMatch(
|
||||
titleMenus,
|
||||
/data-menubar-switch=\{\s*menuState\.id\s*===\s*id\s*&&\s*menuState\.switched/,
|
||||
'TitleMenus must not strip data-menubar-switch from the outgoing sibling menu on switch',
|
||||
)
|
||||
})
|
||||
|
||||
test('Static Guard (CRITICAL-4): software-composited UI avoids backdrop-filter and slow pre shaping', () => {
|
||||
const rawCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8')
|
||||
const css = rawCss.replace(/\/\*[\s\S]*?\*\//g, '')
|
||||
|
||||
// main.go sets WebviewGpuIsDisabled: true (software compositing), where
|
||||
// backdrop-filter blurs stall CPU rasterization on animations and scrolling.
|
||||
assert.doesNotMatch(
|
||||
css,
|
||||
/(?:-webkit-)?backdrop-filter\s*:/i,
|
||||
'app.css must not apply backdrop-filter under software compositing',
|
||||
)
|
||||
assert.match(
|
||||
css,
|
||||
/\.license-pre\s*\{[^}]*contain\s*:\s*content/,
|
||||
'.license-pre should isolate scroll/layout repaints with contain: content',
|
||||
)
|
||||
assert.match(
|
||||
css,
|
||||
/\.license-pre\s*\{[^}]*text-rendering\s*:\s*auto/,
|
||||
'.license-pre should opt out of global optimizeLegibility for long monospace texts',
|
||||
)
|
||||
})
|
||||
|
||||
test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppError (HIGH-2), RTL (L-2), and en-XA', async () => {
|
||||
const mod = await loadBundledTS(`
|
||||
import './i18n/domains/wizard.gen'
|
||||
import './i18n/domains/settings.gen'
|
||||
import './i18n/domains/plugins.gen'
|
||||
export * from './i18n'
|
||||
export * from './lib/format'
|
||||
export * from './lib/themeEngine'
|
||||
`)
|
||||
|
||||
// 1. Built-in bilingual + ICU plural + decimal formatting
|
||||
assert.equal(mod.formatMemory('16G', 'en-US'), '16 GB')
|
||||
assert.equal(mod.formatMemory('1536M', 'de-DE'), '1,5 GB')
|
||||
|
||||
// 2. H-3 & HIGH-9: Functional plugin L10n (has_ui_messages: false) must NOT pollute host UI locales,
|
||||
// while full language pack (has_ui_messages: true) activates properly.
|
||||
mod.setPluginLocales([
|
||||
{
|
||||
locale: 'de-DE',
|
||||
label: 'Deutsch',
|
||||
fallback: 'en-US',
|
||||
has_ui_messages: false,
|
||||
messages: {},
|
||||
plugin_messages: {
|
||||
'acme.de': { 'btn.run': 'Ausführen ({n})' },
|
||||
},
|
||||
},
|
||||
{
|
||||
locale: 'ja-JP',
|
||||
label: '日本語',
|
||||
fallback: 'en-US',
|
||||
has_ui_messages: true,
|
||||
messages: { sidebarSettings: '設定' },
|
||||
plugin_messages: {
|
||||
'acme.de': { 'btn.run': '実行 ({n})' },
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const opts = mod.getLocaleOptions().map((o) => o.value)
|
||||
assert.ok(opts.includes('ja-JP'), 'ja-JP language pack should appear in UI options')
|
||||
assert.ok(!opts.includes('de-DE'), 'de-DE functional plugin L10n must NOT appear as ghost UI locale')
|
||||
assert.equal(mod.resolveActiveLocale('de-DE'), 'en-US')
|
||||
assert.equal(mod.resolveActiveLocale('ja-JP'), 'ja-JP')
|
||||
assert.equal(mod.t('ja-JP', 'sidebarSettings'), '設定')
|
||||
assert.equal(mod.tPlugin('acme.de', 'de-DE', 'btn.run', { n: 3 }), 'Ausführen (3)')
|
||||
assert.equal(mod.getPluginMessageBundle('acme.de', 'ja-JP')['btn.run'], '実行 ({n})')
|
||||
|
||||
// 3. Pseudo-locale en-XA wraps host & plugin strings in ⟦...⟧ and preserves placeholders
|
||||
const pseudoHost = mod.t('en-XA', 'cores', { n: 8 })
|
||||
assert.ok(pseudoHost.startsWith('⟦') && pseudoHost.endsWith('⟧') && pseudoHost.includes('8'), `bad pseudoHost: ${pseudoHost}`)
|
||||
const pseudoPlugin = mod.tPlugin('acme.de', 'en-XA', 'btn.run', { n: 5 }, 'Run ({n})')
|
||||
assert.ok(pseudoPlugin.startsWith('⟦') && pseudoPlugin.includes('5'), `bad pseudoPlugin: ${pseudoPlugin}`)
|
||||
|
||||
// Reset plugin locales
|
||||
mod.setPluginLocales([])
|
||||
|
||||
// 4. HIGH-2: parseAppError handles suffix & prefix [E_CODE], multi-line summaries, codeless [detail], and Error objects
|
||||
const codedSuffix = mod.parseAppError('First summary line\nSecond summary line [E_VM_BUSY]\n[detail] raw trace line 1\nline 2')
|
||||
assert.equal(codedSuffix.code, 'E_VM_BUSY')
|
||||
assert.equal(codedSuffix.summary, 'First summary line\nSecond summary line')
|
||||
assert.equal(codedSuffix.rawDetail, 'raw trace line 1\nline 2')
|
||||
|
||||
const codedPrefix = mod.parseAppError('[E_VM_BUSY] First summary line\nSecond summary line\n[detail] raw trace line 1\nline 2')
|
||||
assert.equal(codedPrefix.code, 'E_VM_BUSY')
|
||||
assert.equal(codedPrefix.summary, 'First summary line\nSecond summary line')
|
||||
assert.equal(codedPrefix.rawDetail, 'raw trace line 1\nline 2')
|
||||
|
||||
const codelessDetail = mod.parseAppError('Human summary without code\n[detail] exit status 1')
|
||||
assert.equal(codelessDetail.code, undefined)
|
||||
assert.equal(codelessDetail.summary, 'Human summary without code')
|
||||
assert.equal(codelessDetail.rawDetail, 'exit status 1')
|
||||
|
||||
const objErr = mod.parseAppError({ message: 'Timeout [E_NET]' })
|
||||
assert.equal(objErr.code, 'E_NET')
|
||||
assert.equal(objErr.summary, 'Timeout')
|
||||
|
||||
// 5. L-2: 8-subtag RTL parity with Go backend
|
||||
for (const rtl of ['ar-SA', 'he-IL', 'iw-IL', 'fa-IR', 'ur-PK', 'ps-AF', 'dv-MV', 'yi']) {
|
||||
assert.equal(mod.isRTLLocale(rtl), true, `expected RTL for ${rtl}`)
|
||||
}
|
||||
assert.equal(mod.isRTLLocale('en-US'), false)
|
||||
assert.equal(mod.isRTLLocale('zh-TW'), false)
|
||||
|
||||
// 6. LOW-5: resolveGuestLang structured preset lookup without punctuation splitting
|
||||
const zhGuest = mod.resolveGuestLang('zh-CN', 'zh-Hans:0')
|
||||
assert.ok(zhGuest.label.length > 0 && zhGuest.detail && zhGuest.detail.length > 0)
|
||||
|
||||
// 7. HIGH-1: Theme seed token derivation enforces WCAG 2.1 AA contrast on bright vs dark accents
|
||||
const hslContrast = (hslStr, surfaceLum) => {
|
||||
const m = hslStr.match(/hsl\(\s*(\d+)\s+(\d+)%\s+(\d+)%\s*\)/)
|
||||
assert.ok(m, `unexpected hsl string: ${hslStr}`)
|
||||
const h = Number(m[1]), s = Number(m[2]) / 100, l = Number(m[3]) / 100
|
||||
const c = (1 - Math.abs(2 * l - 1)) * s
|
||||
const hp = (h % 360) / 60
|
||||
const x = c * (1 - Math.abs((hp % 2) - 1))
|
||||
const [r1, g1, b1] = hp < 1 ? [c, x, 0] : hp < 2 ? [x, c, 0] : hp < 3 ? [0, c, x] : hp < 4 ? [0, x, c] : hp < 5 ? [x, 0, c] : [c, 0, x]
|
||||
const mv = l - c / 2
|
||||
const lin = (v) => (v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4))
|
||||
const lum = 0.2126 * lin(r1 + mv) + 0.7152 * lin(g1 + mv) + 0.0722 * lin(b1 + mv)
|
||||
return (Math.max(lum, surfaceLum) + 0.05) / (Math.min(lum, surfaceLum) + 0.05)
|
||||
}
|
||||
const brightYellow = mod.deriveTokensFromSeeds({ accent: '#ffd60a' }, undefined, 'light')
|
||||
assert.equal(brightYellow['--accent-text'], '#1d1d1f')
|
||||
assert.ok(hslContrast(brightYellow['--accent-soft-text'], 0.92) >= 4.5, `yellow light contrast too low: ${brightYellow['--accent-soft-text']}`)
|
||||
|
||||
const pureBlueDark = mod.deriveTokensFromSeeds({ accent: '#0000ff' }, undefined, 'dark')
|
||||
assert.ok(hslContrast(pureBlueDark['--accent-soft-text'], 0.015) >= 4.5, `blue dark contrast too low: ${pureBlueDark['--accent-soft-text']}`)
|
||||
|
||||
const appleBlue = mod.deriveTokensFromSeeds({ accent: '#0071e3' }, undefined, 'dark')
|
||||
assert.equal(appleBlue['--accent-text'], '#ffffff')
|
||||
assert.ok(hslContrast(appleBlue['--accent-soft-text'], 0.015) >= 4.5, `appleBlue dark contrast too low: ${appleBlue['--accent-soft-text']}`)
|
||||
})
|
||||
|
||||
|
||||
test('VM keymap preserves preset bindings and isolates pending writes by VM', async () => {
|
||||
const source = fs.readFileSync(path.join(srcDir, 'components/SettingsModal.tsx'), 'utf8')
|
||||
const normalized = source.replaceAll('\r\n', '\n')
|
||||
const effects = normalized.slice(
|
||||
normalized.indexOf(' useEffect(() => {\n setKeymap(null)'),
|
||||
normalized.indexOf(' const updateDriveShares'),
|
||||
)
|
||||
const preset = normalized.match(/onChange=\{(\(preset\) => \{\n\s+if \(preset === keymap\.preset\)[\s\S]*?\n\s+\})\} \/>/)?.[1]
|
||||
assert.ok(effects.includes('const updateKeymap') && preset)
|
||||
const { render } = await loadBundledTS(`
|
||||
export function render({ detail, api, useEffect, window, activeVMNameRef, keymapWrite,
|
||||
keymapRevision, setKeymap, setKeymapErr, setKeymapBusy, parseAppError, keymap }) {
|
||||
const cat = 'input'
|
||||
const running = true
|
||||
${effects}
|
||||
return ${preset}
|
||||
}
|
||||
`)
|
||||
let finishWrite
|
||||
const writes = []
|
||||
const reads = []
|
||||
const state = {}
|
||||
let failRead = true
|
||||
const context = {
|
||||
api: {
|
||||
SetVMKeymap(name, req) {
|
||||
writes.push([name, req])
|
||||
return new Promise((resolve) => { finishWrite = resolve })
|
||||
},
|
||||
async GetVMKeymap(name) {
|
||||
reads.push(name)
|
||||
if (name === 'b' && failRead) throw Error('temporary')
|
||||
return { preset: 'off', bindings: {} }
|
||||
},
|
||||
},
|
||||
useEffect(effect) {
|
||||
const cleanup = effect()
|
||||
if (cleanup) this.cleanups.push(cleanup)
|
||||
},
|
||||
cleanups: [],
|
||||
window: { setInterval(refresh) { this.refresh = refresh }, clearInterval() {} },
|
||||
activeVMNameRef: { current: 'a' },
|
||||
keymapWrite: { current: new Set() },
|
||||
keymapRevision: { current: new Map() },
|
||||
setKeymap(value) { state.keymap = value },
|
||||
setKeymapErr(value) { state.error = value },
|
||||
setKeymapBusy(value) { state.busy = value },
|
||||
parseAppError: (error) => ({ summary: error.message }),
|
||||
}
|
||||
context.useEffect = context.useEffect.bind(context)
|
||||
const bindings = { lwin: 'lcmd' }
|
||||
const change = render({ ...context, detail: { name: 'a' }, keymap: { preset: 'win_to_cmd', bindings } })
|
||||
change('win_to_cmd')
|
||||
assert.deepEqual(writes, [])
|
||||
change('custom')
|
||||
assert.deepEqual(writes, [['a', { preset: 'custom', bindings }]])
|
||||
context.cleanups.pop()()
|
||||
context.activeVMNameRef.current = 'b'
|
||||
const changeB = render({ ...context, detail: { name: 'b' }, keymap: { preset: 'custom', bindings } })
|
||||
changeB('custom')
|
||||
assert.equal(writes.length, 1)
|
||||
assert.deepEqual(reads, ['a', 'b'])
|
||||
assert.equal(state.busy, false)
|
||||
await new Promise(setImmediate)
|
||||
assert.equal(state.error, 'temporary')
|
||||
failRead = false
|
||||
await context.window.refresh()
|
||||
assert.equal(state.error, '')
|
||||
finishWrite({ preset: 'custom', bindings })
|
||||
await new Promise(setImmediate)
|
||||
assert.deepEqual(state.keymap, { preset: 'off', bindings: {} })
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
// macOS UI lives under src/macos so it can leave the app as a plugin. Host
|
||||
// files may import from it only while listed below; the test fails when a new
|
||||
// file starts importing it and when a listed file stops, so the list only
|
||||
// shrinks (same ratchet as internal/archtest on the Go side).
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import ts from 'typescript'
|
||||
|
||||
const srcDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src')
|
||||
const macosDir = path.join(srcDir, 'macos')
|
||||
|
||||
const MACOS_IMPORTERS = {
|
||||
'App.tsx': 'mounts the installers page and online-recovery dialog; macOS release names in the VM list',
|
||||
'components/Sidebar.tsx': 'macOS version art next to each VM',
|
||||
'components/VMPage.tsx': 'macOS version art in the VM header',
|
||||
}
|
||||
|
||||
function walk(dir) {
|
||||
const out = []
|
||||
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, e.name)
|
||||
if (e.isDirectory()) {
|
||||
if (p !== macosDir) out.push(...walk(p))
|
||||
} else if (/\.(?:[cm]?[jt]s|[jt]sx)$/.test(e.name)) {
|
||||
out.push(p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
test('host frontend reaches src/macos only from listed files', () => {
|
||||
const importers = new Set()
|
||||
for (const file of walk(srcDir)) {
|
||||
const text = fs.readFileSync(file, 'utf8')
|
||||
for (const { fileName } of ts.preProcessFile(text, true, true).importedFiles) {
|
||||
let target
|
||||
if (fileName.startsWith('.')) target = path.resolve(path.dirname(file), fileName)
|
||||
else if (fileName.startsWith('/src/')) target = path.resolve(srcDir, fileName.slice(5))
|
||||
else continue
|
||||
if (target === macosDir || target.startsWith(macosDir + path.sep)) {
|
||||
importers.add(path.relative(srcDir, file).split(path.sep).join('/'))
|
||||
}
|
||||
}
|
||||
}
|
||||
const unexpected = [...importers].filter((f) => !(f in MACOS_IMPORTERS)).sort()
|
||||
const stale = Object.keys(MACOS_IMPORTERS).filter((f) => !importers.has(f)).sort()
|
||||
assert.deepEqual(unexpected, [], `host files import src/macos without being listed in MACOS_IMPORTERS: ${unexpected.join(', ')}`)
|
||||
assert.deepEqual(stale, [], `listed files no longer import src/macos; remove them from MACOS_IMPORTERS: ${stale.join(', ')}`)
|
||||
})
|
||||
@@ -0,0 +1,396 @@
|
||||
// Guards the AGENTS.md rule forbidding empty catch blocks that silently turn
|
||||
// failures into successes. Covers JS/TS/JSX/TSX/MJS/CJS via the TypeScript AST
|
||||
// and PowerShell (.ps1/.psm1/.psd1) via a comment- and string-aware lexer.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import ts from 'typescript'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
const repoRoot = path.resolve(__dirname, '..', '..')
|
||||
|
||||
const JS_TS_EXTS = new Set(['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'])
|
||||
const PS_EXTS = new Set(['.ps1', '.psm1', '.psd1'])
|
||||
const SKIP_DIRS = new Set(['.git', '.debug', 'node_modules', 'dist', 'build', 'wailsjs'])
|
||||
|
||||
function scriptKindFor(filePath) {
|
||||
switch (path.extname(filePath).toLowerCase()) {
|
||||
case '.tsx': return ts.ScriptKind.TSX
|
||||
case '.ts':
|
||||
case '.mts':
|
||||
case '.cts': return ts.ScriptKind.TS
|
||||
case '.jsx': return ts.ScriptKind.JSX
|
||||
default: return ts.ScriptKind.JS
|
||||
}
|
||||
}
|
||||
|
||||
function isEmptyBlock(block) {
|
||||
return ts.isBlock(block) && block.statements.every((stmt) => ts.isEmptyStatement(stmt))
|
||||
}
|
||||
|
||||
function isEmptyFunctionBody(expr) {
|
||||
let current = expr
|
||||
while (ts.isParenthesizedExpression(current)) current = current.expression
|
||||
if (ts.isArrowFunction(current) || ts.isFunctionExpression(current)) {
|
||||
return isEmptyBlock(current.body)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function getCalleeMethodName(callee) {
|
||||
if (ts.isPropertyAccessExpression(callee)) return callee.name.text
|
||||
if (ts.isElementAccessExpression(callee) && ts.isStringLiteralLike(callee.argumentExpression)) {
|
||||
return callee.argumentExpression.text
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds empty `catch` clauses and empty Promise `.catch(...)` / `.then(_, ...)`
|
||||
* rejection callbacks in a JS/TS source string using the TypeScript AST.
|
||||
*/
|
||||
export function findEmptyCatchesInJS(sourceText, filePath = 'sample.ts') {
|
||||
const sf = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true, scriptKindFor(filePath))
|
||||
const findings = []
|
||||
|
||||
const record = (node, kind) => {
|
||||
const pos = sf.getLineAndCharacterOfPosition(node.getStart(sf))
|
||||
findings.push({
|
||||
file: filePath,
|
||||
line: pos.line + 1,
|
||||
column: pos.character + 1,
|
||||
kind,
|
||||
})
|
||||
}
|
||||
|
||||
function visit(node) {
|
||||
if (ts.isCatchClause(node) && isEmptyBlock(node.block)) {
|
||||
record(node, 'empty-catch-clause')
|
||||
} else if (ts.isCallExpression(node)) {
|
||||
const method = getCalleeMethodName(node.expression)
|
||||
if (method === 'catch' && node.arguments.length >= 1 && isEmptyFunctionBody(node.arguments[0])) {
|
||||
record(node.arguments[0], 'empty-promise-catch')
|
||||
} else if (method === 'then' && node.arguments.length >= 2 && isEmptyFunctionBody(node.arguments[1])) {
|
||||
record(node.arguments[1], 'empty-promise-then-reject')
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
|
||||
visit(sf)
|
||||
return findings
|
||||
}
|
||||
|
||||
function tokenizePowerShell(sourceText) {
|
||||
const tokens = []
|
||||
let i = 0
|
||||
let line = 1
|
||||
let col = 1
|
||||
const len = sourceText.length
|
||||
|
||||
const advance = () => {
|
||||
const ch = sourceText[i++]
|
||||
if (ch === '\n') {
|
||||
line += 1
|
||||
col = 1
|
||||
} else {
|
||||
col += 1
|
||||
}
|
||||
return ch
|
||||
}
|
||||
|
||||
const atHereStringEnd = (quote) => {
|
||||
if (sourceText[i] !== quote || sourceText[i + 1] !== '@') return false
|
||||
return i === 0 || sourceText[i - 1] === '\n'
|
||||
}
|
||||
|
||||
while (i < len) {
|
||||
const ch = sourceText[i]
|
||||
const next = sourceText[i + 1]
|
||||
|
||||
// Whitespace
|
||||
if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') {
|
||||
advance()
|
||||
continue
|
||||
}
|
||||
|
||||
// Block comment <# ... #>
|
||||
if (ch === '<' && next === '#') {
|
||||
advance()
|
||||
advance()
|
||||
while (i < len && !(sourceText[i] === '#' && sourceText[i + 1] === '>')) advance()
|
||||
if (i < len) {
|
||||
advance()
|
||||
advance()
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Line comment # ...
|
||||
if (ch === '#') {
|
||||
while (i < len && sourceText[i] !== '\n') advance()
|
||||
continue
|
||||
}
|
||||
|
||||
// Here-strings @' ... '@ and @" ... "@
|
||||
if (ch === '@' && (next === "'" || next === '"')) {
|
||||
const quote = next
|
||||
let look = i + 2
|
||||
while (look < len && (sourceText[look] === ' ' || sourceText[look] === '\t' || sourceText[look] === '\r')) look++
|
||||
if (look < len && sourceText[look] === '\n') {
|
||||
const startLine = line
|
||||
const startCol = col
|
||||
while (i <= look) advance()
|
||||
while (i < len && !atHereStringEnd(quote)) advance()
|
||||
if (i < len) {
|
||||
advance()
|
||||
advance()
|
||||
}
|
||||
tokens.push({ type: 'string', value: '', line: startLine, column: startCol })
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Single-quoted string ('' escapes ')
|
||||
if (ch === "'") {
|
||||
const startLine = line
|
||||
const startCol = col
|
||||
advance()
|
||||
while (i < len) {
|
||||
if (sourceText[i] === "'") {
|
||||
advance()
|
||||
if (sourceText[i] === "'") {
|
||||
advance()
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
advance()
|
||||
}
|
||||
tokens.push({ type: 'string', value: '', line: startLine, column: startCol })
|
||||
continue
|
||||
}
|
||||
|
||||
// Double-quoted string (` escapes next char, "" escapes ")
|
||||
if (ch === '"') {
|
||||
const startLine = line
|
||||
const startCol = col
|
||||
advance()
|
||||
while (i < len) {
|
||||
if (sourceText[i] === '`') {
|
||||
advance()
|
||||
if (i < len) advance()
|
||||
continue
|
||||
}
|
||||
if (sourceText[i] === '"') {
|
||||
advance()
|
||||
if (sourceText[i] === '"') {
|
||||
advance()
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
advance()
|
||||
}
|
||||
tokens.push({ type: 'string', value: '', line: startLine, column: startCol })
|
||||
continue
|
||||
}
|
||||
|
||||
// Backtick escape outside strings
|
||||
if (ch === '`') {
|
||||
advance()
|
||||
if (i < len) advance()
|
||||
continue
|
||||
}
|
||||
|
||||
const startLine = line
|
||||
const startCol = col
|
||||
|
||||
// :: operator
|
||||
if (ch === ':' && next === ':') {
|
||||
advance()
|
||||
advance()
|
||||
tokens.push({ type: 'punct', value: '::', line: startLine, column: startCol })
|
||||
continue
|
||||
}
|
||||
|
||||
// Punctuation relevant to catch syntax
|
||||
if ('{}[];,.'.includes(ch)) {
|
||||
advance()
|
||||
tokens.push({ type: 'punct', value: ch, line: startLine, column: startCol })
|
||||
continue
|
||||
}
|
||||
|
||||
// Word / identifier / parameter (e.g. -catch, catch)
|
||||
if (/[A-Za-z_-]/.test(ch)) {
|
||||
let word = ''
|
||||
while (i < len && /[A-Za-z0-9_-]/.test(sourceText[i])) word += advance()
|
||||
tokens.push({ type: 'word', value: word, line: startLine, column: startCol })
|
||||
continue
|
||||
}
|
||||
|
||||
// Any other token
|
||||
advance()
|
||||
tokens.push({ type: 'other', value: ch, line: startLine, column: startCol })
|
||||
}
|
||||
|
||||
return tokens
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds empty `catch` blocks (including comment-only and semicolon-only blocks,
|
||||
* with or without `[Type]` exception filters) in a PowerShell script.
|
||||
*/
|
||||
export function findEmptyCatchesInPowerShell(sourceText, filePath = 'sample.ps1') {
|
||||
const tokens = tokenizePowerShell(sourceText)
|
||||
const findings = []
|
||||
|
||||
for (let idx = 0; idx < tokens.length; idx++) {
|
||||
const tok = tokens[idx]
|
||||
if (tok.type !== 'word' || tok.value.toLowerCase() !== 'catch') continue
|
||||
const prev = tokens[idx - 1]
|
||||
if (prev && (prev.value === '.' || prev.value === '::')) continue
|
||||
|
||||
// Skip optional comma-separated type filters: catch [TypeA], [TypeB] { ... }
|
||||
let cursor = idx + 1
|
||||
while (cursor < tokens.length && tokens[cursor].value === '[') {
|
||||
let depth = 0
|
||||
while (cursor < tokens.length) {
|
||||
if (tokens[cursor].value === '[') depth++
|
||||
else if (tokens[cursor].value === ']') {
|
||||
depth--
|
||||
if (depth === 0) {
|
||||
cursor++
|
||||
break
|
||||
}
|
||||
}
|
||||
cursor++
|
||||
}
|
||||
if (cursor < tokens.length && tokens[cursor].value === ',') cursor++
|
||||
else break
|
||||
}
|
||||
|
||||
if (cursor >= tokens.length || tokens[cursor].value !== '{') continue
|
||||
|
||||
// Scan block body until matching '}'
|
||||
let bodyCursor = cursor + 1
|
||||
let empty = true
|
||||
while (bodyCursor < tokens.length && tokens[bodyCursor].value !== '}') {
|
||||
if (tokens[bodyCursor].value !== ';') {
|
||||
empty = false
|
||||
break
|
||||
}
|
||||
bodyCursor++
|
||||
}
|
||||
if (empty && bodyCursor < tokens.length && tokens[bodyCursor].value === '}') {
|
||||
findings.push({
|
||||
file: filePath,
|
||||
line: tok.line,
|
||||
column: tok.column,
|
||||
kind: 'empty-ps-catch',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return findings
|
||||
}
|
||||
|
||||
function walkFiles(dir, out = []) {
|
||||
if (!fs.existsSync(dir)) return out
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue
|
||||
const full = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) walkFiles(full, out)
|
||||
else out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
test('detector self-test: catches all empty JS/TS catch forms and allows handled catches', () => {
|
||||
const bad = [
|
||||
'try { a() } catch {}',
|
||||
'try { a() } catch (e) {}',
|
||||
'try { a() } catch { /* comment only */ }',
|
||||
'try { a() } catch (e) {\n // comment only\n}',
|
||||
'try { a() } catch { ; ; }',
|
||||
'p.catch(() => {})',
|
||||
'p?.catch((e) => { /* noop */ })',
|
||||
'p["catch"](function () {})',
|
||||
'p.catch(async () => { ; })',
|
||||
'p.then(ok, () => {})',
|
||||
'p.then(ok, (err) => { // noop\n})',
|
||||
].join('\n')
|
||||
|
||||
const badFindings = findEmptyCatchesInJS(bad, 'bad.ts')
|
||||
assert.equal(badFindings.length, 11, `expected 11 findings, got ${JSON.stringify(badFindings)}`)
|
||||
|
||||
const good = [
|
||||
'const text = "try { a() } catch {} .catch(() => {})"',
|
||||
'// try { a() } catch {}',
|
||||
'try { a() } catch (e) { console.warn(e) }',
|
||||
'try { a() } catch { return fallback }',
|
||||
'p.catch((e) => console.warn(e))',
|
||||
'p.catch(() => null)',
|
||||
'p.then(ok, (e) => handle(e))',
|
||||
].join('\n')
|
||||
|
||||
assert.deepEqual(findEmptyCatchesInJS(good, 'good.ts'), [])
|
||||
})
|
||||
|
||||
test('detector self-test: catches empty PowerShell catch blocks and ignores strings/comments', () => {
|
||||
const bad = [
|
||||
'try { foo } catch {}',
|
||||
'try { foo } Catch { # comment only\n}',
|
||||
'try { foo } catch { <# block comment #> ; }',
|
||||
'try { foo } catch [System.IO.IOException], [System.Exception] {}',
|
||||
].join('\n')
|
||||
|
||||
const badFindings = findEmptyCatchesInPowerShell(bad, 'bad.ps1')
|
||||
assert.equal(badFindings.length, 4, `expected 4 findings, got ${JSON.stringify(badFindings)}`)
|
||||
|
||||
const good = [
|
||||
'# try { foo } catch {}',
|
||||
'<# try { foo } catch {} #>',
|
||||
'$s1 = "try { foo } catch {}"',
|
||||
"$s2 = 'try { foo } catch {}'",
|
||||
'$here = @"\ntry { foo } catch {}\n"@',
|
||||
'$obj.catch { }',
|
||||
'try { foo } catch { Write-Warning $_ }',
|
||||
'try { foo } catch [System.Exception] { throw }',
|
||||
].join('\n')
|
||||
|
||||
assert.deepEqual(findEmptyCatchesInPowerShell(good, 'good.ps1'), [])
|
||||
})
|
||||
|
||||
test('repository has zero empty catch blocks across frontend/ and scripts/', () => {
|
||||
const roots = [path.join(repoRoot, 'frontend'), path.join(repoRoot, 'scripts')]
|
||||
const violations = []
|
||||
let scannedJS = 0
|
||||
let scannedPS = 0
|
||||
|
||||
for (const root of roots) {
|
||||
for (const file of walkFiles(root)) {
|
||||
const ext = path.extname(file).toLowerCase()
|
||||
const rel = path.relative(repoRoot, file).split(path.sep).join('/')
|
||||
if (JS_TS_EXTS.has(ext)) {
|
||||
scannedJS += 1
|
||||
const text = fs.readFileSync(file, 'utf8')
|
||||
violations.push(...findEmptyCatchesInJS(text, rel))
|
||||
} else if (PS_EXTS.has(ext)) {
|
||||
scannedPS += 1
|
||||
const text = fs.readFileSync(file, 'utf8')
|
||||
violations.push(...findEmptyCatchesInPowerShell(text, rel))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert.ok(scannedJS > 0, 'expected to scan at least one JS/TS file')
|
||||
assert.ok(scannedPS > 0, 'expected to scan at least one PowerShell file')
|
||||
assert.deepEqual(
|
||||
violations.map((v) => `${v.file}:${v.line}:${v.column} (${v.kind})`),
|
||||
[],
|
||||
`Empty catch blocks found (forbidden by AGENTS.md):\n${violations.map((v) => ` - ${v.file}:${v.line}:${v.column} (${v.kind})`).join('\n')}`,
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,386 @@
|
||||
import { Copy, Download, ExternalLink, RotateCw, Scale } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
import { AppUpdateInfo, Locale, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { Segmented } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
import { REPO_URL } from './TitleMenus'
|
||||
import type { UpdatePhase } from './UpdateCapsule'
|
||||
import { BrandMark } from '../ui/themeVisuals'
|
||||
|
||||
const DISCORD_INVITE_URL = 'https://discord.gg/Tj682rW5rS'
|
||||
const QQ_GROUP_ID = '1136042744'
|
||||
|
||||
export type AppUpdateChannel = 'stable' | 'alpha' | 'dev'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
appVersion?: string
|
||||
appUpdateChannel: AppUpdateChannel
|
||||
onAppUpdateChannel: (channel: AppUpdateChannel) => Promise<void> | void
|
||||
/** 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 community channels. */
|
||||
export const AboutPage: React.FC<Props> = ({
|
||||
locale, appVersion, appUpdateChannel, onAppUpdateChannel, 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 [switchingChannel, setSwitchingChannel] = useState(false)
|
||||
const [updateErr, setUpdateErr] = useState('')
|
||||
const [qqInstalled, setQQInstalled] = useState<boolean | null>(null)
|
||||
const [openingQQ, setOpeningQQ] = useState(false)
|
||||
const [qqLaunchErr, setQQLaunchErr] = useState('')
|
||||
const [licenseOpen, setLicenseOpen] = useState(false)
|
||||
const [licenseTab, setLicenseTab] = useState<'notice' | 'license'>('notice')
|
||||
const [licenses, setLicenses] = useState<{ license: string; notice: string } | null>(null)
|
||||
const mountedRef = useRef(true)
|
||||
const loadingLicensesRef = useRef(false)
|
||||
const licensePreRef = useRef<HTMLPreElement>(null)
|
||||
|
||||
const openLicenses = async () => {
|
||||
if (licenses) {
|
||||
setLicenseOpen(true)
|
||||
return
|
||||
}
|
||||
if (loadingLicensesRef.current) return
|
||||
loadingLicensesRef.current = true
|
||||
try {
|
||||
// Load embedded license text before mounting the modal so the dialog opens
|
||||
// with its final content on frame 1 instead of reflowing mid-animation.
|
||||
const res = await api.GetLicenseTexts()
|
||||
if (!mountedRef.current) return
|
||||
setLicenses({ license: res?.license ?? '', notice: res?.notice ?? '' })
|
||||
setLicenseOpen(true)
|
||||
} catch (e) {
|
||||
if (mountedRef.current) onError(tr('failGeneric'), e)
|
||||
} finally {
|
||||
loadingLicensesRef.current = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleLicenseTabChange = (next: 'notice' | 'license') => {
|
||||
setLicenseTab(next)
|
||||
if (licensePreRef.current) licensePreRef.current.scrollTop = 0
|
||||
}
|
||||
|
||||
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(() => {
|
||||
mountedRef.current = true
|
||||
if (!appUpdate) void runUpdateCheck(false)
|
||||
let cancelled = false
|
||||
api.CanOpenQQGroup()
|
||||
.then((ok) => { if (!cancelled) setQQInstalled(!!ok) })
|
||||
.catch(() => { if (!cancelled) setQQInstalled(false) })
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
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 handleChannelChange = async (next: AppUpdateChannel) => {
|
||||
if (next === appUpdateChannel || switchingChannel) return
|
||||
setSwitchingChannel(true)
|
||||
setUpdateErr('')
|
||||
try {
|
||||
await onAppUpdateChannel(next)
|
||||
} catch (e) {
|
||||
setUpdateErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
setSwitchingChannel(false)
|
||||
}
|
||||
}
|
||||
|
||||
const version = appVersion ?? appUpdate?.current ?? ''
|
||||
const pct = updateTask && updateTask.percent >= 0 ? Math.round(updateTask.percent) : null
|
||||
const updateAvailableKey: I18nKey = appUpdate?.channel === 'dev'
|
||||
? 'appUpdateAvailableDev'
|
||||
: appUpdate?.channel === 'alpha'
|
||||
? 'appUpdateAvailableAlpha'
|
||||
: 'appUpdateAvailable'
|
||||
|
||||
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 rg-p-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(updateAvailableKey, { 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">
|
||||
<BrandMark className="about-hero-mark" />
|
||||
<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 rg-p-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 className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('appUpdateChannelTitle')}</div>
|
||||
<div className="row-sub">
|
||||
{appUpdateChannel === 'stable'
|
||||
? tr('appUpdateChannelSubStable')
|
||||
: tr('appUpdateChannelSubKeepOld', {
|
||||
channel: appUpdateChannel === 'dev' ? tr('appUpdateChannelDev') : tr('appUpdateChannelAlpha'),
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Segmented
|
||||
label={tr('appUpdateChannelTitle')}
|
||||
value={appUpdateChannel}
|
||||
onChange={(v) => void handleChannelChange(v)}
|
||||
options={[
|
||||
{ value: 'stable' as AppUpdateChannel, label: tr('appUpdateChannelStable'), disabled: switchingChannel || checkingUpdate || updatePhase === 'downloading' || installing },
|
||||
{ value: 'alpha' as AppUpdateChannel, label: tr('appUpdateChannelAlpha'), disabled: switchingChannel || checkingUpdate || updatePhase === 'downloading' || installing },
|
||||
{ value: 'dev' as AppUpdateChannel, label: tr('appUpdateChannelDev'), disabled: switchingChannel || checkingUpdate || updatePhase === 'downloading' || installing },
|
||||
]}
|
||||
/>
|
||||
</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('aboutLicensesTitle')}</div>
|
||||
<div className="row-sub">{tr('aboutLicensesSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button icon={<Scale size={14} aria-hidden="true" />} onClick={() => void openLicenses()}>
|
||||
{tr('aboutLicensesView')}
|
||||
</Button>
|
||||
<Button variant="ghost" icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(`${REPO_URL}/blob/main/NOTICE.md`)}>
|
||||
{tr('openShort')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('aboutDiscord')}</div>
|
||||
<div className="row-sub">{tr('aboutDiscordSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{onCopy && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('aboutCopyDiscord')}
|
||||
icon={<Copy size={14} aria-hidden="true" />}
|
||||
onClick={() => onCopy(DISCORD_INVITE_URL)}
|
||||
/>
|
||||
)}
|
||||
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(DISCORD_INVITE_URL)}>
|
||||
{tr('aboutJoinDiscord')}
|
||||
</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 rg-p-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>
|
||||
{licenseOpen && (
|
||||
<Modal
|
||||
title={tr('aboutLicensesTitle')}
|
||||
subtitle={tr('aboutLicensesSub')}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setLicenseOpen(false)}
|
||||
>
|
||||
<div className="dialog-body license-modal-body">
|
||||
<Segmented
|
||||
label={tr('aboutLicensesTitle')}
|
||||
value={licenseTab}
|
||||
onChange={handleLicenseTabChange}
|
||||
options={[
|
||||
{ value: 'notice', label: tr('aboutLicensesTabNotice') },
|
||||
{ value: 'license', label: tr('aboutLicensesTabLicense') },
|
||||
]}
|
||||
/>
|
||||
<pre
|
||||
ref={licensePreRef}
|
||||
className="license-pre"
|
||||
dir="ltr"
|
||||
tabIndex={0}
|
||||
role="region"
|
||||
aria-label={licenseTab === 'notice' ? tr('aboutLicensesTabNotice') : tr('aboutLicensesTabLicense')}
|
||||
>
|
||||
{licenses
|
||||
? (licenseTab === 'notice' ? licenses.notice : licenses.license)
|
||||
: ''}
|
||||
</pre>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon={<ExternalLink size={14} aria-hidden="true" />}
|
||||
onClick={() => openURL(`${REPO_URL}/blob/main/${licenseTab === 'notice' ? 'NOTICE.md' : 'LICENSE'}`)}
|
||||
>
|
||||
{tr('aboutLicensesOpenGitHub')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={() => setLicenseOpen(false)}>
|
||||
{tr('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
import { AlertTriangle, Check, Cpu } from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, parseAppError, 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
|
||||
driverID: 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, driverID, 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.GetVMAffinityWithDriver(driverID, 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(parseAppError(e).summary)
|
||||
})
|
||||
.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.SetVMAffinityWithDriver(driverID, vmName, {
|
||||
mode,
|
||||
cpus: mode === 'custom' ? selected : [],
|
||||
disable_eco_qos: disableEcoQoS,
|
||||
})
|
||||
onApplied(updated)
|
||||
} catch (e) {
|
||||
setErr(parseAppError(e).summary)
|
||||
} 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,189 @@
|
||||
import React from 'react'
|
||||
import { PowerOff } from 'lucide-react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
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 quitMode = state.quit_mode
|
||||
|
||||
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
|
||||
const missingFontScript = state.missing_font_hint || ''
|
||||
const memSpecLabel = host.memory_spec?.speed_mhz
|
||||
? `${host.memory_spec.speed_mhz} MHz${host.memory_spec.type_name ? ` ${host.memory_spec.type_name}` : ''}`
|
||||
: ''
|
||||
|
||||
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)
|
||||
})
|
||||
|
||||
const forceQuit = async () => {
|
||||
try {
|
||||
await api.ForceQuitApp()
|
||||
} catch (e) {
|
||||
onError(tr('quitFailed'), e)
|
||||
}
|
||||
}
|
||||
|
||||
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 rg-p-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('syncHostMemorySMBIOS')}</div>
|
||||
<div className="row-sub">
|
||||
{memSpecLabel
|
||||
? tr('syncHostMemorySMBIOSSub', { spec: memSpecLabel })
|
||||
: tr('syncHostMemorySMBIOSUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Switch
|
||||
label={tr('syncHostMemorySMBIOS')}
|
||||
disabled={!memSpecLabel}
|
||||
checked={!!memSpecLabel && !!config.sync_host_memory_smbios}
|
||||
onChange={(checked) => guard(() => api.SetSyncHostMemorySMBIOS(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 className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('forceQuitAppTitle')}</div>
|
||||
<div className="row-sub">{tr('forceQuitAppSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button variant="danger" onClick={forceQuit} busy={quitMode === 'force'} icon={<PowerOff size={14} aria-hidden="true" />}>
|
||||
{tr(quitMode === 'force' ? 'forceQuitInProgress' : 'forceQuitAppButton')}
|
||||
</Button>
|
||||
</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>
|
||||
{missingFontScript && (
|
||||
<div className="row-sub warn-text">{tr('fontMissingFoDHint', { script: missingFontScript })}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<PopupSelect
|
||||
label={tr('language')}
|
||||
value={config.locale || 'auto'}
|
||||
onChange={onSetLocale}
|
||||
options={getLocaleOptions(locales, locale, state.detected_locale)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -18,18 +18,20 @@ export const CloneDialog: React.FC<Props> = ({ locale, sourceName, defaultCloneN
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
|
||||
<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" style={{ marginTop: 10 }}>
|
||||
<div className="field field-spaced">
|
||||
<label className="field-label" htmlFor="clone-name">{t(locale, 'cloneNameLabel')}</label>
|
||||
<input
|
||||
id="clone-name"
|
||||
className="input mono"
|
||||
className="input rg-p-input mono"
|
||||
value={cloneName}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
onChange={(e) => setCloneName(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' && trimmed) onConfirm(trimmed) }}
|
||||
autoFocus
|
||||
@@ -38,10 +40,10 @@ export const CloneDialog: React.FC<Props> = ({ locale, sourceName, defaultCloneN
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn">{t(locale, 'cancel')}</button>
|
||||
<button type="button" className="btn rg-p-button">{t(locale, 'cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-primary" disabled={!trimmed} onClick={() => onConfirm(trimmed)}>
|
||||
<button type="button" className="btn rg-p-button btn-primary" disabled={!trimmed} onClick={() => onConfirm(trimmed)}>
|
||||
{t(locale, 'cloneConfirm')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
|
||||
@@ -1,17 +1,28 @@
|
||||
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import React, { Suspense, lazy, useEffect, useState } from 'react'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, locText, parseAppError, t } from '../i18n'
|
||||
import {
|
||||
GUEST_LANG_PRESETS,
|
||||
guestLangOptions,
|
||||
MEMORY_MARKS,
|
||||
controllerLabel,
|
||||
defaultGuestLang,
|
||||
findGPU,
|
||||
formatMemory,
|
||||
gpuCompatHint,
|
||||
gpuLabel,
|
||||
gpuOptionValue,
|
||||
guestLangLabel,
|
||||
memorySafeLimitGB,
|
||||
parseMemoryGB,
|
||||
recommendedCPUs,
|
||||
fullscreenDisplayPresets,
|
||||
FullscreenDisplayPreset,
|
||||
hidpiLooksLike,
|
||||
hostDisplayAdvice,
|
||||
hostDisplayDesc,
|
||||
recommendedDisplayPresets,
|
||||
recommendedMemoryGB,
|
||||
recommendedResolution,
|
||||
@@ -19,12 +30,16 @@ import {
|
||||
splitLangLabel,
|
||||
sshCommand,
|
||||
} from '../lib/format'
|
||||
import { CachedInstaller, CreateOpts, HostReport, Locale, Release, ValidationIssue } from '../types'
|
||||
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue } from '../types'
|
||||
import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { NumberField, PopupSelect, RangeField, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { api } from '../wails'
|
||||
|
||||
const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm })))
|
||||
const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
|
||||
|
||||
/** Reopen the wizard where the user left it (e.g. after a failed create). */
|
||||
export interface WizardDraft {
|
||||
opts: CreateOpts
|
||||
@@ -34,6 +49,7 @@ export interface WizardDraft {
|
||||
interface Props {
|
||||
locale: Locale
|
||||
host: HostReport
|
||||
tasks?: Task[]
|
||||
draft?: WizardDraft | null
|
||||
onClose: () => void
|
||||
/** Called with the cleaned payload; the caller runs the create in the background. */
|
||||
@@ -42,7 +58,7 @@ interface Props {
|
||||
|
||||
const REVIEW_STEP = 5
|
||||
|
||||
// Which wizard step owns each ValidationIssue.field (internal/driver/reims/reims.go ValidateCreate).
|
||||
// Which wizard step owns each ValidationIssue.field (internal/macos/reims/reims.go ValidateCreate).
|
||||
const STEP_OF_FIELD: Record<string, number> = {
|
||||
installer: 1, disk: 1, macos: 1, guest_lang: 1,
|
||||
cpus: 2, memory: 2,
|
||||
@@ -59,7 +75,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI
|
||||
{ mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' },
|
||||
]
|
||||
|
||||
export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, onSubmit }) => {
|
||||
export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft, onClose, onSubmit }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [step, setStep] = useState(draft?.step ?? 1)
|
||||
// Once the user has reached the review step, keep validating so step markers stay current.
|
||||
@@ -68,6 +84,18 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
const [err, setErr] = useState('')
|
||||
const [issues, setIssues] = useState<ValidationIssue[]>([])
|
||||
const [cmdPreview, setCmdPreview] = useState('')
|
||||
const [drivers, setDrivers] = useState<DriverSummary[]>([])
|
||||
const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER)
|
||||
const [driverOpts, setDriverOpts] = useState<Record<string, unknown>>({})
|
||||
const [driverCreating, setDriverCreating] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch((e) => console.warn('[wizard] ListDrivers failed:', e))
|
||||
return () => { live = false }
|
||||
}, [])
|
||||
const activeDriver = drivers.find((d) => d.id === driverID)
|
||||
const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver
|
||||
|
||||
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
|
||||
name: 'macos-tahoe',
|
||||
@@ -84,8 +112,10 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
disk: '',
|
||||
disk_mode: 'copy',
|
||||
disk_controller: 'nvme',
|
||||
graphics: 'reims-vgpu',
|
||||
gpu: host.recommended_gpu?.vulkan_icd ?? 'auto',
|
||||
graphics: host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga',
|
||||
// Default to "auto" rather than a DriverStore FileRepository ICD path so
|
||||
// Windows GPU driver updates never break existing VM configs.
|
||||
gpu: 'auto',
|
||||
resolution: recommendedResolution(host),
|
||||
displays: 1,
|
||||
borderless: false,
|
||||
@@ -129,7 +159,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
useEffect(() => {
|
||||
if (opts.source_mode !== 'offline' || releases) return
|
||||
let live = true
|
||||
api.ListInstallers().then((l) => { if (live) setCached(l ?? []) }).catch(() => {})
|
||||
api.ListInstallers().then((l) => { if (live) setCached(l ?? []) }).catch((e) => console.warn('[wizard] ListInstallers failed:', e))
|
||||
api.ListOfflineReleases()
|
||||
.then((list) => {
|
||||
if (!live) return
|
||||
@@ -140,9 +170,12 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
return () => { live = false }
|
||||
}, [opts.source_mode])
|
||||
const isCached = (v: string) => cached.some((c) => c.kind === 'offline' && !c.partial && c.version === v)
|
||||
const activeRelease = (v: string) => findActiveOfflineTask(tasks, v)
|
||||
const chosenRelease = releases?.find((r) => r.version === opts.macos)
|
||||
// reims-util pre-allocates the whole image as it starts (19.7 GB for an 18.4 GB release, measured).
|
||||
const needGB = chosenRelease && !isCached(chosenRelease.version) ? Math.ceil((chosenRelease.size * 1.1) / 1e9) : 0
|
||||
const needGB = chosenRelease && !isCached(chosenRelease.version) && !activeRelease(chosenRelease.version)
|
||||
? Math.ceil((chosenRelease.size * 1.1) / 1e9)
|
||||
: 0
|
||||
|
||||
useEffect(() => {
|
||||
if (!reviewed && step !== REVIEW_STEP) return
|
||||
@@ -157,7 +190,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
setCmdPreview(cmd)
|
||||
setErr('')
|
||||
})
|
||||
.catch((e) => { if (live) setErr(String(e).replace(/^Error:\s*/, '')) })
|
||||
.catch((e) => { if (live) setErr(parseAppError(e).summary) })
|
||||
.finally(() => { if (live) setChecking(false) })
|
||||
}, 200)
|
||||
return () => { live = false; clearTimeout(timer) }
|
||||
@@ -177,6 +210,8 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : [])
|
||||
|
||||
const realGPUs = (host.gpus ?? []).filter((g) => g.kind !== 'virtual')
|
||||
const selectedGPU = findGPU(host, opts.gpu)
|
||||
const selectedGPUHint = gpuCompatHint(locale, selectedGPU)
|
||||
const threads = Math.max(host.logical_cpus || 0, 1)
|
||||
const cpuRec = recommendedCPUs(host)
|
||||
const memRec = recommendedMemoryGB(host)
|
||||
@@ -214,6 +249,45 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
<div key={step} className="step-anim">
|
||||
{step === 1 && (
|
||||
<>
|
||||
{drivers.length > 1 && (
|
||||
<SetGroup title={tr('wizardDriverGroup')}>
|
||||
<SetRow
|
||||
title={tr('wizardDriverType')}
|
||||
control={
|
||||
<PopupSelect
|
||||
label={tr('wizardDriverType')}
|
||||
value={driverID}
|
||||
options={drivers.map((d) => ({
|
||||
value: d.id,
|
||||
label: locText(d.name, locale, d.id),
|
||||
}))}
|
||||
onChange={(id) => { setDriverID(id); setErr('') }}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SetGroup>
|
||||
)}
|
||||
{isCustomDriver ? (
|
||||
<div className="stack-3">
|
||||
<SetGroup title={tr('wizardBasics')}>
|
||||
<SetRow
|
||||
title={tr('vmName')}
|
||||
control={<input className="input rg-p-input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
|
||||
/>
|
||||
</SetGroup>
|
||||
{activeDriver.create_schema && (
|
||||
<Suspense fallback={null}>
|
||||
<SchemaForm
|
||||
locale={locale}
|
||||
schema={activeDriver.create_schema}
|
||||
values={driverOpts}
|
||||
onChange={setDriverOpts}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="source-cards" role="radiogroup" aria-label={tr('step1')}>
|
||||
{SOURCES.map((s) => {
|
||||
const Icon = s.icon
|
||||
@@ -234,13 +308,14 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
<span className={`source-icon source-icon-${s.mode}`} aria-hidden="true"><Icon size={20} /></span>
|
||||
<span className="source-title">
|
||||
{tr(s.title)}
|
||||
{s.mode === 'offline' && <span className="badge badge-accent">{tr('recommendedBadge')}</span>}
|
||||
{s.mode === 'offline' && <span className="badge rg-p-badge badge-accent">{tr('recommendedBadge')}</span>}
|
||||
</span>
|
||||
<span className="source-sub">{tr(s.sub)}</span>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className="rg-slot-anchor" data-rg-slot="create.source" />
|
||||
|
||||
<SetGroup>
|
||||
{opts.source_mode === 'apple' && (
|
||||
@@ -253,7 +328,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
<SetRow
|
||||
title={tr('macosVersion')}
|
||||
desc={releasesErr
|
||||
? <span className="warn-text">{tr('offlineListFailed')}:{releasesErr}</span>
|
||||
? <span className="warn-text">{tr('offlineListFailedDetail', { err: releasesErr })}</span>
|
||||
: needGB > 0 && host.free_disk_gb > 0 && host.free_disk_gb < needGB + 10
|
||||
? <span className="warn-text">{tr('offlineSpaceWarn', { free: host.free_disk_gb.toFixed(0), need: needGB })}</span>
|
||||
: tr('offlineHint')}
|
||||
@@ -265,11 +340,19 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
label={tr('macosVersion')}
|
||||
value={opts.macos}
|
||||
onChange={(macos) => set({ macos })}
|
||||
options={releases.map((r) => ({
|
||||
value: r.version,
|
||||
label: `macOS ${r.version}`,
|
||||
detail: `${(r.size / 1e9).toFixed(1)} GB${isCached(r.version) ? ` · ${tr('offlineCached')}` : ''}`,
|
||||
}))}
|
||||
options={releases.map((r) => {
|
||||
const active = activeRelease(r.version)
|
||||
const statusTag = isCached(r.version)
|
||||
? tr('offlineCached')
|
||||
: active
|
||||
? tr(taskInstallerPhase(active.primary) === 'queued' ? 'offlineQueued' : 'offlineDownloading')
|
||||
: ''
|
||||
return {
|
||||
value: r.version,
|
||||
label: `macOS ${r.version}`,
|
||||
detail: `${(r.size / 1e9).toFixed(1)} GB${statusTag ? ` · ${statusTag}` : ''}`,
|
||||
}
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
@@ -301,11 +384,13 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
label={tr('guestLangShort')}
|
||||
value={opts.guest_lang || defaultGuestLang(locale)}
|
||||
onChange={(guest_lang) => set({ guest_lang })}
|
||||
options={GUEST_LANG_PRESETS.map((p) => splitLangLabel(p.value, locale === 'zh-CN' ? p.zh : p.en))}
|
||||
options={guestLangOptions(locale)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SetGroup>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -426,7 +511,22 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
title={tr('gpuSelect')}
|
||||
disabled={opts.graphics !== 'reims-vgpu'}
|
||||
reason={tr('gpuSvgaReason')}
|
||||
desc={realGPUs.length === 0 ? <span className="warn-text">{tr('gpuUnavailableHint')}</span> : undefined}
|
||||
desc={
|
||||
realGPUs.length === 0 ? (
|
||||
<span className="warn-text">{tr('gpuUnavailableHint')}</span>
|
||||
) : selectedGPUHint ? (
|
||||
<span className="warn-text">
|
||||
{selectedGPUHint}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="link-btn"
|
||||
onClick={() => set({ graphics: 'vmware-svga' })}
|
||||
>
|
||||
{tr('gpuSwitchSvga')}
|
||||
</button>
|
||||
</span>
|
||||
) : undefined
|
||||
}
|
||||
control={
|
||||
<PopupSelect
|
||||
id="vm-gpu"
|
||||
@@ -435,7 +535,18 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
onChange={(gpu) => set({ gpu })}
|
||||
options={[
|
||||
{ value: 'auto', label: tr('gpuAutoTitle'), detail: host.recommended_gpu ? shortGPUName(host.recommended_gpu.name) : undefined },
|
||||
...realGPUs.map((g) => ({ value: g.vulkan_icd, label: shortGPUName(g.name) })),
|
||||
...realGPUs.map((g) => ({
|
||||
value: gpuOptionValue(g, realGPUs),
|
||||
label: shortGPUName(g.name),
|
||||
detail:
|
||||
g.compat === 'unsupported'
|
||||
? tr('gpuCompatUnsupported')
|
||||
: g.compat === 'warn'
|
||||
? tr('gpuCompatWarn')
|
||||
: g.vulkan_version
|
||||
? `Vulkan ${g.vulkan_version}`
|
||||
: undefined,
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
}
|
||||
@@ -444,24 +555,22 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
title={tr('resolution')}
|
||||
disabled={opts.graphics !== 'reims-vgpu'}
|
||||
reason={tr('gpuSvgaReason')}
|
||||
desc={host.primary_display
|
||||
? tr('hostDisplayHint', {
|
||||
w: host.primary_display.width,
|
||||
h: host.primary_display.height,
|
||||
scale: host.primary_display.scale_pct || 100,
|
||||
rec: host.recommended_resolution || '1920x1080',
|
||||
})
|
||||
: undefined}
|
||||
desc={[hostDisplayDesc(host, tr), !opts.borderless ? hostDisplayAdvice(host, tr) : undefined].filter(Boolean).join(' · ') || undefined}
|
||||
control={
|
||||
<PopupSelect
|
||||
id="vm-res"
|
||||
label={tr('resolution')}
|
||||
value={opts.resolution}
|
||||
onChange={(resolution) => set({ resolution })}
|
||||
options={recommendedDisplayPresets(host).map((p) => ({
|
||||
options={(opts.borderless ? fullscreenDisplayPresets(host) : recommendedDisplayPresets(host)).map((p: FullscreenDisplayPreset) => ({
|
||||
value: p.resolution,
|
||||
label: p.label,
|
||||
detail: [p.hidpi ? tr('hidpiPresetBadge') : '', p.recommended ? tr('recommendedBadge') : ''].filter(Boolean).join(' · ') || undefined,
|
||||
detail: [
|
||||
p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '',
|
||||
p.scaleBadge ?? '',
|
||||
p.native ? tr('resNativeBadge') : '',
|
||||
p.recommended ? tr('recommendedBadge') : '',
|
||||
].filter(Boolean).join(' · ') || undefined,
|
||||
}))}
|
||||
/>
|
||||
}
|
||||
@@ -512,8 +621,19 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('fullscreenLaunch')}
|
||||
desc={tr('fullscreenLaunchHint')}
|
||||
control={<Switch label={tr('fullscreenLaunch')} checked={!!opts.borderless} onChange={(borderless) => set({ borderless })} />}
|
||||
desc={opts.borderless ? tr('fullscreenDecoupledHint') : tr('fullscreenLaunchHint')}
|
||||
control={
|
||||
<Switch
|
||||
label={tr('fullscreenLaunch')}
|
||||
checked={!!opts.borderless}
|
||||
onChange={(borderless) => {
|
||||
const list = borderless ? fullscreenDisplayPresets(host) : recommendedDisplayPresets(host)
|
||||
const keep = list.some((p) => p.resolution === opts.resolution)
|
||||
const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution
|
||||
set(keep ? { borderless } : { borderless, resolution: fallback })
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('enableLogs')}
|
||||
@@ -542,8 +662,33 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
</div>
|
||||
|
||||
<div className="dialog-foot">
|
||||
<Button variant="ghost" disabled={step === 1} onClick={() => setStep(step - 1)}>{tr('back')}</Button>
|
||||
{step < REVIEW_STEP ? (
|
||||
<Button variant="ghost" disabled={step === 1 || isCustomDriver} onClick={() => setStep(step - 1)}>{tr('back')}</Button>
|
||||
{isCustomDriver ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
busy={driverCreating}
|
||||
disabled={!opts.name.trim() || driverCreating}
|
||||
onClick={async () => {
|
||||
setDriverCreating(true)
|
||||
setErr('')
|
||||
try {
|
||||
await api.CreateVMWithDriver({
|
||||
driver_id: driverID,
|
||||
name: opts.name.trim(),
|
||||
dir: opts.dir,
|
||||
options: driverOpts,
|
||||
})
|
||||
onClose()
|
||||
} catch (e) {
|
||||
setErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setDriverCreating(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{tr('createNow')}
|
||||
</Button>
|
||||
) : step < REVIEW_STEP ? (
|
||||
<Button variant="primary" onClick={() => setStep(step + 1)}>{tr('next')}</Button>
|
||||
) : (
|
||||
<Button
|
||||
@@ -649,7 +794,10 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
|
||||
await navigator.clipboard.writeText(command)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 1500)
|
||||
} catch { /* clipboard unavailable; the text stays selectable */ }
|
||||
} catch (e) {
|
||||
// clipboard unavailable; the text stays selectable
|
||||
console.warn('[wizard] clipboard write failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -658,7 +806,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
|
||||
<SetRow
|
||||
title={tr('vmName')}
|
||||
error={nameIssue}
|
||||
control={<input className="input name-input" aria-label={tr('vmName')} value={opts.name} onChange={(e) => onName(e.target.value)} spellCheck={false} />}
|
||||
control={<input className="input rg-p-input name-input" aria-label={tr('vmName')} value={opts.name} onChange={(e) => onName(e.target.value)} spellCheck={false} />}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('vmDir')}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { FolderOpen } from 'lucide-react'
|
||||
import React, { useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { AppState, Locale } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
status: AppState['data_root_status']
|
||||
/** Localized reason from the backend (dataroot.Error). */
|
||||
message: string
|
||||
/** The folder changed or reopened; the app reloads its state. */
|
||||
onChanged: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Shown instead of the workspace while the data folder is open read-only
|
||||
* (written by a newer release, damaged version record, failed or concurrent
|
||||
* upgrade). Nothing in the folder has been changed; the user can repair it,
|
||||
* try again, or pick another folder.
|
||||
*/
|
||||
export const DataRootReadOnly: React.FC<Props> = ({ locale, status, message, onChanged, onError }) => {
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const [busy, setBusy] = useState<'' | 'repair' | 'retry' | 'choose'>('')
|
||||
|
||||
const run = async (kind: 'repair' | 'retry' | 'choose', fn: () => Promise<unknown>) => {
|
||||
setBusy(kind)
|
||||
try {
|
||||
await fn()
|
||||
onChanged()
|
||||
} catch (e) {
|
||||
onError(tr('failGeneric'), e)
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const choose = () => run('choose', async () => {
|
||||
const dir = await api.PickDirectory(tr('dataRootChooseTitle'))
|
||||
if (dir) await api.SetDataRoot(dir)
|
||||
})
|
||||
|
||||
const canRepair = status.reason === 'damaged'
|
||||
const canRetry = status.reason === 'busy' || status.reason === 'migration_failed'
|
||||
|
||||
return (
|
||||
<div className="setup">
|
||||
<div className="setup-card">
|
||||
<div className="setup-head">
|
||||
<h1>{tr('dataRootReadOnlyTitle')}</h1>
|
||||
<p>{message}</p>
|
||||
</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('dataRootReadOnlyFolder')}</div>
|
||||
<div className="row-sub mono selectable">{status.dir}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{status.detail && (
|
||||
<details className="dataroot-detail">
|
||||
<summary>{tr('dataRootReadOnlyDetail')}</summary>
|
||||
<pre className="mono selectable">{status.detail}</pre>
|
||||
</details>
|
||||
)}
|
||||
<div className="setup-foot">
|
||||
<span className="hstack">
|
||||
{canRepair && (
|
||||
<Button busy={busy === 'repair'} disabled={!!busy} onClick={() => void run('repair', () => api.ReopenDataRoot(true))}>
|
||||
{tr('dataRootRepair')}
|
||||
</Button>
|
||||
)}
|
||||
{canRetry && (
|
||||
<Button busy={busy === 'retry'} disabled={!!busy} onClick={() => void run('retry', () => api.ReopenDataRoot(false))}>
|
||||
{tr('dataRootRetry')}
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
<Button variant="primary" icon={<FolderOpen size={14} aria-hidden="true" />} busy={busy === 'choose'} disabled={!!busy} onClick={() => void choose()}>
|
||||
{tr('dataRootChooseOther')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import React, { useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { Locale } from '../types'
|
||||
import { ConfirmDialog } from '../ui/dialog'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -13,32 +13,18 @@ interface Props {
|
||||
export const DeleteDialog: React.FC<Props> = ({ locale, name, onCancel, onConfirm }) => {
|
||||
const [keepFiles, setKeepFiles] = useState(false)
|
||||
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, 'deleteTitle', { name })}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">
|
||||
{t(locale, keepFiles ? 'deleteDescKeep' : 'deleteDesc')}
|
||||
</Alert.Description>
|
||||
<label className="choice">
|
||||
<input type="checkbox" checked={keepFiles} onChange={(e) => setKeepFiles(e.target.checked)} />
|
||||
{t(locale, 'deleteKeepFiles')}
|
||||
</label>
|
||||
</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-danger" onClick={() => onConfirm(keepFiles)}>
|
||||
{t(locale, 'deleteConfirm')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
<ConfirmDialog
|
||||
title={t(locale, 'deleteTitle', { name })}
|
||||
description={t(locale, keepFiles ? 'deleteDescKeep' : 'deleteDesc')}
|
||||
cancelLabel={t(locale, 'cancel')}
|
||||
confirmLabel={t(locale, 'deleteConfirm')}
|
||||
onCancel={onCancel}
|
||||
onConfirm={() => onConfirm(keepFiles)}
|
||||
>
|
||||
<label className="choice">
|
||||
<input type="checkbox" checked={keepFiles} onChange={(e) => setKeepFiles(e.target.checked)} />
|
||||
{t(locale, 'deleteKeepFiles')}
|
||||
</label>
|
||||
</ConfirmDialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import React from 'react'
|
||||
import { resolveActiveLocale, t } from '../i18n'
|
||||
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 docLocale = typeof document !== 'undefined' ? document.documentElement.dataset.locale : undefined
|
||||
const loc = resolveActiveLocale(docLocale || undefined)
|
||||
return (
|
||||
<div className="error-boundary">
|
||||
<div className="error-boundary-card" role="alert">
|
||||
<h2 className="error-boundary-title">
|
||||
{t(loc, 'errorBoundaryTitle')}
|
||||
</h2>
|
||||
<pre className="error-boundary-pre selectable">
|
||||
{error.message || String(error)}
|
||||
{stack ? `\n\n${stack}` : ''}
|
||||
</pre>
|
||||
<div className="error-boundary-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn rg-p-button btn-primary"
|
||||
onClick={() => window.location.reload()}
|
||||
>
|
||||
{t(loc, 'errorBoundaryReload')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Cpu, Download, HardDrive, MemoryStick, RefreshCw, ShieldCheck } from 'lucide-react'
|
||||
import { Cpu, HardDrive, MemoryStick, Plus, RefreshCw, ShieldCheck, Trash } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { findOptimization, kernelIrqchipHint, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
import { AppState, AppUpdateInfo, Locale, Task } from '../types'
|
||||
import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format'
|
||||
import { AppState, Locale, StorageBreakdown, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
@@ -11,43 +13,29 @@ interface Props {
|
||||
state: AppState
|
||||
locale: Locale
|
||||
onRefresh: () => void
|
||||
onNewVM?: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onSetLocale: (l: Locale) => void
|
||||
onToast?: (title: string) => void
|
||||
runtimeTask: Task | null
|
||||
onChannel: (alpha: boolean) => 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, onToast, runtimeTask, onChannel, onInstallRuntime, onCancelTask }) => {
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
const [appUpdate, setAppUpdate] = useState<AppUpdateInfo | null>(null)
|
||||
const [checkingUpdate, setCheckingUpdate] = useState(false)
|
||||
const [updateErr, setUpdateErr] = useState('')
|
||||
const { host, config, runtimes, optimizations } = state
|
||||
const [confirmDelete, setConfirmDelete] = useState('')
|
||||
const [removing, setRemoving] = useState('')
|
||||
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)
|
||||
|
||||
const runUpdateCheck = async (force: boolean) => {
|
||||
setCheckingUpdate(true)
|
||||
setUpdateErr('')
|
||||
try {
|
||||
const info = await api.CheckAppUpdate(force)
|
||||
setAppUpdate(info)
|
||||
} catch (e) {
|
||||
setUpdateErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
setCheckingUpdate(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void runUpdateCheck(false)
|
||||
}, [])
|
||||
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
|
||||
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
|
||||
const rebootOpt = findOptimization(optimizations, 'cold_reboot')
|
||||
const gpuOpt = findOptimization(optimizations, 'discrete_gpu')
|
||||
let live = true
|
||||
api.GetStorageBreakdown().then((s) => { if (live) setStorage(s) }).catch((e) => console.warn('[host] GetStorageBreakdown failed:', e))
|
||||
return () => { live = false }
|
||||
}, [state.config.data_root, state.vms?.length, state.runtimes?.length])
|
||||
|
||||
const whpx = {
|
||||
ready: { short: tr('whpxReady'), hint: '', tone: 'ok' },
|
||||
@@ -71,11 +59,6 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
setEnabling(false)
|
||||
}
|
||||
|
||||
const pickDataRoot = guard(async () => {
|
||||
const dir = await api.PickDirectory(tr('hostDataRoot'))
|
||||
if (dir) await api.SetDataRoot(dir)
|
||||
})
|
||||
|
||||
const importRuntime = async () => {
|
||||
setImporting(true)
|
||||
await guard(async () => {
|
||||
@@ -85,6 +68,20 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
setImporting(false)
|
||||
}
|
||||
|
||||
const removeRuntime = async (commit: string) => {
|
||||
setRemoving(commit)
|
||||
try {
|
||||
await api.RemoveRuntime(commit)
|
||||
setConfirmDelete('')
|
||||
onToast?.(tr('runtimeDeleted', { commit }))
|
||||
onRefresh()
|
||||
} catch (e) {
|
||||
onError(tr('failDelete'), e)
|
||||
} finally {
|
||||
setRemoving('')
|
||||
}
|
||||
}
|
||||
|
||||
const gpuKind = (k: string) =>
|
||||
tr(k === 'discrete' ? 'gpuDiscrete' : k === 'integrated' ? 'gpuIntegrated' : k === 'virtual' ? 'gpuVirtual' : 'gpuUnknown')
|
||||
|
||||
@@ -99,9 +96,22 @@ 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-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>
|
||||
@@ -110,20 +120,72 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
) : null}
|
||||
</div>
|
||||
<div className="tile">
|
||||
<div className="tile-head"><Cpu size={14} /> {tr('hostCPU')}</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"><MemoryStick size={14} /> {tr('hostRAM')}</div>
|
||||
<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 className="tile-sub">
|
||||
{tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}
|
||||
{host.memory_spec?.speed_mhz
|
||||
? ` · ${host.memory_spec.speed_mhz} MHz${host.memory_spec.type_name ? ` ${host.memory_spec.type_name}` : ''}`
|
||||
: ''}
|
||||
</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>
|
||||
</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 rg-p-card">
|
||||
<div className="card-title">
|
||||
<span>{tr('storageBreakdownTitle')}</span>
|
||||
<span className="spacer" />
|
||||
<span className="muted tnum" style={{ fontSize: 'var(--fs-12)', fontWeight: 'var(--fw-medium)' }}>{formatBytes(storage.total_bytes, locale)}</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, locale)}
|
||||
</span>
|
||||
<span className="storage-legend-item">
|
||||
<span className="storage-dot storage-seg-inst" aria-hidden="true" />
|
||||
{tr('storageInstallers')} · {formatBytes(storage.installers_bytes, locale)}
|
||||
</span>
|
||||
<span className="storage-legend-item">
|
||||
<span className="storage-dot storage-seg-rt" aria-hidden="true" />
|
||||
{tr('storageRuntimes')} · {formatBytes(storage.runtimes_bytes, locale)}
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
})()}
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
{tr('hostRuntime')}
|
||||
@@ -148,167 +210,60 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
<div className="row-sub">{rt.manifest.qemu_version.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button onClick={guard(() => api.UseRuntime(rt.commit))}>{tr('activate')}</Button>
|
||||
{confirmDelete === rt.commit ? (
|
||||
<>
|
||||
<Button variant="ghost" disabled={removing === rt.commit} onClick={() => setConfirmDelete('')}>
|
||||
{tr('cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" busy={removing === rt.commit} onClick={() => removeRuntime(rt.commit)}>
|
||||
{tr('runtimeDeleteConfirm')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button disabled={removing === rt.commit} onClick={guard(() => api.UseRuntime(rt.commit))}>
|
||||
{tr('activate')}
|
||||
</Button>
|
||||
<IconButton
|
||||
label={tr('runtimeDelete')}
|
||||
icon={<Trash size={15} />}
|
||||
disabled={removing !== ''}
|
||||
onClick={() => setConfirmDelete(rt.commit)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settings')}</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">
|
||||
<label className="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={tr('autoPinPCores')}
|
||||
disabled={!pcoreOpt?.supported}
|
||||
checked={!!pcoreOpt?.supported && config.auto_pin_pcores}
|
||||
onChange={(e) => guard(() => api.SetAutoPinPCores(e.target.checked))()}
|
||||
/>
|
||||
<span className="slider" />
|
||||
</label>
|
||||
</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">
|
||||
<label className="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={tr('minimizeToTray')}
|
||||
checked={config.minimize_to_tray !== false}
|
||||
onChange={(e) => guard(() => api.SetMinimizeToTray(e.target.checked))()}
|
||||
/>
|
||||
<span className="slider" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('appVersionTitle')} <span className="mono">{state.app_version ?? appUpdate?.current ?? 'v0.2.2'}</span>
|
||||
{appUpdate && !appUpdate.has_update && (
|
||||
<span className="badge badge-ok">{tr('appUpToDate')}</span>
|
||||
)}
|
||||
</div>
|
||||
{appUpdate?.has_update ? (
|
||||
<div className="row-sub">{tr('appUpdateAvailable', { v: appUpdate.latest })}</div>
|
||||
) : updateErr ? (
|
||||
<div className="row-sub" title={updateErr}>{tr('appUpdateLookupFailed')}</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{appUpdate?.has_update && (appUpdate.page_url || appUpdate.download_url) ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={<Download size={14} />}
|
||||
onClick={() => guard(() => api.OpenURL(appUpdate.page_url || appUpdate.download_url || ''))()}
|
||||
>
|
||||
{tr('appDownloadUpdate')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button busy={checkingUpdate} onClick={() => void runUpdateCheck(true)}>
|
||||
{tr('appCheckUpdate')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('hostOptimizations')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('optKernelIrqchipTitle')}
|
||||
<span className={`badge ${optBadgeClass(irqOpt?.status)}`}>{optStatusLabel(locale, irqOpt?.status)}</span>
|
||||
</div>
|
||||
<div className="row-sub">{kernelIrqchipHint(locale, irqOpt)}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('optColdRebootTitle')}
|
||||
<span className={`badge ${optBadgeClass(rebootOpt?.status)}`}>{optStatusLabel(locale, rebootOpt?.status)}</span>
|
||||
</div>
|
||||
<div className="row-sub">
|
||||
{tr(rebootOpt?.supported ? 'optColdRebootAuto' : 'optColdRebootUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('optDiscreteGpuTitle')}
|
||||
<span className={`badge ${optBadgeClass(gpuOpt?.status)}`}>{optStatusLabel(locale, gpuOpt?.status)}</span>
|
||||
</div>
|
||||
<div className="row-sub">
|
||||
{gpuOpt?.status === 'recommended'
|
||||
? tr('optDiscreteGpuRec', { name: gpuOpt.detail ?? '' })
|
||||
: gpuOpt?.status === 'available'
|
||||
? tr('optDiscreteGpuIntegrated', { name: gpuOpt.detail ?? '' })
|
||||
: tr('optDiscreteGpuUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('hostGPUs')}</div>
|
||||
<div className="list">
|
||||
{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" title={g.vulkan_icd}>
|
||||
{g.name}
|
||||
<span className={`badge ${g.kind === 'discrete' ? 'badge-accent' : ''}`}>{gpuKind(g.kind)}</span>
|
||||
{host.recommended_gpu?.vulkan_icd === g.vulkan_icd && <span className="badge badge-ok">{tr('gpuRecommended')}</span>}
|
||||
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 rg-p-badge ${g.kind === 'discrete' ? 'badge-accent' : ''}`}>{gpuKind(g.kind)}</span>
|
||||
{g.compat === 'unsupported' && <span className="badge rg-p-badge badge-warn">{tr('gpuCompatUnsupported')}</span>}
|
||||
{g.compat === 'warn' && <span className="badge rg-p-badge badge-warn">{tr('gpuCompatWarn')}</span>}
|
||||
{isRec && g.compat !== 'warn' && g.compat !== 'unsupported' && <span className="badge rg-p-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>
|
||||
</div>
|
||||
))
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
@@ -322,8 +277,8 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
<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>}
|
||||
<span className="badge rg-p-badge">{d.scale_pct || 100}%</span>
|
||||
{d.primary && <span className="badge rg-p-badge badge-ok">{tr('hostDisplayPrimary')}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { Disc3, Puzzle, RefreshCw } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { ImageSourceContribution, Locale, PluginUIContributions } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Segmented } from '../ui/settings'
|
||||
import { PluginPanelFrame } from './PluginPanelFrame'
|
||||
import { locText } from './SchemaForm'
|
||||
import { WordmarkLoader } from './WordmarkLoader'
|
||||
|
||||
export interface NativeImageSourceRenderOpts {
|
||||
refreshSignal: number
|
||||
onBusyChange: (busy: boolean) => void
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
appearance: 'light' | 'dark'
|
||||
pluginUI: PluginUIContributions | null
|
||||
renderNativeSource?: (nativeId: string, opts: NativeImageSourceRenderOpts) => React.ReactNode
|
||||
onOpenPlugins: () => void
|
||||
}
|
||||
|
||||
function sourceKey(src: ImageSourceContribution): string {
|
||||
return `${src.pluginId ?? ''}:${src.id}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Top-level Images page: hosts plugin-registered image source tabs via a top
|
||||
* Segmented control. Built-in plugins (such as macOS Images) mount native host
|
||||
* views; external plugins render in a sandboxed L4 iframe.
|
||||
*/
|
||||
export const ImagesPage: React.FC<Props> = ({
|
||||
locale,
|
||||
appearance,
|
||||
pluginUI,
|
||||
renderNativeSource,
|
||||
onOpenPlugins,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const sources = useMemo(() => pluginUI?.image_sources ?? [], [pluginUI?.image_sources])
|
||||
const [selectedKey, setSelectedKey] = useState('')
|
||||
const [refreshSignals, setRefreshSignals] = useState<Record<string, number>>({})
|
||||
const [busyByKey, setBusyByKey] = useState<Record<string, boolean>>({})
|
||||
|
||||
const activeSource = useMemo(() => {
|
||||
if (sources.length === 0) return null
|
||||
return sources.find((s) => sourceKey(s) === selectedKey) ?? sources[0]
|
||||
}, [sources, selectedKey])
|
||||
|
||||
const activeKey = activeSource ? sourceKey(activeSource) : ''
|
||||
|
||||
useEffect(() => {
|
||||
if (activeKey && activeKey !== selectedKey) {
|
||||
setSelectedKey(activeKey)
|
||||
}
|
||||
}, [activeKey, selectedKey])
|
||||
|
||||
const activeBusy = activeKey ? !!busyByKey[activeKey] : false
|
||||
|
||||
const handleActiveBusyChange = useCallback((busy: boolean) => {
|
||||
if (!activeKey) return
|
||||
setBusyByKey((prev) => (prev[activeKey] === busy ? prev : { ...prev, [activeKey]: busy }))
|
||||
}, [activeKey])
|
||||
|
||||
const triggerRefresh = () => {
|
||||
if (!activeKey) return
|
||||
setRefreshSignals((prev) => ({ ...prev, [activeKey]: (prev[activeKey] ?? 0) + 1 }))
|
||||
}
|
||||
|
||||
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>
|
||||
{activeSource && (
|
||||
<div className="actions">
|
||||
<IconButton
|
||||
label={tr('refresh')}
|
||||
icon={<RefreshCw size={16} className={activeBusy ? 'spin' : undefined} />}
|
||||
disabled={activeBusy}
|
||||
onClick={triggerRefresh}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
|
||||
{sources.length > 0 && (
|
||||
<div className="images-switch">
|
||||
<Segmented
|
||||
label={tr('imagesSourcesLabel')}
|
||||
value={activeKey}
|
||||
onChange={setSelectedKey}
|
||||
options={sources.map((src) => ({
|
||||
value: sourceKey(src),
|
||||
label: locText(src.title, locale, src.id),
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pluginUI === null ? (
|
||||
<WordmarkLoader className="installers-loader" />
|
||||
) : !activeSource ? (
|
||||
<div className="empty-panel images-empty">
|
||||
<Disc3 size={28} aria-hidden="true" />
|
||||
<div className="images-empty-title">{tr('imagesNoSourcesTitle')}</div>
|
||||
<div className="images-empty-desc">{tr('imagesNoSourcesDesc')}</div>
|
||||
<Button variant="primary" icon={<Puzzle size={14} aria-hidden="true" />} onClick={onOpenPlugins}>
|
||||
{tr('imagesOpenPlugins')}
|
||||
</Button>
|
||||
</div>
|
||||
) : activeSource.native ? (
|
||||
renderNativeSource?.(activeSource.native, {
|
||||
refreshSignal: refreshSignals[activeKey] ?? 0,
|
||||
onBusyChange: handleActiveBusyChange,
|
||||
})
|
||||
) : (
|
||||
<PluginPanelFrame
|
||||
key={activeKey}
|
||||
locale={locale}
|
||||
panel={{
|
||||
id: activeSource.id,
|
||||
slot: 'images.source',
|
||||
title: activeSource.title,
|
||||
entry: activeSource.entry || 'index.html',
|
||||
height: activeSource.height || 560,
|
||||
pluginId: activeSource.pluginId,
|
||||
}}
|
||||
assetToken={pluginUI.asset_token ?? ''}
|
||||
appearance={appearance}
|
||||
headless
|
||||
maxHeight={1200}
|
||||
refreshSignal={refreshSignals[activeKey] ?? 0}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
import { Download, LoaderCircle, Pause, Plus, RefreshCw, Trash } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
import { CachedInstaller, HostReport, Locale, Release, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
|
||||
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
|
||||
|
||||
/** 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 isDownloaded = (v: string) => (cached ?? []).some((c) => c.kind === 'offline' && !c.partial && c.version === v)
|
||||
|
||||
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" />
|
||||
{task.percent >= 0 && <span className="progress"><div style={{ width: `${task.percent}%` }} /></span>}
|
||||
<span>{task.percent >= 0 ? `${Math.floor(task.percent)}%` : ''} {taskDetail(task)}</span>
|
||||
</span>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
<div className="page-title"><h1>{tr('installersTitle')}</h1></div>
|
||||
<div className="actions">
|
||||
<IconButton label={tr('refresh')} icon={<RefreshCw size={16} />} onClick={() => { loadCached(); loadReleases() }} />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('installersDownloaded')}</div>
|
||||
<div className="list">
|
||||
{cached === null ? (
|
||||
<div className="row"><span className="row-sub">…</span></div>
|
||||
) : cached.length === 0 ? (
|
||||
<div className="row"><span className="row-sub">{tr('installersEmpty')}</span></div>
|
||||
) : cached.map((c) => {
|
||||
const task = c.version ? running(c.version) : undefined
|
||||
return (
|
||||
<div className="row" key={c.name}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{c.title ?? c.name} {c.version}
|
||||
{c.build && <span className="muted">({c.build})</span>}
|
||||
{c.kind === 'offline' && !c.partial && <span className="badge badge-ok">{tr('installersKindOffline')}</span>}
|
||||
{c.kind === 'online' && !c.partial && <span className="badge">{tr('installersKindOnline')}</span>}
|
||||
{c.partial && !task && <span className="badge badge-warn">{tr('installersPartial')}</span>}
|
||||
</div>
|
||||
{task ? progress(task) : <div className="row-sub mono">{c.name} · {gb(c.bytes)}</div>}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{task ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
|
||||
) : (
|
||||
<>
|
||||
{!c.partial && (c.kind === 'offline' || c.kind === 'online') && (
|
||||
<Button variant={c.kind === 'offline' ? 'primary' : 'secondary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
|
||||
{tr('installersCreateVM')}
|
||||
</Button>
|
||||
)}
|
||||
{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>
|
||||
<div className="list">
|
||||
{releasesErr ? (
|
||||
<div className="row"><span className="row-sub">{tr('offlineListFailed')}:{releasesErr}</span></div>
|
||||
) : releases === null ? (
|
||||
<div className="row"><span className="row-sub">{tr('offlineLoading')}</span></div>
|
||||
) : releases.map((r) => {
|
||||
const task = running(r.version)
|
||||
const done = isDownloaded(r.version)
|
||||
const short = !done && !task && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
|
||||
return (
|
||||
<div className="row" key={r.product}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{r.title} {r.version}
|
||||
<span className="muted">({r.build})</span>
|
||||
</div>
|
||||
{task ? progress(task) : (
|
||||
<div className="row-sub">
|
||||
{r.posted} · {gb(r.size)}
|
||||
{short && <span className="warn-text"> · {tr('installersNoSpace', { need: Math.ceil(needBytes(r) / 1e9), free: host.free_disk_gb.toFixed(0) })}</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{task ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
|
||||
) : done ? (
|
||||
<span className="badge badge-ok">{tr('offlineCached')}</span>
|
||||
) : (
|
||||
<Button icon={<Download size={14} />} disabled={short} onClick={() => download(r.version)}>{tr('installersDownload')}</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<span className="hint">{tr('installersHint')}</span>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
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, X } 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 { taskDetail, taskInstallerPhase, taskStopAction, taskTitle } from '../lib/tasks'
|
||||
import { HostReport, Locale, Task } from '../types'
|
||||
import { Button, IconButton, Tip } from '../ui/controls'
|
||||
import { HostIcon } from '../ui/themeVisuals'
|
||||
|
||||
export type LogTab = 'app' | 'serial' | 'qemu'
|
||||
|
||||
@@ -25,6 +26,12 @@ interface Props {
|
||||
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. */
|
||||
@@ -50,55 +57,286 @@ 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, qemuText, showSerial, onRefreshSerial, onRefreshQemu,
|
||||
task, runningTasks, onCancelTask,
|
||||
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 : tab === 'serial' ? serialText : qemuText
|
||||
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 (e) {
|
||||
console.warn('[logPanel] read persisted height failed:', e)
|
||||
}
|
||||
return DEFAULT_LOG_HEIGHT
|
||||
})
|
||||
const persistHeight = (value: number) => {
|
||||
try {
|
||||
localStorage.setItem(LOG_HEIGHT_KEY, String(value))
|
||||
} catch (e) {
|
||||
console.warn('[logPanel] persist height failed:', e)
|
||||
}
|
||||
}
|
||||
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)
|
||||
persistHeight(height)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="logs">
|
||||
<div className="logbar">
|
||||
{task && (
|
||||
<div className="logs rg-p-logpanel">
|
||||
{open && (
|
||||
<div
|
||||
className="log-resize-handle"
|
||||
role="separator"
|
||||
tabIndex={0}
|
||||
aria-orientation="horizontal"
|
||||
aria-label={tr('resizeLogPanel')}
|
||||
aria-valuemin={MIN_LOG_HEIGHT}
|
||||
aria-valuemax={MAX_LOG_HEIGHT}
|
||||
aria-valuenow={height}
|
||||
data-dragging={dragging}
|
||||
onPointerDown={onResizeDown}
|
||||
onPointerMove={onResizeMove}
|
||||
onPointerUp={onResizeUp}
|
||||
onPointerCancel={onResizeUp}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return
|
||||
e.preventDefault()
|
||||
const delta = e.key === 'ArrowUp' ? 24 : -24
|
||||
const next = Math.min(MAX_LOG_HEIGHT, Math.max(MIN_LOG_HEIGHT, height + delta))
|
||||
setHeight(next)
|
||||
persistHeight(next)
|
||||
}}
|
||||
onDoubleClick={() => {
|
||||
setHeight(DEFAULT_LOG_HEIGHT)
|
||||
persistHeight(DEFAULT_LOG_HEIGHT)
|
||||
}}
|
||||
>
|
||||
<span className="log-resize-pill" aria-hidden="true" />
|
||||
</div>
|
||||
)}
|
||||
<div className="logbar rg-p-statusbar">
|
||||
<span className="rg-slot-inline" data-rg-slot="statusbar.left" />
|
||||
{task ? (
|
||||
<>
|
||||
<Tip label={[task.step, taskDetail(task)].filter(Boolean).join(' · ') || taskTitle(locale, task)} side="top">
|
||||
<Tip
|
||||
label={[
|
||||
taskInstallerPhase(task) === 'queued' ? tr('installersQueuedDesc') : 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 rg-p-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>
|
||||
</Tip>
|
||||
{task.cancelable && (
|
||||
<IconButton small tipSide="top" label={tr('pauseDownload')} icon={<Pause size={14} />} onClick={() => onCancelTask(task.id)} />
|
||||
)}
|
||||
{task.cancelable && (() => {
|
||||
const stop = taskStopAction(locale, task)
|
||||
return (
|
||||
<IconButton
|
||||
small
|
||||
tipSide="top"
|
||||
label={stop.label}
|
||||
icon={stop.kind === 'cancel' ? <X size={14} /> : <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')}
|
||||
) : 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}>
|
||||
<HostIcon name="warning"><AlertTriangle size={12} aria-hidden="true" /></HostIcon>
|
||||
<span>{tr('footerHostIssue')}</span>
|
||||
</button>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
|
||||
{tr('logQemu')}
|
||||
</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 rg-p-tabs"
|
||||
role="tablist"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return
|
||||
e.preventDefault()
|
||||
const order: LogTab[] = showSerial ? ['app', 'serial', 'qemu'] : ['app']
|
||||
const cur = Math.max(0, order.indexOf(tab))
|
||||
const isRTL = getComputedStyle(e.currentTarget).direction === 'rtl'
|
||||
const delta = (e.key === 'ArrowRight') !== isRTL ? 1 : -1
|
||||
const next = order[(cur + delta + order.length) % order.length]
|
||||
onTab(next)
|
||||
const btns = e.currentTarget.querySelectorAll<HTMLButtonElement>('[role="tab"]')
|
||||
btns[order.indexOf(next)]?.focus()
|
||||
}}
|
||||
>
|
||||
<button type="button" role="tab" className="tab rg-p-tab" tabIndex={tab === 'app' ? 0 : -1} aria-selected={tab === 'app'} onClick={() => onTab('app')}>
|
||||
{tr('logActivity')}
|
||||
</button>
|
||||
{showSerial && (
|
||||
<>
|
||||
<button type="button" role="tab" className="tab rg-p-tab" tabIndex={tab === 'serial' ? 0 : -1} aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
|
||||
{tr('logSerial')}
|
||||
</button>
|
||||
<button type="button" role="tab" className="tab rg-p-tab" tabIndex={tab === 'qemu' ? 0 : -1} 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} />
|
||||
@@ -109,34 +347,30 @@ export const LogPanel: React.FC<Props> = ({
|
||||
{open && tab === 'qemu' && (
|
||||
<IconButton small tipSide="top" label={tr('refresh')} icon={<RefreshCw size={14} />} onClick={onRefreshQemu} />
|
||||
)}
|
||||
{!open && unseenErrors > 0 && <span className="badge badge-error" aria-hidden="true">{unseenErrors}</span>}
|
||||
<IconButton
|
||||
small
|
||||
tipSide="top"
|
||||
label={open ? tr('collapseLogs') : tr('expandLogs')}
|
||||
shortcut="Ctrl+L"
|
||||
icon={open ? <ChevronDown size={16} /> : <ChevronUp size={16} />}
|
||||
onClick={onToggle}
|
||||
aria-expanded={open}
|
||||
/>
|
||||
<span className="rg-slot-inline" data-rg-slot="statusbar.right" />
|
||||
{!open && unseenErrors > 0 && <span className="badge rg-p-badge badge-error" aria-hidden="true">{unseenErrors}</span>}
|
||||
<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>
|
||||
)))
|
||||
: tab === 'serial'
|
||||
? (serialText || <span className="muted">{tr('logsEmpty')}</span>)
|
||||
: (qemuText || <span className="muted">{tr('logsEmpty')}</span>)}
|
||||
: rows)
|
||||
: (filteredText || <span className="muted">{tr('logsEmpty')}</span>)}
|
||||
</div>
|
||||
{!stuck && (
|
||||
<Button className="jump-latest" icon={<ArrowDown size={14} />} onClick={jump}>
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
Boxes, Clipboard, Compass, Cpu, Disc3, Globe, Keyboard,
|
||||
Layers, Monitor, Palette, Puzzle, RotateCcw,
|
||||
} from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { PermissionSpec } from '../types'
|
||||
|
||||
export interface PluginVisualSource {
|
||||
id?: string
|
||||
kind?: string
|
||||
system?: boolean
|
||||
tier?: string
|
||||
locales?: string[]
|
||||
permissions?: Array<PermissionSpec | string>
|
||||
}
|
||||
|
||||
export interface PluginVisual {
|
||||
tone: string
|
||||
icon: React.ReactNode
|
||||
}
|
||||
|
||||
const ICON_SIZES = { sm: 16, md: 18, lg: 20 } as const
|
||||
|
||||
/**
|
||||
* Single visual resolver for both installed plugins (PluginInfo) and market
|
||||
* entries (MarketEntry), so a plugin keeps the same icon and colour across
|
||||
* Market, Installed and first-run setup.
|
||||
*/
|
||||
export function resolvePluginVisual(src: PluginVisualSource, iconSize = 20): PluginVisual {
|
||||
if (src.system) return { tone: 'indigo', icon: <Boxes size={iconSize} aria-hidden="true" /> }
|
||||
switch (src.kind) {
|
||||
case 'theme': return { tone: 'purple', icon: <Palette size={iconSize} aria-hidden="true" /> }
|
||||
case 'locale': return { tone: 'sky', icon: <Globe size={iconSize} aria-hidden="true" /> }
|
||||
case 'driver':
|
||||
case 'runtime': return { tone: 'indigo', icon: <Monitor size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
const id = (src.id ?? '').toLowerCase()
|
||||
const perms = new Set((src.permissions ?? []).map((x) => (typeof x === 'string' ? x : x.name)))
|
||||
if ((src.locales?.length ?? 0) > 0 || id.includes('lang') || id.includes('locale')) {
|
||||
return { tone: 'sky', icon: <Globe size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('theme') || perms.has('ui:script')) {
|
||||
return { tone: 'purple', icon: <Palette size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('driver') || perms.has('driver:vm') || perms.has('runtime:provider')) {
|
||||
return { tone: 'indigo', icon: <Monitor size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('clipboard') || perms.has('host:clipboard')) {
|
||||
return { tone: 'sky', icon: <Clipboard size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('ime') || id.includes('input') || id.includes('wheel') || perms.has('input:filter')) {
|
||||
return { tone: 'rose', icon: <Keyboard size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('reboot')) {
|
||||
return { tone: 'amber', icon: <RotateCcw size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('whpx') || id.includes('irq')) {
|
||||
return { tone: 'emerald', icon: <Cpu size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('guide')) {
|
||||
return { tone: 'teal', icon: <Compass size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('offline') || id.includes('installer') || id.includes('helper') || id.includes('image')) {
|
||||
return { tone: 'teal', icon: <Disc3 size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (src.tier === 'L3') {
|
||||
return { tone: 'slate', icon: <Layers size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
return { tone: 'teal', icon: <Puzzle size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
|
||||
/** App Store-inspired squircle icon tile shared by Market, Installed and Setup. */
|
||||
export const PluginAppIcon: React.FC<{
|
||||
plugin?: PluginVisualSource
|
||||
kind?: string
|
||||
size?: 'sm' | 'md' | 'lg'
|
||||
}> = ({ plugin, kind, size = 'lg' }) => {
|
||||
const vis = resolvePluginVisual(plugin ?? { kind }, ICON_SIZES[size])
|
||||
const sizeCls = size === 'lg' ? '' : ` is-${size}`
|
||||
return <div className={`plugin-app-icon tone-${vis.tone}${sizeCls}`}>{vis.icon}</div>
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
import { AlertTriangle, Check, Download, ShieldAlert } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, MarketBrowseResult, MarketCatalogItem, PluginInfo } from '../types'
|
||||
import { Button, Tip } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { api, events, MarketInstallProgress } from '../wails'
|
||||
import { PluginAppIcon, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
|
||||
import { locText } from './SchemaForm'
|
||||
import { WordmarkLoader } from './WordmarkLoader'
|
||||
|
||||
// Cards are revealed in pages as the feed scrolls into view.
|
||||
const PAGE_SIZE = 24
|
||||
// A manual refresh keeps the loader up at least this long, so it reads as a
|
||||
// response instead of a flicker.
|
||||
const MIN_REFRESH_MS = 900
|
||||
const QUERY_DEBOUNCE_MS = 180
|
||||
|
||||
const KIND_LABELS: Record<string, I18nKey> = {
|
||||
theme: 'pluginMarketKindTheme',
|
||||
locale: 'pluginMarketKindLocale',
|
||||
driver: 'pluginMarketKindDriver',
|
||||
tool: 'pluginMarketKindTool',
|
||||
template: 'pluginMarketKindTemplate',
|
||||
runtime: 'pluginMarketKindRuntime',
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
safeMode?: boolean
|
||||
/** Installed plugins; a change re-reads install state from the cache. */
|
||||
installed: PluginInfo[]
|
||||
/** Bumped by the page's refresh button to force a network fetch. */
|
||||
refreshSignal: number
|
||||
onBusyChange: (busy: boolean) => void
|
||||
/** Called after an install or enable so the page reloads its plugin list. */
|
||||
onChanged: (opts: { enabled?: PluginInfo }) => Promise<void> | void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
type ProgressMap = Record<string, MarketInstallProgress>
|
||||
|
||||
/**
|
||||
* Plugin market feed: a multi-column card grid that paints from the local
|
||||
* cache first, revalidates over the network, and reveals cards page by page.
|
||||
*/
|
||||
export const PluginMarket: React.FC<Props> = ({
|
||||
locale, safeMode, installed, refreshSignal, onBusyChange, onChanged, onError,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [query, setQuery] = useState('')
|
||||
const [kind, setKind] = useState('')
|
||||
const [result, setResult] = useState<MarketBrowseResult | null>(null)
|
||||
const [syncing, setSyncing] = useState(false)
|
||||
const [refreshing, setRefreshing] = useState(false)
|
||||
const [visible, setVisible] = useState(PAGE_SIZE)
|
||||
const [progress, setProgress] = useState<ProgressMap>({})
|
||||
const [prompt, setPrompt] = useState<PluginInfo | null>(null)
|
||||
const [promptChecked, setPromptChecked] = useState(false)
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
|
||||
const seq = useRef(0)
|
||||
const synced = useRef(false)
|
||||
const sentinel = useRef<HTMLDivElement>(null)
|
||||
const params = useRef({ query, kind })
|
||||
params.current = { query, kind }
|
||||
|
||||
useEffect(() => { onBusyChange(syncing) }, [syncing])
|
||||
|
||||
// Network load. Stale responses (an older query) are dropped.
|
||||
const sync = useCallback(async (force: boolean) => {
|
||||
const id = ++seq.current
|
||||
const { query: q, kind: k } = params.current
|
||||
setSyncing(true)
|
||||
const started = Date.now()
|
||||
if (force) setRefreshing(true)
|
||||
try {
|
||||
const res = await api.BrowsePluginMarket(q, k, false, force)
|
||||
if (force) {
|
||||
const wait = MIN_REFRESH_MS - (Date.now() - started)
|
||||
if (wait > 0) await new Promise((r) => window.setTimeout(r, wait))
|
||||
}
|
||||
if (id !== seq.current) return
|
||||
setResult(res)
|
||||
synced.current = true
|
||||
} catch (e) {
|
||||
if (id === seq.current) onError(tr('pluginFailMarketLoad'), e)
|
||||
} finally {
|
||||
if (id === seq.current) {
|
||||
setSyncing(false)
|
||||
setRefreshing(false)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Cache-only read: instant, no network.
|
||||
const peek = useCallback(async (keepNetworkState: boolean) => {
|
||||
const { query: q, kind: k } = params.current
|
||||
try {
|
||||
const res = await api.PeekPluginMarket(q, k)
|
||||
setResult((prev) => {
|
||||
if (keepNetworkState && prev) {
|
||||
res.stale = prev.stale
|
||||
res.fetch_error = prev.fetch_error
|
||||
}
|
||||
return res
|
||||
})
|
||||
} catch (e) {
|
||||
// the network load reports errors
|
||||
console.warn('[market] PeekPluginMarket failed:', e)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// First open: paint from cache, then revalidate.
|
||||
useEffect(() => {
|
||||
void peek(false).then(() => sync(false))
|
||||
}, [])
|
||||
|
||||
// Query and category changes; the first render is handled above.
|
||||
const firstFilter = useRef(true)
|
||||
useEffect(() => {
|
||||
if (firstFilter.current) { firstFilter.current = false; return }
|
||||
setVisible(PAGE_SIZE)
|
||||
const timer = window.setTimeout(() => { void sync(false) }, query ? QUERY_DEBOUNCE_MS : 0)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [query, kind])
|
||||
|
||||
const firstRefresh = useRef(true)
|
||||
useEffect(() => {
|
||||
if (firstRefresh.current) { firstRefresh.current = false; return }
|
||||
void sync(true)
|
||||
}, [refreshSignal])
|
||||
|
||||
// Install state lives in the plugin list; re-read it without the network.
|
||||
const firstInstalled = useRef(true)
|
||||
useEffect(() => {
|
||||
if (firstInstalled.current) { firstInstalled.current = false; return }
|
||||
if (synced.current) void peek(true)
|
||||
}, [installed])
|
||||
|
||||
useEffect(() => events.onPluginInstall((p) => {
|
||||
setProgress((prev) => prev[p.id] ? { ...prev, [p.id]: p } : prev)
|
||||
}), [])
|
||||
|
||||
const items = result?.items ?? []
|
||||
const shown = items.slice(0, visible)
|
||||
const hasMore = items.length > visible
|
||||
|
||||
// Reveal the next page as the sentinel nears the viewport.
|
||||
useEffect(() => {
|
||||
const el = sentinel.current
|
||||
if (!el || !hasMore || typeof IntersectionObserver === 'undefined') return
|
||||
const io = new IntersectionObserver((entries) => {
|
||||
if (entries.some((e) => e.isIntersecting)) setVisible((v) => v + PAGE_SIZE)
|
||||
}, { rootMargin: '240px 0px' })
|
||||
io.observe(el)
|
||||
return () => io.disconnect()
|
||||
}, [hasMore, visible, items.length])
|
||||
|
||||
const install = async (item: MarketCatalogItem) => {
|
||||
const id = item.entry.id
|
||||
setProgress((prev) => ({ ...prev, [id]: { id, phase: 'download', done: 0, total: item.entry.size_bytes ?? 0 } }))
|
||||
try {
|
||||
const info = await api.InstallMarketPlugin(id, false)
|
||||
await onChanged({})
|
||||
if (info && !info.enabled) {
|
||||
setPromptChecked(false)
|
||||
setPrompt(info)
|
||||
}
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailMarketInstall'), e)
|
||||
} finally {
|
||||
setProgress((prev) => {
|
||||
const next = { ...prev }
|
||||
delete next[id]
|
||||
return next
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const enablePrompted = async () => {
|
||||
if (!prompt) return
|
||||
setEnabling(true)
|
||||
try {
|
||||
const target = prompt
|
||||
await api.EnablePlugin(target.id, target.needs_approval)
|
||||
setPrompt(null)
|
||||
await onChanged({ enabled: target })
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailEnable'), e)
|
||||
} finally {
|
||||
setEnabling(false)
|
||||
}
|
||||
}
|
||||
|
||||
const facets = useMemo(() => {
|
||||
const list = [...(result?.kinds ?? [])]
|
||||
if (kind && !list.some((f) => f.kind === kind)) list.push({ kind, count: 0 })
|
||||
return list
|
||||
}, [result, kind])
|
||||
const kindLabel = (k: string) => KIND_LABELS[k] ? tr(KIND_LABELS[k]) : k.charAt(0).toUpperCase() + k.slice(1)
|
||||
|
||||
const action = (item: MarketCatalogItem) => {
|
||||
const e = item.entry
|
||||
const p = progress[e.id]
|
||||
if (p) {
|
||||
const pct = p.phase === 'download' && p.total > 0 ? Math.min(100, Math.round((p.done / p.total) * 100)) : null
|
||||
const text = p.phase === 'install' ? tr('pluginMarketInstalling') : pct === null ? tr('pluginMarketDownloading') : `${pct}%`
|
||||
return (
|
||||
<div
|
||||
className={`market-progress rg-p-progress${pct === null ? ' is-indeterminate' : ''}`}
|
||||
role="progressbar"
|
||||
aria-label={tr('pluginMarketDownloading')}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={pct ?? undefined}
|
||||
>
|
||||
<span className="market-progress-fill" style={pct === null ? undefined : { transform: `scaleX(${pct / 100})` }} />
|
||||
<span className="market-progress-text">{text}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (item.withdrawn) {
|
||||
const why = locText(item.withdrawn.reason, locale, '')
|
||||
+ (item.withdrawn.instead_id ? ` · ${tr('pluginMarketWithdrawnInstead', { target: item.withdrawn.instead_name || item.withdrawn.instead_id })}` : '')
|
||||
return <Tip label={why || tr('pluginMarketWithdrawn')}><span tabIndex={0}><Button className="market-btn" disabled>{tr('pluginMarketWithdrawn')}</Button></span></Tip>
|
||||
}
|
||||
if (!item.compatible) {
|
||||
return <Tip label={item.incompatible_reason || tr('pluginMarketIncompatible')}><span tabIndex={0}><Button className="market-btn" disabled>{tr('pluginMarketIncompatible')}</Button></span></Tip>
|
||||
}
|
||||
if (item.installed && !item.update_available) {
|
||||
return <Button className="market-btn" disabled icon={<Check size={13} aria-hidden="true" />}>{tr('pluginMarketInstalled')}</Button>
|
||||
}
|
||||
if (item.update_available) {
|
||||
return (
|
||||
<Tip label={tr('pluginMarketVersionTip', { installed: item.installed_version ?? '', version: e.version })}>
|
||||
<span>
|
||||
<Button className="market-btn" variant="primary" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => void install(item)}>
|
||||
{tr('pluginMarketUpdateShort')}
|
||||
</Button>
|
||||
</span>
|
||||
</Tip>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<Button className="market-btn" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => void install(item)}>
|
||||
{tr('pluginMarketInstall')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
// The loader covers the feed when there is nothing to show yet, or when the
|
||||
// user asked for a refresh and should see it happen.
|
||||
const showLoader = refreshing || (syncing && items.length === 0) || (!result && !synced.current)
|
||||
const emptyAfterSync = !showLoader && items.length === 0
|
||||
|
||||
return (
|
||||
<section className="section plugin-market">
|
||||
<div className="market-toolbar">
|
||||
<PluginSearchInput
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder={tr('pluginMarketSearchPlaceholder')}
|
||||
wide
|
||||
/>
|
||||
{facets.length > 1 && (
|
||||
<div className="market-kinds" role="radiogroup" aria-label={tr('pluginMarketKindAll')}>
|
||||
{[{ kind: '', count: 0 }, ...facets].map((f) => (
|
||||
<button
|
||||
key={f.kind || 'all'}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={kind === f.kind}
|
||||
className={`plugin-pill${kind === f.kind ? ' is-active' : ''}`}
|
||||
onClick={() => setKind(f.kind)}
|
||||
>
|
||||
{f.kind ? kindLabel(f.kind) : tr('pluginMarketKindAll')}
|
||||
{f.kind && f.count > 0 && <span className="plugin-pill-count">{f.count}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!showLoader && result?.stale && result.fetch_error && (
|
||||
<div className="notice notice-warn">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('pluginMarketStaleBanner')}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(result?.withdrawn_installed ?? []).map((w) => (
|
||||
<div className="notice notice-warn" key={w.id}>
|
||||
<span className="notice-main">
|
||||
<ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>
|
||||
{tr('pluginMarketWithdrawnInstalledWarn', { id: w.id, reason: locText(w.reason, locale, '') })}
|
||||
{w.instead_id ? ` · ${tr('pluginMarketWithdrawnInstead', { target: w.instead_name || w.instead_id })}` : ''}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{showLoader ? (
|
||||
<WordmarkLoader className="market-loader" label={tr(refreshing || result ? 'pluginMarketSyncing' : 'pluginMarketLoading')} />
|
||||
) : emptyAfterSync ? (
|
||||
<div className="plugins-empty">{query || kind ? tr('pluginSearchEmpty') : tr('pluginMarketEmpty')}</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="market-grid">
|
||||
{shown.map((item, i) => {
|
||||
const e = item.entry
|
||||
const desc = locText(e.description, locale, '')
|
||||
const muted = !!item.withdrawn || !item.compatible
|
||||
return (
|
||||
<article
|
||||
className={`market-card rg-p-card${muted ? ' is-muted' : ''}`}
|
||||
key={e.id}
|
||||
style={{ '--i': i % PAGE_SIZE } as React.CSSProperties}
|
||||
>
|
||||
<div className="market-card-head">
|
||||
<PluginAppIcon plugin={e} size="lg" />
|
||||
<div className="market-card-titles">
|
||||
<h3 className="market-card-name" title={locText(e.name, locale, e.id)}>{locText(e.name, locale, e.id)}</h3>
|
||||
<div className="market-card-byline">
|
||||
<PluginTrustBadge locale={locale} trust={e.trust} publisher={e.publisher} />
|
||||
<span className="market-card-dot" aria-hidden="true">·</span>
|
||||
<span className="market-card-version">v{e.version}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="market-card-action">{action(item)}</div>
|
||||
</div>
|
||||
<p className="market-card-desc" title={desc}>{desc}</p>
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{hasMore
|
||||
? <div ref={sentinel} className="market-sentinel" aria-hidden="true" />
|
||||
: items.length > PAGE_SIZE && <div className="market-feed-end">{tr('pluginMarketFeedEnd', { count: items.length })}</div>}
|
||||
</>
|
||||
)}
|
||||
|
||||
{prompt && (
|
||||
<Modal
|
||||
title={tr('pluginEnablePromptTitle', { name: locText(prompt.name, locale, prompt.id) })}
|
||||
subtitle={`${prompt.publisher || tr('pluginTrustCommunity')} · v${prompt.version}`}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => { if (!enabling) setPrompt(null) }}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
{(prompt.risks?.length ?? 0) > 0 ? (
|
||||
<>
|
||||
<p className="plugin-enable-lead">{tr('pluginEnablePromptBody')}</p>
|
||||
<RiskList locale={locale} risks={prompt.risks} />
|
||||
</>
|
||||
) : (
|
||||
<p className="plugin-enable-lead">{tr('pluginEnablePromptNoRisk')}</p>
|
||||
)}
|
||||
{prompt.needs_approval && (
|
||||
<label className="choice">
|
||||
<input type="checkbox" checked={promptChecked} onChange={(e) => setPromptChecked(e.target.checked)} />
|
||||
<span>{tr('pluginApproveCheckbox')}</span>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" disabled={enabling} onClick={() => setPrompt(null)}>{tr('pluginEnableLater')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={enabling || !!safeMode || (prompt.needs_approval && !promptChecked)}
|
||||
onClick={() => void enablePrompted()}
|
||||
>
|
||||
{tr('pluginEnableNow')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { getPluginMessageBundle, localeDir, parseAppError, 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: Omit<PanelContribution, 'convertValues'>
|
||||
assetToken: string
|
||||
appearance: 'light' | 'dark'
|
||||
/** Omit the panel title bar (e.g. when hosted inside a tab/segmented view). */
|
||||
headless?: boolean
|
||||
/** Upper bound for the iframe height in px (defaults to 480 for inline panels). */
|
||||
maxHeight?: number
|
||||
/** Incrementing this reloads the iframe cleanly. */
|
||||
refreshSignal?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, headless, maxHeight = 480, refreshSignal = 0,
|
||||
}) => {
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null)
|
||||
const localeRef = useRef<Locale>(locale)
|
||||
localeRef.current = locale
|
||||
const [failed, setFailed] = useState(false)
|
||||
const [nonce, setNonce] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (refreshSignal > 0) {
|
||||
setFailed(false)
|
||||
setNonce((n) => n + 1)
|
||||
}
|
||||
}, [refreshSignal])
|
||||
|
||||
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()
|
||||
}
|
||||
const dir = localeDir(locale)
|
||||
const messages = getPluginMessageBundle(panel.pluginId ?? '', locale)
|
||||
// bridgeApi 1.0 events (bridgeContract.ts).
|
||||
win.postMessage({ type: 'reims:event', event: 'theme.changed', data: { appearance, tokens } }, '*')
|
||||
win.postMessage({ type: 'reims:event', event: 'locale.changed', data: { locale, dir, messages } }, '*')
|
||||
// Pre-1.0 message types, kept for panels written before the bridge contract.
|
||||
win.postMessage({ type: 'reims:theme', appearance, locale, dir, tokens, messages }, '*')
|
||||
win.postMessage({ type: 'reims:i18n', locale, dir, messages }, '*')
|
||||
}
|
||||
|
||||
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 {
|
||||
if (msg.method === 'i18n.getBundle') {
|
||||
const curLocale = localeRef.current
|
||||
const bundle = {
|
||||
locale: curLocale,
|
||||
dir: localeDir(curLocale),
|
||||
messages: getPluginMessageBundle(panel.pluginId ?? '', curLocale),
|
||||
}
|
||||
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result: bundle }, '*')
|
||||
return
|
||||
}
|
||||
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: parseAppError(err).summary || 'RPC failed' }, '*')
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('message', onMessage)
|
||||
return () => {
|
||||
cancelled = true
|
||||
window.removeEventListener('message', onMessage)
|
||||
}
|
||||
}, [panel.pluginId, nonce, src])
|
||||
|
||||
if (failed || !src) {
|
||||
return (
|
||||
<div className="notice notice-error" role="alert">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{t(locale, 'panelLoadFailed')}</span>
|
||||
</span>
|
||||
{src && (
|
||||
<Button onClick={() => { setFailed(false); setNonce((n) => n + 1) }}>
|
||||
{t(locale, 'installersRetry')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`plugin-panel-wrap rg-p-plugin-view${headless ? ' is-headless' : ''}`} data-plugin={panel.pluginId}>
|
||||
{!headless && <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(maxHeight, panel.height || 220)) }}
|
||||
onLoad={syncTheme}
|
||||
onError={() => setFailed(true)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import {
|
||||
Activity, BadgeCheck, Binary, Clipboard, Code2, Files, Globe,
|
||||
Keyboard, Monitor, PanelsTopLeft, Search, ShieldCheck, Users,
|
||||
} from 'lucide-react'
|
||||
import React from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale } from '../types'
|
||||
import { Tip } from '../ui/controls'
|
||||
|
||||
export { PluginAppIcon, resolvePluginVisual, type PluginVisual, type PluginVisualSource } from './PluginAppIcon'
|
||||
|
||||
/** Publisher + trust-tier mark shared by Installed rows and Market cards. */
|
||||
export const PluginTrustBadge: React.FC<{
|
||||
locale: Locale
|
||||
trust: string
|
||||
publisher?: string
|
||||
}> = ({ locale, trust, publisher }) => {
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const meta = trust === 'official'
|
||||
? { cls: 'is-official', icon: <BadgeCheck size={13} aria-hidden="true" />, label: tr('pluginTrustOfficial') }
|
||||
: trust === 'verified'
|
||||
? { cls: 'is-verified', icon: <ShieldCheck size={13} aria-hidden="true" />, label: tr('pluginTrustVerified') }
|
||||
: trust === 'dev'
|
||||
? { cls: 'is-dev', icon: <Code2 size={13} aria-hidden="true" />, label: tr('pluginTrustDev') }
|
||||
: { cls: 'is-community', icon: <Users size={13} aria-hidden="true" />, label: tr('pluginTrustCommunity') }
|
||||
return (
|
||||
<Tip label={meta.label}>
|
||||
<span className={`plugin-trust ${meta.cls}`} tabIndex={0}>
|
||||
{meta.icon}
|
||||
<span className="plugin-trust-name">{publisher || meta.label}</span>
|
||||
</span>
|
||||
</Tip>
|
||||
)
|
||||
}
|
||||
|
||||
/** Search input with leading magnifying glass, shared by Installed and Market. */
|
||||
export const PluginSearchInput: React.FC<{
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
placeholder: string
|
||||
wide?: boolean
|
||||
}> = ({ value, onChange, placeholder, wide }) => (
|
||||
<div className={`plugin-search-wrap${wide ? ' is-wide' : ''}`}>
|
||||
<Search size={13} className="plugin-search-icon" aria-hidden="true" />
|
||||
<input
|
||||
type="search"
|
||||
className="input rg-p-input plugin-search"
|
||||
aria-label={placeholder}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
const RISKS: Record<string, { key: I18nKey; icon: React.ReactNode; high: boolean }> = {
|
||||
native: { key: 'pluginRiskNative', icon: <Binary size={15} aria-hidden="true" />, high: true },
|
||||
background: { key: 'pluginRiskBackground', icon: <Activity size={15} aria-hidden="true" />, high: true },
|
||||
network: { key: 'pluginRiskNetwork', icon: <Globe size={15} aria-hidden="true" />, high: true },
|
||||
files: { key: 'pluginRiskFiles', icon: <Files size={15} aria-hidden="true" />, high: true },
|
||||
vm: { key: 'pluginRiskVm', icon: <Monitor size={15} aria-hidden="true" />, high: true },
|
||||
clipboard: { key: 'pluginRiskClipboard', icon: <Clipboard size={15} aria-hidden="true" />, high: true },
|
||||
input: { key: 'pluginRiskInput', icon: <Keyboard size={15} aria-hidden="true" />, high: false },
|
||||
ui: { key: 'pluginRiskUi', icon: <PanelsTopLeft size={15} aria-hidden="true" />, high: false },
|
||||
}
|
||||
|
||||
/** Plain-language list of what a plugin can do (backend risk categories). */
|
||||
export const RiskList: React.FC<{ locale: Locale; risks?: string[] }> = ({ locale, risks }) => {
|
||||
const known = (risks ?? []).filter((r) => RISKS[r])
|
||||
if (known.length === 0) return null
|
||||
return (
|
||||
<ul className="plugin-risk-list">
|
||||
{known.map((r) => (
|
||||
<li key={r} className={`plugin-risk${RISKS[r].high ? ' is-high' : ''}`}>
|
||||
<span className="plugin-risk-icon">{RISKS[r].icon}</span>
|
||||
<span>{t(locale, RISKS[r].key)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,983 @@
|
||||
import {
|
||||
AlertTriangle, CheckCircle2, FolderOpen, PackagePlus, Palette,
|
||||
RefreshCw, Settings2, Shield, ShieldAlert, Sparkles, Terminal, Trash2,
|
||||
} from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import {
|
||||
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions, ScanReport,
|
||||
} from '../types'
|
||||
import { Button, IconButton, Tip } from '../ui/controls'
|
||||
import { ConfirmDialog, Modal } from '../ui/dialog'
|
||||
import { PopupSelect, Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
import { PluginMarket } from './PluginMarket'
|
||||
import { PluginPanelFrame } from './PluginPanelFrame'
|
||||
import { PluginAppIcon, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
|
||||
import { SchemaForm, locText } from './SchemaForm'
|
||||
|
||||
// Search only earns its space once the list is long enough to scan.
|
||||
const SEARCH_THRESHOLD = 12
|
||||
// A manual refresh spins at least this long so the click visibly lands.
|
||||
const MIN_SPIN_MS = 500
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
appearance: 'light' | 'dark'
|
||||
safeMode?: boolean
|
||||
onRefresh: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onThemeChanged?: () => void
|
||||
/** Switches the app language (used after enabling a language pack). */
|
||||
onLocaleSwitch?: (l: Locale) => void
|
||||
}
|
||||
|
||||
// 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, onLocaleSwitch,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [activeTab, setActiveTab] = useState<'installed' | 'market'>('installed')
|
||||
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 [approveReport, setApproveReport] = useState<ScanReport | 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 [disableTarget, setDisableTarget] = useState<PluginInfo | null>(null)
|
||||
const [deleteSchemeTarget, setDeleteSchemeTarget] = useState<CustomThemeScheme | null>(null)
|
||||
|
||||
// Static risk scan modal state (pre-install .zip preview or installed plugin scan)
|
||||
const [scanModal, setScanModal] = useState<{
|
||||
mode: 'archive' | 'installed'
|
||||
archivePath?: string
|
||||
report: ScanReport
|
||||
} | null>(null)
|
||||
const [scanBusy, setScanBusy] = useState(false)
|
||||
|
||||
// The market mounts (and touches the network) only once its tab is opened (§8.1).
|
||||
const [marketOpened, setMarketOpened] = useState(false)
|
||||
const [marketRefresh, setMarketRefresh] = useState(0)
|
||||
const [marketBusy, setMarketBusy] = useState(false)
|
||||
const [reloading, setReloading] = useState(false)
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
const manualReload = async () => {
|
||||
setReloading(true)
|
||||
const started = Date.now()
|
||||
await reload()
|
||||
const wait = MIN_SPIN_MS - (Date.now() - started)
|
||||
if (wait > 0) await new Promise((r) => window.setTimeout(r, wait))
|
||||
setReloading(false)
|
||||
}
|
||||
|
||||
// Enabling a language pack means the user wants that language: switch to
|
||||
// its first locale unless the current one is already among them.
|
||||
const adoptPluginLocale = (p: PluginInfo) => {
|
||||
const tags = p.locales ?? []
|
||||
if (tags.length > 0 && !tags.includes(locale)) onLocaleSwitch?.(tags[0])
|
||||
}
|
||||
|
||||
const onMarketChanged = async ({ enabled }: { enabled?: PluginInfo }) => {
|
||||
await reload()
|
||||
onRefresh()
|
||||
if (enabled) {
|
||||
onThemeChanged?.()
|
||||
adoptPluginLocale(enabled)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => { void reload() }, [safeMode])
|
||||
|
||||
useEffect(() => { if (activeTab === 'market') setMarketOpened(true) }, [activeTab])
|
||||
|
||||
const togglePlugin = async (p: PluginInfo, enable: boolean, confirmed = false) => {
|
||||
// Disabling a plugin that still owns VMs leaves them "driver unavailable": say so first.
|
||||
if (!enable && p.in_use && !confirmed) {
|
||||
setDisableTarget(p)
|
||||
return
|
||||
}
|
||||
if (enable && p.needs_approval) {
|
||||
setApproveChecked(false)
|
||||
setApproveReport(null)
|
||||
setApproveTarget(p)
|
||||
void api.ScanInstalledPlugin(p.id).then(setApproveReport).catch((e) => console.warn('[plugins] ScanInstalledPlugin failed:', p.id, e))
|
||||
return
|
||||
}
|
||||
setBusyID(p.id)
|
||||
try {
|
||||
if (enable) await api.EnablePlugin(p.id, false)
|
||||
else await api.DisablePlugin(p.id)
|
||||
await reload()
|
||||
onRefresh()
|
||||
onThemeChanged?.()
|
||||
if (enable) adoptPluginLocale(p)
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailToggle'), e)
|
||||
} finally {
|
||||
setBusyID('')
|
||||
}
|
||||
}
|
||||
|
||||
const confirmApprove = async () => {
|
||||
if (!approveTarget || !approveChecked) return
|
||||
const target = approveTarget
|
||||
setApproveTarget(null)
|
||||
setApproveReport(null)
|
||||
setBusyID(target.id)
|
||||
try {
|
||||
await api.EnablePlugin(target.id, true)
|
||||
await reload()
|
||||
onRefresh()
|
||||
onThemeChanged?.()
|
||||
adoptPluginLocale(target)
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailEnable'), e)
|
||||
} finally {
|
||||
setBusyID('')
|
||||
}
|
||||
}
|
||||
|
||||
const importLocalZip = async () => {
|
||||
try {
|
||||
const path = await api.PickFile(tr('pluginImportTitle'), '*.zip')
|
||||
if (!path) return
|
||||
setScanBusy(true)
|
||||
const report = await api.InspectPluginArchive(path)
|
||||
setScanModal({ mode: 'archive', archivePath: path, report })
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailScan'), e)
|
||||
} finally {
|
||||
setScanBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const confirmInstallScannedArchive = async () => {
|
||||
if (!scanModal || scanModal.mode !== 'archive' || !scanModal.archivePath || scanModal.report.hard_blocked) return
|
||||
const archivePath = scanModal.archivePath
|
||||
setScanBusy(true)
|
||||
try {
|
||||
await api.InstallPluginArchive(archivePath)
|
||||
setScanModal(null)
|
||||
await reload()
|
||||
onRefresh()
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailImport'), e)
|
||||
} finally {
|
||||
setScanBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const inspectInstalledPlugin = async (p: PluginInfo) => {
|
||||
setScanBusy(true)
|
||||
try {
|
||||
const report = await api.ScanInstalledPlugin(p.id)
|
||||
setScanModal({ mode: 'installed', report })
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailScan'), e)
|
||||
} finally {
|
||||
setScanBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// System plugins are part of the host and never listed; builtins keep backend order.
|
||||
const builtins = useMemo(() => plugins.filter((p) => p.source === 'builtin'), [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])
|
||||
|
||||
// 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 rg-p-badge badge-warn">{tr('pluginStateDegraded')}</span>
|
||||
if (p.state === 'failed') return <span className="badge rg-p-badge badge-warn">{tr('pluginStateFailed')}</span>
|
||||
if (p.state === 'pending' && p.enabled) return <span className="badge rg-p-badge">{tr('pluginStatePending')}</span>
|
||||
return null
|
||||
}
|
||||
|
||||
const renderRow = (p: PluginInfo) => {
|
||||
const isBuiltin = p.source === 'builtin'
|
||||
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}>
|
||||
<PluginAppIcon plugin={p} size="md" />
|
||||
<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">
|
||||
<PluginTrustBadge locale={locale} trust={p.trust} publisher={p.publisher} />
|
||||
<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">
|
||||
{!isBuiltin && (
|
||||
<IconButton label={tr('pluginScanInspect')} icon={<Shield size={15} />} onClick={() => void inspectInstalledPlugin(p)} />
|
||||
)}
|
||||
{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 || (!!safeMode && !isBuiltin)}
|
||||
checked={p.enabled}
|
||||
onChange={(checked) => void togglePlugin(p, checked)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const renderScanReportBody = (report: ScanReport) => {
|
||||
const hard = report.hard_findings ?? []
|
||||
const caps = report.capabilities ?? []
|
||||
const pending = report.pending_findings ?? []
|
||||
const execs = report.executables ?? []
|
||||
return (
|
||||
<div className="stack-3">
|
||||
<div className={`notice ${report.hard_blocked ? 'notice-error' : report.needs_approval ? 'notice-warn' : 'notice-ok'}`}>
|
||||
<span className="notice-main">
|
||||
{report.hard_blocked
|
||||
? <ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
|
||||
: report.needs_approval
|
||||
? <AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
: <CheckCircle2 size={15} className="notice-icon" aria-hidden="true" />}
|
||||
<span>{locText(report.headline, locale, report.hard_blocked ? 'Blocked' : 'Passed')}</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{report.native_exec_notice && locText(report.native_exec_notice, locale, '') && (
|
||||
<div className="notice notice-warn">
|
||||
<span className="notice-main">
|
||||
<ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{locText(report.native_exec_notice, locale, '')}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hard.length > 0 && (
|
||||
<div className="plugin-scan-section">
|
||||
<div className="plugin-scan-section-title is-danger">{tr('pluginScanHardSection')}</div>
|
||||
<div className="list">
|
||||
{hard.map((f, idx) => (
|
||||
<div className="row" key={`${f.check}-${idx}`}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="badge rg-p-badge badge-danger">{f.check}</span>
|
||||
{f.target && <span className="mono">{f.target}</span>}
|
||||
</div>
|
||||
<div className="row-sub">{locText(f.localized, locale, f.message)}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{caps.length > 0 && (
|
||||
<div className="plugin-scan-section">
|
||||
<div className="plugin-scan-section-title">{tr('pluginScanCapabilitiesSection')}</div>
|
||||
<div className="list">
|
||||
{caps.map((c) => (
|
||||
<div className="row" key={c.id}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className={`badge rg-p-badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
|
||||
<span>{locText(c.title, locale, c.id)}</span>
|
||||
<span className="mono muted" style={{ fontSize: 'var(--fs-11)' }}>{c.id}</span>
|
||||
</div>
|
||||
<div className="row-sub">{locText(c.summary, locale, '')}</div>
|
||||
{(c.examples?.length ?? 0) > 0 && (
|
||||
<div className="plugin-scan-examples mono">
|
||||
{c.examples!.map((ex, i) => <div key={i}>· {ex}</div>)}
|
||||
{(c.extra_count ?? 0) > 0 && (
|
||||
<div className="muted">· {tr('pluginScanMoreItems', { count: c.extra_count! })}</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(pending.length > 0 || execs.length > 0) && (
|
||||
<div className="plugin-scan-section">
|
||||
<div className="plugin-scan-section-title">{tr('pluginScanAdvisoriesSection')}</div>
|
||||
<div className="list">
|
||||
{pending.map((f, idx) => (
|
||||
<div className="row" key={`pend-${f.check}-${idx}`}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="badge rg-p-badge">{f.check}</span>
|
||||
{f.target && <span className="mono">{f.target}</span>}
|
||||
</div>
|
||||
<div className="row-sub">{locText(f.localized, locale, f.message)}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{execs.map((ex) => (
|
||||
<div className="row" key={ex.path}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className={`badge rg-p-badge${ex.declared ? '' : ' badge-danger'}`}>{ex.declared ? 'EXE' : 'UNLISTED'}</span>
|
||||
<span className="mono">{ex.path}</span>
|
||||
</div>
|
||||
<div className="row-sub mono selectable">SHA-256: {ex.sha256}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</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">
|
||||
{activeTab === 'installed' && showSearch && (
|
||||
<PluginSearchInput
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder={tr('pluginSearchPlaceholder')}
|
||||
/>
|
||||
)}
|
||||
<IconButton
|
||||
label={activeTab === 'market' ? tr('pluginMarketRefresh') : tr('refresh')}
|
||||
icon={<RefreshCw size={16} className={(activeTab === 'market' ? marketBusy : reloading) ? 'spin' : undefined} />}
|
||||
disabled={activeTab === 'market' ? marketBusy : reloading}
|
||||
onClick={() => activeTab === 'market' ? setMarketRefresh((n) => n + 1) : void manualReload()}
|
||||
/>
|
||||
<IconButton label={tr('pluginLinkDevBtn')} icon={<FolderOpen size={16} />} onClick={linkDevDir} />
|
||||
<Button variant="primary" disabled={scanBusy} icon={<PackagePlus size={14} aria-hidden="true" />} onClick={importLocalZip}>
|
||||
{tr('pluginImportBtn')}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="plugins-switch">
|
||||
<Segmented
|
||||
label={tr('sidebarPlugins')}
|
||||
value={activeTab}
|
||||
onChange={setActiveTab}
|
||||
options={[
|
||||
{ value: 'installed', label: tr('pluginTabInstalled') },
|
||||
{ value: 'market', label: tr('pluginTabMarket') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{marketOpened && (
|
||||
<div hidden={activeTab !== 'market'}>
|
||||
<PluginMarket
|
||||
locale={locale}
|
||||
safeMode={safeMode}
|
||||
installed={plugins}
|
||||
refreshSignal={marketRefresh}
|
||||
onBusyChange={setMarketBusy}
|
||||
onChanged={onMarketChanged}
|
||||
onError={onError}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'installed' && (
|
||||
<>
|
||||
{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" role="radiogroup" aria-label={tr('pluginColorSchemes')}>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={!activeTheme.active_scheme}
|
||||
className={`plugin-pill${!activeTheme.active_scheme ? ' is-active' : ''}`}
|
||||
onClick={() => void selectTheme(activeTheme.theme_id, '')}
|
||||
>
|
||||
{tr('pluginSchemeDefault')}
|
||||
</button>
|
||||
{presetSchemes.map((s) => (
|
||||
<button
|
||||
key={s.id}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={activeTheme.active_scheme === s.id}
|
||||
className={`plugin-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"
|
||||
role="radio"
|
||||
aria-checked={activeTheme.active_scheme === s.id}
|
||||
className={`plugin-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="skeleton-list" role="status" aria-label={tr('sidebarPlugins')}>
|
||||
{[0, 1, 2].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>
|
||||
) : (
|
||||
<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" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{scanModal && (
|
||||
<Modal
|
||||
title={scanModal.mode === 'archive' ? tr('pluginScanArchiveTitle') : tr('pluginScanModalTitle')}
|
||||
subtitle={scanModal.report.plugin_id ? `${locText(scanModal.report.name, locale, scanModal.report.plugin_id)} · v${scanModal.report.version || '—'}` : scanModal.archivePath}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => { if (!scanBusy) setScanModal(null) }}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
{renderScanReportBody(scanModal.report)}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span className="muted mono" style={{ fontSize: 'var(--fs-11)' }}>
|
||||
{scanModal.report.tier ? `${scanModal.report.tier} · ${scanModal.report.trust || 'community'}` : ''}
|
||||
</span>
|
||||
<span className="hstack">
|
||||
{scanModal.mode === 'archive' ? (
|
||||
<>
|
||||
<Button variant="ghost" disabled={scanBusy} onClick={() => setScanModal(null)}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={scanBusy || scanModal.report.hard_blocked}
|
||||
onClick={() => void confirmInstallScannedArchive()}
|
||||
>
|
||||
{scanModal.report.hard_blocked ? tr('pluginScanBlockedBtn') : tr('pluginScanInstallConfirm')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button variant="primary" onClick={() => setScanModal(null)}>{tr('pluginDone')}</Button>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{approveTarget && (
|
||||
<Modal
|
||||
title={tr('pluginApproveTitle')}
|
||||
subtitle={locText(approveTarget.name, locale, approveTarget.id)}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => { setApproveTarget(null); setApproveReport(null) }}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
{(approveTarget.tier === 'L3' || (approveTarget.permissions ?? []).some((p) => p.name === 'ui:script')) && (
|
||||
<div className="notice notice-warn">
|
||||
<span className="notice-main">
|
||||
<ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{approveReport?.native_exec_notice ? locText(approveReport.native_exec_notice, locale, tr('pluginApproveL3Warn')) : tr('pluginApproveL3Warn')}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<RiskList locale={locale} risks={approveTarget.risks} />
|
||||
<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>
|
||||
{(approveReport?.capabilities?.length ?? 0) > 0 && (
|
||||
<div className="plugin-scan-section">
|
||||
<div className="plugin-scan-section-title">{tr('pluginScanCapabilitiesSection')}</div>
|
||||
<div className="list">
|
||||
{approveReport!.capabilities!.map((c) => (
|
||||
<div className="row" key={c.id}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className={`badge rg-p-badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
|
||||
<span>{locText(c.title, locale, c.id)}</span>
|
||||
</div>
|
||||
<div className="row-sub">{locText(c.summary, locale, '')}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<label className="choice">
|
||||
<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); setApproveReport(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 className="dialog-body">
|
||||
<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>
|
||||
)}
|
||||
|
||||
{disableTarget && (
|
||||
<ConfirmDialog
|
||||
title={tr('pluginDisableInUseTitle')}
|
||||
description={tr('pluginDisableInUseBody')}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('pluginDisable')}
|
||||
onCancel={() => setDisableTarget(null)}
|
||||
onConfirm={() => {
|
||||
const target = disableTarget
|
||||
setDisableTarget(null)
|
||||
void togglePlugin(target, false, true)
|
||||
}}
|
||||
>
|
||||
<div className="row-sub">{locText(disableTarget.name, locale, disableTarget.id)}</div>
|
||||
</ConfirmDialog>
|
||||
)}
|
||||
|
||||
{removeTarget && (
|
||||
<ConfirmDialog
|
||||
title={tr('pluginRemove')}
|
||||
description={locText(removeTarget.name, locale, removeTarget.id)}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('pluginRemove')}
|
||||
onCancel={() => setRemoveTarget(null)}
|
||||
onConfirm={() => {
|
||||
const target = removeTarget
|
||||
setRemoveTarget(null)
|
||||
void removePlugin(target)
|
||||
}}
|
||||
>
|
||||
<div className="row-sub mono">{removeTarget.id}@{removeTarget.version}</div>
|
||||
</ConfirmDialog>
|
||||
)}
|
||||
|
||||
{deleteSchemeTarget && (
|
||||
<ConfirmDialog
|
||||
title={tr('pluginDeleteScheme')}
|
||||
description={deleteSchemeTarget.name}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('pluginDeleteScheme')}
|
||||
onCancel={() => setDeleteSchemeTarget(null)}
|
||||
onConfirm={() => {
|
||||
const target = deleteSchemeTarget
|
||||
setDeleteSchemeTarget(null)
|
||||
void deleteScheme(target.id)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{logTarget && (
|
||||
<Modal
|
||||
title={tr('pluginLogTitle', { id: logTarget.id })}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setLogTarget(null)}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
<pre className="plugin-log-pre mono selectable">{logTarget.text}</pre>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{schemeEditorOpen && (
|
||||
<Modal
|
||||
title={tr('pluginSchemeModalTitle')}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setSchemeEditorOpen(false)}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('pluginSchemeName')}</span>
|
||||
<input className="input rg-p-input" value={schemeName} onChange={(e) => setSchemeName(e.target.value)} placeholder={tr('pluginSchemePlaceholder')} />
|
||||
</label>
|
||||
<label className="hstack">
|
||||
<span className="field-label">{tr('pluginAccentSeed')}</span>
|
||||
<input type="color" value={seedAccent} onChange={(e) => setSeedAccent(e.target.value)} />
|
||||
<span className="mono">{seedAccent}</span>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('pluginSurfaceSeed')}</span>
|
||||
<input className="input rg-p-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,9 +1,11 @@
|
||||
import { Download, LoaderCircle, Pause } from 'lucide-react'
|
||||
import { Download, LoaderCircle, Pause, RefreshCw } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
import { InstalledRuntime, Locale, RemoteRuntime, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
interface Props {
|
||||
@@ -29,6 +31,7 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
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
|
||||
@@ -38,11 +41,16 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
.then((list) => { if (live) setRemote(list ?? []) })
|
||||
.catch((e) => { if (live) setError(String(e).replace(/^Error:\s*/, '')) })
|
||||
return () => { live = false }
|
||||
}, [channel, task?.status === 'done'])
|
||||
}, [channel, 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)
|
||||
|
||||
@@ -50,15 +58,21 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
if (running && task) {
|
||||
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 rg-p-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) {
|
||||
sub = <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) {
|
||||
sub = <div className="row-sub">…</div>
|
||||
} else if (!latest) {
|
||||
@@ -67,7 +81,8 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
sub = (
|
||||
<div className="row-sub">
|
||||
{active ? tr('runtimeNewer', { v: latest.commit }) : tr('runtimeLatest', { v: latest.commit })}
|
||||
{' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)} · {gb(latest.archive_size)}
|
||||
{' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)}
|
||||
{latest.archive_size > 0 ? ` · ${gb(latest.archive_size)}` : ''}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -84,12 +99,16 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
<div className="row-right">
|
||||
{running && task?.cancelable ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => onCancel(task.id)} />
|
||||
) : !running && error ? (
|
||||
<Button icon={<RefreshCw size={14} />} onClick={() => setReload((n) => n + 1)}>
|
||||
{tr('runtimeRetry')}
|
||||
</Button>
|
||||
) : !running && updatable ? (
|
||||
<Button variant="primary" icon={<Download size={14} />} onClick={() => onInstall(latest!.commit)}>
|
||||
{tr(active ? 'runtimeUpdate' : 'runtimeInstall')}
|
||||
</Button>
|
||||
) : !running && active && remote ? (
|
||||
<span className="badge badge-ok">{tr('runtimeUpToDate')}</span>
|
||||
<span className="badge rg-p-badge badge-ok">{tr('runtimeUpToDate')}</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
@@ -99,15 +118,7 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
<div className="row-sub">{tr('runtimeAlphaHint')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<label className="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={tr('runtimeAlpha')}
|
||||
checked={channel === 'alpha'}
|
||||
onChange={(e) => onChannel(e.target.checked)}
|
||||
/>
|
||||
<span className="slider" />
|
||||
</label>
|
||||
<Switch label={tr('runtimeAlpha')} checked={channel === 'alpha'} onChange={onChannel} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import React from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
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 rg-p-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 rg-p-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 rg-p-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>
|
||||
)
|
||||
}
|
||||
@@ -19,17 +19,16 @@ export const SendTextDialog: React.FC<Props> = ({ locale, vmName, guestToolsConn
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
|
||||
<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" style={{ marginTop: 10 }}>
|
||||
<div className="field field-spaced">
|
||||
<textarea
|
||||
className="input"
|
||||
className="input rg-p-input textarea"
|
||||
rows={4}
|
||||
style={{ height: 'auto', minHeight: 88, resize: 'vertical', padding: '8px 10px', lineHeight: 1.5 }}
|
||||
placeholder={t(locale, 'sendTextPlaceholder')}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
@@ -45,10 +44,10 @@ export const SendTextDialog: React.FC<Props> = ({ locale, vmName, guestToolsConn
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn">{t(locale, 'cancel')}</button>
|
||||
<button type="button" className="btn rg-p-button">{t(locale, 'cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-primary" disabled={!canSend} onClick={() => onConfirm(text)}>
|
||||
<button type="button" className="btn rg-p-button btn-primary" disabled={!canSend} onClick={() => onConfirm(text)}>
|
||||
{t(locale, 'sendTextConfirm')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
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 '../i18n/domains/wizard.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { getLocaleOptions, I18nKey, joinNotices, locText, t } from '../i18n'
|
||||
import { AppState, DataRootCheck, DataRootChoice, Locale, MarketCatalogItem, ResolvedLocalePack, Task } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { recommendedMemoryGB, shortGPUName } from '../lib/format'
|
||||
import { PopupSelect } from '../ui/settings'
|
||||
import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format'
|
||||
import { api } from '../wails'
|
||||
import { PluginAppIcon } from './PluginAppIcon'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
locales?: ResolvedLocalePack[]
|
||||
state: AppState
|
||||
stage: 'folder' | 'runtime'
|
||||
runtimeTask: Task | null
|
||||
onLocale: (l: Locale) => void
|
||||
/** A plugin was installed or enabled; the app reloads plugin contributions. */
|
||||
onPluginsChanged: () => void
|
||||
onFolderDone: () => void
|
||||
onFinish: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
@@ -38,13 +45,16 @@ 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, state, tr, onLocale, onPluginsChanged, onFolderDone, onError }) => {
|
||||
const [choices, setChoices] = useState<DataRootChoice[]>([])
|
||||
const [custom, setCustom] = useState('')
|
||||
const [customMode, setCustomMode] = useState(false)
|
||||
const [selected, setSelected] = useState('')
|
||||
const [check, setCheck] = useState<DataRootCheck | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
// A market language pack for the OS language, looked up once on first launch.
|
||||
const [langPack, setLangPack] = useState<MarketCatalogItem | null>(null)
|
||||
const [langPackOn, setLangPackOn] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
api.SuggestDataRoots().then((list) => {
|
||||
@@ -53,12 +63,18 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
|
||||
const rec = l.find((c) => c.recommended) ?? l[0]
|
||||
if (rec) setSelected(rec.path)
|
||||
}).catch((e) => onError(tr('failGeneric'), e))
|
||||
api.SuggestLanguagePack().then((p) => { if (p?.entry) setLangPack(p) }).catch((e) => console.warn('[setup] SuggestLanguagePack failed:', e))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selected) { setCheck(null); return }
|
||||
let live = true
|
||||
api.CheckDataRoot(selected).then((c) => { if (live) setCheck(c) }).catch(() => {})
|
||||
api.CheckDataRoot(selected)
|
||||
.then((c) => { if (live) setCheck(c) })
|
||||
.catch((e) => {
|
||||
if (live) setCheck(null)
|
||||
console.warn('[setup] CheckDataRoot failed:', e)
|
||||
})
|
||||
return () => { live = false }
|
||||
}, [selected])
|
||||
|
||||
@@ -71,14 +87,29 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
|
||||
setBusy(true)
|
||||
try {
|
||||
await api.CompleteSetup(selected)
|
||||
onFolderDone()
|
||||
} catch (e) {
|
||||
onError(tr('failGeneric'), e)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
return
|
||||
}
|
||||
// Plugins live in the data folder, so the pack installs once it exists.
|
||||
// With the language left on "auto", enabling the pack is enough for the
|
||||
// UI to switch to the OS language.
|
||||
if (langPack && langPackOn) {
|
||||
try {
|
||||
const info = await api.InstallMarketPlugin(langPack.entry.id, false)
|
||||
if (info && !info.enabled && !info.needs_approval) await api.EnablePlugin(info.id, false)
|
||||
onPluginsChanged()
|
||||
} catch (e) {
|
||||
onError(tr('setupLangPackFailed'), e)
|
||||
}
|
||||
}
|
||||
setBusy(false)
|
||||
onFolderDone()
|
||||
}
|
||||
|
||||
const osTag = state.detected_locale || locale
|
||||
|
||||
const option = (path: string, meta: React.ReactNode) => (
|
||||
<label key={path} className="choice-card" data-selected={selected === path}>
|
||||
<input type="radio" name="data-root" checked={selected === path} onChange={() => setSelected(path)} />
|
||||
@@ -108,18 +139,20 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
|
||||
{choices.map((c) => option(c.path, (
|
||||
<>
|
||||
{tr('setupFree', { n: c.free_gb.toFixed(0) })}
|
||||
{c.recommended && <span className="badge badge-accent">{tr('setupRecommended')}</span>}
|
||||
{c.system && <span className="badge">{tr('setupSystem')}</span>}
|
||||
{c.external && <span className="badge badge-warn">{tr('setupExternal')}</span>}
|
||||
{c.recommended && <span className="badge rg-p-badge badge-accent">{tr('setupRecommended')}</span>}
|
||||
{c.system && <span className="badge rg-p-badge">{tr('setupSystem')}</span>}
|
||||
{c.external && <span className="badge rg-p-badge badge-warn">{tr('setupExternal')}</span>}
|
||||
</>
|
||||
)))}
|
||||
{customMode ? (
|
||||
<div className="input-group">
|
||||
<input
|
||||
className="input mono"
|
||||
className="input rg-p-input mono"
|
||||
aria-label={tr('setupOther')}
|
||||
value={custom}
|
||||
placeholder="D:\VMs\reims-go"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
autoFocus
|
||||
onFocus={() => custom && setSelected(custom)}
|
||||
onChange={(e) => { setCustom(e.target.value); setSelected(e.target.value.trim()) }}
|
||||
@@ -131,17 +164,34 @@ 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>
|
||||
)}
|
||||
{langPack && (
|
||||
<label className="setup-langpack">
|
||||
<input type="checkbox" checked={langPackOn} disabled={busy} onChange={(e) => setLangPackOn(e.target.checked)} />
|
||||
<PluginAppIcon kind="locale" size="sm" />
|
||||
<span className="setup-langpack-main">
|
||||
{/* The pack's name and blurb in the OS language: that is who it is for. */}
|
||||
<span className="setup-langpack-title">
|
||||
{tr('setupLangPackOffer', { name: locText(langPack.entry.name, osTag, langPack.entry.id) })}
|
||||
</span>
|
||||
{locText(langPack.entry.description, osTag) && (
|
||||
<span className="setup-langpack-sub">{locText(langPack.entry.description, osTag)}</span>
|
||||
)}
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
<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={state.config.locale || 'auto'}
|
||||
onChange={onLocale}
|
||||
options={getLocaleOptions(locales, locale, state.detected_locale)}
|
||||
/>
|
||||
<Button variant="primary" busy={busy} disabled={!selected || !!check?.error} onClick={next}>{tr('setupContinue')}</Button>
|
||||
</div>
|
||||
</>
|
||||
@@ -158,6 +208,8 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
|
||||
}
|
||||
const whpxOK = host.whpx === 'ready'
|
||||
const gpu = host.recommended_gpu ?? (host.gpus ?? []).find((g) => g.kind !== 'virtual')
|
||||
const gpuHint = gpuCompatHint(locale, gpu)
|
||||
const gpuOK = !host.vulkan_probe_error && !!gpu && gpu.compat !== 'warn' && gpu.compat !== 'unsupported'
|
||||
const recMem = recommendedMemoryGB(host)
|
||||
return (
|
||||
<>
|
||||
@@ -181,7 +233,7 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
|
||||
{host.whpx === 'missing' ? (
|
||||
<Button variant="primary" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
|
||||
) : (
|
||||
<span className={`badge ${whpxOK ? 'badge-ok' : 'badge-warn'}`}>
|
||||
<span className={`badge rg-p-badge ${whpxOK ? 'badge-ok' : 'badge-warn'}`}>
|
||||
{tr(whpxOK ? 'whpxReady' : host.whpx === 'no_hypervisor' ? 'whpxNoHvShort' : 'whpxUnsupportedShort')}
|
||||
</span>
|
||||
)}
|
||||
@@ -190,10 +242,24 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
|
||||
<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>
|
||||
{gpu && <div className="row-sub">{shortGPUName(gpu.name)}</div>}
|
||||
{host.vulkan_probe_error ? (
|
||||
<div className="row-sub warn-text">{tr('vulkanProbeFailed', { detail: host.vulkan_probe_error })}</div>
|
||||
) : !gpu && <div className="row-sub">{tr('setupNoGPU')}</div>}
|
||||
{gpuHint && <div className="row-sub warn-text">{gpuHint}</div>}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<span className={`badge ${gpu ? 'badge-ok' : 'badge-warn'}`}>{tr(gpu ? 'whpxReady' : 'hostNeedsAction')}</span>
|
||||
<span className={`badge rg-p-badge ${gpuOK ? 'badge-ok' : 'badge-warn'}`}>
|
||||
{tr(
|
||||
gpuOK
|
||||
? 'whpxReady'
|
||||
: gpu?.compat === 'unsupported'
|
||||
? 'gpuCompatUnsupported'
|
||||
: gpu?.compat === 'warn'
|
||||
? 'gpuCompatWarn'
|
||||
: 'hostNeedsAction',
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
@@ -206,7 +272,7 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<span className={`badge ${recMem >= 8 ? 'badge-ok' : 'badge-warn'}`}>{tr('setupRecMem', { n: recMem })}</span>
|
||||
<span className={`badge rg-p-badge ${recMem >= 8 ? 'badge-ok' : 'badge-warn'}`}>{tr('setupRecMem', { n: recMem })}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,27 +1,59 @@
|
||||
import { Cpu, Download, Monitor, Plus } from 'lucide-react'
|
||||
import * as Ctx from '@radix-ui/react-context-menu'
|
||||
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Pause, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
|
||||
import React, { useRef } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { I18nKey, localeDir, t } from '../i18n'
|
||||
import { Locale, VMListItem } from '../types'
|
||||
import { vmRefKey } from '../lib/vmRef'
|
||||
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { VersionArt } from '../macos/VersionArt'
|
||||
import { BrandMark, HostIcon } from '../ui/themeVisuals'
|
||||
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
|
||||
vms: VMListItem[]
|
||||
transitions: Record<string, string>
|
||||
/** VM name → currently running action (disables conflicting context menu actions). */
|
||||
busyActions?: Record<string, VMAction>
|
||||
selected: string
|
||||
hostReady: boolean
|
||||
/** Whether the active runtime supports VM suspend/resume. */
|
||||
canSuspend: 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, downloading }) => {
|
||||
export const Sidebar: React.FC<Props> = ({
|
||||
locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, 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), INSTALLERS_ID, HOST_ID]
|
||||
const ctxOpenedByPointerRef = useRef(false)
|
||||
const ids = [...vms.map((v) => vmRefKey(v)), 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) => {
|
||||
@@ -37,66 +69,221 @@ 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 hasSelectedInList = ids.includes(selected)
|
||||
const navBtn = (
|
||||
id: string,
|
||||
label: string,
|
||||
icon: React.ReactNode,
|
||||
badgeClass: string,
|
||||
stateLabel: string,
|
||||
kind: ReturnType<typeof statusKind> | null,
|
||||
onDoubleClick?: () => void,
|
||||
dot?: boolean,
|
||||
vm?: { state: string; driver: string; busy: boolean },
|
||||
) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
role="option"
|
||||
data-id={id}
|
||||
className="nav-item"
|
||||
className="nav-item rg-p-nav-item"
|
||||
data-selected={selected === id ? 'true' : 'false'}
|
||||
data-vm-state={vm?.state}
|
||||
data-driver={vm?.driver}
|
||||
data-busy={vm ? (vm.busy ? 'true' : 'false') : undefined}
|
||||
aria-selected={selected === id}
|
||||
aria-label={stateLabel ? `${label},${stateLabel}` : label}
|
||||
tabIndex={selected === id ? 0 : -1}
|
||||
aria-label={stateLabel ? t(locale, 'sidebarItemAria', { label, state: stateLabel }) : label}
|
||||
tabIndex={selected === id || (!hasSelectedInList && id === ids[0]) ? 0 : -1}
|
||||
onClick={() => onSelect(id)}
|
||||
onDoubleClick={onDoubleClick}
|
||||
>
|
||||
<span className={`nav-icon-badge ${badgeClass}`} aria-hidden="true">{icon}</span>
|
||||
<span className="nav-label">{label}</span>
|
||||
{dot && <span className="nav-dot" aria-hidden="true" />}
|
||||
{kind && (
|
||||
<Tip label={stateLabel} side="right">
|
||||
<span className="hstack"><StatusShape kind={kind} /></span>
|
||||
</Tip>
|
||||
)}
|
||||
{vm && <span className="rg-slot-anchor nav-item-trailing" data-rg-slot="nav.item.trailing" data-rg-key={id} aria-hidden="true" />}
|
||||
</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">
|
||||
<BrandMark className="sidebar-brand-mark" />
|
||||
<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>}
|
||||
<div className="rg-slot-anchor" data-rg-slot="sidebar.header" />
|
||||
{updateCard}
|
||||
<div className="sidebar-head rg-p-sidebar-head">
|
||||
<span>{tr('sidebarVMs')}</span>
|
||||
<IconButton small label={tr('newVM')} shortcut="Ctrl+N" icon={<HostIcon name="new-vm"><Plus size={15} /></HostIcon>} 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 rg-p-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 st = transitions[vmRefKey(vm)] ?? vm.state
|
||||
const running = st === 'running'
|
||||
const stopped = st === 'stopped'
|
||||
const suspended = st === 'suspended'
|
||||
const transitioning = st === 'starting' || st === 'stopping' || st === 'suspending' || st === 'resuming'
|
||||
const busyAction = Object.prototype.hasOwnProperty.call(busyActions, vm.name) ? busyActions[vm.name] : undefined
|
||||
const vmBusy = !!busyAction
|
||||
const label = displayNames[vm.name] || vm.name
|
||||
const trigger = navBtn(
|
||||
vmRefKey(vm),
|
||||
label,
|
||||
<VersionArt shape="tile" major={macosMajors[vm.name] ?? null} name={label} />,
|
||||
'nav-icon-art',
|
||||
t(locale, `state_${st}` as I18nKey),
|
||||
statusKind(st),
|
||||
onActivate ? () => onActivate(vmRefKey(vm)) : undefined,
|
||||
undefined,
|
||||
{ state: st, driver: vm.driver_id ?? '', busy: vmBusy || transitioning },
|
||||
)
|
||||
if (!onVMContextAction) return trigger
|
||||
return (
|
||||
<Ctx.Root key={vmRefKey(vm)} dir={localeDir(locale)}>
|
||||
<Ctx.Trigger
|
||||
asChild
|
||||
onContextMenu={(e) => {
|
||||
ctxOpenedByPointerRef.current = e.button === 2 && (e.clientX !== 0 || e.clientY !== 0)
|
||||
}}
|
||||
>
|
||||
{trigger}
|
||||
</Ctx.Trigger>
|
||||
<Ctx.Portal>
|
||||
<Ctx.Content
|
||||
className="menu rg-p-menu"
|
||||
onCloseAutoFocus={(e) => {
|
||||
if (
|
||||
ctxOpenedByPointerRef.current
|
||||
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
|
||||
) {
|
||||
e.preventDefault()
|
||||
}
|
||||
}}
|
||||
>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'start')}>
|
||||
<HostIcon name="start"><Play size={14} /></HostIcon> {tr('start')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
{suspended && (
|
||||
<>
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy || !canSuspend} onSelect={() => onVMContextAction(vmRefKey(vm), 'resume')}>
|
||||
<HostIcon name="resume"><Play size={14} /></HostIcon> {tr('resume')}
|
||||
</Ctx.Item>
|
||||
{!canSuspend && <Ctx.Label className="menu-group-label">{tr('resumeUnavailable')}</Ctx.Label>}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item danger" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'discardSuspend')}>
|
||||
<Power size={14} /> {tr('discardSuspend')}
|
||||
</Ctx.Item>
|
||||
</>
|
||||
)}
|
||||
{running && (
|
||||
<>
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'focus')}>
|
||||
<HostIcon name="window"><AppWindow size={14} /></HostIcon> {tr('showWindow')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'fullscreen')}>
|
||||
<HostIcon name="fullscreen"><Maximize2 size={14} /></HostIcon> {tr('toggleFullscreen')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'screenshot')}>
|
||||
<HostIcon name="screenshot"><Camera size={14} /></HostIcon> {tr('copyScreenshot')}
|
||||
</Ctx.Item>
|
||||
{canSuspend && (
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'suspend')}>
|
||||
<HostIcon name="suspend"><Pause size={14} /></HostIcon> {tr('suspend')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'stop')}>
|
||||
<HostIcon name="stop"><Square size={14} /></HostIcon> {tr('stop')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'restart')}>
|
||||
<HostIcon name="restart"><RotateCw size={14} /></HostIcon> {tr('restart')}
|
||||
</Ctx.Item>
|
||||
</>
|
||||
)}
|
||||
{(running || transitioning) && (
|
||||
<Ctx.Item className="menu-item rg-p-menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onVMContextAction(vmRefKey(vm), 'forceStop')}>
|
||||
<HostIcon name="force-stop"><Power size={14} /></HostIcon> {tr('forceStop')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'settings')}>
|
||||
<HostIcon name="settings"><Settings size={14} /></HostIcon> {tr('settingsEllipsis')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openSharedFolder')}>
|
||||
<HostIcon name="folder"><FolderOpen size={14} /></HostIcon> {tr('openSharedFolder')}
|
||||
</Ctx.Item>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'cloneVM')}>
|
||||
<HostIcon name="clone"><CopyPlus size={14} /></HostIcon> {tr('cloneVM')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openFolder')}>
|
||||
<HostIcon name="folder"><FolderOpen size={14} /></HostIcon> {tr('openFolder')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item rg-p-menu-item danger" disabled={vmBusy || running || suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'delete')}>
|
||||
<HostIcon name="delete"><Trash size={14} /></HostIcon> {tr('delete')}
|
||||
</Ctx.Item>
|
||||
</Ctx.Content>
|
||||
</Ctx.Portal>
|
||||
</Ctx.Root>
|
||||
)
|
||||
})}
|
||||
<div className="sidebar-sep" role="presentation" />
|
||||
{item(
|
||||
</div>
|
||||
<div className="nav-group rg-p-nav-group nav-system" role="group" aria-label={tr('sidebarSystem')}>
|
||||
{navBtn(
|
||||
INSTALLERS_ID,
|
||||
t(locale, 'sidebarInstallers'),
|
||||
tr('sidebarInstallers'),
|
||||
<Download size={13} />,
|
||||
'nav-icon-installers',
|
||||
downloading ? t(locale, 'state_starting') : '',
|
||||
downloading ? tr('installersDownloading') : '',
|
||||
downloading ? 'busy' : null,
|
||||
)}
|
||||
{item(
|
||||
{navBtn(
|
||||
PLUGINS_ID,
|
||||
tr('sidebarPlugins'),
|
||||
<HostIcon name="plugin"><Puzzle size={13} /></HostIcon>,
|
||||
'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'),
|
||||
<HostIcon name="settings"><Settings size={13} /></HostIcon>,
|
||||
'nav-icon-settings',
|
||||
'',
|
||||
null,
|
||||
)}
|
||||
{navBtn(
|
||||
ABOUT_ID,
|
||||
tr('settingsAbout'),
|
||||
<HostIcon name="info"><Info size={13} /></HostIcon>,
|
||||
'nav-icon-about',
|
||||
'',
|
||||
null,
|
||||
undefined,
|
||||
updateDot,
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rg-slot-anchor" data-rg-slot="sidebar.footer" />
|
||||
</aside>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import { Check, PanelLeft } from 'lucide-react'
|
||||
import React, { useRef, useState } from 'react'
|
||||
import { I18nKey, localeDir, t } from '../i18n'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
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'
|
||||
|
||||
const MENU_IDS = ['vm', 'view', 'help'] as const
|
||||
type MenuId = (typeof MENU_IDS)[number]
|
||||
|
||||
const HOVER_CLICK_GUARD_MS = 300
|
||||
|
||||
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; driver_id?: string; state: string; busy: boolean; graphics?: string; canSuspend: 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 [menuState, setMenuState] = useState<{ id: MenuId | null; switched: boolean }>({ id: null, switched: false })
|
||||
const openRef = useRef<MenuId | null>(null)
|
||||
const navRef = useRef<HTMLElement>(null)
|
||||
const hoverOpenedRef = useRef<{ id: MenuId; at: number } | null>(null)
|
||||
const openedByPointerRef = useRef(false)
|
||||
const pointerClosedRef = useRef(false)
|
||||
|
||||
const setActiveMenu = (next: MenuId | null, switched: boolean) => {
|
||||
openRef.current = next
|
||||
setMenuState({ id: next, switched })
|
||||
}
|
||||
|
||||
const running = vm?.state === 'running'
|
||||
const stopped = vm?.state === 'stopped'
|
||||
const suspended = vm?.state === 'suspended'
|
||||
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming'
|
||||
const vmBusy = !vm || vm.busy
|
||||
const canFullscreen = running && vm?.graphics !== 'vmware-svga'
|
||||
const stats = useVMStats(vm?.driver_id ?? '', canFullscreen && vm ? vm.name : null, running)
|
||||
const fullscreenLabel = !canFullscreen || !stats?.running
|
||||
? tr('toggleFullscreen')
|
||||
: stats.window_fullscreen
|
||||
? tr('exitFullscreen')
|
||||
: tr('enterFullscreen')
|
||||
|
||||
const item = (label: string, onSelect: () => void, opts: { shortcut?: string; disabled?: boolean; danger?: boolean } = {}) => (
|
||||
<Menu.Item className={`menu-item rg-p-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 rg-p-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: MenuId, label: string, content: React.ReactNode, indented = false) => (
|
||||
<Menu.Root
|
||||
dir={localeDir(locale)}
|
||||
modal={false}
|
||||
open={menuState.id === id}
|
||||
onOpenChange={(o) => {
|
||||
if (o) {
|
||||
hoverOpenedRef.current = null
|
||||
pointerClosedRef.current = false
|
||||
setActiveMenu(id, openRef.current !== null && openRef.current !== id)
|
||||
} else if (openRef.current === id) {
|
||||
hoverOpenedRef.current = null
|
||||
setActiveMenu(null, false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Menu.Trigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="titlebar-menu"
|
||||
onPointerEnter={(e) => {
|
||||
if (e.pointerType !== 'mouse') return
|
||||
if (openRef.current && openRef.current !== id) {
|
||||
openedByPointerRef.current = true
|
||||
pointerClosedRef.current = false
|
||||
hoverOpenedRef.current = { id, at: performance.now() }
|
||||
setActiveMenu(id, true)
|
||||
}
|
||||
}}
|
||||
onPointerDown={(e) => {
|
||||
if (e.button === 0 && !e.ctrlKey) {
|
||||
openedByPointerRef.current = true
|
||||
}
|
||||
const h = hoverOpenedRef.current
|
||||
if (
|
||||
e.pointerType === 'mouse'
|
||||
&& e.button === 0
|
||||
&& !e.ctrlKey
|
||||
&& openRef.current === id
|
||||
&& h
|
||||
&& h.id === id
|
||||
&& performance.now() - h.at < HOVER_CLICK_GUARD_MS
|
||||
) {
|
||||
hoverOpenedRef.current = null
|
||||
e.preventDefault()
|
||||
}
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown') {
|
||||
openedByPointerRef.current = false
|
||||
}
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
</Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Content
|
||||
className={`menu rg-p-menu titlebar-menu-content${indented ? ' menu-indented' : ''}`}
|
||||
data-menubar-switch={menuState.switched ? 'true' : undefined}
|
||||
align="start"
|
||||
sideOffset={4}
|
||||
collisionPadding={8}
|
||||
onPointerDownCapture={(e) => {
|
||||
if (!(e.target as HTMLElement | null)?.closest('[data-disabled]')) {
|
||||
pointerClosedRef.current = true
|
||||
}
|
||||
}}
|
||||
onKeyDownCapture={() => {
|
||||
pointerClosedRef.current = false
|
||||
}}
|
||||
onPointerDownOutside={(e) => {
|
||||
const orig = e.detail.originalEvent
|
||||
const target = e.target instanceof Element ? e.target : (e.target as Node | null)?.parentElement ?? null
|
||||
const trigger = target?.closest('button.titlebar-menu') ?? null
|
||||
if (orig.button === 0 && !orig.ctrlKey && trigger && navRef.current?.contains(trigger)) {
|
||||
e.preventDefault()
|
||||
return
|
||||
}
|
||||
pointerClosedRef.current = true
|
||||
}}
|
||||
onCloseAutoFocus={(e) => {
|
||||
// Prevent Radix's deferred setTimeout(0) focus restoration from pulling focus
|
||||
// back to the old trigger when switching to a sibling menu (which triggers
|
||||
// onFocusOutside on the newly opened menu), when closed via pointer, or when
|
||||
// an item opens a modal dialog.
|
||||
if (
|
||||
openRef.current !== null
|
||||
|| openedByPointerRef.current
|
||||
|| pointerClosedRef.current
|
||||
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
|
||||
) {
|
||||
e.preventDefault()
|
||||
}
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return
|
||||
e.preventDefault()
|
||||
const isRTL = navRef.current ? getComputedStyle(navRef.current).direction === 'rtl' : false
|
||||
const delta = (e.key === 'ArrowRight') !== isRTL ? 1 : -1
|
||||
const idx = MENU_IDS.indexOf(id)
|
||||
const nextId = MENU_IDS[(idx + delta + MENU_IDS.length) % MENU_IDS.length]
|
||||
hoverOpenedRef.current = null
|
||||
openedByPointerRef.current = false
|
||||
pointerClosedRef.current = false
|
||||
setActiveMenu(nextId, true)
|
||||
}}
|
||||
>
|
||||
{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" disabled={menuState.id !== null}>
|
||||
<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 ref={navRef} 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 })
|
||||
: suspended
|
||||
? item(tr('resume'), () => onVMAction('resume'), { shortcut: vm?.canSuspend ? 'Ctrl+Enter' : undefined, disabled: vmBusy || !vm?.canSuspend })
|
||||
: item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })}
|
||||
{suspended && !vm?.canSuspend && <Menu.Label className="menu-group-label">{tr('resumeUnavailable')}</Menu.Label>}
|
||||
{item(fullscreenLabel, () => onVMAction('fullscreen'), { disabled: vmBusy || !canFullscreen })}
|
||||
{item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })}
|
||||
{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 || suspended || transitioning })}
|
||||
{item(tr('openFolder'), () => onVMAction('openFolder'), { disabled: !vm })}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
{suspended && item(tr('discardSuspend'), () => onVMAction('discardSuspend'), { danger: true, disabled: vmBusy })}
|
||||
{item(tr('forceStop'), () => onVMAction('forceStop'), { danger: true, disabled: !vm || !(running || transitioning) })}
|
||||
{item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || suspended || 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 rg-p-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,143 @@
|
||||
import React, { useEffect, useId, useRef } from 'react'
|
||||
|
||||
// Strokes of the Reims-Go wordmark (scripts/brand/wordmark.py), in pen order.
|
||||
// Coordinates sit in the generator's baseline frame (translate 4 107).
|
||||
type Stroke =
|
||||
| { kind: 'path'; d: string; ink: 'ink' | 'dash' | 'brand' }
|
||||
| { kind: 'dot'; cx: number; cy: number; r: number }
|
||||
|
||||
const STROKES: Stroke[] = [
|
||||
{ kind: 'path', ink: 'ink', d: 'M7.5 -7.5V-36A24 28.5 0 0 1 31.5 -64.5' },
|
||||
{ kind: 'path', ink: 'ink', d: 'M50.5 -36H107.5A28.5 28.5 0 1 0 100.18 -16.93' },
|
||||
{ kind: 'path', ink: 'ink', d: 'M133.5 -64.5V-7.5' },
|
||||
{ kind: 'dot', cx: 133.5, cy: -94, r: 9 },
|
||||
{ kind: 'path', ink: 'ink', d: 'M159.5 -7.5V-36A22 28.5 0 0 1 203.5 -36V-7.5M203.5 -36A22 28.5 0 0 1 247.5 -36V-7.5' },
|
||||
{ kind: 'path', ink: 'ink', d: 'M311.05 -59.02A21 14.25 0 0 0 273.5 -50.25A21 14.25 0 0 0 294.5 -36A21 14.25 0 0 1 315.5 -21.75A21 14.25 0 0 1 277.95 -12.98' },
|
||||
{ kind: 'path', ink: 'dash', d: 'M340.5 -36H358.5' },
|
||||
{ kind: 'path', ink: 'brand', d: 'M440.5 -36A28.5 28.5 0 1 1 440.5 -36.01' },
|
||||
{ kind: 'path', ink: 'brand', d: 'M440.5 -64.5V0A28.5 22.5 0 0 1 387.32 11.25' },
|
||||
{ kind: 'path', ink: 'brand', d: 'M523.5 -36A28.5 28.5 0 1 1 523.5 -36.01' },
|
||||
]
|
||||
|
||||
// Pen timing, in ms. Writing speed is constant, so long strokes take longer.
|
||||
const PX_PER_MS = 0.62
|
||||
const LIFT_MS = 70 // pen lift between strokes
|
||||
const DOT_MS = 140
|
||||
const HOLD_MS = 900 // finished word stays on screen
|
||||
const FADE_MS = 420
|
||||
const REST_MS = 260
|
||||
|
||||
const STROKE_EASE = 'cubic-bezier(0.45, 0.05, 0.35, 1)'
|
||||
|
||||
interface Props {
|
||||
/** Rendered width in px; height follows the wordmark's aspect ratio. */
|
||||
width?: number
|
||||
label?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The Reims-Go wordmark written stroke by stroke, on a loop. Used while
|
||||
* waiting on network I/O. With reduced motion it shows the finished word
|
||||
* with a slow pulse instead.
|
||||
*/
|
||||
export const WordmarkLoader: React.FC<Props> = ({ width = 168, label, className }) => {
|
||||
const svgRef = useRef<SVGSVGElement>(null)
|
||||
const gid = `wm-${useId().replace(/[^a-zA-Z0-9_-]/g, '')}`
|
||||
|
||||
useEffect(() => {
|
||||
const svg = svgRef.current
|
||||
if (!svg || typeof svg.animate !== 'function') return
|
||||
if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return
|
||||
|
||||
const els = Array.from(svg.querySelectorAll<SVGGeometryElement>('[data-stroke]'))
|
||||
const spans = els.map((el) => {
|
||||
if (el.tagName.toLowerCase() === 'circle') return DOT_MS
|
||||
const len = typeof el.getTotalLength === 'function' ? el.getTotalLength() : 60
|
||||
return Math.max(90, len / PX_PER_MS)
|
||||
})
|
||||
const writeEnd = spans.reduce((sum, s) => sum + s, 0) + LIFT_MS * (spans.length - 1)
|
||||
const total = writeEnd + HOLD_MS + FADE_MS + REST_MS
|
||||
const at = (ms: number) => Math.min(1, ms / total)
|
||||
const holdEnd = at(writeEnd + HOLD_MS)
|
||||
const fadeEnd = at(writeEnd + HOLD_MS + FADE_MS)
|
||||
|
||||
let t = 0
|
||||
const anims = els.map((el, i) => {
|
||||
const s = at(t)
|
||||
const e = at(t + spans[i])
|
||||
t += spans[i] + LIFT_MS
|
||||
const isDot = el.tagName.toLowerCase() === 'circle'
|
||||
// Opacity hides the round cap that a fully-offset dash still paints.
|
||||
const frames: Keyframe[] = isDot
|
||||
? [
|
||||
{ offset: 0, opacity: 0, transform: 'scale(0.2)' },
|
||||
{ offset: s, opacity: 0, transform: 'scale(0.2)', easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)' },
|
||||
{ offset: e, opacity: 1, transform: 'scale(1)' },
|
||||
{ offset: holdEnd, opacity: 1, transform: 'scale(1)' },
|
||||
{ offset: fadeEnd, opacity: 0, transform: 'scale(1)' },
|
||||
{ offset: 1, opacity: 0, transform: 'scale(0.2)' },
|
||||
]
|
||||
: [
|
||||
{ offset: 0, opacity: 0, strokeDashoffset: 1 },
|
||||
{ offset: s, opacity: 0, strokeDashoffset: 1 },
|
||||
{ offset: Math.min(e, s + 0.0005), opacity: 1, strokeDashoffset: 1, easing: STROKE_EASE },
|
||||
{ offset: e, opacity: 1, strokeDashoffset: 0 },
|
||||
{ offset: holdEnd, opacity: 1, strokeDashoffset: 0 },
|
||||
{ offset: fadeEnd, opacity: 0, strokeDashoffset: 0 },
|
||||
{ offset: 1, opacity: 0, strokeDashoffset: 1 },
|
||||
]
|
||||
return el.animate(frames, { duration: total, iterations: Infinity, fill: 'both' })
|
||||
})
|
||||
svg.dataset.animated = 'true'
|
||||
return () => {
|
||||
anims.forEach((a) => a.cancel())
|
||||
delete svg.dataset.animated
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className={`wordmark-loader${className ? ` ${className}` : ''}`} role="status" aria-live="polite">
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="wordmark-loader-svg"
|
||||
viewBox="0 0 539 141"
|
||||
width={width}
|
||||
height={Math.round((width * 141) / 539)}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id={gid} gradientUnits="userSpaceOnUse" x1="376" y1="0" x2="531" y2="0">
|
||||
<stop offset="0" stopColor="#3b8cff" />
|
||||
<stop offset="0.5" stopColor="#6d5dfc" />
|
||||
<stop offset="1" stopColor="#ff7a9a" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<g transform="translate(4 107)" fill="none" strokeWidth="15" strokeLinecap="round" strokeLinejoin="round">
|
||||
{STROKES.map((s, i) => s.kind === 'dot' ? (
|
||||
<circle
|
||||
key={i}
|
||||
data-stroke=""
|
||||
className="wordmark-loader-dot"
|
||||
cx={s.cx}
|
||||
cy={s.cy}
|
||||
r={s.r}
|
||||
style={{ transformOrigin: 'center', transformBox: 'fill-box' }}
|
||||
/>
|
||||
) : (
|
||||
<path
|
||||
key={i}
|
||||
data-stroke=""
|
||||
className={`wordmark-loader-${s.ink}`}
|
||||
d={s.d}
|
||||
pathLength={1}
|
||||
strokeDasharray="1 1"
|
||||
stroke={s.ink === 'brand' ? `url(#${gid})` : undefined}
|
||||
/>
|
||||
))}
|
||||
</g>
|
||||
</svg>
|
||||
{label && <span className="wordmark-loader-label">{label}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
|
||||
export const coreZh: Record<string, string> = {
|
||||
"affinityMenu": "处理器相关性…",
|
||||
"appearance": "外观",
|
||||
"backToEdit": "返回修改",
|
||||
"borderless": "无边框全屏",
|
||||
"cancel": "取消",
|
||||
"cancelCreate": "取消创建",
|
||||
"cancelQueue": "取消排队",
|
||||
"clear": "清空",
|
||||
"close": "关闭",
|
||||
"closeWindow": "关闭",
|
||||
"collapseLogs": "收起日志",
|
||||
"copy": "复制",
|
||||
"copyTechInfo": "复制技术信息",
|
||||
"dataRootChooseOther": "选择其他数据目录",
|
||||
"dataRootChooseTitle": "选择数据目录",
|
||||
"dataRootReadOnlyDetail": "详细信息",
|
||||
"dataRootReadOnlyFolder": "数据目录",
|
||||
"dataRootReadOnlyTitle": "数据目录暂时无法使用",
|
||||
"dataRootRepair": "修复版本记录",
|
||||
"dataRootRetry": "重试",
|
||||
"delete": "删除…",
|
||||
"deleteEllipsis": "删除…",
|
||||
"displays": "显示器数量",
|
||||
"eject": "弹出安装盘",
|
||||
"emptyVMs": "还没有虚拟机",
|
||||
"errCopyDetails": "复制排障信息",
|
||||
"errRawDetailsToggle": "技术详情",
|
||||
"errorBoundaryReload": "重新加载界面",
|
||||
"errorBoundaryTitle": "界面遇到意外错误",
|
||||
"expandLogs": "展开日志",
|
||||
"failCreate": "{name} 创建失败",
|
||||
"failDownload": "下载失败",
|
||||
"failGeneric": "操作失败",
|
||||
"failRuntime": "运行时安装失败",
|
||||
"failSSH": "SSH 操作失败",
|
||||
"fontMissingFoDHint": "当前 Windows 缺少 {script} 可选字体包,部分原生弹窗字形可能回退;可在「Windows 设置 › 应用 › 可选功能」添加对应补充字体。",
|
||||
"footerDiskLabel": "磁盘",
|
||||
"footerDiskTip": "虚拟机数据目录:{dir}",
|
||||
"footerDiskValue": "可用 {gb} GB",
|
||||
"footerHostIssue": "虚拟化未就绪",
|
||||
"footerHostIssueTip": "打开「内核」页查看需要处理的项",
|
||||
"footerMemLabel": "内存",
|
||||
"footerMemTip": "系统内存:已用 {used} GB / 共 {total} GB(可用 {avail} GB)",
|
||||
"footerMemValue": "{used} / {total} GB",
|
||||
"footerRunningVMs": "{n, plural, other {# 台运行中}}",
|
||||
"forceStop": "硬关机",
|
||||
"gpuErrMissingExt": "缺少必需 Vulkan 扩展({ext}),请更新显卡驱动或改用 VMware SVGA",
|
||||
"gpuErrVulkanCpu": "软件 Vulkan 实现不满足 vGPU 加速要求,请改用 VMware SVGA",
|
||||
"gpuErrVulkanTooOld": "Vulkan {ver} 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA",
|
||||
"gpuWarnAmdLegacy": "AMD Vega/Polaris 在 Windows 闭源驱动下存在上游已知黑屏/设备丢失问题({ref});若有其他独显请改选独显,否则建议暂用 VMware SVGA",
|
||||
"gpuWarnAmdRdna2": "该 AMD 显卡在 Windows 下存在上游已知设备丢失风险({ref});若卡死黑屏请升级驱动或暂用 VMware SVGA",
|
||||
"guestKbdPinyin": "拼音键盘",
|
||||
"guestKbdUS": "美式键盘",
|
||||
"guestKbdUSRecommended": "美式键盘,推荐",
|
||||
"guestLang": "macOS 系统语言",
|
||||
"guestLangEnUS": "English (US)",
|
||||
"guestLangJaJP": "日本語",
|
||||
"guestLangKoKR": "한국어",
|
||||
"guestLangZhHansUS": "简体中文",
|
||||
"guestLangZhHantUS": "繁體中文",
|
||||
"helpAbout": "关于 Reims-Go",
|
||||
"helpCheckUpdate": "检查更新…",
|
||||
"helpProjectPage": "项目主页",
|
||||
"helpReportIssue": "报告问题",
|
||||
"hideSidebar": "隐藏侧边栏",
|
||||
"hidpiTipFullscreen": "窗口里的 macOS 只能 1x,文字会发虚;改用全屏可得到 HiDPI",
|
||||
"hidpiTipScale": "这块屏幕上 macOS 只能 1x,文字会发虚;把 Windows 缩放调到 150% 或以上可得到 HiDPI",
|
||||
"hidpiTipUnavailable": "这块屏幕像素不够,macOS 只能以 1x 显示",
|
||||
"hostDisplayHint": "主屏 {w}×{h},{scale}% 缩放",
|
||||
"hostNeedsAction": "需要处理",
|
||||
"hostReady": "就绪",
|
||||
"importRuntime": "导入运行时包",
|
||||
"installersDownloading": "下载中",
|
||||
"installersQueuedDesc": "等待当前下载完成",
|
||||
"installersRetry": "重试",
|
||||
"jumpLatest": "跳到最新",
|
||||
"localeAuto": "跟随系统",
|
||||
"localeAutoDetail": "当前:{tag}",
|
||||
"logActivity": "活动",
|
||||
"logButton": "日志",
|
||||
"logCopy": "复制日志",
|
||||
"logErrorsOnly": "仅错误/警告",
|
||||
"logQemu": "QEMU",
|
||||
"logSearchPlaceholder": "筛选日志…",
|
||||
"logSerial": "串口",
|
||||
"logsEmpty": "暂无日志",
|
||||
"macos.appsUtilitiesTerminal": "应用程序 › 实用工具 › 终端",
|
||||
"macos.diskUtility": "磁盘工具",
|
||||
"macos.erase": "抹掉",
|
||||
"macos.finder": "访达",
|
||||
"macos.guidPartitionMap": "GUID 分区图",
|
||||
"macos.otherSignInSetUpLater": "其他登录选项 › 稍后设置",
|
||||
"macos.recovery": "恢复",
|
||||
"macos.reinstallMacOS": "重新安装 macOS",
|
||||
"macos.setupAssistant": "设置助理",
|
||||
"macos.showAllDevices": "显示 › 显示所有设备",
|
||||
"macos.utilitiesTerminal": "实用工具 › 终端",
|
||||
"macos.volume": "宗卷",
|
||||
"maximize": "最大化",
|
||||
"menuBar": "菜单栏",
|
||||
"menuHelp": "帮助",
|
||||
"menuVM": "虚拟机",
|
||||
"menuView": "视图",
|
||||
"minimize": "最小化",
|
||||
"more": "更多",
|
||||
"newVM": "新建虚拟机",
|
||||
"newVMEllipsis": "新建虚拟机…",
|
||||
"noRuntimeAlert": "先在「内核」导入运行时包",
|
||||
"off": "关闭",
|
||||
"on": "开启",
|
||||
"openFolder": "打开所在文件夹",
|
||||
"panelLoadFailed": "面板加载失败",
|
||||
"pauseDownload": "暂停下载",
|
||||
"pluginSafeModeShort": "安全模式",
|
||||
"quitFailed": "已取消退出",
|
||||
"quitInProgress": "正在退出…",
|
||||
"refresh": "刷新",
|
||||
"resLooksLike": "看起来像 {w} × {h}",
|
||||
"resizeLogPanel": "拖动调整日志高度",
|
||||
"resolution": "分辨率",
|
||||
"restart": "重启",
|
||||
"safeModeBanner": "安全模式已启用:已跳过全部第三方插件并回退至内置默认主题",
|
||||
"safeModeManagePlugins": "管理插件",
|
||||
"save": "保存",
|
||||
"settings": "设置",
|
||||
"settingsAbout": "关于",
|
||||
"settingsEllipsis": "设置…",
|
||||
"shortcutBarFullscreen": "切换全屏",
|
||||
"shortcutBarRelease": "释放键盘和鼠标",
|
||||
"showSidebar": "显示侧边栏",
|
||||
"shutdownMode": "关机方式",
|
||||
"sidebarHost": "内核",
|
||||
"sidebarInstallers": "镜像",
|
||||
"sidebarItemAria": "{label},{state}",
|
||||
"sidebarLabel": "侧边栏",
|
||||
"sidebarPlugins": "插件",
|
||||
"sidebarSettings": "设置",
|
||||
"sidebarSystem": "系统",
|
||||
"sidebarVMs": "虚拟机",
|
||||
"start": "启动",
|
||||
"starting": "启动中",
|
||||
"stop": "关机",
|
||||
"taskAppUpdate": "下载 Reims-Go {v}",
|
||||
"taskCreate": "创建 {name}",
|
||||
"taskDownload": "下载 macOS {v}",
|
||||
"taskRecoveryDownload": "正在为 {name} 拉取并挂载在线恢复镜像",
|
||||
"taskRuntime": "安装运行时 {v}",
|
||||
"tasksRunning": "{n, plural, other {# 个任务进行中}}",
|
||||
"themeDark": "深色",
|
||||
"themeLight": "浅色",
|
||||
"themeSwitchDark": "切换深色外观",
|
||||
"themeSwitchLight": "切换浅色外观",
|
||||
"themeSystem": "跟随系统",
|
||||
"toastAffinityApplied": "处理器相关性已应用({count} 个逻辑处理器 · {mask})",
|
||||
"toastAffinitySaved": "处理器相关性已保存,下次启动时生效",
|
||||
"toastBorderlessNextStart": "已保存全屏启动偏好,重启虚拟机后生效",
|
||||
"toastBorderlessUpdated": "已保存全屏启动偏好",
|
||||
"toastCopied": "已复制",
|
||||
"toastCreateCanceled": "已取消创建 {name}",
|
||||
"toastCreateCanceledPartial": "已下载部分已保留,可继续下载或返回修改",
|
||||
"toastCreated": "{name} 已创建",
|
||||
"toastDownloadPaused": "已暂停,再次下载会从中断处继续",
|
||||
"toastInstallerReady": "macOS {v} 安装包已就绪",
|
||||
"toastQueueCanceled": "已取消排队",
|
||||
"toastRuntimeReady": "运行时 {v} 已安装",
|
||||
"toastSSHConfigWritten": "已写入 Host {alias}",
|
||||
"toastSSHUserSaved": "已保存 SSH 用户名",
|
||||
"toastSaved": "已保存",
|
||||
"toastSavedNextStart": "已保存,下次启动生效",
|
||||
"updateCancel": "取消下载",
|
||||
"updateCapsuleAvailable": "{v} 可用",
|
||||
"updateCapsuleDownloading": "正在下载更新",
|
||||
"updateCapsuleDownloadingPct": "正在下载 {p}%",
|
||||
"updateCapsuleFailed": "更新下载失败",
|
||||
"updateCapsuleOpen": "查看更新详情",
|
||||
"updateCapsuleReady": "{v} 已就绪",
|
||||
"updateConfirmBody": "{n, plural, other {有 # 台虚拟机正在运行。它们不会被关闭,但 Reims-Go 重启的几秒内,剪贴板、共享文件夹和输入法桥接会暂停,之后自动恢复。}}",
|
||||
"updateConfirmTitle": "重启并安装 {v}",
|
||||
"updateConfirmWin10": "这台 Windows 10 宿主依赖冷重启补偿:这些虚拟机里的 macOS 下次重启后不会自动开机,需要手动启动一次。",
|
||||
"updateDoneToast": "已更新到 {v}",
|
||||
"updateDownload": "下载",
|
||||
"updateFailed": "更新失败",
|
||||
"updateLater": "以后再提醒我",
|
||||
"updateRestart": "重启并安装",
|
||||
"updateRetry": "重试",
|
||||
"uptimeHoursMinutes": "{h} 小时 {m} 分",
|
||||
"uptimeMinutesSeconds": "{m} 分 {s} 秒",
|
||||
"uptimeSeconds": "{s} 秒",
|
||||
"viewLogs": "查看日志",
|
||||
}
|
||||
|
||||
export const coreEn: Record<string, string> = {
|
||||
"affinityMenu": "Processor Affinity…",
|
||||
"appearance": "Appearance",
|
||||
"backToEdit": "Edit and retry",
|
||||
"borderless": "Borderless full screen",
|
||||
"cancel": "Cancel",
|
||||
"cancelCreate": "Cancel creation",
|
||||
"cancelQueue": "Cancel queued download",
|
||||
"clear": "Clear",
|
||||
"close": "Close",
|
||||
"closeWindow": "Close",
|
||||
"collapseLogs": "Hide logs",
|
||||
"copy": "Copy",
|
||||
"copyTechInfo": "Copy technical details",
|
||||
"dataRootChooseOther": "Choose another data folder",
|
||||
"dataRootChooseTitle": "Choose data folder",
|
||||
"dataRootReadOnlyDetail": "Details",
|
||||
"dataRootReadOnlyFolder": "Data folder",
|
||||
"dataRootReadOnlyTitle": "This data folder can’t be used right now",
|
||||
"dataRootRepair": "Repair version record",
|
||||
"dataRootRetry": "Try again",
|
||||
"delete": "Delete…",
|
||||
"deleteEllipsis": "Delete…",
|
||||
"displays": "Displays",
|
||||
"eject": "Eject installer",
|
||||
"emptyVMs": "No virtual machines",
|
||||
"errCopyDetails": "Copy diagnostic details",
|
||||
"errRawDetailsToggle": "Technical details",
|
||||
"errorBoundaryReload": "Reload window",
|
||||
"errorBoundaryTitle": "Something went wrong in the window",
|
||||
"expandLogs": "Show logs",
|
||||
"failCreate": "Couldn’t create {name}",
|
||||
"failDownload": "Download failed",
|
||||
"failGeneric": "Something went wrong",
|
||||
"failRuntime": "Runtime install failed",
|
||||
"failSSH": "SSH action failed",
|
||||
"fontMissingFoDHint": "Windows optional {script} fonts are not installed; native overlay text may use fallback glyphs. Install them under Windows Settings › Apps › Optional features.",
|
||||
"footerDiskLabel": "Disk",
|
||||
"footerDiskTip": "VM data folder: {dir}",
|
||||
"footerDiskValue": "{gb} GB free",
|
||||
"footerHostIssue": "Virtualization not ready",
|
||||
"footerHostIssueTip": "Open the Engine page to see what needs attention",
|
||||
"footerMemLabel": "Memory",
|
||||
"footerMemTip": "System memory: {used} GB used / {total} GB total ({avail} GB free)",
|
||||
"footerMemValue": "{used} / {total} GB",
|
||||
"footerRunningVMs": "{n, plural, one {# running} other {# running}}",
|
||||
"forceStop": "Force shut down",
|
||||
"gpuErrMissingExt": "Missing required Vulkan extensions ({ext}); update GPU drivers or use VMware SVGA",
|
||||
"gpuErrVulkanCpu": "Software Vulkan implementation cannot accelerate vGPU; use VMware SVGA",
|
||||
"gpuErrVulkanTooOld": "Vulkan {ver} is below the required 1.3 floor; update GPU drivers or use VMware SVGA",
|
||||
"gpuWarnAmdLegacy": "AMD Vega/Polaris on Windows hits known upstream black-screen/device-loss issues ({ref}); prefer another discrete GPU or use VMware SVGA for now",
|
||||
"gpuWarnAmdRdna2": "This AMD GPU hits known Windows device-loss issues upstream ({ref}); update drivers or use VMware SVGA if it freezes",
|
||||
"guestKbdPinyin": "Pinyin",
|
||||
"guestKbdUS": "US Keyboard",
|
||||
"guestKbdUSRecommended": "US Keyboard, recommended",
|
||||
"guestLang": "macOS system language",
|
||||
"guestLangEnUS": "English (US)",
|
||||
"guestLangJaJP": "Japanese",
|
||||
"guestLangKoKR": "Korean",
|
||||
"guestLangZhHansUS": "Simplified Chinese",
|
||||
"guestLangZhHantUS": "Traditional Chinese",
|
||||
"helpAbout": "About Reims-Go",
|
||||
"helpCheckUpdate": "Check for Updates…",
|
||||
"helpProjectPage": "Project Page",
|
||||
"helpReportIssue": "Report an Issue",
|
||||
"hideSidebar": "Hide sidebar",
|
||||
"hidpiTipFullscreen": "In a window macOS runs at 1x with rough text; full screen gives HiDPI",
|
||||
"hidpiTipScale": "macOS runs at 1x on this screen, with rough text; Windows scaling at 150% or more gives HiDPI",
|
||||
"hidpiTipUnavailable": "This screen has too few pixels; macOS runs at 1x",
|
||||
"hostDisplayHint": "Main display {w}×{h} at {scale}%",
|
||||
"hostNeedsAction": "Needs attention",
|
||||
"hostReady": "Ready",
|
||||
"importRuntime": "Import runtime",
|
||||
"installersDownloading": "Downloading",
|
||||
"installersQueuedDesc": "Waiting for current download to finish",
|
||||
"installersRetry": "Retry",
|
||||
"jumpLatest": "Jump to latest",
|
||||
"localeAuto": "System Default",
|
||||
"localeAutoDetail": "Current: {tag}",
|
||||
"logActivity": "Activity",
|
||||
"logButton": "Logs",
|
||||
"logCopy": "Copy logs",
|
||||
"logErrorsOnly": "Errors \u0026 warnings",
|
||||
"logQemu": "QEMU",
|
||||
"logSearchPlaceholder": "Filter logs…",
|
||||
"logSerial": "Serial",
|
||||
"logsEmpty": "No logs yet",
|
||||
"macos.appsUtilitiesTerminal": "Applications › Utilities › Terminal",
|
||||
"macos.diskUtility": "Disk Utility",
|
||||
"macos.erase": "Erase",
|
||||
"macos.finder": "Finder",
|
||||
"macos.guidPartitionMap": "GUID Partition Map",
|
||||
"macos.otherSignInSetUpLater": "Other Sign-In Options › Set Up Later",
|
||||
"macos.recovery": "Recovery",
|
||||
"macos.reinstallMacOS": "Reinstall macOS",
|
||||
"macos.setupAssistant": "Setup Assistant",
|
||||
"macos.showAllDevices": "View › Show All Devices",
|
||||
"macos.utilitiesTerminal": "Utilities › Terminal",
|
||||
"macos.volume": "Volume",
|
||||
"maximize": "Maximize",
|
||||
"menuBar": "Menu bar",
|
||||
"menuHelp": "Help",
|
||||
"menuVM": "VM",
|
||||
"menuView": "View",
|
||||
"minimize": "Minimize",
|
||||
"more": "More",
|
||||
"newVM": "New virtual machine",
|
||||
"newVMEllipsis": "New Virtual Machine…",
|
||||
"noRuntimeAlert": "Import a runtime under Engine first",
|
||||
"off": "Off",
|
||||
"on": "On",
|
||||
"openFolder": "Show in folder",
|
||||
"panelLoadFailed": "Panel failed to load",
|
||||
"pauseDownload": "Pause download",
|
||||
"pluginSafeModeShort": "Safe mode",
|
||||
"quitFailed": "Quit canceled",
|
||||
"quitInProgress": "Quitting…",
|
||||
"refresh": "Refresh",
|
||||
"resLooksLike": "Looks like {w} × {h}",
|
||||
"resizeLogPanel": "Drag to resize log panel",
|
||||
"resolution": "Resolution",
|
||||
"restart": "Restart",
|
||||
"safeModeBanner": "Safe mode is active: all third-party plugins are disabled and the built-in theme is restored",
|
||||
"safeModeManagePlugins": "Manage plugins",
|
||||
"save": "Save",
|
||||
"settings": "Settings",
|
||||
"settingsAbout": "About",
|
||||
"settingsEllipsis": "Settings…",
|
||||
"shortcutBarFullscreen": "Toggle full screen",
|
||||
"shortcutBarRelease": "Release keyboard and mouse",
|
||||
"showSidebar": "Show sidebar",
|
||||
"shutdownMode": "Shutdown mode",
|
||||
"sidebarHost": "Engine",
|
||||
"sidebarInstallers": "Images",
|
||||
"sidebarItemAria": "{label}, {state}",
|
||||
"sidebarLabel": "Sidebar",
|
||||
"sidebarPlugins": "Plugins",
|
||||
"sidebarSettings": "Settings",
|
||||
"sidebarSystem": "System",
|
||||
"sidebarVMs": "Virtual machines",
|
||||
"start": "Start",
|
||||
"starting": "Starting",
|
||||
"stop": "Shut down",
|
||||
"taskAppUpdate": "Downloading Reims-Go {v}",
|
||||
"taskCreate": "Creating {name}",
|
||||
"taskDownload": "Downloading macOS {v}",
|
||||
"taskRecoveryDownload": "Downloading online recovery for {name}",
|
||||
"taskRuntime": "Installing runtime {v}",
|
||||
"tasksRunning": "{n, plural, one {# task running} other {# tasks running}}",
|
||||
"themeDark": "Dark",
|
||||
"themeLight": "Light",
|
||||
"themeSwitchDark": "Switch to dark appearance",
|
||||
"themeSwitchLight": "Switch to light appearance",
|
||||
"themeSystem": "System",
|
||||
"toastAffinityApplied": "Processor affinity applied ({count} logical CPUs · {mask})",
|
||||
"toastAffinitySaved": "Processor affinity saved for next start",
|
||||
"toastBorderlessNextStart": "Fullscreen launch saved — applies on next restart",
|
||||
"toastBorderlessUpdated": "Fullscreen launch preference saved",
|
||||
"toastCopied": "Copied",
|
||||
"toastCreateCanceled": "Canceled creating {name}",
|
||||
"toastCreateCanceledPartial": "Downloaded progress is kept; resume anytime or edit and retry",
|
||||
"toastCreated": "{name} created",
|
||||
"toastDownloadPaused": "Paused — downloading again continues where it stopped",
|
||||
"toastInstallerReady": "macOS {v} installer ready",
|
||||
"toastQueueCanceled": "Removed from download queue",
|
||||
"toastRuntimeReady": "Runtime {v} installed",
|
||||
"toastSSHConfigWritten": "Wrote Host {alias}",
|
||||
"toastSSHUserSaved": "Saved SSH username",
|
||||
"toastSaved": "Saved",
|
||||
"toastSavedNextStart": "Saved — applies on next start",
|
||||
"updateCancel": "Cancel download",
|
||||
"updateCapsuleAvailable": "{v} available",
|
||||
"updateCapsuleDownloading": "Downloading update",
|
||||
"updateCapsuleDownloadingPct": "Downloading {p}%",
|
||||
"updateCapsuleFailed": "Update download failed",
|
||||
"updateCapsuleOpen": "Update details",
|
||||
"updateCapsuleReady": "{v} ready",
|
||||
"updateConfirmBody": "{n, plural, one {# VM is running. It will keep running, while clipboard, shared folders and the input bridge pause for a few seconds until Reims-Go is back.} other {# VMs are running. They will keep running, while clipboard, shared folders and the input bridge pause for a few seconds until Reims-Go is back.}}",
|
||||
"updateConfirmTitle": "Restart to install {v}",
|
||||
"updateConfirmWin10": "This Windows 10 host relies on the cold-reboot workaround: the next time macOS in these VMs restarts, start the VM again by hand.",
|
||||
"updateDoneToast": "Updated to {v}",
|
||||
"updateDownload": "Download",
|
||||
"updateFailed": "Update failed",
|
||||
"updateLater": "Remind me later",
|
||||
"updateRestart": "Restart to install",
|
||||
"updateRetry": "Retry",
|
||||
"uptimeHoursMinutes": "{h}h {m}m",
|
||||
"uptimeMinutesSeconds": "{m}m {s}s",
|
||||
"uptimeSeconds": "{s}s",
|
||||
"viewLogs": "View logs",
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
import { registerBuiltinDomain } from '../runtime'
|
||||
|
||||
export const pluginsZh: Record<string, string> = {
|
||||
"pluginAccentSeed": "强调种子色",
|
||||
"pluginActiveCount": "已启用 {active} / {total}",
|
||||
"pluginActiveTheme": "当前主题包",
|
||||
"pluginAlwaysOn": "核心组件,始终启用",
|
||||
"pluginApproveCheckbox": "我已核对来源与权限,确认启用此插件",
|
||||
"pluginApproveConfirm": "确认启用",
|
||||
"pluginApproveL3Warn": "此插件为原生可执行程序(L3 Sidecar),能够以当前 Windows 账户身份执行任意操作",
|
||||
"pluginApproveTitle": "高危权限确认",
|
||||
"pluginBuiltinSection": "内置插件",
|
||||
"pluginColorSchemes": "配色方案",
|
||||
"pluginColorSchemesHint": "修改种子色派生整套界面色阶",
|
||||
"pluginDeleteScheme": "删除方案",
|
||||
"pluginDisable": "停用",
|
||||
"pluginDisableInUseBody": "停用后,这个插件管理的虚拟机会显示为「驱动不可用」,不能启动或修改。虚拟机文件和挂起状态都会保留,重新启用即可恢复。运行中的虚拟机需要先停止或挂起。",
|
||||
"pluginDisableInUseTitle": "停用仍有虚拟机的插件",
|
||||
"pluginDone": "完成",
|
||||
"pluginEnableLater": "暂不启用",
|
||||
"pluginEnableNow": "启用",
|
||||
"pluginEnablePromptBody": "要现在启用吗?启用前请了解它会做什么:",
|
||||
"pluginEnablePromptNoRisk": "此插件没有声明额外能力,可以放心启用。",
|
||||
"pluginEnablePromptTitle": "「{name}」已安装",
|
||||
"pluginEntryPath": "入口路径",
|
||||
"pluginExternalSection": "已安装插件",
|
||||
"pluginFailDeleteScheme": "删除配色方案失败",
|
||||
"pluginFailEnable": "启用插件失败",
|
||||
"pluginFailImport": "导入插件包失败",
|
||||
"pluginFailLinkDev": "链接开发插件失败",
|
||||
"pluginFailLoad": "加载插件列表失败",
|
||||
"pluginFailLoadSettings": "读取插件设置失败",
|
||||
"pluginFailMarketInstall": "安装市场插件失败",
|
||||
"pluginFailMarketLoad": "加载插件市场失败",
|
||||
"pluginFailReadLog": "读取插件日志失败",
|
||||
"pluginFailRemove": "卸载插件失败",
|
||||
"pluginFailSaveScheme": "保存配色方案失败",
|
||||
"pluginFailSaveSettings": "保存插件设置失败",
|
||||
"pluginFailScan": "插件安全扫描失败",
|
||||
"pluginFailSwitchTheme": "切换主题失败",
|
||||
"pluginFailToggle": "切换插件状态失败",
|
||||
"pluginGlobalSettings": "插件全局设置",
|
||||
"pluginHighRiskNotice": "包含高危权限,启用前需确认",
|
||||
"pluginImportBtn": "导入插件",
|
||||
"pluginImportTitle": "导入本地插件包 (.zip)",
|
||||
"pluginInUse": "使用中不可卸载",
|
||||
"pluginLinkDevBtn": "链接插件开发目录",
|
||||
"pluginLinkDevTitle": "链接本地开发插件目录",
|
||||
"pluginLogEmpty": "暂无日志记录",
|
||||
"pluginLogTitle": "{id} — 日志",
|
||||
"pluginMarketDownloading": "下载中",
|
||||
"pluginMarketEmpty": "当前插件市场暂无可用条目,你仍可导入本地 .zip 插件包或配置自定义市场索引地址",
|
||||
"pluginMarketFeedEnd": "共 {count} 个插件",
|
||||
"pluginMarketIncompatible": "不兼容",
|
||||
"pluginMarketInstall": "安装",
|
||||
"pluginMarketInstalled": "已安装",
|
||||
"pluginMarketInstalling": "安装中",
|
||||
"pluginMarketKindAll": "全部",
|
||||
"pluginMarketKindDriver": "客体驱动",
|
||||
"pluginMarketKindLocale": "语言包",
|
||||
"pluginMarketKindRuntime": "运行时",
|
||||
"pluginMarketKindTemplate": "模板",
|
||||
"pluginMarketKindTheme": "主题",
|
||||
"pluginMarketKindTool": "工具",
|
||||
"pluginMarketLoading": "正在读取插件市场",
|
||||
"pluginMarketRefresh": "刷新索引",
|
||||
"pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签",
|
||||
"pluginMarketStaleBanner": "远程插件市场暂不可达,当前显示本地缓存或内置回退索引",
|
||||
"pluginMarketSyncing": "正在同步插件市场",
|
||||
"pluginMarketUpdate": "更新至 v{version}",
|
||||
"pluginMarketUpdateShort": "更新",
|
||||
"pluginMarketVersionTip": "已安装 v{installed},可更新至 v{version}",
|
||||
"pluginMarketWithdrawn": "已撤回",
|
||||
"pluginMarketWithdrawnInstalledWarn": "已安装插件 {id} 已从市场撤回:{reason}",
|
||||
"pluginMarketWithdrawnInstead": "建议改用:{target}",
|
||||
"pluginNewScheme": "新建配色方案",
|
||||
"pluginPanelsSection": "插件面板",
|
||||
"pluginPermCount": "{count, plural, other {# 项权限}}",
|
||||
"pluginPermissionsLabel": "权限:{list}",
|
||||
"pluginPublisherLicense": "发布者 / 许可",
|
||||
"pluginRemove": "卸载",
|
||||
"pluginRequestedPerms": "请求权限",
|
||||
"pluginRiskBackground": "该插件可以持久化运行后台代码",
|
||||
"pluginRiskClipboard": "该插件可以读写系统剪贴板",
|
||||
"pluginRiskFiles": "该插件会读写文件",
|
||||
"pluginRiskInput": "该插件会拦截或改写键盘与鼠标输入",
|
||||
"pluginRiskNative": "该插件包含原生程序,拥有您 Windows 账户的全部权限",
|
||||
"pluginRiskNetwork": "该插件会访问网络",
|
||||
"pluginRiskUi": "该插件会修改您看到的用户界面",
|
||||
"pluginRiskVm": "该插件可以控制虚拟机",
|
||||
"pluginScanAdvisoriesSection": "提示信息与可执行文件",
|
||||
"pluginScanArchiveTitle": "导入前安全检查",
|
||||
"pluginScanBlockedBtn": "已拦截,无法安装",
|
||||
"pluginScanCapabilitiesSection": "能力与权限说明",
|
||||
"pluginScanHardSection": "硬性拦截项(禁止安装)",
|
||||
"pluginScanInspect": "安全扫描",
|
||||
"pluginScanInstallConfirm": "确认导入安装",
|
||||
"pluginScanLoading": "正在扫描插件包…",
|
||||
"pluginScanModalTitle": "插件静态安全报告",
|
||||
"pluginScanMoreItems": "另有 {count} 项已折叠",
|
||||
"pluginSchemeDefault": "默认",
|
||||
"pluginSchemeModalTitle": "新建配色方案",
|
||||
"pluginSchemeName": "方案名称",
|
||||
"pluginSchemePlaceholder": "如:柔蓝",
|
||||
"pluginSearchEmpty": "没有匹配的插件",
|
||||
"pluginSearchPlaceholder": "筛选插件",
|
||||
"pluginSettings": "插件设置",
|
||||
"pluginStateDegraded": "已降级",
|
||||
"pluginStateFailed": "故障",
|
||||
"pluginStatePending": "等待依赖",
|
||||
"pluginSurfaceSeed": "画布种子色(可选)",
|
||||
"pluginTabInstalled": "已安装",
|
||||
"pluginTabMarket": "市场",
|
||||
"pluginThemeEmptyHint": "导入本地主题包(.zip)后可在此切换外观与配色方案",
|
||||
"pluginThemeHint": "同一时刻仅启用一个主题包,停用后自动回退默认主题",
|
||||
"pluginThemePackLabel": "主题包",
|
||||
"pluginThemeSafeModeHint": "安全模式下固定使用内置默认主题",
|
||||
"pluginThemeSection": "主题扩展",
|
||||
"pluginTrustCommunity": "社区",
|
||||
"pluginTrustDev": "开发",
|
||||
"pluginTrustOfficial": "官方",
|
||||
"pluginTrustVerified": "已审核",
|
||||
"pluginViewLog": "查看日志",
|
||||
}
|
||||
|
||||
export const pluginsEn: Record<string, string> = {
|
||||
"pluginAccentSeed": "Accent seed",
|
||||
"pluginActiveCount": "{active} / {total} active",
|
||||
"pluginActiveTheme": "Active theme pack",
|
||||
"pluginAlwaysOn": "Core component, always on",
|
||||
"pluginApproveCheckbox": "I have reviewed the source and permissions and confirm enabling this plugin",
|
||||
"pluginApproveConfirm": "Confirm enable",
|
||||
"pluginApproveL3Warn": "This plugin runs native code (L3 Sidecar) and can perform arbitrary actions as your Windows user",
|
||||
"pluginApproveTitle": "Approve high-risk permissions",
|
||||
"pluginBuiltinSection": "Built-in plugins",
|
||||
"pluginColorSchemes": "Color schemes",
|
||||
"pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp",
|
||||
"pluginDeleteScheme": "Delete scheme",
|
||||
"pluginDisable": "Disable",
|
||||
"pluginDisableInUseBody": "Its VMs will show as “Driver unavailable” and can’t be started or changed. Their files and any suspended state are kept; turning the plugin back on restores them. Stop or suspend any running VM first.",
|
||||
"pluginDisableInUseTitle": "Disable a plugin that still has VMs",
|
||||
"pluginDone": "Done",
|
||||
"pluginEnableLater": "Not now",
|
||||
"pluginEnableNow": "Enable",
|
||||
"pluginEnablePromptBody": "Enable it now? Here is what it can do:",
|
||||
"pluginEnablePromptNoRisk": "This plugin declares no extra capabilities.",
|
||||
"pluginEnablePromptTitle": "“{name}” is installed",
|
||||
"pluginEntryPath": "Entry path",
|
||||
"pluginExternalSection": "Installed plugins",
|
||||
"pluginFailDeleteScheme": "Couldn’t delete color scheme",
|
||||
"pluginFailEnable": "Couldn’t enable plugin",
|
||||
"pluginFailImport": "Couldn’t import plugin package",
|
||||
"pluginFailLinkDev": "Couldn’t link dev plugin",
|
||||
"pluginFailLoad": "Couldn’t load plugins",
|
||||
"pluginFailLoadSettings": "Couldn’t load plugin settings",
|
||||
"pluginFailMarketInstall": "Couldn’t install plugin from market",
|
||||
"pluginFailMarketLoad": "Couldn’t load plugin market",
|
||||
"pluginFailReadLog": "Couldn’t read plugin log",
|
||||
"pluginFailRemove": "Couldn’t remove plugin",
|
||||
"pluginFailSaveScheme": "Couldn’t save color scheme",
|
||||
"pluginFailSaveSettings": "Couldn’t save plugin settings",
|
||||
"pluginFailScan": "Couldn’t scan plugin",
|
||||
"pluginFailSwitchTheme": "Couldn’t switch theme",
|
||||
"pluginFailToggle": "Couldn’t toggle plugin",
|
||||
"pluginGlobalSettings": "Plugin settings",
|
||||
"pluginHighRiskNotice": "Contains high-risk permissions; approval required before enabling",
|
||||
"pluginImportBtn": "Import plugin",
|
||||
"pluginImportTitle": "Import plugin package (.zip)",
|
||||
"pluginInUse": "In use",
|
||||
"pluginLinkDevBtn": "Link plugin dev folder",
|
||||
"pluginLinkDevTitle": "Link local dev plugin folder",
|
||||
"pluginLogEmpty": "No log entries yet",
|
||||
"pluginLogTitle": "{id} — Log",
|
||||
"pluginMarketDownloading": "Downloading",
|
||||
"pluginMarketEmpty": "No plugins available in the market index yet. You can still import local .zip packages or configure a custom index URL.",
|
||||
"pluginMarketFeedEnd": "{count} plugins",
|
||||
"pluginMarketIncompatible": "Incompatible",
|
||||
"pluginMarketInstall": "Install",
|
||||
"pluginMarketInstalled": "Installed",
|
||||
"pluginMarketInstalling": "Installing",
|
||||
"pluginMarketKindAll": "All",
|
||||
"pluginMarketKindDriver": "Drivers",
|
||||
"pluginMarketKindLocale": "Languages",
|
||||
"pluginMarketKindRuntime": "Runtimes",
|
||||
"pluginMarketKindTemplate": "Templates",
|
||||
"pluginMarketKindTheme": "Themes",
|
||||
"pluginMarketKindTool": "Tools",
|
||||
"pluginMarketLoading": "Loading the plugin market",
|
||||
"pluginMarketRefresh": "Refresh index",
|
||||
"pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags",
|
||||
"pluginMarketStaleBanner": "Remote market index is unreachable; showing cached or offline fallback data",
|
||||
"pluginMarketSyncing": "Syncing the plugin market",
|
||||
"pluginMarketUpdate": "Update to v{version}",
|
||||
"pluginMarketUpdateShort": "Update",
|
||||
"pluginMarketVersionTip": "v{installed} installed, v{version} available",
|
||||
"pluginMarketWithdrawn": "Withdrawn",
|
||||
"pluginMarketWithdrawnInstalledWarn": "Installed plugin {id} has been withdrawn: {reason}",
|
||||
"pluginMarketWithdrawnInstead": "Recommended replacement: {target}",
|
||||
"pluginNewScheme": "New scheme",
|
||||
"pluginPanelsSection": "Plugin panels",
|
||||
"pluginPermCount": "{count, plural, one {# permission} other {# permissions}}",
|
||||
"pluginPermissionsLabel": "Permissions: {list}",
|
||||
"pluginPublisherLicense": "Publisher / License",
|
||||
"pluginRemove": "Remove",
|
||||
"pluginRequestedPerms": "Requested permissions",
|
||||
"pluginRiskBackground": "Can keep code running in the background",
|
||||
"pluginRiskClipboard": "Can read and write the system clipboard",
|
||||
"pluginRiskFiles": "Reads and writes files",
|
||||
"pluginRiskInput": "Intercepts or rewrites keyboard and mouse input",
|
||||
"pluginRiskNative": "Ships a native program with full rights of your Windows account",
|
||||
"pluginRiskNetwork": "Accesses the network",
|
||||
"pluginRiskUi": "Changes the interface you see",
|
||||
"pluginRiskVm": "Can control your virtual machines",
|
||||
"pluginScanAdvisoriesSection": "Advisories \u0026 executables",
|
||||
"pluginScanArchiveTitle": "Pre-install security check",
|
||||
"pluginScanBlockedBtn": "Blocked — cannot install",
|
||||
"pluginScanCapabilitiesSection": "Capabilities \u0026 privileges",
|
||||
"pluginScanHardSection": "Hard blockers (install refused)",
|
||||
"pluginScanInspect": "Security scan",
|
||||
"pluginScanInstallConfirm": "Proceed with install",
|
||||
"pluginScanLoading": "Scanning plugin package…",
|
||||
"pluginScanModalTitle": "Plugin security report",
|
||||
"pluginScanMoreItems": "...and {count} more",
|
||||
"pluginSchemeDefault": "Default",
|
||||
"pluginSchemeModalTitle": "New color scheme",
|
||||
"pluginSchemeName": "Scheme name",
|
||||
"pluginSchemePlaceholder": "e.g. Soft Blue",
|
||||
"pluginSearchEmpty": "No matching plugins",
|
||||
"pluginSearchPlaceholder": "Filter plugins",
|
||||
"pluginSettings": "Plugin settings",
|
||||
"pluginStateDegraded": "Degraded",
|
||||
"pluginStateFailed": "Failed",
|
||||
"pluginStatePending": "Pending",
|
||||
"pluginSurfaceSeed": "Surface seed (optional)",
|
||||
"pluginTabInstalled": "Installed",
|
||||
"pluginTabMarket": "Market",
|
||||
"pluginThemeEmptyHint": "Import a local theme package (.zip) to switch visual themes and color schemes",
|
||||
"pluginThemeHint": "One active theme pack at a time; disabling falls back to the built-in default",
|
||||
"pluginThemePackLabel": "Theme pack",
|
||||
"pluginThemeSafeModeHint": "Built-in default theme is enforced in safe mode",
|
||||
"pluginThemeSection": "Theme extensions",
|
||||
"pluginTrustCommunity": "Community",
|
||||
"pluginTrustDev": "Dev",
|
||||
"pluginTrustOfficial": "Official",
|
||||
"pluginTrustVerified": "Verified",
|
||||
"pluginViewLog": "View log",
|
||||
}
|
||||
|
||||
registerBuiltinDomain(pluginsZh, pluginsEn)
|
||||
@@ -0,0 +1,848 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
import { registerBuiltinDomain } from '../runtime'
|
||||
|
||||
export const settingsZh: Record<string, string> = {
|
||||
"aboutCommunity": "社区与支持",
|
||||
"aboutCopyDiscord": "复制邀请链接",
|
||||
"aboutCopyQQGroup": "复制群号",
|
||||
"aboutDiscord": "Discord 社区",
|
||||
"aboutDiscordSub": "交流使用体验、硬件兼容反馈、Alpha 测试与插件开发",
|
||||
"aboutIssueSub": "遇到问题或有功能建议,在 GitHub 提交 Issue",
|
||||
"aboutJoinDiscord": "加入服务器",
|
||||
"aboutJoinQQGroup": "加入群聊",
|
||||
"aboutLicensesOpenGitHub": "在 GitHub 查看",
|
||||
"aboutLicensesSub": "Apache-2.0 协议与第三方开源组件声明(离线可查)",
|
||||
"aboutLicensesTabLicense": "Apache-2.0 协议",
|
||||
"aboutLicensesTabNotice": "第三方声明",
|
||||
"aboutLicensesTitle": "开源许可与声明",
|
||||
"aboutLicensesView": "查看",
|
||||
"aboutProjectSub": "GitHub 上的源码、发布版本与使用文档",
|
||||
"aboutQQGroup": "QQ 交流群",
|
||||
"aboutQQGroupSub": "点击直接拉起 QQ 加群,交流使用与问题反馈",
|
||||
"aboutQQLaunchFailed": "未能拉起 QQ,可复制群号手动搜索加入",
|
||||
"aboutQQNotInstalled": "未安装 QQ",
|
||||
"aboutQQNotInstalledSub": "未检测到本地 QQ,可复制群号手动搜索加入",
|
||||
"aboutTagline": "在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。",
|
||||
"activate": "使用",
|
||||
"affinityApplyNow": "立即应用",
|
||||
"affinityAvoidLPE": "避开 LP-E",
|
||||
"affinityConfigure": "配置…",
|
||||
"affinityEcoQoS": "禁用 Windows 效率模式节流 (EcoQoS)",
|
||||
"affinityEcoQoSDesc": "防止 Windows 11 在窗口失焦或后台运行时把 QEMU 线程压缩到 2 个低功耗核心",
|
||||
"affinityExcludeCPU0": "排除 CPU 0",
|
||||
"affinityLiveMask": "Windows 当前生效:{mask}({count} 线程)",
|
||||
"affinityModeAll": "所有处理器",
|
||||
"affinityModeAllHint": "允许 Windows 将 QEMU 调度到全部宿主机逻辑处理器。",
|
||||
"affinityModeAuto": "自动",
|
||||
"affinityModeAutoHint": "跟随全局策略,在混合大小核处理器上自动避开超售与低功耗核。",
|
||||
"affinityModeCustom": "自定义",
|
||||
"affinityModeCustomHint": "勾选允许运行 QEMU 的逻辑处理器,等价于 Windows 任务管理器的处理器相关性。",
|
||||
"affinityModeNonLPE": "P + E 核",
|
||||
"affinityModeNonLPEHint": "在性能核与能效核(P + E)上运行,仅排除慢速低功耗核(LP-E)。",
|
||||
"affinityModePCores": "仅 P 核",
|
||||
"affinityModePCoresHint": "仅在性能核(P-Core)上运行,减少大小核混调引起的抖动。",
|
||||
"affinityNeedOne": "请至少勾选 1 个逻辑处理器",
|
||||
"affinityOnlyPCores": "仅 P 核",
|
||||
"affinityOversubWarn": "当前只勾选了 {selected} 个逻辑处理器,少于虚拟机分配的 {vcpus} 个 vCPU,可能导致明显卡顿。",
|
||||
"affinityPhysicalOnly": "仅物理核",
|
||||
"affinityRowDesc": "指定虚拟机在哪些核心上运行,立即生效",
|
||||
"affinitySave": "保存",
|
||||
"affinitySelectAll": "所有处理器",
|
||||
"affinitySelectedSummary": "已选 {selected} / {total} 个逻辑处理器 · 掩码 {mask}",
|
||||
"affinitySubtitleRunning": "运行中(PID {pid})· {vcpus} vCPU · 修改后立即生效",
|
||||
"affinitySubtitleStopped": "已停止 · {vcpus} vCPU · 下次启动时自动生效",
|
||||
"affinitySummaryAll": "所有处理器({count} 线程)",
|
||||
"affinitySummaryAuto": "自动({eff} · {count} 线程)",
|
||||
"affinitySummaryCustom": "自定义({count} 线程 · {mask})",
|
||||
"affinitySummaryNonLPE": "P + E 核({count} 线程 · {mask})",
|
||||
"affinitySummaryPCores": "仅 P 核({count} 线程 · {mask})",
|
||||
"affinityTitle": "处理器核心",
|
||||
"appCheckUpdate": "检查更新",
|
||||
"appDownloadUpdate": "前往下载",
|
||||
"appUpToDate": "已是最新",
|
||||
"appUpdateAvailable": "发现新版本 {v}(稳定版)",
|
||||
"appUpdateAvailableAlpha": "发现新版本 {v}(Alpha 测试版)",
|
||||
"appUpdateAvailableDev": "发现新版本 {v}(Dev 滚动版)",
|
||||
"appUpdateChannelAlpha": "Alpha",
|
||||
"appUpdateChannelDev": "Dev",
|
||||
"appUpdateChannelStable": "稳定版",
|
||||
"appUpdateChannelSubKeepOld": "接收 {channel} 预发布版本;启动时不删除旧版程序与已下载安装包,方便随时回退",
|
||||
"appUpdateChannelSubStable": "仅接收经过验证的正式稳定版本",
|
||||
"appUpdateChannelTitle": "更新通道",
|
||||
"appUpdateLookupFailed": "暂时无法连接 GitHub 检查更新",
|
||||
"appVersionTitle": "客户端版本",
|
||||
"appliesNextStart": "下次启动生效",
|
||||
"audioBackendAuto": "自动",
|
||||
"audioBackendDesc": "「静音」保留 macOS 的声卡但不出声,适合排查音频问题",
|
||||
"audioBackendDsound": "DirectSound",
|
||||
"audioBackendNone": "静音",
|
||||
"audioBackendTitle": "声音输出",
|
||||
"audioDesc": "在 Windows 上播放 macOS 的声音",
|
||||
"audioDisabledReason": "请先开启音频",
|
||||
"audioTroubleshootNote": "有爆音时,把 Windows 声音格式设为 48000 Hz;麦克风没声音时,检查 Windows「隐私 › 麦克风」权限",
|
||||
"autoPinPCores": "启动后绑定到性能核",
|
||||
"back": "上一步",
|
||||
"captureInput": "点击窗口时捕获键鼠",
|
||||
"captureInputHint": "开启后 ⌘Tab 等快捷键交给 macOS;关闭时 Win 键和 Alt+Tab 留给 Windows",
|
||||
"catAdvanced": "高级",
|
||||
"catAudio": "音频",
|
||||
"catCompute": "处理器与内存",
|
||||
"catGeneral": "通用",
|
||||
"catGraphics": "图形与显示器",
|
||||
"catInput": "键盘与指针",
|
||||
"catInputAudio": "输入与音频",
|
||||
"catLogs": "日志",
|
||||
"catNetwork": "网络",
|
||||
"catStorage": "存储",
|
||||
"catStorageNet": "存储与网络",
|
||||
"choose": "浏览…",
|
||||
"configured": "已配置",
|
||||
"coresUnit": "核",
|
||||
"cpuOverHint": "留给 Windows 的线程不足 2 个,电脑可能变卡",
|
||||
"cpuRecHint": "推荐 {rec} 核 · 本机共 {n} 线程",
|
||||
"defenderCopyCommand": "复制排除命令",
|
||||
"defenderExclusionDesc": "实时扫描可能拖慢虚拟机磁盘访问。可在 Windows 安全中心为数据目录 {path} 添加排除项。",
|
||||
"defenderExclusionTitle": "Windows Defender 实时防护排除建议",
|
||||
"defenderOpenSecurity": "打开 Windows 安全中心",
|
||||
"diskCompactAction": "立即回收",
|
||||
"diskCompactDesc": "把 macOS 里已删除文件占用的空间还给 Windows,过程中需要与当前占用差不多的空闲空间",
|
||||
"diskCompactDone": "已回收 {reclaimed}({before} → {after})",
|
||||
"diskCompactNoGain": "没有可回收的空间",
|
||||
"diskCompactQcow2Only": "这块磁盘不支持回收空间",
|
||||
"diskCompactTitle": "回收空间",
|
||||
"diskController": "磁盘接口",
|
||||
"diskControllerInstallHint": "装机时保持 SATA,装完弹出安装盘再改 NVMe",
|
||||
"diskControllerNvmeHint": "NVMe 读写更快",
|
||||
"diskControllerNvmeReadyHint": "NVMe 速度快,也兼容恢复模式,推荐",
|
||||
"diskControllerVirtioHint": "VirtIO 开销更低,仍属实验性;遇到问题请改回 NVMe",
|
||||
"diskControllerWarn": "切换前先弹出安装盘",
|
||||
"diskMode": "使用方式",
|
||||
"diskModeCopy": "复制一份,不改动原盘",
|
||||
"diskModeInPlace": "直接使用原盘",
|
||||
"diskOptimizeAction": "优化磁盘结构",
|
||||
"diskOptimizeDesc": "默认 64 KiB 簇可划分为 2 KiB 子簇,减少小块写入的开销,同时整理磁盘并回收空间。",
|
||||
"diskOptimizeDone": "{before} → {after},已回收 {reclaimed}。{status}。",
|
||||
"diskOptimizeEnabled": "已启用 extended_l2",
|
||||
"diskOptimizeInactive": "extended_l2 未启用",
|
||||
"diskOptimizeTitle": "QCOW2 子簇优化",
|
||||
"diskResizeAction": "扩容",
|
||||
"diskResizeDesc": "只能增大。扩大后在 macOS 终端运行提示的命令,新空间才能使用",
|
||||
"diskResizeDone": "已扩大到 {size}。在 macOS 终端运行:",
|
||||
"diskResizeTitle": "扩大磁盘",
|
||||
"diskRewriteBusy": "正在进行另一项磁盘操作。",
|
||||
"diskRewriteOverlay": "此磁盘共享基础镜像,无法直接重写。",
|
||||
"diskRewriteSnapshots": "请先删除内部恢复点,以免重写磁盘时丢失。",
|
||||
"diskSize": "磁盘上限",
|
||||
"diskSizeHint": "按实际占用增长",
|
||||
"diskUsageSummary": "已占用 {actual},上限 {virtual}",
|
||||
"displayGroup": "显示器",
|
||||
"driveShareMaster": "共享 Windows 盘符",
|
||||
"driveShareMasterDesc": "在 macOS 访达中显示所选磁盘,立即生效",
|
||||
"driveShareNeedsTools": "需要 Guest Tools {version} 以上:重启虚拟机,再在 macOS 中重新运行安装命令",
|
||||
"driveShareNoDrives": "没有可共享的内部固定磁盘",
|
||||
"driveShareReadOnly": "只读:macOS 可以打开和复制,不能修改",
|
||||
"driveShareSystem": "系统盘,含个人文件和登录信息,请谨慎共享",
|
||||
"driveShareTitle": "Windows 盘符共享",
|
||||
"effectImmediate": "立即生效",
|
||||
"effectNextStart": "下次启动生效",
|
||||
"enableAudio": "音频",
|
||||
"enableLogs": "记录图形与串口日志",
|
||||
"enableNetwork": "网络(NAT)",
|
||||
"enableWHPX": "启用",
|
||||
"extraArgs": "额外 QEMU 参数",
|
||||
"extraArgsDesc": "原样追加到 QEMU 命令行",
|
||||
"failAffinity": "设置处理器相关性失败",
|
||||
"folderShareAdd": "添加目录…",
|
||||
"folderShareAddTitle": "宿主机目录",
|
||||
"folderShareConfirmRWAction": "改为读写",
|
||||
"folderShareConfirmRWDesc": "允许 macOS 修改或删除「{name}」({path})中的文件,更改会立即同步到宿主机原目录。",
|
||||
"folderShareConfirmRWTitle": "开启读写权限",
|
||||
"folderShareDesc": "在 macOS 桌面 ReimsSharedFolders 中访问,立即生效",
|
||||
"folderShareEmpty": "未添加目录",
|
||||
"folderShareIssueBlocked": "不支持共享此目录(系统目录、数据目录、盘符根或外接盘)",
|
||||
"folderShareIssueCorruptConfig": "Guest Tools 配置文件损坏,已保留原文件未覆盖",
|
||||
"folderShareIssueInvalidMode": "无效的共享权限模式",
|
||||
"folderShareIssueMissing": "目录不存在或已移动",
|
||||
"folderShareIssueNotFound": "未找到该共享目录配置",
|
||||
"folderShareIssueOverlap": "与已有共享目录重复或存在包含关系",
|
||||
"folderShareIssuePathChanged": "目录已被重定向或替换,已暂停共享",
|
||||
"folderShareIssueVolumeMismatch": "所在磁盘已变更,已暂停共享",
|
||||
"folderShareListTitle": "已添加目录",
|
||||
"folderShareModeDisabled": "停用",
|
||||
"folderShareModeRO": "只读",
|
||||
"folderShareModeRW": "读写",
|
||||
"folderShareNeedsTools": "需要 Guest Tools {version} 以上:在虚拟机页面更新工具盘并重启虚拟机,再在 macOS 中重新运行安装命令",
|
||||
"folderShareNote": "仅支持本地固定磁盘目录;新增条目默认只读。CoW 克隆不复制目录配置,但克隆盘会沿用源机 Guest Tools 凭证,需在克隆机重新安装 Guest Tools 以隔离",
|
||||
"folderSharePickTitle": "选择要共享给 macOS 的目录",
|
||||
"folderShareRemove": "移除目录",
|
||||
"folderShareTitle": "自定义共享目录",
|
||||
"folderShareWritableWarn": "读写模式:macOS 中的修改和删除会直接作用于宿主机原目录",
|
||||
"footerDisk": "磁盘可用 {gb} GB",
|
||||
"footerMem": "内存 {pct}%",
|
||||
"footerMemAvail": "可用 {avail} GB",
|
||||
"forceQuitAppButton": "强制退出",
|
||||
"forceQuitAppSub": "对所有运行中的虚拟机执行硬关机,未保存的数据可能丢失。",
|
||||
"forceQuitAppTitle": "强制退出 Reims-Go",
|
||||
"forceQuitInProgress": "正在强制退出…",
|
||||
"fullscreenDecoupledHint": "窗口铺满屏幕;下方分辨率可独立设为原生或超采样 HiDPI(如 4K 1.5× = 5120×2880),由 GPU 自动缩放",
|
||||
"fullscreenLaunch": "无边框全屏启动",
|
||||
"fullscreenLaunchHint": "启动后直接进入无边框全屏",
|
||||
"gpuAutoOption": "自动(优先独显)",
|
||||
"gpuAutoSub": "将使用 {name}",
|
||||
"gpuAutoTitle": "自动",
|
||||
"gpuCompatUnsupported": "不支持加速",
|
||||
"gpuCompatWarn": "已知兼容风险",
|
||||
"gpuCustomIcd": "自定义 Vulkan ICD",
|
||||
"gpuDiscrete": "独显",
|
||||
"gpuIntegrated": "核显",
|
||||
"gpuKindDiscrete": "独立显卡",
|
||||
"gpuKindIntegrated": "集成显卡",
|
||||
"gpuRecommended": "推荐",
|
||||
"gpuSelect": "显卡",
|
||||
"gpuSvgaReason": "VMware SVGA 不使用宿主显卡",
|
||||
"gpuSwitchSvga": "改用 VMware SVGA",
|
||||
"gpuUnavailableHint": "没有找到能加速的显卡,可改用 VMware SVGA",
|
||||
"gpuUnknown": "未知",
|
||||
"gpuVirtual": "虚拟",
|
||||
"graphicsBackend": "虚拟显卡",
|
||||
"graphicsReimsDesc": "用宿主显卡加速 Metal,推荐",
|
||||
"graphicsReimsShort": "Reims vGPU",
|
||||
"graphicsRunningReason": "关机后才能切换",
|
||||
"graphicsSvgaDesc": "没有硬件加速,只用于排障",
|
||||
"graphicsSvgaShort": "VMware SVGA",
|
||||
"groupGraphics": "图形",
|
||||
"groupMacOS": "macOS",
|
||||
"groupPerformance": "性能",
|
||||
"groupQemu": "QEMU",
|
||||
"gtInstallCmd": "安装命令",
|
||||
"guestLangHint": "恢复模式、设置助理和登录界面使用的语言;选美式键盘,在终端输命令不易出错",
|
||||
"guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言",
|
||||
"guestLangShort": "系统语言",
|
||||
"guestMemory": "分配内存",
|
||||
"guestToolsConnected": "已连接",
|
||||
"guestToolsPreventSleepSub": "闲置时让 macOS 保持唤醒,立即生效",
|
||||
"guestToolsReady": "已配置",
|
||||
"hidpiPresetBadge": "HiDPI",
|
||||
"hostAudioInput": "Windows 麦克风",
|
||||
"hostAudioMissingIn": "没有检测到麦克风,macOS 录不到声音",
|
||||
"hostAudioMissingOut": "没有检测到扬声器或耳机,虚拟机将没有声音",
|
||||
"hostAudioOutput": "Windows 播放设备",
|
||||
"hostCPU": "处理器",
|
||||
"hostCoresThreads": "{c} 核 · {t} 线程",
|
||||
"hostDataRoot": "数据目录",
|
||||
"hostDisk": "可用空间",
|
||||
"hostDisplayPrimary": "主屏",
|
||||
"hostDisplays": "物理显示器",
|
||||
"hostGPUs": "显卡",
|
||||
"hostRAM": "内存",
|
||||
"hostRAMAvail": "可用 {n} GB",
|
||||
"hostRAMTotal": "共 {n} GB",
|
||||
"hostRuntime": "运行时",
|
||||
"hostWHPX": "Windows 虚拟机监控程序平台",
|
||||
"imagesNoSourcesDesc": "请在「插件」页面启用至少一个镜像源插件(例如 macOS 镜像源)以浏览和下载系统镜像。",
|
||||
"imagesNoSourcesTitle": "未启用镜像源插件",
|
||||
"imagesOpenPlugins": "前往插件",
|
||||
"imagesSourcesLabel": "镜像来源",
|
||||
"installersAvailable": "Apple 提供的版本",
|
||||
"installersCreateVM": "新建虚拟机",
|
||||
"installersDelete": "删除",
|
||||
"installersDeleteConfirm": "确认删除",
|
||||
"installersDownload": "下载",
|
||||
"installersDownloaded": "已下载",
|
||||
"installersDownloadingForVM": "为 {vm} 下载中",
|
||||
"installersDownloadingPct": "下载中 {p}%",
|
||||
"installersEmpty": "还没有下载任何镜像",
|
||||
"installersHint": "下载好的镜像可以重复用来新建虚拟机",
|
||||
"installersKindOffline": "离线完整包",
|
||||
"installersKindOnline": "在线恢复镜像",
|
||||
"installersLatest": "最新",
|
||||
"installersNoSpace": "空间不足:需要约 {need} GB,可用 {free} GB",
|
||||
"installersOlder": "{count, plural, other {# 个旧版本}}",
|
||||
"installersPartial": "未下载完",
|
||||
"installersQueued": "排队中",
|
||||
"installersQueuedForVM": "为 {vm} 排队中",
|
||||
"installersResume": "继续下载",
|
||||
"installersTitle": "镜像",
|
||||
"installersWaitingVM": "{vm} 等待使用",
|
||||
"kernelIrqchipAuto": "自动",
|
||||
"kernelIrqchipLabel": "中断加速",
|
||||
"kernelIrqchipOff": "关闭",
|
||||
"kernelIrqchipOn": "开启",
|
||||
"keymapGroupNote": "仅在此虚拟机窗口位于前台时生效。Ctrl+Alt+Win 保留用于释放捕获。",
|
||||
"keymapGroupTitle": "修饰键映射",
|
||||
"keymapGuestDefault": "默认",
|
||||
"keymapGuestDisabled": "禁用",
|
||||
"keymapGuestEsc": "Esc",
|
||||
"keymapGuestLcmd": "左 ⌘ Command",
|
||||
"keymapGuestLctrl": "左 ⌃ Control",
|
||||
"keymapGuestLopt": "左 ⌥ Option",
|
||||
"keymapGuestRcmd": "右 ⌘ Command",
|
||||
"keymapGuestRctrl": "右 ⌃ Control",
|
||||
"keymapGuestRopt": "右 ⌥ Option",
|
||||
"keymapHostCapslock": "Caps Lock",
|
||||
"keymapHostLalt": "左 Alt",
|
||||
"keymapHostLctrl": "左 Ctrl",
|
||||
"keymapHostLwin": "左 Win",
|
||||
"keymapHostRalt": "右 Alt",
|
||||
"keymapHostRctrl": "右 Ctrl",
|
||||
"keymapHostRwin": "右 Win",
|
||||
"keymapInactive": "修饰键映射未启用",
|
||||
"keymapInputServiceRequired": "请启用宿主输入服务以使用修饰键映射",
|
||||
"keymapPending": "等待 Guest Tools 启用修饰键映射",
|
||||
"keymapPresetCustom": "自定义",
|
||||
"keymapPresetOff": "关闭",
|
||||
"keymapPresetSwapAltWin": "Alt ↔ Win",
|
||||
"keymapPresetTitle": "映射预设",
|
||||
"keymapPresetWinToCmd": "Win → ⌘",
|
||||
"keymapRunning": "虚拟机获得焦点时生效",
|
||||
"keymapStopped": "虚拟机启动后生效",
|
||||
"keymapUpgrade": "请将 Guest Tools 更新到版本 {version}",
|
||||
"keymapWaiting": "等待 Guest Tools 连接",
|
||||
"language": "语言",
|
||||
"languageSub": "内置简体中文与英语,可通过插件扩展更多语言",
|
||||
"logLevel": "日志级别",
|
||||
"logLevelCustom": "自定义",
|
||||
"logLevelDesc": "排查问题时再调高",
|
||||
"macosSlaButton": "查看许可协议",
|
||||
"macosSlaNotice": "使用此软件必须接受软件附带的原始许可协议。",
|
||||
"macosVersion": "macOS 版本",
|
||||
"memCommitHint": "Windows 还能分配 {avail} GB · 推荐 {rec} GB",
|
||||
"memOverHint": "超过推荐值,启动时可能分配失败",
|
||||
"memRecHint": "推荐 {rec} GB · 本机共 {n} GB",
|
||||
"minimizeToTray": "关闭窗口时最小化到系统托盘",
|
||||
"minimizeToTraySub": "关闭窗口后剪贴板和共享文件夹继续工作,可从托盘启停虚拟机",
|
||||
"multiDisplayHint": "{n, plural, other {检测到 # 块显示器,排列方式在 macOS「系统设置 › 显示器」里调整}}",
|
||||
"navHasIssue": "这一页有需要修改的项",
|
||||
"networkDesc": "通过 Windows 的网络连接上网",
|
||||
"networkOfflineHint": "离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网",
|
||||
"networkTitle": "网络",
|
||||
"next": "下一步",
|
||||
"noChanges": "没有更改",
|
||||
"offlineListFailed": "无法读取 Apple 的版本列表",
|
||||
"opencore": "OpenCore",
|
||||
"optAuto": "已自动开启",
|
||||
"optAvailable": "可用",
|
||||
"optExperimental": "实验性",
|
||||
"optKernelIrqchipExp": "实验性:开启可能更快,启动卡住就改回「自动」(Win10 上自动为关闭)",
|
||||
"optKernelIrqchipNestedErr": "当前 Windows 不支持({code}),「自动」会保持关闭",
|
||||
"optKernelIrqchipRec": "由 Windows 直接处理中断,磁盘和多核更流畅。「自动」即开启",
|
||||
"optKernelIrqchipUnavailable": "当前电脑不支持",
|
||||
"optKernelIrqchipWin10NoPatch": "Win10 上需要先更新运行时才能开启",
|
||||
"optPCoreSub": "仅调度到性能核({detail}),减少卡顿",
|
||||
"optPCoreUnavailable": "当前处理器无大小核架构,无需开启",
|
||||
"optRecommended": "推荐",
|
||||
"optSchedBackground": "后台服务",
|
||||
"optSchedNowBackground": "当前为「后台服务」,适合虚拟机在后台运行(影响整个 Windows)",
|
||||
"optSchedNowPrograms": "当前为「程序优先」,虚拟机在后台时可能变慢,建议改为「后台服务」(影响整个 Windows)",
|
||||
"optSchedOpen": "更改…",
|
||||
"optSchedPrograms": "程序优先",
|
||||
"optSchedSub": "选「后台服务」,虚拟机在后台时更稳定(影响整个 Windows)",
|
||||
"optSchedTitle": "Windows 处理器调度",
|
||||
"optUnavailable": "不可用",
|
||||
"pendingChanges": "{n, plural, other {# 项更改,下次启动生效}}",
|
||||
"platformReadonly": "机型、序列号等平台身份信息不在界面显示",
|
||||
"recommendedBadge": "推荐",
|
||||
"resCustom": "自定义",
|
||||
"resCustomSub": "宽 × 高",
|
||||
"resFullscreen": "全屏",
|
||||
"resInvalid": "格式为 宽x高,例如 2560x1600",
|
||||
"resNativeBadge": "原生",
|
||||
"resetAll": "全部还原",
|
||||
"resetField": "还原为当前值",
|
||||
"runtimeDelete": "删除运行时",
|
||||
"runtimeDeleteConfirm": "确认删除",
|
||||
"runtimeDeleted": "已删除运行时 {commit}",
|
||||
"secondsUnit": "秒",
|
||||
"settingsAppearance": "外观与语言",
|
||||
"settingsGeneral": "常规",
|
||||
"settingsTitle": "{name}",
|
||||
"smbiosApplied": "已写入新的 OpenCore 设备码,下次启动虚拟机生效",
|
||||
"smbiosApply": "写入新设备码",
|
||||
"smbiosCheckHint": "建议将序列号复制到 checkcoverage.apple.com 确认显示「无效序列号」(未被真机占用)后再写入。",
|
||||
"smbiosCopySerial": "复制序列号",
|
||||
"smbiosDesc": "写入 OpenCore 的序列号、主板号 (MLB) 与 UUID,用于 Apple 服务识别。ROM 与虚拟网卡 MAC 保持同步,换码时不会修改。",
|
||||
"smbiosDialogSub": "只修改序列号、MLB 与 SystemUUID,保留原 ROM(网卡 MAC)与 NVRAM",
|
||||
"smbiosDialogTitle": "更换 OpenCore 设备码",
|
||||
"smbiosGenerate": "随机生成一组",
|
||||
"smbiosHide": "隐藏",
|
||||
"smbiosLoadFailed": "无法读取 OpenCore 设备码",
|
||||
"smbiosMLB": "主板号 (MLB)",
|
||||
"smbiosModel": "机型",
|
||||
"smbiosROM": "网卡 ROM",
|
||||
"smbiosRotateBtn": "一键换码…",
|
||||
"smbiosSerial": "序列号",
|
||||
"smbiosShow": "显示完整码",
|
||||
"smbiosStopRequired": "请先彻底关机(不能处于运行或休眠状态)",
|
||||
"smbiosTitle": "设备身份 (SMBIOS)",
|
||||
"smbiosUUID": "系统 UUID",
|
||||
"smbiosWarning": "换码前请先在 macOS 中退出 Apple 账户并彻底关机;换码后首次开机可能弹出「设置助理」,iCloud / App Store 需重新登录。",
|
||||
"sourceDisk": "已有虚拟磁盘(.qcow2)",
|
||||
"sourceInstaller": "本地安装器镜像(.img / .dmg)",
|
||||
"sshForward": "SSH 端口转发",
|
||||
"sshNeedsNetwork": "需要先开启网络",
|
||||
"sshOffDesc": "从 Windows 用 SSH 登录 macOS",
|
||||
"sshPort": "SSH 转发端口",
|
||||
"startAfterCreate": "创建后立即启动",
|
||||
"statsCPU": "QEMU CPU",
|
||||
"statsDisk": "磁盘占用",
|
||||
"statsDiskSub": "实际 {actual} / 上限 {virtual}",
|
||||
"statsMemory": "宿主机内存",
|
||||
"statsUptime": "运行时长",
|
||||
"stopBeforeDiskOp": "关机后才能操作",
|
||||
"stopTimeout": "关机等待时间",
|
||||
"stopTimeoutHint": "0 表示一直等待",
|
||||
"storageBreakdownTitle": "空间分布",
|
||||
"storageInstallers": "镜像",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"storageVMs": "虚拟机文件",
|
||||
"syncHostMemorySMBIOS": "同步宿主机内存规格",
|
||||
"syncHostMemorySMBIOSSub": "在 macOS「关于本机」中显示宿主机真实内存频率与代数(当前:{spec}),下次启动生效",
|
||||
"syncHostMemorySMBIOSUnavailable": "未能从宿主机 SMBIOS 读取物理内存频率,虚拟机将保持默认的 2666 MHz DDR4",
|
||||
"themeLabel": "外观",
|
||||
"themePluginDarkDisabled": "默认主题插件已停用,深色与跟随系统外观不可用",
|
||||
"themePluginLightDisabled": "当前主题仅支持深色外观",
|
||||
"updateDownloadInstall": "下载并安装",
|
||||
"updateDownloadingSub": "正在下载 {v}",
|
||||
"updateFailedSub": "下载或校验失败,可以重试",
|
||||
"updateReadySub": "{v} 已下载并通过校验,重启 Reims-Go 即可完成更新",
|
||||
"updateReleaseNotes": "发行说明",
|
||||
"useDefault": "恢复默认",
|
||||
"vcpus": "虚拟处理器",
|
||||
"vmDir": "存放目录",
|
||||
"vmName": "名称",
|
||||
"welcomeCheckHost": "先完成内核环境配置 →",
|
||||
"welcomeSub": "选择系统来源、分配核数与显卡,几步完成配置",
|
||||
"welcomeTitle": "创建第一台 macOS 虚拟机",
|
||||
"whpxMissing": "启用后需要重启 Windows",
|
||||
"whpxMissingShort": "未启用",
|
||||
"whpxNoHv": "在 BIOS 中开启 Intel VT-x / AMD-V",
|
||||
"whpxNoHvShort": "未激活",
|
||||
"whpxReady": "就绪",
|
||||
"whpxTitle": "WHPX",
|
||||
"whpxUnsupported": "当前不是 Windows 宿主",
|
||||
"whpxUnsupportedShort": "不支持",
|
||||
}
|
||||
|
||||
export const settingsEn: Record<string, string> = {
|
||||
"aboutCommunity": "Community \u0026 support",
|
||||
"aboutCopyDiscord": "Copy invite link",
|
||||
"aboutCopyQQGroup": "Copy group ID",
|
||||
"aboutDiscord": "Discord community",
|
||||
"aboutDiscordSub": "Chat with users, share hardware compatibility, test alphas and build plugins",
|
||||
"aboutIssueSub": "Report a problem or suggest a feature on GitHub",
|
||||
"aboutJoinDiscord": "Join server",
|
||||
"aboutJoinQQGroup": "Join group",
|
||||
"aboutLicensesOpenGitHub": "View on GitHub",
|
||||
"aboutLicensesSub": "Apache-2.0 license and third-party notices (available offline)",
|
||||
"aboutLicensesTabLicense": "Apache-2.0 License",
|
||||
"aboutLicensesTabNotice": "Third-party notices",
|
||||
"aboutLicensesTitle": "Open-source licenses",
|
||||
"aboutLicensesView": "View",
|
||||
"aboutProjectSub": "Source code, releases and docs on GitHub",
|
||||
"aboutQQGroup": "QQ Group",
|
||||
"aboutQQGroupSub": "Launch QQ directly to join for community support and feedback",
|
||||
"aboutQQLaunchFailed": "Couldn’t launch QQ — copy the group ID to join manually",
|
||||
"aboutQQNotInstalled": "QQ not installed",
|
||||
"aboutQQNotInstalledSub": "Local QQ wasn’t detected — copy the group ID to join manually",
|
||||
"aboutTagline": "Run a GPU-accelerated macOS virtual machine on Windows — prebuilt, ready out of the box.",
|
||||
"activate": "Use",
|
||||
"affinityApplyNow": "Apply Now",
|
||||
"affinityAvoidLPE": "Exclude LP-E",
|
||||
"affinityConfigure": "Configure…",
|
||||
"affinityEcoQoS": "Disable Windows EcoQoS power throttling",
|
||||
"affinityEcoQoSDesc": "Prevents Windows 11 from parking unfocused/background QEMU threads onto 2 low-power cores",
|
||||
"affinityExcludeCPU0": "Exclude CPU 0",
|
||||
"affinityLiveMask": "Active in Windows: {mask} ({count} threads)",
|
||||
"affinityModeAll": "All CPUs",
|
||||
"affinityModeAllHint": "Allows Windows to schedule QEMU across all host logical processors.",
|
||||
"affinityModeAuto": "Auto",
|
||||
"affinityModeAutoHint": "Follows global policy and avoids oversubscription and slow LP-E cores on hybrid CPUs.",
|
||||
"affinityModeCustom": "Custom",
|
||||
"affinityModeCustomHint": "Check the host logical CPUs allowed to run QEMU — identical to Windows Task Manager affinity.",
|
||||
"affinityModeNonLPE": "P + E",
|
||||
"affinityModeNonLPEHint": "Runs QEMU on P + E cores while excluding slow SoC LP-E cores.",
|
||||
"affinityModePCores": "P-Cores",
|
||||
"affinityModePCoresHint": "Restricts QEMU to performance cores (P-cores) to minimize scheduling jitter.",
|
||||
"affinityNeedOne": "Select at least 1 logical CPU",
|
||||
"affinityOnlyPCores": "P-cores only",
|
||||
"affinityOversubWarn": "Only {selected} logical CPUs selected for {vcpus} guest vCPUs; this may cause noticeable stalls.",
|
||||
"affinityPhysicalOnly": "Physical cores only",
|
||||
"affinityRowDesc": "Choose which cores the VM runs on. Applies immediately",
|
||||
"affinitySave": "Save",
|
||||
"affinitySelectAll": "All CPUs",
|
||||
"affinitySelectedSummary": "{selected} / {total} logical CPUs selected · Mask {mask}",
|
||||
"affinitySubtitleRunning": "Running (PID {pid}) · {vcpus} vCPU · Applies immediately",
|
||||
"affinitySubtitleStopped": "Stopped · {vcpus} vCPU · Applied on next start",
|
||||
"affinitySummaryAll": "All CPUs ({count}T)",
|
||||
"affinitySummaryAuto": "Auto ({eff} · {count}T)",
|
||||
"affinitySummaryCustom": "Custom ({count}T · {mask})",
|
||||
"affinitySummaryNonLPE": "P + E ({count}T · {mask})",
|
||||
"affinitySummaryPCores": "P-Cores ({count}T · {mask})",
|
||||
"affinityTitle": "CPU cores",
|
||||
"appCheckUpdate": "Check for updates",
|
||||
"appDownloadUpdate": "Download",
|
||||
"appUpToDate": "Up to date",
|
||||
"appUpdateAvailable": "New stable release {v} available",
|
||||
"appUpdateAvailableAlpha": "New alpha release {v} available",
|
||||
"appUpdateAvailableDev": "New dev build {v} available",
|
||||
"appUpdateChannelAlpha": "Alpha",
|
||||
"appUpdateChannelDev": "Dev",
|
||||
"appUpdateChannelStable": "Stable",
|
||||
"appUpdateChannelSubKeepOld": "Receive {channel} prereleases; previous executable and downloaded installers are kept on startup for rollback",
|
||||
"appUpdateChannelSubStable": "Receive verified stable releases only",
|
||||
"appUpdateChannelTitle": "Update channel",
|
||||
"appUpdateLookupFailed": "Couldn’t check GitHub for updates",
|
||||
"appVersionTitle": "App version",
|
||||
"appliesNextStart": "Applies on next start",
|
||||
"audioBackendAuto": "Auto",
|
||||
"audioBackendDesc": "Silent keeps the macOS sound card but plays nothing; useful for troubleshooting",
|
||||
"audioBackendDsound": "DirectSound",
|
||||
"audioBackendNone": "Silent",
|
||||
"audioBackendTitle": "Sound output",
|
||||
"audioDesc": "Plays macOS sound through Windows",
|
||||
"audioDisabledReason": "Enable audio first",
|
||||
"audioTroubleshootNote": "If audio crackles, set the Windows sound format to 48000 Hz. If the mic is silent, check Windows Privacy › Microphone",
|
||||
"autoPinPCores": "Pin to performance cores on start",
|
||||
"back": "Back",
|
||||
"captureInput": "Capture keyboard and mouse on click",
|
||||
"captureInputHint": "When on, shortcuts like ⌘Tab go to macOS; when off, Win and Alt+Tab stay with Windows",
|
||||
"catAdvanced": "Advanced",
|
||||
"catAudio": "Audio",
|
||||
"catCompute": "CPU \u0026 Memory",
|
||||
"catGeneral": "General",
|
||||
"catGraphics": "Graphics \u0026 displays",
|
||||
"catInput": "Keyboard \u0026 pointer",
|
||||
"catInputAudio": "Input \u0026 Audio",
|
||||
"catLogs": "Logs",
|
||||
"catNetwork": "Network",
|
||||
"catStorage": "Storage",
|
||||
"catStorageNet": "Storage \u0026 Network",
|
||||
"choose": "Browse…",
|
||||
"configured": "Configured",
|
||||
"coresUnit": "cores",
|
||||
"cpuOverHint": "Leaves Windows fewer than 2 threads; your PC may slow down",
|
||||
"cpuRecHint": "{rec} cores recommended · this PC has {n} threads",
|
||||
"defenderCopyCommand": "Copy exclusion command",
|
||||
"defenderExclusionDesc": "Real-time scanning can slow VM disk access. You can exclude the data folder {path} in Windows Security.",
|
||||
"defenderExclusionTitle": "Windows Defender real-time protection exclusions",
|
||||
"defenderOpenSecurity": "Open Windows Security",
|
||||
"diskCompactAction": "Reclaim now",
|
||||
"diskCompactDesc": "Gives space from files deleted in macOS back to Windows. Needs about as much free space as the disk uses now",
|
||||
"diskCompactDone": "Reclaimed {reclaimed} ({before} → {after})",
|
||||
"diskCompactNoGain": "Nothing to reclaim",
|
||||
"diskCompactQcow2Only": "This disk does not support reclaiming space",
|
||||
"diskCompactTitle": "Reclaim space",
|
||||
"diskController": "Disk interface",
|
||||
"diskControllerInstallHint": "Keep SATA while installing; switch to NVMe after ejecting the installer",
|
||||
"diskControllerNvmeHint": "NVMe is faster",
|
||||
"diskControllerNvmeReadyHint": "Fast and works with Recovery. Recommended",
|
||||
"diskControllerVirtioHint": "Lower overhead but experimental; switch back to NVMe if you hit problems",
|
||||
"diskControllerWarn": "Eject the installer before switching",
|
||||
"diskMode": "Use disk as",
|
||||
"diskModeCopy": "A copy — original untouched",
|
||||
"diskModeInPlace": "In place",
|
||||
"diskOptimizeAction": "Optimize disk layout",
|
||||
"diskOptimizeDesc": "Splits default 64 KiB clusters into 2 KiB subclusters to reduce small-write overhead while compacting the disk.",
|
||||
"diskOptimizeDone": "{before} → {after}, reclaimed {reclaimed}. {status}.",
|
||||
"diskOptimizeEnabled": "extended_l2 is enabled",
|
||||
"diskOptimizeInactive": "extended_l2 is inactive",
|
||||
"diskOptimizeTitle": "QCOW2 subcluster optimization",
|
||||
"diskResizeAction": "Expand",
|
||||
"diskResizeDesc": "Grow only. Afterwards, run the command shown in macOS Terminal to use the new space",
|
||||
"diskResizeDone": "Expanded to {size}. Run this in macOS Terminal:",
|
||||
"diskResizeTitle": "Expand disk",
|
||||
"diskRewriteBusy": "Another disk operation is in progress.",
|
||||
"diskRewriteOverlay": "This disk shares a backing image and cannot be rewritten directly.",
|
||||
"diskRewriteSnapshots": "Delete internal restore points first to preserve them when rewriting the disk.",
|
||||
"diskSize": "Disk size",
|
||||
"diskSizeHint": "Grows as it fills",
|
||||
"diskUsageSummary": "{actual} used of {virtual}",
|
||||
"displayGroup": "Displays",
|
||||
"driveShareMaster": "Share Windows drives",
|
||||
"driveShareMasterDesc": "Shows the selected drives in macOS Finder. Applies immediately",
|
||||
"driveShareNeedsTools": "Needs Guest Tools {version} or later: restart the VM, then run the install command in macOS again",
|
||||
"driveShareNoDrives": "No internal fixed disks are available to share",
|
||||
"driveShareReadOnly": "Read-only: macOS can open and copy files but not change them",
|
||||
"driveShareSystem": "System drive with personal files and sign-in data; share with care",
|
||||
"driveShareTitle": "Windows drive sharing",
|
||||
"effectImmediate": "Immediate",
|
||||
"effectNextStart": "Next start",
|
||||
"enableAudio": "Audio",
|
||||
"enableLogs": "Keep graphics and serial logs",
|
||||
"enableNetwork": "Network (NAT)",
|
||||
"enableWHPX": "Enable",
|
||||
"extraArgs": "Extra QEMU arguments",
|
||||
"extraArgsDesc": "Appended to the QEMU command line as is",
|
||||
"failAffinity": "Could not update processor affinity",
|
||||
"folderShareAdd": "Add folder…",
|
||||
"folderShareAddTitle": "Host folders",
|
||||
"folderShareConfirmRWAction": "Enable read-write",
|
||||
"folderShareConfirmRWDesc": "Allow macOS to modify or delete files in \"{name}\" ({path}). Changes apply directly to the host folder.",
|
||||
"folderShareConfirmRWTitle": "Enable read-write access",
|
||||
"folderShareDesc": "Accessible from ReimsSharedFolders on the macOS desktop. Applies immediately",
|
||||
"folderShareEmpty": "No folders added",
|
||||
"folderShareIssueBlocked": "This folder cannot be shared (system, data root, drive root, or external volume)",
|
||||
"folderShareIssueCorruptConfig": "Guest Tools config file is unreadable; original file was kept",
|
||||
"folderShareIssueInvalidMode": "Invalid shared folder mode",
|
||||
"folderShareIssueMissing": "Folder is missing or moved",
|
||||
"folderShareIssueNotFound": "Shared folder entry was not found",
|
||||
"folderShareIssueOverlap": "Overlaps with an existing shared folder",
|
||||
"folderShareIssuePathChanged": "Folder target changed or redirected; sharing paused",
|
||||
"folderShareIssueVolumeMismatch": "Volume identity changed; sharing paused",
|
||||
"folderShareListTitle": "Added folders",
|
||||
"folderShareModeDisabled": "Off",
|
||||
"folderShareModeRO": "Read-only",
|
||||
"folderShareModeRW": "Read-write",
|
||||
"folderShareNeedsTools": "Needs Guest Tools {version} or later: mount Guest Tools on the VM page, restart the VM, and run the install command in macOS again",
|
||||
"folderShareNote": "Internal fixed-disk folders only; new entries default to read-only. CoW clones do not copy folder settings, but keep the source Guest Tools token until Guest Tools is reinstalled on the clone",
|
||||
"folderSharePickTitle": "Choose a folder to share with macOS",
|
||||
"folderShareRemove": "Remove folder",
|
||||
"folderShareTitle": "Custom shared folders",
|
||||
"folderShareWritableWarn": "Read-write: changes and deletions in macOS modify the host folder directly",
|
||||
"footerDisk": "Disk {gb} GB free",
|
||||
"footerMem": "Memory {pct}%",
|
||||
"footerMemAvail": "{avail} GB free",
|
||||
"forceQuitAppButton": "Force quit",
|
||||
"forceQuitAppSub": "Cuts power to running virtual machines. Unsaved data may be lost.",
|
||||
"forceQuitAppTitle": "Force quit Reims-Go",
|
||||
"forceQuitInProgress": "Force quitting…",
|
||||
"fullscreenDecoupledHint": "Fills the monitor; pick native or supersampled HiDPI (e.g. 5120×2880 for 4K 1.5×) below, scaled on the GPU",
|
||||
"fullscreenLaunch": "Launch borderless fullscreen",
|
||||
"fullscreenLaunchHint": "Opens macOS in borderless full screen",
|
||||
"gpuAutoOption": "Automatic (prefers discrete)",
|
||||
"gpuAutoSub": "Will use {name}",
|
||||
"gpuAutoTitle": "Automatic",
|
||||
"gpuCompatUnsupported": "Unsupported",
|
||||
"gpuCompatWarn": "Known issue",
|
||||
"gpuCustomIcd": "Custom Vulkan ICD",
|
||||
"gpuDiscrete": "Discrete",
|
||||
"gpuIntegrated": "Integrated",
|
||||
"gpuKindDiscrete": "Discrete",
|
||||
"gpuKindIntegrated": "Integrated",
|
||||
"gpuRecommended": "Recommended",
|
||||
"gpuSelect": "GPU",
|
||||
"gpuSvgaReason": "VMware SVGA does not use the host GPU",
|
||||
"gpuSwitchSvga": "Use VMware SVGA",
|
||||
"gpuUnavailableHint": "No GPU available for acceleration; try VMware SVGA",
|
||||
"gpuUnknown": "Unknown",
|
||||
"gpuVirtual": "Virtual",
|
||||
"graphicsBackend": "Virtual graphics",
|
||||
"graphicsReimsDesc": "Accelerates Metal on the host GPU. Recommended",
|
||||
"graphicsReimsShort": "Reims vGPU",
|
||||
"graphicsRunningReason": "Shut down the VM to change this",
|
||||
"graphicsSvgaDesc": "No acceleration; for troubleshooting only",
|
||||
"graphicsSvgaShort": "VMware SVGA",
|
||||
"groupGraphics": "Graphics",
|
||||
"groupMacOS": "macOS",
|
||||
"groupPerformance": "Performance",
|
||||
"groupQemu": "QEMU",
|
||||
"gtInstallCmd": "Install command",
|
||||
"guestLangHint": "Used by Recovery, Setup Assistant and the login window; a US keyboard layout keeps Terminal input reliable",
|
||||
"guestLangSettingsHint": "Used by Recovery, Setup Assistant and the login window",
|
||||
"guestLangShort": "System language",
|
||||
"guestMemory": "Memory",
|
||||
"guestToolsConnected": "Connected",
|
||||
"guestToolsPreventSleepSub": "Keeps macOS awake while idle; applies immediately",
|
||||
"guestToolsReady": "Configured",
|
||||
"hidpiPresetBadge": "HiDPI",
|
||||
"hostAudioInput": "Windows microphone",
|
||||
"hostAudioMissingIn": "No microphone found; macOS will record silence",
|
||||
"hostAudioMissingOut": "No speakers or headphones found; the VM will be silent",
|
||||
"hostAudioOutput": "Windows playback",
|
||||
"hostCPU": "CPU",
|
||||
"hostCoresThreads": "{c} cores · {t} threads",
|
||||
"hostDataRoot": "Data folder",
|
||||
"hostDisk": "Free space",
|
||||
"hostDisplayPrimary": "Primary",
|
||||
"hostDisplays": "Physical displays",
|
||||
"hostGPUs": "Graphics cards",
|
||||
"hostRAM": "Memory",
|
||||
"hostRAMAvail": "{n} GB free",
|
||||
"hostRAMTotal": "{n} GB total",
|
||||
"hostRuntime": "Runtime",
|
||||
"hostWHPX": "Windows Hypervisor Platform",
|
||||
"imagesNoSourcesDesc": "Enable at least one image source plugin (such as macOS Images) in Plugins to browse and download system images.",
|
||||
"imagesNoSourcesTitle": "No image source plugins enabled",
|
||||
"imagesOpenPlugins": "Open Plugins",
|
||||
"imagesSourcesLabel": "Image sources",
|
||||
"installersAvailable": "Releases from Apple",
|
||||
"installersCreateVM": "Create VM",
|
||||
"installersDelete": "Delete",
|
||||
"installersDeleteConfirm": "Confirm delete",
|
||||
"installersDownload": "Download",
|
||||
"installersDownloaded": "Downloaded",
|
||||
"installersDownloadingForVM": "Downloading for {vm}",
|
||||
"installersDownloadingPct": "Downloading {p}%",
|
||||
"installersEmpty": "No images downloaded yet",
|
||||
"installersHint": "Downloaded images can be reused for new VMs",
|
||||
"installersKindOffline": "Offline installer",
|
||||
"installersKindOnline": "Online recovery",
|
||||
"installersLatest": "Latest",
|
||||
"installersNoSpace": "Not enough space: needs about {need} GB, {free} GB free",
|
||||
"installersOlder": "{count, plural, one {# older version} other {# older versions}}",
|
||||
"installersPartial": "Partly downloaded",
|
||||
"installersQueued": "Queued",
|
||||
"installersQueuedForVM": "Queued for {vm}",
|
||||
"installersResume": "Resume",
|
||||
"installersTitle": "Images",
|
||||
"installersWaitingVM": "{vm} waiting",
|
||||
"kernelIrqchipAuto": "Auto",
|
||||
"kernelIrqchipLabel": "Interrupt acceleration",
|
||||
"kernelIrqchipOff": "Off",
|
||||
"kernelIrqchipOn": "On",
|
||||
"keymapGroupNote": "Applies only while this VM is focused. Ctrl+Alt+Win is reserved for releasing capture.",
|
||||
"keymapGroupTitle": "Modifier keys",
|
||||
"keymapGuestDefault": "Default",
|
||||
"keymapGuestDisabled": "Disabled",
|
||||
"keymapGuestEsc": "Esc",
|
||||
"keymapGuestLcmd": "Left ⌘ Command",
|
||||
"keymapGuestLctrl": "Left ⌃ Control",
|
||||
"keymapGuestLopt": "Left ⌥ Option",
|
||||
"keymapGuestRcmd": "Right ⌘ Command",
|
||||
"keymapGuestRctrl": "Right ⌃ Control",
|
||||
"keymapGuestRopt": "Right ⌥ Option",
|
||||
"keymapHostCapslock": "Caps Lock",
|
||||
"keymapHostLalt": "Left Alt",
|
||||
"keymapHostLctrl": "Left Ctrl",
|
||||
"keymapHostLwin": "Left Win",
|
||||
"keymapHostRalt": "Right Alt",
|
||||
"keymapHostRctrl": "Right Ctrl",
|
||||
"keymapHostRwin": "Right Win",
|
||||
"keymapInactive": "Modifier mapping is inactive",
|
||||
"keymapInputServiceRequired": "Enable Host Input Service to use modifier mapping",
|
||||
"keymapPending": "Waiting for Guest Tools to activate modifier mapping",
|
||||
"keymapPresetCustom": "Custom",
|
||||
"keymapPresetOff": "Off",
|
||||
"keymapPresetSwapAltWin": "Alt ↔ Win",
|
||||
"keymapPresetTitle": "Preset",
|
||||
"keymapPresetWinToCmd": "Win → ⌘",
|
||||
"keymapRunning": "Active while this VM is focused",
|
||||
"keymapStopped": "Applies when this VM is running",
|
||||
"keymapUpgrade": "Update Guest Tools to version {version}",
|
||||
"keymapWaiting": "Waiting for Guest Tools to connect",
|
||||
"language": "Language",
|
||||
"languageSub": "Simplified Chinese and English built in; add more via plugins",
|
||||
"logLevel": "Log level",
|
||||
"logLevelCustom": "Custom",
|
||||
"logLevelDesc": "Raise only when troubleshooting",
|
||||
"macosSlaButton": "View SLA",
|
||||
"macosSlaNotice": "Use of this software requires acceptance of the original license agreement included with the software.",
|
||||
"macosVersion": "macOS version",
|
||||
"memCommitHint": "Windows can allocate {avail} GB more · {rec} GB recommended",
|
||||
"memOverHint": "Above the recommendation; the VM may fail to start",
|
||||
"memRecHint": "{rec} GB recommended · this PC has {n} GB",
|
||||
"minimizeToTray": "Minimize to system tray on close",
|
||||
"minimizeToTraySub": "Clipboard and shared folders keep working; start and stop VMs from the tray",
|
||||
"multiDisplayHint": "{n, plural, one {# display detected; arrange displays inside macOS System Settings › Displays} other {# displays detected; arrange them inside macOS System Settings › Displays}}",
|
||||
"navHasIssue": "This page has settings to fix",
|
||||
"networkDesc": "Uses the Windows network connection",
|
||||
"networkOfflineHint": "Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking",
|
||||
"networkTitle": "Network",
|
||||
"next": "Next",
|
||||
"noChanges": "No changes",
|
||||
"offlineListFailed": "Couldn’t read Apple’s release list",
|
||||
"opencore": "OpenCore",
|
||||
"optAuto": "Automatic",
|
||||
"optAvailable": "Available",
|
||||
"optExperimental": "Experimental",
|
||||
"optKernelIrqchipExp": "Experimental: may be faster. If startup hangs, go back to Auto (off on Windows 10)",
|
||||
"optKernelIrqchipNestedErr": "Not supported by this Windows ({code}); Auto keeps it off",
|
||||
"optKernelIrqchipRec": "Windows handles interrupts directly for smoother disk and multi-core work. Auto turns it on",
|
||||
"optKernelIrqchipUnavailable": "Not supported on this PC",
|
||||
"optKernelIrqchipWin10NoPatch": "On Windows 10, update the runtime to turn this on",
|
||||
"optPCoreSub": "Schedule QEMU on performance cores only ({detail})",
|
||||
"optPCoreUnavailable": "CPU has no hybrid P/E cores",
|
||||
"optRecommended": "Recommended",
|
||||
"optSchedBackground": "Background services",
|
||||
"optSchedNowBackground": "Set to Background services, which suits a VM running in the background (affects all of Windows)",
|
||||
"optSchedNowPrograms": "Set to Programs, so the VM may slow down in the background. Background services is recommended (affects all of Windows)",
|
||||
"optSchedOpen": "Change…",
|
||||
"optSchedPrograms": "Programs",
|
||||
"optSchedSub": "Background services keeps the VM steady in the background (affects all of Windows)",
|
||||
"optSchedTitle": "Windows processor scheduling",
|
||||
"optUnavailable": "Unavailable",
|
||||
"pendingChanges": "{n, plural, one {# change · applies on next start} other {# changes · applies on next start}}",
|
||||
"platformReadonly": "Model, serial number and other platform identity are never shown",
|
||||
"recommendedBadge": "Recommended",
|
||||
"resCustom": "Custom",
|
||||
"resCustomSub": "Width × height",
|
||||
"resFullscreen": "Full screen",
|
||||
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
|
||||
"resNativeBadge": "Native",
|
||||
"resetAll": "Revert all",
|
||||
"resetField": "Revert to current value",
|
||||
"runtimeDelete": "Delete runtime",
|
||||
"runtimeDeleteConfirm": "Confirm delete",
|
||||
"runtimeDeleted": "Removed runtime {commit}",
|
||||
"secondsUnit": "s",
|
||||
"settingsAppearance": "Appearance \u0026 language",
|
||||
"settingsGeneral": "General",
|
||||
"settingsTitle": "{name}",
|
||||
"smbiosApplied": "Updated OpenCore SMBIOS identity. Applies on next start",
|
||||
"smbiosApply": "Write new codes",
|
||||
"smbiosCheckHint": "Tip: check the serial at checkcoverage.apple.com and verify it reports invalid (not registered to a real Mac) before writing.",
|
||||
"smbiosCopySerial": "Copy serial",
|
||||
"smbiosDesc": "Serial, MLB and UUID written to OpenCore for Apple services. ROM stays synced with the virtual NIC MAC and is left unchanged.",
|
||||
"smbiosDialogSub": "Updates Serial, MLB and SystemUUID only; keeps ROM (NIC MAC) and NVRAM intact",
|
||||
"smbiosDialogTitle": "Rotate OpenCore SMBIOS",
|
||||
"smbiosGenerate": "Generate random",
|
||||
"smbiosHide": "Hide",
|
||||
"smbiosLoadFailed": "Could not read OpenCore SMBIOS",
|
||||
"smbiosMLB": "MLB",
|
||||
"smbiosModel": "Model",
|
||||
"smbiosROM": "NIC ROM",
|
||||
"smbiosRotateBtn": "Rotate codes…",
|
||||
"smbiosSerial": "Serial",
|
||||
"smbiosShow": "Reveal",
|
||||
"smbiosStopRequired": "Shut down the VM completely first (not running or suspended)",
|
||||
"smbiosTitle": "Device identity (SMBIOS)",
|
||||
"smbiosUUID": "System UUID",
|
||||
"smbiosWarning": "Sign out of Apple Account in macOS and shut down completely before rotating. First boot may show Setup Assistant and require signing in to iCloud / App Store again.",
|
||||
"sourceDisk": "Existing virtual disk (.qcow2)",
|
||||
"sourceInstaller": "Local installer image (.img / .dmg)",
|
||||
"sshForward": "SSH port forwarding",
|
||||
"sshNeedsNetwork": "Turn on the network first",
|
||||
"sshOffDesc": "Log in to macOS over SSH from Windows",
|
||||
"sshPort": "SSH forward port",
|
||||
"startAfterCreate": "Start after creating",
|
||||
"statsCPU": "QEMU CPU",
|
||||
"statsDisk": "Disk usage",
|
||||
"statsDiskSub": "{actual} actual / {virtual} max",
|
||||
"statsMemory": "Host RAM",
|
||||
"statsUptime": "Uptime",
|
||||
"stopBeforeDiskOp": "Shut down the VM first",
|
||||
"stopTimeout": "Shutdown timeout",
|
||||
"stopTimeoutHint": "0 waits indefinitely",
|
||||
"storageBreakdownTitle": "Storage breakdown",
|
||||
"storageInstallers": "Images",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"storageVMs": "VM files",
|
||||
"syncHostMemorySMBIOS": "Sync host memory specs",
|
||||
"syncHostMemorySMBIOSSub": "Show the host's actual memory speed and generation ({spec}) in macOS About This Mac; applies on next start",
|
||||
"syncHostMemorySMBIOSUnavailable": "Could not read host SMBIOS memory speed; VMs keep the default 2666 MHz DDR4",
|
||||
"themeLabel": "Appearance",
|
||||
"themePluginDarkDisabled": "Default theme plugin is disabled; dark and system appearances are unavailable",
|
||||
"themePluginLightDisabled": "The active theme supports dark appearance only",
|
||||
"updateDownloadInstall": "Download and install",
|
||||
"updateDownloadingSub": "Downloading {v}",
|
||||
"updateFailedSub": "Download or verification failed; try again",
|
||||
"updateReadySub": "{v} is downloaded and verified; restart Reims-Go to finish",
|
||||
"updateReleaseNotes": "Release notes",
|
||||
"useDefault": "Use Default",
|
||||
"vcpus": "Virtual CPUs",
|
||||
"vmDir": "Folder",
|
||||
"vmName": "Name",
|
||||
"welcomeCheckHost": "Set up Engine first →",
|
||||
"welcomeSub": "Pick an installer, assign cores and GPU, and launch in minutes",
|
||||
"welcomeTitle": "Create your first macOS VM",
|
||||
"whpxMissing": "Windows restarts after enabling",
|
||||
"whpxMissingShort": "Off",
|
||||
"whpxNoHv": "Turn on Intel VT-x / AMD-V in BIOS",
|
||||
"whpxNoHvShort": "Inactive",
|
||||
"whpxReady": "Ready",
|
||||
"whpxTitle": "WHPX",
|
||||
"whpxUnsupported": "This host isn’t Windows",
|
||||
"whpxUnsupportedShort": "Unsupported",
|
||||
}
|
||||
|
||||
registerBuiltinDomain(settingsZh, settingsEn)
|
||||
@@ -0,0 +1,433 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
|
||||
export const vmZh: Record<string, string> = {
|
||||
"attachGuestTools": "挂载 Guest Tools",
|
||||
"attachInstaller": "挂载离线镜像",
|
||||
"brokenHint": "这台虚拟机的配置无法读取",
|
||||
"cloneConfirm": "立即派生",
|
||||
"cloneDesc": "用写时复制瞬间创建副本,几乎不占空间,原虚拟机不受影响",
|
||||
"cloneNameLabel": "新虚拟机名称",
|
||||
"cloneTitle": "从「{name}」派生 CoW 副本",
|
||||
"cloneVM": "秒级派生副本 (CoW)",
|
||||
"connGroup": "连接",
|
||||
"copyScreenshot": "截屏并复制",
|
||||
"cores": "{n, plural, other {# 核}}",
|
||||
"deleteConfirm": "删除",
|
||||
"deleteDesc": "配置和虚拟磁盘会被移除,无法撤销",
|
||||
"deleteDescKeep": "只移除配置,磁盘文件留在原目录",
|
||||
"deleteKeepFiles": "保留磁盘文件",
|
||||
"deleteTitle": "删除「{name}」?",
|
||||
"deliverFileShort": "发送文件…",
|
||||
"detachGuestTools": "弹出工具盘",
|
||||
"diagAhciUpgradeHint": "系统盘还是 SATA,改成 NVMe 读写更快",
|
||||
"diagBackingChainBroken": "当前系统盘 CoW 派生链({depth} 层)存在缺失或无法读取的父镜像,请检查源虚拟机磁盘",
|
||||
"diagBackingChainWarn": "当前系统盘 CoW 派生链深度为 {depth} 层(≥ 2),未分配簇读穿透会拖慢小文件 I/O,建议合并为独立镜像或基于基础镜像重新派生",
|
||||
"diagExternalDriveWarn": "数据目录在外置或网络盘上({dir}),读写会明显变慢",
|
||||
"diagHighMemWarn": "宿主内存已用 {pct}%,虚拟机可能会卡顿",
|
||||
"discardSuspend": "放弃挂起状态",
|
||||
"discardSuspendConfirm": "放弃并关机",
|
||||
"discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。",
|
||||
"discardSuspendTitle": "放弃「{name}」的挂起状态?",
|
||||
"displayNameEdit": "点按以修改显示名称",
|
||||
"displayNameEditEllipsis": "修改显示名称…",
|
||||
"displayNameLabel": "显示名称",
|
||||
"displayNameTip": "显示名称 · 虚拟机名称为 {name}(点按修改)",
|
||||
"dropFilesHint": "松开以投递到 macOS 共享目录",
|
||||
"enterFullscreen": "进入全屏",
|
||||
"enterRecovery": "进入恢复模式",
|
||||
"exitFullscreen": "退出全屏",
|
||||
"exportDiagnostics": "导出排障日志 (.zip)",
|
||||
"factBackingChain": "CoW 派生链",
|
||||
"factCPU": "处理器",
|
||||
"factDisk": "存储",
|
||||
"factGraphics": "图形",
|
||||
"factMemory": "内存",
|
||||
"failAttachInstaller": "挂载镜像失败",
|
||||
"failCloneVM": "派生 CoW 副本失败",
|
||||
"failDelete": "删除失败",
|
||||
"failDiscardSuspend": "放弃挂起状态失败",
|
||||
"failEject": "弹出安装盘失败",
|
||||
"failEnterRecovery": "进入恢复模式失败",
|
||||
"failExportDiagnostics": "导出排障日志失败",
|
||||
"failFinishInstall": "退出恢复模式失败",
|
||||
"failFocus": "无法定位虚拟机窗口",
|
||||
"failFullscreen": "无法切换全屏",
|
||||
"failGuestTools": "Guest Tools 操作失败",
|
||||
"failOpenFolder": "无法打开文件夹",
|
||||
"failRestart": "重启失败",
|
||||
"failResume": "恢复失败",
|
||||
"failScreenshot": "截屏失败",
|
||||
"failSnapshot": "恢复点操作失败",
|
||||
"failStart": "启动失败",
|
||||
"failStop": "关机失败",
|
||||
"failSuspend": "挂起失败",
|
||||
"failType": "键入失败",
|
||||
"failUpgradeNVMe": "升级到 NVMe 失败",
|
||||
"fieldAudio": "音频",
|
||||
"fieldCPUModel": "CPU 型号",
|
||||
"fieldController": "磁盘控制器",
|
||||
"fieldDir": "目录",
|
||||
"fieldDisk": "磁盘",
|
||||
"fieldGraphicsBackend": "图形后端",
|
||||
"fieldICD": "Vulkan ICD",
|
||||
"fieldKind": "类型",
|
||||
"fieldNetwork": "网络",
|
||||
"fieldVMName": "虚拟机名称",
|
||||
"finishInstall": "退出恢复模式",
|
||||
"gpuAuto": "自动选择 GPU",
|
||||
"gtInstall": "安装…",
|
||||
"gtInstallSub": "在 macOS 终端里运行",
|
||||
"gtNotInstalledDesc": "未安装:挂载工具盘后在 macOS 中运行安装命令",
|
||||
"gtStatusConnected": "已连接",
|
||||
"gtStatusEnabled": "已启用",
|
||||
"gtStatusNone": "未安装",
|
||||
"gtStatusOff": "已停用",
|
||||
"gtStatusOffTip": "Guest Tools 传输服务已在插件页停用,剪贴板、共享文件夹与防休眠都不可用",
|
||||
"gtStatusUpgrade": "需要更新",
|
||||
"gtStatusWaiting": "未连接",
|
||||
"gtStatusWaitingTip": "在 macOS 里运行安装命令后会自动连接",
|
||||
"gtUpdate": "更新…",
|
||||
"guestToolsModeSync": "文件同步模式",
|
||||
"guestToolsModeWebDAV": "WebDAV 挂载",
|
||||
"guestToolsPreventSleep": "防止 macOS 睡眠",
|
||||
"guestToolsSleepActive": "正在保持唤醒",
|
||||
"guestToolsTitle": "Guest Tools",
|
||||
"guestToolsUpgradeHint": "macOS 里的工具是旧版,重新运行安装命令即可升级",
|
||||
"guideBuiltIn1": "启动后在 OpenCore 引导菜单选择「Recovery」",
|
||||
"guideBuiltIn2": "恢复模式可以联网重装;要离线安装就点「挂载离线镜像」",
|
||||
"guideBuiltIn3": "完成后点「退出恢复模式」",
|
||||
"guideKindBuiltIn": "内置恢复",
|
||||
"guideKindOffline": "离线完整安装",
|
||||
"guideKindOnline": "在线恢复安装",
|
||||
"guideOffline1": "不要点「Reinstall macOS Tahoe」,从菜单栏打开「Utilities › Terminal」",
|
||||
"guideOffline2": "运行下面的命令(点键盘图标可直接键入)。它会把空白磁盘抹成 APFS 并开始安装,中途会重启几次:",
|
||||
"guideOffline3": "看到「设置助理」后,点「退出恢复模式」弹出安装盘并恢复网络",
|
||||
"guideStartHint": "启动后在虚拟机窗口查看安装引导",
|
||||
"guideStep1": "打开「磁盘工具」,选中最大的「QEMU HARDDISK Media」(看不到就选 View › Show All Devices),点 Erase:名称 Macintosh HD,格式 APFS,方案 GUID。抹除时可能停顿 10–30 秒,不要强制关机",
|
||||
"guideStep2": "回到恢复主界面,选「Reinstall macOS Tahoe」,装到刚抹好的磁盘,中途会重启几次",
|
||||
"guideStep3": "看到「设置助理」后,点「退出恢复模式」弹出安装盘",
|
||||
"guideTitle": "恢复模式",
|
||||
"netOff": "无网络",
|
||||
"netShared": "共享网络",
|
||||
"onlineRecoveryConfirm": "拉取并挂载(约 1 GB)",
|
||||
"onlineRecoveryDesc": "本地没有恢复镜像。要从 Apple 下载约 1 GB 的恢复镜像并挂载到「{name}」吗?",
|
||||
"onlineRecoveryTitle": "拉取在线恢复镜像?",
|
||||
"openSharedFolder": "打开共享文件夹",
|
||||
"openShort": "打开",
|
||||
"pendingRestartHint": "重启虚拟机后生效",
|
||||
"pendingTitle": "下次启动生效",
|
||||
"pickRecoveryTitle": "选择离线镜像(.img / .dmg)",
|
||||
"restartToApply": "重启以应用",
|
||||
"resume": "恢复",
|
||||
"resumeUnavailable": "切换到支持挂起的内核后可恢复",
|
||||
"sendText": "发送文本到虚拟机…",
|
||||
"sendTextConfirm": "发送 (Ctrl+Enter)",
|
||||
"sendTextDesc": "支持中文、Emoji、宿主机输入法与语音输入,按 Ctrl+Enter 发送到 macOS 当前输入框。",
|
||||
"sendTextDescNoGT": "当前未连接 Guest Tools,仅支持英文/数字等美式键盘字符;安装 Guest Tools 后支持中文与任意文本。",
|
||||
"sendTextPlaceholder": "在这里输入或粘贴要发送到虚拟机的文字…",
|
||||
"sendTextTitle": "发送文本到「{name}」",
|
||||
"sharedFolder": "共享文件夹",
|
||||
"showInstallGuide": "显示安装引导",
|
||||
"showWindow": "显示窗口",
|
||||
"snapshotCreate": "创建恢复点",
|
||||
"snapshotDelete": "删除恢复点",
|
||||
"snapshotEmpty": "尚未创建恢复点,升级系统或大改环境前可先留档",
|
||||
"snapshotHint": "停机快照 · 非异地备份",
|
||||
"snapshotNamePlaceholder": "例如:升级 macOS 前",
|
||||
"snapshotRestore": "回滚",
|
||||
"snapshotRestoreDesc": "当前磁盘在此恢复点之后的改动将被覆盖,且无法撤销。",
|
||||
"snapshotRestoreTitle": "回滚到「{name}」?",
|
||||
"snapshotStopFirst": "停止虚拟机后才可管理恢复点",
|
||||
"snapshotsTitle": "恢复点",
|
||||
"softwareGraphics": "软件渲染",
|
||||
"specCPULiveTip": "处理器 {n} 核,当前占用 {pct}%",
|
||||
"specCPUTip": "{n, plural, other {处理器 # 核}}",
|
||||
"specDiskTip": "存储:{ctl}",
|
||||
"specDiskUsage": "{ctl} · 已用 {used},上限 {max}",
|
||||
"specGraphicsTip": "图形:{gfx}",
|
||||
"specLang": "语言",
|
||||
"specLangTip": "macOS 系统语言:{label}",
|
||||
"specLangTipDetail": "macOS 系统语言:{label}({detail})",
|
||||
"specMemLiveTip": "内存 {mem},虚拟机在宿主上占用 {used}",
|
||||
"specMemTip": "内存 {mem}",
|
||||
"specNetOffTip": "虚拟机没有网络",
|
||||
"specNetSSHTip": "与宿主共享网络连接,SSH 端口 {port}",
|
||||
"specNetTip": "与宿主共享网络连接",
|
||||
"sshMore": "SSH 工具",
|
||||
"sshOpenTerminal": "终端",
|
||||
"sshOpenVSCode": "用 VS Code 打开",
|
||||
"sshSetUser": "设置 SSH 用户名…",
|
||||
"sshUserDesc": "用于打开终端、写入 ~/.ssh/config 和 VS Code 直连(留空则连接时不带用户名)",
|
||||
"sshUserPlaceholder": "例如 admin",
|
||||
"sshUserTitle": "SSH 登录用户名",
|
||||
"sshWriteConfig": "写入 ~/.ssh/config",
|
||||
"state_broken": "出错",
|
||||
"state_creating": "正在创建",
|
||||
"state_driver_unavailable": "驱动不可用",
|
||||
"state_resuming": "恢复中",
|
||||
"state_running": "运行中",
|
||||
"state_starting": "启动中",
|
||||
"state_stopped": "已停止",
|
||||
"state_stopping": "停止中",
|
||||
"state_suspended": "已挂起",
|
||||
"state_suspending": "挂起中",
|
||||
"suspend": "挂起",
|
||||
"suspendedGuestToolsHint": "恢复或放弃挂起状态后可更改",
|
||||
"suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。",
|
||||
"suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。",
|
||||
"suspendedNoticeTitle": "已保存运行状态",
|
||||
"suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置",
|
||||
"techInfo": "技术信息",
|
||||
"toastCloned": "已派生 CoW 副本「{name}」",
|
||||
"toastDeleted": "已删除 {name}",
|
||||
"toastDiagExported": "已导出脱敏排障日志包 (.zip)",
|
||||
"toastDiscardSuspend": "已放弃 {name} 的挂起状态",
|
||||
"toastEjected": "已弹出安装盘",
|
||||
"toastEnterRecovery": "已进入恢复模式,启动后可在引导菜单选 Recovery",
|
||||
"toastEnterRecoveryNextStart": "已准备进入恢复模式,重启后显示引导菜单",
|
||||
"toastExitRecoveryNextStart": "已退出恢复模式,下次启动生效",
|
||||
"toastFileDelivered": "已发送 {name}",
|
||||
"toastFilesDelivered": "{n, plural, other {已投递 # 个文件到共享目录}}",
|
||||
"toastGuestToolsAttached": "已挂载 Guest Tools 工具盘(REIMSTOOLS)",
|
||||
"toastGuestToolsAttachedNextStart": "已挂载 Guest Tools 工具盘,重启虚拟机后在访达中可见",
|
||||
"toastGuestToolsDetached": "已弹出工具盘",
|
||||
"toastGuestToolsDetachedNextStart": "已弹出工具盘,下次启动生效",
|
||||
"toastInstallFinished": "已退出恢复模式",
|
||||
"toastInstallerAttached": "已挂载离线镜像:{name}",
|
||||
"toastInstallerAttachedNextStart": "已挂载离线镜像(重启后生效):{name}",
|
||||
"toastNVMeNextStart": "已切换为 NVMe,下次启动生效",
|
||||
"toastNVMeReady": "已升级到 NVMe 磁盘控制器",
|
||||
"toastOnlineRecoveryAttached": "在线恢复镜像已挂载到 {name}",
|
||||
"toastOnlineRecoveryStarted": "正在拉取在线恢复镜像(约 1 GB),完成后自动挂载",
|
||||
"toastPreventSleepOff": "已关闭 macOS 防休眠守护",
|
||||
"toastPreventSleepOn": "已开启 macOS 防休眠守护",
|
||||
"toastResumed": "{name} 已恢复",
|
||||
"toastScreenshotCopied": "已复制虚拟机画面",
|
||||
"toastSnapshotCreated": "已创建恢复点 {name}",
|
||||
"toastSnapshotDeleted": "已删除恢复点 {name}",
|
||||
"toastSnapshotRestored": "已回滚到 {name}",
|
||||
"toastStopped": "{name} 已关机",
|
||||
"toastSuspended": "{name} 已挂起",
|
||||
"toastTyped": "{n, plural, other {已键入 # 个字符}}",
|
||||
"toggleFullscreen": "切换全屏",
|
||||
"typeClipboard": "粘贴剪贴板到虚拟机",
|
||||
"typeIntoVM": "在虚拟机里键入",
|
||||
"typeUntypeable": "未连接 Guest Tools 时仅支持美式键盘 ASCII 字符;安装并连接 Guest Tools 后即可输入中文与任意 Unicode 文本",
|
||||
"upgradeToNVMe": "升级到 NVMe",
|
||||
}
|
||||
|
||||
export const vmEn: Record<string, string> = {
|
||||
"attachGuestTools": "Attach Guest Tools",
|
||||
"attachInstaller": "Attach offline image",
|
||||
"brokenHint": "This VM’s configuration can’t be read",
|
||||
"cloneConfirm": "Create clone",
|
||||
"cloneDesc": "Makes an instant copy-on-write clone that takes almost no space and leaves the original untouched",
|
||||
"cloneNameLabel": "New VM name",
|
||||
"cloneTitle": "Derive CoW clone from “{name}”",
|
||||
"cloneVM": "Derive CoW clone",
|
||||
"connGroup": "Connection",
|
||||
"copyScreenshot": "Copy screenshot",
|
||||
"cores": "{n, plural, one {# core} other {# cores}}",
|
||||
"deleteConfirm": "Delete",
|
||||
"deleteDesc": "Its configuration and virtual disk are removed. This can’t be undone",
|
||||
"deleteDescKeep": "Only the configuration is removed; disk files stay in place",
|
||||
"deleteKeepFiles": "Keep disk files",
|
||||
"deleteTitle": "Delete \"{name}\"?",
|
||||
"deliverFileShort": "Send File…",
|
||||
"detachGuestTools": "Eject tools disk",
|
||||
"diagAhciUpgradeHint": "The system disk still uses SATA; NVMe is faster",
|
||||
"diagBackingChainBroken": "System disk CoW backing chain ({depth} layers) has a missing or unreadable parent image; check the source VM disk",
|
||||
"diagBackingChainWarn": "System disk CoW backing chain is {depth} layers deep (\u003e= 2); read-through slows small-file I/O — consider flattening or re-deriving from the base image",
|
||||
"diagExternalDriveWarn": "The data folder is on an external or network drive ({dir}); disk access will be slow",
|
||||
"diagHighMemWarn": "Host memory is {pct}% used; the VM may stutter",
|
||||
"discardSuspend": "Discard saved state",
|
||||
"discardSuspendConfirm": "Discard \u0026 Power Off",
|
||||
"discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.",
|
||||
"discardSuspendTitle": "Discard saved state for “{name}”?",
|
||||
"displayNameEdit": "Click to change the display name",
|
||||
"displayNameEditEllipsis": "Change Display Name…",
|
||||
"displayNameLabel": "Display name",
|
||||
"displayNameTip": "Display name · VM name is {name} (click to change)",
|
||||
"dropFilesHint": "Drop files to send to macOS shared folder",
|
||||
"enterFullscreen": "Enter full screen",
|
||||
"enterRecovery": "Enter recovery mode",
|
||||
"exitFullscreen": "Exit full screen",
|
||||
"exportDiagnostics": "Export diagnostics (.zip)",
|
||||
"factBackingChain": "CoW Backing Chain",
|
||||
"factCPU": "CPU",
|
||||
"factDisk": "Storage",
|
||||
"factGraphics": "Graphics",
|
||||
"factMemory": "Memory",
|
||||
"failAttachInstaller": "Couldn’t attach the image",
|
||||
"failCloneVM": "Couldn’t create CoW clone",
|
||||
"failDelete": "Couldn’t delete",
|
||||
"failDiscardSuspend": "Couldn’t discard saved state",
|
||||
"failEject": "Couldn’t eject the installer",
|
||||
"failEnterRecovery": "Couldn’t enter recovery mode",
|
||||
"failExportDiagnostics": "Couldn’t export diagnostics",
|
||||
"failFinishInstall": "Couldn’t exit recovery mode",
|
||||
"failFocus": "Could not focus VM window",
|
||||
"failFullscreen": "Couldn’t toggle full screen",
|
||||
"failGuestTools": "Guest Tools operation failed",
|
||||
"failOpenFolder": "Couldn’t open the folder",
|
||||
"failRestart": "Couldn’t restart",
|
||||
"failResume": "Couldn’t resume",
|
||||
"failScreenshot": "Screenshot failed",
|
||||
"failSnapshot": "Restore point failed",
|
||||
"failStart": "Couldn’t start",
|
||||
"failStop": "Couldn’t shut down",
|
||||
"failSuspend": "Couldn’t suspend",
|
||||
"failType": "Couldn’t type into the VM",
|
||||
"failUpgradeNVMe": "Couldn’t upgrade to NVMe",
|
||||
"fieldAudio": "Audio",
|
||||
"fieldCPUModel": "CPU model",
|
||||
"fieldController": "Disk controller",
|
||||
"fieldDir": "Directory",
|
||||
"fieldDisk": "Disk",
|
||||
"fieldGraphicsBackend": "Graphics backend",
|
||||
"fieldICD": "Vulkan ICD",
|
||||
"fieldKind": "Kind",
|
||||
"fieldNetwork": "Network",
|
||||
"fieldVMName": "VM name",
|
||||
"finishInstall": "Exit recovery mode",
|
||||
"gpuAuto": "Automatic GPU",
|
||||
"gtInstall": "Install…",
|
||||
"gtInstallSub": "Run in macOS Terminal",
|
||||
"gtNotInstalledDesc": "Not installed: attach the tools disk and run the installer in macOS",
|
||||
"gtStatusConnected": "Connected",
|
||||
"gtStatusEnabled": "Enabled",
|
||||
"gtStatusNone": "Not installed",
|
||||
"gtStatusOff": "Off",
|
||||
"gtStatusOffTip": "Guest Tools Transport is turned off on the Plugins page; clipboard, shared folders and keep-awake are unavailable",
|
||||
"gtStatusUpgrade": "Update needed",
|
||||
"gtStatusWaiting": "Not connected",
|
||||
"gtStatusWaitingTip": "Connects once the install command has run in macOS",
|
||||
"gtUpdate": "Update…",
|
||||
"guestToolsModeSync": "Folder sync",
|
||||
"guestToolsModeWebDAV": "WebDAV mount",
|
||||
"guestToolsPreventSleep": "Prevent macOS sleep",
|
||||
"guestToolsSleepActive": "Keeping macOS awake",
|
||||
"guestToolsTitle": "Guest Tools",
|
||||
"guestToolsUpgradeHint": "The tools in macOS are out of date; run the install command again to update",
|
||||
"guideBuiltIn1": "After starting, choose “Recovery” in the OpenCore boot menu",
|
||||
"guideBuiltIn2": "Recovery can reinstall over the network; for an offline install, click “Attach offline image”",
|
||||
"guideBuiltIn3": "When you are done, click “Exit recovery mode”",
|
||||
"guideKindBuiltIn": "Built-in recovery",
|
||||
"guideKindOffline": "Offline install",
|
||||
"guideKindOnline": "Online recovery",
|
||||
"guideOffline1": "Don’t click “Reinstall macOS Tahoe”; open Utilities › Terminal from the menu bar",
|
||||
"guideOffline2": "Run the command below (the keyboard icon types it for you). It erases the blank disk as APFS and starts the install; it restarts a few times:",
|
||||
"guideOffline3": "When Setup Assistant appears, click “Exit recovery mode” to eject the installer and turn the network back on",
|
||||
"guideStartHint": "Start the VM to open the installation guide in its window",
|
||||
"guideStep1": "Open Disk Utility and select the largest “QEMU HARDDISK Media” (View › Show All Devices if it is hidden). Click Erase: name Macintosh HD, format APFS, scheme GUID. It may pause for 10–30 seconds; don’t force it off",
|
||||
"guideStep2": "Back in Recovery, choose “Reinstall macOS Tahoe” and install to the disk you erased. It restarts a few times",
|
||||
"guideStep3": "When Setup Assistant appears, click “Exit recovery mode” to eject the installer",
|
||||
"guideTitle": "Recovery mode",
|
||||
"netOff": "No network",
|
||||
"netShared": "Shared network",
|
||||
"onlineRecoveryConfirm": "Download \u0026 attach (~1 GB)",
|
||||
"onlineRecoveryDesc": "No recovery image is on this PC. Download Apple’s recovery image (about 1 GB) and attach it to “{name}”?",
|
||||
"onlineRecoveryTitle": "Download online recovery image?",
|
||||
"openSharedFolder": "Open shared folder",
|
||||
"openShort": "Open",
|
||||
"pendingRestartHint": "Takes effect after a restart",
|
||||
"pendingTitle": "Applies on next start",
|
||||
"pickRecoveryTitle": "Choose an offline image (.img / .dmg)",
|
||||
"restartToApply": "Restart to apply",
|
||||
"resume": "Resume",
|
||||
"resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM",
|
||||
"sendText": "Send text to VM…",
|
||||
"sendTextConfirm": "Send (Ctrl+Enter)",
|
||||
"sendTextDesc": "Supports Chinese, emoji, host IME, and dictation. Press Ctrl+Enter to inject into the focused macOS field.",
|
||||
"sendTextDescNoGT": "Guest Tools is not connected; only US-keyboard ASCII characters are supported until Guest Tools is connected.",
|
||||
"sendTextPlaceholder": "Type or paste text to send to the VM…",
|
||||
"sendTextTitle": "Send text to “{name}”",
|
||||
"sharedFolder": "Shared folder",
|
||||
"showInstallGuide": "Show install guide",
|
||||
"showWindow": "Show window",
|
||||
"snapshotCreate": "New restore point",
|
||||
"snapshotDelete": "Delete restore point",
|
||||
"snapshotEmpty": "No restore points yet — save one before OS updates or major changes",
|
||||
"snapshotHint": "Offline snapshots · Not a backup",
|
||||
"snapshotNamePlaceholder": "e.g. before-macos-update",
|
||||
"snapshotRestore": "Restore",
|
||||
"snapshotRestoreDesc": "Disk changes made after this restore point will be overwritten and cannot be undone.",
|
||||
"snapshotRestoreTitle": "Restore \"{name}\"?",
|
||||
"snapshotStopFirst": "Stop the VM before managing restore points",
|
||||
"snapshotsTitle": "Restore points",
|
||||
"softwareGraphics": "Software rendering",
|
||||
"specCPULiveTip": "{n, plural, one {# processor core, {pct}% in use} other {# processor cores, {pct}% in use}}",
|
||||
"specCPUTip": "{n, plural, one {# processor core} other {# processor cores}}",
|
||||
"specDiskTip": "Storage: {ctl}",
|
||||
"specDiskUsage": "{ctl} · {used} of {max} used",
|
||||
"specGraphicsTip": "Graphics: {gfx}",
|
||||
"specLang": "Language",
|
||||
"specLangTip": "macOS system language: {label}",
|
||||
"specLangTipDetail": "macOS system language: {label} ({detail})",
|
||||
"specMemLiveTip": "{mem} memory; the VM uses {used} on this PC",
|
||||
"specMemTip": "{mem} memory",
|
||||
"specNetOffTip": "The VM has no network",
|
||||
"specNetSSHTip": "Shares this PC’s network connection; SSH on port {port}",
|
||||
"specNetTip": "Shares this PC’s network connection",
|
||||
"sshMore": "SSH tools",
|
||||
"sshOpenTerminal": "Terminal",
|
||||
"sshOpenVSCode": "Open in VS Code",
|
||||
"sshSetUser": "Set SSH username…",
|
||||
"sshUserDesc": "Used for Terminal, ~/.ssh/config, and VS Code Remote-SSH (leave empty to omit user)",
|
||||
"sshUserPlaceholder": "e.g. admin",
|
||||
"sshUserTitle": "SSH login username",
|
||||
"sshWriteConfig": "Write ~/.ssh/config",
|
||||
"state_broken": "Error",
|
||||
"state_creating": "Creating",
|
||||
"state_driver_unavailable": "Driver unavailable",
|
||||
"state_resuming": "Resuming",
|
||||
"state_running": "Running",
|
||||
"state_starting": "Starting",
|
||||
"state_stopped": "Stopped",
|
||||
"state_stopping": "Stopping",
|
||||
"state_suspended": "Suspended",
|
||||
"state_suspending": "Suspending",
|
||||
"suspend": "Suspend",
|
||||
"suspendedGuestToolsHint": "Resume or discard saved state to make changes",
|
||||
"suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.",
|
||||
"suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.",
|
||||
"suspendedNoticeTitle": "Saved state ready",
|
||||
"suspendedSettingsHint": "Resume or discard saved state before changing settings",
|
||||
"techInfo": "Technical details",
|
||||
"toastCloned": "CoW clone “{name}” created",
|
||||
"toastDeleted": "{name} deleted",
|
||||
"toastDiagExported": "Redacted diagnostics archive exported (.zip)",
|
||||
"toastDiscardSuspend": "Discarded saved state for {name}",
|
||||
"toastEjected": "Installer ejected",
|
||||
"toastEnterRecovery": "Recovery mode ready — pick Recovery in OpenCore on next start",
|
||||
"toastEnterRecoveryNextStart": "Recovery mode ready — restart to open the boot menu",
|
||||
"toastExitRecoveryNextStart": "Exited recovery mode — applies at next start",
|
||||
"toastFileDelivered": "Sent {name}",
|
||||
"toastFilesDelivered": "{n, plural, one {Sent # file to the shared folder} other {Sent # files to the shared folder}}",
|
||||
"toastGuestToolsAttached": "Guest Tools disk (REIMSTOOLS) attached",
|
||||
"toastGuestToolsAttachedNextStart": "Guest Tools disk attached — restart VM to mount in Finder",
|
||||
"toastGuestToolsDetached": "Tools disk ejected",
|
||||
"toastGuestToolsDetachedNextStart": "Tools disk ejected; applies on next start",
|
||||
"toastInstallFinished": "Exited recovery mode",
|
||||
"toastInstallerAttached": "Offline image attached: {name}",
|
||||
"toastInstallerAttachedNextStart": "Offline image attached (applies on restart): {name}",
|
||||
"toastNVMeNextStart": "Switched to NVMe — applies on next start",
|
||||
"toastNVMeReady": "Upgraded disk controller to NVMe",
|
||||
"toastOnlineRecoveryAttached": "Online recovery image attached to {name}",
|
||||
"toastOnlineRecoveryStarted": "Downloading online recovery image (~1 GB); will attach when ready",
|
||||
"toastPreventSleepOff": "Prevent-sleep guard disabled",
|
||||
"toastPreventSleepOn": "Prevent-sleep guard enabled",
|
||||
"toastResumed": "{name} resumed",
|
||||
"toastScreenshotCopied": "VM screenshot copied",
|
||||
"toastSnapshotCreated": "Created restore point {name}",
|
||||
"toastSnapshotDeleted": "Deleted restore point {name}",
|
||||
"toastSnapshotRestored": "Restored to {name}",
|
||||
"toastStopped": "{name} shut down",
|
||||
"toastSuspended": "{name} suspended",
|
||||
"toastTyped": "{n, plural, one {Typed # character} other {Typed # characters}}",
|
||||
"toggleFullscreen": "Toggle full screen",
|
||||
"typeClipboard": "Send clipboard to VM",
|
||||
"typeIntoVM": "Type into the VM",
|
||||
"typeUntypeable": "Only US-keyboard ASCII characters work without Guest Tools; connect Guest Tools for Chinese and Unicode text",
|
||||
"upgradeToNVMe": "Upgrade to NVMe",
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
import { registerBuiltinDomain } from '../runtime'
|
||||
|
||||
export const wizardZh: Record<string, string> = {
|
||||
"commandToggle": "等效命令",
|
||||
"commandToggleHint": "在终端运行下面这条命令效果相同",
|
||||
"createNow": "创建",
|
||||
"createStartedHint": "创建后窗口会关闭,进度在底部状态栏",
|
||||
"issuesCount": "{n, plural, other {有 # 项需要修改}}",
|
||||
"offlineCached": "已下载",
|
||||
"offlineDownloading": "下载中",
|
||||
"offlineHint": "约 20 GB,安装时不联网",
|
||||
"offlineListFailedDetail": "无法读取 Apple 的版本列表:{err}",
|
||||
"offlineLoading": "正在读取 Apple 的版本列表…",
|
||||
"offlineQueued": "排队中",
|
||||
"offlineSpaceWarn": "可用空间 {free} GB,下载这个版本需要约 {need} GB",
|
||||
"runtimeAlpha": "接收 Alpha 版",
|
||||
"runtimeAlphaHint": "Alpha 版由 CI 每天从上游自动构建,未经真实宿主冒烟测试",
|
||||
"runtimeChannel_alpha": "Alpha 版",
|
||||
"runtimeChannel_stable": "稳定版",
|
||||
"runtimeCurrent": "当前运行时",
|
||||
"runtimeInstall": "安装",
|
||||
"runtimeLatest": "最新:{v}",
|
||||
"runtimeLookupFailed": "无法读取运行时列表",
|
||||
"runtimeLookupRateLimit": "GitHub 接口限流(HTTP 403),请稍后重试或手动导入",
|
||||
"runtimeNewer": "有新版本:{v}",
|
||||
"runtimeNoneOnChannel": "这个通道还没有发布运行时",
|
||||
"runtimeOnline": "在线安装",
|
||||
"runtimeRetry": "重试",
|
||||
"runtimeUpToDate": "已是最新",
|
||||
"runtimeUpdate": "更新",
|
||||
"setupCheck": "环境",
|
||||
"setupContinue": "继续",
|
||||
"setupDesc": "虚拟机、安装包和运行时都放在这里",
|
||||
"setupDone": "完成",
|
||||
"setupExternal": "外置盘",
|
||||
"setupFree": "可用 {n} GB",
|
||||
"setupGPU": "显卡(Vulkan)",
|
||||
"setupImport": "导入本地包…",
|
||||
"setupLangPackFailed": "语言包安装失败,可稍后在插件页重试",
|
||||
"setupLangPackOffer": "同时安装「{name}」",
|
||||
"setupLater": "稍后",
|
||||
"setupNoGPU": "没有检测到 Vulkan 显卡,只能用软件渲染",
|
||||
"setupOther": "其他位置…",
|
||||
"setupRecMem": "推荐 {n} GB",
|
||||
"setupRecommended": "推荐",
|
||||
"setupReuse": "这里已有 Reims-Go 数据,会直接沿用",
|
||||
"setupRuntimeDesc": "运行虚拟机所需的 QEMU 与 reims-ctl,从 GitHub 下载并校验",
|
||||
"setupRuntimeTitle": "检查环境并安装运行时",
|
||||
"setupSystem": "系统盘",
|
||||
"setupTitle": "选择数据目录",
|
||||
"setupWarnExternal": "外置盘拔出时,正在运行的虚拟机会损坏",
|
||||
"setupWarnSpace": "可用空间不足 60 GB:一个离线安装包约 20 GB,虚拟磁盘会随使用增长",
|
||||
"setupWarnSystem": "放在系统盘,空间紧张时会影响 Windows",
|
||||
"srcAppleSub": "恢复镜像,系统在装机时在线下载",
|
||||
"srcAppleTitle": "从 Apple 下载",
|
||||
"srcDiskSub": "已装好 macOS 的 .qcow2 等磁盘",
|
||||
"srcDiskTitle": "已有磁盘",
|
||||
"srcInstallerSub": "本机上的 .img 或 .dmg",
|
||||
"srcInstallerTitle": "安装镜像",
|
||||
"srcOfflineSub": "完整安装包,装机时不联网",
|
||||
"srcOfflineTitle": "离线安装包",
|
||||
"step1": "系统来源",
|
||||
"step2": "处理器与内存",
|
||||
"step3": "存储",
|
||||
"step4": "图形与选项",
|
||||
"step5": "确认",
|
||||
"summaryAppleSource": "从 Apple 下载 · {v}",
|
||||
"summaryDefaultDir": "数据目录(默认)",
|
||||
"summaryDiskGrow": "{size},按实际占用增长",
|
||||
"summaryDiskSource": "已有磁盘 · {file}",
|
||||
"summaryEdit": "修改",
|
||||
"summaryInstallerSource": "本地安装器 · {file}",
|
||||
"summaryLogs": "图形与串口日志",
|
||||
"summaryOfflineSource": "离线安装包 · macOS {v}",
|
||||
"summaryOn": "开",
|
||||
"summarySSH": "SSH 转发",
|
||||
"summarySSHPort": "端口 {n}",
|
||||
"summarySource": "来源",
|
||||
"validationChecking": "正在检查…",
|
||||
"validationPassed": "可以创建",
|
||||
"vulkanProbeFailed": "Vulkan 探测失败({detail})。请运行 vulkaninfo --summary 检查驱动。",
|
||||
"wizChooseFile": "选择…",
|
||||
"wizNoFile": "还没有选择文件",
|
||||
"wizOptions": "选项",
|
||||
"wizardBasics": "基本信息",
|
||||
"wizardDriverGroup": "客体平台驱动",
|
||||
"wizardDriverType": "驱动类型",
|
||||
"wizardTitle": "新建虚拟机",
|
||||
}
|
||||
|
||||
export const wizardEn: Record<string, string> = {
|
||||
"commandToggle": "Equivalent command",
|
||||
"commandToggleHint": "Running this in a terminal does the same thing",
|
||||
"createNow": "Create",
|
||||
"createStartedHint": "The window closes once creation starts; progress shows in the status bar",
|
||||
"issuesCount": "{n, plural, one {# issue to fix} other {# issues to fix}}",
|
||||
"offlineCached": "Downloaded",
|
||||
"offlineDownloading": "Downloading",
|
||||
"offlineHint": "About 20 GB; installs with no network",
|
||||
"offlineListFailedDetail": "Couldn’t read Apple’s release list: {err}",
|
||||
"offlineLoading": "Reading Apple’s release list…",
|
||||
"offlineQueued": "Queued",
|
||||
"offlineSpaceWarn": "{free} GB free; this release needs about {need} GB",
|
||||
"runtimeAlpha": "Receive alpha builds",
|
||||
"runtimeAlphaHint": "Built daily from upstream by CI; not smoke-tested on a real host",
|
||||
"runtimeChannel_alpha": "Alpha",
|
||||
"runtimeChannel_stable": "Stable",
|
||||
"runtimeCurrent": "Current runtime",
|
||||
"runtimeInstall": "Install",
|
||||
"runtimeLatest": "Latest: {v}",
|
||||
"runtimeLookupFailed": "Couldn’t read the runtime list",
|
||||
"runtimeLookupRateLimit": "GitHub API rate limit reached (HTTP 403); retry later or import a local bundle",
|
||||
"runtimeNewer": "New version: {v}",
|
||||
"runtimeNoneOnChannel": "No runtime published on this channel yet",
|
||||
"runtimeOnline": "Online install",
|
||||
"runtimeRetry": "Retry",
|
||||
"runtimeUpToDate": "Up to date",
|
||||
"runtimeUpdate": "Update",
|
||||
"setupCheck": "Host",
|
||||
"setupContinue": "Continue",
|
||||
"setupDesc": "VMs, installers and runtimes all live here",
|
||||
"setupDone": "Done",
|
||||
"setupExternal": "External",
|
||||
"setupFree": "{n} GB free",
|
||||
"setupGPU": "Graphics (Vulkan)",
|
||||
"setupImport": "Import a local package…",
|
||||
"setupLangPackFailed": "Could not install the language pack; you can retry from the Plugins page",
|
||||
"setupLangPackOffer": "Also install “{name}”",
|
||||
"setupLater": "Later",
|
||||
"setupNoGPU": "No Vulkan GPU found; only software rendering will work",
|
||||
"setupOther": "Other location…",
|
||||
"setupRecMem": "{n} GB recommended",
|
||||
"setupRecommended": "Recommended",
|
||||
"setupReuse": "This folder already has Reims-Go data; it will be reused",
|
||||
"setupRuntimeDesc": "QEMU and reims-ctl, downloaded from GitHub and verified",
|
||||
"setupRuntimeTitle": "Check the host and install the runtime",
|
||||
"setupSystem": "System drive",
|
||||
"setupTitle": "Choose a data folder",
|
||||
"setupWarnExternal": "Unplugging an external drive corrupts running VMs",
|
||||
"setupWarnSpace": "Under 60 GB free: an offline installer is about 20 GB and virtual disks grow with use",
|
||||
"setupWarnSystem": "On the system drive, low space can affect Windows",
|
||||
"srcAppleSub": "A recovery image; macOS downloads during install",
|
||||
"srcAppleTitle": "Download from Apple",
|
||||
"srcDiskSub": "A .qcow2 or other disk with macOS installed",
|
||||
"srcDiskTitle": "Existing disk",
|
||||
"srcInstallerSub": "An .img or .dmg on this PC",
|
||||
"srcInstallerTitle": "Installer image",
|
||||
"srcOfflineSub": "The full installer; installs with no network",
|
||||
"srcOfflineTitle": "Offline installer",
|
||||
"step1": "Source",
|
||||
"step2": "CPU \u0026 memory",
|
||||
"step3": "Storage",
|
||||
"step4": "Graphics \u0026 options",
|
||||
"step5": "Review",
|
||||
"summaryAppleSource": "Download from Apple · {v}",
|
||||
"summaryDefaultDir": "Data folder (default)",
|
||||
"summaryDiskGrow": "{size}, grows with use",
|
||||
"summaryDiskSource": "Existing disk · {file}",
|
||||
"summaryEdit": "Edit",
|
||||
"summaryInstallerSource": "Local installer · {file}",
|
||||
"summaryLogs": "Graphics \u0026 serial logs",
|
||||
"summaryOfflineSource": "Offline installer · macOS {v}",
|
||||
"summaryOn": "On",
|
||||
"summarySSH": "SSH forwarding",
|
||||
"summarySSHPort": "Port {n}",
|
||||
"summarySource": "Source",
|
||||
"validationChecking": "Checking…",
|
||||
"validationPassed": "Ready to create",
|
||||
"vulkanProbeFailed": "Vulkan probe failed ({detail}). Run vulkaninfo --summary to check the driver.",
|
||||
"wizChooseFile": "Choose…",
|
||||
"wizNoFile": "No file chosen",
|
||||
"wizOptions": "Options",
|
||||
"wizardBasics": "Basics",
|
||||
"wizardDriverGroup": "Guest driver",
|
||||
"wizardDriverType": "Driver",
|
||||
"wizardTitle": "New virtual machine",
|
||||
}
|
||||
|
||||
registerBuiltinDomain(wizardZh, wizardEn)
|
||||
@@ -0,0 +1,376 @@
|
||||
// Zero-dependency isomorphic lightweight ICU MessageFormat evaluator + en-XA pseudo-localizer.
|
||||
// Matches internal/i18n/icu.go 1:1 while delegating plural selection & number formatting
|
||||
// to native zero-bundle-cost browser Intl APIs.
|
||||
|
||||
export type ICUVars = Record<string, string | number | boolean | undefined | null>
|
||||
|
||||
type ICUNode =
|
||||
| { kind: 'text'; text: string }
|
||||
| { kind: 'pound' }
|
||||
| { kind: 'var'; name: string }
|
||||
| { kind: 'number'; name: string; precision: number }
|
||||
| { kind: 'plural' | 'select'; name: string; branches: Array<{ selector: string; nodes: ICUNode[] }> }
|
||||
|
||||
const astCache = new Map<string, ICUNode[] | null>()
|
||||
const pluralRulesCache = new Map<string, Intl.PluralRules>()
|
||||
const numberFormatCache = new Map<string, Intl.NumberFormat>()
|
||||
|
||||
function getPluralRules(locale: string): Intl.PluralRules {
|
||||
const key = locale === 'en-XA' ? 'en-US' : locale
|
||||
let pr = pluralRulesCache.get(key)
|
||||
if (!pr) {
|
||||
try {
|
||||
pr = new Intl.PluralRules(key)
|
||||
} catch {
|
||||
pr = new Intl.PluralRules('en-US')
|
||||
}
|
||||
pluralRulesCache.set(key, pr)
|
||||
}
|
||||
return pr
|
||||
}
|
||||
|
||||
export function formatLocaleNumber(locale: string, value: number, precision = -1): string {
|
||||
const cleanLoc = locale === 'en-XA' ? 'en-US' : locale
|
||||
const cacheKey = `${cleanLoc}:${precision}`
|
||||
let nf = numberFormatCache.get(cacheKey)
|
||||
if (!nf) {
|
||||
const opts: Intl.NumberFormatOptions =
|
||||
precision >= 0
|
||||
? { minimumFractionDigits: precision, maximumFractionDigits: precision, useGrouping: false }
|
||||
: { useGrouping: false }
|
||||
try {
|
||||
nf = new Intl.NumberFormat(cleanLoc, opts)
|
||||
} catch {
|
||||
nf = new Intl.NumberFormat('en-US', opts)
|
||||
}
|
||||
numberFormatCache.set(cacheKey, nf)
|
||||
}
|
||||
return nf.format(value)
|
||||
}
|
||||
|
||||
const MAX_ICU_DEPTH = 16
|
||||
const MAX_ICU_TEMPLATE_LEN = 16384
|
||||
|
||||
export function parseICU(tmpl: string): ICUNode[] | null {
|
||||
if (tmpl.length > MAX_ICU_TEMPLATE_LEN) return null
|
||||
if (astCache.has(tmpl)) {
|
||||
return astCache.get(tmpl) ?? null
|
||||
}
|
||||
let pos = 0
|
||||
const len = tmpl.length
|
||||
|
||||
const skipWS = () => {
|
||||
while (pos < len) {
|
||||
const c = tmpl.charCodeAt(pos)
|
||||
if (c === 32 || c === 9 || c === 10 || c === 13) pos++
|
||||
else break
|
||||
}
|
||||
}
|
||||
|
||||
const readIdent = (): string => {
|
||||
const start = pos
|
||||
while (pos < len) {
|
||||
const c = tmpl.charCodeAt(pos)
|
||||
if (
|
||||
(c >= 97 && c <= 122) ||
|
||||
(c >= 65 && c <= 90) ||
|
||||
(c >= 48 && c <= 57) ||
|
||||
c === 95 || // _
|
||||
c === 45 || // -
|
||||
c === 46 || // .
|
||||
c === 61 // =
|
||||
) {
|
||||
pos++
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
return tmpl.slice(start, pos)
|
||||
}
|
||||
|
||||
const parseNodes = (stopAtBrace: boolean, inPlural: boolean, depth: number): ICUNode[] | null => {
|
||||
if (depth > MAX_ICU_DEPTH) return null
|
||||
const nodes: ICUNode[] = []
|
||||
let buf = ''
|
||||
const flush = () => {
|
||||
if (buf.length > 0) {
|
||||
nodes.push({ kind: 'text', text: buf })
|
||||
buf = ''
|
||||
}
|
||||
}
|
||||
|
||||
while (pos < len) {
|
||||
const ch = tmpl[pos]
|
||||
if (ch === "'") {
|
||||
if (pos + 1 < len && tmpl[pos + 1] === "'") {
|
||||
buf += "'"
|
||||
pos += 2
|
||||
continue
|
||||
}
|
||||
const next = pos + 1 < len ? tmpl[pos + 1] : ''
|
||||
if (next === '{' || next === '}' || (inPlural && next === '#')) {
|
||||
pos++
|
||||
while (pos < len) {
|
||||
if (tmpl[pos] === "'") {
|
||||
if (pos + 1 < len && tmpl[pos + 1] === "'") {
|
||||
buf += "'"
|
||||
pos += 2
|
||||
continue
|
||||
}
|
||||
pos++
|
||||
break
|
||||
}
|
||||
buf += tmpl[pos++]
|
||||
}
|
||||
continue
|
||||
}
|
||||
buf += "'"
|
||||
pos++
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === '}') {
|
||||
if (stopAtBrace) {
|
||||
flush()
|
||||
return nodes
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
if (ch === '#' && inPlural) {
|
||||
flush()
|
||||
nodes.push({ kind: 'pound' })
|
||||
pos++
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === '{') {
|
||||
flush()
|
||||
const node = parsePlaceholder(inPlural, depth + 1)
|
||||
if (!node) return null
|
||||
nodes.push(node)
|
||||
continue
|
||||
}
|
||||
|
||||
buf += ch
|
||||
pos++
|
||||
}
|
||||
|
||||
if (stopAtBrace) return null
|
||||
flush()
|
||||
return nodes
|
||||
}
|
||||
|
||||
const parsePlaceholder = (parentInPlural: boolean, depth: number): ICUNode | null => {
|
||||
if (depth > MAX_ICU_DEPTH) return null
|
||||
pos++ // skip '{'
|
||||
skipWS()
|
||||
const name = readIdent()
|
||||
if (!name) return null
|
||||
skipWS()
|
||||
if (pos < len && tmpl[pos] === '}') {
|
||||
pos++
|
||||
return { kind: 'var', name }
|
||||
}
|
||||
if (pos >= len || tmpl[pos] !== ',') return null
|
||||
pos++
|
||||
skipWS()
|
||||
const fn = readIdent()
|
||||
skipWS()
|
||||
|
||||
if (fn === 'number') {
|
||||
let precision = -1
|
||||
if (pos < len && tmpl[pos] === ',') {
|
||||
pos++
|
||||
skipWS()
|
||||
const style = readIdent()
|
||||
if (/^\.[0-6]$/.test(style)) {
|
||||
precision = Number.parseInt(style.slice(1), 10)
|
||||
} else if (style !== '') {
|
||||
return null
|
||||
}
|
||||
skipWS()
|
||||
}
|
||||
if (pos >= len || tmpl[pos] !== '}') return null
|
||||
pos++
|
||||
return { kind: 'number', name, precision }
|
||||
}
|
||||
|
||||
if (fn === 'plural' || fn === 'select') {
|
||||
if (pos >= len || tmpl[pos] !== ',') return null
|
||||
pos++
|
||||
const isPlural = fn === 'plural'
|
||||
const branches: Array<{ selector: string; nodes: ICUNode[] }> = []
|
||||
let hasOther = false
|
||||
while (true) {
|
||||
skipWS()
|
||||
if (pos < len && tmpl[pos] === '}') {
|
||||
pos++
|
||||
break
|
||||
}
|
||||
const selector = readIdent()
|
||||
if (!selector) return null
|
||||
if (selector === 'other') hasOther = true
|
||||
skipWS()
|
||||
if (pos >= len || tmpl[pos] !== '{') return null
|
||||
pos++
|
||||
const childNodes = parseNodes(true, isPlural || parentInPlural, depth + 1)
|
||||
if (!childNodes || pos >= len || tmpl[pos] !== '}') return null
|
||||
pos++
|
||||
branches.push({ selector, nodes: childNodes })
|
||||
}
|
||||
if (!hasOther) return null
|
||||
return { kind: fn, name, branches }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const parsed = parseNodes(false, false, 0)
|
||||
const valid = parsed && pos === len ? parsed : null
|
||||
if (astCache.size > 3000) astCache.clear()
|
||||
astCache.set(tmpl, valid)
|
||||
return valid
|
||||
}
|
||||
|
||||
export function formatICU(locale: string, tmpl: string, vars?: ICUVars, strictVars = false): string | null {
|
||||
if (!vars && !tmpl.includes('{') && !tmpl.includes('}') && !tmpl.includes("'")) {
|
||||
return tmpl
|
||||
}
|
||||
const nodes = parseICU(tmpl)
|
||||
if (!nodes) return null
|
||||
|
||||
const evalList = (list: ICUNode[], poundVal?: string): string | null => {
|
||||
let out = ''
|
||||
for (const nd of list) {
|
||||
switch (nd.kind) {
|
||||
case 'text':
|
||||
out += nd.text
|
||||
break
|
||||
case 'pound':
|
||||
out += poundVal !== undefined ? poundVal : '#'
|
||||
break
|
||||
case 'var': {
|
||||
const val = vars?.[nd.name]
|
||||
if (val === undefined || val === null) {
|
||||
if (strictVars) return null
|
||||
out += `{${nd.name}}`
|
||||
} else {
|
||||
out += String(val)
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'number': {
|
||||
const val = vars?.[nd.name]
|
||||
if (val === undefined || val === null) {
|
||||
if (strictVars) return null
|
||||
out += `{${nd.name}}`
|
||||
} else {
|
||||
const num = typeof val === 'number' ? val : Number(val)
|
||||
out += Number.isFinite(num) ? formatLocaleNumber(locale, num, nd.precision) : String(val)
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'plural': {
|
||||
const raw = vars?.[nd.name]
|
||||
if ((raw === undefined || raw === null) && strictVars) return null
|
||||
const num = typeof raw === 'number' ? raw : Number(raw ?? 0)
|
||||
const safeNum = Number.isFinite(num) ? num : 0
|
||||
const exact = Number.isInteger(safeNum) ? `=${safeNum}` : ''
|
||||
const cat = getPluralRules(locale).select(safeNum)
|
||||
const chosen =
|
||||
(exact ? nd.branches.find((b) => b.selector === exact) : undefined) ??
|
||||
nd.branches.find((b) => b.selector === cat) ??
|
||||
nd.branches.find((b) => b.selector === 'other') ??
|
||||
nd.branches[nd.branches.length - 1]
|
||||
const formattedNum = formatLocaleNumber(locale, safeNum, -1)
|
||||
const inner = evalList(chosen ? chosen.nodes : [], formattedNum)
|
||||
if (inner === null) return null
|
||||
out += inner
|
||||
break
|
||||
}
|
||||
case 'select': {
|
||||
const raw = vars?.[nd.name]
|
||||
if ((raw === undefined || raw === null) && strictVars) return null
|
||||
const key = raw === undefined || raw === null ? '' : String(raw)
|
||||
const chosen =
|
||||
nd.branches.find((b) => b.selector === key) ??
|
||||
nd.branches.find((b) => b.selector === 'other') ??
|
||||
nd.branches[nd.branches.length - 1]
|
||||
const inner = evalList(chosen ? chosen.nodes : [], poundVal)
|
||||
if (inner === null) return null
|
||||
out += inner
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
return evalList(nodes)
|
||||
}
|
||||
|
||||
const PSEUDO_MAP: Record<string, string> = {
|
||||
a: 'à', b: 'ƀ', c: 'č', d: 'ď', e: 'ë', f: 'ƒ', g: 'ğ', h: 'ĥ', i: 'î', j: 'ĵ', k: 'ķ', l: 'ľ', m: 'ɱ',
|
||||
n: 'ñ', o: 'ô', p: 'þ', q: 'ǫ', r: 'ŕ', s: 'ś', t: 'ť', u: 'ü', v: 'ṽ', w: 'ŵ', x: 'ẋ', y: 'ÿ', z: 'ž',
|
||||
A: 'À', B: 'Ɓ', C: 'Č', D: 'Ď', E: 'Ë', F: 'Ƒ', G: 'Ğ', H: 'Ĥ', I: 'Î', J: 'Ĵ', K: 'Ķ', L: 'Ľ', M: 'Ṁ',
|
||||
N: 'Ñ', O: 'Ô', P: 'Þ', Q: 'Ǫ', R: 'Ŕ', S: 'Š', T: 'Ť', U: 'Ü', V: 'Ṽ', W: 'Ŵ', X: 'Ẋ', Y: 'Ÿ', Z: 'Ž',
|
||||
}
|
||||
|
||||
function accentString(s: string): string {
|
||||
let out = ''
|
||||
for (const ch of s) {
|
||||
out += PSEUDO_MAP[ch] ?? ch
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function pseudoLocalizeICU(enTmpl: string): string {
|
||||
const nodes = parseICU(enTmpl)
|
||||
if (!nodes) return `⟦${enTmpl}⟧`
|
||||
|
||||
const countChars = (list: ICUNode[]): number =>
|
||||
list.reduce((acc, n) => acc + (n.kind === 'text' ? [...n.text].length : 0), 0)
|
||||
|
||||
const topChars = countChars(nodes)
|
||||
const topPad =
|
||||
topChars === 0
|
||||
? 0
|
||||
: topChars <= 8
|
||||
? Math.max(4, Math.ceil(topChars * 0.85))
|
||||
: Math.ceil(topChars * 0.35)
|
||||
|
||||
const serialize = (list: ICUNode[], pad: number, isTop: boolean): string => {
|
||||
let s = ''
|
||||
for (const nd of list) {
|
||||
if (nd.kind === 'text') {
|
||||
s += accentString(nd.text)
|
||||
.replaceAll("'", "''")
|
||||
.replaceAll('{', "'{'")
|
||||
.replaceAll('}', "'}'")
|
||||
.replaceAll('#', "'#'")
|
||||
} else if (nd.kind === 'pound') {
|
||||
s += '#'
|
||||
} else if (nd.kind === 'var') {
|
||||
s += `{${nd.name}}`
|
||||
} else if (nd.kind === 'number') {
|
||||
s += nd.precision >= 0 ? `{${nd.name}, number, .${nd.precision}}` : `{${nd.name}, number}`
|
||||
} else {
|
||||
s += `{${nd.name}, ${nd.kind}, `
|
||||
s += nd.branches
|
||||
.map((br) => {
|
||||
const brPad = isTop && topChars === 0 ? Math.max(3, Math.ceil(countChars(br.nodes) * 0.35)) : 0
|
||||
return `${br.selector} {${serialize(br.nodes, brPad, false)}}`
|
||||
})
|
||||
.join(' ')
|
||||
s += '}'
|
||||
}
|
||||
}
|
||||
if (pad > 0) {
|
||||
s += ' ' + '·'.repeat(pad)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
return `⟦${serialize(nodes, topPad, true)}⟧`
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { coreEn, coreZh } from './domains/core.gen'
|
||||
import { vmEn, vmZh } from './domains/vm.gen'
|
||||
|
||||
export const builtinDict: Record<'zh-CN' | 'en-US', Record<string, string>> = {
|
||||
'zh-CN': { ...coreZh, ...vmZh },
|
||||
'en-US': { ...coreEn, ...vmEn },
|
||||
}
|
||||
|
||||
export function registerBuiltinDomain(zh: Record<string, string>, en: Record<string, string>): void {
|
||||
Object.assign(builtinDict['zh-CN'], zh)
|
||||
Object.assign(builtinDict['en-US'], en)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Plugin UI bridge contract, bridgeApi 1.0 (docs/plugin-architecture.md §5.6, §6.3).
|
||||
//
|
||||
// Sandboxed plugin views and panels talk to the host only through these
|
||||
// postMessage envelopes. Stable methods and events are implemented and covered
|
||||
// by the compatibility promise; experimental ones are part of the published
|
||||
// shape but the host answers them with an "experimental" error until they are
|
||||
// promoted. Permissions and rate limits are enforced in Go
|
||||
// (internal/plugin/contract.go BridgeMethodCatalog); a Go test keeps the method
|
||||
// lists here and there identical.
|
||||
|
||||
export const BRIDGE_API_VERSION = '1.0.0' as const
|
||||
|
||||
export const BRIDGE_METHODS = [
|
||||
'hello',
|
||||
'i18n.getBundle',
|
||||
'ui.notify',
|
||||
'vm.list',
|
||||
'command.invoke',
|
||||
] as const
|
||||
|
||||
export const BRIDGE_METHODS_EXPERIMENTAL = [
|
||||
'ui.confirm',
|
||||
'ui.showForm',
|
||||
'ui.setTitle',
|
||||
'ui.setBadge',
|
||||
'ui.openView',
|
||||
'ui.close',
|
||||
'ui.navigate',
|
||||
'ui.openExternal',
|
||||
'vm.get',
|
||||
'settings.get',
|
||||
'settings.set',
|
||||
'storage.get',
|
||||
'storage.set',
|
||||
'storage.list',
|
||||
'storage.delete',
|
||||
'file.pick',
|
||||
'file.save',
|
||||
'file.read',
|
||||
'file.write',
|
||||
'task.start',
|
||||
'task.update',
|
||||
'task.finish',
|
||||
'net.fetch',
|
||||
'events.subscribe',
|
||||
'events.unsubscribe',
|
||||
] as const
|
||||
|
||||
export const BRIDGE_EVENTS = [
|
||||
'theme.changed',
|
||||
'locale.changed',
|
||||
] as const
|
||||
|
||||
export const BRIDGE_EVENTS_EXPERIMENTAL = [
|
||||
'vm.stateChanged',
|
||||
'view.visibilityChanged',
|
||||
'task.updated',
|
||||
] as const
|
||||
|
||||
export type BridgeMethod = (typeof BRIDGE_METHODS)[number] | (typeof BRIDGE_METHODS_EXPERIMENTAL)[number]
|
||||
export type BridgeEventName = (typeof BRIDGE_EVENTS)[number] | (typeof BRIDGE_EVENTS_EXPERIMENTAL)[number]
|
||||
|
||||
/** Plugin → host request. `id` is chosen by the plugin and echoed in the result. */
|
||||
export interface BridgeRequest {
|
||||
type: 'reims:rpc'
|
||||
id: string
|
||||
method: BridgeMethod
|
||||
params?: Record<string, unknown>
|
||||
}
|
||||
|
||||
/** Host → plugin response to one request. */
|
||||
export type BridgeResult =
|
||||
| { type: 'reims:rpc-result'; id: string; ok: true; result: unknown }
|
||||
| { type: 'reims:rpc-result'; id: string; ok: false; error: string }
|
||||
|
||||
/** Host → plugin event. Stable events are always delivered; others only after `events.subscribe`. */
|
||||
export interface BridgeEvent {
|
||||
type: 'reims:event'
|
||||
event: BridgeEventName
|
||||
data: unknown
|
||||
}
|
||||
|
||||
/** Result of `hello`, the first call a view or panel makes. */
|
||||
export interface BridgeHello {
|
||||
bridgeApi: string
|
||||
uiApi: string
|
||||
/** Stable host features, e.g. `bridge.vm.list`; feature-detect instead of comparing versions. */
|
||||
features: string[]
|
||||
locale: string
|
||||
dir: 'ltr' | 'rtl'
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
import { t } from '../i18n'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { formatLocaleNumber } from '../i18n/icu'
|
||||
import { DisplayPreset, GPUInfo, HostReport, Locale, VMDetail } from '../types'
|
||||
|
||||
// Human-readable values for the main view (docs/ui-redesign.md §4.3).
|
||||
function currentDocLocale(): string {
|
||||
if (typeof document === 'undefined') return 'en-US'
|
||||
return document.documentElement.dataset.locale || document.documentElement.lang || 'en-US'
|
||||
}
|
||||
|
||||
// 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]
|
||||
@@ -45,12 +51,14 @@ export function parseMemoryGB(raw: string | undefined): number | null {
|
||||
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 {
|
||||
/** "16G" / "16384M" / "16GiB" → "16 GB" (or "16,5 GB" in comma-decimal locales). */
|
||||
export function formatMemory(raw: string, locale?: Locale): string {
|
||||
const gb = parseMemoryGB(raw)
|
||||
if (gb === null) return raw
|
||||
const rounded = gb >= 10 ? Math.round(gb) : Math.round(gb * 10) / 10
|
||||
return `${rounded} GB`
|
||||
const loc = locale ?? currentDocLocale()
|
||||
const precision = Number.isInteger(rounded) ? 0 : 1
|
||||
return `${formatLocaleNumber(loc, rounded, precision)} GB`
|
||||
}
|
||||
|
||||
export function controllerLabel(raw: string): string {
|
||||
@@ -62,9 +70,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". */
|
||||
@@ -105,7 +167,7 @@ export function sshCommand(port: number): string {
|
||||
return `ssh -p ${port} 127.0.0.1`
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number): string {
|
||||
export function formatBytes(bytes: number, locale?: Locale): string {
|
||||
if (!bytes || bytes <= 0) return '0 B'
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
let v = bytes
|
||||
@@ -115,7 +177,22 @@ export function formatBytes(bytes: number): string {
|
||||
i++
|
||||
}
|
||||
const digits = v >= 100 || i === 0 ? 0 : v >= 10 ? 1 : 2
|
||||
return `${v.toFixed(digits)} ${units[i]}`
|
||||
const loc = locale ?? currentDocLocale()
|
||||
return `${formatLocaleNumber(loc, v, digits)} ${units[i]}`
|
||||
}
|
||||
|
||||
/** Compact "54 / 128 GB" when both are gigabytes, falling back to full units. */
|
||||
export function formatDiskUsage(actual: number, virtual: number, locale?: Locale): string {
|
||||
const GiB = 1024 ** 3
|
||||
const loc = locale ?? currentDocLocale()
|
||||
if (actual >= GiB && virtual >= GiB && virtual < 1024 * GiB) {
|
||||
const a = actual / GiB
|
||||
const v = virtual / GiB
|
||||
const aStr = a >= 10 ? formatLocaleNumber(loc, Math.round(a), 0) : formatLocaleNumber(loc, a, 1)
|
||||
const vStr = formatLocaleNumber(loc, Math.round(v), 0)
|
||||
return `${aStr} / ${vStr} GB`
|
||||
}
|
||||
return `${formatBytes(actual, loc)} / ${formatBytes(virtual, loc)}`
|
||||
}
|
||||
|
||||
export function formatUptime(sec: number, locale: Locale): string {
|
||||
@@ -123,23 +200,46 @@ export function formatUptime(sec: number, locale: Locale): string {
|
||||
const h = Math.floor(sec / 3600)
|
||||
const m = Math.floor((sec % 3600) / 60)
|
||||
const s = sec % 60
|
||||
if (locale === 'zh-CN') {
|
||||
if (h > 0) return `${h}小时 ${m}分`
|
||||
if (m > 0) return `${m}分 ${s}秒`
|
||||
return `${s}秒`
|
||||
}
|
||||
if (h > 0) return `${h}h ${m}m`
|
||||
if (m > 0) return `${m}m ${s}s`
|
||||
return `${s}s`
|
||||
if (h > 0) return t(locale, 'uptimeHoursMinutes', { h, m })
|
||||
if (m > 0) return t(locale, 'uptimeMinutesSeconds', { m, s })
|
||||
return t(locale, 'uptimeSeconds', { 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: true },
|
||||
{ resolution: '3840x2160', label: '3840 × 2160', hidpi: true },
|
||||
{ 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
|
||||
@@ -147,6 +247,95 @@ export function recommendedDisplayPresets(host: HostReport): DisplayPreset[] {
|
||||
return DEFAULT_DISPLAY_PRESETS
|
||||
}
|
||||
|
||||
export interface FullscreenDisplayPreset extends DisplayPreset {
|
||||
native?: boolean
|
||||
scaleBadge?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolution presets for borderless fullscreen mode, decoupled from the host
|
||||
* monitor's physical pixels (requires runtime with display-fixed-mode patch
|
||||
* for non-native sizes). On a 4K screen, 5120x2880 renders 2x HiDPI and
|
||||
* downscales to 3840x2160 for a crisp 1.5x ("looks like 2560x1440") desktop.
|
||||
*/
|
||||
export function fullscreenDisplayPresets(host: HostReport): FullscreenDisplayPreset[] {
|
||||
const d = host.primary_display
|
||||
if (!d || d.width <= 0 || d.height <= 0) {
|
||||
return [
|
||||
{ resolution: '5120x2880', label: '5120 × 2880', hidpi: true, scaleBadge: '1.5×' },
|
||||
{ resolution: '3840x2160', label: '3840 × 2160', hidpi: true, native: true, recommended: true },
|
||||
{ resolution: '2560x1440', label: '2560 × 1440', hidpi: false },
|
||||
]
|
||||
}
|
||||
const w = d.width
|
||||
const h = d.height
|
||||
const scalePct = d.scale_pct || 100
|
||||
const align16 = (n: number) => Math.max(16, Math.floor(n / 16) * 16)
|
||||
const align2 = (n: number) => Math.max(2, Math.floor(n / 2) * 2)
|
||||
const out: FullscreenDisplayPreset[] = []
|
||||
const seen = new Set<string>()
|
||||
const push = (p: FullscreenDisplayPreset) => {
|
||||
if (!seen.has(p.resolution)) {
|
||||
seen.add(p.resolution)
|
||||
out.push(p)
|
||||
}
|
||||
}
|
||||
|
||||
// 1.5× HiDPI supersampling for ~4K+ displays (e.g. 3840×2160 -> 5120×2880,
|
||||
// 3840×2400 -> 5120×3200; macOS renders 2× HiDPI = looks like 2560×1440 / 1600).
|
||||
if (w >= 3200) {
|
||||
const sw = align16((w * 4) / 3)
|
||||
const sh = align2((h * 4) / 3)
|
||||
if (sw <= 5120 && sh <= 3200 && (sw !== w || sh !== h)) {
|
||||
push({
|
||||
resolution: `${sw}x${sh}`,
|
||||
label: `${sw} × ${sh}`,
|
||||
hidpi: true,
|
||||
scaleBadge: '1.5×',
|
||||
recommended: scalePct >= 125 && scalePct < 175,
|
||||
})
|
||||
}
|
||||
} else if (w >= 1920) {
|
||||
// Supersampled 2× HiDPI for 1080p / 1440p displays (capped at 5120×3200;
|
||||
// on 2560×1440, 3840×2160 gives crisp "looks like 1920×1080").
|
||||
const factor = w <= 1920 ? 2 : 1.5
|
||||
const sw = Math.min(5120, align16(w * factor))
|
||||
const sh = Math.min(3200, align2((sw * h) / w))
|
||||
if (sw >= 3840 && sh >= 2160 && (sw !== w || sh !== h)) {
|
||||
push({
|
||||
resolution: `${sw}x${sh}`,
|
||||
label: `${sw} × ${sh}`,
|
||||
hidpi: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Native 1:1 monitor resolution (zero-copy blit path).
|
||||
const nativeRecommended = !out.some((p) => p.recommended)
|
||||
push({
|
||||
resolution: `${w}x${h}`,
|
||||
label: `${w} × ${h}`,
|
||||
hidpi: !!host.fullscreen_hidpi,
|
||||
native: true,
|
||||
recommended: nativeRecommended,
|
||||
})
|
||||
|
||||
// 1× scaled option for 4K+ monitors (e.g. 2560×1440 on 4K = 1.5× logical size without HiDPI).
|
||||
if (w >= 3840) {
|
||||
const lw = align16((w * 2) / 3)
|
||||
const lh = align2((h * 2) / 3)
|
||||
if (lw >= 1920 && lh >= 1080) {
|
||||
push({
|
||||
resolution: `${lw}x${lh}`,
|
||||
label: `${lw} × ${lh}`,
|
||||
hidpi: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
export function recommendedResolution(host: HostReport): string {
|
||||
if (host.recommended_resolution) return host.recommended_resolution
|
||||
const rec = recommendedDisplayPresets(host).find((p) => p.recommended)
|
||||
@@ -155,28 +344,48 @@ export function recommendedResolution(host: HostReport): string {
|
||||
|
||||
export interface GuestLangPreset {
|
||||
value: string
|
||||
zh: string
|
||||
en: string
|
||||
labelKey: I18nKey
|
||||
detailKey?: I18nKey
|
||||
}
|
||||
|
||||
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)' },
|
||||
{ value: 'zh-Hans:0', labelKey: 'guestLangZhHansUS', detailKey: 'guestKbdUSRecommended' },
|
||||
{ value: 'zh-Hans:252', labelKey: 'guestLangZhHansUS', detailKey: 'guestKbdPinyin' },
|
||||
{ value: 'zh-Hant:0', labelKey: 'guestLangZhHantUS', detailKey: 'guestKbdUS' },
|
||||
{ value: 'en-US:0', labelKey: 'guestLangEnUS' },
|
||||
{ value: 'ja-JP:0', labelKey: 'guestLangJaJP', detailKey: 'guestKbdUS' },
|
||||
{ value: 'ko-KR:0', labelKey: 'guestLangKoKR', detailKey: 'guestKbdUS' },
|
||||
]
|
||||
|
||||
export function guestLangOptions(locale: Locale): Array<{ value: string; label: string; detail?: string }> {
|
||||
return GUEST_LANG_PRESETS.map((p) => ({
|
||||
value: p.value,
|
||||
label: t(locale, p.labelKey),
|
||||
detail: p.detailKey ? t(locale, p.detailKey) : undefined,
|
||||
}))
|
||||
}
|
||||
|
||||
export function defaultGuestLang(locale: Locale): string {
|
||||
return locale === 'en-US' ? 'en-US:0' : 'zh-Hans:0'
|
||||
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 resolveGuestLang(locale: Locale, code: string | undefined): { label: string; detail?: string } {
|
||||
const target = code || defaultGuestLang(locale)
|
||||
const hit = GUEST_LANG_PRESETS.find((p) => p.value === target)
|
||||
if (!hit) return { label: target }
|
||||
const label = t(locale, hit.labelKey)
|
||||
const detail = hit.detailKey ? t(locale, hit.detailKey) : undefined
|
||||
return { label, detail }
|
||||
}
|
||||
|
||||
export function guestLangLabel(locale: Locale, code: string | undefined): string {
|
||||
if (!code) return defaultGuestLang(locale)
|
||||
const hit = GUEST_LANG_PRESETS.find((p) => p.value === code)
|
||||
if (hit) return locale === 'zh-CN' ? hit.zh : hit.en
|
||||
return code
|
||||
const { label, detail } = resolveGuestLang(locale, code)
|
||||
return detail ? `${label} (${detail})` : label
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -187,3 +396,28 @@ export function splitLangLabel(value: string, text: string): { value: string; la
|
||||
const m = /^(.*?)\s*[((](.*)[))]\s*$/.exec(text)
|
||||
return m ? { value, label: m[1], detail: m[2] } : { value, label: text }
|
||||
}
|
||||
|
||||
/**
|
||||
* A change saved while the VM runs, as the user would say it:
|
||||
* `memory 8G→16G` becomes "内存 8 GB → 16 GB". Field names come from
|
||||
* PendingChange in internal/app/app.go.
|
||||
*/
|
||||
export function pendingChangeText(locale: Locale, p: { field: string; from: string; to: string }, host: HostReport): string {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const bool = (v: string) => tr(v === 'true' ? 'on' : 'off')
|
||||
const lang = (v: string) => resolveGuestLang(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: (v) => formatMemory(v, locale) },
|
||||
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[] {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, Optimization, OptimizationStatus } from '../types'
|
||||
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
import { t } from '../i18n'
|
||||
import { Locale, Task } from '../types'
|
||||
import { CachedInstaller, InstallerKind, InstallerPhase, 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> {
|
||||
@@ -8,10 +21,15 @@ export function upsertTask(prev: Record<string, Task>, task: Task): Record<strin
|
||||
return { ...prev, [task.id]: task }
|
||||
}
|
||||
|
||||
/** The task to show in the status bar: the most recently updated running one. */
|
||||
/** The task to show in the status bar: active work ahead of queued downloads, newest first. */
|
||||
export function currentTask(all: Record<string, Task>): { task: Task | null; running: number } {
|
||||
const running = Object.values(all).filter((x) => x.status === 'running')
|
||||
running.sort((a, b) => b.updated_at - a.updated_at)
|
||||
running.sort((a, b) => {
|
||||
const aq = a.installer_phase === 'queued' ? 1 : 0
|
||||
const bq = b.installer_phase === 'queued' ? 1 : 0
|
||||
if (aq !== bq) return aq - bq
|
||||
return b.updated_at - a.updated_at
|
||||
})
|
||||
return { task: running[0] ?? null, running: running.length }
|
||||
}
|
||||
|
||||
@@ -22,6 +40,7 @@ export function taskTitle(locale: Locale, task: Task): string {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -35,6 +54,134 @@ export function taskDetail(task: Task): string {
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
export function isInstallerTask(task: Task): boolean {
|
||||
return task.kind === 'installer-download' || task.kind === 'recovery-download' || !!task.installer_kind
|
||||
}
|
||||
|
||||
export function taskInstallerKind(task: Task): InstallerKind | '' {
|
||||
if (task.installer_kind === 'offline' || task.installer_kind === 'online') return task.installer_kind
|
||||
if (task.kind === 'installer-download') return 'offline'
|
||||
if (task.kind === 'recovery-download') return 'online'
|
||||
return ''
|
||||
}
|
||||
|
||||
export function taskInstallerVersion(task: Task): string {
|
||||
const v = (task.installer_version ?? '').trim()
|
||||
if (v) return v
|
||||
if (task.kind === 'installer-download') return task.subject.trim()
|
||||
if (task.kind === 'recovery-download') return 'latest'
|
||||
return ''
|
||||
}
|
||||
|
||||
export function taskInstallerPhase(task: Task): InstallerPhase | '' {
|
||||
if (task.status !== 'running') return ''
|
||||
if (task.installer_phase === 'queued' || task.installer_phase === 'downloading') return task.installer_phase
|
||||
if (task.kind === 'installer-download' || task.kind === 'recovery-download') return 'downloading'
|
||||
return ''
|
||||
}
|
||||
|
||||
export function isActiveInstallerTask(task: Task): boolean {
|
||||
return taskInstallerPhase(task) !== ''
|
||||
}
|
||||
|
||||
export function taskInstallerKey(task: Task): string {
|
||||
const kind = taskInstallerKind(task)
|
||||
if (!kind) return ''
|
||||
let v = taskInstallerVersion(task).toLowerCase()
|
||||
if (kind === 'online' && !v) v = 'latest'
|
||||
return `${kind}:${v}`
|
||||
}
|
||||
|
||||
export function matchesOnlineInstallerTitle(title: string | undefined, target: string): boolean {
|
||||
const want = target.trim().toLowerCase()
|
||||
if (!want) return false
|
||||
const norm = (title ?? '').trim().toLowerCase().replace(/^macos\s+/, '')
|
||||
return norm === want || norm.replace(/\s+/g, '-') === want
|
||||
}
|
||||
|
||||
export function matchesCachedInstaller(item: CachedInstaller, task: Task): boolean {
|
||||
if (!isActiveInstallerTask(task)) return false
|
||||
const kind = taskInstallerKind(task)
|
||||
if (!kind || kind !== item.kind) return false
|
||||
const v = taskInstallerVersion(task).toLowerCase()
|
||||
if (kind === 'offline') {
|
||||
if (item.version && item.version.toLowerCase() === v) return true
|
||||
return item.partial && !!v && !/^\d/.test(v) && matchesOnlineInstallerTitle(item.title, v)
|
||||
}
|
||||
if (!v || v === 'latest') return item.partial
|
||||
return matchesOnlineInstallerTitle(item.title, v)
|
||||
}
|
||||
|
||||
export interface ActiveInstallerMatch {
|
||||
primary: Task
|
||||
waitingVMs: string[]
|
||||
matchedIDs: string[]
|
||||
}
|
||||
|
||||
function isStandaloneDownload(task: Task): boolean {
|
||||
return task.kind === 'installer-download' || task.kind === 'recovery-download'
|
||||
}
|
||||
|
||||
function pickPrimaryInstallerTask(matches: Task[]): ActiveInstallerMatch | null {
|
||||
if (matches.length === 0) return null
|
||||
const sorted = [...matches].sort((a, b) => {
|
||||
const aStandalone = isStandaloneDownload(a) ? 0 : 1
|
||||
const bStandalone = isStandaloneDownload(b) ? 0 : 1
|
||||
if (aStandalone !== bStandalone) return aStandalone - bStandalone
|
||||
const aQueued = taskInstallerPhase(a) === 'queued' ? 1 : 0
|
||||
const bQueued = taskInstallerPhase(b) === 'queued' ? 1 : 0
|
||||
if (aQueued !== bQueued) return aQueued - bQueued
|
||||
return a.started_at - b.started_at
|
||||
})
|
||||
const primary = sorted[0]
|
||||
const waitingVMs: string[] = []
|
||||
for (const other of sorted.slice(1)) {
|
||||
if (other.kind !== 'vm-create') continue
|
||||
const vm = (other.vm || other.subject).trim()
|
||||
if (vm && !waitingVMs.includes(vm)) waitingVMs.push(vm)
|
||||
}
|
||||
return { primary, waitingVMs, matchedIDs: sorted.map((x) => x.id) }
|
||||
}
|
||||
|
||||
export function findActiveOfflineTask(tasks: Task[], version: string): ActiveInstallerMatch | null {
|
||||
const want = version.trim().toLowerCase()
|
||||
if (!want) return null
|
||||
const matches = tasks.filter(
|
||||
(x) => isActiveInstallerTask(x) && taskInstallerKind(x) === 'offline' && taskInstallerVersion(x).toLowerCase() === want,
|
||||
)
|
||||
return pickPrimaryInstallerTask(matches)
|
||||
}
|
||||
|
||||
export function findActiveCachedTask(tasks: Task[], item: CachedInstaller): ActiveInstallerMatch | null {
|
||||
const matches = tasks.filter((x) => matchesCachedInstaller(item, x))
|
||||
return pickPrimaryInstallerTask(matches)
|
||||
}
|
||||
|
||||
export function groupUnmatchedInstallerTasks(activeTasks: Task[], matchedTaskIDs: Set<string>): ActiveInstallerMatch[] {
|
||||
const buckets = new Map<string, Task[]>()
|
||||
for (const task of activeTasks) {
|
||||
if (matchedTaskIDs.has(task.id)) continue
|
||||
const key = taskInstallerKey(task)
|
||||
if (!key) continue
|
||||
const list = buckets.get(key)
|
||||
if (list) list.push(task)
|
||||
else buckets.set(key, [task])
|
||||
}
|
||||
const out: ActiveInstallerMatch[] = []
|
||||
for (const group of buckets.values()) {
|
||||
const picked = pickPrimaryInstallerTask(group)
|
||||
if (picked) out.push(picked)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function taskStopAction(locale: Locale, task: Task): { kind: 'pause' | 'cancel'; label: string } {
|
||||
if (task.kind === 'vm-create') return { kind: 'cancel', label: t(locale, 'cancelCreate') }
|
||||
if (task.kind === 'app-update') return { kind: 'cancel', label: t(locale, 'updateCancel') }
|
||||
if (taskInstallerPhase(task) === 'queued') return { kind: 'cancel', label: t(locale, 'cancelQueue') }
|
||||
return { kind: 'pause', label: t(locale, 'pauseDownload') }
|
||||
}
|
||||
|
||||
function bytes(b: number): string {
|
||||
if (b >= 1e9) return `${(b / 1e9).toFixed(1)} GB`
|
||||
return `${Math.max(1, Math.ceil(b / 1e6))} MB`
|
||||
|
||||
@@ -0,0 +1,681 @@
|
||||
// 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_LAYOUT_OPTIONS, UI_CONTRACT_TOKENS, type UIContractSDKEvent } 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'
|
||||
locale: string
|
||||
dir: 'ltr' | 'rtl'
|
||||
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 activeUIScriptNotifier: ((snap: UIStateSnapshot) => void) | null = null
|
||||
let activeUIScriptURL = ''
|
||||
let activeUIScriptEventSink: ((event: string, data: unknown) => void) | null = null
|
||||
|
||||
/**
|
||||
* Forwards a host event to the interactive theme's `sdk.on` handlers. A no-op
|
||||
* unless an interactive theme is loaded; payloads carry no paths or secrets.
|
||||
*/
|
||||
export function emitThemeEvent(event: UIContractSDKEvent, data: unknown): void {
|
||||
if (!activeUIScriptEventSink) return
|
||||
try { activeUIScriptEventSink(event, data) } catch (e) { console.warn('[theme] UI script event handler failed:', event, e) }
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
/** Resolves a theme package asset to its served URL, or null when unsafe. */
|
||||
export function themeAssetURL(payload: ActiveThemePayload | null, rel: string | undefined): string | null {
|
||||
if (!payload || !rel) return null
|
||||
const rawBaseURL = payload.asset_base_url ?? ''
|
||||
if (!RE_ASSET_BASE_URL.test(rawBaseURL) || rawBaseURL.includes('..')) return null
|
||||
const safe = sanitizeRelativeAssetPath(rel)
|
||||
return safe ? rawBaseURL + safe : null
|
||||
}
|
||||
|
||||
// Theme `layout` option → <html> attribute (ui-contract UI_CONTRACT_LAYOUT_OPTIONS).
|
||||
const LAYOUT_ATTRS: Record<string, string> = {
|
||||
sidebarPosition: 'data-layout-sidebar',
|
||||
sidebarMode: 'data-layout-sidebar-mode',
|
||||
density: 'data-layout-density',
|
||||
titlebar: 'data-layout-titlebar',
|
||||
}
|
||||
const ALLOWED_LAYOUT = new Set<string>(UI_CONTRACT_LAYOUT_OPTIONS)
|
||||
|
||||
/** Writes the active theme's layout options as data-layout-* attributes; null clears them. */
|
||||
export function applyThemeLayout(layout: Record<string, unknown> | null | undefined): void {
|
||||
const el = document.documentElement
|
||||
for (const [option, attr] of Object.entries(LAYOUT_ATTRS)) {
|
||||
const value = layout?.[option]
|
||||
if (typeof value === 'string' && ALLOWED_LAYOUT.has(`${option}=${value}`)) el.setAttribute(attr, value)
|
||||
else el.removeAttribute(attr)
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 (e) {
|
||||
console.warn('[theme] read theme preference failed:', e)
|
||||
}
|
||||
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 (e) {
|
||||
console.warn('[theme] clear legacy inline cache failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
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 (e) {
|
||||
console.warn('[theme] apply cached theme tokens failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
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 (e) {
|
||||
console.warn('[theme] clear theme token cache failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
const RE_VALID_HEX = /^(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/
|
||||
|
||||
/** 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(/^#/, '')
|
||||
if (!RE_VALID_HEX.test(clean)) return null
|
||||
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 {
|
||||
r = parseInt(clean.slice(0, 2), 16) / 255
|
||||
g = parseInt(clean.slice(2, 4), 16) / 255
|
||||
b = parseInt(clean.slice(4, 6), 16) / 255
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
function srgbChannelToLinear(c: number): number {
|
||||
return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)
|
||||
}
|
||||
|
||||
/** Computes WCAG 2.1 relative luminance (0..1) for a #RGB or #RRGGBB hex string. */
|
||||
function hexRelativeLuminance(hex: string): number | null {
|
||||
const clean = hex.trim().replace(/^#/, '')
|
||||
if (!RE_VALID_HEX.test(clean)) return null
|
||||
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 {
|
||||
r = parseInt(clean.slice(0, 2), 16) / 255
|
||||
g = parseInt(clean.slice(2, 4), 16) / 255
|
||||
b = parseInt(clean.slice(4, 6), 16) / 255
|
||||
}
|
||||
if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) return null
|
||||
return 0.2126 * srgbChannelToLinear(r) + 0.7152 * srgbChannelToLinear(g) + 0.0722 * srgbChannelToLinear(b)
|
||||
}
|
||||
|
||||
function hslRelativeLuminance(hDeg: number, s: number, l: number): number {
|
||||
const c = (1 - Math.abs(2 * l - 1)) * s
|
||||
const hp = ((hDeg % 360) + 360) % 360 / 60
|
||||
const x = c * (1 - Math.abs((hp % 2) - 1))
|
||||
let r1 = 0, g1 = 0, b1 = 0
|
||||
if (hp < 1) [r1, g1, b1] = [c, x, 0]
|
||||
else if (hp < 2) [r1, g1, b1] = [x, c, 0]
|
||||
else if (hp < 3) [r1, g1, b1] = [0, c, x]
|
||||
else if (hp < 4) [r1, g1, b1] = [0, x, c]
|
||||
else if (hp < 5) [r1, g1, b1] = [x, 0, c]
|
||||
else [r1, g1, b1] = [c, 0, x]
|
||||
const m = l - c / 2
|
||||
return (
|
||||
0.2126 * srgbChannelToLinear(clamp01(r1 + m)) +
|
||||
0.7152 * srgbChannelToLinear(clamp01(g1 + m)) +
|
||||
0.0722 * srgbChannelToLinear(clamp01(b1 + m))
|
||||
)
|
||||
}
|
||||
|
||||
function contrastRatio(lumA: number, lumB: number): number {
|
||||
const hi = Math.max(lumA, lumB)
|
||||
const lo = Math.min(lumA, lumB)
|
||||
return (hi + 0.05) / (lo + 0.05)
|
||||
}
|
||||
|
||||
function pickAccessibleSoftAccentText(h: number, s: number, l: number, appearance: 'light' | 'dark'): string {
|
||||
// Target surface luminance: light canvas/soft (~0.92), dark surface (~0.015 for #1d1e23).
|
||||
const surfaceLum = appearance === 'dark' ? 0.015 : 0.92
|
||||
const targetRatio = 4.6
|
||||
let candidateL = appearance === 'dark' ? Math.max(l, 0.66) : Math.min(l, 0.42)
|
||||
if (contrastRatio(hslRelativeLuminance(h, s, candidateL), surfaceLum) < targetRatio) {
|
||||
let lo = appearance === 'dark' ? candidateL : 0
|
||||
let hi = appearance === 'dark' ? 1 : candidateL
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const mid = (lo + hi) / 2
|
||||
const ok = contrastRatio(hslRelativeLuminance(h, s, mid), surfaceLum) >= targetRatio
|
||||
if (appearance === 'dark') {
|
||||
if (ok) hi = mid
|
||||
else lo = mid
|
||||
} else {
|
||||
if (ok) lo = mid
|
||||
else hi = mid
|
||||
}
|
||||
}
|
||||
candidateL = appearance === 'dark' ? hi : lo
|
||||
}
|
||||
return `hsl(${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(clamp01(candidateL) * 100)}%)`
|
||||
}
|
||||
|
||||
function pickHighContrastAccentText(hex: string): string {
|
||||
const lum = hexRelativeLuminance(hex)
|
||||
if (lum === null) return '#ffffff'
|
||||
const whiteContrast = 1.05 / (lum + 0.05)
|
||||
const darkInkLum = 0.0123 // #1d1d1f
|
||||
const darkContrast = (lum + 0.05) / (darkInkLum + 0.05)
|
||||
return darkContrast > whiteContrast ? '#1d1d1f' : '#ffffff'
|
||||
}
|
||||
|
||||
/** 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-text'] = pickHighContrastAccentText(seeds.accent)
|
||||
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'] = pickAccessibleSoftAccentText(h, s, l, appearance)
|
||||
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 (e) { console.warn('[theme] UI script cleanup failed:', e) }
|
||||
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()
|
||||
applyThemeLayout(null)
|
||||
return
|
||||
}
|
||||
|
||||
const th = payload.theme
|
||||
applyThemeLayout(th.layout as Record<string, unknown> | undefined)
|
||||
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 (e) {
|
||||
console.warn('[theme] persist theme token cache failed:', e)
|
||||
}
|
||||
|
||||
// 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, notifyThemeSDKState, emitThemeSDKEvent } = await import('./uiSdk')
|
||||
if (gen !== applyGeneration) return
|
||||
const cleanup = await mountInteractiveThemeScript(nextScriptURL, getState, actions)
|
||||
if (gen !== applyGeneration) {
|
||||
try { cleanup() } catch (e) { console.warn('[theme] stale UI script cleanup failed:', e) }
|
||||
return
|
||||
}
|
||||
activeUIScriptCleanup = () => {
|
||||
activeUIScriptNotifier = null
|
||||
activeUIScriptEventSink = null
|
||||
cleanup()
|
||||
}
|
||||
activeUIScriptNotifier = notifyThemeSDKState
|
||||
activeUIScriptEventSink = emitThemeSDKEvent
|
||||
activeUIScriptURL = nextScriptURL
|
||||
} catch {
|
||||
if (gen === applyGeneration) {
|
||||
// Fallback gracefully to the scriptless style/token theme (§4.2).
|
||||
activeUIScriptCleanup = null
|
||||
activeUIScriptURL = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const LOCALE_FONT_EL_ID = 'rg-active-locale-fonts'
|
||||
const RE_SAFE_FONT_URL = /^\/plugin-assets\/[a-f0-9]+\/[a-z0-9][a-z0-9._-]*\/[a-zA-Z0-9._/@ -]+\.woff2$/i
|
||||
const RE_SAFE_FONT_FAMILY = /^[\p{L}\p{N} _-]{1,80}$/u
|
||||
|
||||
/**
|
||||
* Injects optional bundled `.woff2` WebFonts declared by the active language pack
|
||||
* into `--font-locale-pack` (scoped strictly inside `@layer theme`, zero cost when empty).
|
||||
*/
|
||||
export function applyActiveLocaleFonts(
|
||||
fonts: Array<{ family: string; url: string; weight?: string; style?: string; unicodeRange?: string }> | undefined,
|
||||
): void {
|
||||
const existing = document.getElementById(LOCALE_FONT_EL_ID)
|
||||
if (!fonts || fonts.length === 0) {
|
||||
existing?.remove()
|
||||
return
|
||||
}
|
||||
const rules: string[] = []
|
||||
const families: string[] = []
|
||||
for (const f of fonts) {
|
||||
const fam = (f.family || '').trim()
|
||||
if (!RE_SAFE_FONT_FAMILY.test(fam) || fam.toLowerCase().includes('</style')) continue
|
||||
if (!f.url || f.url.includes('..') || !RE_SAFE_FONT_URL.test(f.url)) continue
|
||||
const weight = f.weight && RE_FONT_WEIGHT.test(f.weight) ? f.weight : '400'
|
||||
const style = f.style && RE_FONT_STYLE.test(f.style) ? f.style : 'normal'
|
||||
const ur = f.unicodeRange && RE_UNICODE_RANGE.test(f.unicodeRange) ? `unicode-range: ${f.unicodeRange};` : ''
|
||||
rules.push(
|
||||
`@font-face { font-family: "${fam}"; src: url("${f.url}") format("woff2"); font-weight: ${weight}; font-style: ${style}; font-display: swap; ${ur} }`,
|
||||
)
|
||||
if (!families.includes(`"${fam}"`)) {
|
||||
families.push(`"${fam}"`)
|
||||
}
|
||||
}
|
||||
if (rules.length === 0) {
|
||||
existing?.remove()
|
||||
return
|
||||
}
|
||||
let styleEl = existing as HTMLStyleElement | null
|
||||
if (!styleEl) {
|
||||
styleEl = document.createElement('style')
|
||||
styleEl.id = LOCALE_FONT_EL_ID
|
||||
document.head.appendChild(styleEl)
|
||||
}
|
||||
styleEl.textContent = `@layer theme {\n:root {\n --font-locale-pack: ${families.join(', ')}, ;\n}\n${rules.join('\n')}\n}`
|
||||
}
|
||||
|
||||
/** Tears down injected theme/locale style nodes and active UI scripts on unmount. */
|
||||
export function disposeActiveThemeAndLocaleFonts(): void {
|
||||
if (activeUIScriptCleanup) {
|
||||
try { activeUIScriptCleanup() } catch (e) { console.warn('[theme] dispose UI script cleanup failed:', e) }
|
||||
activeUIScriptCleanup = null
|
||||
activeUIScriptNotifier = null
|
||||
activeUIScriptURL = ''
|
||||
}
|
||||
clearDynamicThemeStyles()
|
||||
document.getElementById(LOCALE_FONT_EL_ID)?.remove()
|
||||
}
|
||||
|
||||
export function notifyInteractiveThemeState(snap: UIStateSnapshot): void {
|
||||
activeUIScriptNotifier?.(snap)
|
||||
}
|
||||
|
||||
/** 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((e) => console.warn('[theme] sound playback failed:', eventName, e))
|
||||
} catch (e) {
|
||||
console.warn('[theme] sound init failed:', eventName, e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
// 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_FEATURES, UI_CONTRACT_LAYERS, UI_CONTRACT_PARTS, UI_CONTRACT_SDK_EVENTS, UI_CONTRACT_SLOTS,
|
||||
type UIContractLayer, type UIContractPart, type UIContractSDKEvent, type UIContractSlot,
|
||||
} from '../styles/ui-contract'
|
||||
import { hideWailsGlobals } from '../wails'
|
||||
import type { ThemeSDKHostActions, UIStateSnapshot } from './themeEngine'
|
||||
|
||||
export interface ReimsUISDK {
|
||||
readonly uiApi: string
|
||||
/** Stable host features (e.g. `slot.sidebar.footer`); feature-detect instead of comparing versions. */
|
||||
readonly features: readonly 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
|
||||
/** All elements of a repeated part (e.g. `rg-p-nav-item`), in document order. */
|
||||
queryParts: (part: UIContractPart) => HTMLElement[]
|
||||
/** 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. Repeated slots
|
||||
* (`nav.item.trailing`) take the item key from `slotKeys`.
|
||||
*/
|
||||
mountSlot: (slot: UIContractSlot, node: HTMLElement, key?: string) => () => void
|
||||
/** Keys of the currently rendered instances of a repeated slot (VM references). */
|
||||
slotKeys: (slot: UIContractSlot) => string[]
|
||||
/** Mounts into a full-window layer (`layer.background` / `layer.overlay`). */
|
||||
mountLayer: (layer: UIContractLayer, node: HTMLElement) => () => void
|
||||
/** Subscribes to a host event (VM state, tasks, toasts, view changes). */
|
||||
on: (event: UIContractSDKEvent, cb: (data: unknown) => void) => () => void
|
||||
/** Restricted non-destructive UI actions only (no start/stop/delete/config write). */
|
||||
actions: ThemeSDKHostActions
|
||||
}
|
||||
|
||||
const stateListeners = new Set<(snap: UIStateSnapshot) => void>()
|
||||
const eventListeners = new Map<string, Set<(data: unknown) => void>>()
|
||||
|
||||
/** Delivers a host event to subscribed theme handlers (themeEngine.emitThemeEvent). */
|
||||
export function emitThemeSDKEvent(event: string, data: unknown): void {
|
||||
const set = eventListeners.get(event)
|
||||
if (!set) return
|
||||
for (const cb of set) {
|
||||
try { cb(data) } catch (e) { console.warn('[uiSdk] event listener failed:', event, e) }
|
||||
}
|
||||
}
|
||||
|
||||
export function notifyThemeSDKState(snap: UIStateSnapshot): void {
|
||||
if (stateListeners.size === 0) return
|
||||
for (const cb of stateListeners) {
|
||||
try { cb(snap) } catch (e) { console.warn('[uiSdk] state listener failed:', e) }
|
||||
}
|
||||
}
|
||||
|
||||
// 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 (e) { console.warn('[uiSdk] scheduled read failed:', e) } }
|
||||
for (const w of writes) { try { w() } catch (e) { console.warn('[uiSdk] scheduled write failed:', e) } }
|
||||
}
|
||||
|
||||
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 layerSet = new Set<string>(UI_CONTRACT_LAYERS)
|
||||
const eventSet = new Set<string>(UI_CONTRACT_SDK_EVENTS)
|
||||
|
||||
const addDisposer = (fn: () => void) => {
|
||||
if (disposed) return
|
||||
disposers.add(fn)
|
||||
}
|
||||
|
||||
const mountInto = (host: HTMLElement | null, node: HTMLElement) => {
|
||||
if (disposed || !host) return () => {}
|
||||
host.appendChild(node)
|
||||
const off = () => {
|
||||
node.remove()
|
||||
disposers.delete(off)
|
||||
}
|
||||
addDisposer(off)
|
||||
return off
|
||||
}
|
||||
|
||||
const disposeAll = () => {
|
||||
if (disposed) return
|
||||
disposed = true
|
||||
const list = Array.from(disposers).reverse()
|
||||
disposers.clear()
|
||||
for (const fn of list) {
|
||||
try { fn() } catch (e) { console.warn('[uiSdk] disposer failed:', e) }
|
||||
}
|
||||
}
|
||||
|
||||
const sdk: ReimsUISDK = {
|
||||
uiApi: UI_API_VERSION,
|
||||
features: UI_CONTRACT_FEATURES,
|
||||
onDispose: addDisposer,
|
||||
feature: (_name, setup) => {
|
||||
if (disposed) return
|
||||
const localDisposers: Array<() => void> = []
|
||||
const localDispose = () => {
|
||||
while (localDisposers.length > 0) {
|
||||
try { localDisposers.pop()?.() } catch (e) { console.warn('[uiSdk] feature disposer failed:', e) }
|
||||
}
|
||||
}
|
||||
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}`)
|
||||
},
|
||||
queryParts: (part) => {
|
||||
if (disposed || !partSet.has(part)) return []
|
||||
return Array.from(document.querySelectorAll<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 (e) { console.warn('[uiSdk] part observer failed:', part, e) }
|
||||
})
|
||||
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, key) => {
|
||||
if (!slotSet.has(slot)) return () => {}
|
||||
const sel = `[data-rg-slot="${CSS.escape(slot)}"]` + (key ? `[data-rg-key="${CSS.escape(key)}"]` : '')
|
||||
return mountInto(document.querySelector<HTMLElement>(sel), node)
|
||||
},
|
||||
slotKeys: (slot) => {
|
||||
if (disposed || !slotSet.has(slot)) return []
|
||||
return Array.from(document.querySelectorAll<HTMLElement>(`[data-rg-slot="${CSS.escape(slot)}"][data-rg-key]`))
|
||||
.map((el) => el.dataset.rgKey ?? '')
|
||||
.filter(Boolean)
|
||||
},
|
||||
mountLayer: (layer, node) => {
|
||||
if (!layerSet.has(layer)) return () => {}
|
||||
return mountInto(document.querySelector<HTMLElement>(`[data-rg-layer="${CSS.escape(layer)}"]`), node)
|
||||
},
|
||||
on: (event, cb) => {
|
||||
if (disposed || !eventSet.has(event)) return () => {}
|
||||
let set = eventListeners.get(event)
|
||||
if (!set) {
|
||||
set = new Set()
|
||||
eventListeners.set(event, set)
|
||||
}
|
||||
set.add(cb)
|
||||
const off = () => {
|
||||
eventListeners.get(event)?.delete(cb)
|
||||
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,9 @@
|
||||
export interface VMRefLike {
|
||||
name: string
|
||||
driver_id?: string
|
||||
}
|
||||
|
||||
/** Matches driver.VMRef.Key while tolerating pre-VMRef test/host snapshots. */
|
||||
export function vmRefKey(vm: VMRefLike): string {
|
||||
return vm.driver_id ? `${vm.driver_id}:${vm.name}` : vm.name
|
||||
}
|
||||