Compare commits

...
29 Commits
Author SHA1 Message Date
Nwflower 3ce0000215 release: v0.2.9
Release Reims-Go / release (push) Canceled after 0s
2026-11-30 01:16:40 -07:00
Nwflower 1e80caa255 Merge pull request #13 from icaruszezen/fix/sync-installer-download-progress
Sync VM creation macOS installer downloads with the Installers page, sidebar busy dot, and CreateWizard via the in-process installer coordinator (relates to #11).

Review hardening applied during merge:
- Serialize initial phase/snapshot replay against live subscriber updates in ensureInstallerForTask to avoid backward progress overwrites
- Guard installerDownloads.complete with defer so unexpected download panics cannot leak active entries or deadlock joined waiters
- Regenerate i18n catalogs with cmd/i18ngen after merging with main
2026-11-30 01:08:03 -07:00
Nwflower bcfedf5d36 feat(ui): add About update channel selector, plugin market tab, and scan report modal
- Add stable/alpha/dev update channel selector and prerelease rollback retention notice on AboutPage
- Add Plugin Market tab, pre-install static security report dialog, and installed plugin security scan actions on PluginsPage
- Sync Wails frontend bindings, regenerated frontend i18n domain catalogs, and CHANGELOG
2026-11-30 01:04:20 -07:00
Nwflower 9e9ae6f19b feat(update): support stable/alpha/dev channels and retain backups on prerelease
- Add stable, alpha, and rolling dev release channel resolution in internal/version (including non-monotonic dev commit SHA detection)
- Persist app_update_channel in config and expose App.SetAppUpdateChannel
- Preserve previous executables (.old*) and downloaded update installers on startup (and avoid overwriting existing .old backups during swap) when alpha or dev channel is selected
2026-11-30 01:04:20 -07:00
Nwflower 5a5977f93e feat(plugin,cli): add static security scanner and lazy plugin market
- Add unified static security scanner and install/load gate (internal/plugin/scanner.go) blocking undeclared binaries, SVG active content, theme script escapes, and undeclared network calls while reporting L3 Sidecar privileges and SHA-256
- Add lazy plugin market client (internal/plugin/market.go) with remote index fetching (REIMS_GO_PLUGIN_MARKET_URL), memory/disk caching, embedded offline fallback, withdrawn-plugin blocking, compatibility preflight, and SHA-256 verification
- Extend CLI with plugin search/update/install <id> and enhanced .zip/--json security doctor output; update backend locale catalog and plugin architecture docs
2026-11-30 01:04:20 -07:00
icaruszezen 2513513470 fix(installer,ui): sync VM creation download progress with installers page 2026-11-30 15:53:31 +08:00
Nwflower ceeb483cfb fix(i18n,plugin,ui): harden PR #10 redaction, trust boundaries, ICU limits, and UI contrast
Follow-up hardening from PR #10 review:
- Redact quoted/space-containing SMC OSKs, hyphenated MACs, and extended token keys without corrupting benign 'serial ...' messages; make RawDetail truncation UTF-8-safe and register reims.RedactText in CLI
- Enforce trust boundaries so unprivileged community language packs cannot hijack built-in zh-CN/en-US catalogs or overwrite target-owned plugin metadata/messages
- Avoid triggering inUseChecker/Sidecar wake-ups inside Registry.OnChange (ResolvedLocalePacks) and Broker.AllowRate; bound Sidecar NotifyIfRunning with a 500ms timeout; add l10nCache generation counter and syncLocales broadcast
- Cap ICU nesting depth (16) and template size (16 KiB) in Go & TS; reserve built-in anchors in 8-hop FallbackChain; fix C.UTF-8 detection, zero-var fault isolation, and PseudoLocalize brace escaping
- Fix pluginsdk Server.T apostrophe/contraction handling, defensive cloning, and sequential plugin/localeChanged dispatch
- Fix WCAG 2.1 AA contrast for --accent-soft-text, prevent PluginPanelFrame RPC hang on locale switch, guard setPluginLocales re-renders, and fix <=768px drawer & RTL toast swipe-out CSS
2026-11-30 00:26:14 -07:00
Nwflower 5c647308f4 chore(github): make issue templates bilingual and add hardware compatibility form 2026-11-30 00:22:08 -07:00
Nwflower 14f72889dd Merge pull request #10 from Dnyo666/feat/i18n-l10n-v2
Resolve merge conflicts with main in frontend/src/i18n.ts and internal/i18n/i18n.go, migrate the 12 i18n keys added on main since branching (CoW backing chain diagnostics and About open-source license viewer) into locales/{zh-CN,en-US}/*.json, and regenerate catalogs via cmd/i18ngen.
2026-11-30 00:18:19 -07:00
Nwflower 66da194b05 feat(legal,ui): bundle full third-party licenses and add About license viewer 2026-11-30 00:03:29 -07:00
Nwflower fd23e88679 chore(patches): add reims-ctl virtio discard/iothread and qcow2 L2 cache patches 2026-11-30 00:03:11 -07:00
Nwflower 18df9e5c49 feat(host,cli,ui): detect and surface deep or broken CoW backing chains 2026-11-30 00:02:47 -07:00
Nwflower e800d55f9f feat(disk): preserve qcow2 creation options across compact, clone, and import 2026-11-30 00:02:02 -07:00
Nwflower 7582fd2cfb feat(qmp,io-bench): add small-file I/O benchmark suite and QMP blockstats 2026-11-30 00:02:02 -07:00
Dnyo666 ceeec602be feat(i18n,plugin): implement end-to-end i18n & L10n v2 architecture and language pack protocol
- Build single-source-of-truth 7-domain locale catalog (`locales/{zh-CN,en-US}/*.json`, 1,100+ keys) and `cmd/i18ngen` generator emitting Go catalogs and eager/lazy-split TypeScript domain modules (`core`/`vm` eager; `wizard`/`settings`/`plugins` lazy)
- Add zero-dependency ICU MessageFormat subset (`{var}`, `{n, number}`, CLDR `plural`, `select`), 8-hop cycle-free regional fallback (`zh-HK/zh-MO -> zh-Hant -> zh-TW -> zh-CN`), `auto` OS display-language preference, and `en-XA` pseudo-localization across Go and TypeScript
- Introduce `CodedError` supportability with `[E_CODE]` badges, collapsible `[detail]` diagnostics, and automatic SMC OSK / SMBIOS serial / MAC / token redaction
- Add Host × Guest macOS dual-terminology annotation (`FormatGuestTerm`) across 6 official Apple guest UI locales and localize Win32 system tray, file pickers, and DPI-adaptive `installguide` overlays with CJK font fallback probing
- Upgrade L1–L4 plugin localization to dual-track v2: Track A full language packs (`files`, WOFF2 `fonts`, cross-plugin `pluginOverrides`), Track B plugin-scoped `l10n` bundles (`HasUIMessages` isolation), live `plugin/localeChanged` notifications, `< 2ms` static CLI pack loading, and `reims-go plugin locale init|check` translator toolchain with `zh-TW` and `ja-JP` reference packs
- Harden security, WCAG 2.1 AA token contrast, `< 768px` responsive drawer & form layouts, and RTL logical properties; add backend security/locale regression tests and frontend `node --test` static/runtime guard suite in CI

# Conflicts:
#	frontend/src/i18n.ts
#	internal/cli/cli.go
#	internal/i18n/i18n.go
2026-11-30 14:56:19 +08:00
Nwflower 21eef18f7b refactor(runtime,ci): remove GitCode mirror sync and download source 2026-11-29 23:10:27 -07:00
Nwflower d085734c58 docs(roadmap): track WebDAV path safety hardening and small-file I/O 2026-11-29 21:15:15 -07:00
Nwflower 2a87c8d3b0 docs(readme): tighten overview, reorder sections, and update header badges
Condense the intro and highlights in README.md and README.en.md, place screenshots ahead of Quick Start, fold CLI and build-from-source instructions into collapsible blocks, and update header badges.
2026-11-29 21:15:15 -07:00
Nwflower c91f5901a7 chore(debug,ci): add .debug workspace tooling and hygiene checks
Ignore .debug/ locally and add scripts/debug/ helpers (tmp, work, worktree, check, and tests) to enforce workspace hygiene. Run the hygiene check and self-test in CI, and document the .debug/ contract in AGENTS.md and docs/architecture.md.
2026-11-29 21:15:14 -07:00
NwflowerandClaude Opus 5.5 0802f77705 docs(readme): add wordmark banner and badges to the README header
Replace the small logo and plain title with a banner that pairs the app
icon with a monoline "reims-go" wordmark (light and dark versions picked
by GitHub's theme), a two-line tagline, and status badges.

scripts/brand/wordmark.py draws the wordmark from circles and lines and
writes the banners plus standalone assets/wordmark-{light,dark}.svg.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 20:58:43 -07:00
Nwflower 464ff5683f fix(app,vmstart): wait for QEMU exit and commit memory reclaim before restart 2026-11-29 20:22:36 -07:00
Nwflower 1eb7ac949a feat(runtime,cli,ui): support removing inactive runtimes 2026-11-29 20:22:26 -07:00
千川白浪 f20bb61724 Merge pull request #6 from yxc0915/codex/filevault-preboot-input
修复 FileVault 解锁界面的鼠标与小键盘输入
2026-11-29 17:46:13 -08:00
YXC0915 7b023e5c82 docs: show FileVault boot input screenshots 2026-11-30 09:33:25 +08:00
YXC0915 5e67d50012 fix(opencore): support FileVault mouse and keypad input 2026-11-30 09:32:41 +08:00
Nwflower 5c71ac8482 release: v0.2.8
Release Reims-Go / release (push) Canceled after 0s
2026-11-29 18:17:13 -07:00
Nwflower 78d76f7353 feat(host,ui): probe Vulkan 1.3 GPU capabilities and grade compatibility 2026-11-29 18:16:20 -07:00
Nwflower 5096d162cc fix(runtime): extract .tar.zst archives in pure Go 2026-11-29 18:08:19 -07:00
Nwflower 29e9153d64 fix(vmstart): check WHPX before launch and clarify no-accelerator error 2026-11-29 18:08:12 -07:00
234 changed files with 29312 additions and 4416 deletions

No files matched your search

+40 -12
View File
@@ -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
+5 -2
View File
@@ -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 / 快速开始、环境要求与常见问题排查
+13 -5
View File
@@ -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
+68
View File
@@ -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

+68
View File
@@ -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

-18
View File
@@ -239,24 +239,6 @@ jobs:
gh release create "runtime-$c" @assets --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes
if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" }
- name: Mirror alpha prerelease to GitCode (best-effort)
if: github.event_name == 'schedule' || inputs.publish
continue-on-error: true
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
GITHUB_REPO: ${{ github.repository }}
shell: pwsh
run: |
if (-not $env:GITCODE_TOKEN) {
Write-Host 'GITCODE_TOKEN not set; skipping GitCode mirror'
exit 0
}
$tag = "runtime-$($env:RELEASE_ID)"
git fetch --tags origin
git -c credential.helper= push "https://Nwflower:$($env:GITCODE_TOKEN)@gitcode.com/Nwflower/Reims-Go.git" "refs/tags/${tag}:refs/tags/${tag}"
python scripts/sync-gitcode-release.py $tag
- name: Prune old alpha prereleases
if: github.event_name == 'schedule' || inputs.publish
env:
+8 -1
View File
@@ -39,12 +39,19 @@ jobs:
& ./scripts/build-release-notes.ps1 -Tag $ver -OutFile $tmp
Write-Host "PASS CHANGELOG.md contains valid release notes for $ver ($((Get-Item -LiteralPath $tmp).Length) bytes)"
- name: Frontend build
- 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: |
+239
View File
@@ -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)" }
}
+63 -11
View File
@@ -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:
@@ -20,6 +20,7 @@ jobs:
- uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || '' }}
fetch-depth: 0
- uses: actions/setup-go@v5
with:
@@ -35,20 +36,31 @@ 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 from CHANGELOG.md
- 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 {
@@ -67,13 +79,14 @@ jobs:
$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 release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $tag"
Write-Host "Generated $channel release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $tag"
- name: Build frontend
shell: pwsh
@@ -105,7 +118,7 @@ jobs:
if ($LASTEXITCODE) { throw "wails build failed ($LASTEXITCODE)" }
Copy-Item (Join-Path 'build\bin' "reims-go-$tag-windows-amd64.exe") $guiOut
$zipOut = [IO.Path]::ChangeExtension($guiOut, '.zip')
Compress-Archive -LiteralPath $guiOut -DestinationPath $zipOut -CompressionLevel Optimal -Force
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)"
@@ -120,10 +133,12 @@ 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 = ''
@@ -140,15 +155,52 @@ jobs:
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) {
gh release edit $tag --notes-file $notesFile
if ($LASTEXITCODE -ne 0) { throw "gh release edit failed ($LASTEXITCODE)" }
$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" `
--notes-file $notesFile
$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)"
}
}
-75
View File
@@ -1,75 +0,0 @@
name: Sync Mirror to GitCode
on:
push:
branches: [main]
release:
types: [published, released, edited, prereleased]
workflow_dispatch:
inputs:
tag:
description: "Specific release tag to sync (empty = latest app release + all runtime-* releases)"
required: false
default: ""
sync_releases:
description: "Also sync Release metadata and assets to GitCode"
type: boolean
default: true
concurrency:
group: sync-gitcode
cancel-in-progress: false
jobs:
sync:
runs-on: ubuntu-latest
env:
GITCODE_REPO: Nwflower/Reims-Go
GITCODE_USER: Nwflower
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Push main branch and tags to GitCode
env:
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
run: |
set -euo pipefail
if [ -z "$GITCODE_TOKEN" ]; then
echo "GITCODE_TOKEN secret is not configured; skipping."
exit 0
fi
git fetch --tags origin
# Use GIT_ASKPASS so the token never appears in URLs or process argv.
askpass="$(mktemp)"
chmod 700 "$askpass"
cat > "$askpass" <<'EOF'
#!/bin/sh
case "$1" in
*Username*) printf '%s\n' "$GITCODE_USER" ;;
*) printf '%s\n' "$GITCODE_TOKEN" ;;
esac
EOF
trap 'rm -f "$askpass"' EXIT
GIT_TERMINAL_PROMPT=0 GIT_ASKPASS="$askpass" git -c credential.helper= push "https://gitcode.com/${GITCODE_REPO}.git" HEAD:refs/heads/main
GIT_TERMINAL_PROMPT=0 GIT_ASKPASS="$askpass" git -c credential.helper= push "https://gitcode.com/${GITCODE_REPO}.git" --tags
- name: Sync Release and assets to GitCode
if: github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && inputs.sync_releases)
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
GITHUB_REPO: ${{ github.repository }}
TARGET_TAG: ${{ github.event.release.tag_name || inputs.tag }}
run: |
set -euo pipefail
if [ -z "$GITCODE_TOKEN" ]; then
echo "GITCODE_TOKEN secret is not configured; skipping release sync."
exit 0
fi
if [ -n "$TARGET_TAG" ]; then
python3 scripts/sync-gitcode-release.py "$TARGET_TAG"
else
python3 scripts/sync-gitcode-release.py
fi
+3
View File
@@ -28,3 +28,6 @@ Thumbs.db
*.log
.vscode/
.idea/
# Local debugging scratch, work orders, run logs, caches, scratch worktrees
.debug/
+32 -2
View File
@@ -12,8 +12,38 @@
## 存储与产物边界
1. **大体积文件严禁入库**:便携运行时包、macOS 安装包、`.qcow2` 磁盘与快照一律保存在用户或开发者本地指定的 `<DataRoot>`(推荐非系统盘),不得提交到仓库。
2. **临时文件及时清理**:打包草稿、一次性测试目录使用完后清理,不留在仓库工作区。
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/` 与 `patches/README.md` 严禁引用具体工单 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/` 顶层白名单、临时会话、工单与持久文档引用 |
## 事实核验与安全规则
+32
View File
@@ -2,6 +2,38 @@
本文件只记录 Reims-Go 桌面应用的变化。便携运行时(`runtime-*`)的版本另见 [Releases](https://github.com/Nwflower/Reims-Go/releases)。
## 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
### 新功能
+11 -4
View File
@@ -3,7 +3,14 @@
`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.
child process. Local compatibility patches under `patches/` are licensed under
terms compatible with their target upstream projects (see `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.
The portable runtime bundle (`reims-runtime-win-x64-<commit>.tar.zst`) contains
precompiled binaries built from the following upstream open-source projects.
@@ -15,16 +22,16 @@ Each runtime release ships the matching source package, `NOTICE.md`, and
- 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.
+86 -100
View File
@@ -1,15 +1,33 @@
<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>
<h1 align="center">Reims-Go</h1>
<p align="center">
<strong>A macOS virtual machine for Windows. GPU-accelerated, ready out of the box.</strong>
</p>
<p align="center">
Run a GPU-accelerated macOS virtual machine on Windows — prebuilt, ready out of the box.
<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>
<!-- 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&amp;utm_medium=badge&amp;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> ·
@@ -29,106 +47,25 @@
<br />
Reims-Go is a Windows desktop app and CLI wrapper for [reims-vgpu](https://github.com/steelbrain/reims-vgpu). Host checks, runtime installation, macOS downloads, VM creation, and day-to-day management all happen in one window.
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 active development — features and UI are still being refined.
> Early development. Features and UI will keep changing.
<br />
## Highlights
## Features
- **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.
### Out of the Box
Once macOS is running:
- **No compilation required** — Download and verify the portable runtime in one click, without installing MSYS2 or Rust. Automatically falls back to the GitCode mirror if GitHub is unreachable, and honors Windows system proxy settings.
- **Check before you start** — First launch inspects virtualization (WHPX), Vulkan GPUs, and host memory; if Hypervisor Platform is off, enable it with one click.
- **Keep C: clean** — Runtimes, installers, virtual disks, and temporary files all live in the data folder you choose.
- 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
### Installing macOS
- **Direct downloads from Apple** — Download full offline macOS installers on Windows with pause and resume; no network is required during installation.
- **No manual typing** — One click types the install command straight into macOS Recovery Terminal to erase the disk and start installation automatically.
- **Tuned for your PC** — Suggests memory based on available Windows commit memory and recommends crisp HiDPI resolutions for your display and DPI scaling.
- **Pre-configured system language** — Choose your macOS language up front so Recovery and Setup Assistant launch in your preferred language.
- **Import existing disks** — Reuse an existing `.qcow2`, VMDK, or RAW disk when creating a VM.
### Everyday Use
- **Windows interoperability** — Bidirectional clipboard (including images), shared folders with drag-and-drop file delivery, and optional read-only sharing of Windows drives to macOS Finder.
- **Native IME & Unicode input** — Type CJK characters, emoji, and Windows IME text directly into the VM.
- **Live status at a glance** — Screen preview plus live CPU, memory, and disk usage; copy a VM screenshot in one click.
- **System tray integration** — Closing the window keeps clipboard and shared folders running in the background; start, stop, or keep macOS awake from the tray.
- **Edit settings anytime** — Change VM settings even while running; the UI clearly shows whether changes apply immediately or on next start. Enter or exit Recovery mode in one click.
- **Light & dark appearance, English & Chinese UI** — Automatically detects your Windows display language on first launch.
### Performance
- **GPU acceleration** — Accelerate macOS Metal graphics with your Windows discrete Vulkan GPU.
- **Performance-core scheduling** — Automatically pins VMs to P-cores on hybrid CPUs to reduce stutter, or configure per-VM processor affinity live without restarting.
- **Pre-start memory check** — Warns before starting if Windows commit memory is too low to allocate the VM.
### Power Features
- **Instant CoW clones** — Derive an independent copy-on-write clone from any stopped VM in seconds with near-zero initial disk overhead.
- **Restore points** — Save an offline qcow2 snapshot before OS updates or major changes, and roll back with one click.
- **Disk management** — Grow virtual disks or reclaim unused sparse space from stopped VMs.
- **SSH helpers** — Port forwarding, one-click terminal launch, `~/.ssh/config` writer, and VS Code Remote-SSH integration.
- **Built-in CLI** — Run host diagnostics, manage runtimes, download installers, and create, configure, start, or stop VMs from scripts.
- **Diagnostics & Win10 compatibility** — Export a redacted diagnostics archive (`.zip`) in one click; seamless cold-reboot handling on Windows 10 when macOS restarts itself.
<br />
## Quick Start
### Requirements
- Windows 10 / 11 (64-bit) with CPU virtualization enabled in BIOS (Intel VT-x / AMD-V)
- Discrete Vulkan-capable GPU (NVIDIA RTX series recommended)
- 16 GB+ RAM recommended
- 150 GB+ free disk space recommended, 60 GB minimum (an offline installer is ~20 GB and virtual disks grow with use); an internal non-system drive is recommended
### Installation
Download the single-file `reims-go.exe` from [Releases](https://github.com/Nwflower/Reims-Go/releases) and double-click to run.
<details>
<summary>Build from source</summary>
Requires [Go](https://go.dev/dl/), [Node.js](https://nodejs.org), [pnpm](https://pnpm.io), and [Wails](https://wails.io/docs/gettingstarted/installation):
```powershell
git clone https://github.com/Nwflower/Reims-Go
cd Reims-Go
wails build
```
The binary is written to `build\bin\reims-go.exe`.
</details>
### Getting Started
1. **Initial setup** — Pick a data folder on first launch, check host readiness (enable WHPX with one click and reboot Windows if needed), and install the runtime online.
2. **Create a VM** — Click **+** in the sidebar, choose **Offline installer** (or pre-download one on the **Installers** page), and configure CPU, memory, and disk size.
3. **Install macOS** — Start the VM and follow the on-screen Recovery guide: open Terminal in Recovery and click the keyboard icon to type the install command automatically; once Setup Assistant appears, click **Exit recovery mode**.
4. **Install Guest Tools** — On the macOS desktop, click **Install…** on the Guest Tools row in Reims-Go and run the command shown in macOS Terminal to enable clipboard sync, shared folders, and IME input.
5. **Daily management** — Settings, restore points, and SSH tools are on the VM page; the **More** menu provides Send text, Recovery mode, CoW cloning, and diagnostics export.
### Command Line
The CLI lives inside the same `reims-go.exe`: running it with no arguments opens the window, while passing a subcommand executes in the terminal.
```powershell
reims-go doctor | Out-Host # Inspect host environment
reims-go runtime fetch | Out-Host # Install portable runtime online
reims-go installer download tahoe | Out-Host # Download offline installer (resumable)
reims-go vm create macos-tahoe | Out-Host # Create a VM
reims-go vm start macos-tahoe | Out-Host # Start the VM
reims-go vm stop macos-tahoe | Out-Host # Shut down the VM
```
In interactive PowerShell or cmd, pipe to `| Out-Host` so the terminal waits for the command to finish and returns its exit code. Run `reims-go help` to view all commands; pass `--lang en-US` or `--lang zh-CN` to override the output language.
<br />
For everything else, see the [changelog](./CHANGELOG.md).
## Screenshots
@@ -167,12 +104,61 @@ In interactive PowerShell or cmd, pipe to `| Out-Host` so the terminal waits for
</tr>
</table>
<br />
## 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>
## License & Notice
- **Open-source license**: Reims-Go itself is licensed under [Apache-2.0](./LICENSE). Bundled runtime components such as QEMU are distributed as separate executables; see [`NOTICE.md`](./NOTICE.md) for third-party licenses. Every runtime release ships with its corresponding source archive.
- **About macOS**: Reims-Go does not include or distribute any Apple system files; installers are downloaded directly from Apple on the user's machine. **The macOS Software License Agreement permits virtualization only on Apple-branded hardware** — evaluate your own compliance responsibilities on non-Apple hardware. This project is not affiliated with Apple Inc.; macOS is a registered trademark of Apple Inc.
- 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
+86 -100
View File
@@ -1,15 +1,33 @@
<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>
<!-- 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&amp;utm_medium=badge&amp;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> ·
@@ -29,106 +47,25 @@
<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,也不用自己编译。GitHub 连不上时自动改从 GitCode 国内镜像下载,并沿用 Windows 的系统代理设置。
- **先检查再开工** — 首次打开会检查虚拟化、显卡和内存;虚拟化没开的话可以一键开启。
- **不占 C 盘** — 运行时、安装包、虚拟磁盘和临时文件都放在你选的数据目录里。
- 剪贴板(含图片)和共享文件夹与 Windows 互通,文件拖进窗口就能传进 macOS
- 中文输入法和 emoji 可以直接输入
- 升级系统前留个恢复点,出问题一键回滚;关机的虚拟机能秒级派生副本
- 关掉窗口后常驻托盘,剪贴板和共享照常工作
- 支持 SSH 端口转发和 VS Code 远程连接,常用操作也能在命令行里完成
### 装机
- **安装包直接从 Apple 下载** — 在 Windows 上下载完整安装包,可以暂停和续传;装机过程不用联网。
- **不用手敲命令** — 装机命令点一下就自动键入到 macOS 的恢复终端,抹盘和安装都会自动完成。
- **按本机配置推荐** — 内存大小按电脑的空闲内存推荐,分辨率按显示器和缩放推荐清晰的 HiDPI 档位。
- **装机界面用中文** — 可以提前选好 macOS 系统语言,恢复模式和设置助理不再只有英文。
- **导入已有磁盘** — 新建时可以直接用现成的 VMDK 或 RAW 磁盘。
### 日常使用
- **和 Windows 互通** — 双向剪贴板(包括图片)和共享文件夹,把文件拖到窗口里就能传进 macOS;还可以把 Windows 磁盘以只读方式共享给 macOS。
- **直接打中文** — 中文、emoji 和 Windows 输入法都能直接输入到虚拟机。
- **一眼看清状态** — 页面上有屏幕预览,以及 CPU、内存、磁盘的实时占用;一键截屏并复制。
- **常驻托盘** — 关掉窗口后剪贴板和共享照常工作,可以从托盘启动或关闭虚拟机,也可以让 macOS 保持唤醒。
- **随时修改设置** — 虚拟机运行时也能改设置,界面会说明改动是立即生效还是下次启动生效;一键进入或退出恢复模式。
- **浅色、深色外观,中英双语** — 首次启动自动识别 Windows 系统语言。
### 性能
- **显卡加速** — 用 Windows 上的独立显卡加速 macOS 的图形显示。
- **自动挑选性能核** — 在大小核处理器上,虚拟机自动跑在性能核上,减少卡顿;也可以给每台虚拟机单独指定用哪些核,运行中修改立即生效。
- **启动前检查内存** — 内存不够时会先提示,避免启动到一半失败。
### 进阶
- **秒级派生副本** — 已关机的虚拟机可以秒级派生出一台独立副本,副本只记录与原机的差异,刚派生时几乎不占额外空间。
- **恢复点** — 升级系统或大改环境前留一个恢复点,出问题时一键回滚。
- **磁盘管理** — 关机后可以给虚拟磁盘扩容,或回收没有用到的空间。
- **SSH** — 端口转发,一键打开终端、写入 `~/.ssh/config` 或用 VS Code 远程连接。
- **命令行** — 检查环境、安装运行时、下载安装包,以及新建、修改、启动和关闭虚拟机,都能在命令行里完成,方便写脚本。
- **排障** — 一键导出已去掉隐私信息的日志包;Windows 10 上 macOS 自己重启时也能正常回到系统。
<br />
## 快速开始
### 环境要求
- Windows 10 / 11(64 位),处理器支持虚拟化,并已在 BIOS 里开启 Intel VT-x / AMD-V
- 支持 Vulkan 的独立显卡(推荐 NVIDIA RTX 系列)
- 内存建议 16 GB 以上
- 可用磁盘空间建议 150 GB 以上,至少 60 GB(一个安装包约 20 GB,虚拟磁盘会随使用增长);最好不要放在系统盘或外置盘
### 安装
前往 [Releases](https://github.com/Nwflower/Reims-Go/releases) 下载单文件 `reims-go.exe`,双击即可运行。
<details>
<summary>从源码构建</summary>
需预先安装 [Go](https://go.dev/dl/)、[Node.js](https://nodejs.org)、[pnpm](https://pnpm.io) 与 [Wails](https://wails.io/docs/gettingstarted/installation):
```powershell
git clone https://github.com/Nwflower/Reims-Go
cd Reims-Go
wails build
```
产物位于 `build\bin\reims-go.exe`。
</details>
### 上手步骤
1. **初始化** — 首次打开时按引导选好数据目录,完成电脑检查(虚拟化没开可以一键开启,之后需要重启 Windows),再在线安装运行时。
2. **新建虚拟机** — 点侧边栏的 **+**,安装来源选「离线安装包」(也可以先到「安装包」页下载好),再设好 CPU、内存和磁盘。
3. **安装 macOS** — 启动虚拟机,按页面上的装机引导操作:在恢复终端里点键盘图标,装机命令会自动键入,抹盘和安装随即开始;看到「设置助理」后点「退出恢复模式」。
4. **安装 Guest Tools** — 进入 macOS 桌面后,在虚拟机页 Guest Tools 一行点「安装…」,再到 macOS 终端里运行页面给出的命令。装好后剪贴板、共享文件夹和中文输入就能用了。
5. **日常管理** — 设置、恢复点和 SSH 都在虚拟机页上;「更多」菜单里还有发送文本、进入恢复模式、派生副本、导出排障日志等操作。
### 命令行
命令行就在同一个 `reims-go.exe` 里:不带参数会打开窗口,带上子命令就在终端里执行。
```powershell
reims-go doctor | Out-Host # 检查电脑环境
reims-go runtime fetch | Out-Host # 在线安装运行时
reims-go installer download tahoe | Out-Host # 下载安装包(支持续传)
reims-go vm create macos-tahoe | Out-Host # 新建虚拟机
reims-go vm start macos-tahoe | Out-Host # 启动虚拟机
reims-go vm stop macos-tahoe | Out-Host # 关闭虚拟机
```
在 PowerShell 或 cmd 里直接输入命令时,要加上 `| Out-Host`,终端才会等命令执行完再返回。运行 `reims-go help` 可以查看全部子命令,加 `--lang en-US` 会改成英文输出。
<br />
更多功能见[更新日志](./CHANGELOG.md)。
## 界面
@@ -167,12 +104,61 @@ reims-go vm stop 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 本身采用 [Apache-2.0](./LICENSE) 协议。运行时里的 QEMU 等组件作为独立程序随附,各自的许可证见 [`NOTICE.md`](./NOTICE.md);每个运行时 Release 都附带对应的源码包。
- **关于 macOS**:Reims-Go 不包含、不分发任何 Apple 系统文件,安装包由本机直连 Apple 服务器获取。**macOS 软件许可协议仅允许在 Apple 硬件上虚拟化**,在非 Apple 硬件上使用请自行评估合规责任。本项目与 Apple Inc. 无关,macOS 为 Apple Inc. 注册商标。
- Reims-Go 采用 [Apache-2.0](./LICENSE) 协议。运行时里的 QEMU 等组件作为独立程序随附,许可证见 [`NOTICE.md`](./NOTICE.md),每个运行时 Release 都附带对应源码。
- Reims-Go 不包含、不分发任何 Apple 系统文件,安装包由本机直接从 Apple 下载。**macOS 软件许可协议只允许在 Apple 硬件上虚拟化**,在其他硬件上使用请自行评估。本项目与 Apple Inc. 无关,macOS 是 Apple Inc. 的注册商标。
## 友情链接
+1
View File
@@ -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

+1
View File
@@ -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

+327
View File
@@ -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)
}
+5 -4
View File
@@ -10,7 +10,7 @@
2. **包装而非重写引擎**:通过受控子进程调用上游 `reims-ctl`、`reims-util` 与 `qemu-img`,不手写易随上游演进失效的 QEMU 启动参数拼接逻辑。
3. **GUI 与 CLI 单文件同源**:所有业务逻辑下沉在 `internal/`。无参数启动 Wails 桌面窗口,带子命令(`reims-go <subcommand>`)进入命令行模式,供终端、脚本与自动化工具调用。
4. **数据目录隔离**:运行时、下载缓存、虚拟机磁盘、快照与临时文件全部落在用户选定的 `<DataRoot>` 下,不污染系统盘。
5. **原生中英双语**:前后端内置 `zh-CN` / `en-US` 双语字典,自动跟随系统语言并支持运行时切换。
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 ./...`。
---
@@ -57,7 +57,7 @@ flowchart TB
| `internal/vmstart` | GUI 与 CLI 共用的启动前准备:提交内存预检、离线辅助盘、恢复模式引导、客体语言重放、WHPX 兼容处理、启动后 CPU 绑核 |
| `internal/cli` | 命令行子命令实现、单实例参数解析与向界面进程交接 `vm start` |
| `internal/host` | 宿主机体检与硬件调优:WHPX 检测与 UAC 启用、提交内存预检、Vulkan ICD 扫描、三层大小核拓扑与实时绑核、显示器 HiDPI 推荐、音频与磁盘总线探测、窗口置前、IME 文本钩子 |
| `internal/runtime` | 便携运行时拉取(GitHub 主源 + GitCode 国内镜像回退)、原子解压、多版本切换与子进程环境变量构造 |
| `internal/runtime` | 便携运行时拉取(GitHub Releases)、原子解压、多版本切换与子进程环境变量构造 |
| `internal/fetch` | 发布附件下载:HTTP `Range` 续传与按发布页 `SHA256SUMS.txt` 强制校验,运行时安装与应用内更新共用 |
| `internal/selfupdate` | 应用内更新:把已校验的新版 `reims-go.exe` 换入运行中程序的位置、重新拉起与残留清理 |
| `internal/installer` | 包装 `reims-util --json` 实现 macOS 离线安装包查询、宿主机直连下载、断点续传、互斥锁保护与缓存清理 |
@@ -66,11 +66,12 @@ flowchart TB
| `internal/guesttools` | 本地回环鉴权 HTTP/WebDAV 服务:图文双向剪贴板、共享目录、Windows 盘符只读共享、防休眠开关与 `REIMSTOOLS` 辅助盘生成 |
| `internal/opencore` | 改写 OpenCore 镜像中的 `prev-lang:kbd`,实现系统外预设 macOS 语言 |
| `internal/netproxy` | 统一 HTTP Transport:优先环境变量代理,回退读取 Windows 系统代理配置 |
| `internal/config`、`internal/i18n` | 应用配置持久化(`reims-go.json`)与 Go 端双语消息/结构化错误码 |
| `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/`(页面与对话框)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
| `patches/` | 上游临时补丁队列与 PR 跟踪,见 [`patches/README.md`](../patches/README.md) |
| `scripts/` | 便携运行时打包、二进制裁剪与符号分离、MSYS2 源码归档、`alpha` 准入与冒烟脚本 |
| `scripts/` | 便携运行时打包、二进制裁剪与符号分离、MSYS2 源码归档、`alpha` 准入与冒烟脚本,以及 `scripts/debug/` 本地调试目录管理与卫生校验脚本 |
---
+3 -3
View File
@@ -82,7 +82,7 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台
## 6. 视觉、图标与无障碍基线
- **样式令牌化**:所有颜色、字号、间距(4 px 网格)、圆角与阴影统一引用 [`frontend/src/styles/tokens.css`](../frontend/src/styles/tokens.css) 中的 CSS 变量,禁止在组件内联写死颜色或字号。
- **字体**:内嵌开源 Inter Variable 作为拉丁字体,并针对 Windows DirectWrite 特性显式映射中文字体字重,避免正文过细或中英混排断层。
- **字体与区域排印**:内嵌开源 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 下无文字截断。
@@ -101,9 +101,9 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台
| `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),不在组件中零散拼接。
格式化逻辑统一集中在 [`frontend/src/lib/format.ts`](../frontend/src/lib/format.ts)(数字、列表与相对时间统一经原生 `Intl` API 按当前语种格式化),不在组件中零散拼接。跨宿主与客户机语言的安装引导提示(如宿主机中文操作英文 macOS 恢复环境)自动采用「宿主译名 (`Guest Term`)」双标,同语种则单标。开发模式下提供 `en-XA` 伪本地化语种用于排查硬编码与长词截断。
### 7.2 文案风格
- **克制直接**:标题用名词;按钮用 2–5 字动词;描述控制在清晰的一句话;不使用「请」「您」「成功」和感叹号;按钮和短提示末尾不加句号。
+8 -7
View File
@@ -128,7 +128,7 @@ flowchart TB
| :--- | :--- | :--- | :--- |
| `themes`(令牌、配色方案、字体、图标、背景、提示音、样式表、状态装饰) | Builtin · L1 | 按 id,同一时刻仅一个主题包生效 | 回退内置默认主题 |
| `uiScripts`(交互主题脚本) | 主窗口受信任脚本 | 随所属主题包 | 单个功能出错只停用该功能;整体失败回退到无脚本的主题 |
| `locales`(多语种语言包:`locale` / `label` / `fallback` / `file` / `backendFile` / `messages` / `backend`) | Builtin · L1(纯 JSON,免高危权限) | 按 BCP-47 语种合并,自动出现在设置语言下拉框 | 缺失词条回退 `fallback` / 内置英语;停用插件后自动回退内置语言 |
| `locales`(声明式语言包:分域 `files`、可选包内 `.woff2` 字体、`pluginOverrides` 跨插件翻译覆盖) | Builtin · L1(纯 JSON + WOFF2,免高危权限) | 按 BCP-47 语种与信任等级合并,覆盖 GUI、Win32 浮层、托盘与 CLI | 缺失词条沿有界多跳 `fallback` 链回退至内置语种;单条坏模板自动回退不崩宿主 |
| `inputFilters` | Builtin · L1(仅声明式规则) | 有序列表 | 规则非法即忽略;宿主输入服务异常时卸载钩子、放行原始输入 |
| `vmTemplates` | Builtin · L1 | 列表 | 跳过非法项 |
| `runtimeSources` | Builtin · L1 | 列表 | 跳过该源,回退其他源 |
@@ -302,7 +302,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
| :--- | :--- |
| `schema` | 清单格式版本 |
| `id` / `version` | 反向域名 id;SemVer |
| `name` / `description` | `zh-CN` / `en-US` 本地化文本,**无需执行插件代码即可读取** |
| `name` / `description` | 多语种本地化文本(内置 `zh-CN` / `en-US` 及任意 BCP-47 扩展键),**无需执行插件代码即可读取** |
| `l10n` | 可选的包内私有词表目录(如 `"locales"`),存放 `<locale>.json` 供插件自身 UI、iframe 面板与 Sidecar 使用;独立语言包可通过 `pluginOverrides` 在外部补充或覆盖任意第三方插件的清单字段与私有词条 |
| `publisher` / `license` / `homepage` | 来源与许可,市场审核依据 |
| `engines` | `reims-go` 版本范围与 `pluginApi` 范围,**下载前预检** |
| `platforms` | 如 `windows-x64` |
@@ -344,7 +345,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
## 8. 进程监管与通信协议
- **协议**:stdin/stdout 双向 JSON-RPC 2.0,采用 `Content-Length` 分帧(LSP 风格);握手交换 `pluginApi` 版本与能力;stdout 只走协议帧,日志一律走 stderr 并由宿主采集。截图、磁盘镜像等大对象不进 JSON,经插件数据目录内的文件路径传递。
- **协议**: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。
@@ -377,8 +378,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
- **安装来源**:本地包导入(首批)、市场索引(后续)、开发者模式本地目录链接。
- **随主程序附带的插件**:需要时可以标准插件包形式嵌入 `reims-go.exe`,信任等级为 `official`,版本跟随主程序;可启用/停用,不可卸载。
- **事务安装**:下载到 `tmp` → 校验 `SHA256SUMS` 与签名 → 核对包内 `id` / `version` 与预期一致(防偷换)→ 兼容预检 → 原子 rename 到 `pkgs/<id>/<version>` → 提交 `state.json`。任一步失败都不改变现状。
- **市场索引**:独立仓库发布静态 `index.json`(GitHub 主源 + GitCode 镜像,复用运行时下载源的回退与代理逻辑),含版本、`engines`、下载地址、SHA-256 与签名者;主程序内嵌兜底副本。
- **事务安装与静态准入门禁**:下载到 `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 命令时惰性拉取,使用内存 + `<DataRoot>/plugins/index-cache.json` 双层缓存与主程序内嵌兜底副本,网络失败不覆写有效缓存。
- **更新与回滚**:新旧版本并存、切换指针,保留最近若干版本;插件同样区分 `alpha` / `stable` 通道,默认只取 `stable`。
- **安全模式**:`reims-go --safe-mode` 跳过全部第三方插件,界面顶部显示横幅与插件管理入口;以启动哨兵文件检测上次插件初始化阶段异常退出,下次启动询问是否进入安全模式。
- **市场红线**:拒收含 Apple 专有文件、SMBIOS 真值或闭源固件的包;运行时包必须附源码与许可证。
@@ -389,8 +390,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
| 入口 | 内容 |
| :--- | :--- |
| CLI | `reims-go plugin list / install / link <dir> / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor / run <id> <command>`;`vm create --driver <id>` |
| 应用设置 → 插件 | 分组展示内置插件与第三方插件:核心置顶、显示「始终启用」且无开关;其余显示来源与信任标签、权限摘要、启用开关、故障状态与日志入口;本地包导入 |
| CLI | `reims-go plugin list / search / install <zip\|id> / update [id] / 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` 渲染专属表单 |
+1 -1
View File
@@ -94,7 +94,7 @@ reims-runtime-<commit>/
> **CI 边界**:GitHub 托管的 Windows Server runner 不提供 WHPX,也无法复现 Windows 10 兼容性问题。CI 只验证可编译与控制面基本可用,实际能否启动 macOS 桌面必须经过第 5 节的真机冒烟。
### 3.3 客户端下载与安装
`internal/runtime` 默认从 GitHub Releases(tag `runtime-<commit>`)拉取,并支持官方镜像源 [GitCode `Nwflower/Reims-Go`](https://gitcode.com/Nwflower/Reims-Go) 自动回退(`auto` / `github` / `gitcode`),沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。
`internal/runtime` 默认从 GitHub Releases(tag `runtime-<commit>`)拉取,沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。
---
+2 -1
View File
@@ -12,7 +12,7 @@
## 已实现能力(截至 v0.2.6)
### 1. 免编译与环境初始化
- **便携运行时体系**:剥离 MSYS2 / Rust / 源码仓库依赖,支持 GitHub Release(含 GitCode 国内镜像回退与系统代理)在线下载、断点续传、SHA-256 校验、原子切换与本地 `.tar.zst` 导入。
- **便携运行时体系**:剥离 MSYS2 / Rust / 源码仓库依赖,支持 GitHub Release(含系统代理)在线下载、断点续传、SHA-256 校验、原子切换与本地 `.tar.zst` 导入。
- **宿主机体检与引导**:免提权检测 WHPX(缺失时支持 UAC 一键开启)、物理与可用提交内存预检、Vulkan 独立显卡识别、大小核(P/E/LP-E)拓扑与处理器计划检查、数据盘总线类型风险提示。
- **统一发布物**:桌面界面与命令行共用单个 `reims-go.exe`,支持浅色/深色外观与中英双语。
@@ -41,6 +41,7 @@
- 持续跟进上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的 Windows 图形与窗口改进(热切全屏、无黑边窗口缩放、原生 Windows Vulkan 后端、首帧延迟优化、自由指针 `Win → Command` 映射),合入后经 `alpha` 冒烟升级至 `stable`(跟踪明细见 [patches/README.md](../patches/README.md))。
- 推动当前本地兼容性补丁上游化,并逐步清零 `patches/` 队列。
- 在真实宿主完成长时间开发负载验证(编译、浏览器、多任务、图文剪贴板、WebDAV 挂载、Windows 盘符只读共享、音频/麦克风与休眠唤醒恢复)。
- 修复 WebDAV 共享目录可经 Junction 逃逸的路径校验缺陷,并把共享目录与只读盘统一到基于 `os.Root` 的路径安全层;随后按测量结果推进小文件 I/O 优化。
### 3. 恢复点与磁盘操作可靠性
- 对停机恢复点(创建/回滚/删除)、CoW 派生启动、大容量 VMDK 转换以及停机扩容/空间回收完成真机中断与边界测试,确保空间不足或中途中断不会破坏原盘与 backing file 链。
+1 -1
View File
@@ -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" />
+2 -1
View File
@@ -1,10 +1,11 @@
{
"name": "reims-go-frontend",
"private": true,
"version": "0.2.7",
"version": "0.2.9",
"type": "module",
"scripts": {
"dev": "vite",
"test": "node --test scripts/test-i18n.mjs",
"build": "tsc --noEmit && vite build && node scripts/check-ui-contract.mjs",
"preview": "vite preview"
},
+1 -1
View File
@@ -1 +1 @@
fd01023ab020f4fa559696be6708a9a3
640cefb23cef4711cf51530e8a87140c
+251
View File
@@ -0,0 +1,251 @@
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',
'InstallersPage.tsx',
'PluginsPage.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('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']}`)
})
+100 -27
View File
@@ -11,14 +11,14 @@ import { TitleMenus } from './components/TitleMenus'
import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule'
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
import { VMAction, VMPage } from './components/VMPage'
import { I18nKey, resolveActiveLocale, setPluginLocales, t } from './i18n'
import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
import { LogLine, appendLog } from './lib/logs'
import { macOSMajor } from './lib/macosRelease'
import { currentTask, finishedTaskTTL, pruneFinishedTasks, upsertTask } from './lib/tasks'
import { applyActiveTheme, type UIStateSnapshot } from './lib/themeEngine'
import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine'
import { latestVMStats } from './lib/vmStats'
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, RuntimeSource, Task, VMDetail } from './types'
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types'
import { Button, Tip, TooltipProvider } from './ui/controls'
import { Modal } from './ui/dialog'
import { Toaster, useToasts } from './ui/toast'
@@ -37,7 +37,7 @@ const PluginsPage = lazy(() => import('./components/PluginsPage').then((m) => ({
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage })))
const errText = (e: unknown) => String(e).replace(/^Error:\s*/, '')
const errText = (e: unknown) => parseAppError(e).summary
const failKey: Record<VMAction, I18nKey> = {
start: 'failStart',
@@ -200,7 +200,17 @@ export const App: React.FC = () => {
}, [])
useEffect(() => {
refresh()
Promise.all([
api.GetPluginUIContributions().catch(() => null),
refresh(),
]).then(([pui]) => {
if (pui) {
setPluginLocales(pui.locales)
setPluginUI(pui)
} else {
setPluginUI({} as PluginUIContributions)
}
})
events.emitUIPong()
const offPing = events.onUIPing(() => { events.emitUIPong() })
const offState = events.onStateChanged(() => {
@@ -216,7 +226,6 @@ export const App: React.FC = () => {
}
setLogLines((prev) => appendLog(prev, entry))
})
api.GetPluginUIContributions().then(setPluginUI).catch(() => {})
api.GetActiveTheme().then(setActiveThemePayload).catch(() => {})
// Tasks: seed from the backend, then follow events.
api.GetTasks().then((list) => {
@@ -294,11 +303,26 @@ export const App: React.FC = () => {
// Live VM stats are polled by lib/vmStats.ts and read where they are shown
// (VMPage), so a 3-second tick no longer re-renders the whole App.
setPluginLocales(pluginUI?.locales)
const locale: Locale = resolveActiveLocale(state?.config.locale, pluginUI?.locales)
const lastPluginLocalesRef = useRef<typeof pluginUI>(undefined)
if (lastPluginLocalesRef.current !== pluginUI) {
lastPluginLocalesRef.current = pluginUI
setPluginLocales(pluginUI?.locales)
}
const locale: Locale = resolveActiveLocale(state?.config.locale, pluginUI?.locales, state?.detected_locale)
const dir = localeDir(locale)
useEffect(() => {
document.documentElement.lang = locale
}, [locale])
const html = document.documentElement
html.lang = locale === 'en-XA' ? 'en' : locale
html.dir = dir
html.dataset.locale = locale
const chain = buildFallbackChain(locale, pluginUI?.locales)
const fontPack = chain
.map((step) => pluginUI?.locales?.find((p) => p.locale === step))
.find((p) => p?.fonts && p.fonts.length > 0)
applyActiveLocaleFonts(fontPack?.fonts)
}, [locale, dir, pluginUI?.locales])
useEffect(() => () => { disposeActiveThemeAndLocaleFonts() }, [])
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : ''
const pending = selectedVM ? (state?.pending_changes[selectedVM.name] ?? []) : []
@@ -322,8 +346,10 @@ export const App: React.FC = () => {
} else {
toasts.push({ kind: 'ok', title: isRuntime ? tr('toastRuntimeReady', { v: task.result || task.subject }) : tr('toastInstallerReady', { v: task.subject }) })
}
} else if (task.status === 'canceled') toasts.push({ kind: 'ok', title: tr('toastDownloadPaused') })
else fail(tr(isRuntime ? 'failRuntime' : isRecovery ? 'failAttachInstaller' : 'failDownload'), task.error ?? '')
} else if (task.status === 'canceled') {
const wasQueued = task.step.toLowerCase().includes('waiting for another download')
toasts.push({ kind: 'ok', title: tr(wasQueued ? 'toastQueueCanceled' : 'toastDownloadPaused') })
} else fail(tr(isRuntime ? 'failRuntime' : isRecovery ? 'failAttachInstaller' : 'failDownload'), task.error ?? '')
}
setTaskMap((prev) => upsertTask(prev, task))
}
@@ -338,8 +364,20 @@ export const App: React.FC = () => {
const setChannel = (alpha: boolean) => {
api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(() => refresh()).catch((e) => fail(tr('failGeneric'), e))
}
const setSource = (source: RuntimeSource) => {
api.SetRuntimeSource(source).then(() => refresh()).catch((e) => fail(tr('failGeneric'), e))
const appUpdateChannel = state?.config.app_update_channel === 'alpha' || state?.config.app_update_channel === 'dev'
? state.config.app_update_channel
: 'stable'
const setAppUpdateChannel = async (ch: 'stable' | 'alpha' | 'dev') => {
await api.SetAppUpdateChannel(ch)
setDismissedUpdate('')
try { localStorage.removeItem('reims-go-update-dismissed') } catch {}
await refresh()
try {
setAppUpdate(await api.CheckAppUpdate(true))
} catch (e) {
setAppUpdate(null)
throw e
}
}
const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }
@@ -381,13 +419,13 @@ export const App: React.FC = () => {
// One toast after an update restart: the version changed since the last run.
useEffect(() => {
const v = state?.app_version
if (!v) return
if (!v || pluginUI === null) return
try {
const last = localStorage.getItem('reims-go-last-version')
if (last && last !== v) toasts.push({ kind: 'ok', title: tr('updateDoneToast', { v }) })
localStorage.setItem('reims-go-last-version', v)
} catch {}
}, [state?.app_version])
}, [state?.app_version, pluginUI !== null])
const importRuntime = async () => {
try {
const file = await api.PickFile(tr('importRuntime'), '*.tar.zst;*.zip')
@@ -412,6 +450,8 @@ export const App: React.FC = () => {
const uiStateRef = useRef<UIStateSnapshot>({
appearance: theme,
motion: reducedMotion ? 'reduced' : 'full',
locale,
dir,
view: currentView,
vmName: selectedVM?.name ?? '',
vmState: effectiveState,
@@ -424,6 +464,8 @@ export const App: React.FC = () => {
uiStateRef.current = {
appearance: theme,
motion: reducedMotion ? 'reduced' : 'full',
locale,
dir,
view: currentView,
vmName: selectedVM?.name ?? '',
vmState: effectiveState,
@@ -441,7 +483,8 @@ export const App: React.FC = () => {
el.dataset.hasError = String(hasAnyError)
el.dataset.sidebarCollapsed = String(!sidebarOpen)
el.dataset.safeMode = String(!!state?.safe_mode)
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode])
notifyInteractiveThemeState(uiStateRef.current)
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme])
// Apply active theme pack (zero extra CSS for builtin default theme, §5.1 & §8.1).
useEffect(() => {
@@ -489,8 +532,19 @@ export const App: React.FC = () => {
const loadSerial = (name?: string) => loadVMLog(true, name)
const loadQemu = (name?: string) => loadVMLog(false, name)
const fail = (title: string, e: unknown) =>
toasts.push({ kind: 'error', title, description: errText(e), action: { label: tr('viewLogs'), onClick: () => openLogs('app') } })
const fail = (title: string, e: unknown) => {
const parsed = parseAppError(e)
toasts.push({
kind: 'error',
title,
description: parsed.summary,
errorCode: parsed.code,
rawDetail: parsed.rawDetail,
detailsLabel: tr('errRawDetailsToggle'),
copyDetailsLabel: tr('errCopyDetails'),
action: { label: tr('viewLogs'), onClick: () => openLogs('app') },
})
}
const runVMAction = async (name: string, action: VMAction, fn: () => Promise<void>, okTitle?: string) => {
setBusy((b) => ({ ...b, [name]: action }))
@@ -697,11 +751,12 @@ export const App: React.FC = () => {
}
// The wizard closes as soon as the create starts; progress lives in the status bar
// (vm-create task). On failure the toast reopens the wizard with the same answers.
// (vm-create task). On failure or cancel the toast offers returning to the wizard.
const submitCreate = (payload: CreateOpts, draft: WizardDraft) => {
setShowWizard(false)
setWizardDraft(null)
const name = payload.name
const hasDownload = payload.source_mode === 'offline' || payload.source_mode === 'apple'
api.CreateVM(payload)
.then(() => {
toasts.push({ kind: 'ok', title: tr('toastCreated', { name }) })
@@ -710,10 +765,24 @@ export const App: React.FC = () => {
})
.catch((e) => {
void refresh()
if (/\bcontext canceled\b/i.test(errText(e))) {
toasts.push({
kind: 'ok',
title: tr('toastCreateCanceled', { name }),
description: hasDownload ? tr('toastCreateCanceledPartial') : undefined,
action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } },
})
return
}
const parsed = parseAppError(e)
toasts.push({
kind: 'error',
title: tr('failCreate', { name }),
description: errText(e),
description: parsed.summary,
errorCode: parsed.code,
rawDetail: parsed.rawDetail,
detailsLabel: tr('errRawDetailsToggle'),
copyDetailsLabel: tr('errCopyDetails'),
action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } },
})
})
@@ -737,7 +806,8 @@ export const App: React.FC = () => {
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
shortcutRef.current = (e: KeyboardEvent) => {
if (!e.ctrlKey || e.altKey || e.metaKey) return
if (showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget) return
if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return
if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return
const k = e.key.toLowerCase()
if (k === 'n') { e.preventDefault(); openWizard() }
else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) }
@@ -875,7 +945,6 @@ export const App: React.FC = () => {
onFinish={() => setSetupStage(null)}
onError={fail}
onChannel={setChannel}
onSource={setSource}
onInstallRuntime={installRuntime}
onCancelTask={cancelTask}
onImportRuntime={importRuntime}
@@ -883,6 +952,7 @@ export const App: React.FC = () => {
</Suspense>
) : (
<div className={`workspace rg-p-workspace${sidebarOpen ? '' : ' sidebar-hidden'}`}>
{sidebarOpen && <div className="sidebar-backdrop" aria-hidden="true" onClick={toggleSidebar} />}
<Sidebar
locale={locale}
vms={vms}
@@ -895,7 +965,7 @@ export const App: React.FC = () => {
onActivate={primaryAction}
onNew={openWizard}
onVMContextAction={onSidebarContextAction}
downloading={Object.values(taskMap).some((x) => x.kind === 'installer-download' && x.status === 'running')}
downloading={Object.values(taskMap).some(isActiveInstallerTask)}
safeMode={state?.safe_mode}
updateDot={!!appUpdate?.has_update}
updateCard={showUpdateCard ? (
@@ -1004,6 +1074,8 @@ export const App: React.FC = () => {
<AboutPage
locale={locale}
appVersion={state.app_version}
appUpdateChannel={appUpdateChannel}
onAppUpdateChannel={setAppUpdateChannel}
appUpdate={appUpdate}
onAppUpdate={setAppUpdate}
updatePhase={updatePhase}
@@ -1022,9 +1094,9 @@ export const App: React.FC = () => {
onRefresh={refresh}
onNewVM={openWizard}
onError={fail}
onToast={(title) => toasts.push({ kind: 'ok', title })}
runtimeTask={runtimeTask}
onChannel={setChannel}
onSource={setSource}
onInstallRuntime={installRuntime}
onCancelTask={cancelTask}
/>
@@ -1066,6 +1138,7 @@ export const App: React.FC = () => {
<CreateWizard
locale={locale}
host={state.host}
tasks={Object.values(taskMap)}
draft={wizardDraft}
onClose={() => { setShowWizard(false); setWizardDraft(null) }}
onSubmit={submitCreate}
@@ -1180,7 +1253,7 @@ export const App: React.FC = () => {
/>
)}
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} />
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} dir={dir} />
</div>
</TooltipProvider>
)
+116 -3
View File
@@ -1,18 +1,25 @@
import { Copy, Download, ExternalLink, RotateCw } from 'lucide-react'
import { Copy, Download, ExternalLink, RotateCw, Scale } from 'lucide-react'
import React, { useEffect, 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'
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
@@ -29,15 +36,28 @@ interface Props {
/** About page: version and updates, project links and the community group. */
export const AboutPage: React.FC<Props> = ({
locale, appVersion, appUpdate, onAppUpdate, updatePhase, updateTask, installing,
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 openLicenses = () => {
setLicenseOpen(true)
if (!licenses) {
api.GetLicenseTexts()
.then((res) => setLicenses({ license: res?.license ?? '', notice: res?.notice ?? '' }))
.catch((e) => onError(tr('failGeneric'), e))
}
}
const runUpdateCheck = async (force: boolean) => {
setCheckingUpdate(true)
@@ -81,8 +101,26 @@ export const AboutPage: React.FC<Props> = ({
}
}
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') {
@@ -99,7 +137,7 @@ export const AboutPage: React.FC<Props> = ({
} else if (updatePhase === 'failed') {
updateSub = <div className="row-sub warn-text" title={updateTask?.error}>{tr('updateFailedSub')}</div>
} else if (appUpdate?.has_update) {
updateSub = <div className="row-sub">{tr('appUpdateAvailable', { v: appUpdate.latest })}</div>
updateSub = <div className="row-sub">{tr(updateAvailableKey, { v: appUpdate.latest })}</div>
} else if (updateErr) {
updateSub = <div className="row-sub" title={updateErr}>{tr('appUpdateLookupFailed')}</div>
}
@@ -148,6 +186,30 @@ export const AboutPage: React.FC<Props> = ({
{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>
@@ -176,6 +238,20 @@ export const AboutPage: React.FC<Props> = ({
</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={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">
@@ -216,6 +292,43 @@ export const AboutPage: React.FC<Props> = ({
</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={setLicenseTab}
options={[
{ value: 'notice', label: tr('aboutLicensesTabNotice') },
{ value: 'license', label: tr('aboutLicensesTabLicense') },
]}
/>
<pre className="license-pre">
{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>
)
}
+4 -3
View File
@@ -1,6 +1,7 @@
import { AlertTriangle, Check, Cpu } from 'lucide-react'
import React, { useEffect, useMemo, useState } from 'react'
import { I18nKey, t } from '../i18n'
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'
@@ -110,7 +111,7 @@ export const AffinityDialog: React.FC<Props> = ({
setDisableEcoQoS(st.disable_eco_qos)
})
.catch((e) => {
if (live) setErr(String(e).replace(/^Error:\s*/, ''))
if (live) setErr(parseAppError(e).summary)
})
.finally(() => {
if (live) setLoading(false)
@@ -211,7 +212,7 @@ export const AffinityDialog: React.FC<Props> = ({
})
onApplied(updated)
} catch (e) {
setErr(String(e).replace(/^Error:\s*/, ''))
setErr(parseAppError(e).summary)
} finally {
setSaving(false)
}
+7 -2
View File
@@ -1,4 +1,5 @@
import React from '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'
@@ -28,6 +29,7 @@ export const AppSettingsPage: React.FC<Props> = ({
const { host, config, optimizations } = state
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
const missingFontScript = state.missing_font_hint || ''
const guard = (fn: () => Promise<unknown>) => async () => {
try {
@@ -125,13 +127,16 @@ export const AppSettingsPage: React.FC<Props> = ({
<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={locale}
value={config.locale || 'auto'}
onChange={onSetLocale}
options={getLocaleOptions(locales)}
options={getLocaleOptions(locales, locale, state.detected_locale)}
/>
</div>
</div>
+65 -16
View File
@@ -1,13 +1,19 @@
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
import React, { Suspense, lazy, useEffect, useState } from 'react'
import { I18nKey, locText, t } from '../i18n'
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,
@@ -22,7 +28,8 @@ import {
splitLangLabel,
sshCommand,
} from '../lib/format'
import { CachedInstaller, CreateOpts, DriverSummary, 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'
@@ -40,6 +47,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. */
@@ -65,7 +73,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.
@@ -102,8 +110,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,
@@ -158,9 +168,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
@@ -175,7 +188,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) }
@@ -195,6 +208,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)
@@ -322,11 +337,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}` : ''}`,
}
})}
/>
)}
/>
@@ -358,7 +381,7 @@ 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)}
/>
}
/>
@@ -485,7 +508,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"
@@ -494,7 +532,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,
})),
]}
/>
}
@@ -612,7 +661,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
})
onClose()
} catch (e) {
setErr(String(e).replace(/^Error:\s*/, ''))
setErr(parseAppError(e).summary)
} finally {
setDriverCreating(false)
}
+10 -49
View File
@@ -1,4 +1,5 @@
import React from 'react'
import { resolveActiveLocale, t } from '../i18n'
import { events } from '../wails'
interface State {
@@ -28,65 +29,25 @@ export class ErrorBoundary extends React.Component<{ children: React.ReactNode }
const { error, stack } = this.state
if (!error) return this.props.children
const isZh = (document.documentElement.lang || '').toLowerCase().startsWith('zh')
const docLocale = typeof document !== 'undefined' ? document.documentElement.dataset.locale : undefined
const loc = resolveActiveLocale(docLocale || undefined)
return (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
padding: 24,
background: 'var(--surface-canvas, #1c1c1e)',
color: 'var(--text, #f5f5f7)',
fontFamily: 'var(--font-sans, system-ui, sans-serif)',
}}
>
<div
style={{
maxWidth: 560,
width: '100%',
padding: 20,
borderRadius: 12,
border: '1px solid var(--border, rgba(128,128,128,0.25))',
background: 'var(--surface-1, rgba(128,128,128,0.08))',
display: 'flex',
flexDirection: 'column',
gap: 12,
}}
>
<h2 style={{ margin: 0, fontSize: 16 }}>
{isZh ? '界面发生异常' : 'Interface encountered an error'}
<div className="error-boundary">
<div className="error-boundary-card" role="alert">
<h2 className="error-boundary-title">
{t(loc, 'errorBoundaryTitle')}
</h2>
<p style={{ margin: 0, fontSize: 13, opacity: 0.85 }}>
{isZh
? '渲染过程出现未捕获异常,虚拟机和后台服务不受影响。你可以重新加载界面。'
: 'An unexpected UI error occurred. Running VMs and background services are unaffected.'}
</p>
<pre
style={{
margin: 0,
padding: 10,
borderRadius: 8,
fontSize: 12,
maxHeight: 180,
overflow: 'auto',
background: 'var(--surface-0, rgba(0,0,0,0.2))',
border: '1px solid var(--border, rgba(128,128,128,0.2))',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
}}
>
<pre className="error-boundary-pre selectable">
{error.message || String(error)}
{stack ? `\n\n${stack}` : ''}
</pre>
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
<div className="error-boundary-actions">
<button
type="button"
className="btn btn-primary"
onClick={() => window.location.reload()}
>
{isZh ? '重新加载界面' : 'Reload UI'}
{t(loc, 'errorBoundaryReload')}
</button>
</div>
</div>
+67 -21
View File
@@ -1,8 +1,10 @@
import { Cpu, HardDrive, MemoryStick, Plus, 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 { formatBytes } from '../lib/format'
import { AppState, Locale, RuntimeSource, StorageBreakdown, 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'
@@ -13,16 +15,18 @@ interface Props {
onRefresh: () => void
onNewVM?: () => void
onError: (title: string, e: unknown) => void
onToast?: (title: string) => void
runtimeTask: Task | null
onChannel: (alpha: boolean) => void
onSource: (source: RuntimeSource) => void
onInstallRuntime: (commit: string) => void
onCancelTask: (id: string) => void
}
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, onError, runtimeTask, onChannel, onSource, 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 [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)
@@ -64,6 +68,20 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, 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')
@@ -138,7 +156,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
<div className="card-title">
<span>{tr('storageBreakdownTitle')}</span>
<span className="spacer" />
<span className="muted tnum" style={{ fontSize: 12, fontWeight: 500 }}>{formatBytes(storage.total_bytes)}</span>
<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}%` }} />}
@@ -148,15 +166,15 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
<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)}
{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)}
{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)}
{tr('storageRuntimes')} · {formatBytes(storage.runtimes_bytes, locale)}
</span>
</div>
</section>
@@ -174,11 +192,9 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
<RuntimeOnline
locale={locale}
channel={config.runtime_channel === 'alpha' ? 'alpha' : 'stable'}
source={config.runtime_source === 'github' || config.runtime_source === 'gitcode' ? config.runtime_source : 'auto'}
installed={runtimes ?? []}
task={runtimeTask}
onChannel={onChannel}
onSource={onSource}
onInstall={onInstallRuntime}
onCancel={onCancelTask}
/>
@@ -189,7 +205,28 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, 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>
))}
@@ -202,17 +239,26 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
{realGPUs.length === 0 ? (
<div className="row"><span className="row-sub">—</span></div>
) : (
realGPUs.map((g) => (
<div className="row" key={g.vulkan_icd}>
<div className="row-main">
<div className="row-title" 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 ${g.kind === 'discrete' ? 'badge-accent' : ''}`}>{gpuKind(g.kind)}</span>
{g.compat === 'unsupported' && <span className="badge badge-warn">{tr('gpuCompatUnsupported')}</span>}
{g.compat === 'warn' && <span className="badge badge-warn">{tr('gpuCompatWarn')}</span>}
{isRec && g.compat !== 'warn' && g.compat !== 'unsupported' && <span className="badge badge-ok">{tr('gpuRecommended')}</span>}
</div>
{meta && <div className="row-sub">{meta}</div>}
{hint && <div className="row-sub warn-text">{hint}</div>}
</div>
</div>
</div>
))
)
})
)}
</div>
</section>
+190 -55
View File
@@ -1,8 +1,23 @@
import { AlertTriangle, Check, ChevronDown, Download, LoaderCircle, Pause, Plus, RefreshCw, Trash } from 'lucide-react'
import { AlertTriangle, Check, ChevronDown, Clock, Download, LoaderCircle, Pause, Plus, RefreshCw, Trash, X } 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 { macOSMajor } from '../lib/macosRelease'
import { taskDetail } from '../lib/tasks'
import {
ActiveInstallerMatch,
findActiveCachedTask,
findActiveOfflineTask,
groupUnmatchedInstallerTasks,
isActiveInstallerTask,
isInstallerTask,
taskDetail,
taskInstallerKey,
taskInstallerKind,
taskInstallerPhase,
taskInstallerVersion,
taskStopAction,
} from '../lib/tasks'
import { CachedInstaller, HostReport, Locale, Release, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { api } from '../wails'
@@ -25,6 +40,15 @@ const needBytes = (r: Release) => r.size * 1.1
type ReleaseGroup = { key: string; title: string; major: number | null; releases: Release[] }
type DownloadedRow = {
key: string
title: string
version: string
kind: CachedInstaller['kind']
cached?: CachedInstaller
active: ActiveInstallerMatch | null
}
/** Newest point release first, one card per macOS major version. */
function groupReleases(releases: Release[]): ReleaseGroup[] {
const groups = new Map<string, ReleaseGroup>()
@@ -40,6 +64,13 @@ function groupReleases(releases: Release[]): ReleaseGroup[] {
.sort((a, b) => (b.major ?? -1) - (a.major ?? -1) || a.title.localeCompare(b.title))
}
function formatOnlineTitle(version: string): string {
const v = version.trim()
if (!v || v.toLowerCase() === 'latest') return 'macOS'
const words = v.split(/[-_\s]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1))
return `macOS ${words.join(' ')}`
}
/** 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)
@@ -48,9 +79,12 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
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 installerTasks = tasks.filter(isInstallerTask)
const activeInstallerTasks = installerTasks.filter(isActiveInstallerTask)
const installerTasksSig = installerTasks
.map((x) => `${x.id}:${x.status}:${x.installer_phase ?? ''}`)
.sort()
.join('|')
const loadCached = () => api.ListInstallers().then((l) => setCached(l ?? [])).catch((e) => onError(tr('failGeneric'), e))
const loadReleases = () => {
@@ -61,16 +95,24 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
.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])
// Refresh the downloaded list whenever an installer download starts, shifts phase, or ends.
useEffect(() => {
setConfirmDelete('')
loadCached()
}, [installerTasksSig])
const downloaded = (version: string) => (cached ?? []).find((c) => c.kind === 'offline' && !c.partial && c.version === version)
const partial = (version: string) => (cached ?? []).some((c) => c.kind === 'offline' && c.partial && c.version === version)
const activeForRelease = (version: string) => findActiveOfflineTask(activeInstallerTasks, version)
const download = (version: string) => {
api.DownloadInstaller(version).catch((e) => onError(tr('failDownload'), e))
}
const cancelTask = (task: Task) => {
api.CancelTask(task.id).catch((e) => onError(tr('failGeneric'), e))
}
const remove = async (name: string) => {
if (confirmDelete !== name) { setConfirmDelete(name); return }
setConfirmDelete('')
@@ -83,17 +125,27 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
}
}
const progress = (task: Task) => (
<span className="task-inline row-sub">
<LoaderCircle size={14} className="spin" aria-hidden="true" />
{task.percent >= 0 && (
<span className="progress" aria-hidden="true">
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
const progress = (task: Task) => {
if (taskInstallerPhase(task) === 'queued') {
return (
<span className="task-inline row-sub">
<Clock size={14} aria-hidden="true" />
<span>{tr('installersQueuedDesc')}</span>
</span>
)}
<span>{task.percent >= 0 ? `${Math.floor(task.percent)}%` : ''} {taskDetail(task)}</span>
</span>
)
)
}
return (
<span className="task-inline row-sub">
<LoaderCircle size={14} className="spin" aria-hidden="true" />
{task.percent >= 0 && (
<span className="progress" aria-hidden="true">
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
</span>
)}
<span>{task.percent >= 0 ? `${Math.floor(task.percent)}%` : ''} {taskDetail(task)}</span>
</span>
)
}
const skeleton = (rows: number, label?: string) => (
<div className="skeleton-list" role="status" aria-label={label}>
@@ -109,11 +161,27 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
</div>
)
const spaceShort = (r: Release) => !downloaded(r.version) && !running(r.version) && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
const spaceShort = (r: Release) => !downloaded(r.version) && !activeForRelease(r.version) && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
const releaseAction = (r: Release) => {
const task = running(r.version)
if (task) return <IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
const active = activeForRelease(r.version)
if (active) {
const task = active.primary
const queued = taskInstallerPhase(task) === 'queued'
if (queued) {
return <span className="badge" role="status">{tr('installersQueued')}</span>
}
return (
<span className="badge badge-accent installer-active-status" role="status">
<LoaderCircle size={12} className="spin" aria-hidden="true" />
<span>
{task.percent >= 0
? tr('installersDownloadingPct', { p: Math.floor(task.percent) })
: tr('installersDownloading')}
</span>
</span>
)
}
const item = downloaded(r.version)
if (item) {
return (
@@ -136,8 +204,53 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
</div>
)
const matchedTaskIDs = new Set<string>()
const cachedRows: DownloadedRow[] = (cached ?? []).map((c) => {
const active = findActiveCachedTask(activeInstallerTasks, c)
if (active) {
for (const id of active.matchedIDs) matchedTaskIDs.add(id)
}
return {
key: c.name,
title: c.title ?? c.name,
version: c.version ?? '',
kind: c.kind,
cached: c,
active,
}
})
const virtualRows: DownloadedRow[] = groupUnmatchedInstallerTasks(activeInstallerTasks, matchedTaskIDs).map((active) => {
const task = active.primary
const kind = taskInstallerKind(task) || 'offline'
const version = taskInstallerVersion(task)
if (kind === 'offline') {
const rel = (releases ?? []).find((r) => r.version.toLowerCase() === version.toLowerCase())
return {
key: `active-${taskInstallerKey(task) || task.id}`,
title: rel?.title ?? 'macOS',
version: rel?.version ?? version,
kind: 'offline',
active,
}
}
return {
key: `active-${taskInstallerKey(task) || task.id}`,
title: formatOnlineTitle(version),
version: '',
kind: 'online',
active,
}
})
const rowPriority = (row: DownloadedRow) => {
if (!row.active) return 2
return taskInstallerPhase(row.active.primary) === 'queued' ? 1 : 0
}
const downloadedRows = [...virtualRows, ...cachedRows].sort((a, b) => rowPriority(a) - rowPriority(b))
const groups = groupReleases(releases ?? [])
const showDownloaded = cached === null || cached.length > 0 || downloads.length > 0
const showDownloaded = cached === null || downloadedRows.length > 0
return (
<div className="page installers-page">
@@ -155,35 +268,61 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
<section className="section">
<div className="section-title">
<span>{tr('installersDownloaded')}</span>
{cached && cached.length > 0 && <span className="section-count">{cached.length}</span>}
{downloadedRows.length > 0 && <span className="section-count">{downloadedRows.length}</span>}
</div>
{cached === null || (cached.length === 0 && downloads.length > 0) ? (
{cached === null && downloadedRows.length === 0 ? (
skeleton(1, tr('installersDownloaded'))
) : (
<div className="list installer-list">
{cached.map((c) => {
const task = c.version ? running(c.version) : undefined
const title = c.title ?? c.name
{downloadedRows.map((row) => {
const c = row.cached
const active = row.active
const task = active?.primary
const queued = !!task && taskInstallerPhase(task) === 'queued'
const vmName = task
? (task.vm || (task.kind === 'vm-create' || task.kind === 'recovery-download' ? task.subject : ''))
: ''
const waitingVMs = active?.waitingVMs ?? []
const stop = task ? taskStopAction(locale, task) : null
return (
<div className="row installer-row" key={c.name} title={c.name}>
<div className="row installer-row" key={row.key} title={c?.name ?? row.title}>
<span className="installer-art">
<VersionArt shape="tile" major={macOSMajor(c.version, title)} name={title} />
<VersionArt shape="tile" major={macOSMajor(row.version, row.title)} name={row.title} />
</span>
<div className="row-main">
<div className="row-title">
<span>{title} {c.version}</span>
{c.kind === 'offline' && !c.partial && <span className="badge badge-ok">{tr('installersKindOffline')}</span>}
{c.kind === 'online' && !c.partial && <span className="badge">{tr('installersKindOnline')}</span>}
{c.partial && !task && <span className="badge badge-warn">{tr('installersPartial')}</span>}
<span>{row.title}{row.version ? ` ${row.version}` : ''}</span>
{!task && c?.kind === 'offline' && !c.partial && <span className="badge badge-ok">{tr('installersKindOffline')}</span>}
{(!task && c?.kind === 'online' && !c.partial) || (task && row.kind === 'online')
? <span className="badge">{tr('installersKindOnline')}</span>
: null}
{c?.partial && !task && <span className="badge badge-warn">{tr('installersPartial')}</span>}
{task && vmName && (
<span className={`badge ${queued ? '' : 'badge-accent'}`}>
{tr(queued ? 'installersQueuedForVM' : 'installersDownloadingForVM', { vm: vmName })}
</span>
)}
{task && !vmName && waitingVMs.length > 0 && (
<span className="badge badge-accent">
{tr('installersWaitingVM', { vm: waitingVMs.join(', ') })}
</span>
)}
{task && !vmName && queued && (
<span className="badge">{tr('installersQueued')}</span>
)}
</div>
{task ? progress(task) : (
{task ? progress(task) : c ? (
<div className="row-sub">{gb(c.bytes)}{c.build ? ` · ${c.build}` : ''}</div>
)}
) : null}
</div>
<div className="row-right">
{task ? (
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
) : (
{task && stop ? (
<IconButton
label={stop.label}
icon={stop.kind === 'cancel' ? <X size={16} /> : <Pause size={16} />}
onClick={() => cancelTask(task)}
/>
) : c ? (
<>
{!c.partial && (c.kind === 'offline' || c.kind === 'online') && (
<Button variant={c.kind === 'offline' ? 'primary' : 'secondary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
@@ -199,7 +338,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
<IconButton label={tr('installersDelete')} icon={<Trash size={15} />} onClick={() => remove(c.name)} />
)}
</>
)}
) : null}
</div>
</div>
)
@@ -228,7 +367,6 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
<div className="release-list">
{groups.map((group, groupIndex) => {
const [latest, ...older] = group.releases
const task = running(latest.version)
return (
<article className="release-card" key={group.key}>
<div className="release-latest">
@@ -242,7 +380,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
{groupIndex === 0 && <span className="badge badge-accent">{tr('installersLatest')}</span>}
{downloaded(latest.version) && <Check size={15} className="ok-text" aria-label={tr('offlineCached')} />}
</div>
{task ? progress(task) : releaseMeta(latest)}
{releaseMeta(latest)}
</div>
<div className="row-right">{releaseAction(latest)}</div>
</div>
@@ -253,22 +391,19 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
<ChevronDown size={14} aria-hidden="true" />
</summary>
<div className="release-history-list">
{older.map((r) => {
const oldTask = running(r.version)
return (
<div className="release-history-row" key={r.product}>
<div className="row-main">
<div className="row-title">
<span>{r.version}</span>
<span className="muted">{r.build}</span>
{downloaded(r.version) && <span className="badge badge-ok">{tr('offlineCached')}</span>}
</div>
{oldTask ? progress(oldTask) : releaseMeta(r)}
{older.map((r) => (
<div className="release-history-row" key={r.product}>
<div className="row-main">
<div className="row-title">
<span>{r.version}</span>
<span className="muted">{r.build}</span>
{downloaded(r.version) && <span className="badge badge-ok">{tr('offlineCached')}</span>}
</div>
<div className="row-right">{releaseAction(r)}</div>
{releaseMeta(r)}
</div>
)
})}
<div className="row-right">{releaseAction(r)}</div>
</div>
))}
</div>
</details>
)}
@@ -280,4 +415,4 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
</section>
</div>
)
}
}
+52 -10
View File
@@ -1,8 +1,8 @@
import { AlertTriangle, ArrowDown, ChevronDown, ChevronUp, Copy, Eraser, LoaderCircle, Pause, RefreshCw } from 'lucide-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 { taskDetail, taskInstallerPhase, taskStopAction, taskTitle } from '../lib/tasks'
import { HostReport, Locale, Task } from '../types'
import { Button, IconButton, Tip } from '../ui/controls'
@@ -158,13 +158,25 @@ export const LogPanel: React.FC<Props> = ({
<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)
try { localStorage.setItem(LOG_HEIGHT_KEY, String(next)) } catch {}
}}
onDoubleClick={() => {
setHeight(DEFAULT_LOG_HEIGHT)
try { localStorage.setItem(LOG_HEIGHT_KEY, String(DEFAULT_LOG_HEIGHT)) } catch {}
@@ -176,7 +188,13 @@ export const LogPanel: React.FC<Props> = ({
<div className="logbar rg-p-statusbar">
{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" aria-hidden="true" />
<span className="task-label">
@@ -192,9 +210,18 @@ export const LogPanel: React.FC<Props> = ({
)}
</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)}
/>
)
})()}
</>
) : host ? (
// Host at a glance: a problem first (only when there is one), then
@@ -265,16 +292,31 @@ export const LogPanel: React.FC<Props> = ({
{tr('logErrorsOnly')}
</button>
)}
<div className="tabs" role="tablist">
<button type="button" role="tab" className="tab" aria-selected={tab === 'app'} onClick={() => onTab('app')}>
<div
className="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" tabIndex={tab === 'app' ? 0 : -1} 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')}>
<button type="button" role="tab" className="tab" tabIndex={tab === 'serial' ? 0 : -1} aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
{tr('logSerial')}
</button>
<button type="button" role="tab" className="tab" aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
<button type="button" role="tab" className="tab" tabIndex={tab === 'qemu' ? 0 : -1} aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
{tr('logQemu')}
</button>
</>
+18 -3
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useRef, useState } from 'react'
import { t } from '../i18n'
import { getPluginMessageBundle, localeDir, parseAppError, t } from '../i18n'
import { Locale, PanelContribution } from '../types'
import { Button } from '../ui/controls'
import { api } from '../wails'
@@ -39,6 +39,8 @@ function buildSafePanelSrc(assetToken: string, pluginId: string | undefined, ent
export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, appearance }) => {
const iframeRef = useRef<HTMLIFrameElement>(null)
const localeRef = useRef<Locale>(locale)
localeRef.current = locale
const [failed, setFailed] = useState(false)
const [nonce, setNonce] = useState(0)
@@ -52,7 +54,10 @@ export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, a
for (const k of ['--surface-0', '--surface-1', '--text', '--text-2', '--border', '--accent', '--font-sans']) {
tokens[k] = cs.getPropertyValue(k).trim()
}
win.postMessage({ type: 'reims:theme', appearance, locale, tokens }, '*')
const dir = localeDir(locale)
const messages = getPluginMessageBundle(panel.pluginId ?? '', locale)
win.postMessage({ type: 'reims:theme', appearance, locale, dir, tokens, messages }, '*')
win.postMessage({ type: 'reims:i18n', locale, dir, messages }, '*')
}
useEffect(() => {
@@ -76,12 +81,22 @@ export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, a
? (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: String(err) }, '*')
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: false, error: parseAppError(err).summary || 'RPC failed' }, '*')
}
}
+455 -15
View File
@@ -1,12 +1,15 @@
import {
AlertTriangle, BadgeCheck, Boxes, Clipboard, Code2, Compass, Cpu, Disc3, FolderOpen, Keyboard,
Layers, Monitor, PackagePlus, Palette, Puzzle, RefreshCw, RotateCcw, Search,
Settings2, Shield, ShieldAlert, ShieldCheck, Sparkles, Terminal, Trash2,
AlertTriangle, BadgeCheck, Boxes, CheckCircle2, Clipboard, Code2, Compass, Cpu, Disc3, Download,
FolderOpen, Globe, Keyboard, Layers, Monitor, PackagePlus, Palette, Puzzle, RefreshCw, RotateCcw,
Search, Settings2, Shield, ShieldAlert, ShieldCheck, Sparkles, Store, 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,
ActiveThemePayload, CustomThemeScheme, Locale, MarketBrowseResult, MarketCatalogItem,
PluginInfo, PluginUIContributions, ScanReport,
} from '../types'
import { Button, IconButton, Tip } from '../ui/controls'
import { Modal } from '../ui/dialog'
@@ -82,6 +85,7 @@ export const PluginsPage: React.FC<Props> = ({
locale, appearance, safeMode, onRefresh, onError, onThemeChanged,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [activeTab, setActiveTab] = useState<'installed' | 'market'>('installed')
const [query, setQuery] = useState('')
const [plugins, setPlugins] = useState<PluginInfo[]>([])
const [contribs, setContribs] = useState<PluginUIContributions | null>(null)
@@ -89,6 +93,7 @@ export const PluginsPage: React.FC<Props> = ({
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>>({})
@@ -96,6 +101,23 @@ export const PluginsPage: React.FC<Props> = ({
const [removeTarget, setRemoveTarget] = 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)
// Lazy Plugin Market state (never fetched until user switches to Market tab, §8.1)
const [marketQuery, setMarketQuery] = useState('')
const [marketKind, setMarketKind] = useState('')
const [marketAlpha, setMarketAlpha] = useState(false)
const [marketLoading, setMarketLoading] = useState(false)
const [marketLoadedOnce, setMarketLoadedOnce] = useState(false)
const [marketResult, setMarketResult] = useState<MarketBrowseResult | null>(null)
const [marketInstallingID, setMarketInstallingID] = useState('')
// Theme scheme editor state (§5.1)
const [schemeEditorOpen, setSchemeEditorOpen] = useState(false)
const [schemeName, setSchemeName] = useState('')
@@ -119,12 +141,40 @@ export const PluginsPage: React.FC<Props> = ({
}
}
const loadMarket = async (opts?: { q?: string; kind?: string; alpha?: boolean; forceRefresh?: boolean }) => {
setMarketLoading(true)
try {
const res = await api.BrowsePluginMarket(
opts?.q ?? marketQuery,
opts?.kind ?? marketKind,
opts?.alpha ?? marketAlpha,
opts?.forceRefresh ?? false,
)
setMarketResult(res)
setMarketLoadedOnce(true)
} catch (e) {
onError(tr('pluginFailMarketLoad'), e)
} finally {
setMarketLoading(false)
}
}
useEffect(() => { void reload() }, [safeMode])
useEffect(() => {
if (activeTab !== 'market') return
const timer = window.setTimeout(() => {
void loadMarket({ q: marketQuery, kind: marketKind, alpha: marketAlpha, forceRefresh: false })
}, marketLoadedOnce ? 180 : 0)
return () => window.clearTimeout(timer)
}, [activeTab, marketQuery, marketKind, marketAlpha])
const togglePlugin = async (p: PluginInfo, enable: boolean) => {
if (enable && p.needs_approval) {
setApproveChecked(false)
setApproveReport(null)
setApproveTarget(p)
void api.ScanInstalledPlugin(p.id).then(setApproveReport).catch(() => {})
return
}
setBusyID(p.id)
@@ -145,6 +195,7 @@ export const PluginsPage: React.FC<Props> = ({
if (!approveTarget || !approveChecked) return
const target = approveTarget
setApproveTarget(null)
setApproveReport(null)
setBusyID(target.id)
try {
await api.EnablePlugin(target.id, true)
@@ -162,11 +213,57 @@ export const PluginsPage: React.FC<Props> = ({
try {
const path = await api.PickFile(tr('pluginImportTitle'), '*.zip')
if (!path) return
await api.InstallPluginArchive(path)
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()
if (marketLoadedOnce) void loadMarket({ forceRefresh: false })
} 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 installFromMarket = async (item: MarketCatalogItem) => {
const id = item.entry.id
setMarketInstallingID(id)
try {
await api.InstallMarketPlugin(id, marketAlpha)
await reload()
onRefresh()
await loadMarket({ forceRefresh: false })
} catch (e) {
onError(tr('pluginFailMarketInstall'), e)
} finally {
setMarketInstallingID('')
}
}
@@ -359,6 +456,9 @@ export const PluginsPage: React.FC<Props> = ({
)}
</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)} />
)}
@@ -394,6 +494,128 @@ export const PluginsPage: React.FC<Props> = ({
)
}
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 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${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">{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${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 marketSourceLabel = (src?: string) => {
if (src === 'remote') return tr('pluginMarketSourceRemote')
if (src === 'cache') return tr('pluginMarketSourceCache')
return tr('pluginMarketSourceFallback')
}
const marketKindIcon = (kind?: string) => {
switch (kind) {
case 'theme': return { tone: 'purple', icon: <Palette size={18} aria-hidden="true" /> }
case 'locale': return { tone: 'sky', icon: <Globe size={18} aria-hidden="true" /> }
case 'driver': return { tone: 'indigo', icon: <Monitor size={18} aria-hidden="true" /> }
default: return { tone: 'teal', icon: <Puzzle size={18} aria-hidden="true" /> }
}
}
const showThemeHero = themes.length > 1 && !q
const showSearch = plugins.length > SEARCH_THRESHOLD
const noMatches = !loading && !!q && filteredBuiltins.length === 0 && filteredExternal.length === 0
@@ -409,7 +631,7 @@ export const PluginsPage: React.FC<Props> = ({
{!loading && <span>{tr('pluginActiveCount', { active: activeCount, total: plugins.length })}</span>}
</div>
<div className="actions">
{showSearch && (
{activeTab === 'installed' && showSearch && (
<div className="plugins-search-wrap">
<Search size={13} className="plugins-search-icon" aria-hidden="true" />
<input
@@ -422,15 +644,177 @@ export const PluginsPage: React.FC<Props> = ({
/>
</div>
)}
<IconButton label={tr('refresh')} icon={<RefreshCw size={16} />} onClick={() => void reload()} />
<IconButton
label={activeTab === 'market' ? tr('pluginMarketRefresh') : tr('refresh')}
icon={<RefreshCw size={16} />}
onClick={() => activeTab === 'market' ? void loadMarket({ forceRefresh: true }) : void reload()}
/>
<IconButton label={tr('pluginLinkDevBtn')} icon={<FolderOpen size={16} />} onClick={linkDevDir} />
<Button variant="primary" icon={<PackagePlus size={14} aria-hidden="true" />} onClick={importLocalZip}>
<Button variant="primary" disabled={scanBusy} icon={<PackagePlus size={14} aria-hidden="true" />} onClick={importLocalZip}>
{tr('pluginImportBtn')}
</Button>
</div>
</header>
{showThemeHero && (
<div className="plugins-tabs" role="tablist" aria-label={tr('sidebarPlugins')}>
<button
type="button"
role="tab"
aria-selected={activeTab === 'installed'}
className={`plugin-cat-pill${activeTab === 'installed' ? ' is-active' : ''}`}
onClick={() => setActiveTab('installed')}
>
<Puzzle size={13} aria-hidden="true" />
{tr('pluginTabInstalled')}
</button>
<button
type="button"
role="tab"
aria-selected={activeTab === 'market'}
className={`plugin-cat-pill${activeTab === 'market' ? ' is-active' : ''}`}
onClick={() => setActiveTab('market')}
>
<Store size={13} aria-hidden="true" />
{tr('pluginTabMarket')}
</button>
</div>
{activeTab === 'market' ? (
<section className="section">
<div className="plugins-market-toolbar">
<div className="plugins-search-wrap plugins-market-search-wrap">
<Search size={13} className="plugins-search-icon" aria-hidden="true" />
<input
type="search"
className="input plugins-market-search"
aria-label={tr('pluginMarketSearchPlaceholder')}
placeholder={tr('pluginMarketSearchPlaceholder')}
value={marketQuery}
onChange={(e) => setMarketQuery(e.target.value)}
/>
</div>
<div className="plugins-market-kinds">
{[
{ id: '', label: tr('pluginMarketKindAll') },
{ id: 'theme', label: tr('pluginMarketKindTheme') },
{ id: 'locale', label: tr('pluginMarketKindLocale') },
{ id: 'driver', label: tr('pluginMarketKindDriver') },
{ id: 'tool', label: tr('pluginMarketKindTool') },
].map((k) => (
<button
key={k.id || 'all'}
type="button"
className={`plugin-cat-pill${marketKind === k.id ? ' is-active' : ''}`}
onClick={() => setMarketKind(k.id)}
>
{k.label}
</button>
))}
</div>
<div className="plugins-market-meta">
<label className="hstack" style={{ fontSize: 'var(--fs-12)', color: 'var(--text-2)', cursor: 'pointer' }}>
<input type="checkbox" checked={marketAlpha} onChange={(e) => setMarketAlpha(e.target.checked)} />
<span>{tr('pluginMarketIncludeAlpha')}</span>
</label>
{marketResult && (
<span className="badge">{marketSourceLabel(marketResult.source)}</span>
)}
</div>
</div>
{marketResult?.stale && marketResult.fetch_error && (
<div className="notice notice-warn" style={{ marginBottom: 'var(--sp-3)' }}>
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('pluginMarketStaleBanner')}</span>
</span>
</div>
)}
{(marketResult?.withdrawn_installed ?? []).map((w) => (
<div className="notice notice-warn" style={{ marginBottom: 'var(--sp-3)' }} 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>
))}
{marketLoading && !marketResult ? (
<div className="list"><div className="row plugin-row"><span className="muted">…</span></div></div>
) : (marketResult?.items ?? []).length === 0 ? (
<div className="plugins-empty">{tr('pluginMarketEmpty')}</div>
) : (
<div className="list">
{(marketResult?.items ?? []).map((item) => {
const e = item.entry
const vis = marketKindIcon(e.kind)
const trust = trustMeta(e.trust)
const desc = locText(e.description, locale, '')
const changelog = locText(e.changelog, locale, '')
const isBusy = marketInstallingID === e.id
const blocked = !!item.withdrawn || !item.compatible || !!safeMode
return (
<div className="row plugin-row" key={e.id}>
<div className={`plugin-app-icon tone-${vis.tone}`}>{vis.icon}</div>
<div className="row-main">
<div className="row-title">
<span className="plugin-row-name">{locText(e.name, locale, e.id)}</span>
{e.channel === 'alpha' && <span className="badge badge-warn">alpha</span>}
{item.withdrawn && <span className="badge badge-danger">{tr('pluginMarketWithdrawn')}</span>}
{!item.compatible && <span className="badge badge-warn">{tr('pluginMarketIncompatible')}</span>}
</div>
{desc && <div className="row-sub plugin-row-desc" title={desc}>{desc}</div>}
<div className="row-sub plugin-row-meta">
<span className={`plugin-trust ${trust.cls}`}>{trust.icon}{e.publisher || trust.label}</span>
<span className="mono">v{e.version}</span>
{e.tier && <span className="mono">{e.tier}</span>}
{(item.high_risk_permissions?.length ?? 0) > 0 && (
<span className="plugin-row-alert">
<ShieldAlert size={12} aria-hidden="true" />
<span>{tr('pluginHighRiskNotice')}</span>
</span>
)}
</div>
{changelog && <div className="row-sub muted">{changelog}</div>}
{!item.compatible && item.incompatible_reason && (
<div className="row-sub plugin-row-alert">{item.incompatible_reason}</div>
)}
{item.withdrawn && (
<div className="row-sub plugin-row-alert">
{locText(item.withdrawn.reason, locale, '')}
{item.withdrawn.instead_id ? ` · ${tr('pluginMarketWithdrawnInstead', { target: item.withdrawn.instead_name || item.withdrawn.instead_id })}` : ''}
</div>
)}
</div>
<div className="row-right">
{item.installed && !item.update_available ? (
<Button disabled>{tr('pluginMarketInstalled')}</Button>
) : (
<Button
variant={item.update_available ? 'primary' : undefined}
disabled={blocked || isBusy}
icon={<Download size={13} aria-hidden="true" />}
onClick={() => void installFromMarket(item)}
>
{item.update_available
? tr('pluginMarketUpdate', { version: e.version })
: tr('pluginMarketInstall')}
</Button>
)}
</div>
</div>
)
})}
</div>
)}
</section>
) : (
<>
{showThemeHero && (
<section className="section">
<div className="section-title">{tr('pluginThemeSection')}</div>
<div className="theme-hero-card">
@@ -572,19 +956,57 @@ export const PluginsPage: React.FC<Props> = ({
) : (
<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 style={{ padding: 'var(--sp-4)', maxHeight: 440, overflow: 'auto' }}>
{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)}
onClose={() => { setApproveTarget(null); setApproveReport(null) }}
>
<div className="stack-3" style={{ padding: 'var(--sp-4)' }}>
<div className="stack-3" style={{ padding: 'var(--sp-4)', maxHeight: 440, overflow: 'auto' }}>
{(approveTarget.tier === 'L3' || (approveTarget.permissions ?? []).some((p) => p.name === 'ui:script')) && (
<div className="notice notice-warn">
<ShieldAlert size={15} aria-hidden="true" style={{ marginRight: 6, verticalAlign: '-2px' }} />
{tr('pluginApproveL3Warn')}
<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>
)}
<div className="list">
@@ -597,6 +1019,24 @@ export const PluginsPage: React.FC<Props> = ({
)}
<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${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="hstack" style={{ cursor: 'pointer' }}>
<input type="checkbox" checked={approveChecked} onChange={(e) => setApproveChecked(e.target.checked)} />
<span>{tr('pluginApproveCheckbox')}</span>
@@ -605,7 +1045,7 @@ export const PluginsPage: React.FC<Props> = ({
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setApproveTarget(null)}>{tr('cancel')}</Button>
<Button variant="ghost" onClick={() => { setApproveTarget(null); setApproveReport(null) }}>{tr('cancel')}</Button>
<Button variant="primary" disabled={!approveChecked} onClick={() => void confirmApprove()}>
{tr('pluginApproveConfirm')}
</Button>
@@ -698,7 +1138,7 @@ export const PluginsPage: React.FC<Props> = ({
closeLabel={tr('close')}
onClose={() => setLogTarget(null)}
>
<pre className="mono selectable" style={{ padding: 'var(--sp-4)', maxHeight: 360, overflow: 'auto', margin: 0 }}>
<pre className="mono selectable" style={{ padding: 'var(--sp-4)', maxHeight: 360, overflow: 'auto', margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
{logTarget.text}
</pre>
</Modal>
+6 -26
View File
@@ -1,20 +1,19 @@
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, RuntimeSource, Task } from '../types'
import { InstalledRuntime, Locale, RemoteRuntime, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Segmented, Switch } from '../ui/settings'
import { Switch } from '../ui/settings'
import { api } from '../wails'
interface Props {
locale: Locale
channel: 'stable' | 'alpha'
source: RuntimeSource
installed: InstalledRuntime[]
task: Task | null
onChannel: (alpha: boolean) => void
onSource: (source: RuntimeSource) => void
onInstall: (commit: string) => void
onCancel: (taskId: string) => void
}
@@ -26,9 +25,9 @@ const shortQemu = (v: string) => v.replace(/^QEMU emulator version\s*/i, 'QEMU '
/**
* The runtime rows: the active runtime and whether it is current (or, with
* none installed, the newest release to install), then download source and alpha switches.
* none installed, the newest release to install), then the alpha switch.
*/
export const RuntimeOnline: React.FC<Props> = ({ locale, channel, source, installed, task, onChannel, onSource, onInstall, onCancel }) => {
export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, task, onChannel, onInstall, onCancel }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [remote, setRemote] = useState<RemoteRuntime[] | null>(null)
const [error, setError] = useState('')
@@ -42,7 +41,7 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, source, instal
.then((list) => { if (live) setRemote(list ?? []) })
.catch((e) => { if (live) setError(String(e).replace(/^Error:\s*/, '')) })
return () => { live = false }
}, [channel, source, task?.status === 'done', reload])
}, [channel, task?.status === 'done', reload])
const active = installed.find((i) => i.active) ?? installed[0]
const latest = remote?.[0]
@@ -79,12 +78,10 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, source, instal
} else if (!latest) {
sub = <div className="row-sub">{tr('runtimeNoneOnChannel')}</div>
} else {
const srcLabel = latest.source === 'gitcode' ? 'GitCode' : latest.source === 'github' ? 'GitHub' : ''
sub = (
<div className="row-sub">
{active ? tr('runtimeNewer', { v: latest.commit }) : tr('runtimeLatest', { v: latest.commit })}
{' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)}
{srcLabel ? ` · ${srcLabel}` : ''}
{latest.archive_size > 0 ? ` · ${gb(latest.archive_size)}` : ''}
</div>
)
@@ -115,23 +112,6 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, source, instal
) : null}
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('runtimeSource')}</div>
<div className="row-sub">{tr('runtimeSourceHint')}</div>
</div>
<div className="row-right">
<Segmented
label={tr('runtimeSource')}
value={source}
onChange={onSource}
options={(['auto', 'github', 'gitcode'] as RuntimeSource[]).map((s) => ({
value: s,
label: tr(`runtimeSource_${s}` as I18nKey),
}))}
/>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('runtimeAlpha')}</div>
+2
View File
@@ -1,4 +1,6 @@
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'
+61 -25
View File
@@ -1,11 +1,15 @@
import { CircleAlert, Copy, Cpu, HardDrive, Info, Keyboard, LucideIcon, Monitor, Wrench } from 'lucide-react'
import React, { Suspense, lazy, useEffect, useMemo, useRef, useState } from 'react'
import { I18nKey, t } from '../i18n'
import '../i18n/domains/settings.gen'
import { I18nKey, parseAppError, t } from '../i18n'
import {
GUEST_LANG_PRESETS,
splitLangLabel,
guestLangOptions,
MEMORY_MARKS,
findGPU,
formatBytes,
gpuCompatHint,
gpuOptionValue,
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
@@ -172,7 +176,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
const updateVMPluginSetting = (pluginID: string, next: Record<string, unknown>) => {
setVmPluginVals((prev) => ({ ...prev, [pluginID]: next }))
void api.SetPluginSettings(pluginID, detail.name, next).catch((e) => setErr(String(e)))
void api.SetPluginSettings(pluginID, detail.name, next).catch((e) => setErr(parseAppError(e).summary))
}
const renderVMPluginGroup = (group: string) => {
@@ -255,7 +259,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
setDriveErr('')
api.GetVMDriveShareSettings(detail.name)
.then((settings) => { if (active) setDriveSettings(settings) })
.catch((e) => { if (active) setDriveErr(String(e).replace(/^Error:\s*/, '')) })
.catch((e) => { if (active) setDriveErr(parseAppError(e).summary) })
return () => { active = false }
}, [detail.name])
@@ -277,7 +281,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
const next = await api.SetVMDriveShareSettings(vmName, enabled, selected)
if (activeVMNameRef.current === vmName) setDriveSettings(next)
} catch (e) {
if (activeVMNameRef.current === vmName) setDriveErr(String(e).replace(/^Error:\s*/, ''))
if (activeVMNameRef.current === vmName) setDriveErr(parseAppError(e).summary)
} finally {
driveBusyRef.current = false
setDriveBusy(false)
@@ -295,7 +299,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
await api.OpenProcessorScheduling()
onHostChanged?.()
} catch (e) {
setErr(String(e).replace(/^Error:\s*/, ''))
setErr(parseAppError(e).summary)
} finally {
setOpeningSched(false)
}
@@ -319,7 +323,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
await api.ApplyVMSettings(diff)
onSaved()
} catch (e) {
setErr(String(e).replace(/^Error:\s*/, ''))
setErr(parseAppError(e).summary)
} finally {
setBusy(false)
}
@@ -363,7 +367,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
value={form.guest_lang || 'en-US:0'}
onChange={(guest_lang) => set({ guest_lang })}
options={[
...GUEST_LANG_PRESETS.map((p) => splitLangLabel(p.value, locale === 'zh-CN' ? p.zh : p.en)),
...guestLangOptions(locale),
...(form.guest_lang && !GUEST_LANG_PRESETS.some((p) => p.value === form.guest_lang)
? [{ value: form.guest_lang, label: form.guest_lang }]
: []),
@@ -487,14 +491,21 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
sub: host.recommended_gpu ? tr('gpuAutoSub', { name: shortGPUName(host.recommended_gpu.name) }) : tr('gpuAutoOption'),
},
...realGPUs.map((g) => ({
value: g.vulkan_icd,
value: gpuOptionValue(g, realGPUs),
title: shortGPUName(g.name),
sub: g.kind === 'discrete' ? tr('gpuKindDiscrete') : g.kind === 'integrated' ? tr('gpuKindIntegrated') : undefined,
sub: [
g.kind === 'discrete' ? tr('gpuKindDiscrete') : g.kind === 'integrated' ? tr('gpuKindIntegrated') : '',
g.compat === 'unsupported' ? tr('gpuCompatUnsupported') : g.compat === 'warn' ? tr('gpuCompatWarn') : '',
]
.filter(Boolean)
.join(' · ') || undefined,
})),
]
if (form.gpu && form.gpu !== 'auto' && !gpuOptions.some((o) => normPath(o.value) === normPath(form.gpu))) {
gpuOptions.push({ value: form.gpu, title: form.gpu.split(/[\\/]/).pop() || form.gpu, sub: tr('gpuCustomIcd') })
}
const selectedGPU = findGPU(host, form.gpu)
const selectedGPUHint = gpuCompatHint(locale, selectedGPU)
const vgpu = form.graphics !== 'vmware-svga'
const pd = host.primary_display
const hidpiAdvice = hostDisplayAdvice(host, tr)
@@ -527,7 +538,27 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
<SetRow
{...rowProps('gpu')}
title={tr('gpuSelect')}
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}
{!running && vgpu && (
<>
{' '}
<button
type="button"
className="link-btn"
onClick={() => set({ graphics: 'vmware-svga' })}
>
{tr('gpuSwitchSvga')}
</button>
</>
)}
</span>
) : undefined
}
disabled={!vgpu}
reason={tr('gpuSvgaReason')}
block={<OptionCards label={tr('gpuSelect')} value={gpuOptions.find((o) => normPath(o.value) === normPath(form.gpu))?.value} onChange={(gpu) => set({ gpu })} options={gpuOptions} />}
@@ -611,7 +642,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
setResizeResult(res)
onDiskChanged?.()
} catch (e) {
setErr(String(e).replace(/^Error:\s*/, ''))
setErr(parseAppError(e).summary)
} finally {
setDiskOpBusy('')
}
@@ -626,7 +657,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
setCompactResult(res)
onDiskChanged?.()
} catch (e) {
setErr(String(e).replace(/^Error:\s*/, ''))
setErr(parseAppError(e).summary)
} finally {
setDiskOpBusy('')
}
@@ -649,12 +680,21 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
<SetValue
title={tr('factDisk')}
value={tr('diskUsageSummary', {
actual: formatBytes(stats.disk_actual_bytes),
virtual: formatBytes(stats.disk_virtual_bytes),
format: (stats.disk_format || 'qcow2').toUpperCase(),
actual: formatBytes(stats.disk_actual_bytes, locale),
virtual: formatBytes(stats.disk_virtual_bytes, locale),
})}
/>
)}
{stats && ((stats.disk_backing_depth ?? 0) >= 2 || stats.disk_backing_broken) && (
<SetValue
title={tr('factBackingChain')}
value={
stats.disk_backing_broken
? tr('diagBackingChainBroken', { depth: stats.disk_backing_depth ?? 1 })
: tr('diagBackingChainWarn', { depth: stats.disk_backing_depth ?? 2 })
}
/>
)}
<SetRow
{...rowProps('disk_controller')}
title={tr('diskController')}
@@ -719,7 +759,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
</div>
{resizeResult && (
<div className="notice">
<div>{tr('diskResizeDone', { size: formatBytes(resizeResult.new_virtual_bytes) })}</div>
<div>{tr('diskResizeDone', { size: formatBytes(resizeResult.new_virtual_bytes, locale) })}</div>
<div className="cmd-line cmd-line-spaced">
<code>{resizeResult.guest_expand_cmd}</code>
{onCopy && (
@@ -736,14 +776,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
desc={compactResult
? compactResult.reclaimed_bytes > 0
? tr('diskCompactDone', {
before: formatBytes(compactResult.before_bytes),
after: formatBytes(compactResult.after_bytes),
reclaimed: formatBytes(compactResult.reclaimed_bytes),
})
: tr('diskCompactNoGain', {
before: formatBytes(compactResult.before_bytes),
after: formatBytes(compactResult.after_bytes),
before: formatBytes(compactResult.before_bytes, locale),
after: formatBytes(compactResult.after_bytes, locale),
reclaimed: formatBytes(compactResult.reclaimed_bytes, locale),
})
: tr('diskCompactNoGain')
: tr('diskCompactDesc')}
disabled={running || !isQcow2}
reason={running ? tr('stopBeforeDiskOp') : tr('diskCompactQcow2Only')}
@@ -973,7 +1010,6 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
key={c.id}
type="button"
className="nav-item"
aria-selected={cat === c.id}
aria-current={cat === c.id ? 'page' : undefined}
onClick={() => setCat(c.id)}
>
+22 -10
View File
@@ -1,10 +1,12 @@
import { FolderOpen, HardDrive } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import '../i18n/domains/wizard.gen'
import '../i18n/domains/settings.gen'
import { getLocaleOptions, I18nKey, joinNotices, t } from '../i18n'
import { AppState, DataRootCheck, DataRootChoice, Locale, ResolvedLocalePack, RuntimeSource, Task } from '../types'
import { AppState, DataRootCheck, DataRootChoice, Locale, ResolvedLocalePack, Task } from '../types'
import { Button } from '../ui/controls'
import { PopupSelect } from '../ui/settings'
import { recommendedMemoryGB, shortGPUName } from '../lib/format'
import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format'
import { api } from '../wails'
import { RuntimeOnline } from './RuntimeOnline'
@@ -19,7 +21,6 @@ interface Props {
onFinish: () => void
onError: (title: string, e: unknown) => void
onChannel: (alpha: boolean) => void
onSource: (source: RuntimeSource) => void
onInstallRuntime: (commit: string) => void
onCancelTask: (id: string) => void
onImportRuntime: () => void
@@ -41,7 +42,7 @@ export const Setup: React.FC<Props> = (p) => {
type StepProps = Props & { tr: (k: I18nKey, v?: Record<string, string | number>) => string }
const FolderStep: React.FC<StepProps> = ({ locale, locales, tr, onLocale, onFolderDone, onError }) => {
const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale, onFolderDone, onError }) => {
const [choices, setChoices] = useState<DataRootChoice[]>([])
const [custom, setCustom] = useState('')
const [customMode, setCustomMode] = useState(false)
@@ -145,9 +146,9 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, tr, onLocale, onFold
<div className="setup-foot">
<PopupSelect
label={tr('language')}
value={locale}
value={state.config.locale || 'auto'}
onChange={onLocale}
options={getLocaleOptions(locales)}
options={getLocaleOptions(locales, locale, state.detected_locale)}
/>
<Button variant="primary" busy={busy} disabled={!selected || !!check?.error} onClick={next}>{tr('setupContinue')}</Button>
</div>
@@ -155,7 +156,7 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, tr, onLocale, onFold
)
}
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask, onImportRuntime, onFinish, onError }) => {
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFinish, onError }) => {
const ready = !!state.active_runtime
const { host } = state
const [enabling, setEnabling] = useState(false)
@@ -165,6 +166,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 = !!gpu && gpu.compat !== 'warn' && gpu.compat !== 'unsupported'
const recMem = recommendedMemoryGB(host)
return (
<>
@@ -198,9 +201,20 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
<div className="row-main">
<div className="row-title">{tr('setupGPU')}</div>
<div className="row-sub">{gpu ? shortGPUName(gpu.name) : tr('setupNoGPU')}</div>
{gpuHint && <div className="row-sub warn-text">{gpuHint}</div>}
</div>
<div className="row-right">
<span className={`badge ${gpu ? 'badge-ok' : 'badge-warn'}`}>{tr(gpu ? 'whpxReady' : 'hostNeedsAction')}</span>
<span className={`badge ${gpuOK ? 'badge-ok' : 'badge-warn'}`}>
{tr(
gpuOK
? 'whpxReady'
: gpu?.compat === 'unsupported'
? 'gpuCompatUnsupported'
: gpu?.compat === 'warn'
? 'gpuCompatWarn'
: 'hostNeedsAction',
)}
</span>
</div>
</div>
<div className="row">
@@ -222,11 +236,9 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
<RuntimeOnline
locale={locale}
channel={state.config.runtime_channel === 'alpha' ? 'alpha' : 'stable'}
source={state.config.runtime_source === 'github' || state.config.runtime_source === 'gitcode' ? state.config.runtime_source : 'auto'}
installed={state.runtimes ?? []}
task={runtimeTask}
onChannel={onChannel}
onSource={onSource}
onInstall={onInstallRuntime}
onCancel={onCancelTask}
/>
+3 -2
View File
@@ -62,6 +62,7 @@ export const Sidebar: React.FC<Props> = ({
listRef.current?.querySelector<HTMLElement>(`[data-id="${CSS.escape(ids[next])}"]`)?.focus()
}
const hasSelectedInList = ids.includes(selected)
const navBtn = (
id: string,
label: string,
@@ -80,7 +81,7 @@ export const Sidebar: React.FC<Props> = ({
className="nav-item"
aria-selected={selected === id}
aria-label={stateLabel ? t(locale, 'sidebarItemAria', { label, state: stateLabel }) : label}
tabIndex={selected === id ? 0 : -1}
tabIndex={selected === id || (!hasSelectedInList && id === ids[0]) ? 0 : -1}
onClick={() => onSelect(id)}
onDoubleClick={onDoubleClick}
>
@@ -188,7 +189,7 @@ export const Sidebar: React.FC<Props> = ({
tr('sidebarInstallers'),
<Download size={13} />,
'nav-icon-installers',
downloading ? tr('state_starting') : '',
downloading ? tr('installersDownloading') : '',
downloading ? 'busy' : null,
)}
{navBtn(
+23 -9
View File
@@ -41,8 +41,8 @@ import {
import React, { useEffect, useRef, useState } from 'react'
import { I18nKey, locText, t } from '../i18n'
import {
controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel, guestLangLabel,
parseMemoryGB, pendingChangeText, splitLangLabel, sshCommand,
controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel,
parseMemoryGB, pendingChangeText, resolveGuestLang, sshCommand,
} from '../lib/format'
import { useVMStats } from '../lib/vmStats'
import { DiskSnapshot, HostReport, Locale, PendingChange, PluginUIContributions, VMDetail, VMThumbnail } from '../types'
@@ -296,7 +296,8 @@ export const VMPage: React.FC<Props> = ({
const formatSnapTime = (sec: number) => {
if (!sec) return ''
try {
return new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(sec * 1000))
const loc = locale === 'en-XA' ? 'en-US' : locale
return new Intl.DateTimeFormat(loc, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(sec * 1000))
} catch {
return ''
}
@@ -448,7 +449,7 @@ export const VMPage: React.FC<Props> = ({
const memPct = memGB > 0 && rss > 0 ? clampPct((rss / (memGB * 1024 ** 3)) * 100) : 0
const diskKnown = !!stats && stats.disk_virtual_bytes > 0 && stats.disk_actual_bytes > 0
const diskPct = diskKnown ? clampPct((stats!.disk_actual_bytes / stats!.disk_virtual_bytes) * 100) : 0
const mem = formatMemory(detail.memory)
const mem = formatMemory(detail.memory, locale)
specs.push(
{
@@ -458,14 +459,14 @@ export const VMPage: React.FC<Props> = ({
},
{
key: 'mem', label: tr('factMemory'), icon: <MemoryStick size={15} aria-hidden="true" />, value: mem,
tip: live && rss > 0 ? tr('specMemLiveTip', { mem, used: formatBytes(rss) }) : tr('specMemTip', { mem }),
tip: live && rss > 0 ? tr('specMemLiveTip', { mem, used: formatBytes(rss, locale) }) : tr('specMemTip', { mem }),
meter: { pct: memPct, tone: '', idle: !live },
},
{
key: 'disk', label: tr('factDisk'), icon: <HardDrive size={15} aria-hidden="true" />,
value: diskKnown ? formatDiskUsage(stats!.disk_actual_bytes, stats!.disk_virtual_bytes) : controllerLabel(detail.disk_controller),
value: diskKnown ? formatDiskUsage(stats!.disk_actual_bytes, stats!.disk_virtual_bytes, locale) : controllerLabel(detail.disk_controller),
tip: diskKnown
? tr('specDiskUsage', { ctl: controllerLabel(detail.disk_controller), used: formatBytes(stats!.disk_actual_bytes), max: formatBytes(stats!.disk_virtual_bytes) })
? tr('specDiskUsage', { ctl: controllerLabel(detail.disk_controller), used: formatBytes(stats!.disk_actual_bytes, locale), max: formatBytes(stats!.disk_virtual_bytes, locale) })
: tr('specDiskTip', { ctl: controllerLabel(detail.disk_controller) }),
meter: { pct: diskPct, tone: meterTone(diskPct, 85, 95), idle: !diskKnown },
},
@@ -481,7 +482,7 @@ export const VMPage: React.FC<Props> = ({
},
)
if (detail.guest_lang) {
const lang = splitLangLabel('', guestLangLabel(locale, detail.guest_lang))
const lang = resolveGuestLang(locale, detail.guest_lang)
specs.push({
key: 'lang', label: tr('specLang'), icon: <Globe size={15} aria-hidden="true" />, value: lang.label,
tip: lang.detail
@@ -588,7 +589,7 @@ export const VMPage: React.FC<Props> = ({
<div className={`vm-spec-card rg-p-vm-summary${running ? ' is-live' : ''}`} role="list" data-rg-slot="vm.card">
{specs.map((s) => (
<Tip key={s.key} label={s.tip}>
<div className="vm-spec-cell" role="listitem" tabIndex={-1}>
<div className="vm-spec-cell" role="listitem" tabIndex={0}>
<span className="vm-spec-icon">{s.icon}</span>
<span className="vm-spec-label">{s.label}</span>
<span className="vm-spec-val">{s.value}</span>
@@ -639,6 +640,19 @@ export const VMPage: React.FC<Props> = ({
</div>
)}
{stats && (stats.disk_backing_depth_warn || (stats.disk_backing_depth ?? 0) >= 2 || stats.disk_backing_broken) && (
<div className="notice">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>
{stats.disk_backing_broken
? tr('diagBackingChainBroken', { depth: stats.disk_backing_depth ?? 1 })
: tr('diagBackingChainWarn', { depth: stats.disk_backing_depth ?? 2 })}
</span>
</span>
</div>
)}
{(host.memory_load_pct ?? 0) >= 85 && (
<div className="notice">
<span className="notice-main">
+349 -1632
View File
File diff suppressed because it is too large. Load diff
+365
View File
@@ -0,0 +1,365 @@
// 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": "复制技术信息",
"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": "安全模式",
"refresh": "刷新",
"resLooksLike": "看起来像 {w} × {h}",
"resizeLogPanel": "拖动调整日志高度",
"resolution": "分辨率",
"restart": "重启",
"safeModeBanner": "安全模式已启用:已跳过全部第三方插件并回退至内置默认主题",
"safeModeManagePlugins": "管理插件",
"save": "保存",
"settings": "设置",
"settingsAbout": "关于",
"settingsEllipsis": "设置…",
"shortcutBarFullscreen": "切换全屏",
"shortcutBarRelease": "释放键盘和鼠标",
"showSidebar": "显示侧边栏",
"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",
"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",
"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",
"sidebarHost": "Engine",
"sidebarInstallers": "Installers",
"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",
}
+208
View File
@@ -0,0 +1,208 @@
// 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": "删除方案",
"pluginDone": "完成",
"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} — 日志",
"pluginMarketEmpty": "当前插件市场暂无可用条目,你仍可导入本地 .zip 插件包或配置自定义市场索引地址",
"pluginMarketIncludeAlpha": "显示 Alpha 测试通道",
"pluginMarketIncompatible": "不兼容",
"pluginMarketInstall": "安装",
"pluginMarketInstalled": "已安装",
"pluginMarketKindAll": "全部",
"pluginMarketKindDriver": "客体驱动",
"pluginMarketKindLocale": "语言包",
"pluginMarketKindTheme": "主题",
"pluginMarketKindTool": "工具",
"pluginMarketRefresh": "刷新索引",
"pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签",
"pluginMarketSourceCache": "本地缓存",
"pluginMarketSourceFallback": "离线回退",
"pluginMarketSourceRemote": "在线索引",
"pluginMarketStaleBanner": "远程插件市场暂不可达,当前显示本地缓存或内置回退索引",
"pluginMarketUpdate": "更新至 v{version}",
"pluginMarketWithdrawn": "已撤回",
"pluginMarketWithdrawnInstalledWarn": "已安装插件 {id} 已从市场撤回:{reason}",
"pluginMarketWithdrawnInstead": "建议改用:{target}",
"pluginNewScheme": "新建配色方案",
"pluginPanelsSection": "插件面板",
"pluginPermCount": "{count, plural, other {# 项权限}}",
"pluginPermissionsLabel": "权限:{list}",
"pluginPublisherLicense": "发布者 / 许可",
"pluginRemove": "卸载",
"pluginRequestedPerms": "请求权限",
"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",
"pluginDone": "Done",
"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",
"pluginMarketEmpty": "No plugins available in the market index yet. You can still import local .zip packages or configure a custom index URL.",
"pluginMarketIncludeAlpha": "Include alpha channel",
"pluginMarketIncompatible": "Incompatible",
"pluginMarketInstall": "Install",
"pluginMarketInstalled": "Installed",
"pluginMarketKindAll": "All",
"pluginMarketKindDriver": "Drivers",
"pluginMarketKindLocale": "Languages",
"pluginMarketKindTheme": "Themes",
"pluginMarketKindTool": "Tools",
"pluginMarketRefresh": "Refresh index",
"pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags",
"pluginMarketSourceCache": "Cached index",
"pluginMarketSourceFallback": "Offline fallback",
"pluginMarketSourceRemote": "Online index",
"pluginMarketStaleBanner": "Remote market index is unreachable; showing cached or offline fallback data",
"pluginMarketUpdate": "Update to v{version}",
"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",
"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)
+634
View File
@@ -0,0 +1,634 @@
// Code generated by cmd/i18ngen; DO NOT EDIT.
import { registerBuiltinDomain } from '../runtime'
export const settingsZh: Record<string, string> = {
"aboutCommunity": "社区与支持",
"aboutCopyQQGroup": "复制群号",
"aboutIssueSub": "遇到问题或有功能建议,在 GitHub 提交 Issue",
"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} 线程",
"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": "直接使用原盘",
"diskResizeAction": "扩容",
"diskResizeDesc": "只能增大。扩大后在 macOS 终端运行提示的命令,新空间才能使用",
"diskResizeDone": "已扩大到 {size}。在 macOS 终端运行:",
"diskResizeTitle": "扩大磁盘",
"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": "设置处理器相关性失败",
"footerDisk": "磁盘可用 {gb} GB",
"footerMem": "内存 {pct}%",
"footerMemAvail": "可用 {avail} GB",
"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 虚拟机监控程序平台",
"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": "开启",
"language": "语言",
"languageSub": "内置简体中文与英语,可通过插件扩展更多语言",
"logLevel": "日志级别",
"logLevelCustom": "自定义",
"logLevelDesc": "排查问题时再调高",
"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",
"resetAll": "全部还原",
"resetField": "还原为当前值",
"runtimeDelete": "删除运行时",
"runtimeDeleteConfirm": "确认删除",
"runtimeDeleted": "已删除运行时 {commit}",
"secondsUnit": "秒",
"settingsAppearance": "外观与语言",
"settingsGeneral": "常规",
"settingsTitle": "{name}",
"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": "虚拟机文件",
"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",
"aboutCopyQQGroup": "Copy group ID",
"aboutIssueSub": "Report a problem or suggest a feature on GitHub",
"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",
"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",
"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",
"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",
"footerDisk": "Disk {gb} GB free",
"footerMem": "Memory {pct}%",
"footerMemAvail": "{avail} GB free",
"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",
"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 installers downloaded yet",
"installersHint": "Downloaded installers 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": "Installers",
"installersWaitingVM": "{vm} waiting",
"kernelIrqchipAuto": "Auto",
"kernelIrqchipLabel": "Interrupt acceleration",
"kernelIrqchipOff": "Off",
"kernelIrqchipOn": "On",
"language": "Language",
"languageSub": "Simplified Chinese and English built in; add more via plugins",
"logLevel": "Log level",
"logLevelCustom": "Custom",
"logLevelDesc": "Raise only when troubleshooting",
"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",
"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}",
"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": "Installers",
"storageRuntimes": "Reims-Go",
"storageVMs": "VM files",
"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)
+383
View File
@@ -0,0 +1,383 @@
// 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}%,虚拟机可能会卡顿",
"displayNameEdit": "点按以修改显示名称",
"displayNameEditEllipsis": "修改显示名称…",
"displayNameLabel": "显示名称",
"displayNameTip": "显示名称 · 虚拟机名称为 {name}(点按修改)",
"dropFilesHint": "松开以投递到 macOS 共享目录",
"enterRecovery": "进入恢复模式",
"exportDiagnostics": "导出排障日志 (.zip)",
"factBackingChain": "CoW 派生链",
"factCPU": "处理器",
"factDisk": "存储",
"factGraphics": "图形",
"factMemory": "内存",
"failAttachInstaller": "挂载镜像失败",
"failCloneVM": "派生 CoW 副本失败",
"failDelete": "删除失败",
"failEject": "弹出安装盘失败",
"failEnterRecovery": "进入恢复模式失败",
"failExportDiagnostics": "导出排障日志失败",
"failFinishInstall": "退出恢复模式失败",
"failFocus": "无法定位虚拟机窗口",
"failGuestTools": "Guest Tools 操作失败",
"failOpenFolder": "无法打开文件夹",
"failRestart": "重启失败",
"failScreenshot": "截屏失败",
"failSnapshot": "恢复点操作失败",
"failStart": "启动失败",
"failStop": "关机失败",
"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": "重启以应用",
"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_running": "运行中",
"state_starting": "启动中",
"state_stopped": "已停止",
"state_stopping": "停止中",
"techInfo": "技术信息",
"toastCloned": "已派生 CoW 副本「{name}」",
"toastDeleted": "已删除 {name}",
"toastDiagExported": "已导出脱敏排障日志包 (.zip)",
"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 防休眠守护",
"toastScreenshotCopied": "已复制虚拟机画面",
"toastSnapshotCreated": "已创建恢复点 {name}",
"toastSnapshotDeleted": "已删除恢复点 {name}",
"toastSnapshotRestored": "已回滚到 {name}",
"toastStopped": "{name} 已关机",
"toastTyped": "{n, plural, other {已键入 # 个字符}}",
"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",
"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",
"enterRecovery": "Enter recovery mode",
"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",
"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",
"failGuestTools": "Guest Tools operation failed",
"failOpenFolder": "Couldn’t open the folder",
"failRestart": "Couldn’t restart",
"failScreenshot": "Screenshot failed",
"failSnapshot": "Restore point failed",
"failStart": "Couldn’t start",
"failStop": "Couldn’t shut down",
"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",
"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_running": "Running",
"state_starting": "Starting",
"state_stopped": "Stopped",
"state_stopping": "Stopping",
"techInfo": "Technical details",
"toastCloned": "CoW clone “{name}” created",
"toastDeleted": "{name} deleted",
"toastDiagExported": "Redacted diagnostics archive exported (.zip)",
"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",
"toastScreenshotCopied": "VM screenshot copied",
"toastSnapshotCreated": "Created restore point {name}",
"toastSnapshotDeleted": "Deleted restore point {name}",
"toastSnapshotRestored": "Restored to {name}",
"toastStopped": "{name} shut down",
"toastTyped": "{n, plural, one {Typed # character} other {Typed # characters}}",
"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",
}
+174
View File
@@ -0,0 +1,174 @@
// 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": "导入本地包…",
"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": "可以创建",
"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…",
"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",
"wizChooseFile": "Choose…",
"wizNoFile": "No file chosen",
"wizOptions": "Options",
"wizardBasics": "Basics",
"wizardDriverGroup": "Guest driver",
"wizardDriverType": "Driver",
"wizardTitle": "New virtual machine",
}
registerBuiltinDomain(wizardZh, wizardEn)
+376
View File
@@ -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)}⟧`
}
+863
View File
@@ -0,0 +1,863 @@
// Code generated by cmd/i18ngen; DO NOT EDIT.
export type I18nKey =
| "aboutCommunity"
| "aboutCopyQQGroup"
| "aboutIssueSub"
| "aboutJoinQQGroup"
| "aboutLicensesOpenGitHub"
| "aboutLicensesSub"
| "aboutLicensesTabLicense"
| "aboutLicensesTabNotice"
| "aboutLicensesTitle"
| "aboutLicensesView"
| "aboutProjectSub"
| "aboutQQGroup"
| "aboutQQGroupSub"
| "aboutQQLaunchFailed"
| "aboutQQNotInstalled"
| "aboutQQNotInstalledSub"
| "aboutTagline"
| "activate"
| "affinityApplyNow"
| "affinityAvoidLPE"
| "affinityConfigure"
| "affinityEcoQoS"
| "affinityEcoQoSDesc"
| "affinityExcludeCPU0"
| "affinityLiveMask"
| "affinityMenu"
| "affinityModeAll"
| "affinityModeAllHint"
| "affinityModeAuto"
| "affinityModeAutoHint"
| "affinityModeCustom"
| "affinityModeCustomHint"
| "affinityModeNonLPE"
| "affinityModeNonLPEHint"
| "affinityModePCores"
| "affinityModePCoresHint"
| "affinityNeedOne"
| "affinityOnlyPCores"
| "affinityOversubWarn"
| "affinityPhysicalOnly"
| "affinityRowDesc"
| "affinitySave"
| "affinitySelectAll"
| "affinitySelectedSummary"
| "affinitySubtitleRunning"
| "affinitySubtitleStopped"
| "affinitySummaryAll"
| "affinitySummaryAuto"
| "affinitySummaryCustom"
| "affinitySummaryNonLPE"
| "affinitySummaryPCores"
| "affinityTitle"
| "appCheckUpdate"
| "appDownloadUpdate"
| "appUpToDate"
| "appUpdateAvailable"
| "appUpdateAvailableAlpha"
| "appUpdateAvailableDev"
| "appUpdateChannelAlpha"
| "appUpdateChannelDev"
| "appUpdateChannelStable"
| "appUpdateChannelSubKeepOld"
| "appUpdateChannelSubStable"
| "appUpdateChannelTitle"
| "appUpdateLookupFailed"
| "appVersionTitle"
| "appearance"
| "appliesNextStart"
| "attachGuestTools"
| "attachInstaller"
| "audioBackendAuto"
| "audioBackendDesc"
| "audioBackendDsound"
| "audioBackendNone"
| "audioBackendTitle"
| "audioDesc"
| "audioDisabledReason"
| "audioTroubleshootNote"
| "autoPinPCores"
| "back"
| "backToEdit"
| "borderless"
| "brokenHint"
| "cancel"
| "cancelCreate"
| "cancelQueue"
| "captureInput"
| "captureInputHint"
| "catAdvanced"
| "catAudio"
| "catCompute"
| "catGeneral"
| "catGraphics"
| "catInput"
| "catInputAudio"
| "catLogs"
| "catNetwork"
| "catStorage"
| "catStorageNet"
| "choose"
| "clear"
| "cloneConfirm"
| "cloneDesc"
| "cloneNameLabel"
| "cloneTitle"
| "cloneVM"
| "close"
| "closeWindow"
| "collapseLogs"
| "commandToggle"
| "commandToggleHint"
| "configured"
| "connGroup"
| "copy"
| "copyScreenshot"
| "copyTechInfo"
| "cores"
| "coresUnit"
| "cpuOverHint"
| "cpuRecHint"
| "createNow"
| "createStartedHint"
| "delete"
| "deleteConfirm"
| "deleteDesc"
| "deleteDescKeep"
| "deleteEllipsis"
| "deleteKeepFiles"
| "deleteTitle"
| "deliverFileShort"
| "detachGuestTools"
| "diagAhciUpgradeHint"
| "diagBackingChainBroken"
| "diagBackingChainWarn"
| "diagExternalDriveWarn"
| "diagHighMemWarn"
| "diskCompactAction"
| "diskCompactDesc"
| "diskCompactDone"
| "diskCompactNoGain"
| "diskCompactQcow2Only"
| "diskCompactTitle"
| "diskController"
| "diskControllerInstallHint"
| "diskControllerNvmeHint"
| "diskControllerNvmeReadyHint"
| "diskControllerVirtioHint"
| "diskControllerWarn"
| "diskMode"
| "diskModeCopy"
| "diskModeInPlace"
| "diskResizeAction"
| "diskResizeDesc"
| "diskResizeDone"
| "diskResizeTitle"
| "diskSize"
| "diskSizeHint"
| "diskUsageSummary"
| "displayGroup"
| "displayNameEdit"
| "displayNameEditEllipsis"
| "displayNameLabel"
| "displayNameTip"
| "displays"
| "driveShareMaster"
| "driveShareMasterDesc"
| "driveShareNeedsTools"
| "driveShareNoDrives"
| "driveShareReadOnly"
| "driveShareSystem"
| "driveShareTitle"
| "dropFilesHint"
| "effectImmediate"
| "effectNextStart"
| "eject"
| "emptyVMs"
| "enableAudio"
| "enableLogs"
| "enableNetwork"
| "enableWHPX"
| "enterRecovery"
| "errCopyDetails"
| "errRawDetailsToggle"
| "errorBoundaryReload"
| "errorBoundaryTitle"
| "expandLogs"
| "exportDiagnostics"
| "extraArgs"
| "extraArgsDesc"
| "factBackingChain"
| "factCPU"
| "factDisk"
| "factGraphics"
| "factMemory"
| "failAffinity"
| "failAttachInstaller"
| "failCloneVM"
| "failCreate"
| "failDelete"
| "failDownload"
| "failEject"
| "failEnterRecovery"
| "failExportDiagnostics"
| "failFinishInstall"
| "failFocus"
| "failGeneric"
| "failGuestTools"
| "failOpenFolder"
| "failRestart"
| "failRuntime"
| "failSSH"
| "failScreenshot"
| "failSnapshot"
| "failStart"
| "failStop"
| "failType"
| "failUpgradeNVMe"
| "fieldAudio"
| "fieldCPUModel"
| "fieldController"
| "fieldDir"
| "fieldDisk"
| "fieldGraphicsBackend"
| "fieldICD"
| "fieldKind"
| "fieldNetwork"
| "fieldVMName"
| "finishInstall"
| "fontMissingFoDHint"
| "footerDisk"
| "footerDiskLabel"
| "footerDiskTip"
| "footerDiskValue"
| "footerHostIssue"
| "footerHostIssueTip"
| "footerMem"
| "footerMemAvail"
| "footerMemLabel"
| "footerMemTip"
| "footerMemValue"
| "footerRunningVMs"
| "forceStop"
| "fullscreenLaunch"
| "fullscreenLaunchHint"
| "gpuAuto"
| "gpuAutoOption"
| "gpuAutoSub"
| "gpuAutoTitle"
| "gpuCompatUnsupported"
| "gpuCompatWarn"
| "gpuCustomIcd"
| "gpuDiscrete"
| "gpuErrMissingExt"
| "gpuErrVulkanCpu"
| "gpuErrVulkanTooOld"
| "gpuIntegrated"
| "gpuKindDiscrete"
| "gpuKindIntegrated"
| "gpuRecommended"
| "gpuSelect"
| "gpuSvgaReason"
| "gpuSwitchSvga"
| "gpuUnavailableHint"
| "gpuUnknown"
| "gpuVirtual"
| "gpuWarnAmdLegacy"
| "gpuWarnAmdRdna2"
| "graphicsBackend"
| "graphicsReimsDesc"
| "graphicsReimsShort"
| "graphicsRunningReason"
| "graphicsSvgaDesc"
| "graphicsSvgaShort"
| "groupGraphics"
| "groupMacOS"
| "groupPerformance"
| "groupQemu"
| "gtInstall"
| "gtInstallCmd"
| "gtInstallSub"
| "gtNotInstalledDesc"
| "gtStatusConnected"
| "gtStatusEnabled"
| "gtStatusNone"
| "gtStatusOff"
| "gtStatusOffTip"
| "gtStatusUpgrade"
| "gtStatusWaiting"
| "gtStatusWaitingTip"
| "gtUpdate"
| "guestKbdPinyin"
| "guestKbdUS"
| "guestKbdUSRecommended"
| "guestLang"
| "guestLangEnUS"
| "guestLangHint"
| "guestLangJaJP"
| "guestLangKoKR"
| "guestLangSettingsHint"
| "guestLangShort"
| "guestLangZhHansUS"
| "guestLangZhHantUS"
| "guestMemory"
| "guestToolsConnected"
| "guestToolsModeSync"
| "guestToolsModeWebDAV"
| "guestToolsPreventSleep"
| "guestToolsPreventSleepSub"
| "guestToolsReady"
| "guestToolsSleepActive"
| "guestToolsTitle"
| "guestToolsUpgradeHint"
| "guideBuiltIn1"
| "guideBuiltIn2"
| "guideBuiltIn3"
| "guideKindBuiltIn"
| "guideKindOffline"
| "guideKindOnline"
| "guideOffline1"
| "guideOffline2"
| "guideOffline3"
| "guideStartHint"
| "guideStep1"
| "guideStep2"
| "guideStep3"
| "guideTitle"
| "helpAbout"
| "helpCheckUpdate"
| "helpProjectPage"
| "helpReportIssue"
| "hideSidebar"
| "hidpiPresetBadge"
| "hidpiTipFullscreen"
| "hidpiTipScale"
| "hidpiTipUnavailable"
| "hostAudioInput"
| "hostAudioMissingIn"
| "hostAudioMissingOut"
| "hostAudioOutput"
| "hostCPU"
| "hostCoresThreads"
| "hostDataRoot"
| "hostDisk"
| "hostDisplayHint"
| "hostDisplayPrimary"
| "hostDisplays"
| "hostGPUs"
| "hostNeedsAction"
| "hostRAM"
| "hostRAMAvail"
| "hostRAMTotal"
| "hostReady"
| "hostRuntime"
| "hostWHPX"
| "importRuntime"
| "installersAvailable"
| "installersCreateVM"
| "installersDelete"
| "installersDeleteConfirm"
| "installersDownload"
| "installersDownloaded"
| "installersDownloading"
| "installersDownloadingForVM"
| "installersDownloadingPct"
| "installersEmpty"
| "installersHint"
| "installersKindOffline"
| "installersKindOnline"
| "installersLatest"
| "installersNoSpace"
| "installersOlder"
| "installersPartial"
| "installersQueued"
| "installersQueuedDesc"
| "installersQueuedForVM"
| "installersResume"
| "installersRetry"
| "installersTitle"
| "installersWaitingVM"
| "issuesCount"
| "jumpLatest"
| "kernelIrqchipAuto"
| "kernelIrqchipLabel"
| "kernelIrqchipOff"
| "kernelIrqchipOn"
| "language"
| "languageSub"
| "localeAuto"
| "localeAutoDetail"
| "logActivity"
| "logButton"
| "logCopy"
| "logErrorsOnly"
| "logLevel"
| "logLevelCustom"
| "logLevelDesc"
| "logQemu"
| "logSearchPlaceholder"
| "logSerial"
| "logsEmpty"
| "macos.appsUtilitiesTerminal"
| "macos.diskUtility"
| "macos.erase"
| "macos.finder"
| "macos.guidPartitionMap"
| "macos.otherSignInSetUpLater"
| "macos.recovery"
| "macos.reinstallMacOS"
| "macos.setupAssistant"
| "macos.showAllDevices"
| "macos.utilitiesTerminal"
| "macos.volume"
| "macosVersion"
| "maximize"
| "memCommitHint"
| "memOverHint"
| "memRecHint"
| "menuBar"
| "menuHelp"
| "menuVM"
| "menuView"
| "minimize"
| "minimizeToTray"
| "minimizeToTraySub"
| "more"
| "multiDisplayHint"
| "navHasIssue"
| "netOff"
| "netShared"
| "networkDesc"
| "networkOfflineHint"
| "networkTitle"
| "newVM"
| "newVMEllipsis"
| "next"
| "noChanges"
| "noRuntimeAlert"
| "off"
| "offlineCached"
| "offlineDownloading"
| "offlineHint"
| "offlineListFailed"
| "offlineListFailedDetail"
| "offlineLoading"
| "offlineQueued"
| "offlineSpaceWarn"
| "on"
| "onlineRecoveryConfirm"
| "onlineRecoveryDesc"
| "onlineRecoveryTitle"
| "openFolder"
| "openSharedFolder"
| "openShort"
| "opencore"
| "optAuto"
| "optAvailable"
| "optExperimental"
| "optKernelIrqchipExp"
| "optKernelIrqchipNestedErr"
| "optKernelIrqchipRec"
| "optKernelIrqchipUnavailable"
| "optKernelIrqchipWin10NoPatch"
| "optPCoreSub"
| "optPCoreUnavailable"
| "optRecommended"
| "optSchedBackground"
| "optSchedNowBackground"
| "optSchedNowPrograms"
| "optSchedOpen"
| "optSchedPrograms"
| "optSchedSub"
| "optSchedTitle"
| "optUnavailable"
| "panelLoadFailed"
| "pauseDownload"
| "pendingChanges"
| "pendingRestartHint"
| "pendingTitle"
| "pickRecoveryTitle"
| "platformReadonly"
| "pluginAccentSeed"
| "pluginActiveCount"
| "pluginActiveTheme"
| "pluginAlwaysOn"
| "pluginApproveCheckbox"
| "pluginApproveConfirm"
| "pluginApproveL3Warn"
| "pluginApproveTitle"
| "pluginBuiltinSection"
| "pluginColorSchemes"
| "pluginColorSchemesHint"
| "pluginDeleteScheme"
| "pluginDone"
| "pluginEntryPath"
| "pluginExternalSection"
| "pluginFailDeleteScheme"
| "pluginFailEnable"
| "pluginFailImport"
| "pluginFailLinkDev"
| "pluginFailLoad"
| "pluginFailLoadSettings"
| "pluginFailMarketInstall"
| "pluginFailMarketLoad"
| "pluginFailReadLog"
| "pluginFailRemove"
| "pluginFailSaveScheme"
| "pluginFailSaveSettings"
| "pluginFailScan"
| "pluginFailSwitchTheme"
| "pluginFailToggle"
| "pluginGlobalSettings"
| "pluginHighRiskNotice"
| "pluginImportBtn"
| "pluginImportTitle"
| "pluginInUse"
| "pluginLinkDevBtn"
| "pluginLinkDevTitle"
| "pluginLogEmpty"
| "pluginLogTitle"
| "pluginMarketEmpty"
| "pluginMarketIncludeAlpha"
| "pluginMarketIncompatible"
| "pluginMarketInstall"
| "pluginMarketInstalled"
| "pluginMarketKindAll"
| "pluginMarketKindDriver"
| "pluginMarketKindLocale"
| "pluginMarketKindTheme"
| "pluginMarketKindTool"
| "pluginMarketRefresh"
| "pluginMarketSearchPlaceholder"
| "pluginMarketSourceCache"
| "pluginMarketSourceFallback"
| "pluginMarketSourceRemote"
| "pluginMarketStaleBanner"
| "pluginMarketUpdate"
| "pluginMarketWithdrawn"
| "pluginMarketWithdrawnInstalledWarn"
| "pluginMarketWithdrawnInstead"
| "pluginNewScheme"
| "pluginPanelsSection"
| "pluginPermCount"
| "pluginPermissionsLabel"
| "pluginPublisherLicense"
| "pluginRemove"
| "pluginRequestedPerms"
| "pluginSafeModeShort"
| "pluginScanAdvisoriesSection"
| "pluginScanArchiveTitle"
| "pluginScanBlockedBtn"
| "pluginScanCapabilitiesSection"
| "pluginScanHardSection"
| "pluginScanInspect"
| "pluginScanInstallConfirm"
| "pluginScanLoading"
| "pluginScanModalTitle"
| "pluginScanMoreItems"
| "pluginSchemeDefault"
| "pluginSchemeModalTitle"
| "pluginSchemeName"
| "pluginSchemePlaceholder"
| "pluginSearchEmpty"
| "pluginSearchPlaceholder"
| "pluginSettings"
| "pluginStateDegraded"
| "pluginStateFailed"
| "pluginStatePending"
| "pluginSurfaceSeed"
| "pluginTabInstalled"
| "pluginTabMarket"
| "pluginThemeEmptyHint"
| "pluginThemeHint"
| "pluginThemePackLabel"
| "pluginThemeSafeModeHint"
| "pluginThemeSection"
| "pluginTrustCommunity"
| "pluginTrustDev"
| "pluginTrustOfficial"
| "pluginTrustVerified"
| "pluginViewLog"
| "recommendedBadge"
| "refresh"
| "resCustom"
| "resCustomSub"
| "resFullscreen"
| "resInvalid"
| "resLooksLike"
| "resetAll"
| "resetField"
| "resizeLogPanel"
| "resolution"
| "restart"
| "restartToApply"
| "runtimeAlpha"
| "runtimeAlphaHint"
| "runtimeChannel_alpha"
| "runtimeChannel_stable"
| "runtimeCurrent"
| "runtimeDelete"
| "runtimeDeleteConfirm"
| "runtimeDeleted"
| "runtimeInstall"
| "runtimeLatest"
| "runtimeLookupFailed"
| "runtimeLookupRateLimit"
| "runtimeNewer"
| "runtimeNoneOnChannel"
| "runtimeOnline"
| "runtimeRetry"
| "runtimeUpToDate"
| "runtimeUpdate"
| "safeModeBanner"
| "safeModeManagePlugins"
| "save"
| "secondsUnit"
| "sendText"
| "sendTextConfirm"
| "sendTextDesc"
| "sendTextDescNoGT"
| "sendTextPlaceholder"
| "sendTextTitle"
| "settings"
| "settingsAbout"
| "settingsAppearance"
| "settingsEllipsis"
| "settingsGeneral"
| "settingsTitle"
| "setupCheck"
| "setupContinue"
| "setupDesc"
| "setupDone"
| "setupExternal"
| "setupFree"
| "setupGPU"
| "setupImport"
| "setupLater"
| "setupNoGPU"
| "setupOther"
| "setupRecMem"
| "setupRecommended"
| "setupReuse"
| "setupRuntimeDesc"
| "setupRuntimeTitle"
| "setupSystem"
| "setupTitle"
| "setupWarnExternal"
| "setupWarnSpace"
| "setupWarnSystem"
| "sharedFolder"
| "shortcutBarFullscreen"
| "shortcutBarRelease"
| "showInstallGuide"
| "showSidebar"
| "showWindow"
| "sidebarHost"
| "sidebarInstallers"
| "sidebarItemAria"
| "sidebarLabel"
| "sidebarPlugins"
| "sidebarSettings"
| "sidebarSystem"
| "sidebarVMs"
| "snapshotCreate"
| "snapshotDelete"
| "snapshotEmpty"
| "snapshotHint"
| "snapshotNamePlaceholder"
| "snapshotRestore"
| "snapshotRestoreDesc"
| "snapshotRestoreTitle"
| "snapshotStopFirst"
| "snapshotsTitle"
| "softwareGraphics"
| "sourceDisk"
| "sourceInstaller"
| "specCPULiveTip"
| "specCPUTip"
| "specDiskTip"
| "specDiskUsage"
| "specGraphicsTip"
| "specLang"
| "specLangTip"
| "specLangTipDetail"
| "specMemLiveTip"
| "specMemTip"
| "specNetOffTip"
| "specNetSSHTip"
| "specNetTip"
| "srcAppleSub"
| "srcAppleTitle"
| "srcDiskSub"
| "srcDiskTitle"
| "srcInstallerSub"
| "srcInstallerTitle"
| "srcOfflineSub"
| "srcOfflineTitle"
| "sshForward"
| "sshMore"
| "sshNeedsNetwork"
| "sshOffDesc"
| "sshOpenTerminal"
| "sshOpenVSCode"
| "sshPort"
| "sshSetUser"
| "sshUserDesc"
| "sshUserPlaceholder"
| "sshUserTitle"
| "sshWriteConfig"
| "start"
| "startAfterCreate"
| "starting"
| "state_broken"
| "state_creating"
| "state_driver_unavailable"
| "state_running"
| "state_starting"
| "state_stopped"
| "state_stopping"
| "statsCPU"
| "statsDisk"
| "statsDiskSub"
| "statsMemory"
| "statsUptime"
| "step1"
| "step2"
| "step3"
| "step4"
| "step5"
| "stop"
| "stopBeforeDiskOp"
| "stopTimeout"
| "stopTimeoutHint"
| "storageBreakdownTitle"
| "storageInstallers"
| "storageRuntimes"
| "storageVMs"
| "summaryAppleSource"
| "summaryDefaultDir"
| "summaryDiskGrow"
| "summaryDiskSource"
| "summaryEdit"
| "summaryInstallerSource"
| "summaryLogs"
| "summaryOfflineSource"
| "summaryOn"
| "summarySSH"
| "summarySSHPort"
| "summarySource"
| "taskAppUpdate"
| "taskCreate"
| "taskDownload"
| "taskRecoveryDownload"
| "taskRuntime"
| "tasksRunning"
| "techInfo"
| "themeDark"
| "themeLabel"
| "themeLight"
| "themePluginDarkDisabled"
| "themePluginLightDisabled"
| "themeSwitchDark"
| "themeSwitchLight"
| "themeSystem"
| "toastAffinityApplied"
| "toastAffinitySaved"
| "toastBorderlessNextStart"
| "toastBorderlessUpdated"
| "toastCloned"
| "toastCopied"
| "toastCreateCanceled"
| "toastCreateCanceledPartial"
| "toastCreated"
| "toastDeleted"
| "toastDiagExported"
| "toastDownloadPaused"
| "toastEjected"
| "toastEnterRecovery"
| "toastEnterRecoveryNextStart"
| "toastExitRecoveryNextStart"
| "toastFileDelivered"
| "toastFilesDelivered"
| "toastGuestToolsAttached"
| "toastGuestToolsAttachedNextStart"
| "toastGuestToolsDetached"
| "toastGuestToolsDetachedNextStart"
| "toastInstallFinished"
| "toastInstallerAttached"
| "toastInstallerAttachedNextStart"
| "toastInstallerReady"
| "toastNVMeNextStart"
| "toastNVMeReady"
| "toastOnlineRecoveryAttached"
| "toastOnlineRecoveryStarted"
| "toastPreventSleepOff"
| "toastPreventSleepOn"
| "toastQueueCanceled"
| "toastRuntimeReady"
| "toastSSHConfigWritten"
| "toastSSHUserSaved"
| "toastSaved"
| "toastSavedNextStart"
| "toastScreenshotCopied"
| "toastSnapshotCreated"
| "toastSnapshotDeleted"
| "toastSnapshotRestored"
| "toastStopped"
| "toastTyped"
| "typeClipboard"
| "typeIntoVM"
| "typeUntypeable"
| "updateCancel"
| "updateCapsuleAvailable"
| "updateCapsuleDownloading"
| "updateCapsuleDownloadingPct"
| "updateCapsuleFailed"
| "updateCapsuleOpen"
| "updateCapsuleReady"
| "updateConfirmBody"
| "updateConfirmTitle"
| "updateConfirmWin10"
| "updateDoneToast"
| "updateDownload"
| "updateDownloadInstall"
| "updateDownloadingSub"
| "updateFailed"
| "updateFailedSub"
| "updateLater"
| "updateReadySub"
| "updateReleaseNotes"
| "updateRestart"
| "updateRetry"
| "upgradeToNVMe"
| "uptimeHoursMinutes"
| "uptimeMinutesSeconds"
| "uptimeSeconds"
| "useDefault"
| "validationChecking"
| "validationPassed"
| "vcpus"
| "viewLogs"
| "vmDir"
| "vmName"
| "welcomeCheckHost"
| "welcomeSub"
| "welcomeTitle"
| "whpxMissing"
| "whpxMissingShort"
| "whpxNoHv"
| "whpxNoHvShort"
| "whpxReady"
| "whpxTitle"
| "whpxUnsupported"
| "whpxUnsupportedShort"
| "wizChooseFile"
| "wizNoFile"
| "wizOptions"
| "wizardBasics"
| "wizardDriverGroup"
| "wizardDriverType"
| "wizardTitle";
+12
View File
@@ -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)
}
+108 -34
View File
@@ -1,6 +1,12 @@
import { I18nKey, t } from '../i18n'
import { formatLocaleNumber } from '../i18n/icu'
import { DisplayPreset, GPUInfo, HostReport, Locale, VMDetail } from '../types'
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".
@@ -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,20 +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): string {
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 ? Math.round(a).toString() : a.toFixed(1)
const vStr = Math.round(v).toString()
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)} / ${formatBytes(virtual)}`
return `${formatBytes(actual, loc)} / ${formatBytes(virtual, loc)}`
}
export function formatUptime(sec: number, locale: Locale): string {
@@ -136,14 +200,9 @@ 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.toLowerCase().startsWith('zh')) {
if (h > 0) return `${h}小时 ${m}分`
if (m > 0) return `${m}分 ${s}秒`
return `${s}秒`
}
if (h > 0) return `${h}h ${m}m`
if (m > 0) return `${m}m ${s}s`
return `${s}s`
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
@@ -196,19 +255,27 @@ 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 {
const l = locale.toLowerCase()
if (l === 'zh-tw' || l === 'zh-hk' || l === 'zh-mo' || l.startsWith('zh-hant')) return 'zh-Hant:0'
@@ -218,11 +285,18 @@ export function defaultGuestLang(locale: Locale): string {
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.toLowerCase().startsWith('zh') ? hit.zh : hit.en
return code
const { label, detail } = resolveGuestLang(locale, code)
return detail ? `${label} (${detail})` : label
}
/**
@@ -242,10 +316,10 @@ export function splitLangLabel(value: string, text: string): { value: string; la
export function pendingChangeText(locale: Locale, p: { field: string; from: string; to: string }, host: HostReport): string {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const bool = (v: string) => tr(v === 'true' ? 'on' : 'off')
const lang = (v: string) => splitLangLabel('', guestLangLabel(locale, v)).label
const 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: formatMemory },
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 },
+1
View File
@@ -1,3 +1,4 @@
import '../i18n/domains/settings.gen'
import { I18nKey, t } from '../i18n'
import { Locale, Optimization, OptimizationStatus } from '../types'
+136 -3
View File
@@ -1,5 +1,5 @@
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
@@ -21,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 }
}
@@ -49,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`
+156 -6
View File
@@ -34,6 +34,8 @@ interface ThemeTokenCache {
export interface UIStateSnapshot {
appearance: 'light' | 'dark'
motion: 'full' | 'reduced'
locale: string
dir: 'ltr' | 'rtl'
view: string
vmName: string
vmState: string
@@ -51,6 +53,7 @@ export interface ThemeSDKHostActions {
}
let activeUIScriptCleanup: (() => void) | null = null
let activeUIScriptNotifier: ((snap: UIStateSnapshot) => void) | null = null
let activeUIScriptURL = ''
let applyGeneration = 0
@@ -231,20 +234,21 @@ function clearDynamicThemeStyles(): void {
}
}
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 if (clean.length === 6) {
} 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
} else {
return null
}
if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) return null
const max = Math.max(r, g, b)
@@ -264,6 +268,86 @@ 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>,
@@ -276,9 +360,10 @@ export function deriveTokensFromSeeds(
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'] = `hsl(${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(clamp01(appearance === 'dark' ? Math.max(l, 0.66) : Math.min(l, 0.42)) * 100)}%)`
out['--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})`
}
}
@@ -454,14 +539,18 @@ export async function applyActiveTheme(
// 5. Tier 3: lazy-load UI SDK ONLY when an approved interactive theme script is present (§8.1).
if (nextScriptURL && nextScriptURL !== activeUIScriptURL) {
try {
const { mountInteractiveThemeScript } = await import('./uiSdk')
const { mountInteractiveThemeScript, notifyThemeSDKState } = await import('./uiSdk')
if (gen !== applyGeneration) return
const cleanup = await mountInteractiveThemeScript(nextScriptURL, getState, actions)
if (gen !== applyGeneration) {
try { cleanup() } catch {}
return
}
activeUIScriptCleanup = cleanup
activeUIScriptCleanup = () => {
activeUIScriptNotifier = null
cleanup()
}
activeUIScriptNotifier = notifyThemeSDKState
activeUIScriptURL = nextScriptURL
} catch {
if (gen === applyGeneration) {
@@ -473,6 +562,67 @@ export async function applyActiveTheme(
}
}
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 {}
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]
+213 -71
View File
@@ -10,14 +10,22 @@
html, body, #root {
margin: 0; padding: 0; height: 100%; overflow: hidden;
background: var(--surface-0); color: var(--text);
font-family: var(--font-sans); font-size: var(--fs-14); font-weight: var(--fw-regular); line-height: 1.48;
font-family: var(--font-sans); font-size: var(--fs-14); font-weight: var(--fw-regular); line-height: var(--body-lh, 1.48);
font-optical-sizing: auto;
font-feature-settings: "cv02", "cv03", "cv04";
text-autospace: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
html:lang(ja) { line-break: strict; }
html:lang(ko) { word-break: keep-all; }
:is(:lang(zh), :lang(ja), :lang(ko)) :is(em, i) { font-style: normal; font-weight: var(--fw-medium); }
:is(:lang(zh), :lang(ja), :lang(ko)) :is(.brand, .sidebar-head, .sidebar-section-label, .sidebar-brand-name, .about-hero-text h1) {
letter-spacing: var(--heading-tracking, 0em);
}
@media (pointer: fine) {
html { overscroll-behavior: none; }
}
@@ -54,7 +62,7 @@ h1, h2, h3, p { margin: 0; }
.titlebar {
height: var(--titlebar-h); flex-shrink: 0; position: relative; z-index: 10;
display: flex; align-items: center; justify-content: space-between;
padding-left: var(--sp-4);
padding-inline-start: var(--sp-4);
/* No backdrop blur: the bar is opaque, so blurring behind it showed nothing
and still cost a GPU compositing layer (the GPU is shared with the VM). */
background: var(--surface-chrome);
@@ -96,9 +104,9 @@ h1, h2, h3, p { margin: 0; }
color: var(--text-3); font-variant-numeric: tabular-nums;
}
.menu-item[data-highlighted] .menu-shortcut { color: rgba(255, 255, 255, 0.78); }
.menu-item.menu-item-check, .menu-indented .menu-item { position: relative; padding-left: 28px; }
.menu-indented .menu-group-label { padding-left: 28px; }
.menu-check { position: absolute; left: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; }
.menu-item.menu-item-check, .menu-indented .menu-item { position: relative; padding-inline-start: 28px; }
.menu-indented .menu-group-label { padding-inline-start: 28px; }
.menu-check { position: absolute; inset-inline-start: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; }
.menu-group-label { padding: 6px 10px 2px; font-size: 11.5px; font-weight: var(--fw-medium); color: var(--text-3); user-select: none; }
.theme-toggle {
width: 30px; height: 28px; margin-right: var(--sp-1);
@@ -120,7 +128,8 @@ h1, h2, h3, p { margin: 0; }
.win-btn.close:hover { background: #e81123; color: #fff; }
.win-btn:focus-visible { border-radius: 0; }
.workspace { display: flex; flex: 1; min-height: 0; background: var(--surface-canvas); }
.workspace { position: relative; display: flex; flex: 1; min-height: 0; background: var(--surface-canvas); }
.sidebar-backdrop { display: none; }
/* ── Floating Tahoe Sidebar ────────────────────────────── */
.sidebar-wrap {
@@ -128,12 +137,12 @@ h1, h2, h3, p { margin: 0; }
padding: 10px;
display: flex; overflow: hidden;
background: var(--surface-sidebar-rail);
border-right: 1px solid var(--border);
border-inline-end: 1px solid var(--border);
transition: width var(--dur-modal) var(--ease-out), padding var(--dur-modal) var(--ease-out), opacity var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out);
}
/* Hidden sidebar (Ctrl+B): slides shut; the card keeps its width so its
contents don't reflow while the rail narrows. */
.workspace.sidebar-hidden .sidebar-wrap { width: 0; padding-left: 0; padding-right: 0; opacity: 0; border-right-color: transparent; }
.workspace.sidebar-hidden .sidebar-wrap { width: 0; padding-inline: 0; opacity: 0; border-inline-end-color: transparent; }
.sidebar-wrap > .sidebar { min-width: calc(var(--sidebar-w) - 20px); }
.sidebar {
flex: 1; min-height: 0;
@@ -180,30 +189,30 @@ h1, h2, h3, p { margin: 0; }
.update-capsule.is-failed { background: var(--warn-soft); color: var(--warn-text); }
.update-capsule-main {
flex: 1; min-width: 0; display: flex; align-items: center; gap: 7px;
padding: 0; border: 0; background: none; color: inherit; cursor: pointer; text-align: left;
padding: 0; border: 0; background: none; color: inherit; cursor: pointer; text-align: start;
}
.update-capsule-icon {
width: 22px; height: 22px; flex-shrink: 0; border-radius: 50%;
display: inline-flex; align-items: center; justify-content: center;
background: var(--accent); color: var(--accent-text);
}
.update-capsule.is-failed .update-capsule-icon { background: var(--warn-text); }
.update-capsule.is-failed .update-capsule-icon { background: var(--status-busy); color: #1d1d1f; }
.update-capsule-title {
min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
font-size: 12px; font-weight: var(--fw-medium);
font-size: var(--fs-12); font-weight: var(--fw-medium);
}
.update-capsule-btn {
flex-shrink: 0; display: inline-flex; align-items: center; gap: 3px;
height: 22px; padding: 0 9px; border: 0; border-radius: 999px;
height: 24px; padding: 0 9px; border: 0; border-radius: 999px;
background: var(--surface-1); color: inherit;
font-size: 11.5px; font-weight: var(--fw-medium); cursor: pointer;
font-size: var(--fs-12); font-weight: var(--fw-medium); cursor: pointer;
transition: filter var(--dur) var(--ease-out), transform var(--dur) var(--ease-out);
}
.update-capsule-btn.is-primary { background: var(--accent); color: var(--accent-text); }
.update-capsule-btn:hover { filter: brightness(1.06); }
.update-capsule-btn:active { transform: scale(0.96); }
.update-capsule-x {
flex-shrink: 0; width: 22px; height: 22px; border: 0; border-radius: 50%;
flex-shrink: 0; width: 24px; height: 24px; border: 0; border-radius: 50%;
display: inline-flex; align-items: center; justify-content: center;
background: none; color: inherit; opacity: 0.7; cursor: pointer;
}
@@ -219,24 +228,27 @@ h1, h2, h3, p { margin: 0; }
.nav-vms { flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; }
.nav-system { flex-shrink: 0; margin-top: 6px; padding-top: 8px; border-top: 1px solid var(--border); }
.nav-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; background: var(--accent); }
.nav-item[aria-selected="true"] .nav-dot { background: var(--accent-text); }
.nav-item[aria-selected="true"] .nav-dot,
.nav-item[aria-current="page"] .nav-dot { background: var(--accent-text); }
.nav-empty { padding: 8px 10px; font-size: var(--fs-12); color: var(--text-3); }
.nav-item {
width: 100%; height: 36px; padding: 0 10px;
display: flex; align-items: center; gap: 10px;
border: none; border-radius: 9px; background: transparent; color: var(--text);
text-align: left; cursor: pointer;
text-align: start; cursor: pointer;
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), box-shadow var(--dur) var(--ease-out), transform var(--dur-press) var(--ease-out);
}
.nav-item:hover { background: var(--surface-hover); }
.nav-item:active { transform: scale(0.985); }
.nav-item[aria-selected="true"] {
.nav-item[aria-selected="true"],
.nav-item[aria-current="page"] {
background: var(--accent);
color: var(--accent-text);
font-weight: var(--fw-medium);
box-shadow: 0 1px 2px rgba(0, 122, 255, 0.22), inset 0 1px 0 rgba(255, 255, 255, 0.18);
}
.nav-item[aria-selected="true"] .nav-icon-badge {
.nav-item[aria-selected="true"] .nav-icon-badge,
.nav-item[aria-current="page"] .nav-icon-badge {
background: rgba(255, 255, 255, 0.22);
color: #ffffff;
box-shadow: none;
@@ -313,8 +325,8 @@ h1, h2, h3, p { margin: 0; }
@media (hover: hover) and (pointer: fine) {
.vm-display-unit.is-actionable:hover { transform: translateY(-2px); }
.vm-display-unit.is-actionable:hover .vm-screen { box-shadow: 0 20px 40px rgba(15, 23, 42, 0.22), 0 4px 10px rgba(15, 23, 42, 0.10), inset 0 1px 0 rgba(255, 255, 255, 0.14); }
.vm-display-unit.is-actionable:hover .vm-screen-play,
.vm-display-unit.is-actionable:hover .vm-screen-chip { opacity: 1; transform: none; }
.vm-display-unit.is-actionable:hover .vm-screen-play { opacity: 1; transform: none; }
.vm-display-unit.is-actionable:hover .vm-screen-chip { opacity: 1; transform: translateX(-50%) translateY(0); }
.vm-display-unit.is-actionable:hover .vm-screen.is-idle .vm-screen-img { filter: saturate(0.7) brightness(0.8); }
}
.vm-display-unit.is-actionable:active { transform: scale(0.985); }
@@ -378,9 +390,9 @@ h1, h2, h3, p { margin: 0; }
}
.vm-spec-cell {
display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center;
column-gap: 8px; row-gap: 6px; min-width: 0; cursor: default;
column-gap: 8px; row-gap: 6px; min-width: 0; cursor: default; border-radius: var(--r-sm);
}
.vm-spec-cell:focus-visible { box-shadow: none; }
.vm-spec-cell:focus-visible { outline: none; box-shadow: var(--focus-ring); }
.vm-spec-icon {
color: var(--text-3); display: inline-flex; align-items: center; flex-shrink: 0;
}
@@ -550,7 +562,11 @@ h1, h2, h3, p { margin: 0; }
.notice-icon { flex-shrink: 0; margin-top: 2px; color: var(--warn-text); }
.notice-error { background: var(--danger-soft); border-color: var(--danger-border); color: var(--danger-text); padding: 10px 14px; }
.notice-error .notice-icon { color: var(--danger-text); }
.notice-error ul { margin: 0; padding-left: var(--sp-4); }
.notice-error ul { margin: 0; padding-inline-start: var(--sp-4); }
.notice-warn { background: var(--warn-soft); border-color: var(--notice-border); color: var(--warn-text); justify-content: flex-start; }
.notice-warn .notice-icon { color: var(--warn-text); }
.notice-ok { background: var(--ok-soft); border-color: transparent; color: var(--ok-text); justify-content: flex-start; }
.notice-ok .notice-icon { color: var(--ok-text); }
.notice-info { background: var(--accent-soft); border-color: transparent; }
.notice-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.notice-title { font-weight: var(--fw-medium); }
@@ -597,9 +613,9 @@ h1, h2, h3, p { margin: 0; }
.tech[open] > summary svg { transform: rotate(90deg); }
.tech > summary:hover { color: var(--text); background: var(--surface-hover); }
.tech-body { position: relative; margin-top: 8px; }
.tech-copy { position: absolute; top: 8px; right: 8px; }
.tech-copy { position: absolute; top: 8px; inset-inline-end: 8px; }
.kv-list {
margin: 0; padding: 12px 44px 12px 16px;
margin: 0; padding-block: 12px; padding-inline: 16px 44px;
background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg);
display: grid; grid-template-columns: max-content 1fr; gap: 7px 24px; font-size: var(--fs-13);
}
@@ -619,11 +635,12 @@ h1, h2, h3, p { margin: 0; }
.badge-accent { background: var(--accent-soft); color: var(--accent-soft-text); }
.badge-ok { background: var(--ok-soft); color: var(--ok-text); }
.badge-warn { background: var(--warn-soft); color: var(--warn-text); }
.badge-danger { background: var(--danger-soft); color: var(--danger-text); }
.badge-error { background: var(--danger); color: #fff; min-width: 18px; height: 18px; padding: 0 var(--sp-1); justify-content: center; border-radius: 999px; font-variant-numeric: tabular-nums; }
/* Host summary tiles (4-up single row, 2x2 on narrow windows) */
/* Host summary tiles (4-up single row, 2x2 on narrow content column) */
.tiles { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; }
@media (max-width: 820px) {
@container (max-width: 680px) {
.tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
.tile {
@@ -693,9 +710,17 @@ h1, h2, h3, p { margin: 0; }
.about-hero-text { min-width: 0; display: flex; flex-direction: column; gap: 4px; }
.about-hero-text h1 { font-size: 22px; font-weight: var(--fw-strong); letter-spacing: -0.02em; color: var(--text); }
.about-hero-text p { margin: 0; font-size: var(--fs-13); color: var(--text-2); line-height: 1.5; }
.license-modal-body { gap: var(--sp-3); }
.license-pre {
margin: 0; padding: 14px 16px; min-height: 260px; max-height: 52vh; overflow: auto;
border-radius: var(--r-md); border: 1px solid var(--border); background: var(--surface-1);
font-family: var(--font-mono); font-size: var(--fs-12); line-height: 1.55; color: var(--text-2);
white-space: pre-wrap; word-break: break-word; user-select: text;
}
.section-count { min-width: 20px; padding: 1px 7px; border-radius: 999px; background: var(--surface-active); color: var(--text-3); font-size: 11px; font-weight: var(--fw-medium); text-align: center; }
.installer-row { min-height: 62px; }
.installer-art, .release-art { display: block; flex-shrink: 0; overflow: hidden; border-radius: 10px; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.28), 0 2px 5px rgba(15, 23, 42, 0.12); }
.installer-active-status { gap: 5px; font-variant-numeric: tabular-nums; }
.installer-art { width: 36px; height: 36px; }
.installer-art svg, .release-art svg { display: block; width: 100%; height: 100%; }
.release-list { display: flex; flex-direction: column; gap: 10px; }
@@ -772,9 +797,10 @@ h1, h2, h3, p { margin: 0; }
.log-resize-handle[data-dragging="true"] .log-resize-pill {
width: 48px; background: var(--border-strong);
}
.logbar { height: var(--logbar-h); display: flex; align-items: center; gap: var(--sp-2); padding: 0 var(--sp-3) 0 var(--sp-4); }
.logbar { height: var(--logbar-h); display: flex; align-items: center; gap: var(--sp-2); padding-inline: var(--sp-4) var(--sp-3); overflow-x: auto; scrollbar-width: none; }
.logbar::-webkit-scrollbar { display: none; }
.status-telemetry {
display: inline-flex; align-items: center; min-width: 0; margin-left: -8px;
display: inline-flex; align-items: center; min-width: 0; flex-shrink: 1; overflow: hidden; margin-inline-start: -8px;
font-size: var(--fs-12); color: var(--text-2); user-select: none;
font-variant-numeric: tabular-nums;
}
@@ -815,10 +841,15 @@ button.status-issue + .status-metric { margin-left: 6px; }
background: var(--accent); transform-origin: left center;
transition: transform 260ms var(--ease-out), background var(--dur) var(--ease-out);
}
:root[dir="rtl"] .status-mini-fill,
:root[dir="rtl"] .progress-fill,
:root[dir="rtl"] .meter-fill {
transform-origin: right center;
}
.status-mini-fill.warn { background: var(--status-busy); }
.status-mini-fill.high { background: var(--status-error); }
.log-toggle-btn {
height: 24px; padding: 0 8px;
height: 24px; padding: 0 8px; white-space: nowrap; flex-shrink: 0;
display: inline-flex; align-items: center; gap: 4px;
border: none; border-radius: var(--r-sm); background: transparent;
color: var(--text-2); font-size: var(--fs-12); font-weight: var(--fw-medium);
@@ -827,9 +858,9 @@ button.status-issue + .status-metric { margin-left: 6px; }
}
.log-toggle-btn:hover { background: var(--surface-hover); color: var(--text); }
.log-toggle-btn:active { transform: scale(0.97); }
.tabs { display: flex; gap: 2px; }
.tabs { display: flex; gap: 2px; flex-shrink: 0; }
.tab {
height: 24px; padding: 0 var(--sp-2); border: none; border-radius: var(--r-sm);
height: 24px; padding: 0 var(--sp-2); border: none; border-radius: var(--r-sm); white-space: nowrap;
background: transparent; color: var(--text-3); font-size: var(--fs-12); cursor: pointer;
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
}
@@ -854,9 +885,9 @@ button.status-issue + .status-metric { margin-left: 6px; }
.log-line { display: flex; gap: var(--sp-3); }
.log-ts { color: var(--text-3); flex-shrink: 0; font-variant-numeric: tabular-nums; }
.log-src { color: var(--accent-soft-text); flex-shrink: 0; }
.log-line.warn .log-msg { color: var(--status-busy); }
.log-line.error .log-msg { color: var(--status-error); }
.jump-latest { position: absolute; right: var(--sp-4); bottom: var(--sp-3); }
.log-line.warn .log-msg { color: var(--warn-text); }
.log-line.error .log-msg { color: var(--danger-text); }
.jump-latest { position: absolute; inset-inline-end: var(--sp-4); bottom: var(--sp-3); }
/* ── Overlays: dialog, menu, tooltip, toast ────────────── */
.overlay { position: fixed; inset: 0; background: var(--scrim); backdrop-filter: blur(5px); z-index: 40; }
@@ -908,9 +939,9 @@ button.status-issue + .status-metric { margin-left: 6px; }
}
.tooltip kbd { font-family: var(--font-sans); color: var(--text-3); }
.toast-viewport { position: fixed; right: var(--sp-4); bottom: calc(var(--logbar-h) + var(--sp-4)); z-index: 70; display: flex; flex-direction: column; gap: var(--sp-2); width: 348px; max-width: calc(100vw - 32px); margin: 0; padding: 0; list-style: none; outline: none; }
.toast-viewport { position: fixed; inset-inline-end: var(--sp-4); bottom: calc(var(--logbar-h) + var(--sp-4)); z-index: 70; display: flex; flex-direction: column; gap: var(--sp-2); width: 380px; max-width: calc(100vw - 32px); margin: 0; padding: 0; list-style: none; outline: none; }
.toast {
display: flex; align-items: flex-start; gap: var(--sp-3); padding: var(--sp-3);
display: flex; flex-direction: column; gap: var(--sp-2); padding: var(--sp-3);
background: var(--surface-2); backdrop-filter: var(--blur-overlay);
border: 1px solid var(--border); border-radius: var(--r-lg);
box-shadow: var(--shadow-overlay), var(--highlight-top);
@@ -920,12 +951,37 @@ button.status-issue + .status-metric { margin-left: 6px; }
.toast[data-swipe="move"] { transform: translateX(var(--radix-toast-swipe-move-x)); transition: none; }
.toast[data-swipe="cancel"] { transform: translateX(0); transition: transform var(--dur) var(--ease-out); }
.toast[data-swipe="end"] { animation: toast-swipe-out var(--dur-fast) var(--ease-out) both; }
.toast > svg { margin-top: 2px; flex-shrink: 0; }
.toast.ok > svg { color: var(--status-running); }
.toast.error > svg { color: var(--status-error); }
.toast-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
:root[dir="rtl"] .toast[data-swipe="end"] { animation: toast-swipe-out-rtl var(--dur-fast) var(--ease-out) both; }
.toast-main-row { display: flex; align-items: flex-start; gap: var(--sp-3); width: 100%; min-width: 0; }
.toast-main-row > svg { margin-top: 2px; flex-shrink: 0; }
.toast.ok .toast-main-row > svg { color: var(--status-running); }
.toast.error .toast-main-row > svg { color: var(--status-error); }
.toast-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.toast-title-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.toast-title { font-size: var(--fs-13); font-weight: var(--fw-strong); }
.toast-desc { font-size: var(--fs-12); color: var(--text-2); overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
.toast-code {
font-family: var(--font-mono); font-size: var(--fs-11); padding: 1px 5px;
border-radius: 4px; background: var(--surface-active); color: var(--text-3);
}
.toast-desc { font-size: var(--fs-12); color: var(--text-2); overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden; }
.toast-footer { display: flex; flex-direction: column; gap: var(--sp-2); padding-inline-start: 28px; width: 100%; min-width: 0; }
.toast-details { font-size: var(--fs-12); color: var(--text-3); width: 100%; min-width: 0; }
.toast-details summary { cursor: pointer; user-select: none; font-weight: var(--fw-medium); }
.toast-details summary:hover { color: var(--text-2); }
.toast-details-body {
margin-top: 4px; padding: 6px 8px; border-radius: var(--r-sm);
background: var(--surface-1); border: 1px solid var(--border);
font-family: var(--font-mono); font-size: var(--fs-11); color: var(--text-code);
max-height: 120px; overflow: auto; white-space: pre-wrap; word-break: break-word;
}
.toast-copy-btn {
display: inline-flex; align-items: center; gap: 4px;
margin-top: 5px; padding: 0 8px; height: 24px; font-size: var(--fs-11);
border-radius: var(--r-sm); border: 1px solid var(--border-strong);
background: var(--surface-card-elevated); color: var(--text-2); cursor: pointer;
}
.toast-copy-btn:hover { background: var(--surface-hover); color: var(--text); }
.toast-action-btn { align-self: flex-end; }
.toast .btn { height: 26px; }
/* ── Forms (wizard, settings) ──────────────────────────── */
@@ -1013,10 +1069,10 @@ button.status-issue + .status-metric { margin-left: 6px; }
/* ── VM settings (ui/settings.tsx) ─────────────────────── */
.dialog.settings-dialog { width: 900px; }
.settings-split { display: flex; height: min(600px, calc(100vh - 210px)); min-height: 0; }
.settings-split { display: flex; flex: 1; min-height: 0; max-height: min(600px, calc(100vh - 180px)); }
.settings-nav {
width: 204px; flex-shrink: 0; padding: 10px 8px;
border-right: 1px solid var(--border); background: var(--surface-sidebar);
border-inline-end: 1px solid var(--border); background: var(--surface-sidebar);
display: flex; flex-direction: column; gap: 3px; overflow-y: auto; overscroll-behavior: contain;
}
.settings-pane {
@@ -1037,9 +1093,11 @@ button.status-issue + .status-metric { margin-left: 6px; }
background: var(--accent-soft); color: var(--accent-soft-text);
font-size: 11px; font-weight: var(--fw-strong); font-variant-numeric: tabular-nums;
}
.nav-item[aria-selected="true"] .nav-count { background: rgba(255, 255, 255, 0.25); color: var(--accent-text); }
.nav-item[aria-selected="true"] .nav-count,
.nav-item[aria-current="page"] .nav-count { background: rgba(255, 255, 255, 0.25); color: var(--accent-text); }
.nav-issue { color: var(--status-error); flex-shrink: 0; }
.nav-item[aria-selected="true"] .nav-issue { color: var(--accent-text); }
.nav-item[aria-selected="true"] .nav-issue,
.nav-item[aria-current="page"] .nav-issue { color: var(--accent-text); }
.sgroup { display: flex; flex-direction: column; gap: var(--sp-2); }
.sgroup-title { margin: 0 0 0 4px; font-size: var(--fs-12); font-weight: var(--fw-strong); color: var(--text-3); }
@@ -1065,16 +1123,19 @@ button.status-issue + .status-metric { margin-left: 6px; }
.dirty-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); flex-shrink: 0; }
.warn-text { color: var(--warn-text); }
.inline-code { font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); background: var(--surface-active); padding: 2px 7px; border-radius: 5px; user-select: text; }
.stack-1 { display: flex; flex-direction: column; gap: var(--sp-1); }
.stack-2 { display: flex; flex-direction: column; align-items: flex-start; gap: var(--sp-2); }
.stack-2 > .input { max-width: 320px; }
.stack-3 { display: flex; flex-direction: column; gap: var(--sp-3); }
.res-input { margin-top: var(--sp-2); max-width: 220px; }
.foot-status { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-13); color: var(--text-2); }
.foot-status .link-btn { font-size: var(--fs-13); margin-left: var(--sp-1); }
.foot-status .link-btn { font-size: var(--fs-13); margin-inline-start: var(--sp-1); }
.foot-status .link-btn:disabled { opacity: 0.5; cursor: default; text-decoration: none; }
/* Segmented control with a sliding highlight */
.seg { position: relative; display: inline-flex; padding: 2px; gap: 2px; border-radius: var(--r-md); background: var(--surface-active); isolation: isolate; }
.seg { position: relative; display: inline-flex; max-width: 100%; overflow-x: auto; scrollbar-width: none; padding: 2px; gap: 2px; border-radius: var(--r-md); background: var(--surface-active); isolation: isolate; }
.seg::-webkit-scrollbar { display: none; }
.seg-wide { display: flex; }
.seg-wide button { flex: 1; }
.seg-thumb {
@@ -1165,10 +1226,10 @@ button.status-issue + .status-metric { margin-left: 6px; }
/* Pop-up button (replaces native <select>) */
.popup-btn {
display: inline-flex; align-items: center; justify-content: space-between; gap: 10px;
height: 29px; min-width: 140px; max-width: 100%; padding: 0 8px 0 10px;
height: 29px; min-width: 140px; max-width: 100%; padding-inline: 10px 8px;
border-radius: var(--r-sm); border: 1px solid var(--border-strong);
background: var(--seg-thumb); color: var(--text); box-shadow: var(--shadow-btn);
font: inherit; font-size: var(--fs-13); text-align: left; cursor: pointer;
font: inherit; font-size: var(--fs-13); text-align: start; cursor: pointer;
transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
}
.popup-btn:hover { border-color: var(--text-3); }
@@ -1179,9 +1240,9 @@ button.status-issue + .status-metric { margin-left: 6px; }
.popup-value { min-width: 0; display: inline-flex; align-items: baseline; gap: 6px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.popup-chevron { flex-shrink: 0; color: var(--text-3); }
.popup-detail { font-size: var(--fs-12); color: var(--text-3); white-space: nowrap; }
.popup-menu { min-width: var(--radix-dropdown-menu-trigger-width); max-height: min(360px, var(--radix-dropdown-menu-content-available-height)); overflow-y: auto; overscroll-behavior: contain; }
.popup-item { position: relative; padding-left: 28px; padding-right: 14px; gap: 8px; }
.popup-check { position: absolute; left: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; }
.popup-menu { min-width: var(--radix-dropdown-menu-trigger-width); max-width: calc(100vw - 16px); max-height: min(360px, var(--radix-dropdown-menu-content-available-height)); overflow-y: auto; overscroll-behavior: contain; }
.popup-item { position: relative; padding-inline: 28px 14px; gap: 8px; }
.popup-check { position: absolute; inset-inline-start: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; }
.popup-item-label { white-space: nowrap; }
.popup-item[data-highlighted] .popup-detail { color: rgba(255, 255, 255, 0.78); }
@@ -1245,6 +1306,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
@keyframes toast-in { from { opacity: 0; transform: translateY(10px) scale(0.97); } to { opacity: 1; transform: translateY(0) scale(1); } }
@keyframes toast-out { from { opacity: 1; transform: scale(1); } to { opacity: 0; transform: scale(0.96); } }
@keyframes toast-swipe-out { from { transform: translateX(var(--radix-toast-swipe-end-x)); opacity: 1; } to { transform: translateX(calc(100% + 24px)); opacity: 0; } }
@keyframes toast-swipe-out-rtl { from { transform: translateX(var(--radix-toast-swipe-end-x)); opacity: 1; } to { transform: translateX(calc(-100% - 24px)); opacity: 0; } }
.page { animation: rise-in var(--dur) var(--ease-out) both; }
.overlay { animation: fade-in var(--dur) var(--ease-out) both; }
@@ -1295,12 +1357,14 @@ button.status-issue + .status-metric { margin-left: 6px; }
transition: opacity var(--dur) var(--ease-out), transform var(--dur) var(--ease-out);
}
.vm-screen-chip {
position: absolute; left: 50%; bottom: 10px; z-index: 2; margin-left: -60px; width: 120px;
position: absolute; left: 50%; bottom: 10px; z-index: 2;
width: max-content; max-width: calc(100% - 20px); padding: 0 12px;
display: inline-flex; align-items: center; justify-content: center; gap: 5px;
height: 26px; border-radius: 999px; pointer-events: none;
background: rgba(20, 21, 26, 0.72); color: #fff; backdrop-filter: blur(10px);
font-size: var(--fs-12); font-weight: var(--fw-medium);
opacity: 0; transform: translateY(4px);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
opacity: 0; transform: translateX(-50%) translateY(4px);
transition: opacity var(--dur) var(--ease-out), transform var(--dur) var(--ease-out);
}
@@ -1333,8 +1397,8 @@ button.status-issue + .status-metric { margin-left: 6px; }
.source-title { display: flex; align-items: center; gap: 6px; font-size: 14px; font-weight: var(--fw-strong); color: var(--text); }
.source-title .badge { height: 18px; padding: 0 7px; font-size: 11px; }
.source-sub { font-size: var(--fs-12); color: var(--text-3); }
.path-text { display: block; max-width: 420px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-12); }
.name-input { width: 260px; }
.path-text { display: block; max-width: min(420px, 100%); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-12); }
.name-input { width: 260px; max-width: 100%; }
/* The assistant keeps one size across steps, like macOS setup assistants. */
.dialog.wizard-dialog { width: 760px; height: min(660px, calc(100vh - 80px)); }
@@ -1352,7 +1416,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out);
}
.affinity-chip:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); }
.affinity-chip.is-active { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
.affinity-chip.is-active { border-color: var(--accent); background: var(--accent-soft); color: var(--accent-soft-text); }
.affinity-chip:disabled { opacity: 0.45; cursor: not-allowed; }
.affinity-grid {
display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px;
@@ -1361,7 +1425,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
.affinity-cpu {
display: flex; align-items: center; gap: 7px; padding: 7px 9px;
border-radius: var(--r-md); border: 1px solid var(--border-strong);
background: var(--surface-1); color: var(--text-2); cursor: pointer; text-align: left;
background: var(--surface-1); color: var(--text-2); cursor: pointer; text-align: start;
transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
}
.affinity-cpu:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); }
@@ -1375,21 +1439,21 @@ button.status-issue + .status-metric { margin-left: 6px; }
}
.affinity-cpu.is-checked .affinity-check { border-color: var(--accent); background: var(--accent); }
.affinity-cpu-name { font-size: var(--fs-12); font-weight: var(--fw-medium); white-space: nowrap; }
.affinity-cpu-meta { margin-left: auto; display: inline-flex; align-items: center; gap: 4px; }
.affinity-cpu-meta { margin-inline-start: auto; display: inline-flex; align-items: center; gap: 4px; }
.affinity-core-tag { font-size: 10px; color: var(--text-3); }
.affinity-tier {
font-size: 10px; font-weight: var(--fw-strong); line-height: 1; padding: 2px 5px; border-radius: 999px;
}
.affinity-tier.tier-p { background: rgba(0, 122, 255, 0.14); color: var(--accent); }
.affinity-tier.tier-e { background: rgba(52, 199, 89, 0.15); color: var(--status-running); }
.affinity-tier.tier-lpe { background: rgba(255, 159, 10, 0.16); color: var(--status-busy); }
.affinity-tier.tier-p { background: var(--accent-soft); color: var(--accent-soft-text); }
.affinity-tier.tier-e { background: var(--ok-soft); color: var(--ok-text); }
.affinity-tier.tier-lpe { background: var(--warn-soft); color: var(--warn-text); }
.affinity-summary {
display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px;
padding: 8px 10px; border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border);
font-size: var(--fs-12); color: var(--text-2);
}
.affinity-summary > span { display: inline-flex; align-items: center; gap: 5px; }
.affinity-live { color: var(--status-running); }
.affinity-live { color: var(--ok-text); }
.affinity-eco-row {
display: flex; align-items: center; justify-content: space-between; gap: 12px;
padding: 10px 12px; border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border);
@@ -1433,7 +1497,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
.vm-name-btn > span { overflow-wrap: anywhere; }
.vm-name-btn:hover { background: var(--surface-hover); }
.vm-name-pencil {
position: absolute; left: 100%; top: 50%; margin-left: 6px; transform: translateY(-50%);
position: absolute; inset-inline-start: 100%; top: 50%; margin-inline-start: 6px; transform: translateY(-50%);
color: var(--text-3); opacity: 0; transition: opacity var(--dur-fast) var(--ease-out);
}
.vm-name-btn:hover .vm-name-pencil, .vm-name-btn:focus-visible .vm-name-pencil { opacity: 1; }
@@ -1460,8 +1524,8 @@ button.status-issue + .status-metric { margin-left: 6px; }
/* One line per fact: icon · label · value · short usage bar at the end.
Every row has the same height, and a bar appearing or hiding when the VM
starts or stops doesn't move anything. */
.vm-spec-cell { grid-template-columns: auto 4.5em minmax(0, 1fr) 56px; column-gap: 10px; min-height: 22px; }
.vm-spec-label { display: block; font-size: var(--fs-13); color: var(--text-3); white-space: nowrap; }
.vm-spec-cell { grid-template-columns: auto minmax(4.5em, max-content) minmax(0, 1fr) 56px; column-gap: 10px; min-height: 22px; }
.vm-spec-label { display: block; max-width: 9.5em; overflow: hidden; text-overflow: ellipsis; font-size: var(--fs-13); color: var(--text-3); white-space: nowrap; }
.vm-spec-meter { grid-column: 4; grid-row: 1; align-self: center; }
/* Rows without a bar (graphics, network, language) give its column to the value. */
.vm-spec-cell:not(:has(.vm-spec-meter)) .vm-spec-val { grid-column: 3 / 5; }
@@ -1480,7 +1544,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
/* Interactive install stepper */
.guide-step-btn {
width: 22px; height: 22px; padding: 0; border-radius: 50%; flex-shrink: 0; margin-top: 1px;
width: 24px; height: 24px; padding: 0; border-radius: 50%; flex-shrink: 0; margin-top: 1px;
display: grid; place-items: center; border: none; cursor: pointer;
background: var(--accent-soft); color: var(--accent-soft-text);
font-size: var(--fs-11); font-weight: var(--fw-strong); font-variant-numeric: tabular-nums;
@@ -1501,15 +1565,15 @@ button.status-issue + .status-metric { margin-left: 6px; }
/* Log filter controls */
.log-filter-input {
width: 148px; height: 22px; padding: 0 8px;
width: 148px; height: 24px; padding: 0 8px; flex-shrink: 0;
border-radius: var(--r-sm); border: 1px solid var(--border-strong);
background: var(--surface-input); color: var(--text); font: inherit; font-size: var(--fs-12);
}
.log-filter-input:focus { border-color: var(--accent); box-shadow: var(--focus-ring); }
.log-filter-pill {
height: 22px; padding: 0 8px; border-radius: var(--r-sm);
height: 24px; padding: 0 8px; border-radius: var(--r-sm); white-space: nowrap; flex-shrink: 0;
border: 1px solid var(--border); background: transparent;
color: var(--text-3); font-size: 11.5px; cursor: pointer;
color: var(--text-3); font-size: var(--fs-12); cursor: pointer;
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out);
}
.log-filter-pill:hover { color: var(--text); background: var(--surface-hover); }
@@ -1626,6 +1690,16 @@ button.status-issue + .status-metric { margin-left: 6px; }
.plugin-trust.is-dev { color: var(--accent-soft-text); }
.plugin-trust.is-community { color: var(--text-2); }
.plugins-empty { padding: 24px 4px; text-align: center; color: var(--text-3); font-size: var(--fs-13); }
.plugins-tabs { display: flex; align-items: center; gap: 6px; margin-bottom: var(--sp-3); }
.plugins-market-toolbar { display: flex; flex-direction: column; gap: 8px; margin-bottom: var(--sp-3); }
.plugins-market-search-wrap { width: 100%; }
.plugins-market-search { width: 100%; padding-left: 30px; }
.plugins-market-kinds { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.plugins-market-meta { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
.plugin-scan-section { display: flex; flex-direction: column; gap: 6px; }
.plugin-scan-section-title { font-size: var(--fs-12); font-weight: var(--fw-semibold); color: var(--text-2); }
.plugin-scan-section-title.is-danger { color: var(--danger-text); }
.plugin-scan-examples { margin-top: 4px; font-size: var(--fs-11); color: var(--text-2); display: flex; flex-direction: column; gap: 2px; }
/* Visual theme hero card with live miniature window preview */
.theme-hero-card {
@@ -1670,6 +1744,74 @@ button.status-issue + .status-metric { margin-left: 6px; }
.theme-scheme-strip { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.theme-scheme-chips { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
/* ErrorBoundary recovery surface (tokens-backed for both Light and Dark themes) */
.error-boundary {
display: flex; align-items: center; justify-content: center;
height: 100%; padding: var(--sp-6);
background: var(--surface-canvas); color: var(--text); font-family: var(--font-sans);
}
.error-boundary-card {
max-width: 560px; width: 100%; padding: var(--sp-5);
border-radius: var(--r-xl); border: 1px solid var(--border);
background: var(--surface-1); box-shadow: var(--shadow-card);
display: flex; flex-direction: column; gap: var(--sp-3);
}
.error-boundary-title { margin: 0; font-size: var(--fs-16); font-weight: var(--fw-strong); }
.error-boundary-pre {
margin: 0; padding: 10px 12px; border-radius: var(--r-md);
font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code);
max-height: 180px; overflow: auto;
background: var(--surface-0); border: 1px solid var(--border);
white-space: pre-wrap; word-break: break-word;
}
.error-boundary-actions { display: flex; gap: var(--sp-2); justify-content: flex-end; }
/* Responsive / narrow-window / high-DPI & mobile drawer adaptations */
@media (max-width: 1040px) {
.logs:has(.logs-body-wrap) .status-telemetry .status-metric:not(.status-issue) {
display: none;
}
}
@media (max-width: 768px) {
.sidebar-backdrop {
display: block; position: absolute;
inset: 0;
background: var(--scrim); backdrop-filter: blur(3px); z-index: 31;
}
.sidebar-wrap {
position: absolute; z-index: 32;
inset-block: 0; inset-inline-start: 0;
box-shadow: var(--shadow-overlay);
}
.workspace.sidebar-hidden .sidebar-wrap { pointer-events: none; }
.scroll { padding: 14px 16px 20px; }
.dialog { max-width: calc(100vw - 16px); max-height: calc(100vh - 32px); }
.dialog.wizard-dialog { height: min(660px, calc(100vh - 32px)); }
.settings-split { flex-direction: column; max-height: none; }
.settings-nav {
width: 100%; flex-direction: row; overflow-x: auto; overflow-y: hidden;
border-inline-end: none; border-bottom: 1px solid var(--border);
padding: 8px 12px; scrollbar-width: none;
}
.settings-nav::-webkit-scrollbar { display: none; }
.settings-nav .nav-item { width: auto; flex-shrink: 0; }
.settings-pane { padding: 16px; }
}
@media (max-width: 640px) {
.source-cards, .field-row, .review-groups { grid-template-columns: 1fr; }
.review-group:last-child .review-rows { grid-template-columns: max-content 1fr; }
.vm-spec-card { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 12px 14px; }
.affinity-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.conn-row, .srow-head, .row, .page-head { flex-wrap: wrap; }
.conn-ctrl { flex-wrap: wrap; max-width: 100%; }
.plugins-search { width: 100%; }
}
@container (max-width: 560px) {
.review-group:last-child .review-rows { grid-template-columns: max-content 1fr; }
}
}
/* Host usability invariants locked with !important in earliest layer so themes
+44 -7
View File
@@ -8,11 +8,12 @@
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* Map installed PingFang SC / HarmonyOS Sans SC / MiSans / Noto Sans SC / Source Han Sans CN
explicitly across weights. On Windows DirectWrite, PingFang SC Regular renders overly thin
compared to macOS Retina CoreText, so body weights (400–550) map to Medium for balanced ink. */
/* Scoped Simplified Chinese weight-mapping face ("ReimsCJK-SC").
IMPORTANT: Never attach this unconditionally to all languages — doing so
hijacks Han Unification `locl` glyphs and turns Traditional Chinese / Japanese
Kanji into Mainland Simplified forms. Only `:lang(zh-CN|zh-SG|zh-Hans)` activates it. */
@font-face {
font-family: "ReimsCJK";
font-family: "ReimsCJK-SC";
font-style: normal;
font-weight: 400 550;
src:
@@ -26,7 +27,7 @@
unicode-range: U+2E80-9FFF, U+3000-303F, U+FF00-FFEF, U+F900-FAFF;
}
@font-face {
font-family: "ReimsCJK";
font-family: "ReimsCJK-SC";
font-style: normal;
font-weight: 560 900;
src:
@@ -44,9 +45,13 @@
:root {
color-scheme: light;
/* Typography */
--font-sans: "ReimsSans", "ReimsCJK", "PingFang SC Medium", "PingFang SC", "HarmonyOS Sans SC", "MiSans", "Noto Sans SC", "Source Han Sans CN", -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", system-ui, sans-serif;
/* Typography — regional CJK family injected via --font-cjk per :lang() */
--font-locale-pack: ;
--font-cjk: "PingFang SC", "Microsoft YaHei UI", "Noto Sans CJK SC", sans-serif;
--font-sans: "ReimsSans", var(--font-locale-pack) -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI Variable Text", "Segoe UI", var(--font-cjk), system-ui, sans-serif;
--font-mono: "SF Mono", "JetBrains Mono", "Cascadia Mono", Consolas, monospace;
--body-lh: 1.48;
--heading-tracking: -0.015em;
--fs-11: 11px;
--fs-12: 12px;
--fs-13: 13px;
@@ -245,4 +250,36 @@
--text-3: #a6a6b0;
}
}
/* Regional script & OpenType `locl` typography stacks:
- Simplified Chinese: DirectWrite Medium ink compensation ("ReimsCJK-SC")
- Traditional Chinese (TW/HK/MO): Orthodox Traditional glyph stack, 400 regular weight
and taller line-height (1.56) so dense 20+ stroke characters never blob at 11–13px
- Japanese: Kana/Kanji stack, 400 regular weight, strict kinsoku line-breaking
- Korean: Hangul stack, 400 regular weight, `word-break: keep-all` syllable-word integrity */
:root:lang(zh-CN), :root:lang(zh-SG), :root:lang(zh-Hans) {
--font-cjk: "ReimsCJK-SC", "PingFang SC Medium", "PingFang SC", "HarmonyOS Sans SC", "MiSans", "Noto Sans SC", "Source Han Sans CN", "Microsoft YaHei UI", sans-serif;
--heading-tracking: 0em;
}
:root:lang(zh-TW), :root:lang(zh-HK), :root:lang(zh-MO), :root:lang(zh-Hant) {
--font-cjk: "PingFang TC", "Noto Sans TC", "Source Han Sans TC", "Microsoft JhengHei UI", "Microsoft JhengHei", sans-serif;
--fw-regular: 400;
--body-lh: 1.56;
--heading-tracking: 0em;
}
:root:lang(ja) {
--font-cjk: "Hiragino Sans", "Noto Sans JP", "BIZ UDPGothic", "Yu Gothic UI", "Meiryo UI", "Meiryo", sans-serif;
--fw-regular: 400;
--body-lh: 1.58;
--heading-tracking: 0em;
}
:root:lang(ko) {
--font-cjk: "Apple SD Gothic Neo", "Malgun Gothic", "Noto Sans KR", sans-serif;
--fw-regular: 400;
--body-lh: 1.54;
--heading-tracking: 0em;
}
}
+3 -1
View File
@@ -27,6 +27,7 @@ export type UIContractPart = (typeof UI_CONTRACT_PARTS)[number]
export const UI_CONTRACT_STATE_ATTRS = [
'data-theme',
'data-motion',
'data-locale',
'data-view',
'data-vm-state',
'data-busy',
@@ -51,7 +52,8 @@ export const UI_CONTRACT_SLOTS = [
export type UIContractSlot = (typeof UI_CONTRACT_SLOTS)[number]
export const UI_CONTRACT_TOKENS = [
'--font-sans', '--font-mono',
'--font-sans', '--font-cjk', '--font-mono',
'--body-lh', '--heading-tracking',
'--fs-11', '--fs-12', '--fs-13', '--fs-14', '--fs-15', '--fs-16', '--fs-20', '--fs-24',
'--fw-regular', '--fw-medium', '--fw-strong',
'--sp-1', '--sp-2', '--sp-3', '--sp-4', '--sp-5', '--sp-6', '--sp-8',
+31 -7
View File
@@ -9,12 +9,9 @@ type Model<T> = Omit<T, 'convertValues'>
export type BuiltinLocale = 'zh-CN' | 'en-US'
export type Locale = BuiltinLocale | (string & {})
export type RuntimeSource = 'auto' | 'github' | 'gitcode'
export type Config = Model<config.Config> & {
locale: Locale
runtime_channel?: 'stable' | 'alpha' | ''
runtime_source?: RuntimeSource | ''
}
export type DisplayInfo = host.DisplayInfo
@@ -23,8 +20,11 @@ export type AudioInfo = host.AudioInfo
export type WHPXCapabilities = host.WHPXCapabilities
export type LogicalCPUInfo = host.LogicalCPUInfo
export type GPUInfo = Model<host.GPUInfo> & {
export type GPUCompat = 'supported' | 'warn' | 'unsupported' | 'unknown'
export type GPUInfo = Omit<Model<host.GPUInfo>, 'compat'> & {
kind: 'discrete' | 'integrated' | 'virtual' | 'unknown'
compat?: GPUCompat
}
export type OptimizationStatus = 'recommended' | 'available' | 'experimental' | 'auto' | 'unavailable'
@@ -45,7 +45,6 @@ export type InstalledRuntime = Model<runtime.Installed>
export type RemoteRuntime = Model<runtime.Remote> & {
channel: 'stable' | 'alpha'
source?: 'github' | 'gitcode'
}
export type VMListItem = Model<reims.VMListItem> & {
@@ -100,9 +99,14 @@ export type CreateOpts = Model<reims.CreateOpts> & {
export type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
export type InstallerKind = 'offline' | 'online'
export type InstallerPhase = 'queued' | 'downloading'
/** A tracked long-running job pushed as "reims:task" (internal/app/tasks.go). */
export type Task = Model<app.Task> & {
kind: 'installer-download' | 'vm-create' | string
kind: 'installer-download' | 'recovery-download' | 'vm-create' | 'runtime-install' | 'app-update' | string
installer_kind?: InstallerKind | ''
installer_phase?: InstallerPhase | ''
status: TaskStatus
}
@@ -123,6 +127,14 @@ export type SettingProperty = plugin.SettingProperty
export type SettingsSchema = plugin.SettingsSchema
export type PluginInfo = plugin.PluginInfo
export type DoctorFinding = plugin.DoctorFinding
export type ScanFinding = plugin.ScanFinding
export type ExecutableFile = plugin.ExecutableFile
export type CapabilityItem = plugin.CapabilityItem
export type ScanReport = plugin.ScanReport
export type MarketEntry = plugin.MarketEntry
export type MarketWithdrawal = plugin.MarketWithdrawal
export type MarketCatalogItem = plugin.MarketCatalogItem
export type MarketBrowseResult = plugin.MarketBrowseResult
export type TokenDeriveRule = plugin.TokenDeriveRule
export type ThemeScheme = plugin.ThemeScheme
export type ThemeDecoration = plugin.ThemeDecoration
@@ -130,7 +142,19 @@ export type ThemeDecorationState = plugin.ThemeDecorationState
export type ThemeContribution = plugin.ThemeContribution
export type CustomThemeScheme = plugin.CustomThemeScheme
export type ActiveThemePayload = plugin.ActiveThemePayload
export type ResolvedLocalePack = plugin.ResolvedLocalePack
export interface ResolvedLocaleFont {
family: string
url: string
weight?: string
style?: string
unicodeRange?: string
}
export type ResolvedLocalePack = Model<plugin.ResolvedLocalePack> & {
has_ui_messages?: boolean
plugin_messages?: Record<string, Record<string, string>>
fonts?: ResolvedLocaleFont[]
}
export type MenuContribution = plugin.MenuContribution
export type VMCardContribution = plugin.VMCardContribution
export type PanelContribution = plugin.PanelContribution
+1
View File
@@ -85,6 +85,7 @@ export type StatusKind = 'running' | 'stopped' | 'busy' | 'broken' | 'warn'
export function statusKind(state: string): StatusKind {
if (state === 'running') return 'running'
if (state === 'starting' || state === 'stopping' || state === 'creating') return 'busy'
if (state === 'driver_unavailable') return 'warn'
if (state === 'broken') return 'broken'
return 'stopped'
}
+4 -2
View File
@@ -146,7 +146,9 @@ export function Segmented<V extends string | number>({ options, value, onChange,
e.preventDefault()
const enabled = options.filter((o) => !o.disabled)
const i = enabled.findIndex((o) => o.value === value)
const next = enabled[(i + (e.key === 'ArrowRight' ? 1 : -1) + enabled.length) % enabled.length]
const isRTL = box.current ? getComputedStyle(box.current).direction === 'rtl' : false
const delta = (e.key === 'ArrowRight') !== isRTL ? 1 : -1
const next = enabled[(i + delta + enabled.length) % enabled.length]
if (next) {
onChange(next.value)
requestAnimationFrame(() => box.current?.querySelector<HTMLElement>('[aria-checked="true"]')?.focus())
@@ -277,7 +279,7 @@ export const RangeField: React.FC<RangeProps> = ({ value, min, max, step = 1, un
return (
<div className="range-field" data-warn={over || undefined}>
<div className="range-main">
<div className="range-rail-wrap">
<div className="range-rail-wrap" dir="ltr">
<div className="range-rail" aria-hidden="true">
<div className="range-track" />
{recommend && (
+97 -19
View File
@@ -1,5 +1,5 @@
import * as RToast from '@radix-ui/react-toast'
import { CircleCheck, CircleX, X } from 'lucide-react'
import { Check, CircleCheck, CircleX, X } from 'lucide-react'
import React, { useCallback, useState } from 'react'
import { IconButton } from './controls'
@@ -7,6 +7,10 @@ export interface ToastInput {
kind: 'ok' | 'error'
title: string
description?: string
errorCode?: string
rawDetail?: string
detailsLabel?: string
copyDetailsLabel?: string
action?: { label: string; onClick: () => void }
}
@@ -25,35 +29,109 @@ export function useToasts() {
return { items, push, remove }
}
interface ToasterProps {
items: ToastItem[]
interface ToastCardProps {
item: ToastItem
onRemove: (id: number) => void
closeLabel: string
}
export const Toaster: React.FC<ToasterProps> = ({ items, onRemove, closeLabel }) => (
<RToast.Provider swipeDirection="right">
{items.map((item) => (
<RToast.Root
key={item.id}
className={`toast ${item.kind}`}
duration={item.kind === 'error' ? 8000 : 3000}
onOpenChange={(open) => { if (!open) onRemove(item.id) }}
>
{item.kind === 'ok' ? <CircleCheck size={16} /> : <CircleX size={16} />}
const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) => {
const [expanded, setExpanded] = useState(false)
const [copied, setCopied] = useState(false)
const copyDiagnostic = () => {
const full = [
item.errorCode ? `[${item.errorCode}] ${item.title}` : item.title,
item.description,
item.rawDetail,
]
.filter(Boolean)
.join('\n')
navigator.clipboard
?.writeText(full)
.then(() => {
setCopied(true)
window.setTimeout(() => setCopied(false), 1500)
})
.catch(() => {})
}
return (
<RToast.Root
className={`toast ${item.kind}${item.rawDetail || item.action ? ' has-extra' : ''}`}
duration={expanded ? 600_000 : item.kind === 'error' ? 10_000 : item.action ? 8000 : 3000}
onOpenChange={(open) => {
if (!open) onRemove(item.id)
}}
>
<div className="toast-main-row">
{item.kind === 'ok' ? (
<CircleCheck size={16} aria-hidden="true" />
) : (
<CircleX size={16} aria-hidden="true" />
)}
<div className="toast-text">
<RToast.Title className="toast-title">{item.title}</RToast.Title>
{item.description && <RToast.Description className="toast-desc">{item.description}</RToast.Description>}
<div className="toast-title-row">
<RToast.Title className="toast-title">{item.title}</RToast.Title>
{item.errorCode && <span className="toast-code selectable">{item.errorCode}</span>}
</div>
{item.description && (
<RToast.Description className="toast-desc">{item.description}</RToast.Description>
)}
</div>
{item.action && (
{item.action && !item.rawDetail && (
<RToast.Action asChild altText={item.action.label}>
<button type="button" className="btn" onClick={item.action.onClick}>{item.action.label}</button>
<button type="button" className="btn" onClick={item.action.onClick}>
{item.action.label}
</button>
</RToast.Action>
)}
<RToast.Close asChild>
<IconButton small label={closeLabel} icon={<X size={14} />} tipSide="top" />
<IconButton small label={closeLabel} icon={<X size={14} aria-hidden="true" />} tipSide="top" />
</RToast.Close>
</RToast.Root>
</div>
{(item.rawDetail || (item.action && item.rawDetail)) && (
<div className="toast-footer">
{item.rawDetail && (
<details
className="toast-details"
onClick={(e) => e.stopPropagation()}
onToggle={(e) => setExpanded(e.currentTarget.open)}
>
<summary>{item.detailsLabel}</summary>
<div className="toast-details-body selectable">{item.rawDetail}</div>
{item.copyDetailsLabel && (
<button type="button" className="toast-copy-btn" onClick={copyDiagnostic}>
{copied ? <Check size={12} aria-hidden="true" /> : null}
<span>{item.copyDetailsLabel}</span>
</button>
)}
</details>
)}
{item.action && (
<RToast.Action asChild altText={item.action.label}>
<button type="button" className="btn toast-action-btn" onClick={item.action.onClick}>
{item.action.label}
</button>
</RToast.Action>
)}
</div>
)}
</RToast.Root>
)
}
interface ToasterProps {
items: ToastItem[]
onRemove: (id: number) => void
closeLabel: string
dir?: 'ltr' | 'rtl'
}
export const Toaster: React.FC<ToasterProps> = ({ items, onRemove, closeLabel, dir = 'ltr' }) => (
<RToast.Provider swipeDirection={dir === 'rtl' ? 'left' : 'right'}>
{items.map((item) => (
<ToastCard key={item.id} item={item} onRemove={onRemove} closeLabel={closeLabel} />
))}
<RToast.Viewport className="toast-viewport" />
</RToast.Provider>
+6 -2
View File
@@ -16,8 +16,8 @@ import {
} from '../wailsjs/runtime/runtime'
import type {
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
LogEntry, PluginInfo, PluginUIContributions, RemoteRuntime, RuntimeKindSpec,
Task, VMAffinityStatus, VMAffinityUpdate,
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime,
RuntimeKindSpec, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate,
} from './types'
type AnyFn = (...args: never[]) => unknown
@@ -144,6 +144,10 @@ export const api = {
ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
ListPlugins: boundGo.ListPlugins as () => Promise<PluginInfo[] | null>,
InspectPluginArchive: boundGo.InspectPluginArchive as (path: string) => Promise<ScanReport>,
ScanInstalledPlugin: boundGo.ScanInstalledPlugin as (id: string) => Promise<ScanReport>,
BrowsePluginMarket: boundGo.BrowsePluginMarket as (query: string, kind: string, includeAlpha: boolean, forceRefresh: boolean) => Promise<MarketBrowseResult>,
InstallMarketPlugin: boundGo.InstallMarketPlugin as (id: string, includeAlpha: boolean) => Promise<PluginInfo>,
GetPluginUIContributions: boundGo.GetPluginUIContributions as () => Promise<PluginUIContributions>,
GetActiveTheme: boundGo.GetActiveTheme as () => Promise<ActiveThemePayload>,
ListDrivers: boundGo.ListDrivers as () => Promise<DriverSummary[] | null>,
+4
View File
@@ -2,7 +2,10 @@
"uiApi": "1.0.0",
"tokens": [
"--font-sans",
"--font-cjk",
"--font-mono",
"--body-lh",
"--heading-tracking",
"--fs-11",
"--fs-12",
"--fs-13",
@@ -107,6 +110,7 @@
"stateAttrs": [
"data-theme",
"data-motion",
"data-locale",
"data-view",
"data-vm-state",
"data-busy",
+14 -2
View File
@@ -15,6 +15,8 @@ export function AttachGuestTools(arg1:string):Promise<void>;
export function AttachInstaller(arg1:string,arg2:string):Promise<string>;
export function BrowsePluginMarket(arg1:string,arg2:string,arg3:boolean,arg4:boolean):Promise<plugin.MarketBrowseResult>;
export function CanOpenQQGroup():Promise<boolean>;
export function CancelTask(arg1:string):Promise<void>;
@@ -79,6 +81,8 @@ export function FocusVMWindow(arg1:string):Promise<void>;
export function GetActiveTheme():Promise<plugin.ActiveThemePayload>;
export function GetLicenseTexts():Promise<app.LicenseTexts>;
export function GetPluginSettings(arg1:string,arg2:string):Promise<Record<string, any>>;
export function GetPluginUIContributions():Promise<app.PluginUIContributions>;
@@ -107,8 +111,12 @@ export function GetVMStats(arg1:string):Promise<app.VMStats>;
export function GetVMThumbnail(arg1:string):Promise<app.VMThumbnail>;
export function InspectPluginArchive(arg1:string):Promise<plugin.ScanReport>;
export function InstallAppUpdate():Promise<void>;
export function InstallMarketPlugin(arg1:string,arg2:boolean):Promise<plugin.PluginInfo>;
export function InstallPluginArchive(arg1:string):Promise<plugin.PluginInfo>;
export function InstallRuntimeArchive(arg1:string):Promise<runtime.Installed>;
@@ -165,6 +173,8 @@ export function ReadVMLogs(arg1:string,arg2:boolean):Promise<string>;
export function RemovePlugin(arg1:string,arg2:boolean):Promise<void>;
export function RemoveRuntime(arg1:string):Promise<void>;
export function RequestClose():Promise<void>;
export function ResizeVMDisk(arg1:string,arg2:string):Promise<reims.DiskResizeResult>;
@@ -175,10 +185,14 @@ export function RestoreSnapshot(arg1:string,arg2:string):Promise<void>;
export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise<void>;
export function ScanInstalledPlugin(arg1:string):Promise<plugin.ScanReport>;
export function SetActiveTheme(arg1:string,arg2:string):Promise<void>;
export function SetAutoPinPCores(arg1:boolean):Promise<void>;
export function SetAppUpdateChannel(arg1:string):Promise<void>;
export function SetDataRoot(arg1:string):Promise<void>;
export function SetGuestPreventSleep(arg1:string,arg2:boolean):Promise<void>;
@@ -191,8 +205,6 @@ export function SetPluginSettings(arg1:string,arg2:string,arg3:Record<string, an
export function SetRuntimeChannel(arg1:string):Promise<void>;
export function SetRuntimeSource(arg1:string):Promise<void>;
export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
+28 -4
View File
@@ -14,6 +14,10 @@ export function AttachInstaller(arg1, arg2) {
return window['go']['app']['App']['AttachInstaller'](arg1, arg2);
}
export function BrowsePluginMarket(arg1, arg2, arg3, arg4) {
return window['go']['app']['App']['BrowsePluginMarket'](arg1, arg2, arg3, arg4);
}
export function CanOpenQQGroup() {
return window['go']['app']['App']['CanOpenQQGroup']();
}
@@ -142,6 +146,10 @@ export function GetActiveTheme() {
return window['go']['app']['App']['GetActiveTheme']();
}
export function GetLicenseTexts() {
return window['go']['app']['App']['GetLicenseTexts']();
}
export function GetPluginSettings(arg1, arg2) {
return window['go']['app']['App']['GetPluginSettings'](arg1, arg2);
}
@@ -198,10 +206,18 @@ export function GetVMThumbnail(arg1) {
return window['go']['app']['App']['GetVMThumbnail'](arg1);
}
export function InspectPluginArchive(arg1) {
return window['go']['app']['App']['InspectPluginArchive'](arg1);
}
export function InstallAppUpdate() {
return window['go']['app']['App']['InstallAppUpdate']();
}
export function InstallMarketPlugin(arg1, arg2) {
return window['go']['app']['App']['InstallMarketPlugin'](arg1, arg2);
}
export function InstallPluginArchive(arg1) {
return window['go']['app']['App']['InstallPluginArchive'](arg1);
}
@@ -314,6 +330,10 @@ export function RemovePlugin(arg1, arg2) {
return window['go']['app']['App']['RemovePlugin'](arg1, arg2);
}
export function RemoveRuntime(arg1) {
return window['go']['app']['App']['RemoveRuntime'](arg1);
}
export function RequestClose() {
return window['go']['app']['App']['RequestClose']();
}
@@ -334,6 +354,10 @@ export function SaveCustomThemeScheme(arg1) {
return window['go']['app']['App']['SaveCustomThemeScheme'](arg1);
}
export function ScanInstalledPlugin(arg1) {
return window['go']['app']['App']['ScanInstalledPlugin'](arg1);
}
export function SetActiveTheme(arg1, arg2) {
return window['go']['app']['App']['SetActiveTheme'](arg1, arg2);
}
@@ -362,12 +386,12 @@ export function SetPluginSettings(arg1, arg2, arg3) {
return window['go']['app']['App']['SetPluginSettings'](arg1, arg2, arg3);
}
export function SetRuntimeChannel(arg1) {
return window['go']['app']['App']['SetRuntimeChannel'](arg1);
export function SetAppUpdateChannel(arg1) {
return window['go']['app']['App']['SetAppUpdateChannel'](arg1);
}
export function SetRuntimeSource(arg1) {
return window['go']['app']['App']['SetRuntimeSource'](arg1);
export function SetRuntimeChannel(arg1) {
return window['go']['app']['App']['SetRuntimeChannel'](arg1);
}
export function SetVMAffinity(arg1, arg2) {
+328 -5
View File
@@ -15,6 +15,9 @@ export namespace app {
app_version: string;
safe_mode?: boolean;
plugin_crash_detected?: boolean;
detected_locale?: string;
effective_locale?: string;
missing_font_hint?: string;
static createFrom(source: any = {}) {
return new AppState(source);
@@ -36,6 +39,9 @@ export namespace app {
this.app_version = source["app_version"];
this.safe_mode = source["safe_mode"];
this.plugin_crash_detected = source["plugin_crash_detected"];
this.detected_locale = source["detected_locale"];
this.effective_locale = source["effective_locale"];
this.missing_font_hint = source["missing_font_hint"];
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
@@ -152,6 +158,20 @@ export namespace app {
return a;
}
}
export class LicenseTexts {
license: string;
notice: string;
static createFrom(source: any = {}) {
return new LicenseTexts(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.license = source["license"];
this.notice = source["notice"];
}
}
export class PendingChange {
field: string;
from: string;
@@ -281,6 +301,9 @@ export namespace app {
kind: string;
subject: string;
vm?: string;
installer_kind?: string;
installer_version?: string;
installer_phase?: string;
step: string;
done: number;
total: number;
@@ -303,6 +326,9 @@ export namespace app {
this.kind = source["kind"];
this.subject = source["subject"];
this.vm = source["vm"];
this.installer_kind = source["installer_kind"];
this.installer_version = source["installer_version"];
this.installer_phase = source["installer_phase"];
this.step = source["step"];
this.done = source["done"];
this.total = source["total"];
@@ -378,6 +404,9 @@ export namespace app {
disk_actual_bytes: number;
disk_virtual_bytes: number;
disk_format?: string;
disk_backing_depth?: number;
disk_backing_broken?: boolean;
disk_backing_depth_warn?: boolean;
uptime_seconds: number;
guest_tools_connected: boolean;
guest_tools_mount_mode?: string;
@@ -398,6 +427,9 @@ export namespace app {
this.disk_actual_bytes = source["disk_actual_bytes"];
this.disk_virtual_bytes = source["disk_virtual_bytes"];
this.disk_format = source["disk_format"];
this.disk_backing_depth = source["disk_backing_depth"];
this.disk_backing_broken = source["disk_backing_broken"];
this.disk_backing_depth_warn = source["disk_backing_depth_warn"];
this.uptime_seconds = source["uptime_seconds"];
this.guest_tools_connected = source["guest_tools_connected"];
this.guest_tools_mount_mode = source["guest_tools_mount_mode"];
@@ -433,7 +465,7 @@ export namespace config {
auto_pin_pcores: boolean;
default_gpu?: string;
runtime_channel?: string;
runtime_source?: string;
app_update_channel?: string;
minimize_to_tray?: boolean;
static createFrom(source: any = {}) {
@@ -448,7 +480,7 @@ export namespace config {
this.auto_pin_pcores = source["auto_pin_pcores"];
this.default_gpu = source["default_gpu"];
this.runtime_channel = source["runtime_channel"];
this.runtime_source = source["runtime_source"];
this.app_update_channel = source["app_update_channel"];
this.minimize_to_tray = source["minimize_to_tray"];
}
}
@@ -544,6 +576,24 @@ export namespace host {
this.default_backend = source["default_backend"];
}
}
export class BackingChainIssue {
vm_name: string;
path: string;
depth: number;
broken?: boolean;
static createFrom(source: any = {}) {
return new BackingChainIssue(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.vm_name = source["vm_name"];
this.path = source["path"];
this.depth = source["depth"];
this.broken = source["broken"];
}
}
export class DisplayInfo {
name?: string;
width: number;
@@ -592,6 +642,13 @@ export namespace host {
name: string;
vulkan_icd: string;
kind: string;
vendor_id?: string;
device_id?: string;
driver_version?: string;
vulkan_version?: string;
compat?: string;
compat_code?: string;
compat_detail?: string;
static createFrom(source: any = {}) {
return new GPUInfo(source);
@@ -602,6 +659,13 @@ export namespace host {
this.name = source["name"];
this.vulkan_icd = source["vulkan_icd"];
this.kind = source["kind"];
this.vendor_id = source["vendor_id"];
this.device_id = source["device_id"];
this.driver_version = source["driver_version"];
this.vulkan_version = source["vulkan_version"];
this.compat = source["compat"];
this.compat_code = source["compat_code"];
this.compat_detail = source["compat_detail"];
}
}
export class LogicalCPUInfo {
@@ -686,6 +750,7 @@ export namespace host {
commit_limit_gb: number;
data_root: string;
data_root_drive_type?: string;
deep_backing_chains?: BackingChainIssue[];
free_disk_gb: number;
whpx: string;
whpx_caps: WHPXCapabilities;
@@ -730,6 +795,7 @@ export namespace host {
this.commit_limit_gb = source["commit_limit_gb"];
this.data_root = source["data_root"];
this.data_root_drive_type = source["data_root_drive_type"];
this.deep_backing_chains = this.convertValues(source["deep_backing_chains"], BackingChainIssue);
this.free_disk_gb = source["free_disk_gb"];
this.whpx = source["whpx"];
this.whpx_caps = this.convertValues(source["whpx_caps"], WHPXCapabilities);
@@ -1393,11 +1459,21 @@ export namespace plugin {
return a;
}
}
export interface ResolvedLocaleFont {
family: string;
url: string;
weight?: string;
style?: string;
unicodeRange?: string;
}
export class ResolvedLocalePack {
locale: string;
label: string;
fallback?: string;
has_ui_messages?: boolean;
messages?: Record<string, string>;
plugin_messages?: Record<string, Record<string, string>>;
fonts?: ResolvedLocaleFont[];
pluginIds?: string[];
static createFrom(source: any = {}) {
@@ -1409,7 +1485,10 @@ export namespace plugin {
this.locale = source["locale"];
this.label = source["label"];
this.fallback = source["fallback"];
this.has_ui_messages = source["has_ui_messages"];
this.messages = source["messages"];
this.plugin_messages = source["plugin_messages"];
this.fonts = source["fonts"];
this.pluginIds = source["pluginIds"];
}
}
@@ -1623,6 +1702,246 @@ export namespace plugin {
return a;
}
}
export class Engines {
'reims-go'?: string;
pluginApi?: string;
uiApi?: string;
static createFrom(source: any = {}) {
return new Engines(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this['reims-go'] = source["reims-go"];
this.pluginApi = source["pluginApi"];
this.uiApi = source["uiApi"];
}
}
export class ScanFinding {
severity: string;
check: string;
target?: string;
message: string;
localized?: LocalizedText;
static createFrom(source: any = {}) {
return new ScanFinding(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.severity = source["severity"];
this.check = source["check"];
this.target = source["target"];
this.message = source["message"];
this.localized = source["localized"] ? new LocalizedText(source["localized"]) : undefined;
}
}
export class ExecutableFile {
path: string;
sha256: string;
declared: boolean;
size_bytes: number;
static createFrom(source: any = {}) {
return new ExecutableFile(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.path = source["path"];
this.sha256 = source["sha256"];
this.declared = source["declared"];
this.size_bytes = source["size_bytes"];
}
}
export class CapabilityItem {
id: string;
level: string;
title: LocalizedText;
summary: LocalizedText;
examples?: string[];
extra_count?: number;
static createFrom(source: any = {}) {
return new CapabilityItem(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.level = source["level"];
this.title = new LocalizedText(source["title"]);
this.summary = new LocalizedText(source["summary"]);
this.examples = source["examples"];
this.extra_count = source["extra_count"];
}
}
export class ScanReport {
plugin_id?: string;
version?: string;
name?: LocalizedText;
tier?: string;
trust?: string;
publisher?: string;
license?: string;
passed: boolean;
hard_blocked: boolean;
needs_approval: boolean;
headline: LocalizedText;
native_exec_notice?: LocalizedText;
hard_findings?: ScanFinding[];
capabilities?: CapabilityItem[];
pending_findings?: ScanFinding[];
executables?: ExecutableFile[];
static createFrom(source: any = {}) {
return new ScanReport(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.plugin_id = source["plugin_id"];
this.version = source["version"];
this.name = source["name"] ? new LocalizedText(source["name"]) : undefined;
this.tier = source["tier"];
this.trust = source["trust"];
this.publisher = source["publisher"];
this.license = source["license"];
this.passed = source["passed"];
this.hard_blocked = source["hard_blocked"];
this.needs_approval = source["needs_approval"];
this.headline = new LocalizedText(source["headline"]);
this.native_exec_notice = source["native_exec_notice"] ? new LocalizedText(source["native_exec_notice"]) : undefined;
this.hard_findings = (source["hard_findings"] || []).map((x: any) => new ScanFinding(x));
this.capabilities = (source["capabilities"] || []).map((x: any) => new CapabilityItem(x));
this.pending_findings = (source["pending_findings"] || []).map((x: any) => new ScanFinding(x));
this.executables = (source["executables"] || []).map((x: any) => new ExecutableFile(x));
}
}
export class MarketEntry {
id: string;
version: string;
name: LocalizedText;
description: LocalizedText;
publisher: string;
license: string;
channel: string;
trust: string;
kind?: string;
tier?: string;
homepage?: string;
readme_url?: string;
engines: Engines;
platforms?: string[];
permissions?: string[];
download_url: string;
sha256: string;
size_bytes?: number;
signer?: string;
changelog?: LocalizedText;
tags?: string[];
updated_at?: string;
static createFrom(source: any = {}) {
return new MarketEntry(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.version = source["version"];
this.name = new LocalizedText(source["name"]);
this.description = new LocalizedText(source["description"]);
this.publisher = source["publisher"];
this.license = source["license"];
this.channel = source["channel"];
this.trust = source["trust"];
this.kind = source["kind"];
this.tier = source["tier"];
this.homepage = source["homepage"];
this.readme_url = source["readme_url"];
this.engines = new Engines(source["engines"]);
this.platforms = source["platforms"];
this.permissions = source["permissions"];
this.download_url = source["download_url"];
this.sha256 = source["sha256"];
this.size_bytes = source["size_bytes"];
this.signer = source["signer"];
this.changelog = source["changelog"] ? new LocalizedText(source["changelog"]) : undefined;
this.tags = source["tags"];
this.updated_at = source["updated_at"];
}
}
export class MarketWithdrawal {
id: string;
reason: LocalizedText;
instead_id?: string;
instead_name?: string;
withdrawn_at?: string;
static createFrom(source: any = {}) {
return new MarketWithdrawal(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.reason = new LocalizedText(source["reason"]);
this.instead_id = source["instead_id"];
this.instead_name = source["instead_name"];
this.withdrawn_at = source["withdrawn_at"];
}
}
export class MarketCatalogItem {
entry: MarketEntry;
installed: boolean;
installed_version?: string;
update_available: boolean;
compatible: boolean;
incompatible_reason?: string;
withdrawn?: MarketWithdrawal;
high_risk_permissions?: string[];
static createFrom(source: any = {}) {
return new MarketCatalogItem(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.entry = new MarketEntry(source["entry"]);
this.installed = source["installed"];
this.installed_version = source["installed_version"];
this.update_available = source["update_available"];
this.compatible = source["compatible"];
this.incompatible_reason = source["incompatible_reason"];
this.withdrawn = source["withdrawn"] ? new MarketWithdrawal(source["withdrawn"]) : undefined;
this.high_risk_permissions = source["high_risk_permissions"];
}
}
export class MarketBrowseResult {
source: string;
stale: boolean;
fetch_error?: string;
updated_at?: string;
items: MarketCatalogItem[];
withdrawn_installed?: MarketWithdrawal[];
static createFrom(source: any = {}) {
return new MarketBrowseResult(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.source = source["source"];
this.stale = source["stale"];
this.fetch_error = source["fetch_error"];
this.updated_at = source["updated_at"];
this.items = (source["items"] || []).map((x: any) => new MarketCatalogItem(x));
this.withdrawn_installed = (source["withdrawn_installed"] || []).map((x: any) => new MarketWithdrawal(x));
}
}
}
@@ -1900,7 +2219,8 @@ export namespace reims {
}
export class ValidationIssue {
field: string;
code: string;
code?: string;
params?: Record<string, any>;
message: string;
static createFrom(source: any = {}) {
@@ -1911,6 +2231,7 @@ export namespace reims {
if ('string' === typeof source) source = JSON.parse(source);
this.field = source["field"];
this.code = source["code"];
this.params = source["params"];
this.message = source["message"];
}
}
@@ -2053,6 +2374,7 @@ export namespace runtime {
}
export class KindSpec {
kind: string;
name?: plugin.LocalizedText;
name_zh: string;
name_en: string;
required_files?: string[];
@@ -2067,6 +2389,7 @@ export namespace runtime {
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.kind = source["kind"];
this.name = source["name"];
this.name_zh = source["name_zh"];
this.name_en = source["name_en"];
this.required_files = source["required_files"];
@@ -2081,7 +2404,6 @@ export namespace runtime {
commit: string;
tag: string;
channel: string;
source?: string;
published_at: string;
page_url: string;
archive_name: string;
@@ -2100,7 +2422,6 @@ export namespace runtime {
this.commit = source["commit"];
this.tag = source["tag"];
this.channel = source["channel"];
this.source = source["source"];
this.published_at = source["published_at"];
this.page_url = source["page_url"];
this.archive_name = source["archive_name"];
@@ -2119,6 +2440,7 @@ export namespace version {
export class UpdateInfo {
current: string;
latest: string;
channel?: string;
has_update: boolean;
page_url?: string;
download_url?: string;
@@ -2135,6 +2457,7 @@ export namespace version {
if ('string' === typeof source) source = JSON.parse(source);
this.current = source["current"];
this.latest = source["latest"];
this.channel = source["channel"];
this.has_update = source["has_update"];
this.page_url = source["page_url"];
this.download_url = source["download_url"];
+1
View File
@@ -3,6 +3,7 @@ module github.com/Nwflower/reims-go
go 1.26.0
require (
github.com/klauspost/compress v1.20.5
github.com/ulikunitz/xz v0.5.17
github.com/wailsapp/wails/v2 v2.17.1
golang.org/x/net v0.60.0
+2
View File
@@ -16,6 +16,8 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e h1:Q3+PugElBCf4PFpxhErSzU3/PY5sFL5Z6rfv4AbGAck=
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/labstack/echo/v4 v4.16.1 h1:h05NuF1GvNu6jSAZxOv++AdjD/NJK+mZdGy0thiiuns=
github.com/labstack/echo/v4 v4.16.1/go.mod h1:V/EQaTVHYJH92QhbQe7kFQ4mjgcjxLQQUQtAN87zZdw=
github.com/labstack/gommon v0.5.0 h1:6VSQ2NOzsnEJ5W6+84E0RbcaDDmgB6NIAzWCczTEe6c=
+228 -43
View File
@@ -54,6 +54,9 @@ type AppState struct {
AppVersion string `json:"app_version"`
SafeMode bool `json:"safe_mode,omitempty"`
PluginCrashDetected bool `json:"plugin_crash_detected,omitempty"`
DetectedLocale string `json:"detected_locale,omitempty"`
EffectiveLocale string `json:"effective_locale,omitempty"`
MissingFontHint string `json:"missing_font_hint,omitempty"`
}
type rebootWatcherEntry struct {
@@ -85,6 +88,7 @@ type App struct {
trayIcon []byte // embedded PNG passed in from package main
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
pluginMgr *plugin.Manager
pluginMarket *plugin.MarketClient
driverRouter *driver.Router
runtimeKinds *rt.KindRegistry
uiHealth uiHealthState
@@ -103,6 +107,7 @@ type Lifecycle struct {
}
func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
i18n.SetDetailRedactor(reims.RedactText)
cfg, needsSetup, err := config.Resolve()
if err != nil {
cfg = config.Default()
@@ -373,10 +378,9 @@ func (a *App) pollVMs(ctx context.Context) {
}
a.syncInputTargets(imeTargets)
if tm != nil {
if runningCount == 1 {
tm.UpdateTooltip(i18n.T(loc, "tray.running.one"))
} else if runningCount > 1 {
tm.UpdateTooltip(i18n.T(loc, "tray.running.many", runningCount))
effLoc := i18n.EffectiveLocale(loc)
if runningCount >= 1 {
tm.UpdateTooltip(i18n.M(effLoc, "tray.running", i18n.Vars{"count": runningCount}))
} else {
tm.UpdateTooltip("Reims-Go")
}
@@ -654,6 +658,9 @@ func (a *App) GetState() AppState {
AppVersion: version.Version,
SafeMode: safeMode,
PluginCrashDetected: crashDetected,
DetectedLocale: string(i18n.DetectOSLocaleTag()),
EffectiveLocale: string(i18n.EffectiveLocale(cfgCopy.Locale)),
MissingFontHint: host.CheckMissingLocaleFontsForUI(string(i18n.EffectiveLocale(cfgCopy.Locale)), i18n.EffectiveLocale(cfgCopy.Locale)),
}
}
@@ -674,9 +681,18 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
func (a *App) SetLocale(raw string) error {
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.Locale = i18n.ResolveLocale(raw)
return config.Save("", a.cfg)
a.cfg.Locale = i18n.ParsePreference(raw)
err := config.Save("", a.cfg)
eff := i18n.EffectiveLocale(a.cfg.Locale)
mgr := a.pluginMgr
a.mu.Unlock()
if mgr != nil {
mgr.NotifyLocaleChanged(eff)
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return err
}
func (a *App) SetAutoPinPCores(enabled bool) error {
@@ -779,8 +795,10 @@ func (a *App) startTray() {
}
items = append(items, tray.VMItem{Name: vm.Name, Label: label, State: state})
}
effLoc := i18n.EffectiveLocale(loc)
return tray.Snapshot{
LocaleZh: loc == i18n.ZhCN,
Locale: effLoc,
LocaleZh: effLoc == i18n.ZhCN,
VMs: items,
}
},
@@ -799,35 +817,31 @@ func (a *App) startTray() {
// result) are reported as a Windows notification from the tray icon.
func (a *App) trayVMAction(name string, act tray.Action) {
a.mu.Lock()
zh := a.cfg.Locale == i18n.ZhCN
rawLoc := a.cfg.Locale
tm := a.trayMgr
a.mu.Unlock()
pick := func(cn, en string) string {
if zh {
return cn
}
return en
}
loc := i18n.EffectiveLocale(rawLoc)
vars := i18n.Vars{"name": name}
var err error
var failTitle string
switch act {
case tray.ActStart:
err, failTitle = a.StartVM(name), pick("无法启动 ", "Couldn't start ")+name
err, failTitle = a.StartVM(name), i18n.M(loc, "tray.notify.start_fail", vars)
case tray.ActStop:
err, failTitle = a.StopVM(name, false), pick("无法关机 ", "Couldn't shut down ")+name
err, failTitle = a.StopVM(name, false), i18n.M(loc, "tray.notify.stop_fail", vars)
case tray.ActForceStop:
err, failTitle = a.StopVM(name, true), pick("无法强制关机 ", "Couldn't force shut down ")+name
err, failTitle = a.StopVM(name, true), i18n.M(loc, "tray.notify.force_stop_fail", vars)
case tray.ActRestart:
err, failTitle = a.RestartVM(name), pick("无法重启 ", "Couldn't restart ")+name
err, failTitle = a.RestartVM(name), i18n.M(loc, "tray.notify.restart_fail", vars)
case tray.ActShowWindow:
err, failTitle = a.FocusVMWindow(name), pick("找不到 ", "Couldn't find the window of ")+name+pick(" 的窗口", "")
err, failTitle = a.FocusVMWindow(name), i18n.M(loc, "tray.notify.focus_fail", vars)
case tray.ActScreenshot:
if err = a.CopyVMScreenshot(name); err == nil && tm != nil {
tm.Notify(pick("已复制屏幕截图", "Screenshot copied"), name, false)
tm.Notify(i18n.T(loc, "tray.notify.screenshot_ok"), name, false)
}
failTitle = pick("截图失败:", "Screenshot failed: ") + name
failTitle = i18n.M(loc, "tray.notify.screenshot_fail", vars)
case tray.ActSharedFolder:
err, failTitle = a.OpenSharedFolder(name), pick("无法打开共享文件夹", "Couldn't open the shared folder")
err, failTitle = a.OpenSharedFolder(name), i18n.T(loc, "tray.notify.shared_fail")
case tray.ActOpenInApp:
a.ShowMainWindow()
if a.ctx != nil {
@@ -842,22 +856,85 @@ func (a *App) trayVMAction(name string, act tray.Action) {
}
}
func (a *App) SetDataRoot(dir string) error {
dir = strings.TrimSpace(dir)
if dir == "" {
return fmt.Errorf("data root cannot be empty")
}
func (a *App) resetDataRootCaches() {
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.lastVMs = nil
a.lastVMsAt = time.Time{}
a.diskPaths = make(map[string]cachedDiskPath)
a.procSamples = make(map[string]host.ProcessSample)
a.mu.Unlock()
}
func (a *App) SetDataRoot(dir string) error {
a.mu.Lock()
loc := i18n.EffectiveLocale(a.cfg.Locale)
prev := a.cfg.DataRoot
curLocalePref := a.cfg.Locale
curAutoPin := a.cfg.AutoPinPCores
curRuntimeChannel := a.cfg.RuntimeChannel
curAppUpdateChannel := a.cfg.AppUpdateChannel
curMinToTray := a.cfg.MinimizeToTray
for _, v := range a.lastVMs {
if v.State == "running" || v.State == "starting" || v.State == "stopping" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
}
}
a.mu.Unlock()
return err
for _, t := range tasks.list() {
if t.Status == TaskRunning {
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_TASKS", "err.dataroot.busy_tasks", nil, nil)
}
}
dir = strings.TrimSpace(dir)
if dir != "" {
dir = filepath.Clean(dir)
}
if err := validateDataRoot(dir, loc); err != nil {
return err
}
cfgPath := filepath.Join(dir, "reims-go.json")
nextCfg, err := config.Load(cfgPath)
if err != nil {
return fmt.Errorf("read %s: %w", cfgPath, err)
}
nextCfg.DataRoot = dir
if _, statErr := os.Stat(cfgPath); statErr != nil {
nextCfg.Locale = curLocalePref
nextCfg.AutoPinPCores = curAutoPin
nextCfg.RuntimeChannel = curRuntimeChannel
nextCfg.AppUpdateChannel = curAppUpdateChannel
nextCfg.MinimizeToTray = curMinToTray
}
if err := nextCfg.EnsureDirs(); err != nil {
return err
}
if err := writable(dir); err != nil {
return err
}
if err := config.Save(cfgPath, nextCfg); err != nil {
return err
}
if err := config.SaveLocation(dir); err != nil {
return err
}
a.mu.Lock()
a.cfg = nextCfg
a.mu.Unlock()
if filepath.Clean(prev) != filepath.Clean(dir) {
a.resetDataRootCaches()
a.reloadPlugins()
a.wakePoll()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
}
return nil
}
func (a *App) PickDirectory(title string) (string, error) {
@@ -917,10 +994,37 @@ func (a *App) UseRuntime(commit string) error {
return config.Save("", a.cfg)
}
func (a *App) RemoveRuntime(commit string) error {
a.mu.Lock()
cfg := a.cfg
loc := i18n.EffectiveLocale(a.cfg.Locale)
ctx := a.ctx
a.mu.Unlock()
inst, err := rt.Remove(cfg, commit)
if err != nil {
switch {
case errors.Is(err, rt.ErrNotFound):
return errors.New(i18n.T(loc, "runtime.not_found", commit))
case errors.Is(err, rt.ErrRemoveActive):
return errors.New(i18n.T(loc, "runtime.remove_active", commit))
case errors.Is(err, rt.ErrRuntimeInUse):
return errors.New(i18n.T(loc, "runtime.remove_in_use", commit))
default:
return err
}
}
a.emitLog("runtime", fmt.Sprintf("Removed runtime %s (%s)", inst.Commit, inst.Dir))
if ctx != nil {
wailsRuntime.EventsEmit(ctx, "reims:state-changed", true)
}
return nil
}
func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
a.mu.Lock()
root := a.cfg.DataRoot
loc := a.cfg.Locale
loc := i18n.EffectiveLocale(a.cfg.Locale)
a.mu.Unlock()
issues := reims.ValidateCreateLocalized(opts, host.Inspect(root), loc)
// reims-ctl refuses a name already registered; say so before the create runs.
@@ -1042,6 +1146,44 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
return nil
}
const (
vmExitWaitTimeout = 12 * time.Second
vmMemoryReclaimWaitTimeout = 15 * time.Second
)
func (a *App) cachedVMPID(name string) int {
a.mu.Lock()
defer a.mu.Unlock()
for _, vm := range a.lastVMs {
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
return *vm.PID
}
}
return 0
}
func (a *App) waitForVMProcessExit(ctx context.Context, pid int, timeout time.Duration) {
if pid <= 0 || timeout <= 0 {
return
}
waitCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
_ = host.WaitProcessExit(waitCtx, uint32(pid), qemuImage)
}
func (a *App) waitForCommitMemoryReclaim(ctx context.Context, c *reims.Client, name, logPrefix string) {
if ctx.Err() != nil || c == nil {
return
}
detail, err := c.Show(ctx, name)
if err != nil || detail.Memory == "" {
return
}
vmstart.WaitForCommitMemory(ctx, detail.Memory, vmMemoryReclaimWaitTimeout, func(availGB, neededGB float64) {
a.emitLog(name, fmt.Sprintf("%s: waiting for Windows to release VM memory (available %.1f GB, need %.1f GB)...", logPrefix, availGB, neededGB))
})
}
func (a *App) cancelRebootWatcher(name string) {
a.mu.Lock()
if entry, ok := a.rebootWatchers[name]; ok {
@@ -1095,13 +1237,21 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
}
a.emitLog(name, "Win10 WHPX cold-reboot: guest requested reboot (guest-reset), restarting in a fresh Hyper-V partition...")
oldPID := a.cachedVMPID(name)
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)
// Wait for QEMU to finish exiting cleanly under -no-reboot. Wait on the
// OS process handle when known so we don't race against QEMU teardown
// even if `reims-ctl list` reports stopped early.
deadline := time.Now().Add(vmExitWaitTimeout)
waitedPID := 0
if oldPID > 0 {
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
waitedPID = oldPID
}
for time.Now().Before(deadline) {
if watchCtx.Err() != nil {
return
@@ -1110,17 +1260,39 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
if err == nil {
stopped := false
for _, vm := range vms {
if vm.Name == name && vm.State == "stopped" {
stopped = true
break
if vm.Name != name {
continue
}
if vm.PID != nil && *vm.PID > 0 && oldPID == 0 {
oldPID = *vm.PID
}
if vm.State == "stopped" {
stopped = true
}
break
}
if stopped {
break
}
if oldPID > 0 && oldPID != waitedPID {
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
waitedPID = oldPID
continue
}
}
select {
case <-watchCtx.Done():
return
case <-time.After(300 * time.Millisecond):
}
time.Sleep(300 * time.Millisecond)
}
if oldPID > 0 && oldPID != waitedPID {
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
}
if watchCtx.Err() != nil {
return
}
a.waitForCommitMemoryReclaim(watchCtx, c, name, "Win10 WHPX cold-reboot")
if watchCtx.Err() != nil {
return
}
@@ -1152,6 +1324,10 @@ func (a *App) StartVM(name string) error {
tmpDir := a.cfg.TempDir()
a.mu.Unlock()
rep := host.Inspect(root)
if err := prep.CheckWHPX(rep); err != nil {
a.emitLog(name, "Start refused: "+err.Error())
return err
}
curDetail, _ := c.Show(context.Background(), name)
if err := prep.CheckMemory(curDetail.Memory, rep); err != nil {
a.emitLog(name, "Start refused: "+err.Error())
@@ -1332,9 +1508,18 @@ func (a *App) RestartVM(name string) error {
}
func (a *App) restartVM(name string) (stopped bool, err error) {
oldPID := a.cachedVMPID(name)
if err := a.StopVM(name, false); err != nil {
return false, err
}
ctx := a.baseCtx()
a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout)
if c, err := a.client(); err == nil {
a.waitForCommitMemoryReclaim(ctx, c, name, "Restart")
}
if err := ctx.Err(); err != nil {
return true, err
}
return true, a.StartVM(name)
}
+19
View File
@@ -121,3 +121,22 @@ func TestWakePollMarksStaleAndWakesOnce(t *testing.T) {
default:
}
}
func TestCachedVMPID(t *testing.T) {
runningPID, stoppedPID := 4784, 9244
a := &App{
lastVMs: []reims.VMListItem{
{Name: "running-vm", State: "running", PID: &runningPID},
{Name: "stopped-vm", State: "stopped", PID: &stoppedPID},
},
}
if got := a.cachedVMPID("running-vm"); got != runningPID {
t.Fatalf("cachedVMPID(running-vm) = %d, want %d", got, runningPID)
}
if got := a.cachedVMPID("stopped-vm"); got != 0 {
t.Fatalf("cachedVMPID(stopped-vm) = %d, want 0", got)
}
if got := a.cachedVMPID("missing-vm"); got != 0 {
t.Fatalf("cachedVMPID(missing-vm) = %d, want 0", got)
}
}
+39 -11
View File
@@ -37,8 +37,9 @@ var appUpdateReady struct {
func (a *App) locale() i18n.Locale {
a.mu.Lock()
defer a.mu.Unlock()
return a.cfg.Locale
raw := a.cfg.Locale
a.mu.Unlock()
return i18n.EffectiveLocale(raw)
}
func (a *App) updateErr(key string, args ...any) error {
@@ -168,8 +169,14 @@ func (a *App) InstallAppUpdate() error {
return a.updateErr("err.update_not_writable", filepath.Dir(exe))
}
// A file still named after a release takes the new release's name.
a.mu.Lock()
channel := version.ChannelStable
if a.cfg != nil {
channel = version.NormalizeChannel(a.cfg.AppUpdateChannel)
}
a.mu.Unlock()
target := selfupdate.Target(exe, filepath.Base(path))
if err := selfupdate.Swap(exe, target, path); err != nil {
if err := selfupdate.SwapWithOptions(exe, target, path, version.KeepsPreviousInstall(channel)); err != nil {
return err
}
a.emitLog("app", fmt.Sprintf("Installed update %s at %s; restarting", ver, target))
@@ -190,22 +197,43 @@ func (a *App) InstallAppUpdate() error {
return nil
}
// finishAppUpdate runs at startup: removes what an earlier swap left next to
// the executable and, after an update restart, the downloaded installer files.
// finishAppUpdate runs at startup: on the stable channel it removes what an
// earlier swap left next to the executable and, after an update restart, the
// downloaded installer files. On alpha/dev channels those old executables and
// downloaded installers are preserved for safe manual rollback.
func (a *App) finishAppUpdate() {
exe, err := selfupdate.Executable()
if err != nil {
return
}
selfupdate.Cleanup(exe)
a.finishAppUpdateWithExe(exe)
}
func (a *App) finishAppUpdateWithExe(exe string) {
a.mu.Lock()
dataRoot := ""
channel := version.ChannelStable
if a.cfg != nil {
dataRoot = a.cfg.DataRoot
channel = version.NormalizeChannel(a.cfg.AppUpdateChannel)
}
a.mu.Unlock()
keepOld := version.KeepsPreviousInstall(channel)
if keepOld {
selfupdate.CleanupStaging(exe)
} else {
selfupdate.Cleanup(exe)
}
if a.launch.WaitPID == 0 {
return
}
a.mu.Lock()
dataRoot := a.cfg.DataRoot
a.mu.Unlock()
if dataRoot != "" {
if !keepOld && dataRoot != "" {
_ = os.RemoveAll(appUpdateDir(dataRoot))
}
a.emitLog("app", "Reims-Go updated to "+version.Version)
if keepOld {
a.emitLog("app", fmt.Sprintf("Reims-Go updated to %s (%s channel; previous executable and downloaded installers preserved)", version.Version, channel))
} else {
a.emitLog("app", "Reims-Go updated to "+version.Version)
}
}
+63
View File
@@ -12,6 +12,7 @@ import (
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/cli"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/version"
@@ -85,3 +86,65 @@ func TestInstallAppUpdateGuards(t *testing.T) {
t.Fatal("a changed download must be forgotten")
}
}
func TestFinishAppUpdatePreservesOldOnAlphaAndDev(t *testing.T) {
for _, tc := range []struct {
channel string
wantKept bool
}{
{version.ChannelStable, false},
{version.ChannelAlpha, true},
{version.ChannelDev, true},
} {
t.Run(tc.channel, func(t *testing.T) {
binDir := t.TempDir()
dataRoot := t.TempDir()
exe := filepath.Join(binDir, "reims-go.exe")
oldExe := exe + ".old"
newStaged := exe + ".new"
dlDir := appUpdateDir(dataRoot)
dlFile := filepath.Join(dlDir, "reims-go-v0.2.9-alpha.1-windows-amd64.exe")
for _, p := range []string{exe, oldExe, newStaged} {
if err := os.WriteFile(p, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
}
if err := os.MkdirAll(dlDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(dlFile, []byte("installer"), 0o644); err != nil {
t.Fatal(err)
}
cfg := config.Default()
cfg.DataRoot = dataRoot
cfg.AppUpdateChannel = tc.channel
a := &App{cfg: cfg, launch: cli.WindowArgs{WaitPID: 12345}}
a.finishAppUpdateWithExe(exe)
// Aborted staging .new is always cleaned up.
if _, err := os.Stat(newStaged); !os.IsNotExist(err) {
t.Fatalf("channel %s: expected .new staging file removed", tc.channel)
}
_, oldErr := os.Stat(oldExe)
_, dlErr := os.Stat(dlFile)
if tc.wantKept {
if oldErr != nil {
t.Fatalf("channel %s: expected .old backup preserved, err=%v", tc.channel, oldErr)
}
if dlErr != nil {
t.Fatalf("channel %s: expected downloaded installer preserved, err=%v", tc.channel, dlErr)
}
} else {
if !os.IsNotExist(oldErr) {
t.Fatalf("channel %s: expected .old backup removed", tc.channel)
}
if !os.IsNotExist(dlErr) {
t.Fatalf("channel %s: expected downloaded installer removed", tc.channel)
}
}
})
}
}
+12 -10
View File
@@ -19,17 +19,19 @@ import (
// 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 {
loc := a.locale()
cloneName = strings.TrimSpace(cloneName)
if cloneName == "" {
return fmt.Errorf("clone VM name is required")
return i18n.NewCodedError(loc, "E_VM_CLONE_EMPTY_NAME", "err.clone.missing_name", nil, nil)
}
if strings.EqualFold(sourceName, cloneName) {
return fmt.Errorf("clone name must differ from source VM")
return i18n.NewCodedError(loc, "E_VM_CLONE_SAME_NAME", "err.clone.same_name", nil, nil)
}
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
cfgCopy.Locale = loc
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return err
@@ -42,41 +44,41 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error {
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)
return i18n.NewCodedError(loc, "E_VM_CLONE_RUNNING", "err.clone.source_running", i18n.Vars{"name": sourceName}, nil)
}
if src.HasInstaller {
return fmt.Errorf("exit recovery mode on %s before deriving a CoW clone", sourceName)
return i18n.NewCodedError(loc, "E_VM_CLONE_RECOVERY", "err.clone.in_recovery", i18n.Vars{"name": sourceName}, nil)
}
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)
return i18n.NewCodedError(loc, "E_VM_CLONE_NO_DISK", "err.clone.no_disk", i18n.Vars{"name": sourceName}, nil)
}
if _, err := os.Stat(srcDisk); err != nil {
return fmt.Errorf("source disk not found (%s): %w", srcDisk, err)
return i18n.NewCodedError(loc, "E_VM_CLONE_DISK_MISSING", "err.clone.disk_missing", i18n.Vars{"path": srcDisk}, err)
}
// Validate clone name and check for name collisions.
rep := host.Inspect(cfgCopy.DataRoot)
nameCheck := reims.ValidateCreateLocalized(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, cfgCopy.Locale)
nameCheck := reims.ValidateCreateLocalized(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, loc)
for _, iss := range nameCheck {
if iss.Field == "name" {
return fmt.Errorf("%s", iss.Message)
return i18n.NewCodedError(loc, "E_VM_CLONE_INVALID_NAME", "validate."+iss.Code, i18n.Vars{"name": cloneName}, nil)
}
}
if existing, err := c.List(ctx); err == nil {
for _, vm := range existing {
if strings.EqualFold(vm.Name, cloneName) {
return fmt.Errorf("%s", i18n.T(cfgCopy.Locale, "validate.name_taken", cloneName))
return i18n.NewCodedError(loc, "E_VM_NAME_TAKEN", "validate.name_taken", i18n.Vars{"name": cloneName}, nil)
}
}
}
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)
return i18n.NewCodedError(loc, "E_VM_CLONE_OVERLAY_EXISTS", "err.clone.overlay_exists", i18n.Vars{"path": overlayPath}, nil)
}
w := vmstart.LineWriter(func(line string) { a.emitLog(cloneName, line) })
+67 -5
View File
@@ -46,6 +46,37 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
a.emitLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
}
// Ensure any requested macOS installer is downloaded via installer.Client
// before invoking reims-ctl create, so the Installers page, sidebar, and
// concurrent downloads share live byte progress, queueing and deduplication.
// reims-ctl create checks the same shared installers directory and reuses
// the completed image without downloading again.
if dlKind, dlVersion := createInstallerTarget(opts); dlKind != "" {
ic := installer.NewClient(&cfgCopy, *active)
cached, _ := ic.ListCached()
if installerDownloads.hasActive(dlKind, dlVersion) || !hasCompleteCachedInstaller(cached, dlKind, dlVersion) {
res, derr := a.ensureInstallerForTask(ctx, taskID, "vm-create", opts.Name, dlKind, dlVersion, func(dlCtx context.Context, onUpdate func(installer.Update)) (*installer.Result, error) {
if dlKind == "offline" {
return ic.DownloadOffline(dlCtx, dlVersion, onUpdate)
}
return ic.DownloadOnline(dlCtx, dlVersion, onUpdate)
})
if derr != nil {
if errors.Is(derr, context.Canceled) || ctx.Err() != nil {
finishTask(context.Canceled)
a.emitLog(opts.Name, "Create canceled.")
return context.Canceled
}
finishTask(derr)
a.emitLog(opts.Name, "Create error: "+derr.Error())
return derr
}
if res != nil && res.Image != "" {
a.emitLog(opts.Name, "Installer ready: "+res.Image)
}
}
}
// 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) {
@@ -58,10 +89,10 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
tasks.update(taskID, u)
})
if perr != nil {
if errors.Is(perr, context.Canceled) {
finishTask(perr)
if errors.Is(perr, context.Canceled) || ctx.Err() != nil {
finishTask(context.Canceled)
a.emitLog(opts.Name, "Create canceled.")
return perr
return context.Canceled
}
a.emitLog(opts.Name, "Pre-fetch OpenCore resources skipped (reims-ctl will retry): "+perr.Error())
}
@@ -75,8 +106,15 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
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 {
if ctx.Err() != nil {
cerr = context.Canceled
}
finishTask(cerr)
a.emitLog(opts.Name, "Disk conversion error: "+cerr.Error())
if errors.Is(cerr, context.Canceled) {
a.emitLog(opts.Name, "Create canceled.")
} else {
a.emitLog(opts.Name, "Disk conversion error: "+cerr.Error())
}
return cerr
}
opts.Disk = convertedTmp
@@ -85,8 +123,15 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
err = c.Create(ctx, opts, w, w)
if err != nil {
if ctx.Err() != nil {
err = context.Canceled
}
finishTask(err)
a.emitLog(opts.Name, "Create error: "+err.Error())
if errors.Is(err, context.Canceled) {
a.emitLog(opts.Name, "Create canceled.")
} else {
a.emitLog(opts.Name, "Create error: "+err.Error())
}
return err
}
if postSet, ok := reims.PostCreateSetOpts(opts); ok {
@@ -139,3 +184,20 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
}
return nil
}
func createInstallerTarget(opts reims.CreateOpts) (kind, version string) {
if strings.TrimSpace(opts.Disk) != "" || strings.TrimSpace(opts.Installer) != "" {
return "", ""
}
if opts.SourceMode == "disk" || opts.SourceMode == "installer" {
return "", ""
}
v := strings.TrimSpace(opts.MacOS)
if v == "" {
return "", ""
}
if opts.Offline || opts.SourceMode == "offline" {
return "offline", v
}
return "online", v
}
+6
View File
@@ -57,6 +57,12 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
"host": b.HostReport,
"optimizations": b.Optimizations,
}
if code, detail := reims.DiagnoseGPULog(b.QEMULog); code != "" {
hostSummary["gpu_diagnosis"] = map[string]string{
"code": code,
"detail": detail,
}
}
if err := addJSON("host-report.json", hostSummary); err != nil {
_ = zw.Close()
_ = f.Close()
+4 -8
View File
@@ -189,19 +189,15 @@ func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, err
base = context.Background()
}
ctx, cancel := context.WithCancel(base)
id := tasks.start("recovery-download", name, "", cancel)
id := tasks.start("recovery-download", name, name, cancel)
a.emitLog(name, "Downloading Apple online recovery image (~1 GB) for "+name+"...")
go func() {
defer cancel()
res, err := ic.DownloadOnline(ctx, v, func(u installer.Update) {
switch u.Kind {
case installer.KindStep, installer.KindNote:
a.emitLog(name, u.Message)
}
tasks.update(id, u)
res, err := a.ensureInstallerForTask(ctx, id, "recovery-download", name, "online", v, func(dlCtx context.Context, onUpdate func(installer.Update)) (*installer.Result, error) {
return ic.DownloadOnline(dlCtx, v, onUpdate)
})
if err != nil {
if ctx.Err() != nil {
if errors.Is(err, context.Canceled) || ctx.Err() != nil {
a.emitLog(name, "Online recovery download paused; starting again continues where it stopped")
tasks.finish(id, "", context.Canceled)
} else {
+9 -11
View File
@@ -2,7 +2,6 @@ package app
import (
"context"
"fmt"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/i18n"
@@ -37,8 +36,10 @@ func (a *App) installGuideEnabled() bool {
func (a *App) guidePreferences() (i18n.Locale, installguide.Theme) {
a.mu.Lock()
defer a.mu.Unlock()
return a.cfg.Locale, a.themeMode
rawLoc := a.cfg.Locale
th := a.themeMode
a.mu.Unlock()
return i18n.EffectiveLocale(rawLoc), th
}
func (a *App) bindGuideEvents(ctx context.Context) {
@@ -83,6 +84,7 @@ func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manag
Name: name,
PID: uint32(pid),
Locale: loc,
GuestLang: d.GuestLang,
Kind: kind,
ToolsAttached: reims.HasGuestToolsArgs(d.ExtraArgs),
}
@@ -112,10 +114,8 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei
return ctx.Err()
}
}
if loc, _ := a.guidePreferences(); loc == i18n.ZhCN {
return fmt.Errorf("虚拟机 %s 的运行状态已改变", name)
}
return fmt.Errorf("the running instance of %s has changed", name)
loc, _ := a.guidePreferences()
return i18n.NewCodedError(loc, "E_GUIDE_INSTANCE_CHANGED", "guide.err.instance_changed", i18n.Vars{"name": name}, nil)
}
g.TypeText = func(text string) error {
if err := checkBoot(); err != nil {
@@ -151,10 +151,8 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei
stopped, err := a.restartVM(name)
if stopped && err != nil {
// The guest window has closed, so report start failures via the tray.
title := "Could not restart VM: " + name
if loc, _ := a.guidePreferences(); loc == i18n.ZhCN {
title = "未能重启虚拟机:" + name
}
loc, _ := a.guidePreferences()
title := i18n.M(loc, "guide.err.restart_failed", i18n.Vars{"name": name})
a.emitLog(name, title+": "+err.Error())
a.mu.Lock()
tm := a.trayMgr
+21 -10
View File
@@ -5,6 +5,7 @@ package app
import (
"context"
"errors"
"fmt"
"strings"
@@ -38,8 +39,9 @@ func (a *App) ListOfflineReleases() ([]installer.Release, error) {
}
// DownloadInstaller starts downloading an offline installer in the background
// and returns its task ID. A download already running for the same release is
// returned instead of starting another; CancelTask pauses it.
// and returns its task ID. A download already running for the same release
// (whether standalone or driven by VM creation) is returned instead of starting
// another; CancelTask pauses a standalone download.
func (a *App) DownloadInstaller(version string) (string, error) {
version = strings.TrimSpace(version)
if version == "" {
@@ -49,18 +51,22 @@ func (a *App) DownloadInstaller(version string) (string, error) {
if err != nil {
return "", err
}
for _, t := range tasks.list() {
if t.Kind == "installer-download" && t.Status == TaskRunning && strings.EqualFold(t.Subject, version) {
return t.ID, nil
}
}
a.ensureTaskEmitter()
base := a.ctx
if base == nil {
base = context.Background()
}
ctx, cancel := context.WithCancel(base)
id := tasks.start("installer-download", version, "", cancel)
var (
ctx context.Context
cancel context.CancelFunc
)
run, id, owned := installerDownloads.reserveOrFind("offline", version, "installer-download", func(initialPhase string) string {
ctx, cancel = context.WithCancel(base)
return tasks.startWithInstaller("installer-download", version, "", "offline", version, initialPhase, cancel)
})
if !owned {
return id, nil
}
a.emitLog("installer", "Downloading macOS "+version+" offline installer")
go func() {
defer cancel()
@@ -70,12 +76,17 @@ func (a *App) DownloadInstaller(version string) (string, error) {
a.emitLog("installer", u.Message)
}
tasks.update(id, u)
run.publish(u)
})
if ctx.Err() != nil && err != nil {
err = context.Canceled
}
installerDownloads.complete(run, res, err)
switch {
case err == nil:
a.emitLog("installer", "Installer ready: "+res.Image)
tasks.finish(id, res.Image, nil)
case ctx.Err() != nil:
case errors.Is(err, context.Canceled):
a.emitLog("installer", "Download paused; starting it again continues where it stopped")
tasks.finish(id, "", context.Canceled)
default:
+271
View File
@@ -0,0 +1,271 @@
package app
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"github.com/Nwflower/reims-go/internal/installer"
)
type installerDownloadFunc func(ctx context.Context, onUpdate func(installer.Update)) (*installer.Result, error)
// installerDownloadRun tracks one active in-process macOS installer download
// so standalone downloads, VM creations and online recovery fetches share
// progress, deduplicate the same release, and surface queueing cleanly.
type installerDownloadRun struct {
key string
kind string // "offline" | "online"
version string
ownerID string
ownerKind string // "installer-download" | "vm-create" | "recovery-download"
done chan struct{}
res *installer.Result
err error
mu sync.Mutex
phase string // TaskPhaseQueued | TaskPhaseDownloading
lastUpdate *installer.Update
subs map[int]func(installer.Update)
nextSub int
}
func (r *installerDownloadRun) currentPhase() string {
r.mu.Lock()
defer r.mu.Unlock()
return r.phase
}
func (r *installerDownloadRun) publish(u installer.Update) {
r.mu.Lock()
switch u.Kind {
case installer.KindNote:
if u.Message == installer.WaitingNote {
r.phase = TaskPhaseQueued
cp := u
r.lastUpdate = &cp
}
case installer.KindStep, installer.KindProgress:
r.phase = TaskPhaseDownloading
cp := u
r.lastUpdate = &cp
}
subs := make([]func(installer.Update), 0, len(r.subs))
for _, fn := range r.subs {
subs = append(subs, fn)
}
r.mu.Unlock()
for _, fn := range subs {
fn(u)
}
}
func (r *installerDownloadRun) subscribe(fn func(installer.Update)) (phase string, last *installer.Update, unsub func()) {
r.mu.Lock()
id := r.nextSub
r.nextSub++
r.subs[id] = fn
phase = r.phase
if r.lastUpdate != nil {
cp := *r.lastUpdate
last = &cp
}
r.mu.Unlock()
return phase, last, func() {
r.mu.Lock()
delete(r.subs, id)
r.mu.Unlock()
}
}
type installerCoordinator struct {
mu sync.Mutex
active map[string]*installerDownloadRun
}
func newInstallerCoordinator() *installerCoordinator {
return &installerCoordinator{active: map[string]*installerDownloadRun{}}
}
var installerDownloads = newInstallerCoordinator()
func installerDownloadKey(kind, version string) string {
k := strings.ToLower(strings.TrimSpace(kind))
v := strings.ToLower(strings.TrimSpace(version))
if k == "online" && v == "" {
v = "latest"
}
return k + ":" + v
}
// reserveOrFind atomically joins an existing download for (kind, version) or
// registers a new one owned by the task created via startTask.
func (c *installerCoordinator) reserveOrFind(kind, version, ownerKind string, startTask func(initialPhase string) string) (run *installerDownloadRun, taskID string, owned bool) {
key := installerDownloadKey(kind, version)
c.mu.Lock()
defer c.mu.Unlock()
if existing, ok := c.active[key]; ok {
return existing, existing.ownerID, false
}
phase := TaskPhaseDownloading
if len(c.active) > 0 {
phase = TaskPhaseQueued
}
taskID = startTask(phase)
run = &installerDownloadRun{
key: key,
kind: kind,
version: version,
ownerID: taskID,
ownerKind: ownerKind,
done: make(chan struct{}),
phase: phase,
subs: map[int]func(installer.Update){},
}
c.active[key] = run
return run, taskID, true
}
// acquireOrJoin joins an existing active download for (kind, version) or
// registers taskID as the owner of a new download run.
func (c *installerCoordinator) acquireOrJoin(kind, version, taskID, ownerKind string) (run *installerDownloadRun, owned bool) {
run, _, owned = c.reserveOrFind(kind, version, ownerKind, func(string) string {
return taskID
})
return run, owned
}
func (c *installerCoordinator) complete(run *installerDownloadRun, res *installer.Result, err error) {
run.res = res
run.err = err
c.mu.Lock()
if c.active[run.key] == run {
delete(c.active, run.key)
}
c.mu.Unlock()
close(run.done)
}
func (c *installerCoordinator) hasActive(kind, version string) bool {
c.mu.Lock()
defer c.mu.Unlock()
_, ok := c.active[installerDownloadKey(kind, version)]
return ok
}
// ensureInstallerForTask runs or joins an installer download for an already
// started task (vm-create or recovery-download), mirroring progress into the
// task and clearing its installer phase as soon as the download completes.
func (a *App) ensureInstallerForTask(
ctx context.Context,
taskID, ownerKind, logSource, kind, version string,
download installerDownloadFunc,
) (*installer.Result, error) {
for {
run, owned := installerDownloads.acquireOrJoin(kind, version, taskID, ownerKind)
if owned {
tasks.setInstaller(taskID, kind, version, run.currentPhase())
var (
res *installer.Result
err error
)
completed := false
defer func() {
if !completed {
installerDownloads.complete(run, nil, errors.New("installer download aborted unexpectedly"))
}
}()
res, err = download(ctx, func(u installer.Update) {
switch u.Kind {
case installer.KindStep, installer.KindNote:
a.emitLog(logSource, u.Message)
}
tasks.update(taskID, u)
run.publish(u)
})
if ctx.Err() != nil && err != nil {
err = context.Canceled
}
completed = true
installerDownloads.complete(run, res, err)
if err == nil {
tasks.clearInstallerPhase(taskID)
}
return res, err
}
// Gate live subscriber updates until initial phase & last snapshot are
// applied so an interleaved publish cannot be overwritten backwards.
var subMu sync.Mutex
subMu.Lock()
phase, last, unsub := run.subscribe(func(u installer.Update) {
subMu.Lock()
defer subMu.Unlock()
tasks.update(taskID, u)
})
tasks.setInstaller(taskID, kind, version, phase)
if last != nil {
tasks.update(taskID, *last)
}
subMu.Unlock()
a.emitLog(logSource, fmt.Sprintf("Waiting for in-progress %s installer download (%s)...", kind, version))
select {
case <-ctx.Done():
unsub()
return nil, context.Canceled
case <-run.done:
unsub()
if run.err == nil {
tasks.clearInstallerPhase(taskID)
return run.res, nil
}
if errors.Is(run.err, context.Canceled) {
// Pausing a standalone download stops any VM creation waiting on it
// cleanly; if another VM creation owned the download and was canceled,
// take over the download while this task is still active.
if run.ownerKind == "installer-download" || ctx.Err() != nil {
return nil, context.Canceled
}
continue
}
return nil, run.err
}
}
}
func hasCompleteCachedInstaller(items []installer.Cached, kind, version string) bool {
kind = strings.ToLower(strings.TrimSpace(kind))
version = strings.TrimSpace(version)
if version == "" {
return false
}
for _, c := range items {
if c.Partial || !strings.EqualFold(c.Kind, kind) {
continue
}
switch kind {
case "offline":
if c.Version != "" && strings.EqualFold(c.Version, version) {
return true
}
case "online":
if !strings.EqualFold(version, "latest") && matchesOnlineInstallerTitle(c.Title, version) {
return true
}
}
}
return false
}
func matchesOnlineInstallerTitle(title, target string) bool {
t := strings.ToLower(strings.TrimSpace(target))
if t == "" {
return false
}
name := strings.ToLower(strings.TrimSpace(title))
name = strings.TrimPrefix(name, "macos ")
return name == t || strings.ReplaceAll(name, " ", "-") == t
}
+271
View File
@@ -0,0 +1,271 @@
package app
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/installer"
)
func newTestCoordinator(t *testing.T) {
t.Helper()
old := installerDownloads
installerDownloads = newInstallerCoordinator()
t.Cleanup(func() { installerDownloads = old })
}
func TestTaskInstallerPhaseTransitions(t *testing.T) {
sent := newTestTasks(t)
id := tasks.startWithInstaller("installer-download", "15.8.3", "", "offline", "15.8.3", TaskPhaseQueued, func() {})
if got := (*sent)[len(*sent)-1]; got.InstallerPhase != TaskPhaseQueued || got.Step != installer.WaitingNote || got.InstallerKind != "offline" || got.InstallerVersion != "15.8.3" {
t.Fatalf("initial queued task = %+v", got)
}
tasks.update(id, installer.Update{Kind: installer.KindStep, Message: "downloading macOS 15.8.3", Percent: -1})
if got := (*sent)[len(*sent)-1]; got.InstallerPhase != TaskPhaseDownloading || got.Step != "downloading macOS 15.8.3" {
t.Fatalf("after step = %+v", got)
}
tasks.update(id, installer.Update{Kind: installer.KindProgress, Done: 50, Total: 100, Percent: 50})
tasks.update(id, installer.Update{Kind: installer.KindNote, Message: installer.WaitingNote, Percent: -1})
if got := (*sent)[len(*sent)-1]; got.InstallerPhase != TaskPhaseQueued || got.Percent != -1 || got.Done != 0 {
t.Fatalf("after waiting note = %+v", got)
}
tasks.update(id, installer.Update{Kind: installer.KindProgress, Done: 60, Total: 100, Percent: 60})
if got := (*sent)[len(*sent)-1]; got.InstallerPhase != TaskPhaseDownloading || got.Percent != 60 {
t.Fatalf("resumed progress = %+v", got)
}
tasks.clearInstallerPhase(id)
if got := (*sent)[len(*sent)-1]; got.Status != TaskRunning || got.InstallerPhase != "" || got.Percent != -1 {
t.Fatalf("after clearInstallerPhase = %+v", got)
}
tasks.finish(id, "", nil)
if got := (*sent)[len(*sent)-1]; got.Status != TaskDone || got.InstallerPhase != "" {
t.Fatalf("final task = %+v", got)
}
}
func TestInstallerCoordinatorForwardDedupAndQueueing(t *testing.T) {
newTestTasks(t)
newTestCoordinator(t)
vmTaskID := tasks.start("vm-create", "macos-tahoe", "macos-tahoe", func() {})
run1, owned1 := installerDownloads.acquireOrJoin("offline", "26.7.3", vmTaskID, "vm-create")
if !owned1 || run1.currentPhase() != TaskPhaseDownloading {
t.Fatalf("run1 owned=%v phase=%q", owned1, run1.currentPhase())
}
// Duplicate DownloadInstaller for the same version returns the vm-create task ID.
startedDup := false
_, dupID, dupOwned := installerDownloads.reserveOrFind("offline", "26.7.3", "installer-download", func(string) string {
startedDup = true
return "should-not-create"
})
if dupOwned || startedDup || dupID != vmTaskID {
t.Fatalf("dup owned=%v started=%v id=%q want %q", dupOwned, startedDup, dupID, vmTaskID)
}
// A different version starts queued because another download is already active.
var secondPhase string
run2, id2, owned2 := installerDownloads.reserveOrFind("offline", "15.8.3", "installer-download", func(phase string) string {
secondPhase = phase
return tasks.startWithInstaller("installer-download", "15.8.3", "", "offline", "15.8.3", phase, func() {})
})
if !owned2 || secondPhase != TaskPhaseQueued || run2.currentPhase() != TaskPhaseQueued || id2 == "" {
t.Fatalf("second run owned=%v phase=%q id=%q", owned2, secondPhase, id2)
}
installerDownloads.complete(run1, &installer.Result{Version: "26.7.3"}, nil)
installerDownloads.complete(run2, &installer.Result{Version: "15.8.3"}, nil)
}
func TestInstallerCoordinatorReverseJoinAndIndependentVMCancel(t *testing.T) {
sent := newTestTasks(t)
newTestCoordinator(t)
a := &App{}
// Standalone manual download is already running at 40%.
dlID := tasks.startWithInstaller("installer-download", "26.7.3", "", "offline", "26.7.3", TaskPhaseDownloading, func() {})
dlRun, owned := installerDownloads.acquireOrJoin("offline", "26.7.3", dlID, "installer-download")
if !owned {
t.Fatal("expected standalone download to own run")
}
u40 := installer.Update{Kind: installer.KindProgress, Step: "downloading macOS Tahoe 26.7.3", Done: 400, Total: 1000, Percent: 40}
tasks.update(dlID, u40)
dlRun.publish(u40)
// VM creation joins the in-progress download and mirrors 40% immediately.
vmCtx, vmCancel := context.WithCancel(context.Background())
vmID := tasks.start("vm-create", "macos-tahoe", "macos-tahoe", vmCancel)
var downloadCalls atomic.Int32
done := make(chan error, 1)
go func() {
_, err := a.ensureInstallerForTask(vmCtx, vmID, "vm-create", "macos-tahoe", "offline", "26.7.3", func(context.Context, func(installer.Update)) (*installer.Result, error) {
downloadCalls.Add(1)
return &installer.Result{}, nil
})
done <- err
}()
// Wait until vm-create mirrors progress.
deadline := time.Now().Add(2 * time.Second)
mirrored := false
for time.Now().Before(deadline) {
for _, task := range tasks.list() {
if task.ID == vmID && task.InstallerVersion == "26.7.3" && task.Percent == 40 {
mirrored = true
break
}
}
if mirrored {
break
}
time.Sleep(10 * time.Millisecond)
}
if !mirrored {
t.Fatalf("vm-create did not mirror in-progress download: %+v", *sent)
}
// Canceling vm-create stops only the VM creation; the standalone download remains active.
vmCancel()
select {
case err := <-done:
if !errors.Is(err, context.Canceled) {
t.Fatalf("vm-create err = %v, want context.Canceled", err)
}
case <-time.After(2 * time.Second):
t.Fatal("vm-create did not exit after cancel")
}
if downloadCalls.Load() != 0 {
t.Fatalf("joiner invoked download func %d times", downloadCalls.Load())
}
if !installerDownloads.hasActive("offline", "26.7.3") {
t.Fatal("standalone download was unexpectedly cleared when vm-create canceled")
}
// A second VM creation joins and receives completion cleanly when standalone finishes.
vm2ID := tasks.start("vm-create", "macos-tahoe-2", "macos-tahoe-2", func() {})
done2 := make(chan error, 1)
go func() {
res, err := a.ensureInstallerForTask(context.Background(), vm2ID, "vm-create", "macos-tahoe-2", "offline", "26.7.3", func(context.Context, func(installer.Update)) (*installer.Result, error) {
downloadCalls.Add(1)
return nil, errors.New("should not download directly")
})
if err == nil && (res == nil || res.Image != "C:/ok.img") {
err = errors.New("missing result image")
}
done2 <- err
}()
time.Sleep(30 * time.Millisecond)
installerDownloads.complete(dlRun, &installer.Result{Version: "26.7.3", Image: "C:/ok.img"}, nil)
select {
case err := <-done2:
if err != nil {
t.Fatalf("vm2 err = %v", err)
}
case <-time.After(2 * time.Second):
t.Fatal("vm2 did not finish after standalone completed")
}
for _, task := range tasks.list() {
if task.ID == vm2ID && task.InstallerPhase != "" {
t.Fatalf("vm2 installer_phase was not cleared: %+v", task)
}
}
}
func TestInstallerCoordinatorPauseStandaloneCancelsWaitingVMAndTakeoverOnVMCancel(t *testing.T) {
newTestTasks(t)
newTestCoordinator(t)
a := &App{}
// Case 1: Pausing a standalone download cancels a VM creation waiting on it.
dlID := tasks.startWithInstaller("installer-download", "26.7.3", "", "offline", "26.7.3", TaskPhaseDownloading, func() {})
dlRun, _ := installerDownloads.acquireOrJoin("offline", "26.7.3", dlID, "installer-download")
vm1ID := tasks.start("vm-create", "vm-1", "vm-1", func() {})
done1 := make(chan error, 1)
go func() {
_, err := a.ensureInstallerForTask(context.Background(), vm1ID, "vm-create", "vm-1", "offline", "26.7.3", func(context.Context, func(installer.Update)) (*installer.Result, error) {
return nil, errors.New("must not restart after explicit pause")
})
done1 <- err
}()
time.Sleep(30 * time.Millisecond)
installerDownloads.complete(dlRun, nil, context.Canceled)
if err := <-done1; !errors.Is(err, context.Canceled) {
t.Fatalf("waiting vm err = %v, want context.Canceled", err)
}
// Case 2: If VM A owns the download and is canceled, waiting VM B takes over.
vmAID := tasks.start("vm-create", "vm-a", "vm-a", func() {})
vmARun, _ := installerDownloads.acquireOrJoin("offline", "26.7.3", vmAID, "vm-create")
vmBID := tasks.start("vm-create", "vm-b", "vm-b", func() {})
var takeoverCalls atomic.Int32
doneB := make(chan error, 1)
go func() {
res, err := a.ensureInstallerForTask(context.Background(), vmBID, "vm-create", "vm-b", "offline", "26.7.3", func(ctx context.Context, onUpdate func(installer.Update)) (*installer.Result, error) {
takeoverCalls.Add(1)
onUpdate(installer.Update{Kind: installer.KindProgress, Done: 100, Total: 100, Percent: 100})
return &installer.Result{Version: "26.7.3", Image: "C:/taken.img"}, nil
})
if err == nil && (res == nil || res.Image != "C:/taken.img") {
err = errors.New("missing takeover result")
}
doneB <- err
}()
time.Sleep(30 * time.Millisecond)
installerDownloads.complete(vmARun, nil, context.Canceled)
select {
case err := <-doneB:
if err != nil {
t.Fatalf("takeover err = %v", err)
}
case <-time.After(2 * time.Second):
t.Fatal("vm-b did not take over after vm-a canceled")
}
if takeoverCalls.Load() != 1 {
t.Fatalf("takeover calls = %d, want 1", takeoverCalls.Load())
}
}
func TestHasCompleteCachedInstallerAndCreateTarget(t *testing.T) {
items := []installer.Cached{
{Kind: "offline", Title: "macOS Tahoe", Version: "26.7.3", Partial: true},
{Kind: "offline", Title: "macOS Sequoia", Version: "15.8.3", Partial: false},
{Kind: "online", Title: "macOS Tahoe", Partial: false},
}
if hasCompleteCachedInstaller(items, "offline", "26.7.3") {
t.Fatal("partial offline installer must not count as complete")
}
if !hasCompleteCachedInstaller(items, "offline", "15.8.3") {
t.Fatal("complete offline installer not recognized")
}
if hasCompleteCachedInstaller(items, "offline", "latest") {
t.Fatal("symbolic latest must not bypass reims-util")
}
if !hasCompleteCachedInstaller(items, "online", "tahoe") {
t.Fatal("complete online installer for tahoe not recognized")
}
if hasCompleteCachedInstaller(items, "online", "latest") {
t.Fatal("online latest must not skip resolution")
}
if k, v := createInstallerTarget(reims.CreateOpts{SourceMode: "offline", MacOS: "26.7.3", Offline: true}); k != "offline" || v != "26.7.3" {
t.Fatalf("offline target = %q, %q", k, v)
}
if k, v := createInstallerTarget(reims.CreateOpts{SourceMode: "apple", MacOS: "tahoe"}); k != "online" || v != "tahoe" {
t.Fatalf("apple target = %q, %q", k, v)
}
if k, v := createInstallerTarget(reims.CreateOpts{SourceMode: "installer", Installer: "C:/a.img", MacOS: "26.7.3"}); k != "" || v != "" {
t.Fatalf("local installer should not trigger download: %q, %q", k, v)
}
if k, v := createInstallerTarget(reims.CreateOpts{SourceMode: "disk", Disk: "C:/d.qcow2", MacOS: "26.7.3"}); k != "" || v != "" {
t.Fatalf("existing disk should not trigger download: %q, %q", k, v)
}
}
+30
View File
@@ -0,0 +1,30 @@
package app
import "sync"
// LicenseTexts holds the embedded LICENSE and NOTICE.md texts bundled into the
// executable so users can inspect them offline from the About page.
type LicenseTexts struct {
License string `json:"license"`
Notice string `json:"notice"`
}
var embeddedLicenses struct {
mu sync.RWMutex
data LicenseTexts
}
// RegisterLicenseTexts stores the repository's LICENSE and NOTICE.md text
// embedded by package main.
func RegisterLicenseTexts(license, notice string) {
embeddedLicenses.mu.Lock()
embeddedLicenses.data = LicenseTexts{License: license, Notice: notice}
embeddedLicenses.mu.Unlock()
}
// GetLicenseTexts returns the embedded Apache-2.0 LICENSE and NOTICE.md texts.
func (a *App) GetLicenseTexts() LicenseTexts {
embeddedLicenses.mu.RLock()
defer embeddedLicenses.mu.RUnlock()
return embeddedLicenses.data
}
+175 -7
View File
@@ -56,6 +56,7 @@ func (a *App) initPlugins() {
HostVersion: version.Version,
SafeMode: safeMode,
RedactFn: reims.RedactText,
LocaleFn: a.locale,
Logger: func(source, line string) {
a.emitLog(source, line)
},
@@ -201,6 +202,7 @@ func (a *App) shutdownPlugins() {
a.mu.Lock()
mgr := a.pluginMgr
a.pluginMgr = nil
a.pluginMarket = nil
a.mu.Unlock()
i18n.SetPluginCatalogs(nil)
if mgr != nil {
@@ -208,6 +210,50 @@ func (a *App) shutdownPlugins() {
}
}
func (a *App) getPluginMarket() *plugin.MarketClient {
a.mu.Lock()
defer a.mu.Unlock()
if a.pluginMarket != nil {
return a.pluginMarket
}
dataRoot := ""
if a.cfg != nil {
dataRoot = a.cfg.DataRoot
}
a.pluginMarket = plugin.NewMarketClient(plugin.MarketClientOptions{
Layout: plugin.NewPluginsLayout(dataRoot),
HostVersion: version.Version,
})
return a.pluginMarket
}
// reloadPlugins tears down the existing Plugin Manager (if running) and
// re-initializes plugins and language packs against the current a.cfg.DataRoot.
func (a *App) reloadPlugins() {
a.mu.Lock()
hadPlugins := a.pluginMgr != nil
hasCtx := a.ctx != nil
ib := a.imeBridge
a.imeBridge = nil
a.mu.Unlock()
if ib != nil {
ib.Close()
}
if !hadPlugins && !hasCtx {
// Headless unit test without initialized app runtime: load static locale packs only.
a.mu.Lock()
dr := ""
if a.cfg != nil {
dr = a.cfg.DataRoot
}
a.mu.Unlock()
plugin.LoadStaticLocalePacks(dr)
return
}
a.shutdownPlugins()
a.initPlugins()
}
func (a *App) syncLocales() {
a.mu.Lock()
mgr := a.pluginMgr
@@ -216,8 +262,25 @@ func (a *App) syncLocales() {
i18n.SetPluginCatalogs(nil)
return
}
_, backendPacks := mgr.ResolvedLocalePacks()
uiPacks, backendPacks := mgr.ResolvedLocalePacks()
if len(uiPacks) > 0 {
if backendPacks == nil {
backendPacks = make(map[i18n.Locale]i18n.PluginCatalog)
}
for _, up := range uiPacks {
if !up.HasUIMessages {
continue
}
loc := i18n.Locale(up.Locale)
if _, exists := backendPacks[loc]; !exists {
backendPacks[loc] = i18n.PluginCatalog{
Fallback: i18n.Locale(up.Fallback),
}
}
}
}
i18n.SetPluginCatalogs(backendPacks)
go mgr.NotifyLocaleChanged(mgr.CurrentLocale())
}
func (a *App) syncRuntimeKinds(kr *rt.KindRegistry, reg *plugin.Registry) {
@@ -229,6 +292,7 @@ func (a *App) syncRuntimeKinds(kr *rt.KindRegistry, reg *plugin.Registry) {
activeKinds[rk.Kind] = true
_ = kr.Register(rt.KindSpec{
Kind: rk.Kind,
Name: rk.Name,
NameZh: rk.Name.ZhCN,
NameEn: rk.Name.EnUS,
RequiredFiles: rk.RequiredFiles,
@@ -466,7 +530,7 @@ func (a *App) ListPlugins() []plugin.PluginInfo {
if mgr == nil {
return nil
}
return mgr.Registry().List()
return mgr.LocalizePluginInfos(mgr.Registry().List())
}
func (a *App) InstallPluginArchive(archivePath string) (*plugin.PluginInfo, error) {
@@ -571,11 +635,11 @@ func (a *App) GetPluginUIContributions() PluginUIContributions {
out := PluginUIContributions{
SafeMode: mgr.SafeMode(),
CrashDetected: mgr.CrashDetected(),
Menus: reg.Menus(""),
VMCards: reg.VMCards(),
SettingsPages: reg.SettingsPages(),
StatusItems: reg.StatusItems(),
Panels: reg.Panels(""),
Menus: mgr.LocalizeMenus(reg.Menus("")),
VMCards: mgr.LocalizeVMCards(reg.VMCards()),
SettingsPages: mgr.LocalizeSettingsPages(reg.SettingsPages()),
StatusItems: mgr.LocalizeStatusItems(reg.StatusItems()),
Panels: mgr.LocalizePanels(reg.Panels("")),
VMTemplates: reg.VMTemplates(),
Themes: reg.Themes(),
Locales: uiLocales,
@@ -780,6 +844,96 @@ func (a *App) DoctorPlugin(pluginID string) []plugin.DoctorFinding {
return plugin.DoctorDirectory(info.InstallDir, version.Version, nil)
}
// InspectPluginArchive runs the unified static security scanner on a local .zip
// package before installing it so the UI can display hard blockers, capabilities,
// and L3 native execution notices.
func (a *App) InspectPluginArchive(archivePath string) (plugin.ScanReport, error) {
a.mu.Lock()
mgr := a.pluginMgr
dataRoot := ""
if a.cfg != nil {
dataRoot = a.cfg.DataRoot
}
a.mu.Unlock()
tmpDir := plugin.NewPluginsLayout(dataRoot).TmpDir()
if mgr != nil {
tmpDir = mgr.Layout().TmpDir()
}
return plugin.ScanArchive(archivePath, tmpDir, version.Version, plugin.ScanOptions{})
}
// ScanInstalledPlugin runs the unified static risk report against an installed
// or dev-linked plugin directory.
func (a *App) ScanInstalledPlugin(pluginID string) (plugin.ScanReport, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return plugin.ScanReport{}, errors.New("plugin manager not initialized")
}
info, ok := mgr.Registry().Info(pluginID)
if !ok {
return plugin.ScanReport{}, fmt.Errorf("plugin %q not found", pluginID)
}
if info.InstallDir == "" {
return plugin.ScanReport{
PluginID: info.ID,
Version: info.Version,
Name: info.Name,
Tier: info.Tier,
Trust: info.Trust,
Publisher: info.Publisher,
License: info.License,
Passed: true,
Headline: plugin.LocalizedText{
ZhCN: "内置插件状态正常",
EnUS: "Built-in plugin is healthy",
},
}, nil
}
rep := plugin.ScanDirectory(info.InstallDir, version.Version, plugin.ScanOptions{})
if info.Trust == plugin.TrustDev {
rep.Trust = plugin.TrustDev
}
return rep, nil
}
// BrowsePluginMarket lazily queries the remote/cached/fallback plugin market
// index (never called at app startup, §8.1, §9).
func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh bool) plugin.MarketBrowseResult {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
var installed []plugin.PluginInfo
if mgr != nil {
installed = mgr.Registry().List()
}
return a.getPluginMarket().Browse(context.Background(), installed, plugin.MarketBrowseOptions{
Query: query,
Kind: kind,
IncludeAlpha: includeAlpha,
ForceRefresh: forceRefresh,
})
}
// InstallMarketPlugin downloads, verifies SHA-256, static-scans, and installs
// a plugin from the market index.
func (a *App) InstallMarketPlugin(pluginID string, includeAlpha bool) (*plugin.PluginInfo, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil, errors.New("plugin manager not initialized")
}
info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, plugin.MarketInstallOptions{
IncludeAlpha: includeAlpha,
})
if err == nil && a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return info, err
}
// PanelBridgeCall handles permission-checked, rate-limited, redacted Host API
// reads from sandboxed L4 iframe panels (§7.3).
func (a *App) PanelBridgeCall(pluginID, method string, params map[string]any) (any, error) {
@@ -800,6 +954,20 @@ func (a *App) PanelBridgeCall(pluginID, method string, params map[string]any) (a
return nil, fmt.Errorf("plugin %q has no active panel", pluginID)
}
switch method {
case "i18n.getBundle":
if err := mgr.Broker().AllowRate(pluginID); err != nil {
return nil, err
}
eff := mgr.CurrentLocale()
msgs := mgr.PluginL10nBundle(pluginID, eff)
if msgs == nil {
msgs = map[string]string{}
}
return map[string]any{
"locale": string(eff),
"dir": i18n.DirOf(eff),
"messages": msgs,
}, nil
case "vm.list":
if err := mgr.Broker().Authorize(pluginID, "vm:read"); err != nil {
return nil, err
+51 -43
View File
@@ -32,43 +32,35 @@ func (a *App) includeAlpha() bool {
return rt.NormalizeChannel(a.cfg.RuntimeChannel) == rt.ChannelAlpha
}
func (a *App) runtimeSource() string {
a.mu.Lock()
defer a.mu.Unlock()
return rt.NormalizeSource(a.cfg.RuntimeSource)
}
// remoteCache keeps the release list for a while: GitHub allows 60
// unauthenticated API requests an hour, and the host page, first launch and
// the CLI all ask for it.
var remoteCache struct {
sync.Mutex
at time.Time
alpha bool
source string
list []rt.Remote
at time.Time
alpha bool
list []rt.Remote
}
const remoteCacheTTL = 10 * time.Minute
// ListRemoteRuntimes lists published runtimes for the configured channel and source.
// ListRemoteRuntimes lists published runtimes for the configured channel.
func (a *App) ListRemoteRuntimes() ([]rt.Remote, error) {
alpha := a.includeAlpha()
source := a.runtimeSource()
remoteCache.Lock()
defer remoteCache.Unlock()
if remoteCache.list != nil && remoteCache.alpha == alpha && remoteCache.source == source && time.Since(remoteCache.at) < remoteCacheTTL {
if remoteCache.list != nil && remoteCache.alpha == alpha && time.Since(remoteCache.at) < remoteCacheTTL {
return remoteCache.list, nil
}
list, err := rt.DefaultSourceFor(source).ListRemote(a.baseCtx(), alpha)
list, err := rt.DefaultSource().ListRemote(a.baseCtx(), alpha)
if err != nil {
return nil, err
}
remoteCache.at, remoteCache.alpha, remoteCache.source, remoteCache.list = time.Now(), alpha, source, list
remoteCache.at, remoteCache.alpha, remoteCache.list = time.Now(), alpha, list
return list, nil
}
// forgetRemoteRuntimes drops the cached list (after an install or a channel/source change).
// forgetRemoteRuntimes drops the cached list (after an install or a channel change).
func forgetRemoteRuntimes() {
remoteCache.Lock()
remoteCache.list = nil
@@ -91,25 +83,6 @@ func (a *App) SetRuntimeChannel(channel string) error {
return config.Save("", a.cfg)
}
// SetRuntimeSource picks "auto", "github", or "gitcode" for online runtime and
// app update lookups.
func (a *App) SetRuntimeSource(source string) error {
switch strings.ToLower(strings.TrimSpace(source)) {
case "", rt.SourceAuto, rt.SourceGitHub, rt.SourceGitCode:
source = rt.NormalizeSource(source)
default:
return fmt.Errorf("unknown runtime source %q", source)
}
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.RuntimeSource = source
forgetRemoteRuntimes()
appUpdateCache.Lock()
appUpdateCache.info = nil
appUpdateCache.Unlock()
return config.Save("", a.cfg)
}
// InstallRuntimeOnline downloads, verifies and installs a published runtime
// ("" or "latest" for the newest on the channel) and makes it active. It runs
// in the background and returns the task ID; CancelTask pauses the download,
@@ -156,7 +129,7 @@ func (a *App) InstallRuntimeOnline(commit string) (string, error) {
}
func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, taskID string) (string, error) {
src := rt.DefaultSourceFor(cfg.RuntimeSource)
src := rt.DefaultSource()
step := func(msg string) {
a.emitLog("runtime", msg)
tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: msg, Percent: -1})
@@ -213,25 +186,60 @@ func percent(done, total int64) float64 {
var appUpdateCache struct {
sync.Mutex
at time.Time
info *version.UpdateInfo
at time.Time
channel string
info *version.UpdateInfo
}
// CheckAppUpdate checks GitHub Releases for a newer stable Reims-Go version.
// Results are cached for 10 minutes unless force is true.
// SetAppUpdateChannel picks "stable", "alpha", or "dev" for Reims-Go client
// updates. Selecting "alpha" or "dev" also preserves old executables and
// downloaded installers on startup so users can roll back safely.
func (a *App) SetAppUpdateChannel(channel string) error {
switch strings.ToLower(strings.TrimSpace(channel)) {
case version.ChannelStable, version.ChannelAlpha, version.ChannelDev:
channel = version.NormalizeChannel(channel)
default:
return fmt.Errorf("unknown app update channel %q", channel)
}
a.mu.Lock()
a.cfg.AppUpdateChannel = channel
err := config.Save("", a.cfg)
a.mu.Unlock()
if err != nil {
return err
}
appUpdateCache.Lock()
appUpdateCache.info = nil
appUpdateCache.channel = ""
appUpdateCache.Unlock()
appUpdateReady.Lock()
appUpdateReady.version, appUpdateReady.path, appUpdateReady.sha256 = "", "", ""
appUpdateReady.Unlock()
return nil
}
// CheckAppUpdate checks GitHub Releases for a newer Reims-Go version on the
// configured app update channel. Results are cached for 10 minutes unless force is true.
func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) {
source := a.runtimeSource()
a.mu.Lock()
ch := version.ChannelStable
if a.cfg != nil {
ch = version.NormalizeChannel(a.cfg.AppUpdateChannel)
}
a.mu.Unlock()
appUpdateCache.Lock()
defer appUpdateCache.Unlock()
if !force && appUpdateCache.info != nil && time.Since(appUpdateCache.at) < remoteCacheTTL {
if !force && appUpdateCache.info != nil && appUpdateCache.channel == ch && time.Since(appUpdateCache.at) < remoteCacheTTL {
return *appUpdateCache.info, nil
}
info, err := version.DefaultSourceFor(source).CheckUpdate(a.baseCtx(), version.Version)
info, err := version.DefaultSource().CheckUpdateChannel(a.baseCtx(), version.Version, ch)
if err != nil {
return info, err
}
copyInfo := info
appUpdateCache.at = time.Now()
appUpdateCache.channel = ch
appUpdateCache.info = &copyInfo
return info, nil
}
+9
View File
@@ -130,9 +130,18 @@ func (a *App) CompleteSetup(dir string) error {
return err
}
a.mu.Lock()
prevRoot := ""
if a.cfg != nil {
prevRoot = a.cfg.DataRoot
}
a.cfg = cfg
a.needsSetup = false
a.mu.Unlock()
if filepath.Clean(prevRoot) != filepath.Clean(dir) {
a.resetDataRootCaches()
a.reloadPlugins()
}
a.wakePoll()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
+19 -6
View File
@@ -7,6 +7,7 @@ import (
"strings"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -55,6 +56,18 @@ func (a *App) DeleteSnapshot(name, snapName string) error {
}
func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
loc := a.locale()
cleanSnap := strings.TrimSpace(snapName)
if cleanSnap == "" {
return i18n.NewCodedError(loc, "E_SNAPSHOT_NAME_EMPTY", "err.snapshot.name_empty", nil, nil)
}
if len([]rune(cleanSnap)) > 64 {
return i18n.NewCodedError(loc, "E_SNAPSHOT_NAME_TOO_LONG", "err.snapshot.name_too_long", nil, nil)
}
if _, err := reims.ValidateSnapshotName(cleanSnap); err != nil {
return i18n.NewCodedError(loc, "E_SNAPSHOT_NAME_INVALID", "err.snapshot.name_invalid", nil, err)
}
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
@@ -70,20 +83,20 @@ func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
return err
}
if a.isVMRunning(ctx, c, name, d) {
return fmt.Errorf("stop %s before managing restore points", name)
return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_RUNNING", "err.snapshot.vm_running", i18n.Vars{"name": name}, nil)
}
diskPath := resolveVMDiskPath(d)
if diskPath == "" {
return fmt.Errorf("VM %s has no disk path", name)
return i18n.NewCodedError(loc, "E_SNAPSHOT_NO_DISK", "err.clone.no_disk", i18n.Vars{"name": name}, nil)
}
if !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
return fmt.Errorf("restore points are only supported on .qcow2 disks")
return i18n.NewCodedError(loc, "E_SNAPSHOT_QCOW2_ONLY", "err.snapshot.qcow2_only", nil, nil)
}
env := rt.BuildChildEnv(&cfgCopy, *active)
if err := reims.RunDiskSnapshot(ctx, active.QemuImgPath(), env, flag, snapName, diskPath); err != nil {
return err
if err := reims.RunDiskSnapshot(ctx, active.QemuImgPath(), env, flag, cleanSnap, diskPath); err != nil {
return i18n.NewCodedError(loc, "E_SNAPSHOT_QEMU_IMG", "err.snapshot.qemu_img_failed", i18n.Vars{"snap": cleanSnap}, err)
}
a.emitLog(name, fmt.Sprintf("%s %q", verb, strings.TrimSpace(snapName)))
a.emitLog(name, fmt.Sprintf("%s %q", verb, cleanSnap))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
+7 -5
View File
@@ -164,15 +164,17 @@ func upsertSSHConfigBlock(cfgPath, vmName, alias string, port int, user string)
endMark := fmt.Sprintf("# <<< reims-go:%s <<<", vmName)
var block strings.Builder
block.WriteString(startMark + "\n")
block.WriteString(fmt.Sprintf("Host %s\n", alias))
block.WriteString(startMark)
block.WriteByte('\n')
fmt.Fprintf(&block, "Host %s\n", alias)
block.WriteString(" HostName 127.0.0.1\n")
block.WriteString(fmt.Sprintf(" Port %d\n", port))
fmt.Fprintf(&block, " Port %d\n", port)
if user != "" {
block.WriteString(fmt.Sprintf(" User %s\n", user))
fmt.Fprintf(&block, " User %s\n", user)
}
block.WriteString(" StrictHostKeyChecking accept-new\n")
block.WriteString(endMark + "\n")
block.WriteString(endMark)
block.WriteByte('\n')
existingBytes, err := os.ReadFile(cfgPath)
if err != nil && !os.IsNotExist(err) {
+6
View File
@@ -22,6 +22,9 @@ type VMStats struct {
DiskActualBytes uint64 `json:"disk_actual_bytes"`
DiskVirtualBytes uint64 `json:"disk_virtual_bytes"`
DiskFormat string `json:"disk_format,omitempty"`
DiskBackingDepth int `json:"disk_backing_depth,omitempty"`
DiskBackingBroken bool `json:"disk_backing_broken,omitempty"`
DiskBackingDepthWarn bool `json:"disk_backing_depth_warn,omitempty"`
UptimeSeconds int64 `json:"uptime_seconds"`
GuestToolsConnected bool `json:"guest_tools_connected"`
GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"`
@@ -75,6 +78,9 @@ func (a *App) GetVMStats(name string) (VMStats, error) {
stats.DiskActualBytes = du.ActualBytes
stats.DiskVirtualBytes = du.VirtualBytes
stats.DiskFormat = du.Format
stats.DiskBackingDepth = du.BackingDepth
stats.DiskBackingBroken = du.BackingBroken
stats.DiskBackingDepthWarn = du.BackingDepth >= host.BackingChainWarnDepth || du.BackingBroken
}
}
+101 -18
View File
@@ -6,6 +6,7 @@ package app
import (
"context"
"errors"
"fmt"
"io"
"sort"
@@ -23,25 +24,31 @@ const (
TaskDone = "done"
TaskFailed = "failed"
TaskCanceled = "canceled"
TaskPhaseQueued = "queued"
TaskPhaseDownloading = "downloading"
)
// Task is one tracked job as the frontend sees it.
type Task struct {
ID string `json:"id"`
Kind string `json:"kind"` // "installer-download" | "vm-create"
Subject string `json:"subject"` // release ("26.7.1") or VM name
VM string `json:"vm,omitempty"`
Step string `json:"step"` // upstream wording, e.g. "downloading OpenCore 1.0.8"
Done int64 `json:"done"`
Total int64 `json:"total"` // 0 when unknown
Percent float64 `json:"percent"` // -1 when unknown
Rate float64 `json:"rate"` // bytes per second, 0 when unknown
Status string `json:"status"`
Error string `json:"error,omitempty"`
Result string `json:"result,omitempty"`
Cancelable bool `json:"cancelable"`
StartedAt int64 `json:"started_at"` // unix ms
UpdatedAt int64 `json:"updated_at"`
ID string `json:"id"`
Kind string `json:"kind"` // "installer-download" | "recovery-download" | "vm-create" | "runtime-install" | "app-update"
Subject string `json:"subject"` // release ("26.7.3") or VM name
VM string `json:"vm,omitempty"`
InstallerKind string `json:"installer_kind,omitempty"` // "offline" | "online" while an installer download is attached
InstallerVersion string `json:"installer_version,omitempty"` // release ("26.7.3") or online target ("tahoe" / "latest")
InstallerPhase string `json:"installer_phase,omitempty"` // "queued" | "downloading" while active
Step string `json:"step"` // upstream wording, e.g. "downloading OpenCore 1.0.8"
Done int64 `json:"done"`
Total int64 `json:"total"` // 0 when unknown
Percent float64 `json:"percent"` // -1 when unknown
Rate float64 `json:"rate"` // bytes per second, 0 when unknown
Status string `json:"status"`
Error string `json:"error,omitempty"`
Result string `json:"result,omitempty"`
Cancelable bool `json:"cancelable"`
StartedAt int64 `json:"started_at"` // unix ms
UpdatedAt int64 `json:"updated_at"`
}
type taskEntry struct {
@@ -69,14 +76,23 @@ const emitInterval = 200 * time.Millisecond
const finishedTTL = 10 * time.Minute
func (m *taskManager) start(kind, subject, vm string, cancel context.CancelFunc) string {
return m.startWithInstaller(kind, subject, vm, "", "", "", cancel)
}
func (m *taskManager) startWithInstaller(kind, subject, vm, installerKind, installerVersion, installerPhase string, cancel context.CancelFunc) string {
m.mu.Lock()
m.seq++
id := fmt.Sprintf("%s-%d", kind, m.seq)
now := time.Now().UnixMilli()
step := ""
if installerPhase == TaskPhaseQueued {
step = installer.WaitingNote
}
e := &taskEntry{
task: Task{
ID: id, Kind: kind, Subject: subject, VM: vm,
Percent: -1, Status: TaskRunning, Cancelable: cancel != nil,
InstallerKind: installerKind, InstallerVersion: installerVersion, InstallerPhase: installerPhase,
Step: step, Percent: -1, Status: TaskRunning, Cancelable: cancel != nil,
StartedAt: now, UpdatedAt: now,
},
cancel: cancel,
@@ -89,6 +105,50 @@ func (m *taskManager) start(kind, subject, vm string, cancel context.CancelFunc)
return id
}
// setInstaller attaches installer download metadata and phase to a running task.
func (m *taskManager) setInstaller(id, kind, version, phase string) {
m.mu.Lock()
e, ok := m.tasks[id]
if !ok || e.task.Status != TaskRunning {
m.mu.Unlock()
return
}
e.task.InstallerKind = kind
e.task.InstallerVersion = version
e.task.InstallerPhase = phase
if phase == TaskPhaseQueued {
e.task.Step = installer.WaitingNote
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
e.rate = rateMeter{}
}
e.task.UpdatedAt = time.Now().UnixMilli()
t := e.task
m.mu.Unlock()
m.send(t)
}
// clearInstallerPhase marks a task's installer download stage complete while
// keeping the task running for any remaining work (e.g. OpenCore / disk creation).
func (m *taskManager) clearInstallerPhase(id string) {
m.mu.Lock()
e, ok := m.tasks[id]
if !ok || e.task.Status != TaskRunning {
m.mu.Unlock()
return
}
if e.task.InstallerPhase == "" {
m.mu.Unlock()
return
}
e.task.InstallerPhase = ""
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
e.rate = rateMeter{}
e.task.UpdatedAt = time.Now().UnixMilli()
t := e.task
m.mu.Unlock()
m.send(t)
}
// update applies an upstream progress report to the task.
func (m *taskManager) update(id string, u installer.Update) {
m.mu.Lock()
@@ -99,12 +159,34 @@ func (m *taskManager) update(id string, u installer.Update) {
}
force := false
switch u.Kind {
case installer.KindNote:
if u.Message != installer.WaitingNote || e.task.InstallerKind == "" {
m.mu.Unlock()
return
}
if e.task.InstallerPhase == TaskPhaseQueued && e.task.Step == u.Message {
m.mu.Unlock()
return
}
e.task.InstallerPhase = TaskPhaseQueued
e.task.Step = u.Message
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
e.rate = rateMeter{}
force = true
case installer.KindStep:
force = e.task.Step != u.Message
if e.task.InstallerPhase == TaskPhaseQueued {
e.task.InstallerPhase = TaskPhaseDownloading
force = true
}
force = force || e.task.Step != u.Message
e.task.Step = u.Message
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
e.rate = rateMeter{}
case installer.KindProgress:
if e.task.InstallerPhase == TaskPhaseQueued {
e.task.InstallerPhase = TaskPhaseDownloading
force = true
}
if u.Step != "" && u.Step != e.task.Step {
e.task.Step = u.Step
e.rate = rateMeter{}
@@ -142,12 +224,13 @@ func (m *taskManager) finish(id string, result string, err error) {
if e.task.Total > 0 {
e.task.Done, e.task.Percent = e.task.Total, 100
}
case err == context.Canceled || strings.Contains(err.Error(), context.Canceled.Error()):
case errors.Is(err, context.Canceled) || strings.Contains(err.Error(), context.Canceled.Error()):
e.task.Status = TaskCanceled
default:
e.task.Status = TaskFailed
e.task.Error = err.Error()
}
e.task.InstallerPhase = ""
e.task.Cancelable = false
e.task.Rate = 0
e.task.UpdatedAt = time.Now().UnixMilli()
+38 -62
View File
@@ -67,10 +67,6 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
}{id: myID, cancel: cancel}
vmMonitors.mu.Unlock()
a.mu.Lock()
loc := a.cfg.Locale
a.mu.Unlock()
go func() {
defer func() {
cancel()
@@ -107,6 +103,7 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
case <-ctx.Done():
return
case <-logTicker.C:
loc := a.locale()
for _, line := range serial.read(serialPath) {
a.emitPluginLogLine(name, "serial", line)
if key, msg := parseSerialMilestone(loc, line); msg != "" && !seenEvents[key] {
@@ -127,13 +124,10 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
}
}
case <-hbTicker.C:
loc := a.locale()
pid, running := a.currentVMPID(ctx, name)
if !running {
if loc == i18n.ZhCN {
a.emitLog(name, "[状态] 虚拟机进程已退出")
} else {
a.emitLog(name, "[state] VM process exited")
}
a.emitLog(name, i18n.T(loc, "monitor.exited"))
return
}
now := time.Now()
@@ -177,11 +171,7 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
}
if idleStreak >= 3 && !stallWarned {
stallWarned = true
if loc == i18n.ZhCN {
a.emitLog(name, "[警告] 连续 90 秒几乎无 CPU 与磁盘写入,虚拟机可能停在启动或重启阶段;可切到「QEMU」页签排查,或下次引导时按住 Win+V 查看内核输出")
} else {
a.emitLog(name, "[warn] Almost no CPU or disk activity for 90s; VM may be stalled during boot/reboot. Check the QEMU log tab or hold Win+V on next boot for verbose output")
}
a.emitLog(name, i18n.T(loc, "monitor.stall_warn"))
}
}
}
@@ -272,15 +262,9 @@ func (t *logTail) read(path string) []string {
func parseSerialMilestone(loc i18n.Locale, line string) (key, msg string) {
switch {
case strings.Contains(line, "BdsDxe: starting Boot"):
if loc == i18n.ZhCN {
return "serial:boot", "[引导] UEFI 正在启动 OpenCore 引导程序"
}
return "serial:boot", "[boot] UEFI starting OpenCore bootloader"
return "serial:boot", i18n.T(loc, "monitor.serial.boot")
case strings.Contains(line, "#[EB|LOG:HANDOFF TO XNU]"), strings.Contains(line, "End of efiboot serial output"):
if loc == i18n.ZhCN {
return "serial:xnu", "[引导] OpenCore 已交接 macOS 内核(XNU 正在加载系统与驱动)"
}
return "serial:xnu", "[boot] OpenCore handed off to macOS kernel (XNU loading)"
return "serial:xnu", i18n.T(loc, "monitor.serial.xnu")
default:
return "", ""
}
@@ -296,28 +280,16 @@ func parseQemuMilestone(loc i18n.Locale, line string) (key, msg string) {
if semi := strings.IndexByte(rest, ';'); semi >= 0 {
rest = rest[:semi]
}
if loc == i18n.ZhCN {
return "qemu:gpu", "[图形] vGPU 已初始化:" + strings.TrimSpace(rest)
}
return "qemu:gpu", "[gpu] vGPU initialized: " + strings.TrimSpace(rest)
return "qemu:gpu", i18n.M(loc, "monitor.qemu.gpu", i18n.Vars{"device": strings.TrimSpace(rest)})
}
if strings.Contains(line, "windows open through SDL") {
if loc == i18n.ZhCN {
return "qemu:window", "[窗口] 虚拟机显示窗口已打开"
}
return "qemu:window", "[window] VM display window opened"
return "qemu:window", i18n.T(loc, "monitor.qemu.window")
}
if strings.Contains(line, "the device was reset") {
if loc == i18n.ZhCN {
return "qemu:reset", "[图形] vGPU 设备已重置"
}
return "qemu:reset", "[gpu] vGPU device reset"
return "qemu:reset", i18n.T(loc, "monitor.qemu.reset")
}
if strings.Contains(line, "the control completion ring is full") {
if loc == i18n.ZhCN {
return "qemu:ring-full", "[图形] 图形事件环短暂阻塞(常见于抹除硬盘或大块磁盘写入期间),请稍候 10–30 秒等待自动恢复,无需强制关闭"
}
return "qemu:ring-full", "[gpu] Graphics completion ring briefly stalled (typical during disk erase or heavy disk I/O); wait 10–30s for it to recover automatically"
return "qemu:ring-full", i18n.T(loc, "monitor.qemu.ring_full")
}
// Known benign WHPX advisories: keep out of the activity log so they don't look like errors.
if strings.Contains(line, "no pre-fault of the pool") ||
@@ -337,21 +309,24 @@ func parseQemuMilestone(loc i18n.Locale, line string) (key, msg string) {
func formatBootHeartbeat(loc i18n.Locale, elapsed time.Duration, diskBytes, diskDelta int64, cpuPct float64) string {
dur := fmt.Sprintf("%dm%02ds", int(elapsed.Minutes()), int(elapsed.Seconds())%60)
diskStr := fmt.Sprintf("%.2f GB", float64(diskBytes)/(1024*1024*1024))
diskStr := i18n.FormatNumber(loc, float64(diskBytes)/(1024*1024*1024), 2) + " GB"
deltaStr := ""
if diskDelta >= 1024*1024 {
deltaStr = fmt.Sprintf(" (+%.1f MB)", float64(diskDelta)/(1024*1024))
}
if loc == i18n.ZhCN {
if cpuPct >= 0 {
return fmt.Sprintf("[状态] 运行中(%s)· 磁盘占用 %s%s · QEMU CPU %.0f%%", dur, diskStr, deltaStr, cpuPct)
}
return fmt.Sprintf("[状态] 运行中(%s)· 磁盘占用 %s%s", dur, diskStr, deltaStr)
deltaStr = " (+" + i18n.FormatNumber(loc, float64(diskDelta)/(1024*1024), 1) + " MB)"
}
if cpuPct >= 0 {
return fmt.Sprintf("[state] Running (%s) · disk %s%s · QEMU CPU %.0f%%", dur, diskStr, deltaStr, cpuPct)
return i18n.M(loc, "monitor.heartbeat.cpu", i18n.Vars{
"dur": dur,
"disk": diskStr,
"delta": deltaStr,
"cpu": cpuPct,
})
}
return fmt.Sprintf("[state] Running (%s) · disk %s%s", dur, diskStr, deltaStr)
return i18n.M(loc, "monitor.heartbeat.nocpu", i18n.Vars{
"dur": dur,
"disk": diskStr,
"delta": deltaStr,
})
}
func fileSizeBytes(path string) int64 {
@@ -364,10 +339,11 @@ func fileSizeBytes(path string) int64 {
func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Report, qmpAddr string) {
a.mu.Lock()
loc := a.cfg.Locale
rawLoc := a.cfg.Locale
rtCommit := a.cfg.ActiveRuntime
pinPCores := a.cfg.AutoPinPCores
a.mu.Unlock()
loc := i18n.EffectiveLocale(rawLoc)
if rtCommit == "" {
rtCommit = "auto"
}
@@ -380,19 +356,19 @@ func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Repo
irqMode = "on"
}
pinStr := vmstart.AffinitySummary(loc, rep, detail.Directory, pinPCores, detail.CPUs)
if loc == i18n.ZhCN {
coldStr := "关闭"
if qmpAddr != "" {
coldStr = "开启"
}
a.emitLog(name, fmt.Sprintf("[启动] 运行时 %s · %d 核 / %s(可用提交内存 %.1f GB)· 图形 %s · 磁盘 %s · irqchip=%s · 核心映射=%s · Win10冷重启=%s",
rtCommit, detail.CPUs, detail.Memory, rep.CommitAvailGB, detail.Graphics, strings.ToUpper(detail.DiskController), irqMode, pinStr, coldStr))
return
}
coldStr := "off"
coldStr := i18n.T(loc, "monitor.start.off")
if qmpAddr != "" {
coldStr = "on"
coldStr = i18n.T(loc, "monitor.start.on")
}
a.emitLog(name, fmt.Sprintf("[start] runtime %s · %d vCPU / %s (commit free %.1f GB) · graphics %s · disk %s · irqchip=%s · affinity=%s · Win10-cold-reboot=%s",
rtCommit, detail.CPUs, detail.Memory, rep.CommitAvailGB, detail.Graphics, strings.ToUpper(detail.DiskController), irqMode, pinStr, coldStr))
a.emitLog(name, i18n.M(loc, "monitor.start.summary", i18n.Vars{
"rt": rtCommit,
"cpus": detail.CPUs,
"mem": detail.Memory,
"avail": rep.CommitAvailGB,
"gfx": detail.Graphics,
"disk": strings.ToUpper(detail.DiskController),
"irq": irqMode,
"pin": pinStr,
"cold": coldStr,
}))
}
+148 -81
View File
@@ -3,6 +3,7 @@ package cli
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
@@ -17,6 +18,7 @@ import (
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/opencore"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
@@ -29,8 +31,10 @@ import (
// Main runs one command and returns the process exit code.
func Main(args []string) int {
if err := run(args); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
i18n.SetDetailRedactor(reims.RedactText)
loc, err := run(args)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", i18n.FormatCLIError(loc, err))
return 1
}
return 0
@@ -43,12 +47,15 @@ func IsCommand(args []string) bool {
return !isWindow
}
func run(args []string) error {
func run(args []string) (i18n.Locale, error) {
fs := flag.NewFlagSet("reims-go", flag.ContinueOnError)
langFlag := fs.String("lang", "", "UI/CLI language: zh-CN | en-US")
fs.SetOutput(io.Discard)
langFlag := fs.String("lang", "", "UI/CLI language: auto | zh-CN | en-US | <BCP-47> | en-XA")
dataRootFlag := fs.String("data-root", "", "Override reims-go data root directory")
helpFlag := fs.Bool("help", false, "Show CLI usage")
hFlag := fs.Bool("h", false, "Show CLI usage")
if err := fs.Parse(args); err != nil {
return err
return i18n.Detect(), err
}
cfgPath := ""
@@ -57,104 +64,81 @@ func run(args []string) error {
}
cfg, err := config.Load(cfgPath)
if err != nil {
return err
return i18n.Detect(), err
}
if *dataRootFlag != "" {
cfg.DataRoot = *dataRootFlag
}
// Load enabled static language packs from <DataRoot>/plugins before resolving
// effective locale so "auto" and custom --lang tags (e.g. ja-JP, zh-TW) work in CLI.
plugin.LoadStaticLocalePacks(cfg.DataRoot)
if *langFlag != "" {
cfg.Locale = i18n.Normalize(*langFlag)
cfg.Locale = i18n.ParsePreference(*langFlag)
}
loc := cfg.Locale
loc := i18n.EffectiveLocale(cfg.Locale)
cfg.Locale = loc
rest := fs.Args()
if len(rest) == 0 {
if len(rest) == 0 || *helpFlag || *hFlag {
printUsage(loc)
return nil
return loc, nil
}
switch rest[0] {
case "doctor":
return cmdDoctor(cfg, loc, rest[1:])
return loc, cmdDoctor(cfg, loc, rest[1:])
case "runtime":
return cmdRuntime(cfg, loc, rest[1:])
return loc, cmdRuntime(cfg, loc, rest[1:])
case "vm":
return cmdVM(cfg, loc, rest[1:], *dataRootFlag == "")
return loc, cmdVM(cfg, loc, rest[1:], *dataRootFlag == "")
case "installer":
return cmdInstaller(cfg, loc, rest[1:])
return loc, cmdInstaller(cfg, loc, rest[1:])
case "plugin":
return cmdPlugin(cfg, loc, rest[1:])
return loc, cmdPlugin(cfg, loc, rest[1:])
case "version", "-v", "--version":
fmt.Printf("reims-go %s\n", version.Version)
return nil
return loc, nil
case "help", "-h", "--help":
printUsage(loc)
return nil
return loc, nil
default:
return fmt.Errorf("unknown command %q", rest[0])
return loc, fmt.Errorf("unknown command %q", rest[0])
}
}
func printUsage(loc i18n.Locale) {
if loc == i18n.ZhCN {
fmt.Println("reims-go - Windows 一站式免编译 reims-vgpu 启动器")
fmt.Println("\n用法:")
fmt.Println(" reims-go 打开界面(--background:只在托盘运行,不显示窗口)")
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <命令> [参数]")
fmt.Println("\n 在交互式 PowerShell / cmd 中提示符会先返回;要等命令结束并拿到退出码,请加 | Out-Host 或用管道。")
fmt.Println("\n命令:")
fmt.Println(" doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)")
fmt.Println(" runtime available 列出 GitHub 上发布的运行时(--alpha 含 alpha 版)")
fmt.Println(" runtime fetch [commit] 在线下载、校验并安装运行时(默认最新;Ctrl+C 暂停,再次运行续传)")
fmt.Println(" runtime install <archive> 导入并校验本地运行时包(.tar.zst 或 .zip)")
fmt.Println(" runtime list 查看已安装的便携运行时版本")
fmt.Println(" runtime use <commit> 切换当前激活运行时")
fmt.Println(" vm list 列出已创建的虚拟机")
fmt.Println(" vm create [options] <name> 创建 macOS 虚拟机(可指定目录/核数/内存/硬盘/显卡)")
fmt.Println(" vm set [options] <name> 修改虚拟机配置(下次启动生效)")
fmt.Println(" vm resize <name> <大小> 停机扩容虚拟磁盘(如 256G 或 +64G)")
fmt.Println(" vm compact <name> 停机回收 .qcow2 磁盘未用空间")
fmt.Println(" vm start <name> 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动")
fmt.Println(" vm stop|eject <name> 停止 / 弹出安装盘")
fmt.Println(" vm type <name> [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)")
fmt.Println(" installer list 列出 Apple 提供的离线安装包版本(需联网)")
fmt.Println(" installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)")
fmt.Println(" installer cached 查看已下载的安装包及占用空间")
fmt.Println(" installer delete <文件名> 删除已下载的安装包(正在使用或下载中的会被拒绝)")
fmt.Println(" plugin list|install|link|enable|disable|remove|info|doctor|run")
fmt.Println(" 管理内置扩展与第三方插件(含主题与驱动)")
fmt.Println(" version 查看当前版本")
return
fmt.Println(i18n.T(loc, "cli.usage.header"))
fmt.Println("\n" + i18n.T(loc, "cli.usage.section_usage"))
fmt.Println(i18n.T(loc, "cli.usage.line_gui"))
fmt.Println(i18n.T(loc, "cli.usage.line_cmd"))
fmt.Println("\n" + i18n.T(loc, "cli.usage.ps_hint"))
fmt.Println("\n" + i18n.T(loc, "cli.usage.section_commands"))
for _, k := range []string{
"cli.usage.cmd_doctor",
"cli.usage.cmd_rt_avail",
"cli.usage.cmd_rt_fetch",
"cli.usage.cmd_rt_install",
"cli.usage.cmd_rt_list",
"cli.usage.cmd_rt_use",
"cli.usage.cmd_rt_remove",
"cli.usage.cmd_vm_list",
"cli.usage.cmd_vm_create",
"cli.usage.cmd_vm_set",
"cli.usage.cmd_vm_resize",
"cli.usage.cmd_vm_compact",
"cli.usage.cmd_vm_start",
"cli.usage.cmd_vm_stop",
"cli.usage.cmd_vm_type",
"cli.usage.cmd_inst_list",
"cli.usage.cmd_inst_dl",
"cli.usage.cmd_inst_cached",
"cli.usage.cmd_inst_del",
"cli.usage.cmd_plugin",
"cli.usage.cmd_version",
} {
fmt.Println(i18n.T(loc, k))
}
fmt.Println("reims-go - Portable one-stop reims-vgpu launcher for Windows")
fmt.Println("\nUsage:")
fmt.Println(" reims-go Open the window (--background: tray only, no window)")
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <command> [args]")
fmt.Println("\n Interactive PowerShell / cmd return to the prompt early; pipe the output (e.g. | Out-Host)")
fmt.Println(" to wait for the command and get its exit code.")
fmt.Println("\nCommands:")
fmt.Println(" doctor Inspect host (WHPX / Vulkan GPUs / P-E cores / disk / runtime)")
fmt.Println(" runtime available List runtimes published on GitHub (--alpha includes alpha builds)")
fmt.Println(" runtime fetch [commit] Download, verify and install a runtime (newest by default; Ctrl+C pauses)")
fmt.Println(" runtime install <archive> Verify and install a local runtime package (.tar.zst or .zip)")
fmt.Println(" runtime list List installed portable runtimes")
fmt.Println(" runtime use <commit> Activate an installed runtime version")
fmt.Println(" vm list List virtual machines")
fmt.Println(" vm create [options] <name> Create a macOS VM (custom dir, CPUs, RAM, disk size, GPU)")
fmt.Println(" vm set [options] <name> Update VM settings (applies on next start)")
fmt.Println(" vm resize <name> <size> Expand stopped VM disk (e.g. 256G or +64G)")
fmt.Println(" vm compact <name> Compact stopped .qcow2 disk to reclaim unused space")
fmt.Println(" vm start <name> Start a VM in the Reims-Go window process (launched in the tray if needed),")
fmt.Println(" with clipboard and shared folders; with --data-root it starts in this process")
fmt.Println(" vm stop|eject <name> Stop / eject installer")
fmt.Println(" vm type <name> [text] Type text into a running VM as US-keyboard keys (stdin if no text)")
fmt.Println(" installer list List offline macOS installers Apple offers (needs network)")
fmt.Println(" installer download <ver> Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)")
fmt.Println(" installer cached List downloaded installers and the space they take")
fmt.Println(" installer delete <name> Delete a downloaded installer (refused if in use or downloading)")
fmt.Println(" plugin list|install|link|enable|disable|remove|info|doctor|run")
fmt.Println(" Manage built-in extensions and third-party plugins")
fmt.Println(" version Show current version")
}
func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
@@ -207,11 +191,38 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
} else {
fmt.Printf("%s:\n", i18n.T(loc, "doctor.gpu"))
for _, g := range rep.GPUs {
rec := ""
if rep.RecommendedGPU != nil && rep.RecommendedGPU.VulkanICD == g.VulkanICD {
rec = " [" + i18n.T(loc, "doctor.gpu.recommended") + "]"
tags := []string{}
if rep.RecommendedGPU != nil && sameGPU(rep.RecommendedGPU, &g) {
tags = append(tags, i18n.T(loc, "doctor.gpu.recommended"))
}
if g.Compat != "" {
tags = append(tags, i18n.T(loc, "doctor.gpu.compat."+string(g.Compat)))
}
tagStr := ""
if len(tags) > 0 {
tagStr = " [" + strings.Join(tags, " | ") + "]"
}
meta := []string{}
if g.VendorID != "" && g.DeviceID != "" {
meta = append(meta, g.VendorID+":"+g.DeviceID)
}
if g.VulkanVersion != "" {
meta = append(meta, "Vulkan "+g.VulkanVersion)
}
if g.DriverVersion != "" {
meta = append(meta, "drv "+g.DriverVersion)
}
metaStr := ""
if len(meta) > 0 {
metaStr = " (" + strings.Join(meta, ", ") + ")"
}
fmt.Printf(" - [%s] %s%s%s\n", g.Kind, g.Name, metaStr, tagStr)
if g.VulkanICD != "" {
fmt.Printf(" ICD: %s\n", g.VulkanICD)
}
if note := formatGPUCompatNote(loc, g); note != "" {
fmt.Printf(" ! %s\n", note)
}
fmt.Printf(" - [%s] %s%s\n ICD: %s\n", g.Kind, g.Name, rec, g.VulkanICD)
}
}
@@ -220,12 +231,49 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
} else {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.active", active.Commit, active.Dir))
}
if len(rep.DeepBackingChains) > 0 {
fmt.Printf("%s:\n", i18n.T(loc, "doctor.cow_chain"))
for _, c := range rep.DeepBackingChains {
if c.Broken {
fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.broken", c.VMName, c.Depth, c.Path))
} else {
fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.item", c.VMName, c.Depth, host.BackingChainWarnDepth))
}
}
}
return nil
}
func sameGPU(a, b *host.GPUInfo) bool {
if a == nil || b == nil {
return false
}
if a.VendorID != "" && a.DeviceID != "" && b.VendorID != "" && b.DeviceID != "" {
return a.VendorID == b.VendorID && a.DeviceID == b.DeviceID
}
return a.VulkanICD != "" && a.VulkanICD == b.VulkanICD && a.Name == b.Name
}
func formatGPUCompatNote(loc i18n.Locale, g host.GPUInfo) string {
switch g.CompatCode {
case "amd_legacy_win_driver":
return i18n.T(loc, "doctor.gpu.warn.amd_legacy", g.CompatDetail)
case "amd_rdna2_device_lost":
return i18n.T(loc, "doctor.gpu.warn.amd_rdna2", g.CompatDetail)
case "vulkan_too_old":
return i18n.T(loc, "doctor.gpu.err.vulkan_too_old", g.CompatDetail)
case "vulkan_missing_extensions":
return i18n.T(loc, "doctor.gpu.err.missing_ext", g.CompatDetail)
case "vulkan_cpu":
return i18n.T(loc, "doctor.gpu.err.vulkan_cpu")
default:
return ""
}
}
func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go runtime <available|fetch|install|list|use>")
return fmt.Errorf("usage: reims-go runtime <available|fetch|install|list|use|remove>")
}
switch args[0] {
case "install":
@@ -287,6 +335,25 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
}
}
return fmt.Errorf("%s", i18n.T(loc, "runtime.not_found", args[1]))
case "remove", "rm", "delete":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go runtime remove <commit>")
}
inst, err := rt.Remove(cfg, args[1])
if err != nil {
switch {
case errors.Is(err, rt.ErrNotFound):
return fmt.Errorf("%s", i18n.T(loc, "runtime.not_found", args[1]))
case errors.Is(err, rt.ErrRemoveActive):
return fmt.Errorf("%s", i18n.T(loc, "runtime.remove_active", args[1]))
case errors.Is(err, rt.ErrRuntimeInUse):
return fmt.Errorf("%s", i18n.T(loc, "runtime.remove_in_use", args[1]))
default:
return err
}
}
fmt.Println(i18n.T(loc, "runtime.removed", inst.Commit, inst.Dir))
return nil
case "available":
return cmdRuntimeAvailable(cfg, loc, args[1:])
case "fetch":
+346 -21
View File
@@ -24,6 +24,9 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
HostVersion: version.Version,
SafeMode: safeMode,
RedactFn: reims.RedactText,
LocaleFn: func() i18n.Locale {
return i18n.EffectiveLocale(cfg.Locale)
},
Logger: func(source, line string) {
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
},
@@ -66,16 +69,89 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
}
_ = mgr.LoadExternal()
mgr.Registry().Reconcile(context.Background())
mgr.MarkBootComplete()
return mgr, router, nil
}
func openCLIMarketClient(cfg *config.Config) *plugin.MarketClient {
return plugin.NewMarketClient(plugin.MarketClientOptions{
Layout: plugin.NewPluginsLayout(cfg.DataRoot),
HostVersion: version.Version,
})
}
func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go plugin <list|install|link|enable|disable|remove|info|doctor|run>")
return fmt.Errorf("usage: reims-go plugin <list|search|install|update|link|enable|disable|remove|info|doctor|locale|run>")
}
ctx := context.Background()
switch args[0] {
case "search":
fs := flag.NewFlagSet("plugin search", flag.ContinueOnError)
kind := fs.String("kind", "", "Filter by plugin kind (theme, locale, driver, tool, template, runtime)")
includeAlpha := fs.Bool("alpha", false, "Include alpha channel plugins")
refresh := fs.Bool("refresh", false, "Bypass cache and refresh market index")
asJSON := fs.Bool("json", false, "Output JSON")
if err := fs.Parse(args[1:]); err != nil {
return err
}
mgr, _, err := openCLIPluginManager(cfg, true)
if err != nil {
return err
}
defer mgr.Close()
mc := openCLIMarketClient(cfg)
query := strings.TrimSpace(strings.Join(fs.Args(), " "))
res := mc.Browse(ctx, mgr.Registry().List(), plugin.MarketBrowseOptions{
Query: query,
Kind: *kind,
IncludeAlpha: *includeAlpha,
ForceRefresh: *refresh,
})
if *asJSON {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(res)
}
if res.Stale && res.FetchError != "" {
fmt.Fprintf(os.Stderr, "[warn] %s (%s)\n", i18n.T(loc, "plugin.market.stale_warn"), res.FetchError)
}
for _, w := range res.WithdrawnInstalled {
fmt.Fprintf(os.Stderr, "[warn] %s: %s", w.ID, w.Reason.Get(string(loc)))
if w.InsteadID != "" {
fmt.Fprintf(os.Stderr, " -> %s", w.InsteadID)
}
fmt.Fprintln(os.Stderr)
}
if len(res.Items) == 0 {
fmt.Println(i18n.T(loc, "plugin.market.empty"))
return nil
}
for _, it := range res.Items {
status := it.Entry.Channel
switch {
case it.Withdrawn != nil:
status = "withdrawn"
case !it.Compatible:
status = "incompat"
case it.UpdateAvailable:
status = "update:" + it.InstalledVersion + "->" + it.Entry.Version
case it.Installed:
status = "installed"
}
kindLabel := it.Entry.Kind
if kindLabel == "" {
kindLabel = string(it.Entry.Tier)
}
if kindLabel == "" {
kindLabel = "-"
}
fmt.Printf("%-34s %-10s %-8s %-9s %-18s %s\n",
it.Entry.ID, it.Entry.Version, kindLabel, it.Entry.Trust, status, it.Entry.Name.Get(string(loc)))
}
return nil
case "list":
fs := flag.NewFlagSet("plugin list", flag.ContinueOnError)
asJSON := fs.Bool("json", false, "Output JSON")
@@ -87,7 +163,7 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
return err
}
defer mgr.Close()
list := mgr.Registry().List()
list := mgr.LocalizePluginInfos(mgr.Registry().List())
if *asJSON {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
@@ -95,9 +171,10 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
}
for _, p := range list {
mark := " "
if p.State == plugin.StateActive {
switch p.State {
case plugin.StateActive:
mark = "*"
} else if p.State == plugin.StateDegraded || p.State == plugin.StateFailed {
case plugin.StateDegraded, plugin.StateFailed:
mark = "!"
}
fmt.Printf("%s %-34s %-8s %-8s %-9s %-8s %s\n",
@@ -106,15 +183,39 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
return nil
case "install":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go plugin install <archive.zip>")
fs := flag.NewFlagSet("plugin install", flag.ContinueOnError)
includeAlpha := fs.Bool("alpha", false, "Allow alpha channel when installing by market plugin ID")
refresh := fs.Bool("refresh", false, "Refresh market index before installing")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go plugin install [--alpha] [--refresh] <archive.zip|plugin-id>")
}
target := fs.Arg(0)
mgr, _, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
info, err := mgr.InstallLocalArchive(ctx, args[1], plugin.PackageInstallOptions{})
isLocalFile := false
if st, statErr := os.Stat(target); statErr == nil && !st.IsDir() {
isLocalFile = true
} else if strings.HasSuffix(strings.ToLower(target), ".zip") || strings.ContainsAny(target, `/\`) {
isLocalFile = true
}
var info *plugin.PluginInfo
if isLocalFile {
info, err = mgr.InstallLocalArchive(ctx, target, plugin.PackageInstallOptions{})
} else {
mc := openCLIMarketClient(cfg)
info, err = mc.InstallFromMarket(ctx, mgr, target, plugin.MarketInstallOptions{
IncludeAlpha: *includeAlpha,
ForceRefresh: *refresh,
})
}
if err != nil {
return err
}
@@ -124,6 +225,60 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
}
return nil
case "update":
fs := flag.NewFlagSet("plugin update", flag.ContinueOnError)
includeAlpha := fs.Bool("alpha", false, "Allow alpha channel updates")
refresh := fs.Bool("refresh", true, "Refresh market index before checking updates")
if err := fs.Parse(args[1:]); err != nil {
return err
}
mgr, _, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
mc := openCLIMarketClient(cfg)
if fs.NArg() > 0 {
id := fs.Arg(0)
if _, ok := mgr.Registry().Info(id); !ok {
return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", id))
}
info, uErr := mc.InstallFromMarket(ctx, mgr, id, plugin.MarketInstallOptions{
IncludeAlpha: *includeAlpha,
ForceRefresh: *refresh,
})
if uErr != nil {
return uErr
}
fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier))
if info.NeedsApproval {
fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID))
}
return nil
}
updates, browse := mc.CheckUpdates(ctx, mgr.Registry().List(), *includeAlpha, *refresh)
if browse.Stale && browse.FetchError != "" {
fmt.Fprintf(os.Stderr, "[warn] %s (%s)\n", i18n.T(loc, "plugin.market.stale_warn"), browse.FetchError)
}
if len(updates) == 0 {
fmt.Println(i18n.T(loc, "plugin.market.up_to_date"))
return nil
}
for _, up := range updates {
info, uErr := mc.InstallFromMarket(ctx, mgr, up.Entry.ID, plugin.MarketInstallOptions{
IncludeAlpha: *includeAlpha,
ForceRefresh: false,
})
if uErr != nil {
return fmt.Errorf("update %s: %w", up.Entry.ID, uErr)
}
fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier))
if info.NeedsApproval {
fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID))
}
}
return nil
case "link":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go plugin link <dir>")
@@ -216,6 +371,7 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
case "doctor":
fs := flag.NewFlagSet("plugin doctor", flag.ContinueOnError)
contractPath := fs.String("contract", "", "Optional path to ui-contract.json for CSS validation")
asJSON := fs.Bool("json", false, "Output structured ScanReport JSON")
if err := fs.Parse(args[1:]); err != nil {
return err
}
@@ -231,15 +387,26 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
}
contract = &c
}
scanOpts := plugin.ScanOptions{Contract: contract}
target := ""
if fs.NArg() > 0 {
target = fs.Arg(0)
}
// If target is an existing directory, validate it directly (developer workflow, §5.1).
// Direct directory or .zip archive inspection (developer & market CI workflow, §5.1).
if target != "" {
if st, err := os.Stat(target); err == nil && st.IsDir() {
findings := plugin.DoctorDirectory(target, version.Version, contract)
return printDoctorFindings(loc, findings)
if st, err := os.Stat(target); err == nil {
if st.IsDir() {
rep := plugin.ScanDirectory(target, version.Version, scanOpts)
return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON)
}
if strings.HasSuffix(strings.ToLower(target), ".zip") {
layout := plugin.NewPluginsLayout(cfg.DataRoot)
rep, sErr := plugin.ScanArchive(target, layout.TmpDir(), version.Version, scanOpts)
if sErr != nil {
return sErr
}
return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON)
}
}
}
mgr, _, err := openCLIPluginManager(cfg, false)
@@ -253,25 +420,49 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
return fmt.Errorf("%s", i18n.T(loc, "plugin.target_not_found", target))
}
if info.InstallDir == "" {
if *asJSON {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(plugin.ScanReport{
PluginID: info.ID,
Version: info.Version,
Name: info.Name,
Tier: info.Tier,
Trust: info.Trust,
Passed: true,
Headline: plugin.LocalizedText{
ZhCN: "内置插件状态正常",
EnUS: "Built-in plugin is healthy",
},
})
}
fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State)
return nil
}
return printDoctorFindings(loc, plugin.DoctorDirectory(info.InstallDir, version.Version, contract))
rep := plugin.ScanDirectory(info.InstallDir, version.Version, scanOpts)
return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON)
}
// Audit all installed external plugins.
var allFindings []plugin.DoctorFinding
var reports []plugin.ScanReport
for _, info := range mgr.Registry().List() {
if info.InstallDir != "" {
allFindings = append(allFindings, plugin.DoctorDirectory(info.InstallDir, version.Version, contract)...)
} else {
allFindings = append(allFindings, plugin.DoctorFinding{
Severity: "ok",
Check: info.ID,
Message: fmt.Sprintf("%s@%s state=%s", info.ID, info.Version, info.State),
})
reports = append(reports, plugin.ScanDirectory(info.InstallDir, version.Version, scanOpts))
}
}
return printDoctorFindings(loc, allFindings)
if len(reports) == 0 {
if *asJSON {
fmt.Println("[]")
return nil
}
for _, info := range mgr.Registry().List() {
fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State)
}
return nil
}
return printScanReports(loc, reports, *asJSON)
case "locale":
return cmdPluginLocale(loc, args[1:])
case "run":
if len(args) < 3 {
@@ -303,6 +494,42 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
}
}
func printScanReports(loc i18n.Locale, reports []plugin.ScanReport, asJSON bool) error {
hasErr := false
for _, r := range reports {
if r.HardBlocked {
hasErr = true
}
}
if asJSON {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if len(reports) == 1 {
if err := enc.Encode(reports[0]); err != nil {
return err
}
} else {
if err := enc.Encode(reports); err != nil {
return err
}
}
if hasErr {
return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors"))
}
return nil
}
for i, r := range reports {
if i > 0 {
fmt.Println("---")
}
fmt.Println(r.SummaryText(string(loc)))
}
if hasErr {
return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors"))
}
return nil
}
func printDoctorFindings(loc i18n.Locale, findings []plugin.DoctorFinding) error {
hasErr := false
for _, f := range findings {
@@ -316,3 +543,101 @@ func printDoctorFindings(loc i18n.Locale, findings []plugin.DoctorFinding) error
}
return nil
}
func cmdPluginLocale(loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go plugin locale <init|check> ...")
}
switch args[0] {
case "init":
// Allow flags either before or after the positional <bcp47-locale> argument.
var flagArgs, posArgs []string
rest := args[1:]
for i := 0; i < len(rest); i++ {
a := rest[i]
if strings.HasPrefix(a, "-") {
flagArgs = append(flagArgs, a)
if !strings.Contains(a, "=") && i+1 < len(rest) && !strings.HasPrefix(rest[i+1], "-") {
i++
flagArgs = append(flagArgs, rest[i])
}
} else {
posArgs = append(posArgs, a)
}
}
fs := flag.NewFlagSet("plugin locale init", flag.ContinueOnError)
outDir := fs.String("out", "", "Output directory for the scaffolded language pack")
pluginID := fs.String("id", "", "Optional reverse-domain plugin ID (default: community.lang.<locale>)")
forPlugin := fs.String("for", "", "Optional target plugin ID to scaffold pluginOverrides for")
if err := fs.Parse(flagArgs); err != nil {
return err
}
posArgs = append(posArgs, fs.Args()...)
if len(posArgs) < 1 || strings.TrimSpace(*outDir) == "" {
return fmt.Errorf("usage: reims-go plugin locale init <bcp47-locale> --out <dir> [--id <plugin.id>] [--for <target.plugin>]")
}
if err := plugin.InitLocalePack(plugin.LocaleInitOptions{
Locale: posArgs[0],
OutDir: *outDir,
PluginID: *pluginID,
ForPlugin: *forPlugin,
}); err != nil {
return err
}
fmt.Printf("[ok] scaffolded language pack (%s) in %s\n", posArgs[0], *outDir)
return nil
case "check":
var flagArgs, posArgs []string
for _, a := range args[1:] {
if strings.HasPrefix(a, "-") {
flagArgs = append(flagArgs, a)
} else {
posArgs = append(posArgs, a)
}
}
fs := flag.NewFlagSet("plugin locale check", flag.ContinueOnError)
asJSON := fs.Bool("json", false, "Output structured JSON report")
if err := fs.Parse(flagArgs); err != nil {
return err
}
posArgs = append(posArgs, fs.Args()...)
if len(posArgs) < 1 {
return fmt.Errorf("usage: reims-go plugin locale check [--json] <dir>")
}
reports, findings, err := plugin.CheckLocalePack(posArgs[0])
if err != nil {
return err
}
if *asJSON {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(reports); err != nil {
return err
}
} else {
for _, rep := range reports {
fmt.Printf("Locale %s (%s): %d/%d translated (%.1f%%)\n",
rep.Locale, rep.PluginID, rep.TotalTranslated, rep.TotalReference, rep.TotalPercent)
for _, d := range rep.Domains {
fmt.Printf(" %-15s %4d/%-4d (%5.1f%%)\n", d.Domain, d.Translated, d.Total, d.Percent)
}
}
for _, f := range findings {
if f.Check == "locale-coverage" {
continue
}
fmt.Printf("[%s] (%s) %s\n", f.Severity, f.Check, f.Message)
}
}
for _, f := range findings {
if f.Severity == "error" {
return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors"))
}
}
return nil
default:
return fmt.Errorf("unknown plugin locale subcommand %q (expected init or check)", args[0])
}
}
+56
View File
@@ -0,0 +1,56 @@
package cli
import (
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
)
func TestCLIPluginLocaleInitAndCheck(t *testing.T) {
outDir := filepath.Join(t.TempDir(), "ko-pack")
if err := cmdPluginLocale(i18n.EnUS, []string{"init", "ko-KR", "--out", outDir}); err != nil {
t.Fatalf("plugin locale init failed: %v", err)
}
if _, err := os.Stat(filepath.Join(outDir, "plugin.json")); err != nil {
t.Fatalf("missing scaffolded plugin.json: %v", err)
}
if err := cmdPluginLocale(i18n.EnUS, []string{"check", outDir}); err != nil {
t.Fatalf("plugin locale check failed on scaffolded pack: %v", err)
}
// Also verify official zh-TW and ja-JP reference packs via CLI `plugin locale check`.
for _, rel := range []string{
filepath.Join("..", "plugin", "testdata", "official.lang.zh-tw"),
filepath.Join("..", "plugin", "testdata", "official.lang.ja-jp"),
} {
if err := cmdPluginLocale(i18n.EnUS, []string{"check", rel}); err != nil {
t.Fatalf("CLI check(%s) failed: %v", rel, err)
}
}
}
func TestCLILinkEnableActivatesStaticLocalePackWithoutCrashSentinel(t *testing.T) {
defer i18n.SetPluginCatalogs(nil)
dataRoot := t.TempDir()
jaDir, err := filepath.Abs(filepath.Join("..", "plugin", "testdata", "official.lang.ja-jp"))
if err != nil {
t.Fatal(err)
}
if code := Main([]string{"--data-root", dataRoot, "plugin", "link", jaDir}); code != 0 {
t.Fatalf("plugin link exit code = %d", code)
}
if code := Main([]string{"--data-root", dataRoot, "plugin", "enable", "official.lang.ja-jp"}); code != 0 {
t.Fatalf("plugin enable exit code = %d", code)
}
if plugin.DidLastStartupCrash(plugin.NewPluginsLayout(dataRoot).Root) {
t.Fatal("CLI plugin manager left .initializing crash sentinel behind")
}
loc, err := run([]string{"--data-root", dataRoot, "--lang", "ja-JP", "--help"})
if err != nil || loc != i18n.Locale("ja-JP") {
t.Fatalf("run(--lang ja-JP --help) = (%q, %v), want (ja-JP, nil)", loc, err)
}
}
+10 -18
View File
@@ -14,15 +14,14 @@ import (
rt "github.com/Nwflower/reims-go/internal/runtime"
)
// runtime available [--alpha] [--source auto|github|gitcode]: published runtimes.
// runtime available [--alpha]: published runtimes.
func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) error {
fs := flag.NewFlagSet("runtime available", flag.ContinueOnError)
alpha := alphaFlag(fs, cfg, "Include alpha runtimes")
source := fs.String("source", rt.NormalizeSource(cfg.RuntimeSource), "Download source: auto, github, or gitcode")
if err := fs.Parse(flagsFirst(args)); err != nil {
return err
}
list, err := rt.DefaultSourceFor(*source).ListRemote(context.Background(), *alpha)
list, err := rt.DefaultSource().ListRemote(context.Background(), *alpha)
if err != nil {
return err
}
@@ -30,7 +29,7 @@ func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) err
fmt.Println(i18n.T(loc, "runtime.remote.empty"))
return nil
}
fmt.Printf("%-12s %-10s %-8s %-11s %9s %s\n", "COMMIT", "CHANNEL", "SOURCE", "PUBLISHED", "SIZE", "INSTALLED")
fmt.Printf("%-12s %-10s %-11s %9s %s\n", "COMMIT", "CHANNEL", "PUBLISHED", "SIZE", "INSTALLED")
for _, r := range list {
mark := ""
if rt.IsInstalled(cfg, r.Commit) {
@@ -40,16 +39,15 @@ func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) err
if len(date) >= 10 {
date = date[:10]
}
fmt.Printf("%-12s %-10s %-8s %-11s %9s %s\n", r.Commit, r.Channel, r.Source, date, humanBytes(r.ArchiveSize), mark)
fmt.Printf("%-12s %-10s %-11s %9s %s\n", r.Commit, r.Channel, date, humanBytes(r.ArchiveSize), mark)
}
return nil
}
// runtime fetch [commit|latest] [--alpha] [--source auto|github|gitcode]: download, verify, install, activate.
// runtime fetch [commit|latest] [--alpha]: download, verify, install, activate.
func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
fs := flag.NewFlagSet("runtime fetch", flag.ContinueOnError)
alpha := alphaFlag(fs, cfg, "Allow alpha runtimes for \"latest\"")
source := fs.String("source", rt.NormalizeSource(cfg.RuntimeSource), "Download source: auto, github, or gitcode")
if err := fs.Parse(flagsFirst(args)); err != nil {
return err
}
@@ -58,7 +56,7 @@ func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
src := rt.DefaultSourceFor(*source)
src := rt.DefaultSource()
list, err := src.ListRemote(ctx, *alpha || explicit)
if err != nil {
return err
@@ -108,20 +106,14 @@ func alphaFlag(fs *flag.FlagSet, cfg *config.Config, usage string) *bool {
return v
}
// flagsFirst moves "-x" arguments (and their values for value flags like
// --source) before positional ones, so "fetch latest --source gitcode --alpha"
// works like "fetch --source gitcode --alpha latest" (the flag package stops
// at the first positional argument).
// flagsFirst moves "-x" arguments before positional ones, so
// "fetch latest --alpha" works like "fetch --alpha latest" (the flag package
// stops at the first positional argument).
func flagsFirst(args []string) []string {
var flags, rest []string
for i := 0; i < len(args); i++ {
a := args[i]
for _, a := range args {
if len(a) > 1 && a[0] == '-' {
flags = append(flags, a)
if (a == "-source" || a == "--source") && i+1 < len(args) {
i++
flags = append(flags, args[i])
}
} else {
rest = append(rest, a)
}
+8 -24
View File
@@ -40,6 +40,9 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s
// Preparation rewrites extra-args and the OpenCore image; never under a live VM.
return fmt.Errorf("%s", i18n.T(cfg.Locale, "vm.already_running", name))
}
if err := prep.CheckWHPX(rep); err != nil {
return err
}
if err := prep.CheckMemory(d.Memory, rep); err != nil {
return err
}
@@ -75,28 +78,19 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s
}
func startInWindow(ctx context.Context, cfg *config.Config, name string) error {
zh := cfg.Locale == i18n.ZhCN
if err := os.MkdirAll(cfg.TempDir(), 0o755); err != nil {
return err
}
result := filepath.Join(cfg.TempDir(), fmt.Sprintf("cli-start-%d.json", time.Now().UnixNano()))
w := WindowArgs{StartVM: name, StartResult: result}
if hwnd := findWindow(); hwnd != 0 {
if zh {
fmt.Fprintf(os.Stderr, "交给正在运行的 Reims-Go 启动 %s…\n", name)
} else {
fmt.Fprintf(os.Stderr, "Handing %s to the running Reims-Go...\n", name)
}
fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.handing_to_window", i18n.Vars{"name": name}))
if err := sendToWindow(hwnd, w.Args()); err != nil {
return err
}
} else {
w.Background = true
if zh {
fmt.Fprintf(os.Stderr, "在后台拉起 Reims-Go(托盘)来启动 %s…\n", name)
} else {
fmt.Fprintf(os.Stderr, "Starting Reims-Go in the tray to run %s...\n", name)
}
fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.spawning_tray", i18n.Vars{"name": name}))
if err := spawnWindow(w.Args()); err != nil {
return err
}
@@ -107,15 +101,9 @@ func startInWindow(ctx context.Context, cfg *config.Config, name string) error {
res, err := waitStartResult(ctx, result, startHandoffTimeout)
switch {
case errors.Is(err, context.Canceled):
if zh {
return fmt.Errorf("已停止等待;%s 仍由 Reims-Go 继续启动", name)
}
return fmt.Errorf("stopped waiting; Reims-Go keeps starting %s", name)
return fmt.Errorf("%s", i18n.M(cfg.Locale, "cli.start.canceled", i18n.Vars{"name": name}))
case errors.Is(err, context.DeadlineExceeded):
if zh {
return fmt.Errorf("Reims-Go 在 %v 内没有回报 %s 的启动结果;请看界面的日志面板(若正在运行的是旧版 Reims-Go,请先退出它)", startHandoffTimeout, name)
}
return fmt.Errorf("Reims-Go did not report starting %s within %v; check its log panel (quit it first if it is an older version)", name, startHandoffTimeout)
return fmt.Errorf("%s", i18n.M(cfg.Locale, "cli.start.timeout", i18n.Vars{"name": name, "timeout": startHandoffTimeout}))
case err != nil:
return err
}
@@ -124,11 +112,7 @@ func startInWindow(ctx context.Context, cfg *config.Config, name string) error {
}
// Guest Tools only connects once macOS is up and its agent runs, so say
// what this process can know: who now looks after the VM.
if zh {
fmt.Printf("%s 已启动,由 Reims-Go 界面进程管理;macOS 启动后,已安装 Guest Tools 的客体会接入剪贴板与共享目录\n", name)
} else {
fmt.Printf("%s is running, looked after by the Reims-Go window process; once macOS is up, a guest with Guest Tools installed gets clipboard and shared folders\n", name)
}
fmt.Println(i18n.M(cfg.Locale, "cli.start.managed_ok", i18n.Vars{"name": name}))
return nil
}
+13 -6
View File
@@ -20,10 +20,10 @@ type Config struct {
// whether online install offers alpha runtimes (portable-runtime-spec.md §6).
// "candidate", the name used before 2026-11-28, is read as "alpha".
RuntimeChannel string `json:"runtime_channel,omitempty"`
// RuntimeSource chooses where online runtimes and app updates are fetched:
// "auto" (default, also when empty: try GitHub first, fall back to GitCode),
// "github", or "gitcode".
RuntimeSource string `json:"runtime_source,omitempty"`
// AppUpdateChannel is "stable" (default, also when empty), "alpha", or "dev":
// controls which Reims-Go client releases CheckAppUpdate offers, and whether
// previous executables/installers are kept on startup for rollback.
AppUpdateChannel string `json:"app_update_channel,omitempty"`
// MinimizeToTray keeps Reims-Go running in the Windows system tray when the
// main window is closed so Guest Tools bridges stay alive. Defaults to true.
MinimizeToTray *bool `json:"minimize_to_tray,omitempty"`
@@ -157,7 +157,7 @@ func Resolve() (cfg *Config, needsSetup bool, err error) {
func Default() *Config {
return &Config{
DataRoot: CurrentDataRoot(),
Locale: i18n.Detect(),
Locale: i18n.Auto,
AutoPinPCores: true,
DefaultGPU: "auto",
}
@@ -181,10 +181,17 @@ func Load(path string) (*Config, error) {
if cfg.DataRoot == "" {
cfg.DataRoot = filepath.Dir(path)
}
cfg.Locale = i18n.ResolveLocale(string(cfg.Locale))
cfg.Locale = i18n.ParsePreference(string(cfg.Locale))
if cfg.RuntimeChannel == "candidate" {
cfg.RuntimeChannel = "alpha"
}
if cfg.AppUpdateChannel != "" {
switch cfg.AppUpdateChannel {
case "stable", "alpha", "dev":
default:
cfg.AppUpdateChannel = "stable"
}
}
return cfg, nil
}
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff. Show more