Compare commits

..
112 Commits
Author SHA1 Message Date
Nwflower 6cb6467a3c release: v0.2.11
Release Reims-Go / release (push) Canceled after 0s
2026-12-01 06:54:27 -07:00
Nwflower d55c965e6d refactor(ui): unify plugin frontend components and styles 2026-12-01 06:54:27 -07:00
Nwflower 8df8663932 chore(lint): forbid empty catch blocks and add static guard test 2026-12-01 06:48:19 -07:00
Nwflower a312ff4567 feat(images): add pluggable Images page with macOS builtin plugin, wordmark loader, and SLA notice 2026-12-01 06:44:40 -07:00
Nwflower 8d94d7976c fix(vm): preserve Guest Tools during direct CLI launches 2026-12-01 05:53:56 -07:00
Nwflower d573104072 fix(vm): honor plugin state and report inventory failures 2026-12-01 05:53:47 -07:00
Nwflower ae253be3e1 fix(installer): authenticate Apple recovery downloads 2026-12-01 05:53:31 -07:00
Nwflower f26f5be4c3 feat(theme): implement host theme slots, layout, and visuals 2026-12-01 05:53:19 -07:00
Nwflower 3281bfed12 Merge pull request #52 from yfl520/feat/downloader-plugin 2026-12-01 05:04:02 -07:00
Nwflower bc59aca9e5 Merge pull request #53 from reiasu2/feat/modifier-key-remap 2026-12-01 04:59:51 -07:00
Nwflower 5c6735ada1 Merge remote-tracking branch 'origin/main' 2026-12-01 04:51:45 -07:00
Nwflower fd48130c32 Merge pull request #39 from reiasu2/feat/custom-shared-folders
feat(guesttools): add custom shared folders with volume checks, agent v9, and settings UI
2026-12-01 04:49:14 -07:00
NwflowerandClaude Opus 5.5 5a8014864e feat(plugin): lock the UI and bridge contracts before the ecosystem grows
Plugins that need their own UI and richer themes should not force breaking
contract changes later, so the full shape is published now (uiApi 2.0,
bridgeApi 1.0) and every entry is marked stable or experimental:

- docs/plugin-architecture.md: plugin-owned views (sidebar, vm.tab,
  settings, dialog) and the bridge methods (§5.6), the finer theme
  contract with slot catalogue, layers, layout and icons (§5.1), and the
  contract evolution rules (§6.3).
- ui-contract.ts and the new bridgeContract.ts list stable and
  experimental entries; the build fails if a stable entry is not emitted
  or an emitted entry is still experimental, and writes
  bridge-contract.json next to ui-contract.json.
- internal/plugin/contract.go mirrors them as catalogs (contribution
  points, slots with accepted content, view locations, layers, layout,
  icons, bridge methods and events) and derives HostFeatures; tests keep
  Go and TypeScript identical and require every contributes field to be
  catalogued.
- Manifests gain views, theme layout and engines.bridgeApi. Unknown
  slots, locations, layout values and icon names are rejected;
  experimental use, unknown fields and missing engines ranges are doctor
  warnings. Declared-but-unrendered entries (vmCards, statusItems,
  settingsPages, vmTemplates, runtimeSources, runtimes, uiScripts,
  diagnostics, theme icons and brandMark, panels outside
  settings.plugin) are now marked experimental.
- The panel bridge resolves methods through the catalog, adds hello and
  refuses experimental methods; panels get theme.changed and
  locale.changed events; the Sidecar handshake and the Go SDK carry
  uiApi, bridgeApi and features.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 04:40:10 -07:00
Nwflower 03dc4cbe4c Merge pull request #38 from reiasu2/feat/webdav-os-root
refactor(guesttools): unify WebDAV and sync file confinement on os.Root
2026-12-01 04:40:05 -07:00
Nwflower 16fe93defd test(app): adapt disk_flow_test to lifecycle driver router 2026-12-01 04:36:46 -07:00
Nwflower b493b395e4 Merge pull request #56 from reiasu2/feat/disk-perf-subclusters-defender
feat(disk,host,ui): add qcow2 extended_l2 optimization, snapshot rewrite guard, and Defender exclusion guidance
2026-12-01 04:33:53 -07:00
Nwflower 593a8d92a3 Merge pull request #44 from yfl520/feat/host-memory-smbios
feat: 支持可选同步宿主机内存 SMBIOS Type 17 频率与代数
2026-12-01 04:29:23 -07:00
Nwflower 6eca802ddd Merge pull request #47 from yfl520/feat/smbios-rotate
feat(opencore,ui): 新增 OpenCore 设备身份 (SMBIOS) 一键换码功能
2026-12-01 04:26:03 -07:00
Nwflower fbfe376403 Merge pull request #51 from ELDment/feat/vm-management
feat(app): add VM shutdown mode selection and one-click force quit
2026-12-01 04:23:18 -07:00
千川白浪 4b12b435ed Merge pull request #57 from Dnyo666/fix/ui-perf-community-hardening
fix(ui,runtime,guesttools,docs): fix menu flash & modal lag, harden security/a11y/RTL, add community & plugin docs
2026-12-01 19:16:41 +08:00
Nwflower 49659193fa Merge pull request #57 from Dnyo666/fix/ui-perf-community-hardening
fix(ui,runtime,guesttools,docs): fix menu flash & modal lag, harden security/a11y/RTL, add community & plugin docs
2026-12-01 04:13:50 -07:00
Nwflower 3c75181fbc Merge pull request #46 from ChenRuoT/fix/vulkan-probe-diagnostics
fix(host): 自动发现 Windows 驱动包中的 Vulkan ICD 并报告探测错误
2026-12-01 04:12:50 -07:00
Dnyo666 d11ea85b73 docs(readme): add GitHub organization and plugin development sections
Document the reims-go GitHub organization, reims-go/plugins market repository, L1/L3/declarative plugin tiers, pkg/pluginsdk, and verified plugin development CLI commands in README.md and README.en.md.
2026-12-01 19:09:14 +08:00
Dnyo666 2fde035993 fix(runtime,guesttools,app): harden fallback channel isolation, guest config escaping, and OpenURL validation
Fail closed in listRemoteWeb when release tag HTML cannot be verified and sort entries with sortRemotesNewestFirst; bump Guest Tools agent_version and DriveShareAgentVersion to 8, single-quote escape config values with 0600 permissions, harden mount_drive_readonly (fd 3 read-only at offset 0, parent symlink/VM/byte-length checks, ENVIRON in awk); validate external HTTPS URLs via net/url in OpenURL; add regression unit tests for all three.
2026-12-01 19:09:13 +08:00
Dnyo666 ee5c02f54f perf(ui): eliminate software-compositing modal lag and harden UI responsiveness
Remove backdrop-filter from software-composited overlays/dialogs under WebviewGpuIsDisabled: true, preload license text before mounting the modal, fix short-viewport double scrollbars and narrow-screen row wrapping, restore keyboard focus on modal close, wire RTL direction to Radix menus, add ArrowUp/ArrowDown support and signature-based layout measurement in Segmented, and harden CRITICAL-3/CRITICAL-4 static guards.
2026-12-01 19:09:13 +08:00
Dnyo666 6fbcd6422e fix(ui): prevent previous titlebar menu from flashing on switch
Scope `.menu` and `.tooltip` enter animations to their open data-state
selectors and explicitly set `animation: none` on `[data-state="closed"]`
so Radix Presence unmounts closing menus immediately instead of replaying
`menu-in` for 160ms when `data-menubar-switch` is removed during a sibling
switch. Also keep `data-menubar-switch` active across the switch frame,
narrow `onPointerDownOutside` to sibling menu buttons so clicks in the gap
still dismiss, fix `prefers-reduced-motion` close animations (adding
`fade-out` for closing toasts), and add a static guard in `test-i18n.mjs`.
2026-12-01 19:05:47 +08:00
Dnyo666 a1b8e96c3d feat(ui,docs): add Discord community link to About page and READMEs
- Add a Discord community entry with open-in-browser and copy-invite actions to AboutPage
- Add zh-CN and en-US i18n strings for the Discord entry and regenerate settings/key catalogs
- Add Discord and QQ group badges, nav anchors, and community sections to README.md and README.en.md
2026-12-01 19:05:47 +08:00
NwflowerandClaude Opus 5.5 5e12d5511b chore(frontend): refresh package.json checksum
Wails rewrites frontend/package.json.md5 on every build because the
committed value went stale when the test script was added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 04:04:25 -07:00
NwflowerandClaude Opus 5.5 3b33e3b6bf fix(plugin): let suspended VMs allow disabling their driver plugin
The busy check treated the merged "suspended" state as live, so one
suspended macOS VM blocked turning off macOS VM Support. A suspended VM
has no process; its saved state stays in the VM folder and resumes once
the plugin is enabled again. The disable dialog and plugin docs say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 04:03:22 -07:00
Dnyo666 dfa1372f9c docs(readme): add GitHub organization and plugin development sections
Document the reims-go GitHub organization, reims-go/plugins market repository, L1/L3/declarative plugin tiers, pkg/pluginsdk, and verified plugin development CLI commands in README.md and README.en.md.
2026-12-01 18:53:40 +08:00
Dnyo666 3ab04c3627 fix(runtime,guesttools,app): harden fallback channel isolation, guest config escaping, and OpenURL validation
Fail closed in listRemoteWeb when release tag HTML cannot be verified and sort entries with sortRemotesNewestFirst; bump Guest Tools agent_version and DriveShareAgentVersion to 8, single-quote escape config values with 0600 permissions, harden mount_drive_readonly (fd 3 read-only at offset 0, parent symlink/VM/byte-length checks, ENVIRON in awk); validate external HTTPS URLs via net/url in OpenURL; add regression unit tests for all three.
2026-12-01 18:53:40 +08:00
Dnyo666 8721f3de70 perf(ui): eliminate software-compositing modal lag and harden UI responsiveness
Remove backdrop-filter from software-composited overlays/dialogs under WebviewGpuIsDisabled: true, preload license text before mounting the modal, fix short-viewport double scrollbars and narrow-screen row wrapping, restore keyboard focus on modal close, wire RTL direction to Radix menus, add ArrowUp/ArrowDown support and signature-based layout measurement in Segmented, and harden CRITICAL-3/CRITICAL-4 static guards.
2026-12-01 18:53:39 +08:00
Dnyo666 6bac79b346 fix(ui): prevent previous titlebar menu from flashing on switch
Scope `.menu` and `.tooltip` enter animations to their open data-state
selectors and explicitly set `animation: none` on `[data-state="closed"]`
so Radix Presence unmounts closing menus immediately instead of replaying
`menu-in` for 160ms when `data-menubar-switch` is removed during a sibling
switch. Also keep `data-menubar-switch` active across the switch frame,
narrow `onPointerDownOutside` to sibling menu buttons so clicks in the gap
still dismiss, fix `prefers-reduced-motion` close animations (adding
`fade-out` for closing toasts), and add a static guard in `test-i18n.mjs`.
2026-12-01 18:53:39 +08:00
Dnyo666 c8b792b316 feat(ui,docs): add Discord community link to About page and READMEs
- Add a Discord community entry with open-in-browser and copy-invite actions to AboutPage
- Add zh-CN and en-US i18n strings for the Discord entry and regenerate settings/key catalogs
- Add Discord and QQ group badges, nav anchors, and community sections to README.md and README.en.md
2026-12-01 18:53:39 +08:00
Nwflower 563b5a45bb Merge branch 'feat/vmref-driver-start' into main 2026-12-01 03:47:21 -07:00
Nwflower aacaec535d Merge origin/main into feat/vmref-driver-start
Adapt Intel VM suspend/resume to driver.SuspendDriver and lifecycle.Service, move native VM close confirmation into internal/host, migrate vm-suspend legacy capability detection, drop moved runtime build tooling, and regenerate i18n and Wails bindings.
2026-12-01 03:47:20 -07:00
Nwflower 8887771bec feat(plugin): allow disabling macOS guest plugin and guard native flows 2026-12-01 03:29:03 -07:00
棠渚听潮 97597d5334 feat(disk,host,ui): add qcow2 extended_l2 optimization, snapshot rewrite guard, and Defender exclusion guidance 2026-12-01 18:19:31 +08:00
Xiaochi You 07ec5f9543 Merge PR #55: define PR ownership and client boundaries
Add the review guidance and link it from AGENTS.md.
2026-12-01 18:16:14 +08:00
YXC0915 f8943ea78c docs: define PR ownership and client boundaries 2026-12-01 18:06:40 +08:00
NwflowerandClaude Opus 5.5 aabe0cf29f feat(plugin): hide the core system plugin from plugin lists
builtin.core only contributes the default theme and cannot be turned off,
so listing it as a plugin was noise. The plugins page, plugin list and
the plugin doctor fallback now use Registry.ListVisible; Info and
market comparisons still see every plugin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 03:05:54 -07:00
NwflowerandClaude Opus 5.5 974389f56b fix(app): resolve macOS-native flows within the macOS driver
A same-named VM in another driver made macOS restart, GetVMDetail and the
flows built on it fail as ambiguous even when the driver was known.
Restart now resolves the owner first and sends macOS VMs through
restartMacOSVM, which also restores the commit-memory wait that a
bare-name restart had skipped. Create-then-start and the Win10
cold-reboot start name the macOS driver explicitly. Tray items carry
their driver ID, and the tray reads transitions by VMRef key so
starting/stopping shows again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 03:05:54 -07:00
NwflowerandClaude Opus 5.5 b1eec6050b fix(runtime): keep capabilities of manifests without the field
Packages published before manifest.json carried "capabilities" (up to
runtime-3731afd-p4) lost every capability once inference was removed, so
Win10 hosts got kernel-irqchip=off and rule hooks saw no runtime caps.
When a built-in reims-vgpu manifest has no "capabilities" key, declare the
patch-derived set at load time with the same mapping as pack-runtime.ps1.
A declared list, including an empty one, still wins; other kinds must
declare their own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 03:05:54 -07:00
YXC0915 30db99fc71 fix(ui): anchor close confirmation to the VM window 2026-12-01 17:45:29 +08:00
ELDment 0bb1e1a8a6 feat(app): add VM shutdown mode selection and one-click force quit 2026-12-01 17:29:58 +08:00
事事休 f0207315b6 fix(installer): match recovery osType and verify partition chunklist before parallel download 2026-12-01 17:10:47 +08:00
棠渚听潮 de1eb1f92f feat(input,guesttools,ui): add per-VM Windows modifier key remapping and Win-to-Command support 2026-12-01 16:44:30 +08:00
事事休 1fdbefd9c9 feat(plugin,installer): add downloaders extension point and builtin parallel downloader 2026-12-01 16:22:12 +08:00
事事休 cbcbec7f83 feat(opencore,ui): add one-click OpenCore SMBIOS identity rotation 2026-12-01 13:38:57 +08:00
ChenRuoT 6628da21ff fix(host): discover missing Vulkan ICDs in active display driver packages 2026-12-01 13:17:18 +08:00
ChenRuoT e62742f65d fix(host): surface Vulkan probe failures in setup and doctor 2026-12-01 13:01:37 +08:00
事事休 7672925cac feat: optional host SMBIOS Type 17 memory speed and type sync 2026-12-01 12:40:23 +08:00
YXC0915 e7a6dd7a5b ui: confirm native VM closes in the desktop client 2026-12-01 12:05:05 +08:00
棠渚听潮 0e8454d494 feat(guesttools): add custom shared folders with volume checks, agent v8, and settings UI 2026-12-01 12:02:26 +08:00
YXC0915 c2c168da4e suspend: retry rejected direct writes only after migration fails 2026-12-01 11:55:46 +08:00
棠渚听潮 8150b4aee3 Merge remote-tracking branch 'upstream/main' into feat/custom-shared-folders 2026-12-01 11:46:41 +08:00
YXC0915 80bc11f1c2 perf(suspend): uncap migration bandwidth, use 8 multifd channels, and opt into direct-io on save
- Set max-bandwidth=0 (QEMU RATE_LIMIT_DISABLED) in configureMappedRAM so
  paused local snapshot saves are no longer throttled to QEMU's 128 MiB/s
  default.
- Increase DefaultMultifdChannels from 4 to 8 and lower migratePollInterval
  from 200ms to 100ms.
- Enable direct-io on outgoing suspend saves with automatic fallback for
  older QEMU builds or volumes that reject direct I/O; keep direct-io
  disabled on incoming resume to preserve OS read-ahead.
- Compute suspend progress from (Total - Remaining) / Total (100% on
  completed) so sparse mapped-ram saves report accurate completion instead
  of stopping at the non-zero RAM ratio.
2026-12-01 11:41:19 +08:00
YXC0915 e6c8388c37 build: keep portable runtime tooling in the runtime repository 2026-12-01 11:19:50 +08:00
YXC0915 5f96f4ab08 runtime: use the fork catalog for stable and preview releases 2026-12-01 11:05:44 +08:00
YXC0915 43d793ec36 runtime: show promoted previews only once 2026-12-01 10:57:38 +08:00
YXC0915 4a2bffd5d2 ci: publish runtime previews from the runtime fork 2026-12-01 10:55:06 +08:00
YXC0915 fc19631676 build: source the runtime from the Reims vGPU and QEMU forks 2026-12-01 10:52:08 +08:00
YXC0915 059c1a3b76 fix(guesttools): authenticate macOS Windows drive mounts 2026-12-01 10:23:07 +08:00
YXC0915 2d5ee45163 Merge main and preserve Guest Tools file sync compatibility 2026-12-01 10:02:08 +08:00
Xiaochi You c125fb2510 Merge pull request #37 from Nwflower/codex/intel-vm-suspend
feat: suspend and resume Intel macOS VMs across host reboots
2026-12-01 09:20:13 +08:00
YXC0915 0d6a153621 Merge remote-tracking branch 'upstream/main' into codex/intel-vm-suspend 2026-12-01 09:15:38 +08:00
YXC0915 003821a28a fix(ui): refine VM suspend actions and confirmation 2026-12-01 09:14:02 +08:00
YXC0915 5f8d96a401 fix(ui): align suspend confirmation and single-line toasts 2026-12-01 09:05:57 +08:00
棠渚听潮 1c5e5484b9 refactor(guesttools): unify WebDAV and sync file confinement on os.Root 2026-12-01 09:04:14 +08:00
YXC0915 a32fe323ab fix: preserve force stop and recover incomplete VM suspend attempts 2026-12-01 08:54:22 +08:00
Xiaochi You f622a3a5b0 Merge pull request #34 from yxc0915/codex/fix-offline-installer-home-paths
修复 macOS 离线安装辅助盘缺失和键入命令失败
2026-12-01 08:45:31 +08:00
Xiaochi You 061e65bc52 Merge pull request #33 from yxc0915/codex/fix-guest-tools-sync-deletions
修复 Guest Tools 同步模式下删除文件后回填
2026-12-01 08:44:57 +08:00
YXC0915 4cc4b6c02c fix: make Intel VM suspend and resume transactional 2026-12-01 08:37:30 +08:00
YXC0915 790a42912e fix(installer): expand home paths from reims-ctl show 2026-12-01 08:22:58 +08:00
YXC0915 552d6e4cad fix(guesttools): confine sync to the current shared folders 2026-12-01 08:06:43 +08:00
YXC0915 2596728789 feat: integrate Intel VM suspend and instant resume across backend, CLI, and UI 2026-12-01 08:05:05 +08:00
YXC0915 347840490e feat(patches): add reims-vgpu/metal2vulkan snapshot replay and build pipeline support 2026-12-01 07:48:14 +08:00
YXC0915 585669e0b3 feat(patches): add Intel WHPX suspend and Win32 mapped-ram I/O patches 2026-12-01 07:44:35 +08:00
YXC0915 f96d78be14 fix(guesttools): propagate fallback sync deletions 2026-12-01 07:37:44 +08:00
Nwflower 8270597fe2 refactor(runtime): declare kind paths and capabilities
Move control and utility executable names plus the QEMU environment key into runtime kind specs. Read capabilities only from manifest.json and declare them when packing reims runtimes.
2026-11-30 11:28:14 -07:00
Nwflower c1b33c9c4f refactor(app): isolate native macOS adapters
Route generic App and CLI code through lifecycle and driver models. Move native macOS detail, create, settings and legacy flows into explicit files, share progress and redaction through host, and enforce the boundary with a file-scoped architecture ratchet.
2026-11-30 11:18:09 -07:00
Nwflower 05ddd2b6f3 refactor(app): remove legacy storage client paths
Share redaction and GPU log diagnosis outside the macOS client, move snapshot validation to the driver contract, and delete superseded App storage implementations.
2026-11-30 10:45:58 -07:00
Nwflower 847d447d81 refactor(lifecycle): route VM observation and diagnostics
Resolve stats, thumbnails, window actions, SSH, affinity and diagnostic bundles through VMRef-aware VM information. Isolate caches, SSH aliases and frontend pollers for same-name VMs while preserving macOS defaults.
2026-11-30 10:33:06 -07:00
千川白浪 9eb8d95443 Merge pull request #28 from reiasu2/fix/clipboard-sync-reliability
fix(guesttools): harden Windows clipboard locking, DIB/PNG handling, and echo prevention
2026-11-30 09:30:32 -08:00
Nwflower 2235195587 refactor(lifecycle): route VM storage operations by driver
Add typed snapshot, CoW clone, resize and compaction contracts. Move macOS disk mechanics behind the driver, preserve progress and pending UI behavior, and pass driver identity through App, CLI and frontend entry points.
2026-11-30 10:16:48 -07:00
Nwflower 827f942238 refactor(lifecycle): route recovery actions by driver
Move recovery and finish-install mechanics into macOS driver actions. Keep the App pending-change and notification behavior, with legacy fallbacks for minimal embedding.
2026-11-30 09:59:27 -07:00
Nwflower 84f42a7604 fix(migrate): collapse guest and VMRef upgrades
Support the released unstamped and v1 layouts without migrating unreleased plugin IDs. Combine guest and VMRef transformations into one v3 state save, preserve the original backup, and abort on backup failures. Rescan owner markers during v3 and record ownership on every macOS create path.
2026-11-30 09:54:45 -07:00
Nwflower e83cce28e6 feat(lifecycle): route media actions and VM logs
Add ActionDriver/LogDriver dispatch for insert, eject, NVMe upgrades and serial/QEMU logs across lifecycle, App and CLI.

Pass driver IDs through frontend media and log calls and extend second-driver action/log coverage.
2026-11-30 09:40:52 -07:00
棠渚听潮 93c981ff01 fix(guesttools): harden Windows clipboard locking, DIB/PNG handling, and echo prevention 2026-12-01 00:14:38 +08:00
Nwflower b6fde8fd4b feat(lifecycle): route VM details and settings by driver
Resolve details through driver.Show with a generic GetVMInfo binding, and validate/apply changes through lifecycle.Set in App and CLI.

Move guest language and OpenCore replay into ReimsMacOSDriver.Set, preserving legacy fallbacks and adding second-driver detail/settings acceptance.
2026-11-30 09:04:14 -07:00
Nwflower 8b6ca5c719 feat(lifecycle): route restart and delete by driver
Add lifecycle Delete and driver-qualified App Restart/Delete methods, CLI vm delete --driver/--keep-files, and frontend driver-aware actions.

Extend the second-driver App acceptance to restart and delete while preserving legacy macOS restart fallback and cleanup.
2026-11-30 08:56:36 -07:00
Nwflower 71fb8bb458 refactor(vmstart): split macOS preparation from host helpers
Move Prep, recovery markers, offline helper and OpenCore language handling into internal/macos/startprep while retaining memory, affinity and line-writer helpers in vmstart.

Remove the host-to-macOS vmstart architecture exception and preserve preparation and commit-memory tests on both sides.
2026-11-30 08:50:55 -07:00
Nwflower 74be2f73a9 refactor(macos): own guest tools images and tuning
Build Guest Tools images in the macOS driver after all start hooks pass, through a host callback rather than a new macOS-to-guesttools dependency.

Add driver.OptimizationAdvisor, keep generic hardware evaluation in host, and move WHPX recommendations and tests into macosdriver for both the UI and diagnostics.
2026-11-30 08:45:12 -07:00
Nwflower 7ba5e3fa9c feat(lifecycle): route VM starts through owning drivers
Change Driver.Start to StartRequest/StartResult with a compile-time macOS adapter assertion and registry-to-router coverage. Keep legacy Sidecar name alongside VMRef and grant argument privileges by driver ownership.

Move macOS preparation into ReimsMacOSDriver after hook veto, fail preparation errors before launch, and verify veto leaves OpenCore, recovery markers and ledgers unchanged.

Unify GUI, CLI and window list/start/stop through internal/lifecycle, select frontend VMs by VMRef, lazily initialize reims only in legacy CLI branches, and cover a second driver through App user entry points.
2026-11-30 08:34:20 -07:00
千川白浪 890ca4c5ad Merge pull request #24 from Admilkk/feat/parallel-offline-installer-download
feat: 支持 macOS 离线安装包并发下载
2026-11-30 07:21:28 -08:00
Nwflower 25766a9cdb refactor(guesttools): isolate registrations by VMRef
Key Guest Tools registrations, connection state, clipboard policies, text queues, and WebDAV handlers by driver-qualified VM references while preserving existing guest URLs and token authentication.

Pass VMRef through host-text callbacks and removal cleanup, with same-name coverage for authentication, policies, handlers, and independent unregister.
2026-11-30 07:59:06 -07:00
Nwflower 59aaf36eb5 refactor(app): key VM runtime state by VMRef
Qualify transitions, pending changes, reboot watchers, disk/process caches, typing queues, thumbnail locks, and VM log sources so same-named VMs do not share mutable state.

Read driver-qualified transition keys in the frontend and add --start-driver to CLI/window handoff. Legacy window start rejects other drivers explicitly until lifecycle routing lands.
2026-11-30 07:51:10 -07:00
Nwflower 9204b58987 feat(driver): disambiguate VMs with VMRef
Keep same-named VMs from different drivers, reject ambiguous bare-name resolution, and add exact ResolveRef routing with driver-qualified keys.

Declare DataRoot-relative VM roots in guest driver manifests, validate traversal and absolute paths, and scan declarations for unavailable drivers.

Add data layout v3 for driver-qualified per-VM plugin settings, preserve explicit values during migration, and pass VMRef keys from the settings UI.
2026-11-30 07:38:46 -07:00
Nwflower 5cbd7bceac feat(plugins): move macOS support into builtin.guest.macos
Declare the reims guest driver statically, merge the install guide into the optional macOS plugin, and keep compatibility settings under the new owner.

Add data layout v2 with atomic state migration, ledger backups, targeted argument ownership moves, and idempotent v1 upgrade coverage. Reduce builtin.core to the default theme.

Add a reverse import ratchet for internal/macos and document the transition. The macOS plugin remains enabled by default during migration; that default and the future privilege/trust rules remain subject to review.
2026-11-30 07:20:15 -07:00
Admilkk d7e1091074 feat: parallelize macOS offline installer downloads 2026-11-30 22:17:19 +08:00
Nwflower 6dcf33f71b feat(dataroot): guard data folder writes and migrations 2026-11-30 06:58:32 -07:00
Nwflower 2ffddf94b4 docs(plugins): plan guest migration and macOS extraction 2026-11-30 06:58:32 -07:00
Nwflower 5e39b11566 refactor(macos): isolate guest-specific code and guard host imports 2026-11-30 05:47:14 -07:00
Nwflower fe139def0c Merge branch 'feat/plugin-market-and-data-version' 2026-11-30 05:20:20 -07:00
NwflowerandClaude Opus 5.5 e259833b5f feat(plugins): rework the plugin market and first-run language packs
Market page
- Card grid that fills the width; cards show only icon, name,
  publisher (trust mark by color and icon), version and the action.
- Paints from cache via the new PeekPluginMarket binding, then revalidates;
  cards reveal 24 at a time as the feed scrolls.
- Category chips come from the index (MarketBrowseResult.kinds) instead of
  a fixed list; the alpha toggle and source badge are gone.
- Installed/Market is a segmented control; refresh now shows feedback.
- WordmarkLoader writes the Reims-Go wordmark stroke by stroke while the
  market loads (static pulse under reduced motion).

Install and enable
- reims:plugin-install events drive a progress bar on the card.
- After install, a dialog offers to enable the plugin and lists what it can
  do in plain words (PluginInfo.risks / MarketCatalogItem.risks, derived
  from tier, permissions and contributions in risks.go).
- Enabling a plugin that provides UI languages switches to the first one
  unless the current language is among them (PluginInfo.locales).

Trust
- A package installed from the project's own index, fetched over HTTPS in
  this session, inherits the index's trust level when its SHA-256 matches.
  Third-party indexes (REIMS_GO_PLUGIN_MARKET_URL) cannot vouch and show
  every entry as community.
- Trust no longer waives review: official packages get the same scan,
  high-risk approval and L3 hash check as any other; only builtin and
  bundled plugins are pre-approved.

First launch
- When the OS language is not covered by zh-CN/en-US, the folder screen
  looks up a matching pack once (SuggestLanguagePack) and offers to install
  it; Continue installs and enables it so the UI follows the OS language.
  Before setup the market keeps its index in memory only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 05:17:45 -07:00
NwflowerandClaude Opus 5.5 809ce68cf3 feat(datamigrate): version the data folder and migrate it on startup
The data folder had no record of which layout wrote it, so a new release
could not tell old data from current data. <DataRoot>\.reims-go-data.json
now records data_version and the app version that last raised it. It is
kept out of reims-go.json, which is rewritten whole on every save and
would drop the field under an older build.

Each build carries every step from older layouts to its own; the GUI and
CLI run them in order before reading the folder, so users can jump
straight from any old version. A failed step leaves the version at the
last success and resumes next launch; a folder from a newer build is left
untouched.

Step v1 writes the driver ownership marker into every reims-ctl VM.
driver.RenamedDriverIDs maps old driver IDs to new ones for when a driver
moves to another plugin; markers are not rewritten, so downgrades still
resolve.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 05:16:38 -07:00
千川白浪 8ff80090d8 Merge pull request #22 from reiasu2/feat/runtime-window-fullscreen
feat(display,ui,tray): toggle running reims-vgpu window fullscreen on Windows
2026-11-30 04:09:16 -08:00
Nwflower f4993fa333 Merge branch 'main' into feat/runtime-window-fullscreen 2026-11-30 05:08:56 -07:00
千川白浪 18acc57209 Merge pull request #21 from reiasu2/fix/stale-gpu-driver-file
fix(gpu): auto-rebind stale Windows DriverStore Vulkan ICD before VM start
2026-11-30 04:07:55 -08:00
棠渚听潮 e62f6127fe feat(display,ui,tray): toggle running reims-vgpu window fullscreen on Windows 2026-11-30 19:57:50 +08:00
棠渚听潮 957da43b2d fix(gpu): auto-rebind stale Windows DriverStore Vulkan ICD before VM start 2026-11-30 19:57:47 +08:00
Nwflower 9baa1e341c feat(display,patches): decouple fullscreen from guest resolution for 1.5x HiDPI scaling 2026-11-30 03:41:47 -07:00
432 changed files with 37756 additions and 8702 deletions

No files matched your search

+1
View File
@@ -1,2 +1,3 @@
*.patch -text
*.diff -text
internal/guesttools/file_sync.sh text eol=lf
-291
View File
@@ -1,291 +0,0 @@
name: Build Portable Runtime (Alpha)
# Daily: build the newest steelbrain/reims-vgpu commit with the patch queue
# (patches/series.txt) and publish it as a GitHub prerelease = the alpha
# channel (portable-runtime-spec.md section 6). Never publishes stable:
# promotion needs a real-host smoke test and a person (AGENTS.md rule 6).
on:
schedule:
- cron: "23 3 * * *" # 03:23 UTC daily; skipped when upstream has not moved
workflow_dispatch:
inputs:
upstream_commit:
description: "steelbrain/reims-vgpu commit (empty = upstream default branch HEAD)"
required: false
default: ""
publish:
description: "Publish as an alpha prerelease (never stable)"
type: boolean
default: true
rebuild:
description: "Build a new patch revision (runtime-<commit>-pN) even if this upstream commit is already released"
type: boolean
default: false
permissions:
contents: write
issues: write
concurrency:
group: build-runtime
cancel-in-progress: false
env:
UPSTREAM_URL: https://github.com/steelbrain/reims-vgpu.git
KEEP_ALPHAS: "7" # unpromoted alpha prereleases kept; older ones are deleted
jobs:
resolve:
runs-on: ubuntu-latest
outputs:
commit: ${{ steps.r.outputs.commit }}
skip: ${{ steps.r.outputs.skip }}
suffix: ${{ steps.r.outputs.suffix }}
steps:
- id: r
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
WANT: ${{ inputs.upstream_commit }}
REBUILD: ${{ inputs.rebuild }}
run: |
set -euo pipefail
git clone -q --filter=blob:none --no-checkout "$UPSTREAM_URL" up
commit="$(git -C up rev-parse --verify "${WANT:-HEAD}^{commit}")"
echo "commit=$commit" >> "$GITHUB_OUTPUT"
# Already published (alpha or stable) under any short-hash length or -pN revision?
max_rev=0
for tag in $(gh release list -R "$GITHUB_REPOSITORY" --limit 1000 --json tagName -q '.[].tagName' | grep '^runtime-' || true); do
rest="${tag#runtime-}"
base="${rest%%-p*}"
case "$commit" in
"$base"*)
rev=1
if [ "$rest" != "$base" ]; then
num="${rest#"$base"-p}"
case "$num" in
''|*[!0-9]*) ;;
*) rev="$num" ;;
esac
fi
if [ "$rev" -gt "$max_rev" ]; then max_rev="$rev"; fi
echo "Upstream $commit is already released as $tag (rev $rev)"
;;
esac
done
skip=false
suffix=""
if [ "$max_rev" -gt 0 ]; then
if [ "$REBUILD" = "true" ]; then
suffix="-p$((max_rev + 1))"
echo "Rebuild requested: will publish with suffix $suffix"
else
skip=true
fi
fi
echo "skip=$skip" >> "$GITHUB_OUTPUT"
echo "suffix=$suffix" >> "$GITHUB_OUTPUT"
build:
needs: resolve
if: needs.resolve.outputs.skip != 'true'
runs-on: windows-latest
timeout-minutes: 150
outputs:
short: ${{ steps.patches.outputs.short }}
release_id: ${{ steps.patches.outputs.release_id }}
applied: ${{ steps.patches.outputs.applied }}
merged: ${{ steps.patches.outputs.merged }}
conflict: ${{ steps.patches.outputs.conflict }}
steps:
- uses: actions/checkout@v4
- name: Setup MSYS2 CLANG64
id: msys2
uses: msys2/setup-msys2@v2
with:
msystem: CLANG64
update: true
install: >-
git zstd tar mingw-w64-clang-x86_64-toolchain
mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-meson
mingw-w64-clang-x86_64-ninja mingw-w64-clang-x86_64-pkgconf
mingw-w64-clang-x86_64-glib2 mingw-w64-clang-x86_64-pixman
mingw-w64-clang-x86_64-gtk3 mingw-w64-clang-x86_64-libslirp
mingw-w64-clang-x86_64-libusb mingw-w64-clang-x86_64-libva
mingw-w64-clang-x86_64-mesa mingw-w64-clang-x86_64-vulkan-loader
mingw-w64-clang-x86_64-python mingw-w64-clang-x86_64-python-pip
- name: Check out upstream and apply the patch queue
id: patches
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$work = Join-Path $env:RUNNER_TEMP 'reims-vgpu'
foreach ($d in 'cargo', 'xdg-data', 'xdg-cache') { New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP $d) | Out-Null }
# The runner's git defaults to core.autocrlf=true; LF patches need an LF
# checkout (upstream also rewrites CRLF files to LF, install-ctl.sh).
git config --global core.autocrlf false
git clone -q $env:UPSTREAM_URL $work
if ($LASTEXITCODE) { throw 'clone failed' }
git -C $work checkout -q '${{ needs.resolve.outputs.commit }}'
if ($LASTEXITCODE) { throw 'checkout failed' }
git -C $work submodule update --init --depth 1 vendor/qemu
if ($LASTEXITCODE) { git -C $work submodule update --init vendor/qemu }
if ($LASTEXITCODE) { throw 'vendor/qemu submodule failed' }
$short = (git -C $work rev-parse --short=7 HEAD).Trim()
$releaseId = "$short${{ needs.resolve.outputs.suffix }}"
"short=$short" >> $env:GITHUB_OUTPUT
"release_id=$releaseId" >> $env:GITHUB_OUTPUT
# Applies what applies, skips what upstream already has, stops on a
# conflict without touching the patch (AGENTS.md rule 4).
$resultFile = Join-Path $env:RUNNER_TEMP 'patches.json'
try {
pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -ResultFile $resultFile
$ok = $LASTEXITCODE -eq 0
} finally {
if (Test-Path $resultFile) {
$r = Get-Content -Raw $resultFile | ConvertFrom-Json
"applied=$(@($r.applied) -join ',')" >> $env:GITHUB_OUTPUT
"merged=$(@($r.merged) -join ',')" >> $env:GITHUB_OUTPUT
"conflict=$($r.conflict)" >> $env:GITHUB_OUTPUT
"APPLIED_PATCHES=$(@($r.applied) -join ',')" >> $env:GITHUB_ENV
}
}
if (-not $ok) { throw 'patch queue does not apply' }
"UPSTREAM_DIR=$work" >> $env:GITHUB_ENV
"SHORT_COMMIT=$short" >> $env:GITHUB_ENV
"RELEASE_ID=$releaseId" >> $env:GITHUB_ENV
"CARGO_HOME=$(Join-Path $env:RUNNER_TEMP 'cargo')" >> $env:GITHUB_ENV
"XDG_DATA_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-data')" >> $env:GITHUB_ENV
"XDG_CACHE_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-cache')" >> $env:GITHUB_ENV
- name: Build upstream runtime in MSYS2 CLANG64
shell: msys2 {0}
env:
REIMS_INSTALL_SKIP_HOST_CHECKS: "1"
run: |
set -euo pipefail
cd "$(cygpath -u "$UPSTREAM_DIR")"
# Upstream's own non-interactive CLANG64 build script.
bash scripts/install-ctl.sh --yes
- name: Package alpha runtime and source archives
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$outDir = Join-Path $env:RUNNER_TEMP 'releases'
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
# In-process call, so an empty list (every patch already upstream) binds
# as an empty array rather than being dropped as an empty argument.
$applied = @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
& ./scripts/pack-runtime.ps1 `
-ReimsRepo $env:UPSTREAM_DIR `
-CargoHome $env:CARGO_HOME `
-QemuDir (Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current') `
-Msys2 '${{ steps.msys2.outputs.msys2-location }}' `
-OutDir $outDir `
-TempRoot $env:RUNNER_TEMP `
-Channel alpha `
-ReleaseId $env:RELEASE_ID `
-Patches $applied
- name: Alpha entry gate
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
& ./scripts/check-runtime-alpha.ps1 `
-OutDir (Join-Path $env:RUNNER_TEMP 'releases') `
-Commit $env:RELEASE_ID -RequireSlim `
-Zstd (Join-Path '${{ steps.msys2.outputs.msys2-location }}' 'usr\bin\zstd.exe') `
-AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
- name: Upload alpha artifacts
uses: actions/upload-artifact@v4
with:
name: reims-runtime-win-x64-${{ env.RELEASE_ID }}-alpha
path: |
${{ runner.temp }}/releases/reims-runtime-*.tar.zst
${{ runner.temp }}/releases/SHA256SUMS.txt
retention-days: 14
- name: Publish alpha prerelease (never stable)
if: github.event_name == 'schedule' || inputs.publish
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
MERGED: ${{ steps.patches.outputs.merged }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$c = $env:RELEASE_ID
$short = $env:SHORT_COMMIT
$dir = Join-Path $env:RUNNER_TEMP 'releases'
$assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", "reims-runtime-symbols-$c.tar.zst", 'SHA256SUMS.txt') |
ForEach-Object { Join-Path $dir $_ }
$applied = if ($env:APPLIED_PATCHES) { ($env:APPLIED_PATCHES -split ',' | ForEach-Object { "- ``$_``" }) -join "`n" } else { '- (none)' }
$merged = if ($env:MERGED) { "`n`nAlready upstream, skipped (retire from patches/): $env:MERGED" } else { '' }
$notes = @"
**Alpha** runtime (``$c``), built automatically from upstream [steelbrain/reims-vgpu@$short](https://github.com/steelbrain/reims-vgpu/commit/${{ needs.resolve.outputs.commit }}).
Not smoke-tested on a real host. It becomes stable only after ``scripts/smoke-runtime.ps1`` passes on a real Windows host and a person approves (portable-runtime-spec.md section 6).
Local patches applied (sources and patches are in the attached source packages):
$applied$merged
The optional ``reims-runtime-symbols-$c.tar.zst`` contains matching debug files for crash analysis.
Build: $env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID
"@
gh release create "runtime-$c" @assets --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes
if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" }
- name: Prune old alpha prereleases
if: github.event_name == 'schedule' || inputs.publish
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
shell: pwsh
run: |
# Only unpromoted runtime prereleases; stable releases are never touched.
$alphas = gh release list -R $env:GITHUB_REPOSITORY --limit 1000 --json tagName,isPrerelease,isDraft,createdAt | ConvertFrom-Json |
Where-Object { $_.tagName -like 'runtime-*' -and $_.isPrerelease -and -not $_.isDraft } |
Sort-Object createdAt -Descending
$alphas | Select-Object -Skip ([int]$env:KEEP_ALPHAS) | ForEach-Object {
Write-Host "Deleting old alpha $($_.tagName)"
gh release delete $_.tagName -R $env:GITHUB_REPOSITORY --yes --cleanup-tag
}
report:
needs: [resolve, build]
if: always() && needs.resolve.outputs.skip != 'true' && (failure() || needs.build.outputs.merged != '')
runs-on: ubuntu-latest
steps:
- env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RESULT: ${{ needs.build.result }}
COMMIT: ${{ needs.resolve.outputs.commit }}
CONFLICT: ${{ needs.build.outputs.conflict }}
MERGED: ${{ needs.build.outputs.merged }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
# One open issue per kind; later runs add a comment instead of a new issue.
file_issue() {
local title="$1" body="$2" n
n="$(gh issue list -R "$GITHUB_REPOSITORY" --state open --search "in:title \"$title\"" --json number,title -q ".[] | select(.title == \"$title\") | .number" | head -n1)"
if [ -n "$n" ]; then
gh issue comment "$n" -R "$GITHUB_REPOSITORY" --body "$body"
else
gh issue create -R "$GITHUB_REPOSITORY" --title "$title" --body "$body"
fi
}
if [ "$RESULT" != "success" ]; then
if [ -n "$CONFLICT" ]; then
why="Patch \`$CONFLICT\` neither applies to upstream \`$COMMIT\` nor is already there. Per AGENTS.md rule 4 the patch was not edited; a person decides how to rebase or retire it."
else
why="The build, packaging or alpha gate failed for upstream \`$COMMIT\`; see the log."
fi
file_issue "Runtime alpha build failed" "$why"$'\n\n'"Run: $RUN_URL"$'\n\n'"No alpha was published."
fi
if [ -n "$MERGED" ]; then
file_issue "Patch queue: patches already upstream" "Upstream \`$COMMIT\` already contains: \`$MERGED\`. They were skipped. Record the merge commit in portable-runtime-spec.md section 5, then remove them from patches/ and patches/series.txt."$'\n\n'"Run: $RUN_URL"
fi
+8 -5
View File
@@ -8,7 +8,7 @@
与上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的分工:
- **`reims-vgpu`**:底层引擎(QEMU 分支、`reims-graphics-pci`、`metal2vulkan`、`reims-ctl`、`reims-util`)。
- **`reims-go`(本仓库)**:桌面应用、命令行包装与便携运行时打包/分发流水线,提供开箱即用的环境体检、离线装机、硬件调优、Guest Tools、恢复点与 CoW 派生能力。
- **`reims-go`(本仓库)**:桌面应用、命令行包装与运行时下载管理,提供开箱即用的环境体检、离线装机、硬件调优、Guest Tools、恢复点与 CoW 派生能力。
## 存储与产物边界
@@ -32,7 +32,7 @@
- 用户显式要求工单,或任务需要跨会话恢复、多人/多 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/` 会话实例路径。
- **持久文档零引用**:`README.md`、`README.en.md`、`CHANGELOG.md`、`AGENTS.md` 与 `docs/` 严禁引用具体工单 ID 或 `.debug/tmp/` 会话实例路径。
| 命令 | 用途 |
| :--- | :--- |
@@ -48,13 +48,14 @@
## 事实核验与安全规则
1. **上游行为以一手源码为准**:引用 `reims-ctl` / `reims-vgpu` 行为时核对对应上游 commit 与 `文件:行号`;未实测项显式标注「待验证」。
2. **人工确认红线**:UAC 提权启用 WHPX、重启 Windows、macOS 图形安装向导、向上游提交 PR、将运行时升级为 `stable` 正式发布,均须由人确认触发。自动化例外:[`.github/workflows/build-runtime.yml`](.github/workflows/build-runtime.yml) 每日从上游构建,通过 `alpha` 准入检查后自动发布为 GitHub 预发布(`alpha` 通道),并自动清理较旧的未升级 `alpha` 预发布。
2. **人工确认红线**:UAC 提权启用 WHPX、重启 Windows、macOS 图形安装向导、向上游提交 PR、将运行时升级为 `stable` 正式发布,均须由人确认触发。自动化例外:Reims vGPU fork 的 Preview 工作流每天构建,通过 `alpha` 准入检查后在运行时仓库发布 GitHub 预发布。
3. **敏感与专有内容零入库**:严禁提交 SMC OSK、SMBIOS 真实序列号、MAC 地址、任何 Apple IPSW / BaseSystem / 解密固件或闭源二进制。
4. **对上游的修改只走补丁队列**:不长期维护 fork。补丁放 [`patches/`](patches/),顺序与状态统一在 [`patches/series.txt`](patches/series.txt) 与 [`patches/README.md`](patches/README.md) 维护,目标是清零。补丁打不上就停下报告,不要自动改写补丁。
4. **构建职责**:本仓库构建并发布客户端。便携运行时的编译、打包、依赖补丁和 Preview 发布由 [Reims vGPU fork 的 CI](https://github.com/yxc0915/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) 负责。
5. **运行时包如实声明来源**:`manifest.json` 必须写清上游各仓库 commit 与实际应用的全部补丁;带补丁的包不得宣称为纯上游构建。
6. **默认用户只拿 `stable` 通道**:CI 产物先入 `alpha`,经真实宿主冒烟并人工确认后才升为 `stable`(见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md))。
7. **配置写入只走 `reims-ctl set`**:不直接改写 `vm.toml`,保证上游校验与 OpenCore 重建生效(见 [`docs/design-guidelines.md`](docs/design-guidelines.md))。
8. **文档维护纪律**:`docs/` 只存放当前生效的长期文档,使用单一事实来源;不写私人本机路径、日期补丁式叙事、易过时的伪代码/ASCII 草图;一次性排查、审视与排期记录留在 Issue 或 PR 中。
9. **禁止空 `catch` 吞错**:严禁编写带有空代码块(含仅注释或空语句)的 `catch` 语句或空回调(如 `catch {}`、`catch (e) {}`、`.catch(() => {})`、`.then(..., () => {})`)把失败静默包装成成功;捕获异常后必须执行明确的错误处理(上报/展示错误、记录诊断告警、分类过滤预期错误并重抛其余异常,或显式回退状态)。该约束由 [`frontend/scripts/test-no-empty-catch.mjs`](frontend/scripts/test-no-empty-catch.mjs) 在 `pnpm --dir frontend test` 中强制校验。
## 开源合规边界
@@ -69,6 +70,8 @@
- [`docs/roadmap.md`](docs/roadmap.md) — 公开路线图与近期重点
- [`docs/architecture.md`](docs/architecture.md) — 系统架构、模块职责与安全边界
- [`docs/design-guidelines.md`](docs/design-guidelines.md) — 产品与界面设计规范(配置原语、状态模型、视觉与文案)
- [`docs/pr-review-guidelines.md`](docs/pr-review-guidelines.md) — PR 变更归属、跨仓交付与客户端独立性审查
- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时打包、发布通道与合规规范
- [`docs/plugin-architecture.md`](docs/plugin-architecture.md) — 插件系统架构与扩展接口规范
- [`patches/README.md`](patches/README.md) — 上游临时补丁队列与 PR 跟踪
- [`docs/guest-plugin-migration.md`](docs/guest-plugin-migration.md) — 客体插件化与 macOS 剥离的迁移路径
- [运行时补丁与上游跟踪](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) — 运行时源码入口与依赖补丁
+24
View File
@@ -2,6 +2,30 @@
本文件只记录 Reims-Go 桌面应用的变化。便携运行时(`runtime-*`)的版本另见 [Releases](https://github.com/Nwflower/Reims-Go/releases)。
## v0.2.11 — 2026-12-01
### 新功能
- **Intel 虚拟机挂起与瞬间恢复**([#37](https://github.com/Nwflower/Reims-Go/pull/37)):支持在虚拟机运行中挂起保存内存与图形状态并在下次启动秒级恢复,采用事务化状态保存、异常回滚与多通道直接 I/O 优化。
- **自定义共享文件夹与 WebDAV 路径隔离**([#38](https://github.com/Nwflower/Reims-Go/pull/38)、[#39](https://github.com/Nwflower/Reims-Go/pull/39)):Guest Tools 升级至 v8,支持按虚拟机配置自定义宿主机共享文件夹(含卷校验与设置页管理),并统一基于 `os.Root` 收紧 WebDAV 与回退文件同步的路径边界。
- **内置并行下载器插件与可扩展下载器接口**([#24](https://github.com/Nwflower/Reims-Go/pull/24)、[#52](https://github.com/Nwflower/Reims-Go/pull/52)):离线安装包与镜像下载支持多线程分片并行加速,并开放 `downloaders` 插件扩展点。
- **可插拔「镜像」页面与内置 macOS 镜像源**:将原安装包页升级为支持多插件镜像源切换的「镜像」页(`images.source` 扩展点),内置 macOS 镜像插件并接入品牌描边加载动画与服务可用性提示。
- **插件 UI / 桥接契约锁定与主题能力升级(uiApi 2.0 / bridgeApi 1.0)**:冻结插件契约,新增主题插槽(slots)、全窗装饰层(layers)、布局选项(侧栏位置/模式、界面紧凑度、标题栏高度)以及图标与品牌标志覆写。
- **虚拟机硬件、显示与交互增强**:
- 支持按虚拟机配置 Windows 修饰键重映射及 `Win` 键映射为 macOS `Command`([#53](https://github.com/Nwflower/Reims-Go/pull/53))。
- 支持一键轮换 OpenCore SMBIOS 硬件标识([#47](https://github.com/Nwflower/Reims-Go/pull/47))及可选同步宿主机 SMBIOS Type 17 内存规格([#44](https://github.com/Nwflower/Reims-Go/pull/44))。
- 支持 `qcow2` `extended_l2` 磁盘性能优化、快照改写保护与 Windows Defender 排除项引导([#56](https://github.com/Nwflower/Reims-Go/pull/56))。
- 全屏模式与客体分辨率解耦以支持 1.5x HiDPI 缩放([#22](https://github.com/Nwflower/Reims-Go/pull/22));新增关机模式选择与一键强制退出([#51](https://github.com/Nwflower/Reims-Go/pull/51))、虚拟机关闭确认弹窗及「关于」页 Discord 社区入口([#57](https://github.com/Nwflower/Reims-Go/pull/57))。
- 支持停用内置 macOS 客体插件并按驱动隔离虚拟机生命周期路由。
### 优化与修复
- **统一插件前端组件与视觉样式**:合并已安装列表、插件市场与首次向导中的插件图标块、信任徽标、胶囊筛选按钮与搜索框(补齐语言包图标识别与 RTL 逻辑属性),将插件危险确认弹窗、表单、复选框、错误提示条与加载骨架屏收敛至全局基础组件。
- **修复 Apple 在线恢复镜像鉴权与离线路径展开**([#34](https://github.com/Nwflower/Reims-Go/pull/34)):修复恢复镜像下载鉴权、分区 chunklist 校验及 `reims-ctl show` 主目录路径展开问题。
- **修复剪贴板互通与文件同步可靠性**([#28](https://github.com/Nwflower/Reims-Go/pull/28)、[#33](https://github.com/Nwflower/Reims-Go/pull/33)):加固 Windows 剪贴板锁与 DIB/PNG 回声抑制,修复回退同步删除传播、Windows 驱动器挂载认证及 CLI 直接启动时保留 Guest Tools 的问题。
- **修复 Vulkan 诊断与 GPU 驱动发现**([#21](https://github.com/Nwflower/Reims-Go/pull/21)、[#46](https://github.com/Nwflower/Reims-Go/pull/46)):清理失效的 GPU 驱动缓存文件,从活动显示驱动包中发现缺失的 Vulkan ICD 并在向导与 `doctor` 中展示探测诊断。
- **界面性能与工程健壮性加固**([#57](https://github.com/Nwflower/Reims-Go/pull/57)):消除软件合成模式下的弹窗卡顿,修复插件状态判定、列表错误上报与休眠虚拟机停用驱动插件问题,全面禁止空 `catch` 吞错并加入静态门禁测试;运行时发布源切换至独立的 Reims vGPU / QEMU fork 通道。
## v0.2.10 — 2026-11-30
### 新功能
+29 -2
View File
@@ -3,8 +3,9 @@
`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. Local compatibility patches under `patches/` are licensed under
terms compatible with their target upstream projects (see `patches/LICENSE`).
child process. Compatibility patches in the runtime repository are licensed
under terms compatible with their target upstream projects (see [runtime patch
licenses](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/LICENSE)).
The Reims-Go desktop executable also incorporates open-source Go and frontend
libraries (including Wails, React, Radix UI, Lucide, Inter font, Go `golang.org/x`
@@ -12,6 +13,32 @@ packages, `klauspost/compress`, and `ulikunitz/xz`) under permissive licenses
(MIT, BSD, ISC, and SIL OFL 1.1); see `go.mod` and `frontend/package.json` for
the complete dependency list.
### go-toml v2
The MIT License (MIT)
Copyright (c) 2021 - 2023 Thomas Pelletier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## Portable runtime
The portable runtime bundle (`reims-runtime-win-x64-<commit>.tar.zst`) contains
precompiled binaries built from the following upstream open-source projects.
Each runtime release ships the matching source package, `NOTICE.md`, and
+36 -1
View File
@@ -17,6 +17,8 @@
<a href="https://github.com/Nwflower/Reims-Go/releases"><img src="https://img.shields.io/github/v/release/Nwflower/Reims-Go?label=release&color=3b8cff" alt="release" /></a>
<a href="https://github.com/Nwflower/Reims-Go/stargazers"><img src="https://img.shields.io/github/stars/Nwflower/Reims-Go?style=flat&label=stars&logo=github&color=ffb86b" alt="GitHub stars" /></a>
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-ff7a9a" alt="license Apache-2.0" /></a>
<a href="https://discord.gg/Tj682rW5rS"><img src="https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white" alt="Discord" /></a>
<a href="https://qm.qq.com/q/TBmRJlVbSo"><img src="https://img.shields.io/badge/QQ%20Group-1136042744-12B7F5?logo=qq&logoColor=white" alt="QQ Group 1136042744" /></a>
<!-- Go daily list: uncomment after making it; replace %23N with the rank
<a href="https://github.com/trending/go?since=daily"><img src="https://img.shields.io/badge/Trending-%23N%20Go%20Repo%20of%20the%20Day-00ADD8?logo=go&logoColor=white" alt="GitHub Trending: Go Repo of the Day" /></a>
-->
@@ -32,7 +34,9 @@
<a href="https://github.com/Nwflower/Reims-Go/releases"><strong>Download</strong></a> ·
<a href="#quick-start">Quick Start</a> ·
<a href="#screenshots">Screenshots</a> ·
<a href="./docs/roadmap.md">Roadmap</a>
<a href="#plugin-development">Plugins</a> ·
<a href="./docs/roadmap.md">Roadmap</a> ·
<a href="#organization-and-community">Community</a>
</p>
<p align="center">
@@ -155,6 +159,37 @@ The binary is written to `build\bin\reims-go.exe`.
</details>
## Plugin Development
Reims-Go ships an out-of-process plugin system with zero external runtime dependencies. Browse and install plugins from the built-in **Plugins** page or import a local `.zip` archive; if a third-party plugin breaks startup, launch with `reims-go --safe-mode` to skip all third-party plugins.
- **L1 declarative plugins** (JSON + static assets): UI themes backed by the versioned [UI contract](./frontend/ui-contract.json), language packs (domain JSON + optional `.woff2` fonts), VM templates, runtime sources, input filters and rule hooks.
- **L3 sidecar plugins** (standalone executables in any language): one isolated process per plugin speaking `Content-Length`-framed JSON-RPC 2.0 over stdin/stdout for custom guest drivers (such as non-macOS VMs), lifecycle hooks, custom commands and diagnostics; Go authors can use the zero-dependency SDK in [`pkg/pluginsdk`](./pkg/pluginsdk).
- **Declarative UI extensions**: render native plugin settings from `settings` JSON Schema and contribute menu items, cards and status items to declared host slots.
<details>
<summary>Plugin development CLI</summary>
```powershell
reims-go plugin link <dir> | Out-Host # Link a local plugin directory for development
reims-go plugin doctor --contract frontend/ui-contract.json <dir|zip> | Out-Host # Run static security, manifest and UI contract checks
reims-go plugin locale init ja-JP --out <dir> | Out-Host # Scaffold a language pack
reims-go plugin locale check <dir> | Out-Host # Validate language pack coverage and syntax
reims-go plugin pack <dir> | Out-Host # Verify and pack a .zip with SHA256SUMS (optional --sign-key)
reims-go plugin search | Out-Host # Browse the official plugin market
```
</details>
- Full architecture, `plugin.json` manifest reference, permission tiers and protocol spec: [`docs/plugin-architecture.md`](./docs/plugin-architecture.md)
- Official plugin market index and submissions: [`reims-go/plugins`](https://github.com/reims-go/plugins)
## Organization and Community
- **GitHub Organization**: [`reims-go`](https://github.com/reims-go) — Maintains the official plugin market index ([`reims-go/plugins`](https://github.com/reims-go/plugins)) and ecosystem repositories; the desktop launcher repository lives at [`Nwflower/Reims-Go`](https://github.com/Nwflower/Reims-Go)
- **Discord**: [Join the Discord server](https://discord.gg/Tj682rW5rS) — Bilingual chat, troubleshooting, hardware compatibility reports, alpha testing and plugin development
- **QQ Group**: [1136042744](https://qm.qq.com/q/TBmRJlVbSo) — Chinese community chat and feedback
## License & Notice
- Reims-Go is licensed under [Apache-2.0](./LICENSE). Runtime components such as QEMU ship as separate programs; their licenses are in [`NOTICE.md`](./NOTICE.md), and every runtime release includes the matching source.
+36 -1
View File
@@ -17,6 +17,8 @@
<a href="https://github.com/Nwflower/Reims-Go/releases"><img src="https://img.shields.io/github/v/release/Nwflower/Reims-Go?label=release&color=3b8cff" alt="release" /></a>
<a href="https://github.com/Nwflower/Reims-Go/stargazers"><img src="https://img.shields.io/github/stars/Nwflower/Reims-Go?style=flat&label=stars&logo=github&color=ffb86b" alt="GitHub stars" /></a>
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-ff7a9a" alt="license Apache-2.0" /></a>
<a href="https://discord.gg/Tj682rW5rS"><img src="https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white" alt="Discord" /></a>
<a href="https://qm.qq.com/q/TBmRJlVbSo"><img src="https://img.shields.io/badge/QQ%20群-1136042744-12B7F5?logo=qq&logoColor=white" alt="QQ 交流群 1136042744" /></a>
<!-- Go 日榜:上榜后取消注释,把 %23N 改成名次
<a href="https://github.com/trending/go?since=daily"><img src="https://img.shields.io/badge/Trending-%23N%20Go%20日榜-00ADD8?logo=go&logoColor=white" alt="GitHub Trending: Go 日榜" /></a>
-->
@@ -32,7 +34,9 @@
<a href="https://github.com/Nwflower/Reims-Go/releases"><strong>下载</strong></a> ·
<a href="#快速开始">快速开始</a> ·
<a href="#界面">界面</a> ·
<a href="./docs/roadmap.md">路线图</a>
<a href="#插件与开发">插件与开发</a> ·
<a href="./docs/roadmap.md">路线图</a> ·
<a href="#项目组与社区">项目组与社区</a>
</p>
<p align="center">
@@ -155,6 +159,37 @@ wails build
</details>
## 插件与开发
Reims-Go 内置进程外隔离的插件体系,零外部运行时依赖。可以在应用的「插件」页直接浏览安装官方市场插件或导入本地 `.zip` 包;如插件引发启动异常,可用 `reims-go --safe-mode` 跳过全部第三方插件恢复。
- **L1 声明式插件**(纯 JSON + 静态资源):界面主题(基于稳定的 [UI 契约](./frontend/ui-contract.json))、多语种语言包(分域 JSON 与可选 `.woff2` 字体)、虚拟机模板、运行时源、输入过滤与规则 Hook。
- **L3 Sidecar 插件**(任意语言独立可执行文件):每插件独立进程,通过 stdin/stdout `Content-Length` 分帧 JSON-RPC 2.0 通信,可用于非 macOS 虚拟机驱动、生命周期 Hook、自定义命令与排障采集;Go 开发者可直接使用零依赖 SDK [`pkg/pluginsdk`](./pkg/pluginsdk)。
- **声明式 UI 扩展**:通过 `settings` JSON Schema 原生渲染插件设置页,向宿主预定义槽位贡献菜单项、卡片与状态项。
<details>
<summary>插件开发常用命令</summary>
```powershell
reims-go plugin link <dir> | Out-Host # 链接本地插件目录用于开发调试
reims-go plugin doctor --contract frontend/ui-contract.json <dir|zip> | Out-Host # 静态安全扫描与清单/UI 契约校验
reims-go plugin locale init ja-JP --out <dir> | Out-Host # 生成多语种语言包脚手架
reims-go plugin locale check <dir> | Out-Host # 校验语言包覆盖率与格式
reims-go plugin pack <dir> | Out-Host # 校验并打包 .zip(自动生成 SHA256SUMS,支持 --sign-key)
reims-go plugin search | Out-Host # 浏览官方插件市场
```
</details>
- 完整插件架构、清单字段(`plugin.json`)、权限分级与协议规范见 [`docs/plugin-architecture.md`](./docs/plugin-architecture.md)
- 官方插件市场索引与投稿发布见 [`reims-go/plugins`](https://github.com/reims-go/plugins)
## 项目组与社区
- **GitHub 项目组**:[`reims-go`](https://github.com/reims-go) — 维护官方插件市场索引([`reims-go/plugins`](https://github.com/reims-go/plugins))及周边生态项目;桌面客户端主仓库位于 [`Nwflower/Reims-Go`](https://github.com/Nwflower/Reims-Go)
- **Discord 社区**:[加入 Discord 服务器](https://discord.gg/Tj682rW5rS) — 中英双语交流、排障求助、硬件兼容性实测、Alpha 测试与插件开发
- **QQ 交流群**:[1136042744](https://qm.qq.com/q/TBmRJlVbSo) — 中文日常交流与使用反馈
## 许可与声明
- Reims-Go 采用 [Apache-2.0](./LICENSE) 协议。运行时里的 QEMU 等组件作为独立程序随附,许可证见 [`NOTICE.md`](./NOTICE.md),每个运行时 Release 都附带对应源码。
+28 -11
View File
@@ -54,23 +54,26 @@ flowchart TB
| :--- | :--- |
| `main.go`、`console_*.go` | 统一入口:无参数启动 Wails GUI,带子命令进入 `internal/cli`;处理 GUI 子系统下的父控制台句柄接管 |
| `internal/app` | Wails 绑定与桌面编排(启停、安装、快照、CoW 派生、磁盘扩容/回收、SSH、脱敏排障包、任务状态、运行监视) |
| `internal/vmstart` | GUI 与 CLI 共用的启动前准备:提交内存预检、离线辅助盘、恢复模式引导、客体语言重放、WHPX 兼容处理、启动后 CPU 绑核 |
| `internal/vmstart` | 通用启动辅助:提交内存等待、启动后 CPU 绑核、亲和性配置与命令行日志 |
| `internal/macos/startprep` | macOS 启动前准备:WHPX/内存检查、离线辅助盘、恢复模式引导、客体语言重放与兼容处理 |
| `internal/cli` | 命令行子命令实现、单实例参数解析与向界面进程交接 `vm start` |
| `internal/host` | 宿主机体检与硬件调优:WHPX 检测与 UAC 启用、提交内存预检、Vulkan ICD 扫描、三层大小核拓扑与实时绑核、显示器 HiDPI 推荐、音频与磁盘总线探测、窗口置前、IME 文本钩子 |
| `internal/runtime` | 便携运行时拉取(GitHub Releases)、原子解压、多版本切换与子进程环境变量构造 |
| `internal/fetch` | 发布附件下载:HTTP `Range` 续传与按发布页 `SHA256SUMS.txt` 强制校验,运行时安装与应用内更新共用 |
| `internal/selfupdate` | 应用内更新:把已校验的新版 `reims-go.exe` 换入运行中程序的位置、重新拉起与残留清理 |
| `internal/installer` | 包装 `reims-util --json` 实现 macOS 离线安装包查询、宿主机直连下载、断点续传、互斥锁保护与缓存清理 |
| `internal/driver/reims` | `reims-ctl` 与 `qemu-img` 受控子进程包装、输出解析、快照/派生/导入操作、日志与配置脱敏 |
| `internal/macos/installer` | 包装 `reims-util --json` 实现 macOS 离线安装包查询、宿主机直连下载、断点续传、互斥锁保护与缓存清理 |
| `internal/macos/reims` | `reims-ctl` 与 `qemu-img` 受控子进程包装、输出解析、快照/派生/导入操作、日志与配置脱敏 |
| `internal/macos/macosdriver` | 把 `internal/macos/reims` 适配为通用 `driver.Driver`(内置驱动 `builtin.driver.reims-macos`) |
| `internal/macos/guest` | 内置可选插件 `builtin.guest.macos`:静态驱动声明、宿主体检、启动与兼容 Hook、安装引导服务,以及数据布局 v2 的状态与参数账本迁移 |
| `internal/macos/installguide` | 虚拟机窗口旁的 macOS 安装与恢复分步引导(Win32 浮层) |
| `internal/qmp` | QMP 客户端:键盘键入、截屏与 Win10 冷重启监视 |
| `internal/guesttools` | 本地回环鉴权 HTTP/WebDAV 服务:图文双向剪贴板、共享目录、Windows 盘符只读共享、防休眠开关与 `REIMSTOOLS` 辅助盘生成 |
| `internal/opencore` | 改写 OpenCore 镜像中的 `prev-lang:kbd`,实现系统外预设 macOS 语言 |
| `internal/macos/opencore` | 改写 OpenCore 镜像中的 `prev-lang:kbd`,实现系统外预设 macOS 语言 |
| `internal/netproxy` | 统一 HTTP Transport:优先环境变量代理,回退读取 Windows 系统代理配置 |
| `locales/`、`cmd/i18ngen` | 单一事实源分域 JSON 词表(含译者上下文 `$comment` 与 Apple macOS 官方多语种词汇表)及编译期前后端字典代码生成器 |
| `internal/config`、`internal/i18n` | 应用配置持久化(`reims-go.json`)、轻量 ICU 格式化引擎、多跳语言回退链与带稳定排障码的结构化错误(`CodedError`) |
| `internal/thumb`、`internal/tray`、`internal/version` | 4K 截屏行级缩放预览、Windows 系统托盘常驻、版本信息与新版本检查 |
| `frontend/src` | 桌面界面:`components/`(页面与对话框)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
| `patches/` | 上游临时补丁队列与 PR 跟踪,见 [`patches/README.md`](../patches/README.md) |
| `frontend/src` | 桌面界面:`components/`(页面与对话框)、`macos/`(macOS 专属页面与组件)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
| `scripts/` | 便携运行时打包、二进制裁剪与符号分离、MSYS2 源码归档、`alpha` 准入与冒烟脚本,以及 `scripts/debug/` 本地调试目录管理与卫生校验脚本 |
---
@@ -78,8 +81,8 @@ flowchart TB
## 4. 关键机制与安全边界
### 4.1 启动编排与单实例交接
- `internal/vmstart` 承载 GUI 与 CLI 共用的启动步骤;只有常驻进程才能维持的能力(Guest Tools 桥接、Win10 冷重启监视)由界面进程托管。
- CLI 执行 `vm start` 时,默认交由桌面进程启动:界面已在运行时通过 Wails 单实例锁(`WM_COPYDATA`)发消息不弹窗拉起;未运行时以 `--background` 启动隐藏到托盘的后台界面进程,结果经 `<DataRoot>\tmp\cli-start-*.json` 回传并带退出码返回。
- `internal/lifecycle` 统一 GUI、CLI 与窗口交接的 VM 列表、详情、设置、启动、停止、重启、删除、介质动作和日志读取:按 `VMRef` 解析所属驱动,先收集第三方 Hook,否决时不调用驱动,成功后再发事件。macOS 的启动前检查、参数账本与磁盘准备由 `internal/macos/macosdriver` 自己完成,准备失败即中止;`internal/vmstart` 保留共享检查与旧回退。只有常驻进程才能维持的能力(Guest Tools 桥接、Win10 冷重启监视)由界面进程托管。
- CLI 执行 `vm start` 时,默认交由桌面进程启动:界面已在运行时通过 Wails 单实例锁(`WM_COPYDATA`)发消息不弹窗拉起;未运行时以 `--background` 启动隐藏到托盘的后台界面进程,结果经 `<DataRoot>\tmp\cli-start-*.json` 回传并带退出码返回。交接同时携带 `--start-driver=`,裸名称不再作为跨驱动的完整身份。
- 仅在 CLI 显式指定 `--data-root` 时由命令进程直接启动,此时不包含 Guest Tools 桥接与 Win10 冷重启监视。
- `reims-go.exe` 编译为 Windows GUI 子系统程序,命令行模式下保留调用方管道/文件句柄,缺失时通过 `AttachConsole` 挂载父控制台;在交互式 PowerShell/cmd 中加 `| Out-Host` 可等待命令执行完毕。
@@ -88,13 +91,13 @@ flowchart TB
- **Win10 冷重启监视通道**:Windows 10 19045 缺少 `WHvResetPartition`,客体热重启会导致 WHPX 退出异常。在 Win10 宿主上,启动时附加 `-no-reboot` 并另开一条独立的 `AF_UNIX` QMP 通道监听重启退出事件,干净退出后自动重新拉起。使用 `AF_UNIX` 而非 TCP,避免客体经 SLIRP 的 `10.0.2.2` 访问宿主机监控接口。
### 4.3 Guest Tools 与宿客安全边界
- Guest Tools 服务仅监听 `127.0.0.1`,每台虚拟机分配独立的 256-bit 随机 Token(Bearer / Basic 鉴权)。
- Guest Tools 服务仅监听 `127.0.0.1`,每台虚拟机分配独立的 256-bit 随机 Token(Bearer / Basic 鉴权)。注册表、连接状态、剪贴板策略、文本输入与 WebDAV handler 按 `driver.VMRef.Key()` 隔离;token 认证同时识别驱动与名称,既有客体 URL 不变。
- WebDAV 共享目录(`/dav/<vm>/`)严格校验路径防目录穿越;Windows 盘符只读共享(`/dav/<vm>/drives/<盘符>/`)默认全部关闭,服务端同时限制 HTTP 写方法与只读打开标志、校验持久化 Volume GUID 防盘符漂移、限制 `PROPFIND Depth` 并校验 Junction/符号链接解析目标仍在授权盘符内。
### 4.4 宿主机体检与硬件调优
- **免提权 WHPX 检测**:通过 `WinHvPlatform.dll`(`WHvGetCapability`)与系统功能查询判断状态,仅在缺失且用户确认时通过 `ShellExecuteW(..., "runas", ...)` 触发 UAC 启用。
- **提交内存预检**:通过 `GlobalMemoryStatusEx` 检查可用提交内存(`AvailPageFile`),因为 QEMU 在 Windows 上会一次性提交整块客体内存;建机时推荐安全档位,启动前余量不足时提前拦截。
- **GPU 与大小核**:扫描注册表 Vulkan ICD 并过滤虚拟显示适配器;解析 `GetLogicalProcessorInformationEx` 识别 P / E / LP-E 三层混合核心,支持按 VM 实时调整进程亲和性,避免超售卡顿。
- **GPU 与大小核**:扫描注册表 Vulkan ICD 并过滤虚拟显示适配器;解析 `GetLogicalProcessorInformationEx` 识别 P / E / LP-E 三层混合核心,支持按 VM 实时调整进程亲和性,避免超售卡顿。宿主只评估通用硬件事实;`kernel_irqchip`、冷重启等 macOS/WHPX 建议由所属驱动的 `driver.OptimizationAdvisor` 提供,与启动准备共用运行时判定。
### 4.5 应用内更新
- 界面启动后检查一次新版本,之后每 6 小时检查一次(后端缓存 10 分钟),只看 `vX.Y.Z` 正式版,忽略草稿与预发布。有新版本时侧栏顶部显示更新胶囊卡片,关于页提供同样的操作。
@@ -104,10 +107,24 @@ flowchart TB
- 开发构建(`wails dev`,`dev` 标签)与非 Windows 平台不支持应用内更新;程序所在目录不可写(如未提权的 `Program Files`)时提示改为手动更新。
### 4.6 资源回收与内存约束
- 按 VM 生命周期分配的状态(缩略图锁、Guest Tools 注册与 WebDAV handler、进程采样、绑核记录、文本队列与 worker)在删除 VM 或轮询发现外部删除时立即回收。
- 按 VM 生命周期分配的状态(过渡态、待生效设置、冷重启监视、磁盘路径缓存、进程采样、缩略图与键入锁、文本队列与 worker)以 `driver.VMRef.Key()` 隔离,并在删除 VM 或轮询发现外部删除时立即回收;VM 日志来源也使用规范键。
- 日志监视器对单行无换行输出设 **64 KiB** 内存上限(原始日志文件完整保留);已结束任务在 10 分钟后从前后端状态中清理。
- 4K 屏幕预览采用按行流式缩放降低单帧分配;手动复制截图仍保留全分辨率。不在热路径中人为调用 `debug.FreeOSMemory`。
### 4.7 数据目录版本与迁移
- `<DataRoot>\.reims-go-data.json` 记录数据布局版本 `data_version`,以及最后一次提升它的应用版本 `written_by`。它不放进 `reims-go.json`,因为配置每次保存都会按结构体整体重写,旧版本会丢掉不认识的字段。
- 每个版本都带着从旧布局升到自身布局的全部迁移步骤(`internal/datamigrate`),GUI 与 CLI 启动时、读取数据之前按版本号依次执行。步骤必须可重复执行;某步失败时,版本号停在最后一个成功的步骤,下次启动从那里继续。用户可以从任意旧版本直接升到新版本。
- GUI 启动、首次设置、切换数据目录与 CLI 都经 `internal/dataroot` 打开数据目录:先不加锁读取版本戳,需要迁移时才取 `<DataRoot>.reims-go.lock` 并在锁内重读版本戳,两个进程同时打开同一目录时迁移只执行一次。
- 数据目录由更新版本写入、版本戳无法解析、迁移失败或另一进程长时间持锁时,以只读模式打开,不创建或修改任何文件(包括锁文件):GUI 不启动插件、不轮询虚拟机,以只读界面代替工作台;CLI 只放行 `version`、`help` 与 `doctor`。版本戳损坏时可由用户显式修复,从 v0 重新执行全部步骤。
- 首次设置选定目录之前,宿主不写入默认建议目录:不迁移、不启动插件、不轮询,界面中的选择只保存在内存里,由 `CompleteSetup` 写入选定的目录。
- 只有删除很老的迁移步骤之后,才需要「最低迁移版本」:新版本根据 `data_version` 判断,并提示先安装某个中间版本。这个判断看的是数据本身,所以直接下载新版本运行也会生效。
- 现有步骤:v1 为 reims-ctl 管理的每台 VM(目录含 `vm.toml`)补写驱动归属标记,见 [plugin-architecture.md](plugin-architecture.md) 的「VM 归属」;v3 一次性把正式版 `builtin.core` 的设置、`builtin.install-guide` 的启停和已知参数账本条目迁入 `builtin.guest.macos`,把按裸 VM 名的插件设置键改为 `driverID:vmName`,并补扫无归属标记的 VM。`state.json` 只加载、保存一次,原始 `.bak` 不被中间布局覆盖;功能分支上的 v2 仍可直升,未公开发布过的旧插件 ID 不做长期迁移。
### 4.8 macOS 代码边界
- macOS 专属代码集中在 `internal/macos/` 与 `frontend/src/macos/`,最终作为独立插件移出本仓库;宿主只应经驱动层(`driver.Router`)与宿主服务使用它。
- 三个棘轮测试守住边界:`internal/archtest` 分别检查宿主到 macOS、macOS 到宿主私有 Go 包的依赖,`frontend/scripts/test-macos-boundary.mjs` 检查前端文件。只有列入清单的包或文件可以跨界;新增引用、或清单中的条目已不再引用时,测试都会失败,所以清单只能缩短。
- 宿主到 macOS 的例外包括 GUI 与 CLI 的组装入口、数据布局 v2 的迁移,以及仍混有宿主与 macOS 逻辑、待拆分的 `internal/guesttools`。反向清单记录 macOS 对宿主私有包的现有依赖,随公开接口建设逐步清零。
---
## 5. 与上游 `reims-vgpu` 的边界
+6 -3
View File
@@ -20,7 +20,7 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台
| :--- | :--- |
| **声明式配置** | 一台虚拟机对应一份声明式配置,界面只编辑配置项,不让用户直接拼 QEMU 命令行参数。 |
| **先校验,后保存** | 保存前在 Go 端完成前置校验(CPU 核数、可用提交内存上限、Vulkan ICD 路径存在性、切换磁盘控制器前是否已弹出安装盘),非法值在提交前拦截。 |
| **随时可编辑,标明生效时机** | 无论虚拟机运行与否,设置面板均可打开编辑;每项设置明确标注生效时机。运行中保存「下次启动生效」的修改时,详情页汇总待生效项并提供「重启以应用」。 |
| **标明设置的生效时机** | 虚拟机运行中或已停止时可编辑设置。每项设置明确标注生效时机。运行中保存「下次启动生效」的修改时,详情页汇总待生效项并提供「重启以应用」。 |
**写入约束**:凡属于上游 `reims-ctl` 管理的配置项,一律通过 `reims-ctl set` 写入,不直接改写 `vm.toml`,确保上游校验与 OpenCore 重建逻辑照常生效。
@@ -55,11 +55,14 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台
| **正在创建** | 创建流程进行中 | 无(展示分步进度) | 取消创建 |
| **已停止** | 上游 `stopped` | **启动** | 设置、恢复点、更多(派生副本、扩容/回收、打开目录、删除) |
| **正在启动** | 发起 `start` 至 `running` | 启动中(忙碌态,禁用) | 设置、强制关机 |
| **运行中** | 上游 `running` | **显示 VM 窗口** | 关机、截屏、设置、更多(重启、强制关机、发送文本、进入/退出恢复模式、导出排障包) |
| **运行中** | 上游 `running` | **显示 VM 窗口** | 挂起(需支持此功能的内核)、关机、截屏、设置、更多(重启、强制关机、发送文本、进入/退出恢复模式、导出排障包) |
| **正在停止** | 发起 `stop` 至 `stopped` | 停止中(忙碌态,禁用) | 强制关机 |
| **正在挂起** | 正在保存运行状态 | 挂起中(忙碌态,禁用) | 强制关机 |
| **已挂起** | 运行状态已保存到磁盘 | **恢复**(需支持此功能的内核) | 更多(放弃挂起状态、打开目录) |
| **正在恢复** | 正在从磁盘恢复运行状态 | 恢复中(忙碌态,禁用) | 强制关机 |
| **配置损坏** | 上游 `broken` | **查看问题** | 打开目录、删除 |
- 暂不提供暂停或运行中热快照状态(`paused` / `saving` / `restoring`),直到上游验证 `reims-vgpu` 显存与设备状态序列化。
- 已挂起时,恢复或放弃挂起状态后才可修改配置、管理磁盘和安装或弹出 Guest Tools。切换到不支持挂起的内核时,禁用恢复并提示用户切换内核。放弃挂起状态须经破坏性操作确认框确认。
- 禁用按钮不占据主操作位置;状态变化时直接切换为当前最合适的主操作。
---
+272
View File
@@ -0,0 +1,272 @@
# 客体插件化与 macOS 剥离方案
> 状态:待评审。本文描述从现有代码走到"与客体无关的主程序 + macOS 外部插件"的路径。[plugin-architecture.md](plugin-architecture.md) 记录的是插件系统当前的权威设计;本文的每一步合入时,同步修改该文对应章节(§3.2、§5.3、§5.4、§12 等),两份文档不得长期并存矛盾。
## 1. 目标与边界
- **终态**:主程序是与客体无关的本地虚拟机工作台。macOS 能力作为外部插件(独立仓库、独立发布)提供;主程序的源码、文档、语言词表、发布物与运行时流水线不含 macOS 专属内容。
- **过渡态**:macOS 先成为内置插件 `builtin.guest.macos`,仍随 `reims-go.exe` 编译。过渡期只保证两件事,以免外置时再做一次迁移:
- **职责与数据按终态划分**:设置、参数账本、VM 归属、启动准备从一开始就归 macOS 插件与它的驱动所有。
- **调用面按终态收敛**:macOS 代码只经驱动接口、Hook 与宿主服务使用宿主;它对宿主 Go 包的依赖逐步收敛到可公开的 `pkg/` 包(第 6 节的反向棘轮)。
- 界面是唯一允许的例外:过渡期可挂载原生页面,步骤 5 替换。
- **特权按角色而不是按 ID 前缀**:宿主内置插件(留在主程序的部分)保留现有特权;拥有某台 VM 的驱动,对该 VM 的启动参数拥有完整控制(含 `-drive`、`-chardev`、`-qmp` 等),无论它是内置还是外部。外部驱动本身是 L3 原生程序,拥有完整账户权限,这不构成提权;第三方 Hook 仍受现有脱敏、超时与参数族限制。
- **Linux 驱动**用于验证接口通用性,按 plugin-architecture.md Phase 4 以独立仓库的 L3 插件实现。Android 只预留接口。
- **不在本方案内**:常驻后台服务、OCI 分发、运行态热迁移、整盘导出导入、稳定 VM ID(第 8 节)。
- 哪些内容构成法律风险、需剥离到什么程度,不由本文判断,见第 9 节。
## 2. 现状
macOS 代码已集中到 `internal/macos/`(`installer`、`opencore`、`installguide`、`reims`、`macosdriver`)与 `frontend/src/macos/`,宿主到 macOS 的 import 由两处棘轮测试守住([architecture.md](architecture.md) §4.8)。仍需解决的问题:
### 2.1 身份与数据
| 问题 | 现状 |
| :--- | :--- |
| 驱动 ID 与旧插件 ID 混用 | `builtin.driver.reims-macos` 同时列在 `builtin.RetiredIDs` 中,不能直接拿来做新插件 ID |
| 设置迁移不原子 | `MigrateRetired` 先落盘删除旧记录,再单独落盘新设置;两次写盘之间退出会丢失用户关闭过的选项 |
| 安装引导独立成插件 | `builtin.install-guide` 是独立可选插件,内容是纯 macOS 的安装与恢复引导 |
| 使用中保护依赖静态声明 | 使用中检查经 `DeclaredDriverIDs` 读取清单的 `guestDrivers`;`builtin.core` 在激活时动态注册驱动,未静态声明。核心插件不可停用所以目前无害,macOS 插件可停用后会失效 |
| VM 以裸名称索引 | `PluginRecord.VMSettings` 以 VM 名为键;宿主内存态(`transitions`、`pendingChanges`、`rebootWatchers`、`diskPaths`、`procSamples`)、Guest Tools 注册表、缩略图与键入锁、日志来源同样以名称索引;界面进程交接参数 `--start-vm=` 不带驱动 |
| VM 目录只有一个根 | 路由与"驱动不可用"扫描只看 `<DataRoot>/data/reims-ctl/vms` |
| 运行时只能选一个 | `config.ActiveRuntime` 是单个字符串;非默认种类直接取已安装列表第一项;已装多个 reims-vgpu 运行时且未选定时,所有依赖运行时的功能失败 |
### 2.2 数据目录写入
GUI 启动、首次设置、`SetDataRoot`、CLI 各自打开数据目录;迁移失败时 GUI 只记日志、CLI 只打印警告;`SetDataRoot` 先保存配置再迁移;首次设置完成前,宿主已把默认建议目录当作数据目录读写;版本戳损坏时按 v0 重跑;没有跨进程写锁。
### 2.3 启动链路
| 问题 | 现状 |
| :--- | :--- |
| 启动入口 | GUI 的 `App.StartVM` 直接取 reims 客户端、自做 WHPX 检查,启动事件写死 macOS 驱动 ID 与能力;CLI 有直接启动(`startVM`)与交给界面进程(`startInWindow`)两条路径 |
| 启动准备放在公共 Hook | `builtin.core` 的 `vm.beforeStart` 依次执行离线辅助盘、恢复启动、引导语言、WHPX 兼容降级、Win10 冷重启五步;恢复与语言两步在回调里直接写恢复标记、改写 OpenCore 镜像,后续插件否决时磁盘已被改动 |
| 特权按前缀 | `BuiltinOnlyQEMUOptionFamilies`(`-drive`、`-chardev`、`-qmp`、`-fw_cfg`、`-global`、`-object`)、宿主环境变量白名单与 `PostStart` 动作都按 `builtin.` 前缀放行;外部插件的 `vm.beforeStart` 拿不到 `VMDir`、`ExtraArgs`、`InstallerPath`,单个回调限时 2 秒 |
| 驱动接口缺参数 | `Driver.Start` 只收 VM 名,不接收合并后的参数、环境变量与启动后动作;参数账本的合并结果在 `StartVM` 中经 `reims-ctl set --extra-args` 写入;`stripLegacyManagedExtraArgs` 在 `internal/app` 中直接调用 macOS 代码 |
| 调优不分驱动 | `host.EvaluateOptimizations` 一次算出绑核、irqchip、冷重启、独显与 CoW 建议 |
### 2.4 路由与界面
列表、详情、设置、停止、删除、日志等十余处直接调用 reims 客户端;`Router.ListAllVMs` 没有调用方且按名称去重;`Router.ResolveVM` 返回第一个同名结果;CLI 只有 `vm create --driver` 走驱动层;前端类型直接使用 `reims.VMDetail`,`CreateWizard`、`SettingsModal`、`lib/tasks.ts` 含 OpenCore、恢复、引导语言、无边框、安装包等字段与交互(不经 import,棘轮看不到)。
### 2.5 外置障碍
| 问题 | 现状 |
| :--- | :--- |
| Go 可见性 | `internal/macos/*` 导入宿主的 `internal/config`、`host`、`i18n`、`driver`、`plugin`、`runtime`、`vmstart`;外部仓库不能导入别的模块的 `internal/` 包 |
| SDK | `pkg/pluginsdk` 只有 JSON-RPC 骨架 |
| 反向宿主接口 | Sidecar 只能调用 `notify`、`audit`、`vm.spawn`、`vm.stop`、`vm.isRunning`;没有运行时查询、内存预检、绑核、日志与任务、进程退出、窗口信息等服务 |
| 外部界面 | 外部插件不能贡献整页界面;沙箱 iframe 没有文件选择、流式任务进度、弹窗与尺寸协调等桥接 |
| 非 import 耦合 | 全局脱敏器(`i18n.SetDetailRedactor`、插件管理器 `RedactFn`、排障包、界面错误上报)都直接用 `reims.RedactText`;`internal/runtime` 内置 `DefaultKind = "reims-vgpu"`、`reims-ctl` / `reims-util` 路径、reims 专用环境变量、按补丁推断能力与发布源;`locales/*/macos-glossary.json` 与 `internal/i18n/glossary.go`,以及 `vm`、`wizard`、`settings` 等词表中的 macOS 文案;`internal/app/macos_release.go`(`.reims-go-macos`);数据目录禁止逗号源于 `reims-util`;`internal/host` 中面向 reims-vgpu / metal2vulkan 的显卡兼容判断;CLI 顶层 `installer` 子命令 |
| 外围文件 | `patches/`、`.github/workflows/build-runtime.yml`、`scripts/` 中的运行时打包与补丁脚本、`docs/portable-runtime-spec.md` |
## 3. 身份模型
| 身份 | 作用 | 规则 |
| :--- | :--- | :--- |
| 插件 ID | 启停、设置、贡献、参数账本归属 | 过渡期 `builtin.guest.macos`;外部插件不可使用 `builtin.` 前缀,换新 ID,经声明式承接接收旧 ID 的数据(见下) |
| 驱动 ID | 一台 VM 由谁管理,写在 VM 目录的 `.reims-go-driver` | 过渡期保留 `builtin.driver.reims-macos`;外部驱动换新 ID,并把旧 ID 声明为别名,已有标记不改写 |
| 运行时种类 | 安装哪套可执行程序、驱动要求的接口版本 | 每种类单独选定活跃运行时(步骤 3.5) |
| VM 引用 `VMRef` | 一次操作、一份设置或一项内存状态针对哪台 VM | `{驱动 ID, 驱动内名称}`,自步骤 2 起贯穿宿主;稳定 VM ID 见第 8 节 |
| VM 目录根 | 驱动的 VM 放在哪里 | 驱动在清单中静态声明自己的 VM 根目录(相对 DataRoot);macOS 驱动声明现有的 `data/reims-ctl/vms`。停用的驱动清单仍可读,宿主据此扫描"驱动不可用"的 VM,两个驱动的同名 VM 不会在磁盘上冲突 |
**声明式承接**:外部插件在清单中声明 `replaces`(它承接的旧插件 ID)与驱动 `aliases`(它承接的旧驱动 ID)。宿主在**安装或首次激活该插件时**把旧 ID 名下的设置、参数账本条目与按 VM 设置转给它,并让带旧驱动 ID 标记的 VM 归它管理。约束:
- 宿主在旧插件消失后保留其 `state.json` 记录与账本条目,直到有插件承接,期间这些 VM 显示"驱动不可用"。
- 承接 `builtin.*` ID 只允许信任等级为 `official` 的包,或经用户逐项确认,防止任意插件接管已有 VM。
- 主程序不硬编码任何 macOS 新旧 ID 映射。数据迁移带入的 `driver.RenamedDriverIDs` 只用于主程序内部的内置驱动改名,外部插件改名一律走 `aliases`。
驱动 ID 从此与插件 ID 分开:步骤 1 将 `builtin.driver.reims-macos` 移出 `RetiredIDs`,只有正式发布过的旧记录进入迁移清单:`builtin.core` 的设置与账本,以及 `builtin.install-guide` 的启停。未公开发布过的独立 theme/driver、compat/prep 插件记录不迁移、不删除。
## 4. 分步方案
每一步单独合入、单独发布,完成后对应的棘轮例外缩短(第 6 节)。
### 步骤 0:数据目录写入保护
后续每一步的数据迁移都依赖它;不依赖第 3 节的任何决定,可以立即开始。
- **统一打开入口**:新增宿主包(暂名 `internal/dataroot`),GUI 启动(`config.Resolve`)、首次设置(`CompleteSetup`)、切换目录(`SetDataRoot`)与 CLI 都经它进入。顺序为:
1. 不加锁读取版本戳。版本高于本程序、或版本戳无法解析时,以只读模式返回,**不创建锁文件、不写任何文件**。
2. 需要迁移或即将写入时,才创建并获取写锁,**拿锁后重新读取版本戳**,再决定是否迁移。另一个进程已完成迁移时直接返回。
3. 迁移完成、版本戳写入后释放写锁。
- **写锁**:把 `internal/macos/installer` 中基于 `LockFileEx` 的文件锁上提为宿主公共实现(`internal/filelock`),锁文件放在数据目录内,只在迁移时持有。配置与 `state.json` 都以临时文件加改名的方式原子写入,单次写入不会留下残缺文件,因此不为单次写入加锁;GUI 与 CLI 同时修改同一份配置时的相互覆盖不在本步解决。
- **只读诊断模式**:GUI 不启动插件、不轮询虚拟机,以只读界面代替工作台,说明原因与详细信息,可选择其他目录;版本记录损坏时提供显式"修复(从 v0 重新迁移)",另一进程升级中或升级失败时提供"重试"。CLI 只放行 `version`、`help` 与 `doctor`,其他命令以非零退出码拒绝。
- **写入点清单**(只读模式与首次设置前全部拦截):`reims-go.json`、`plugins/state.json` 与其备份、市场索引缓存、版本戳、启动哨兵 `.startup-sentinel`、`cli-start-*.json`、界面健康日志 `logs/ui-health.log`、应用更新后对更新下载目录的清理、VM 目录内的参数账本与归属标记。`CompleteSetup` 对候选目录的可写性探测(`.write-test-*`)只针对用户已选定的目录,保留。
- **首次设置前零写入**:`needsSetup` 期间不把默认建议目录当作数据目录,数据迁移、插件状态与配置保存都要等目录选定。`REIMS_GO_FIRST_RUN` 测试模式必须同时指定隔离的数据目录,否则拒绝启动。
- **CLI 交给界面进程**:`location.json` 位于数据目录之外。CLI 未指定数据目录、经单实例交给界面进程时,以界面进程当前打开的目录为准;该目录处于只读模式时,写命令被拒绝并说明原因。
- **`MigrateRetired` 一次落盘**:删除旧记录与写入新设置合并为一次 `state.json` 原子替换。
**验收**
- 高版本或版本戳损坏的数据目录:GUI 进入只读模式、CLI 写命令被拒,目录内无任何文件(含锁文件)被创建或修改。
- 首次设置测试模式与设置完成前,默认建议目录内无任何文件被创建或修改。
- 在 `MigrateRetired` 两步之间模拟退出,重启后用户关闭的选项仍为关闭。
- GUI 与 CLI 同时启动并触发迁移,迁移只执行一次,结果一致。
### 步骤 1:macOS 插件身份与元数据迁移(已落地,合并至 v3)
- 新增内置插件 `builtin.guest.macos`,注册代码放在 `internal/macos/guest` 内,由 GUI 与 CLI 组装入口注册。`builtin.core` 只保留客体无关的默认主题。过渡期 macOS 插件默认启用,以保留存量 VM 的升级行为。
- **安装引导并入**:`builtin.install-guide` 并入 `builtin.guest.macos`,成为它的一个可开关功能;旧 ID 退役,用户原来的启用状态转为新插件的对应设置。外部 macOS 插件因此只是一个包。
- **静态声明驱动**:新插件在清单 `guestDrivers` 中静态声明 `builtin.driver.reims-macos`,运行中检查才能阻止在 macOS VM 运行时停用它,使用中检查才能阻止在仍有 macOS VM 时卸载它。
- **设置迁移**:`whpx_fallback`、`win10_cold_reboot` 从 `builtin.core` 转给新插件,合并顺序为"新插件显式值 → 旧插件显式值 → 默认值"。
- **参数账本迁移**:每台 VM 的账本中,只把已知由 macOS 启动步骤写入的条目转给新插件;用户手动参数与其他插件的条目保持原所有者。无账本的旧 VM(老版本或 CLI 直接启动过)由 `stripLegacyManagedExtraArgs` 兜底,该函数随之迁入 macOS 代码。
- **迁移方式**:在写锁下先备份受影响的小文件,一次替换 `state.json`,各步可重复执行,全部校验通过后才写版本戳 v3;与步骤 2a 的 VMRef 设置键转换共用一次 `state.json` 读取和写入,保留升级前原始备份。VM 目录、磁盘、快照、CoW 父盘与 `vm.toml` 不移动。
- **反向棘轮**:新增"`internal/macos/` 只能导入列入清单的宿主包"的测试,清单从现状开始,只减不增。
**验收**
- 从 v0.2.x 直升:用户关闭过的兼容选项与安装引导开关保持原值,手动设置的 `kernel-irqchip` 仍优先。
- 迁移中途退出后重启,迁移可继续,结果与一次完成相同。
- 同一台 VM 连续启动两次,参数不重复追加,辅助盘不重复挂载。
### 步骤 2:VM 引用与启动链路
**2a. `VMRef` 身份、内部索引与 list/start/stop 用户入口已落地**(原计划在步骤 3,提前是因为统一启动入口就要按归属解析 VM)
- 引入 `VMRef{DriverID, Name}`;`Router.ResolveVM` 遇到多个同名结果时返回歧义错误;`ListAllVMs` 不再按名称去重。
- 驱动在清单中声明 VM 根目录(第 3 节),路由与"驱动不可用"扫描遍历所有已声明的根。
- 宿主内存态、Guest Tools 注册表、缩略图与键入锁、日志来源改为按 `VMRef` 索引;对客体已经暴露的访问路径保留兼容。
- `PluginRecord.VMSettings` 的键改为 `VMRef` 的规范字符串,与步骤 1 共用版本 v3 的一次写入:已有键全部归属 `builtin.driver.reims-macos`。
- 界面进程交接参数增加驱动;只给名称且不重名时仍可用。
**2b. 驱动自有准备与第三方意图分开(已落地)**
- `Driver.Start` 改为接收启动请求:`VMRef`、第三方插件经 `vm.beforeStart` 给出的意图(参数片段、环境变量、启动后动作),以及日志输出。
- 启动前检查(WHPX、运行时兼容)与启动准备由驱动自己完成。macOS 的离线辅助盘、恢复启动、引导语言、WHPX 兼容降级、Win10 冷重启、Guest Tools 辅助盘从 `vm.beforeStart` 移入 macOS 驱动的 `Start`,"先准备恢复环境,再写引导语言"的顺序由驱动保证。
- 参数账本的合并与写入(对 reims 即 `reims-ctl set --extra-args`)由驱动执行,宿主以公共函数提供账本合并逻辑。
- `vm.beforeStart` 只留给第三方插件,继续脱敏、限时、限参数族。驱动在完成全部第三方 Hook、无人否决之后才改动磁盘,因此不需要通用回滚:准备步骤保持可重复执行,任一步失败即中止启动并明确报错;用户选择恢复启动而准备失败时,不悄悄转为普通启动。
- 特权按第 1 节的角色规则判定:驱动对自己的 VM 拥有完整参数控制;宿主内置插件保留现有白名单;其他插件按现有限制。
**2c. 统一入口与职责拆分(已落地)**
- 新增生命周期模块(暂名 `internal/lifecycle`),GUI 的 `StartVM` 与 CLI 的 `startVM` 都调用它,`startInWindow` 交给界面进程后同样进入它。宿主负责按 `VMRef` 解析驱动、串行化同一台 VM 的操作、派发事件(驱动 ID、运行时与能力取自该 VM)、任务与日志、进程退出监视。
- **拆分 `vmstart`**:提交内存检查、P 核绑核、亲和性配置留在宿主;离线辅助盘、恢复标记与 OpenCore 相关步骤迁入 `internal/macos/`。
- **拆分 Guest Tools**:传输、剪贴板与共享目录留在宿主(`guest-tools.transport` 服务),macOS 客体代理与辅助盘镜像(`BuildToolsDiskImage` 等)迁入 `internal/macos/`;镜像构建由 macOS 驱动在全部启动 Hook 通过后执行。
- **拆分调优判定**:宿主只报告探测事实;驱动针对选中的 VM 结合运行时能力给出建议,设置页与实际启动共用同一份判定。`kernel-irqchip`、WHPX 兼容降级与冷重启补偿的策略归 macOS 驱动。
**验收**
- 升级后用原有 macOS VM 验证:恢复引导、离线辅助盘、引导语言、冷重启监视、Guest Tools 与升级前行为一致;按 VM 的插件设置不丢失。
- 第三方插件否决启动时,VM 目录与 OpenCore 镜像未被修改。
- 测试驱动在相同宿主探测结果下,不会收到 OpenCore、辅助盘或冷重启参数。
### 步骤 3:其余入口统一路由(通用 App/CLI 已去 reims 直调,原生 macOS 流程按文件例外隔离)
- **后端**:VM 列表与轮询、详情、创建、设置、停止、重启、删除、日志、弹出安装介质,以及快照、克隆、磁盘、缩略图、统计、排障采集、亲和性等流程,全部经生命周期模块按 `VMRef` 路由。
- **CLI**:`vm` 子命令全部走驱动层,重名时要求 `--driver`。顶层 `installer` 子命令改由 macOS 插件经 `commands` 扩展点贡献,宿主 CLI 提供插件命令转发。
- **前端**:改用通用 VM 模型(名称、驱动、状态、CPU、内存、磁盘摘要、可用操作),按驱动能力位显示入口,后端执行时同样校验能力。`CreateWizard`、`SettingsModal` 中的 macOS 字段改为驱动的 `CreateSchema` / `SettingsSchema` 或插件页面。
- **macOS 界面**:安装包页、在线恢复、版本图、OpenCore 设置由 macOS 插件贡献;过渡期经同一处注册表挂载 `frontend/src/macos/` 内的原生页面。
**验收**
- 在测试装配中不注册 macOS 插件:工作台仍可用测试驱动完成"创建 → 启动 → 停止 → 删除"。
- 两个驱动各有一台名为 `dev` 的 VM:两台都出现在列表、各自的按 VM 设置互不覆盖;停止其中一台只调用其所属驱动。
- 恢复 macOS 插件后,原有 macOS VM 沿原路径启动,无需转换磁盘或重建配置。
### 步骤 3.5:宿主服务与按种类的运行时
Linux 驱动(步骤 4)与 macOS 外置(步骤 5)共同的前置条件,可在步骤 2 之后与步骤 3 并行开发。
- **按种类选定运行时**:配置改为每个运行时种类各记一个活跃运行时,随数据版本迁移现有的单值;只读操作在未选定时临时使用该种类最新安装的运行时、不写回配置,启动与创建前要求选定(待决,见第 9 节)。
- **运行时与 reims 解耦**:`internal/runtime` 只保留按种类的通用安装、校验、切换与环境构造;reims-vgpu 的默认种类、`reims-ctl` / `reims-util` 路径、专用环境变量、按补丁推断能力与发布源,改由运行时种类声明提供(过渡期由 macOS 插件声明)。
- **反向宿主接口扩充**(同时进入 `pkg/pluginsdk` 的公开类型):运行时查询(按种类返回路径与能力)、提交内存预检、绑核、日志与任务进度、进程退出通知、QMP 访问、VM 窗口信息与宿主明暗主题事件(安装引导浮层需要)。每项按权限校验。
- **脱敏注册**:宿主提供通用脱敏层,插件可注册自己的脱敏规则;全局脱敏器、插件管理器、排障包与界面错误上报改用它。macOS 的规则由 macOS 插件注册。
### 步骤 4:Linux 最小驱动与驱动契约测试
- 新增与具体驱动无关的契约测试集(暂名 `internal/driver/drivertest`),对每个驱动运行同一组用例:生命周期调用的幂等与可重试边界、错误分类,以及"进程已启动 / 控制通道可用 / 客体已就绪"三种状态的区分。
- Linux 驱动以独立仓库的 L3 插件实现,只依赖 `pkg/pluginsdk` 与反向宿主接口;先跑通一种镜像的创建、启动、停止与删除,再按 plugin-architecture.md Phase 4 的验收标准补齐。
- 只有出现两份以上重复实现时,才从中提取磁盘或 QEMU 公共模块。
**验收**:契约测试同时覆盖 macOS 内置驱动与 Linux 驱动;Linux 驱动不修改主程序源码即可接入。
### 步骤 5:macOS 外置
前置条件:
- **外部插件页面**:整页插件页面(iframe,插件自带前端包,宿主提供主题令牌与到插件自身 Sidecar 的桥接)、创建向导步骤槽位、VM 详情分区槽位。桥接至少提供:宿主文件与目录选择(返回宿主路径交给插件 Sidecar,iframe 内不可见)、长任务的注册与流式进度(下载、取消、退出前拦截活跃任务)、由宿主绘制的对话框、iframe 高度自适应与焦点和快捷键传递。
- **运行时需求声明**:插件在清单中声明需要的运行时种类与版本范围;缺少时宿主引导用户安装。运行时包不随插件安装事务自动拉取,插件之间的安装期依赖等出现真实用例再设计。
- **语言与文案**:`macos-glossary.json`、`internal/i18n/glossary.go` 与各词表中的 macOS 文案迁入 macOS 插件的 `l10n`;第三方语言包对 macOS 文案的翻译改为针对该插件的 `pluginOverrides`。
- **反向棘轮清零**:`internal/macos/` 不再导入任何宿主 `internal/` 包,只依赖 `pkg/`。
- **声明式承接可用**:`replaces` 与 `aliases`(第 3 节)已实现并有测试。
外置本身:
- 迁出清单:`internal/macos/`、`frontend/src/macos/`、macOS 词表、`patches/`、`.github/workflows/build-runtime.yml`、`scripts/` 中的运行时打包与补丁脚本、`docs/portable-runtime-spec.md` 中 reims-vgpu 专属部分。用 `git filter-repo` 按清单生成 macOS 插件仓库,保留这部分历史;主仓库一次提交删除,并改写 README 与 AGENTS 中的产品定位。若历史本身也需剥离,改为反向拆分(第 9 节)。
- 发布不含 macOS 的主程序:已有 macOS VM 因归属标记与 macOS 驱动声明的 VM 根仍在列表中,显示"需要安装对应驱动插件",由用户自行安装;主程序不自动安装、不默认推荐。用户安装外部 macOS 插件后,经声明式承接取回设置、账本与 VM 归属。
**验收**
- 主仓库删除迁出清单后,构建、测试与两处棘轮全部通过;对 `macOS`、`OpenCore`、`reims`、`Apple` 等词的全仓检索只剩明确列出的例外(如"驱动不可用"提示中的通用说法)。
- 安装外部 macOS 插件后,原有 macOS VM 无需转换即可启动,用户关闭过的选项保持关闭。
## 5. 顺序与并行
```mermaid
flowchart LR
S0["步骤 0\n数据目录写入保护"] --> S1["步骤 1\nmacOS 插件身份\n与 v3 迁移"]
S1 --> S2["步骤 2\nVMRef 与启动链路"]
S2 --> S3["步骤 3\n其余入口统一路由"]
S2 --> S35["步骤 3.5\n宿主服务与\n按种类的运行时"]
S3 --> S4["步骤 4\nLinux 最小驱动"]
S35 --> S4
S3 --> S5["步骤 5\nmacOS 外置"]
S35 --> S5
P5["外部插件页面 · 承接机制\n语言迁出 · 反向棘轮清零"] --> S5
```
- 步骤 0 不依赖其他决定,可以立即开始;步骤 1、2 开始前需定下第 3 节的身份模型与第 1 节的特权规则。
- 步骤 3 与 3.5 可并行;外部插件页面、承接机制与语言迁出可在步骤 2 之后并行开发。
- 以法律目标为准时,最快路径仍要经过步骤 1–3.5;跳过它们会让外置时再做一次数据与职责迁移。
## 6. 棘轮与检查
**宿主 → macOS**(现有,`internal/archtest` 与 `frontend/scripts/test-macos-boundary.mjs`):
| 例外 | 移除时机 |
| :--- | :--- |
| `internal/plugin/builtin`(仅源码的 Guest Tools 参数辅助) | 步骤 2:客体代理与辅助盘镜像迁出后移除;注册与测试例外已在步骤 1 移除 |
| `internal/datamigrate` | 步骤 5:历史 v3 迁移改为不依赖 macOS 实现的通用数据迁移后移除 |
| `internal/guesttools`(源码与测试) | 步骤 2:客体代理与辅助盘镜像迁出 |
| `internal/plugin`(仅测试) | 步骤 3:Sidecar 测试改用通用测试替身 |
| `internal/app`、`internal/cli` | 步骤 3:只剩一个组装文件注册 macOS 插件,例外细化到该文件 |
| 前端 `App.tsx`、`Sidebar.tsx`、`VMPage.tsx` | 步骤 3:改为插件贡献 |
| 组装文件 | 步骤 5:macOS 外置后删除 |
**macOS → 宿主 `internal/`**(步骤 1 新增):清单从现状开始,随步骤 2 与 3.5 把依赖改到 `pkg/`,步骤 5 前清零。
**非 import 耦合**:import 棘轮看不到第 2.5 节所列的词表、脱敏、运行时、前端字段等耦合。不为它们另建常驻检查;各自在所属步骤内迁移,步骤 5 以一次全仓检索作为验收。
## 7. 风险
| 风险 | 应对 |
| :--- | :--- |
| 迁移改坏用户数据 | 步骤 0 的写锁、只读模式与一次落盘;迁移前备份小文件;只动元数据,不动磁盘 |
| 升级后 macOS VM 行为变化 | 每步以原有 macOS VM 做回归:恢复引导、辅助盘、引导语言、冷重启监视、Guest Tools、绑核 |
| 特权模型改变引入越权 | "驱动对自己的 VM 拥有完整参数控制"只授予 VM 的所属驱动;`builtin.*` 的承接只允许 `official` 包或用户逐项确认;改动单独评审 |
| `VMRef` 迁移遗漏某处按名索引的状态 | 步骤 2a 以"两台同名 VM"作为贯穿测试用例,覆盖设置、内存态、Guest Tools 与交接参数 |
| 新旧版本混用 | 只读模式只保护新版本;降级支持的最低版本需明确公布(第 9 节) |
| 步骤之间长期停留在半迁移状态 | 每步自成闭环、可单独发布;棘轮清单只减不增 |
| 外部插件界面体验不及原生 | 过渡期保留原生页面;外置前以安装包页与恢复向导做可用性验收 |
## 8. 后续(不在本方案内)
触发条件出现时再立项:
- **稳定 VM ID**:VM 改名需要保持设置与历史、PID 复用或 CLI 超时重试出现实际问题时,引入 VM ID、一次开机的运行 ID 与一次长操作的操作 ID(参考 libvirt 的 UUID 与 containerd 将对象与运行分离的做法)。`VMRef` 届时作为人读入口保留。
- **重新接管**:管理进程重启后重新连接正在运行的 VM,GUI 退出后 CLI 能找回同一次运行。
- **常驻服务**:需要"GUI 退出后任务继续""多客户端订阅同一状态"或第三方程序调用时,再把生命周期模块放到用户级后台进程后,经 Windows 命名管道提供带版本的接口。
- **整盘迁移**:换盘、换电脑做成停机导出与导入;验收为原数据目录完全不可访问时,目标机仍能从带 CoW 子盘的副本启动。
- **升级交接**:进行中的创建、克隆、快照绑定发起时的驱动版本,运行中 VM 的控制权在重连验证后移交(参考 Magpie 插件宿主升级时的处理)。
- **插件间安装期依赖**:出现"插件 A 必须与插件 B 一起安装"的真实用例后再设计,届时优先考虑只提示、不自动求解。
## 9. 待决事项
步骤 1 开始前需要定下:
1. **特权规则**:是否接受第 1 节"按角色授予特权"的规则,替代现有按 `builtin.` 前缀放行。
2. **承接的信任要求**:承接 `builtin.*` ID 是只允许 `official` 包,还是也允许用户逐项确认。
3. **过渡期 macOS 插件是否默认启用**:步骤 1 暂取默认启用,保证升级无感;默认关闭更贴近剥离方向,但存量用户升级后会看到"驱动不可用"。最终实现仍待评审。
可在后续步骤前决定:
4. **多运行时未选定时的行为**(步骤 3.5):建议只读操作临时使用最新安装的运行时、不写回配置,启动与创建前要求选定。
5. **降级支持**(步骤 0 发布前):可安全退回的最低版本,以及只读模式的提示文案。
6. **剥离范围**(步骤 5):法律风险具体涉及哪些内容(OpenCore 与 SMBIOS 处理、Apple 安装包下载、产品定位中的 macOS 字样、reims-vgpu 运行时),决定迁出清单的范围。
7. **官方市场是否上架 macOS 插件**(步骤 5):上架方便用户,但官方索引仍与 macOS 产生关联。
8. **代码历史**(步骤 5):只删除当前代码,还是让主程序以新仓库重新开始历史、本仓库保留为 macOS 插件仓库。
+97 -26
View File
@@ -1,7 +1,7 @@
# 插件系统架构(Plugin Architecture)
> 状态:**核心内核、内置扩展、主题引擎、Sidecar 托管与 CLI/GUI 管理已落地**;市场远端索引与 L2 脚本层按需迭代。
> 关联文档:[`architecture.md`](architecture.md) · [`design-guidelines.md`](design-guidelines.md) · [`portable-runtime-spec.md`](portable-runtime-spec.md) · [`patches/README.md`](../patches/README.md)
> 关联文档:[`architecture.md`](architecture.md) · [`design-guidelines.md`](design-guidelines.md) · [`portable-runtime-spec.md`](portable-runtime-spec.md)
---
@@ -60,7 +60,7 @@
flowchart TB
subgraph Exe["reims-go.exe(可信核心)"]
Reg["扩展点注册表\n依赖解析 · 可逆副作用 · Reconcile"]
Builtin["内置扩展(编译期注册)\n核心:reims 驱动 · 默认主题 · 启动准备 · 兼容补偿\n可选:宿客桥接 · 剪贴板 · 输入服务 · 窗口安装引导 · reims-vgpu 运行时种类"]
Builtin["内置扩展(编译期注册)\n核心:默认主题\n可选:macOS 客体驱动 · 宿客桥接 · 剪贴板 · 输入服务 · reims-vgpu 运行时种类"]
Mgr["插件管理器\n清单校验 · 事务安装 · 状态 · 安全模式"]
Broker["Host API 代理\n权限校验 · 脱敏 · 限流 · 审计"]
Sup["进程监管器\nJob Object · 重启退避 · 健康检查"]
@@ -106,10 +106,11 @@ flowchart TB
扩展点先由内置功能使用一遍再对外开放。内置功能分两类,判断标准是用户关掉它之后,是「少了一项功能」还是「已有功能坏掉」:
- **核心** `builtin.core`:Reims-Go 离开它就无法运行 macOS 虚拟机的部分,包括 reims 驱动(驱动 id 仍为 `builtin.driver.reims-macos`)、默认主题(主题 id 仍为 `builtin.theme.default`)、启动准备(离线辅助盘、恢复模式引导切换、引导语言重放)与宿主兼容补偿(WHPX 降级、Win10 冷重启)。它是**系统插件**:始终启用,不能停用或卸载,插件页显示为一行「始终启用」,不参与「使用中」检查。两项兼容补偿作为核心的应用级设置保留开关,仅供排障。启动准备在同一个 `vm.beforeStart` 处理器里按固定顺序执行,引导语言重放必须在恢复模式切换(可能重建 OpenCore)之后。
- **核心** `builtin.core`:只保留客体无关的默认主题(主题 id 为 `builtin.theme.default`)。它是**系统插件**:始终启用,不能停用或卸载,不出现在插件页与 `plugin list` 中(按 ID 查询仍可见),不参与「使用中」检查。
- **macOS 客体插件** `builtin.guest.macos`:注册代码位于 `internal/macos/guest`,静态声明 reims 驱动(驱动 id 仍为 `builtin.driver.reims-macos`)、宿主体检、启动准备、WHPX 降级、Win10 冷重启和安装引导。它是可停用插件,过渡期默认启用以保留升级行为;有 VM 运行时不能停用,停用后宿主内的 macOS 原生页面与流程(创建、设置、Guest Tools 挂载、安装与恢复等)一并拒绝执行,直到重新启用。安装引导保留独立应用级开关。启动准备暂经 `vm.beforeStart`,下一步改由驱动自己执行,见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 2。
- **可选内置扩展**:Guest Tools 传输服务、剪贴板互通、宿主输入服务、虚拟机窗口安装引导。经同一注册表注册、可独立启停、停用后零残留,停用即真正停止(不被其他调用方重新拉起)。首批示例为默认开启的剪贴板互通(见 §5.4)。
核心由曾经拆开的七个内置插件合并而来(`builtin.RetiredIDs`)。启动时删除 `state.json` 中这些旧 ID 的记录,关闭过的兼容补偿转为对应的核心设置;启动 VM 时,参数归属账本中旧 ID 名下的片段移交给核心,继续沿用而不是被当作已卸载插件的残留剥离。
旧版曾把 macOS 驱动、兼容补偿、安装引导与准备步骤拆成多个内置插件。数据布局 v2 的迁移删除这些旧 ID 的记录:显式设置与旧安装引导启停状态转入 `builtin.guest.macos`,参数账本中已知 macOS 条目也转给该插件;无关插件与宿主参数保持原所有者。
---
@@ -119,7 +120,8 @@ flowchart TB
- 每个已启用插件(含内置)拥有一个作用域,所有注册行为(提供服务、贡献扩展点、订阅事件、后台服务、Win32 钩子、QMP 监视)都登记一个释放函数;停用、卸载或升级时**逆序释放**,激活中途失败则回滚已登记项。
- 插件声明 `requires` / `provides`(服务名 + 版本范围)。Reconcile 先关后开:先释放不再需要的插件及依赖其服务的插件,再按依赖求不动点激活。状态为 `off / pending / active / degraded / failed`。
- **使用中不可移除**:仍有 VM 归属的驱动、仍被 VM 使用的运行时,不可停用或卸载;使用情况查询失败按「使用中」处理。
- **使用中不可移除**:仍有 VM 归属的驱动不可卸载,仍被 VM 使用的运行时不可删除;使用情况查询失败按「使用中」处理。
- **运行中不可停用**:驱动的 VM 只要有一台处于停止、挂起或损坏以外的状态,就不能停用其插件;状态查询失败同样拒绝。VM 都已停止或挂起时可以停用:VM 文件与挂起状态保留,显示为「驱动不可用」,不能启动、恢复或修改,重新启用后恢复。插件页停用这类插件前先弹窗说明。
- 内置扩展通过 `pluginApi` 版本做兼容检查;激活 panic 转为 `failed` 并回滚。
### 4.2 扩展点目录
@@ -137,10 +139,11 @@ flowchart TB
| `hooks` | Builtin · L1 · L2 · L3 | 有序列表 | 按事件模式(§4.3) |
| `commands` | Builtin · L2 · L3 | 按 id | 报错并提示 |
| `menus` / `vmCards` / `settingsPages` / `statusItems` | 声明式 | 列表,设数量上限 | 隐藏该项 |
| `panels` | L4 iframe | 限定槽位 | 错误占位 + 重试 |
| `panels` | L4 iframe,嵌在槽位内 | 限定槽位,限高 | 错误占位 + 重试 |
| `views` | L4 iframe,整页或标签页(§5.6) | 按位置设数量上限 | 错误页 + 重试;不影响其他视图 |
| `diagnostics` | Builtin · L3 | 列表 | 跳过;输出强制脱敏 |
UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`、`settings.plugin`,后续按真实需求再增加 `sidebar.footer`、`statusbar.right`、`create.source`;插件只能向已声明槽位贡献。
UI 槽位采用「声明即占有」:插件只能向宿主槽位目录(§5.1)中的槽位贡献。目录中的每个槽位、每种视图位置都必须由宿主实际渲染,前端构建检查覆盖这一点;不能出现可以声明、界面上却不显示的位置(§6.3)。
### 4.3 Hook 事件与分发模式
@@ -185,11 +188,14 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
| 契约 | 内容 |
| :--- | :--- |
| 设计令牌 | 单一来源(令牌数据同时生成 CSS 变量与前端常量),覆盖颜色、字体排印、形状、阴影、动效时长与缓动、层级;动效档位(含系统「减少动态效果」)在一处解析为文档属性,样式与脚本读同一个值 |
| 部件 | 关键区域与控件挂稳定的部件类名(如 `rg-p-sidebar`、`rg-p-vm-header`、`rg-p-statusbar`),每个部件一个独立类名,便于浏览器按类名分桶匹配;主题选择器只允许使用部件、状态属性与令牌,不得依赖内部类名或界面文字 |
| 状态属性 | 文档与区域上的只读状态:外观、当前视图、VM 显示状态、忙碌态、是否有错误、侧栏折叠 |
| 槽位锚点 | 装饰与扩展内容的挂载点(如侧栏底部、VM 预览四角、状态栏、空状态区) |
| 部件 | 区域与控件挂稳定的部件类名,每个部件一个独立类名,便于浏览器按类名分桶匹配;主题选择器只允许使用部件、状态属性与令牌,不得依赖内部类名或界面文字。区域级:`rg-p-shell`、`rg-p-titlebar`、`rg-p-sidebar`、`rg-p-nav`、`rg-p-main`、`rg-p-vm-page`、`rg-p-statusbar`、`rg-p-logpanel`、`rg-p-settings` 等;控件级:`rg-p-nav-group`、`rg-p-nav-item`、`rg-p-button`、`rg-p-icon-button`、`rg-p-card`、`rg-p-badge`、`rg-p-tabs`、`rg-p-tab`、`rg-p-menu`、`rg-p-menu-item`、`rg-p-dialog`、`rg-p-toast`、`rg-p-tooltip`、`rg-p-input`、`rg-p-switch`、`rg-p-progress`、`rg-p-vm-actions`、`rg-p-plugin-view` |
| 状态属性 | 文档级只读状态:外观、动效档位、语种与书写方向、当前视图、侧栏折叠、安全模式、布局选项;逐项状态:导航项与 VM 区域带 `data-vm-state`、`data-driver`、`data-selected`、`data-busy`,按钮带 `data-variant`、`data-busy`,对话框与提示条带 `data-tone`。主题可据此为单个 VM 条目做动效,不必解析界面文字 |
| 槽位目录 | 每个槽位声明上限与可挂内容(装饰、SDK 挂载、`panels`、`menus`、`statusItems`):`titlebar.center`、`sidebar.header`、`sidebar.footer`、`nav.item.trailing`(逐个 VM 条目)、`vm.header.trailing`、`vm.toolbar`、`vm.card`、`vm.preview.tl/tr/bl/br`、`statusbar.left`、`statusbar.right`、`empty.state`、`create.source`、`settings.plugin` |
| 图层 | 全窗口背景层 `layer.background` 与前景装饰层 `layer.overlay`:不拦截指针、不参与焦点,「减少动态效果」时停播动画;用于动态壁纸、粒子与满屏吉祥物 |
| 布局选项 | 主题清单的 `layout` 声明:侧栏位置(左/右)、侧栏形态(完整/图标窄栏/悬浮)、密度(紧凑/常规/宽松)、标题栏样式。只改摆放与尺寸,不能隐藏操作入口 |
| 图标 | 宿主公开图标名清单(如 `start`、`stop`、`settings`、`plugin`、`vm.state.running`);主题以 `icons` 映射到包内单色 SVG,宿主按令牌着色 |
契约内的部件、状态属性与令牌的重命名或删除属于 `uiApi` 主版本变更;前端构建检查契约中的每个部件仍由某个组件输出。
契约内的部件、状态属性、槽位、图层、布局选项、图标名与令牌的重命名或删除属于 `uiApi` 主版本变更;前端构建检查契约中的每个部件、槽位与图层都由某个组件输出(§6.3)。
**三档主题能力**
@@ -203,8 +209,10 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
- 生命周期:主题脚本导出装载函数,所有订阅、计时器与挂载都登记释放函数;切换或停用主题时逆序拆除,单个功能抛错不影响其余功能。
- 只读状态订阅:非敏感的 VM 摘要、任务进度、当前视图、外观;不提供原始路径与敏感字段。
- 事件流:VM 状态变化(含过渡态)、任务开始/进度/结束、提示条出现、视图切换,供主题做转场动画,不必轮询状态。
- 宿主提供的页面观察总线、帧读写管线与按部件查询:主题不自建节点观察者,也不整页查询文档。
- 槽位挂载:框架无关的 DOM 挂载,不共享宿主的 React 实例,避免随宿主依赖升级断裂。
- 槽位挂载:框架无关的 DOM 挂载,不共享宿主的 React 实例,避免随宿主依赖升级断裂。按 VM 重复的槽位(`nav.item.trailing`)以 VM 引用为键挂载;全窗口图层另有专用挂载;按部件查询可取回重复部件的全部实例。
- 声明式装饰与 SDK 挂载共用同一批槽位与图层;重复槽位里的装饰按所在 VM 自身的状态匹配。
- 受限动作:仅开放非破坏性界面动作(折叠侧栏、打开设置、前置 VM 窗口等);启停、删除、配置写入不在 SDK 中。
- 主题设置:由 `settings` Schema 定义,宿主渲染设置页。
@@ -214,7 +222,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
- 样式清洗:禁止外部 `url()` 与远程 `@import`,资源只能引用包内清单中的文件;窗口拖拽区、焦点环与最小点击热区等可用性属性由宿主在更高层保留,不被主题覆盖。
- 同一时刻只启用一个主题包,切换时先停用旧主题再装载新主题;安全模式一律回到内置主题。
- 首帧前按当前主题内联令牌防闪烁;无边框窗口的标题栏由前端绘制,可随主题变化。
- 主题只改视觉与交互呈现,不改文案、信息层级与操作入口([`design-guidelines.md`](design-guidelines.md) 的主操作与破坏性操作约束由宿主守住)。
- 主题只改视觉与交互呈现,不改文案、信息层级与操作入口([`design-guidelines.md`](design-guidelines.md) 的主操作与破坏性操作约束由宿主守住)。布局选项可以挪动区域、改变侧栏形态,但 VM 列表、新建、设置与插件入口始终可达。
- 主题不提供功能页面;需要自有界面的插件走 §5.6 的视图,不经 `ui:script`。
- 需要读写用户文件或常驻服务的主题,以同包 L3 Sidecar 实现。
- 开发支持:`reims-go plugin link` 链接本地目录并热重载;`reims-go plugin doctor` 校验样式只使用契约内的部件、状态属性与令牌。
@@ -228,16 +237,17 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
### 5.3 非 macOS 虚拟机(客体驱动,L3)
**驱动抽象**:当前 `internal/app`、`internal/vmstart`、`internal/cli` 直接依赖 `internal/driver/reims` 的具体类型。抽象后:
**驱动抽象**:当前 `internal/app`、`internal/vmstart`、`internal/cli` 直接依赖 `internal/macos/reims` 的具体类型。抽象后:
| 层 | 内容 |
| :--- | :--- |
| 通用 VM 模型 | 驱动 id + 名称、状态(`stopped / running / broken` 与过渡态)、CPU / 内存 / 磁盘摘要、目录、能力位 |
| 驱动专有数据 | 不透明扩展字段 + 驱动提供的创建/设置 JSON Schema(宿主原生渲染,标注生效时机) |
| 能力位 | `snapshot`、`cow_clone`、`resize`、`qmp`、`ssh`、`guest_tools`、`affinity`、`opencore`、`recovery`、`cloud_init`、`uefi_iso` 等;UI 与 CLI 按能力位显隐操作 |
| 驱动动作 | `List / Show / ValidateCreate / Create / ValidateSet / Set / Start / Stop / Delete`,可选快照、派生、扩容与通用 `InvokeAction` |
| 驱动动作 | `List / Show / ValidateCreate / Create / ValidateSet / Set / Start / Stop / Delete`,可选 `SnapshotDriver`、`CloneDriver`、`DiskDriver` 与通用 `InvokeAction`;存储调用由生命周期先解析 `VMRef`,结果使用 `driver.DiskSnapshot / DiskResizeResult / DiskCompactResult` |
- **VM 归属**:VM 目录内标记文件记录驱动 id;无标记的存量 VM 自动归属 `builtin.driver.reims-macos`,零迁移。CLI 增加 `vm create --driver <id>`,其余 `vm` 子命令按归属自动路由。
- **VM 归属**:VM 目录内的标记文件 `.reims-go-driver` 记录驱动 id;无标记的存量 VM 归属 `builtin.driver.reims-macos`,并由数据迁移补写标记([architecture.md](architecture.md) §4.7)。有标记的 VM 在其驱动缺席时仍以「驱动不可用」列出。驱动迁到另一个插件、id 随之改变时(市场插件不能使用 `builtin.` 前缀),在 `driver.RenamedDriverIDs` 登记旧 id 到新 id 的映射;标记文件不改写,降级后旧版本仍能识别。CLI 增加 `vm create --driver <id>`,其余 `vm` 子命令按归属自动路由。
- **VM 引用与根目录**:`driver.VMRef{DriverID, Name}` 的规范键为 `driverID:vmName`;`Router.ListAllVMs` 按完整引用去重,裸名称解析遇到跨驱动同名时返回歧义错误,调用方须显式指定驱动。每个 `guestDrivers` 条目用 `vmRoots` 声明相对 `<DataRoot>` 的斜杠路径,绝对路径、反斜杠与 `..` 均被拒绝;路由遍历所有已声明根(包括停用驱动)以保留「驱动不可用」条目。按 VM 的插件设置也以规范键持久化。
- **宿主共享服务**(驱动经反向调用复用):体检报告、提交内存预检、大小核绑核、QMP 截屏与键入、缩略图、Guest Tools 注册、进程退出监视、任务进度、日志通道、托盘菜单。
- **VM 进程归宿主托管**:驱动不直接派生 QEMU,而是请求宿主代为启动并返回 PID。这样 VM 进程不随驱动进程的 Job Object 被回收(驱动崩溃或重启不误杀 VM),绑核、退出监视与冷重启补偿也只在宿主实现一份。
- **配置写入**:`reims-ctl set` 铁律约束 reims 管理的 VM;Linux 驱动自管配置文件,同样不允许 UI 拼接原始命令行。
@@ -269,17 +279,57 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
| :--- | :--- | :--- |
| `builtin.bridge.guest-tools` | `internal/guesttools`、`guesttools_flow.go` | 提供传输服务 + `vm.beforeStart`(注入桥接参数与环境变量)+ `vm.afterStart` + `vm.card`;共享文件夹、盘符共享、防休眠逐步拆为功能扩展 |
| `builtin.input` | `host/ime_hook_windows.go` | 提供输入服务与 `inputFilters`;IME 桥成为其上的功能,停用时卸载钩子线程 |
| `builtin.install-guide` | `internal/installguide`、`internal/app/install_guide.go` | 提供 `ui.install-guide` 服务 + `vm.afterStop` / `vm.deleted` 观察钩子;在虚拟机窗口悬浮展示安装与恢复引导,停用时立即关闭全部浮层并回退主界面恢复卡片 |
| `builtin.core`(系统插件) | `driver/reims_adapter.go`、`vmstart.Prepare` 各步骤、`app.go` 冷重启监视 | `guestDrivers` + `themes` + `host.preflight` + 一个按序执行全部启动准备的 `vm.beforeStart`(离线辅助盘 → 恢复模式引导 → 引导语言 → WHPX 降级 → Win10 冷重启)+ `vm.afterStart` / `vm.afterStop`(冷重启监视);设置 `whpx_fallback`、`win10_cold_reboot` |
| `builtin.guest.macos` | `internal/macos/guest`、`internal/macos/installguide`、`macosdriver`、`vmstart.Prepare` 各步骤 | 静态 `guestDrivers` + `host.preflight` + 驱动内启动准备与冷重启意图 + 条件提供的 `ui.install-guide` 服务;设置 `install_guide`、`whpx_fallback`、`win10_cold_reboot` |
| `builtin.core`(系统插件) | `internal/plugin/builtin/core.go` | `themes`:默认主题 |
> 下一步:Guest Tools 的 macOS 客体代理与辅助盘镜像迁入 macOS 插件,传输服务留在宿主;启动准备改由驱动自己执行。见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 2。
### 5.5 与上游补丁队列的边界
| 类别 | 归属 | 原则 |
| :--- | :--- | :--- |
| 引擎内部崩溃与 Hypervisor 层修复(WHPX 兼容、协程、构建锁文件等) | [`patches/`](../patches/)(编译期) | 外部插件无法等价替代;坚持上游 PR,合入即退役 |
| 引擎内部崩溃与 Hypervisor 层修复(WHPX 兼容、协程、构建锁文件等) | [运行时源码与补丁](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md)(编译期) | 外部插件无法等价替代,修复交由运行时仓库维护 |
| 窗口内部消息循环拦截(如 SDL 窗口内字符消息) | `patches/`,宿主侧做部分补偿 | 跨进程拦截需 DLL 注入,杀软误报风险高,不做成插件 |
| 宿主侧绕过、兜底补偿与宿客桥接 | 内置扩展(§5.4) | 运行时缺少对应补丁时平滑降级;依据运行时 `capabilities` 判断 |
### 5.6 插件自有界面
插件需要界面时按以下顺序选择形式,能用前一种就不用后一种:
| 形式 | 适用 | 渲染与信任 |
| :--- | :--- | :--- |
| **声明式界面** | 应用与按 VM 设置、VM 卡片信息、工具栏按钮与菜单、状态栏项、通知、确认框、表单对话框、任务进度 | 宿主原生渲染,自动跟随主题、语种、键盘操作与无障碍;只需低、中危权限 |
| **视图(`views`)与面板(`panels`)** | 自定义可视化、控制台、多步向导、需要自绘交互的页面 | 沙箱 iframe(不透明源),只经插件界面桥(bridge)与宿主通信,能力由权限约束 |
| **交互主题脚本** | 仅限主题的视觉与交互增强 | 主窗口受信任脚本(`ui:script`);功能插件不得使用 |
**视图位置**(`views[].location`;面板仍按槽位嵌入,限高):
| 位置 | 呈现 | 上限 |
| :--- | :--- | :--- |
| `sidebar` | 侧栏「扩展」分组中的导航项,点击后在主区域整页打开;导航项的图标、标题、角标与选中态由宿主绘制 | 每插件 2 个;超出部分折叠进「更多」 |
| `vm.tab` | VM 页内的标签页;以 `when` 限定驱动或能力位(如只对某驱动的 VM 显示控制台) | 每个 VM 页 4 个 |
| `settings` | 设置中的独立分节,用于放不进 Schema 表单的复杂设置 | 每插件 1 个 |
| `dialog` | 不常驻;由命令或 bridge 的 `ui.openView` 以模态打开,可返回结果 | 同一时刻 1 个 |
视图字段:`id`、`title`、`icon`(包内单色 SVG,宿主按令牌着色)、`location`、`entry`(包内 HTML)、`order`、`when`、`minWidth`。宿主负责外框:标题、返回、加载与错误占位、重试、尺寸、焦点进出与快捷键。视图惰性加载;同一时刻保持存活的视图有上限,切走的视图超过上限即卸载,插件停用时全部卸载。
**插件界面桥(`bridgeApi` 1.0)**:iframe 与宿主之间的请求/响应与事件消息,宿主只应答来源窗口为该 iframe 的消息,每个方法在 Go 侧按权限二次校验并限流。
| 命名空间 | 方法与事件 | 权限 |
| :--- | :--- | :--- |
| 握手 | `hello`:返回 `bridgeApi`、`features`、语种与书写方向、完整契约令牌、视图上下文(位置、所在 VM 的 `VMRef`) | 无 |
| `ui` | `notify`、`confirm`(宿主原生确认框)、`showForm`(以 Schema 弹出原生表单并返回值)、`setTitle`、`setBadge`、`openView`、`close`(`dialog` 返回结果)、`navigate`(只限宿主路由白名单)、`openExternal`(宿主确认后用系统浏览器打开) | `ui:notify` / `ui:slot` |
| `vm` | `list`、`get`(通用 VM 模型,不含敏感字段);事件 `vm.stateChanged` | `vm:read` |
| `command` | `invoke`:只能调用本插件声明的命令;VM 启停等动作由命令处理方经 `vm:control` 执行 | `ui:slot` |
| `settings` | 读写本插件的应用级与按 VM 设置 | 无(限本插件) |
| `storage` | 本插件私有键值存储,位于 `data/<id>/`,有配额 | `fs:plugin_data` |
| `file` | `pick` / `save` 弹出宿主文件对话框,只返回不透明句柄;按句柄分块读写,不暴露路径 | `fs:pick` |
| `task` | 开始、更新、结束任务;在宿主任务区显示进度并可取消 | `task:progress` |
| `net` | `fetch` 经宿主代理发出(iframe 自身 `connect-src 'none'`) | `net:<origin>` |
| `events` | 订阅主题与语种变化、视图可见性、任务事件 | 无 |
大对象分块传输,单条消息设大小上限。宿主以 `/plugin-ui-kit/<uiApi>/` 提供界面套件(令牌样式表与常用控件样式),主题或语种变化时经 bridge 推送新令牌,插件界面因此与宿主外观一致,不必自带一套设计系统。
---
## 6. 插件包与清单
@@ -305,7 +355,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
| `name` / `description` | 多语种本地化文本(内置 `zh-CN` / `en-US` 及任意 BCP-47 扩展键),**无需执行插件代码即可读取** |
| `l10n` | 可选的包内私有词表目录(如 `"locales"`),存放 `<locale>.json` 供插件自身 UI、iframe 面板与 Sidecar 使用;独立语言包可通过 `pluginOverrides` 在外部补充或覆盖任意第三方插件的清单字段与私有词条 |
| `publisher` / `license` / `homepage` | 来源与许可,市场审核依据 |
| `engines` | `reims-go` 版本范围与 `pluginApi` 范围,**下载前预检** |
| `engines` | `reims-go` 版本范围,以及所依赖契约面的范围:`pluginApi`、`uiApi`(主题与面板样式)、`bridgeApi`(视图与面板);**下载前与激活前预检**(§6.3) |
| `platforms` | 如 `windows-x64` |
| `entry` | Sidecar 可执行文件、脚本文件、面板 HTML 根目录;层级由内容推导,不信任自报 |
| `contributes` | 各扩展点贡献(§4.2) |
@@ -316,6 +366,24 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
| `defaultEnabled` | 安装或首次启动时的默认启用状态;仅内置扩展与随主程序附带的插件可为 `true` |
| `provenance` | **运行时包必填**:上游仓库与 commit、补丁清单与哈希、源码包文件名 |
### 6.3 契约版本与演进规则
公开契约分三个版本面,各自按 SemVer 演进,插件在 `engines` 中声明依赖范围:
| 版本面 | 范围 |
| :--- | :--- |
| `pluginApi` | 清单字段、扩展点、Hook 事件与载荷、权限名、Sidecar JSON-RPC 协议 |
| `uiApi` | 主题可依赖的界面契约:令牌、部件、状态属性、槽位目录、图层、布局选项、图标名、UI SDK |
| `bridgeApi` | 视图与面板的消息协议(§5.6) |
- **契约先于生态定全**:扩展点、槽位目录、视图位置与 bridge 方法在第三方插件依赖它们之前一次定全。目前生态只有语言包(只依赖 `pluginApi`),`uiApi` 与 `bridgeApi` 在首个第三方主题或界面插件出现前定稿为 `uiApi` 2.0 与 `bridgeApi` 1.0,定稿前可做不兼容清理。
- **公开即实现**:每个公开的扩展点、槽位、视图位置、图层与 bridge 方法在发布前都要有宿主实现和契约测试。前端构建检查每个槽位、视图位置与图层都被渲染;Go 测试检查每个扩展点都有消费者。尚未落地的项标为实验性:清单校验接受它,`plugin doctor` 警告,不受兼容承诺约束,市场不允许稳定版插件依赖它;某项在实现它的同一次变更中转为稳定。哪些项仍是实验性,以契约文件为准:`frontend/src/styles/ui-contract.ts`、`frontend/src/lib/bridgeContract.ts` 与 `internal/plugin/contract.go`(构建产物 `ui-contract.json`、`bridge-contract.json` 中的 `experimental` 部分),Go 测试保证三者一致,新增的 `contributes` 字段必须先在目录中登记状态。
- **主版本内只增不改**:新增字段一律可选,缺省时保持旧行为;新增枚举值(事件、视图位置、bridge 方法)只投递给声明了相应次版本的插件。改名、删除或改变语义只在主版本发生。
- **按特性协商,不按版本号猜**:宿主在 Sidecar 握手、bridge 握手与 UI SDK 中下发 `features` 列表(如 `view.sidebar`、`bridge.file.pick`、`layer.overlay`),插件据此降级。
- **未知字段**:宿主忽略清单中的未知字段并由 `plugin doctor` 警告,插件因此可以使用新字段同时兼容旧宿主;`engines` 下限高于宿主版本时拒绝安装与激活。
- **命名空间**:`builtin.*` 插件 id、`rg-` 前缀的类名、`data-rg-` 属性与契约令牌归宿主;主题自定义的 CSS 变量使用 `--theme-` 前缀(视图与面板在各自 iframe 内,不受此限);命令 id 由宿主自动加上插件 id 前缀。
- **弃用**:先在至少一个次版本中给出 `plugin doctor` 警告与替代项,下一个主版本再删除;契约文件(`ui-contract.json`、bridge 类型定义)随版本发布,作者可在本地校验。
---
## 7. 权限、信任与安全边界
@@ -325,20 +393,21 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
| 等级 | 权限 | 审批 |
| :--- | :--- | :--- |
| **低** | `vm:read`(通用模型,不含敏感字段)、`ui:notify`、`task:progress`、`fs:plugin_data`、`log:read` | 启用时展示说明 |
| **中** | `vm:intent`、`runtime:source`、`net:<origin>`(经宿主代理发出)、`ui:slot`、`input:filter`(声明输入过滤规则) | 首次启用逐项确认 |
| **中** | `vm:intent`、`runtime:source`、`net:<origin>`(经宿主代理发出)、`ui:slot`、`input:filter`(声明输入过滤规则)、`fs:pick`(经宿主文件对话框读写用户选中的文件) | 首次启用逐项确认 |
| **高** | `driver:vm`、`runtime:provider`、`process:spawn`、`vm:control`、`qmp:write`、`fs:vm_dir`、`fs:shared`、`host:clipboard`、`ui:script` | 强提示(展示可执行文件或脚本路径、SHA-256、发布者、许可证)并显式勾选;升级新增高危权限时暂停并要求重新批准 |
| **不存在** | 敏感字段读取、UAC 提权、重启 Windows、直写 `vm.toml` | 插件只能请求宿主发起人工确认流程 |
### 7.2 如实声明的信任边界
- L1、L2、L4 的权限由宿主强制。**L3 是原生代码,OS 层面无法约束**,权限只约束其对 Host API 的访问;安装与启用 L3 插件时明确告知「此插件能以你的账户身份执行任意操作」。
- 信任等级:`official`(官方密钥签名)、`verified`(审核 + 发布者签名)、`community`(仅哈希)、`dev`(本地链接,需开启开发者模式)。`community` 级 L3 插件默认不可启用,需二次确认。
- 信任等级:`official`、`verified`、`community`、`dev`(本地链接,需开启开发者模式)。`official` / `verified` 有两个来源:一是包内 ed25519 签名与内置密钥匹配;二是包从项目自有市场索引安装,该索引在本次会话经 HTTPS 从内置地址拉取(非过期缓存),且包的 SHA-256 与索引条目一致,此时沿用索引标注的等级。经 `REIMS_GO_PLUGIN_MARKET_URL` 指向的第三方索引不能担保信任,其条目在市场中一律显示为 `community`。其余情况为 `community`(仅哈希)。
- 信任等级只用于标识来源,不豁免任何检查:所有安装包(含 `official`)都走同一套静态安全扫描、高危权限审批与 L3 可执行文件哈希确认;只有内置与随主程序附带的插件预先批准。
- 以 AppContainer 或低完整性级别运行 Sidecar 作为后续增强项评估。
### 7.3 UI 与本地接口安全
- 插件资源经 Wails AssetServer 的独立路由提供,路径带每次运行随机生成的令牌,校验目录穿越,附 `X-Content-Type-Options: nosniff` 与 CSP;SVG 一律禁脚本。
- iframe 面板(后置):`sandbox="allow-scripts"`、`connect-src 'none'`;bridge 只应答来源窗口为自身 iframe 的消息,所有读取在 Go 侧按 `permissions` 二次校验并限流;主题令牌经 bridge 下发。
- iframe 视图与面板:`sandbox="allow-scripts"`(不加 `allow-same-origin`、`allow-popups`、`allow-top-navigation`)、`connect-src 'none'`;bridge 只应答来源窗口为自身 iframe 的消息,所有读写在 Go 侧按 `permissions` 二次校验并限流;文件只以句柄交换,网络只经宿主代理;主题令牌经 bridge 下发。
- 宿主本地 HTTP 接口(如 Guest Tools)拒绝 `Origin: null`、跨站请求与 `Sec-Fetch-Dest: iframe` 请求,防止被沙箱 iframe 或外部网页借道调用。
---
@@ -379,7 +448,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
- **安装来源**:本地包导入(首批)、市场索引(后续)、开发者模式本地目录链接。
- **随主程序附带的插件**:需要时可以标准插件包形式嵌入 `reims-go.exe`,信任等级为 `official`,版本跟随主程序;可启用/停用,不可卸载。
- **事务安装与静态准入门禁**:下载到 `tmp` → 校验 `SHA256SUMS` 与签名 → 核对包内 `id` / `version` 与预期一致(防偷换)→ 兼容预检 → 静态安全门禁(拦截 L1/L4 夹带可执行/系统脚本、L3 未声明二进制、SVG 主动脚本、`ui:script` 宿主逃逸或未声明联网、市场红线)→ 原子 rename 到 `pkgs/<id>/<version>` → 提交 `state.json`。任一步失败都不改变现状。对 L3 原生程序不声称“代码扫描安全”,仅核对清单完整性与 SHA-256 并向用户如实展示完整当前 Windows 账户权限说明。
- **市场索引与软撤回**:独立仓库发布轻量静态 `index.json`(二进制包托管在 GitHub Releases,复用运行时下载与代理逻辑;可通过 `REIMS_GO_PLUGIN_MARKET_URL` 配置镜像或 `off` 强制离线),含版本、`engines`、`platforms`、下载地址、SHA-256、签名者与软撤回列表(`withdrawn`,阻止新装并对存量用户展示替代建议);首次打开市场或执行市场 CLI 命令时惰性拉取,使用内存 + `<DataRoot>/plugins/index-cache.json` 双层缓存与主程序内嵌兜底副本,网络失败不覆写有效缓存。
- **市场索引与软撤回**:独立仓库发布轻量静态 `index.json`(二进制包托管在 GitHub Releases,复用运行时下载与代理逻辑;可通过 `REIMS_GO_PLUGIN_MARKET_URL` 配置镜像或 `off` 强制离线),含版本、`engines`、`platforms`、下载地址、SHA-256、签名者与软撤回列表(`withdrawn`,阻止新装并对存量用户展示替代建议);首次打开市场或执行市场 CLI 命令时惰性拉取;唯一例外是首次启动设置页:系统语言不被内置 zh-CN / en-US 覆盖时,按系统语言查一次索引,若有匹配的语言包,就在设置页提供「同时安装」选项(默认勾选,选好数据目录后安装并启用)。索引条目可用 `locales` 显式声明语言包提供的语言,未声明时按标签与名称译文推断。使用内存 + `<DataRoot>/plugins/index-cache.json` 双层缓存与主程序内嵌兜底副本,网络失败不覆写有效缓存。
- **更新与回滚**:新旧版本并存、切换指针,保留最近若干版本;插件同样区分 `alpha` / `stable` 通道,默认只取 `stable`。
- **安全模式**:`reims-go --safe-mode` 跳过全部第三方插件,界面顶部显示横幅与插件管理入口;以启动哨兵文件检测上次插件初始化阶段异常退出,下次启动询问是否进入安全模式。
- **市场红线**:拒收含 Apple 专有文件、SMBIOS 真值或闭源固件的包;运行时包必须附源码与许可证。
@@ -391,7 +460,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
| 入口 | 内容 |
| :--- | :--- |
| CLI | `reims-go plugin list / search / install <zip\|id> / update [id] / pack <dir> / link <dir> / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor [--json] [dir\|zip\|id] / locale <init\|check> / run <id> <command>`;`vm create --driver <id>` |
| 应用设置 → 插件 | 提供「已安装 / 插件市场」双视图(市场索引惰性加载):核心置顶、显示「始终启用」且无开关;其余显示来源与信任标签、权限摘要、安全扫描报告入口、启用开关、故障状态与日志入口;本地包导入前先展示三段式静态安全报告并执行硬门禁拦截 |
| 应用设置 → 插件 | 提供「已安装 / 插件市场」双视图(市场索引惰性加载):系统插件(核心)不列出;其余显示来源与信任标签、权限摘要、安全扫描报告入口、启用开关、故障状态与日志入口;本地包导入前先展示三段式静态安全报告并执行硬门禁拦截 |
| 插件设置页 | 由 `settings` Schema 渲染,复用现有设置控件,标注生效时机 |
| VM 页面 | 按能力位显隐操作;`vm.toolbar` 菜单项支持 `when` 条件;`vm.card` 展示驱动或插件提供的键值信息 |
| 创建向导 | 先选驱动,再按驱动 `CreateSchema` 渲染专属表单 |
@@ -419,6 +488,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
## 12. 分阶段演进与验收标准
从现有代码走到这里所述的客体驱动形态、并将 macOS 外置为插件的具体路径,见 [guest-plugin-migration.md](guest-plugin-migration.md)。
```mermaid
flowchart LR
P0["Phase 0\n内部抽象\n(不对外)"] --> P1["Phase 1\n插件底座 + L1\n(主题/模板/运行时源/规则 Hook)"]
@@ -435,7 +506,7 @@ flowchart LR
| **Phase 2** | 运行时种类注册表、`runtime_api` 与 `capabilities`、来源展示 | 第二种运行时与官方运行时并存切换;不兼容组合被拦截并给出提示 |
| **Phase 3** | JSON-RPC 协议 v1、进程监管、反向 Host API、权限审批、代码 Hook、插件命令、排障采集、轻量 Go SDK | 死循环或崩溃的示例 Sidecar 不影响主窗口与运行中 VM;退出或禁用后无孤儿进程 |
| **Phase 4** | 独立仓库的官方 Linux 驱动 | 不修改主程序源码,经 GUI 与 CLI 完成 Linux VM 创建、WHPX 启动、绑核、截屏、SSH 与快照;真机验证 |
| **Phase 5** | 签名体系与市场索引、iframe 面板、交互主题 UI SDK、按需引入 L2 脚本宿主 | 第三方插件经审核上架;iframe 面板无法越权读取或联网;参照 dsh-claude-style 的功能清单逐项确认可由三档主题能力承载或列出缺口 |
| **Phase 5** | 签名体系与市场索引、`uiApi` 2.0 与 `bridgeApi` 1.0 定稿(§5.1、§5.6、§6.3)、iframe 视图与面板、交互主题 UI SDK、按需引入 L2 脚本宿主 | 契约检查覆盖全部槽位、视图位置、图层与 bridge 方法,无「可声明但不渲染」项;第三方插件经审核上架;iframe 视图无法越权读取、联网或拿到文件路径;参照 dsh-claude-style 的功能清单逐项确认可由三档主题能力承载或列出缺口 |
---
+19 -21
View File
@@ -39,7 +39,7 @@ reims-runtime-<commit>/
### 2.2 裁剪与调试符号分离
打包脚本 [`scripts/stage-runtime-binaries.ps1`](../scripts/stage-runtime-binaries.ps1) 执行两项体积优化,在缩小下载体积的同时保留完整调试能力:
运行时仓库的 [`stage-runtime-binaries.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/stage-runtime-binaries.ps1) 执行两项体积优化,在缩小下载体积的同时保留完整调试能力:
1. **裁剪非必要工具与异架构固件**:仅移除 Windows x64 启动器不会调用的 `qemu-system-x86_64w.exe`、`elf2dmp.exe`、`qemu-edid.exe`、`qemu-io.exe`、`qemu-nbd.exe`、`qemu-storage-daemon.exe`,以及 ARM64、RISC-V、LoongArch64 的 EDK2 固件与描述文件;完整保留 x64 固件、BIOS、ROM、keymaps、动态加载的 `libva` 视频驱动与全部 DLL。
2. **独立发布调试符号**:使用 MSYS2 CLANG64 的 `llvm-objcopy` 从 5 个主可执行文件(`reims-ctl.exe`、`reims-util.exe`、`qemu-system-x86_64.exe`、`qemu-img.exe`、`reims-vgpu-compile.exe`)提取 `.debug` 符号并写入 GNU debug link,打包为同 Release 下的 `reims-runtime-symbols-<commit>.tar.zst`(客户端默认不下载符号包)。`manifest.json` 记录最终剥离后可执行文件的 SHA-256。
@@ -73,38 +73,36 @@ reims-runtime-<commit>/
## 3. 打包与 CI 自动构建
### 3.1 本地打包
运行 `pwsh -File scripts/pack-runtime.ps1 -Channel alpha` 一次产出以下发布附件:
### 3.1 运行时发布附件
运行时仓库的 [`pack-runtime.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/pack-runtime.ps1) 产出以下发布附件。
1. `reims-runtime-win-x64-<commit>.tar.zst`(运行时主体)
2. `reims-runtime-symbols-<commit>.tar.zst`(独立调试符号包)
3. `reims-runtime-src-<commit>.tar.zst`(上游源码 + 补丁原文 + 重建说明)
4. `reims-runtime-msys2-src-<commit>.tar.zst`(MSYS2 copyleft DLL 源码包,由 [`scripts/pack-msys2-sources.ps1`](../scripts/pack-msys2-sources.ps1) 生成)
3. `reims-runtime-src-<commit>.tar.zst`(运行时源码、依赖补丁和重建说明)
4. `reims-runtime-msys2-src-<commit>.tar.zst`(MSYS2 copyleft DLL 源码包,由 [`pack-msys2-sources.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/pack-msys2-sources.ps1) 生成)
5. `SHA256SUMS.txt`(覆盖上述压缩包的统一校验清单)
打包前脚本会核对构建目录的 `git diff` 是否与声明的补丁逐字节一致;存在未声明修改或补丁不匹配时立即停止。
### 3.2 每日 CI 构建
[`.github/workflows/build-runtime.yml`](../.github/workflows/build-runtime.yml) 每日定时(也支持手动指定 commit)在 `windows-latest`(MSYS2 CLANG64)执行:
1. 读取上游默认分支 `HEAD`;若已存在 `runtime-<commit>` Release(不论 `alpha` 或 `stable`)则跳过。
2. 由 [`scripts/apply-patch-series.ps1`](../scripts/apply-patch-series.ps1) 按 [`patches/series.txt`](../patches/series.txt) 顺序打补丁:可正常应用的直接应用;已合入上游的自动跳过并开 Issue 提醒退役;遇到冲突则中止构建。
3. 执行上游 `scripts/install-ctl.sh --yes` 编译,调用 `scripts/pack-runtime.ps1 -Channel alpha` 打包。
4. 运行 [`scripts/check-runtime-alpha.ps1`](../scripts/check-runtime-alpha.ps1) 校验 5 个附件、`SHA256SUMS.txt`、`manifest.json` 哈希一致、许可证齐全,以及在不含 MSYS2 的纯净 `PATH` 下验证 vGPU 设备枚举、CLI 版本与 `qcow2` 创建读取。
5. 通过后发布为 GitHub 预发布(`alpha`),并自动清理超过保留上限(最近 7 个)的旧 `alpha` 预发布;正式版不受影响。
Reims vGPU fork 的 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) 每日构建,也支持手动指定提交。工作流从运行时仓库读取打包脚本和依赖补丁,在 `windows-latest`(MSYS2 CLANG64)执行以下步骤。
1. 读取 Reims vGPU fork 的运行时分支,并检出其中固定的 QEMU fork 提交。若该 Reims vGPU 提交已有运行时 Release,则跳过。
2. 按 [`series.txt`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/series.txt) 顺序为固定的依赖版本应用补丁。已合入上游的补丁会跳过并报告,遇到冲突时中止构建。
3. 运行 Reims vGPU 源码中的 `scripts/install-ctl.sh --yes` 编译,再调用运行时仓库的打包脚本。
4. 运行 [`check-runtime-alpha.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/check-runtime-alpha.ps1) 校验附件哈希、许可证、挂起能力声明,以及在不含 MSYS2 的 `PATH` 下验证 vGPU 设备枚举、CLI 版本和 `qcow2` 创建读取。
5. 通过后在 Reims vGPU fork 的 Releases 发布 Preview,标记为 GitHub 预发布(`alpha`)。手动构建可通过 `publish=false` 仅下载 CI 产物进行验证。
> **CI 边界**:GitHub 托管的 Windows Server runner 不提供 WHPX,也无法复现 Windows 10 兼容性问题。CI 只验证可编译与控制面基本可用,实际能否启动 macOS 桌面必须经过第 5 节的真机冒烟。
### 3.3 客户端下载与安装
`internal/runtime` 默认从 GitHub Releases(tag `runtime-<commit>`)拉取,沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。
`internal/runtime` 从 `yxc0915/reims-vgpu` 的 GitHub Releases 查找 `runtime-<commit>`。默认列出正式运行时,开启内核 Alpha 后同时列出 Preview。下载沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。
---
## 4. 补丁队列
本仓库不维护长期 fork,所有尚未合入上游的最小兼容性补丁统一维护在 [`patches/`](../patches/)。补丁清单、作用对象、上游化进展与退役检查表见:
- 机器清单:[`patches/series.txt`](../patches/series.txt)
- 维护文档:[`patches/README.md`](../patches/README.md)
Reims vGPU 和 QEMU 的修改由各自的 fork 维护。Reims vGPU fork 的 [依赖补丁目录](https://github.com/yxc0915/reims-vgpu/tree/master/packaging/windows-runtime/patches) 保存构建时应用的补丁与维护说明。
运行时包的 `manifest.json` 必须如实列出所有实际应用的补丁与哈希,带补丁的构建不得标注为纯上游版本。
运行时包的 `manifest.json` 记录源码仓库、提交、运行时能力及打包时应用的依赖补丁和哈希。
---
@@ -114,11 +112,11 @@ reims-runtime-<commit>/
| 通道 | GitHub Release 形态 | 准入条件 |
| :--- | :--- | :--- |
| **`alpha`** | 预发布(Pre-release) | CI 每日自动构建并通过 `scripts/check-runtime-alpha.ps1` 全部校验 |
| **`stable`** | 正式发布(Release) | 从 `alpha` 晋升:在真实 Windows 10/11 宿主运行 [`scripts/smoke-runtime.ps1`](../scripts/smoke-runtime.ps1),验证纯净目录 `doctor`、启动至 macOS 桌面、截屏与正常关机,经人工确认后晋升 |
| **`alpha`** | 预发布(Pre-release) | 运行时 CI 自动构建并通过 Alpha 准入检查 |
| **`stable`** | 正式发布(Release) | 从 `alpha` 晋升。在真实 Windows 10/11 宿主运行 [`smoke-runtime.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/smoke-runtime.ps1),验证纯净目录 `doctor`、启动至 macOS 桌面、截屏与正常关机,经人工确认后晋升 |
- 客户端默认仅获取 `stable` 通道;`alpha` 需用户在界面开启「接收 Alpha 版」或在 CLI 传入 `--alpha`。
- 晋升 `stable` 不重新打包,仅将既有 GitHub 预发布转为正式发布,确保用户下载的二进制与冒烟验证的资产完全一致(因此包内 `manifest.json` 的构建通道字段保持 `alpha`,客户端以 Release 状态区分通道)。
- 晋升 `stable` 时,在运行时仓库将已通过冒烟的 Preview 改为正式 Release,并移除标题中的 Alpha 标记。保留原资产、校验清单和 `manifest.json` 的构建通道。
---
@@ -129,6 +127,6 @@ Reims-Go 本体(Go 后端与前端外壳)采用 [Apache-2.0](../LICENSE) 协
由于便携运行时包含 GPLv2(QEMU)、`GPL-2.0-or-later OR LGPL-3.0-or-later`(`reims-vgpu` / `reims-ctl` / `metal2vulkan`)以及 MSYS2 CLANG64 / libva 动态库,每个公开运行时 Release **必须同处附带完整对应源码与许可证文本**:
1. **上游源码包(`reims-runtime-src-<commit>.tar.zst`)**:导出所用 commit 的四个上游仓库源码树、构建所需的 QEMU meson 子项目、`patches/` 中的全部补丁原文及重建说明。
2. **MSYS2 copyleft 源码包(`reims-runtime-msys2-src-<commit>.tar.zst`)**:由 [`scripts/pack-msys2-sources.ps1`](../scripts/pack-msys2-sources.ps1) 根据本机 pacman 元数据自动筛选全部无宽松替代协议的 GPL / LGPL / MPL 依赖包,下载官方 `.src.tar.zst` 并使用 `gpgv` 与 MSYS2 密钥逐一验签,同时附带 `MSYS2-PACKAGES.txt` 说明全部 DLL 归属与许可。
3. **许可证与声明**:运行时包根目录内置 [`NOTICE.md`](../NOTICE.md) 与 `licenses/` 全文。
2. **MSYS2 copyleft 源码包(`reims-runtime-msys2-src-<commit>.tar.zst`)**:由 [`pack-msys2-sources.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/pack-msys2-sources.ps1) 根据本机 pacman 元数据自动筛选全部无宽松替代协议的 GPL / LGPL / MPL 依赖包,下载官方 `.src.tar.zst` 并使用 `gpgv` 与 MSYS2 密钥逐一验签,同时附带 `MSYS2-PACKAGES.txt` 说明全部 DLL 归属与许可。
3. **许可证与声明**:运行时包根目录内置 [`NOTICE.md`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/NOTICE.md) 与 `licenses/` 全文。
4. **不含 Apple 专有文件**:任何仓库目录或运行时 Release 均不包含 macOS 安装包、恢复镜像、解密固件或 SMC 密钥;系统安装包均由用户端直连 Apple 服务器获取。
+53
View File
@@ -0,0 +1,53 @@
# PR 变更归属审查
> 以产生行为的实现为准。先定位改动发生在哪个组件,再决定提交仓库和验证范围。桌面或 CLI 是否有入口,只决定客户端是否也需要改动。
## 1. 确认归属
以 PR 实际目标分支与提交的差异为准。使用 GitHub 的「Files changed」或本地 `git diff <base>...<head>`,同时检查生成文件对应的源文件、补丁目标、依赖锁定和 CI 变更。先从用户入口沿调用链找到行为的实现,再按下表归属。
| 类别 | 行为或改动 | 实现归属 |
| :--- | :--- | :--- |
| 客户端 | GUI、CLI、虚拟机流程编排、宿主机体检及窗口集成、Guest Tools、运行时下载和安装 | `Reims-Go`。主要入口和模块见[系统架构](architecture.md)。 |
| 客户端运行时适配 | 构造命令和环境、调用已发布的 CLI / QMP 接口、解析结果以及处理版本、能力或错误 | `Reims-Go`。生效行为仍由被调用的组件实现。 |
| Reims vGPU 内核及控制工具 | `reims-ctl` 的配置、启动与参数语义,`reims-restore` 的恢复流程,Reims 的宿主图形、原生 VM 窗口及输入实现 | [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)。运行时所用改动以 [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu) 的实际构建提交为准。 |
| QEMU 虚拟化层 | WHPX / TCG、客体机器与设备模型、`reims-graphics-pci` 的 PCI 设备侧、QMP 命令实现、`qcow2` 格式与迁移机制 | [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)。核对构建提交中的 `vendor/qemu` gitlink 及其来源。 |
| 独立上游工具 | `reims-util` 内的引导资源生成、安装镜像处理和工具自身的参数语义 | [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。按运行时锁定的提交定位。 |
| 独立图形依赖 | Metal 到 Vulkan 的命令、资源和着色器转换实现 | [`steelbrain/metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。按运行时锁定的提交定位。 |
| 其他独立引擎 | 引擎自身的执行、翻译和固件实现 | 对应引擎的源代码仓库。客户端的驱动注册、启动参数适配和状态展示仍归 `Reims-Go`。 |
| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`yxc0915/reims-vgpu`](https://github.com/yxc0915/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时规范](portable-runtime-spec.md)。 |
同一项功能可以涉及多个仓库。窗口安装引导调用已有运行时能力时,浮层、进度和流程编排属于客户端。若同时调整 Reims 原生窗口的事件语义,窗口实现属于 `reims-vgpu`,调用和交互留在客户端。挂起功能同理,GUI / CLI 和任务状态属于客户端,QEMU 的迁移或设备状态实现属于 QEMU;运行时再负责选取具备该能力的版本。
## 2. 审查客户端独立性
- **构建与发布**:客户端 CI 仅从 `Reims-Go` 源码检出完成前端构建、Go 检查和应用产物构建。运行时源码、编译工具链和运行时发布产物由运行时仓库管理。客户端自行发布应用,并在虚拟机运行前下载、校验或导入兼容的独立运行时。
- **接口边界**:客户端通过约定的子进程接口和协议调用运行时。配置写入沿用 [`reims-ctl set`](design-guidelines.md#2-配置原语)。需要新增命令、参数、字段或能力时,在负责组件实现,并在客户端附上对应接口证据。
- **运行时兼容**:客户端 PR 写明验证使用的运行时与最低要求。若依赖新能力,优先使用运行时明确声明的能力或版本,在旧版、缺失运行时和不支持该能力的场景下明确禁用、提示或保留既有流程。客户端合入与运行时发布各自按其流程验收,用户默认仍走受支持的 `stable` 通道。
- **跨仓交付**:按归属拆分 PR。客户端 PR 链接底层 PR、提交或运行时版本,列出合并顺序和兼容路径。临时依赖补丁由运行时仓库记录,注明目标仓库、适用提交和退役条件。跨仓定位以源码、依赖锁定和产物清单为证据。
## 3. PR 描述与合并检查
提交者在 PR 描述中附上以下信息。纯文档或纯客户端改动可将无关字段写为「不适用」。
```markdown
## 变更归属
- 用户可见行为
- 变更位置与责任仓库
- 上游证据(仓库、commit、文件及行号)
- 跨仓依赖(关联 PR、合并顺序、运行时要求)
- 旧版或缺失运行时的表现
## 验证
- 已通过的检查及运行时版本
- 待验证场景及其影响
```
审查者在合并前核对以下各项。
- [ ] 差异中的客户端、内核、独立依赖和分发变更均已注明归属。跨仓实现已拆分并可追溯。
- [ ] 客户端能独立通过其 CI。行为变更已按影响验证 GUI、CLI 或两者的正常入口。
- [ ] 底层或打包改动有负责仓库的验证证据。涉及运行时发布时,核对 `manifest.json` 中的来源提交、补丁与能力声明,以及相应的 [`alpha` 准入与 `stable` 冒烟要求](portable-runtime-spec.md#5-发布通道alpha--stable)。
- [ ] 上游行为已定位到对应提交和源码行号。真机或兼容性覆盖不足的场景标明「待验证」,合并前明确其对客户端发布和能力开放的影响。
+2 -2
View File
@@ -33,12 +33,12 @@
优先打磨和验证已有能力,在 P0 任务稳定前不堆砌新子系统。
### 1. 首次装机与发版闭环
- 在 GitHub Actions 上实跑 `build-runtime.yml` 每日构建与 `alpha` 准入流程,验证公开资产的 `manifest.json`、补丁队列与源码包一致性。
- 在运行时仓库的 [Preview CI](https://github.com/yxc0915/reims-vgpu/actions/workflows/runtime-preview.yml) 验证公开资产的 `manifest.json`、补丁队列与源码包一致性。
- 在多种受支持的 Windows 10 / 11、GPU 与 macOS 组合上跑通完整开箱流程(干净目录 → 体检 → 安装运行时 → 下载离线包 → 装机 → 退出恢复模式)。
- 完善中断与异常场景的故障恢复(断网续传、磁盘不足、取消 UAC、运行时损坏),确保失败后可安全重试且不残留半配置虚拟机。
### 2. 日常主力体验与上游性能跟进
- 持续跟进上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的 Windows 图形与窗口改进(热切全屏、无黑边窗口缩放、原生 Windows Vulkan 后端、首帧延迟优化、自由指针 `Win → Command` 映射),合入后经 `alpha` 冒烟升级至 `stable`(跟踪明细见 [patches/README.md](../patches/README.md))。
- 持续跟进上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的 Windows 图形与窗口改进(热切全屏、无黑边窗口缩放、原生 Windows Vulkan 后端、首帧延迟优化、自由指针 `Win → Command` 映射),合入后经 `alpha` 冒烟升级至 `stable`。跟踪明细见[运行时补丁文档](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md)。
- 推动当前本地兼容性补丁上游化,并逐步清零 `patches/` 队列。
- 在真实宿主完成长时间开发负载验证(编译、浏览器、多任务、图文剪贴板、WebDAV 挂载、Windows 盘符只读共享、音频/麦克风与休眠唤醒恢复)。
- 修复 WebDAV 共享目录可经 Junction 逃逸的路径校验缺陷,并把共享目录与只读盘统一到基于 `os.Root` 的路径安全层;随后按测量结果推进小文件 I/O 优化。
+48
View File
@@ -0,0 +1,48 @@
{
"bridgeApi": "1.0.0",
"methods": [
"hello",
"i18n.getBundle",
"ui.notify",
"vm.list",
"command.invoke"
],
"events": [
"theme.changed",
"locale.changed"
],
"experimental": {
"methods": [
"ui.confirm",
"ui.showForm",
"ui.setTitle",
"ui.setBadge",
"ui.openView",
"ui.close",
"ui.navigate",
"ui.openExternal",
"vm.get",
"settings.get",
"settings.set",
"storage.get",
"storage.set",
"storage.list",
"storage.delete",
"file.pick",
"file.save",
"file.read",
"file.write",
"task.start",
"task.update",
"task.finish",
"net.fetch",
"events.subscribe",
"events.unsubscribe"
],
"events": [
"vm.stateChanged",
"view.visibilityChanged",
"task.updated"
]
}
}
+2 -2
View File
@@ -1,11 +1,11 @@
{
"name": "reims-go-frontend",
"private": true,
"version": "0.2.10",
"version": "0.2.11",
"type": "module",
"scripts": {
"dev": "vite",
"test": "node --test scripts/test-i18n.mjs",
"test": "node --test scripts/test-i18n.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs",
"build": "tsc --noEmit && vite build && node scripts/check-ui-contract.mjs",
"preview": "vite preview"
},
+1 -1
View File
@@ -1 +1 @@
58f4fafea894c5f7c1c6ebefde51e110
d5f2fdb982362b7c1d77e7244b0a024f
+148 -37
View File
@@ -1,3 +1,9 @@
// Checks the UI and bridge contracts (docs/plugin-architecture.md §5.1, §5.6, §6.3)
// and writes ui-contract.json / bridge-contract.json for plugin authors.
//
// Rule "public means implemented": every stable part, state attribute, slot and
// layer must be emitted by the host, and an experimental entry the host already
// emits must be promoted to stable in the same change.
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -7,55 +13,160 @@ const rootDir = path.resolve(__dirname, '..')
const srcDir = path.join(rootDir, 'src')
const contractSrc = fs.readFileSync(path.join(srcDir, 'styles', 'ui-contract.ts'), 'utf8')
const bridgeSrc = fs.readFileSync(path.join(srcDir, 'lib', 'bridgeContract.ts'), 'utf8')
const tokensCss = fs.readFileSync(path.join(srcDir, 'styles', 'tokens.css'), 'utf8')
const appCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8')
function extractArray(name) {
function extractArray(src, name) {
const re = new RegExp(`export const ${name} = \\[([\\s\\S]*?)\\] as const`)
const m = contractSrc.match(re)
if (!m) throw new Error(`Could not parse ${name} from ui-contract.ts`)
const m = src.match(re)
if (!m) throw new Error(`Could not parse ${name}`)
return [...m[1].matchAll(/'([^']+)'/g)].map((x) => x[1])
}
function extractVersion(src, name) {
const m = src.match(new RegExp(`${name}\\s*=\\s*'([^']+)'`))
if (!m) throw new Error(`Could not parse ${name}`)
return m[1]
}
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const apiMatch = contractSrc.match(/UI_API_VERSION\s*=\s*'([^']+)'/)
const uiApi = apiMatch ? apiMatch[1] : '1.0.0'
const parts = extractArray('UI_CONTRACT_PARTS')
const stateAttrs = extractArray('UI_CONTRACT_STATE_ATTRS')
const slots = extractArray('UI_CONTRACT_SLOTS')
const tokens = extractArray('UI_CONTRACT_TOKENS')
const uiApi = extractVersion(contractSrc, 'UI_API_VERSION')
const stable = {
parts: extractArray(contractSrc, 'UI_CONTRACT_PARTS'),
stateAttrs: extractArray(contractSrc, 'UI_CONTRACT_STATE_ATTRS'),
itemStates: extractArray(contractSrc, 'UI_CONTRACT_ITEM_STATES'),
slots: extractArray(contractSrc, 'UI_CONTRACT_SLOTS'),
layers: extractArray(contractSrc, 'UI_CONTRACT_LAYERS'),
layoutOptions: extractArray(contractSrc, 'UI_CONTRACT_LAYOUT_OPTIONS'),
icons: extractArray(contractSrc, 'UI_CONTRACT_ICONS'),
viewLocations: extractArray(contractSrc, 'UI_CONTRACT_VIEW_LOCATIONS'),
sdkEvents: extractArray(contractSrc, 'UI_CONTRACT_SDK_EVENTS'),
tokens: extractArray(contractSrc, 'UI_CONTRACT_TOKENS'),
}
const experimental = {
parts: extractArray(contractSrc, 'UI_CONTRACT_PARTS_EXPERIMENTAL'),
stateAttrs: extractArray(contractSrc, 'UI_CONTRACT_STATE_ATTRS_EXPERIMENTAL'),
itemStates: extractArray(contractSrc, 'UI_CONTRACT_ITEM_STATES_EXPERIMENTAL'),
slots: extractArray(contractSrc, 'UI_CONTRACT_SLOTS_EXPERIMENTAL'),
layers: extractArray(contractSrc, 'UI_CONTRACT_LAYERS_EXPERIMENTAL'),
layoutOptions: extractArray(contractSrc, 'UI_CONTRACT_LAYOUT_OPTIONS_EXPERIMENTAL'),
icons: extractArray(contractSrc, 'UI_CONTRACT_ICONS_EXPERIMENTAL'),
viewLocations: extractArray(contractSrc, 'UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL'),
sdkEvents: extractArray(contractSrc, 'UI_CONTRACT_SDK_EVENTS_EXPERIMENTAL'),
}
const bridgeApi = extractVersion(bridgeSrc, 'BRIDGE_API_VERSION')
const bridge = {
methods: extractArray(bridgeSrc, 'BRIDGE_METHODS'),
events: extractArray(bridgeSrc, 'BRIDGE_EVENTS'),
experimentalMethods: extractArray(bridgeSrc, 'BRIDGE_METHODS_EXPERIMENTAL'),
experimentalEvents: extractArray(bridgeSrc, 'BRIDGE_EVENTS_EXPERIMENTAL'),
}
// Collect all React component TSX source text (excluding contract/SDK/theme helpers)
// and verify every declared part class is emitted as a distinct class token (§5.1, M17).
function readComponentTsx(dir) {
// Host source the contract is emitted from (contract/SDK definitions excluded).
function readSources(dir, exts) {
let buf = ''
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) buf += readComponentTsx(full)
else if (entry.name.endsWith('.tsx')) buf += '\n' + fs.readFileSync(full, 'utf8')
if (entry.isDirectory()) buf += readSources(full, exts)
else if (exts.some((e) => entry.name.endsWith(e)) && !/ui-contract\.ts$|bridgeContract\.ts$|\.gen\.ts$/.test(entry.name)) {
buf += '\n' + fs.readFileSync(full, 'utf8')
}
}
return buf
}
const allTsx = readSources(srcDir, ['.tsx'])
const allCode = readSources(srcDir, ['.ts', '.tsx'])
// Per-file sources, for checks that need two things in the same component.
function sourceFiles(dir, out = []) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) sourceFiles(full, out)
else if (entry.name.endsWith('.tsx')) out.push(fs.readFileSync(full, 'utf8'))
}
return out
}
const tsxFiles = sourceFiles(srcDir)
const allTsx = readComponentTsx(srcDir)
const missingParts = parts.filter((p) => {
const re = new RegExp(`(?<![a-zA-Z0-9_-])${p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![a-zA-Z0-9_-])`)
return !re.test(allTsx)
const hasClass = (p) => new RegExp(`(?<![a-zA-Z0-9_-])${esc(p)}(?![a-zA-Z0-9_-])`).test(allTsx)
const camel = (attr) => attr.replace(/^data-/, '').replace(/-([a-z])/g, (_, c) => c.toUpperCase())
const hasAttr = (a) => allCode.includes(a) || new RegExp(`dataset\\.${camel(a)}\\b`).test(allCode)
const hasSlot = (s) => allTsx.includes(`data-rg-slot="${s}"`)
const hasLayer = (l) => allTsx.includes(`data-rg-layer="${l}"`)
const errors = []
const fail = (msg, list) => { if (list.length) errors.push(`${msg}: ${list.join(', ')}`) }
fail('stable parts not emitted by any component', stable.parts.filter((p) => !hasClass(p)))
fail('stable state attributes never set', stable.stateAttrs.filter((a) => !hasAttr(a)))
fail('stable slots without a data-rg-slot anchor', stable.slots.filter((s) => !hasSlot(s)))
fail('stable layers without a data-rg-layer element', stable.layers.filter((l) => !hasLayer(l)))
fail('stable tokens missing in tokens.css', stable.tokens.filter((tk) => !tokensCss.includes(`${tk}:`)))
// An item state counts as emitted when one component carries both the part and the attribute.
fail('stable item states not emitted together with their part', stable.itemStates.filter((s) => {
const [part, attr] = s.split(':')
return !tsxFiles.some((src) => new RegExp(`(?<![a-zA-Z0-9_-])${esc(part)}(?![a-zA-Z0-9_-])`).test(src) && src.includes(`${attr}=`))
}))
// Layout values other than the defaults need CSS that implements them.
const LAYOUT_ATTR = { sidebarPosition: 'data-layout-sidebar', sidebarMode: 'data-layout-sidebar-mode', density: 'data-layout-density', titlebar: 'data-layout-titlebar' }
const LAYOUT_DEFAULTS = ['sidebarPosition=left', 'sidebarMode=full', 'density=regular', 'titlebar=standard']
fail('stable layout options without CSS in app.css', stable.layoutOptions.filter((o) => {
if (LAYOUT_DEFAULTS.includes(o)) return false
const [opt, val] = o.split('=')
return !LAYOUT_ATTR[opt] || !appCss.includes(`[${LAYOUT_ATTR[opt]}="${val}"]`)
}))
fail('layout options with an unknown option name', [...stable.layoutOptions, ...experimental.layoutOptions].filter((o) => !LAYOUT_ATTR[o.split('=')[0]]))
// Every stable icon name is rendered through <HostIcon name="..."> (or the status-shape map).
const controlsSrc = fs.readFileSync(path.join(srcDir, 'ui', 'controls.tsx'), 'utf8')
fail('stable icon names never rendered through HostIcon', stable.icons.filter((n) =>
!allTsx.includes(`HostIcon name="${n}"`) && !(n.startsWith('vm.state.') && controlsSrc.includes(`'${n}'`))))
// Every stable SDK event has an emitter.
fail('stable SDK events never emitted', stable.sdkEvents.filter((e) => !allCode.includes(`emitThemeEvent('${e}'`)))
fail('experimental parts already emitted (promote them to UI_CONTRACT_PARTS)', experimental.parts.filter(hasClass))
fail('experimental slots already anchored (promote them to UI_CONTRACT_SLOTS)', experimental.slots.filter(hasSlot))
fail('experimental layers already rendered (promote them to UI_CONTRACT_LAYERS)', experimental.layers.filter(hasLayer))
const overlap = (a, b) => a.filter((x) => b.includes(x))
fail('entries listed as both stable and experimental (parts)', overlap(stable.parts, experimental.parts))
fail('entries listed as both stable and experimental (state attributes)', overlap(stable.stateAttrs, experimental.stateAttrs))
fail('entries listed as both stable and experimental (slots)', overlap(stable.slots, experimental.slots))
fail('entries listed as both stable and experimental (layers)', overlap(stable.layers, experimental.layers))
fail('entries listed as both stable and experimental (item states)', overlap(stable.itemStates, experimental.itemStates))
fail('entries listed as both stable and experimental (layout options)', overlap(stable.layoutOptions, experimental.layoutOptions))
fail('entries listed as both stable and experimental (icons)', overlap(stable.icons, experimental.icons))
fail('entries listed as both stable and experimental (view locations)', overlap(stable.viewLocations, experimental.viewLocations))
fail('entries listed as both stable and experimental (SDK events)', overlap(stable.sdkEvents, experimental.sdkEvents))
fail('bridge methods listed as both stable and experimental', overlap(bridge.methods, bridge.experimentalMethods))
fail('bridge events listed as both stable and experimental', overlap(bridge.events, bridge.experimentalEvents))
const knownParts = [...stable.parts, ...experimental.parts]
fail('item states on unknown parts', [...stable.itemStates, ...experimental.itemStates].filter((s) => !knownParts.includes(s.split(':')[0])))
for (const [name, list] of Object.entries({ ...stable, ...experimental, ...bridge })) {
const dupes = list.filter((x, i) => list.indexOf(x) !== i)
fail(`duplicate entries in ${name}`, dupes)
}
if (errors.length > 0) {
for (const e of errors) console.error(`[ui-contract] ERROR: ${e}`)
process.exit(1)
}
const write = (file, data) => {
const text = JSON.stringify(data, null, 2) + '\n'
fs.writeFileSync(path.join(rootDir, file), text, 'utf8')
const distDir = path.join(rootDir, 'dist')
if (fs.existsSync(distDir)) fs.writeFileSync(path.join(distDir, file), text, 'utf8')
}
write('ui-contract.json', { uiApi, ...stable, experimental })
write('bridge-contract.json', {
bridgeApi,
methods: bridge.methods,
events: bridge.events,
experimental: { methods: bridge.experimentalMethods, events: bridge.experimentalEvents },
})
const missingTokens = tokens.filter((tk) => !tokensCss.includes(`${tk}:`))
if (missingParts.length > 0) {
console.error('[ui-contract] ERROR: contract parts not emitted by any component:', missingParts.join(', '))
process.exit(1)
}
if (missingTokens.length > 0) {
console.error('[ui-contract] ERROR: contract tokens missing in tokens.css:', missingTokens.join(', '))
process.exit(1)
}
const out = { uiApi, tokens, parts, stateAttrs, slots }
const jsonText = JSON.stringify(out, null, 2) + '\n'
fs.writeFileSync(path.join(rootDir, 'ui-contract.json'), jsonText, 'utf8')
const distDir = path.join(rootDir, 'dist')
if (fs.existsSync(distDir)) {
fs.writeFileSync(path.join(distDir, 'ui-contract.json'), jsonText, 'utf8')
}
console.log(`[ui-contract] OK (uiApi=${uiApi}, parts=${parts.length}, tokens=${tokens.length}, slots=${slots.length})`)
console.log(
`[ui-contract] OK (uiApi=${uiApi}, parts=${stable.parts.length}+${experimental.parts.length}x, ` +
`tokens=${stable.tokens.length}, slots=${stable.slots.length}+${experimental.slots.length}x, layers=${stable.layers.length}, ` +
`icons=${stable.icons.length}, sdkEvents=${stable.sdkEvents.length}, ` +
`bridgeApi=${bridgeApi}, methods=${bridge.methods.length}+${bridge.experimentalMethods.length}x)`,
)
+157
View File
@@ -63,8 +63,11 @@ test('Static Guard (CRITICAL-1): lazy i18n domain keys are always backed by doma
'Setup.tsx',
'RuntimeOnline.tsx',
'HostView.tsx',
'ImagesPage.tsx',
'InstallersPage.tsx',
'PluginsPage.tsx',
'PluginMarket.tsx',
'PluginParts.tsx',
'AppSettingsPage.tsx',
'AboutPage.tsx',
'PluginPanelFrame.tsx',
@@ -136,6 +139,86 @@ test('Static Guard (CRITICAL-2): every stack-*, notice-*, error-boundary*, and t
}
})
test('Static Guard (CRITICAL-3): Radix Presence .menu/.tooltip animations never replay on close', () => {
const rawCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8')
const css = rawCss.replace(/\/\*[\s\S]*?\*\//g, '')
const titleMenus = fs.readFileSync(path.join(srcDir, 'components', 'TitleMenus.tsx'), 'utf8')
// Unconditional `.menu` / `.tooltip` animation (including animation-name inside
// comma-separated selector lists or reduced-motion media queries) causes Radix
// Presence to detect an animationName change on close and flash for 160ms.
for (const m of css.matchAll(/([^{}@]+)\{([^{}]+)\}/g)) {
const selectors = m[1].split(',').map((s) => s.trim()).filter(Boolean)
const decls = m[2]
if (!/\banimation(?:-name)?\s*:(?!\s*none\b)/.test(decls)) continue
for (const sel of selectors) {
assert.doesNotMatch(
sel,
/\.menu(?![a-zA-Z0-9_-])(?!\[data-state="open"\])/,
`Non-open .menu selector "${sel}" must not apply an active animation`,
)
assert.doesNotMatch(
sel,
/\.tooltip(?![a-zA-Z0-9_-])(?!\[data-state="delayed-open"\])/,
`Non-delayed-open .tooltip selector "${sel}" must not apply an active animation`,
)
}
}
assert.match(
css,
/\.menu\[data-state="open"\]\s*\{[^}]*animation\s*:/,
'.menu[data-state="open"] must define the menu enter animation',
)
assert.match(
css,
/\.menu\[data-state="open"\]\[data-menubar-switch="true"\][^\{]*\{[^}]*animation\s*:\s*none/,
'.menu[data-state="open"][data-menubar-switch="true"] must disable enter animation',
)
assert.match(
css,
/\.menu\[data-state="closed"\][^\{]*\{[^}]*animation\s*:\s*none/,
'.menu[data-state="closed"] must explicitly disable animation so Radix Presence unmounts immediately',
)
assert.match(
css,
/\.tooltip\[data-state="closed"\][^\{]*\{[^}]*animation\s*:\s*none/,
'.tooltip[data-state="closed"] must explicitly disable animation',
)
assert.match(
css,
/@media\s*\(\s*prefers-reduced-motion\s*:\s*reduce\s*\)\s*\{[\s\S]*?\.toast\[data-state="closed"\][^{]*\{[^}]*animation-name\s*:\s*fade-out/,
'Reduced-motion .toast[data-state="closed"] must use fade-out',
)
assert.doesNotMatch(
titleMenus,
/data-menubar-switch=\{\s*menuState\.id\s*===\s*id\s*&&\s*menuState\.switched/,
'TitleMenus must not strip data-menubar-switch from the outgoing sibling menu on switch',
)
})
test('Static Guard (CRITICAL-4): software-composited UI avoids backdrop-filter and slow pre shaping', () => {
const rawCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8')
const css = rawCss.replace(/\/\*[\s\S]*?\*\//g, '')
// main.go sets WebviewGpuIsDisabled: true (software compositing), where
// backdrop-filter blurs stall CPU rasterization on animations and scrolling.
assert.doesNotMatch(
css,
/(?:-webkit-)?backdrop-filter\s*:/i,
'app.css must not apply backdrop-filter under software compositing',
)
assert.match(
css,
/\.license-pre\s*\{[^}]*contain\s*:\s*content/,
'.license-pre should isolate scroll/layout repaints with contain: content',
)
assert.match(
css,
/\.license-pre\s*\{[^}]*text-rendering\s*:\s*auto/,
'.license-pre should opt out of global optimizeLegibility for long monospace texts',
)
})
test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppError (HIGH-2), RTL (L-2), and en-XA', async () => {
const mod = await loadBundledTS(`
import './i18n/domains/wizard.gen'
@@ -249,3 +332,77 @@ test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppErr
assert.equal(appleBlue['--accent-text'], '#ffffff')
assert.ok(hslContrast(appleBlue['--accent-soft-text'], 0.015) >= 4.5, `appleBlue dark contrast too low: ${appleBlue['--accent-soft-text']}`)
})
test('VM keymap preserves preset bindings and isolates pending writes by VM', async () => {
const source = fs.readFileSync(path.join(srcDir, 'components/SettingsModal.tsx'), 'utf8')
const normalized = source.replaceAll('\r\n', '\n')
const effects = normalized.slice(
normalized.indexOf(' useEffect(() => {\n setKeymap(null)'),
normalized.indexOf(' const updateDriveShares'),
)
const preset = normalized.match(/onChange=\{(\(preset\) => \{\n\s+if \(preset === keymap\.preset\)[\s\S]*?\n\s+\})\} \/>/)?.[1]
assert.ok(effects.includes('const updateKeymap') && preset)
const { render } = await loadBundledTS(`
export function render({ detail, api, useEffect, window, activeVMNameRef, keymapWrite,
keymapRevision, setKeymap, setKeymapErr, setKeymapBusy, parseAppError, keymap }) {
const cat = 'input'
const running = true
${effects}
return ${preset}
}
`)
let finishWrite
const writes = []
const reads = []
const state = {}
let failRead = true
const context = {
api: {
SetVMKeymap(name, req) {
writes.push([name, req])
return new Promise((resolve) => { finishWrite = resolve })
},
async GetVMKeymap(name) {
reads.push(name)
if (name === 'b' && failRead) throw Error('temporary')
return { preset: 'off', bindings: {} }
},
},
useEffect(effect) {
const cleanup = effect()
if (cleanup) this.cleanups.push(cleanup)
},
cleanups: [],
window: { setInterval(refresh) { this.refresh = refresh }, clearInterval() {} },
activeVMNameRef: { current: 'a' },
keymapWrite: { current: new Set() },
keymapRevision: { current: new Map() },
setKeymap(value) { state.keymap = value },
setKeymapErr(value) { state.error = value },
setKeymapBusy(value) { state.busy = value },
parseAppError: (error) => ({ summary: error.message }),
}
context.useEffect = context.useEffect.bind(context)
const bindings = { lwin: 'lcmd' }
const change = render({ ...context, detail: { name: 'a' }, keymap: { preset: 'win_to_cmd', bindings } })
change('win_to_cmd')
assert.deepEqual(writes, [])
change('custom')
assert.deepEqual(writes, [['a', { preset: 'custom', bindings }]])
context.cleanups.pop()()
context.activeVMNameRef.current = 'b'
const changeB = render({ ...context, detail: { name: 'b' }, keymap: { preset: 'custom', bindings } })
changeB('custom')
assert.equal(writes.length, 1)
assert.deepEqual(reads, ['a', 'b'])
assert.equal(state.busy, false)
await new Promise(setImmediate)
assert.equal(state.error, 'temporary')
failRead = false
await context.window.refresh()
assert.equal(state.error, '')
finishWrite({ preset: 'custom', bindings })
await new Promise(setImmediate)
assert.deepEqual(state.keymap, { preset: 'off', bindings: {} })
})
+52
View File
@@ -0,0 +1,52 @@
// macOS UI lives under src/macos so it can leave the app as a plugin. Host
// files may import from it only while listed below; the test fails when a new
// file starts importing it and when a listed file stops, so the list only
// shrinks (same ratchet as internal/archtest on the Go side).
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import ts from 'typescript'
const srcDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src')
const macosDir = path.join(srcDir, 'macos')
const MACOS_IMPORTERS = {
'App.tsx': 'mounts the installers page and online-recovery dialog; macOS release names in the VM list',
'components/Sidebar.tsx': 'macOS version art next to each VM',
'components/VMPage.tsx': 'macOS version art in the VM header',
}
function walk(dir) {
const out = []
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name)
if (e.isDirectory()) {
if (p !== macosDir) out.push(...walk(p))
} else if (/\.(?:[cm]?[jt]s|[jt]sx)$/.test(e.name)) {
out.push(p)
}
}
return out
}
test('host frontend reaches src/macos only from listed files', () => {
const importers = new Set()
for (const file of walk(srcDir)) {
const text = fs.readFileSync(file, 'utf8')
for (const { fileName } of ts.preProcessFile(text, true, true).importedFiles) {
let target
if (fileName.startsWith('.')) target = path.resolve(path.dirname(file), fileName)
else if (fileName.startsWith('/src/')) target = path.resolve(srcDir, fileName.slice(5))
else continue
if (target === macosDir || target.startsWith(macosDir + path.sep)) {
importers.add(path.relative(srcDir, file).split(path.sep).join('/'))
}
}
}
const unexpected = [...importers].filter((f) => !(f in MACOS_IMPORTERS)).sort()
const stale = Object.keys(MACOS_IMPORTERS).filter((f) => !importers.has(f)).sort()
assert.deepEqual(unexpected, [], `host files import src/macos without being listed in MACOS_IMPORTERS: ${unexpected.join(', ')}`)
assert.deepEqual(stale, [], `listed files no longer import src/macos; remove them from MACOS_IMPORTERS: ${stale.join(', ')}`)
})
+396
View File
@@ -0,0 +1,396 @@
// Guards the AGENTS.md rule forbidding empty catch blocks that silently turn
// failures into successes. Covers JS/TS/JSX/TSX/MJS/CJS via the TypeScript AST
// and PowerShell (.ps1/.psm1/.psd1) via a comment- and string-aware lexer.
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import ts from 'typescript'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const repoRoot = path.resolve(__dirname, '..', '..')
const JS_TS_EXTS = new Set(['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'])
const PS_EXTS = new Set(['.ps1', '.psm1', '.psd1'])
const SKIP_DIRS = new Set(['.git', '.debug', 'node_modules', 'dist', 'build', 'wailsjs'])
function scriptKindFor(filePath) {
switch (path.extname(filePath).toLowerCase()) {
case '.tsx': return ts.ScriptKind.TSX
case '.ts':
case '.mts':
case '.cts': return ts.ScriptKind.TS
case '.jsx': return ts.ScriptKind.JSX
default: return ts.ScriptKind.JS
}
}
function isEmptyBlock(block) {
return ts.isBlock(block) && block.statements.every((stmt) => ts.isEmptyStatement(stmt))
}
function isEmptyFunctionBody(expr) {
let current = expr
while (ts.isParenthesizedExpression(current)) current = current.expression
if (ts.isArrowFunction(current) || ts.isFunctionExpression(current)) {
return isEmptyBlock(current.body)
}
return false
}
function getCalleeMethodName(callee) {
if (ts.isPropertyAccessExpression(callee)) return callee.name.text
if (ts.isElementAccessExpression(callee) && ts.isStringLiteralLike(callee.argumentExpression)) {
return callee.argumentExpression.text
}
return null
}
/**
* Finds empty `catch` clauses and empty Promise `.catch(...)` / `.then(_, ...)`
* rejection callbacks in a JS/TS source string using the TypeScript AST.
*/
export function findEmptyCatchesInJS(sourceText, filePath = 'sample.ts') {
const sf = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true, scriptKindFor(filePath))
const findings = []
const record = (node, kind) => {
const pos = sf.getLineAndCharacterOfPosition(node.getStart(sf))
findings.push({
file: filePath,
line: pos.line + 1,
column: pos.character + 1,
kind,
})
}
function visit(node) {
if (ts.isCatchClause(node) && isEmptyBlock(node.block)) {
record(node, 'empty-catch-clause')
} else if (ts.isCallExpression(node)) {
const method = getCalleeMethodName(node.expression)
if (method === 'catch' && node.arguments.length >= 1 && isEmptyFunctionBody(node.arguments[0])) {
record(node.arguments[0], 'empty-promise-catch')
} else if (method === 'then' && node.arguments.length >= 2 && isEmptyFunctionBody(node.arguments[1])) {
record(node.arguments[1], 'empty-promise-then-reject')
}
}
ts.forEachChild(node, visit)
}
visit(sf)
return findings
}
function tokenizePowerShell(sourceText) {
const tokens = []
let i = 0
let line = 1
let col = 1
const len = sourceText.length
const advance = () => {
const ch = sourceText[i++]
if (ch === '\n') {
line += 1
col = 1
} else {
col += 1
}
return ch
}
const atHereStringEnd = (quote) => {
if (sourceText[i] !== quote || sourceText[i + 1] !== '@') return false
return i === 0 || sourceText[i - 1] === '\n'
}
while (i < len) {
const ch = sourceText[i]
const next = sourceText[i + 1]
// Whitespace
if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') {
advance()
continue
}
// Block comment <# ... #>
if (ch === '<' && next === '#') {
advance()
advance()
while (i < len && !(sourceText[i] === '#' && sourceText[i + 1] === '>')) advance()
if (i < len) {
advance()
advance()
}
continue
}
// Line comment # ...
if (ch === '#') {
while (i < len && sourceText[i] !== '\n') advance()
continue
}
// Here-strings @' ... '@ and @" ... "@
if (ch === '@' && (next === "'" || next === '"')) {
const quote = next
let look = i + 2
while (look < len && (sourceText[look] === ' ' || sourceText[look] === '\t' || sourceText[look] === '\r')) look++
if (look < len && sourceText[look] === '\n') {
const startLine = line
const startCol = col
while (i <= look) advance()
while (i < len && !atHereStringEnd(quote)) advance()
if (i < len) {
advance()
advance()
}
tokens.push({ type: 'string', value: '', line: startLine, column: startCol })
continue
}
}
// Single-quoted string ('' escapes ')
if (ch === "'") {
const startLine = line
const startCol = col
advance()
while (i < len) {
if (sourceText[i] === "'") {
advance()
if (sourceText[i] === "'") {
advance()
continue
}
break
}
advance()
}
tokens.push({ type: 'string', value: '', line: startLine, column: startCol })
continue
}
// Double-quoted string (` escapes next char, "" escapes ")
if (ch === '"') {
const startLine = line
const startCol = col
advance()
while (i < len) {
if (sourceText[i] === '`') {
advance()
if (i < len) advance()
continue
}
if (sourceText[i] === '"') {
advance()
if (sourceText[i] === '"') {
advance()
continue
}
break
}
advance()
}
tokens.push({ type: 'string', value: '', line: startLine, column: startCol })
continue
}
// Backtick escape outside strings
if (ch === '`') {
advance()
if (i < len) advance()
continue
}
const startLine = line
const startCol = col
// :: operator
if (ch === ':' && next === ':') {
advance()
advance()
tokens.push({ type: 'punct', value: '::', line: startLine, column: startCol })
continue
}
// Punctuation relevant to catch syntax
if ('{}[];,.'.includes(ch)) {
advance()
tokens.push({ type: 'punct', value: ch, line: startLine, column: startCol })
continue
}
// Word / identifier / parameter (e.g. -catch, catch)
if (/[A-Za-z_-]/.test(ch)) {
let word = ''
while (i < len && /[A-Za-z0-9_-]/.test(sourceText[i])) word += advance()
tokens.push({ type: 'word', value: word, line: startLine, column: startCol })
continue
}
// Any other token
advance()
tokens.push({ type: 'other', value: ch, line: startLine, column: startCol })
}
return tokens
}
/**
* Finds empty `catch` blocks (including comment-only and semicolon-only blocks,
* with or without `[Type]` exception filters) in a PowerShell script.
*/
export function findEmptyCatchesInPowerShell(sourceText, filePath = 'sample.ps1') {
const tokens = tokenizePowerShell(sourceText)
const findings = []
for (let idx = 0; idx < tokens.length; idx++) {
const tok = tokens[idx]
if (tok.type !== 'word' || tok.value.toLowerCase() !== 'catch') continue
const prev = tokens[idx - 1]
if (prev && (prev.value === '.' || prev.value === '::')) continue
// Skip optional comma-separated type filters: catch [TypeA], [TypeB] { ... }
let cursor = idx + 1
while (cursor < tokens.length && tokens[cursor].value === '[') {
let depth = 0
while (cursor < tokens.length) {
if (tokens[cursor].value === '[') depth++
else if (tokens[cursor].value === ']') {
depth--
if (depth === 0) {
cursor++
break
}
}
cursor++
}
if (cursor < tokens.length && tokens[cursor].value === ',') cursor++
else break
}
if (cursor >= tokens.length || tokens[cursor].value !== '{') continue
// Scan block body until matching '}'
let bodyCursor = cursor + 1
let empty = true
while (bodyCursor < tokens.length && tokens[bodyCursor].value !== '}') {
if (tokens[bodyCursor].value !== ';') {
empty = false
break
}
bodyCursor++
}
if (empty && bodyCursor < tokens.length && tokens[bodyCursor].value === '}') {
findings.push({
file: filePath,
line: tok.line,
column: tok.column,
kind: 'empty-ps-catch',
})
}
}
return findings
}
function walkFiles(dir, out = []) {
if (!fs.existsSync(dir)) return out
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (SKIP_DIRS.has(entry.name)) continue
const full = path.join(dir, entry.name)
if (entry.isDirectory()) walkFiles(full, out)
else out.push(full)
}
return out
}
test('detector self-test: catches all empty JS/TS catch forms and allows handled catches', () => {
const bad = [
'try { a() } catch {}',
'try { a() } catch (e) {}',
'try { a() } catch { /* comment only */ }',
'try { a() } catch (e) {\n // comment only\n}',
'try { a() } catch { ; ; }',
'p.catch(() => {})',
'p?.catch((e) => { /* noop */ })',
'p["catch"](function () {})',
'p.catch(async () => { ; })',
'p.then(ok, () => {})',
'p.then(ok, (err) => { // noop\n})',
].join('\n')
const badFindings = findEmptyCatchesInJS(bad, 'bad.ts')
assert.equal(badFindings.length, 11, `expected 11 findings, got ${JSON.stringify(badFindings)}`)
const good = [
'const text = "try { a() } catch {} .catch(() => {})"',
'// try { a() } catch {}',
'try { a() } catch (e) { console.warn(e) }',
'try { a() } catch { return fallback }',
'p.catch((e) => console.warn(e))',
'p.catch(() => null)',
'p.then(ok, (e) => handle(e))',
].join('\n')
assert.deepEqual(findEmptyCatchesInJS(good, 'good.ts'), [])
})
test('detector self-test: catches empty PowerShell catch blocks and ignores strings/comments', () => {
const bad = [
'try { foo } catch {}',
'try { foo } Catch { # comment only\n}',
'try { foo } catch { <# block comment #> ; }',
'try { foo } catch [System.IO.IOException], [System.Exception] {}',
].join('\n')
const badFindings = findEmptyCatchesInPowerShell(bad, 'bad.ps1')
assert.equal(badFindings.length, 4, `expected 4 findings, got ${JSON.stringify(badFindings)}`)
const good = [
'# try { foo } catch {}',
'<# try { foo } catch {} #>',
'$s1 = "try { foo } catch {}"',
"$s2 = 'try { foo } catch {}'",
'$here = @"\ntry { foo } catch {}\n"@',
'$obj.catch { }',
'try { foo } catch { Write-Warning $_ }',
'try { foo } catch [System.Exception] { throw }',
].join('\n')
assert.deepEqual(findEmptyCatchesInPowerShell(good, 'good.ps1'), [])
})
test('repository has zero empty catch blocks across frontend/ and scripts/', () => {
const roots = [path.join(repoRoot, 'frontend'), path.join(repoRoot, 'scripts')]
const violations = []
let scannedJS = 0
let scannedPS = 0
for (const root of roots) {
for (const file of walkFiles(root)) {
const ext = path.extname(file).toLowerCase()
const rel = path.relative(repoRoot, file).split(path.sep).join('/')
if (JS_TS_EXTS.has(ext)) {
scannedJS += 1
const text = fs.readFileSync(file, 'utf8')
violations.push(...findEmptyCatchesInJS(text, rel))
} else if (PS_EXTS.has(ext)) {
scannedPS += 1
const text = fs.readFileSync(file, 'utf8')
violations.push(...findEmptyCatchesInPowerShell(text, rel))
}
}
}
assert.ok(scannedJS > 0, 'expected to scan at least one JS/TS file')
assert.ok(scannedPS > 0, 'expected to scan at least one PowerShell file')
assert.deepEqual(
violations.map((v) => `${v.file}:${v.line}:${v.column} (${v.kind})`),
[],
`Empty catch blocks found (forbidden by AGENTS.md):\n${violations.map((v) => ` - ${v.file}:${v.line}:${v.column} (${v.kind})`).join('\n')}`,
)
})
+298 -97
View File
@@ -3,25 +3,28 @@ import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from
import type { WizardDraft } from './components/CreateWizard'
import { DeleteDialog } from './components/DeleteDialog'
import { CloneDialog } from './components/CloneDialog'
import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog'
import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog'
import { SendTextDialog } from './components/SendTextDialog'
import type { ThemeMode } from './components/AppSettingsPage'
import { LogPanel, LogTab } from './components/LogPanel'
import { TitleMenus } from './components/TitleMenus'
import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule'
import { DataRootReadOnly } from './components/DataRootReadOnly'
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
import { VMAction, VMPage } from './components/VMPage'
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 { macOSMajor } from './macos/macosRelease'
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 { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, emitThemeEvent, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine'
import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats'
import { vmRefKey } from './lib/vmRef'
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 { ConfirmDialog, Modal } from './ui/dialog'
import { Toaster, useToasts } from './ui/toast'
import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals'
import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from './wails'
// Opened on demand, so each is its own chunk and stays out of the startup
@@ -32,7 +35,8 @@ const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) =
const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m) => ({ default: m.AffinityDialog })))
const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup })))
const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView })))
const InstallersPage = lazy(() => import('./components/InstallersPage').then((m) => ({ default: m.InstallersPage })))
const ImagesPage = lazy(() => import('./components/ImagesPage').then((m) => ({ default: m.ImagesPage })))
const InstallersPage = lazy(() => import('./macos/InstallersPage').then((m) => ({ default: m.InstallersPage })))
const PluginsPage = lazy(() => import('./components/PluginsPage').then((m) => ({ default: m.PluginsPage })))
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage })))
@@ -41,7 +45,11 @@ const errText = (e: unknown) => parseAppError(e).summary
const failKey: Record<VMAction, I18nKey> = {
start: 'failStart',
suspend: 'failSuspend',
resume: 'failResume',
discardSuspend: 'failDiscardSuspend',
focus: 'failFocus',
fullscreen: 'failFullscreen',
screenshot: 'failScreenshot',
stop: 'failStop',
forceStop: 'failStop',
@@ -71,7 +79,7 @@ export const App: React.FC = () => {
const stateReady = !!state
useEffect(() => {
if (!stateReady) return
const check = () => { api.CheckAppUpdate(false).then(setAppUpdate).catch(() => {}) }
const check = () => { api.CheckAppUpdate(false).then(setAppUpdate).catch((e) => console.warn('[app] CheckAppUpdate failed:', e)) }
check()
const id = window.setInterval(check, 6 * 60 * 60 * 1000)
return () => window.clearInterval(id)
@@ -81,20 +89,25 @@ export const App: React.FC = () => {
const [showWizard, setShowWizard] = useState(false)
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
const [showSettings, setShowSettings] = useState(false)
const [affinityTarget, setAffinityTarget] = useState<string | null>(null)
const [affinityTarget, setAffinityTarget] = useState<{ name: string; driverID: string } | null>(null)
const [affinityVersion, setAffinityVersion] = useState(0)
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
const [cloneSource, setCloneSource] = useState<string | null>(null)
const [discardSuspendTarget, setDiscardSuspendTarget] = useState<string | null>(null)
const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null)
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
const [busy, setBusy] = useState<Record<string, VMAction>>({})
const busyOpsRef = useRef<Map<string, Map<number, VMAction>>>(new Map())
const nextBusyTokenRef = useRef(0)
const [dropping, setDropping] = useState(false)
const [loadError, setLoadError] = useState('')
const [themeMode, setThemeModeState] = useState<ThemeMode>(() => {
try {
const saved = localStorage.getItem('reims-go-theme')
if (saved === 'dark' || saved === 'light') return saved
} catch {}
} catch (e) {
console.warn('[app] read theme preference failed:', e)
}
return 'system'
})
const [sysDark, setSysDark] = useState<boolean>(() =>
@@ -151,7 +164,9 @@ export const App: React.FC = () => {
try {
if (mode === 'system') localStorage.removeItem('reims-go-theme')
else localStorage.setItem('reims-go-theme', mode)
} catch {}
} catch (e) {
console.warn('[app] persist theme preference failed:', e)
}
}
const toggleTheme = () => {
@@ -164,7 +179,7 @@ export const App: React.FC = () => {
try { return localStorage.getItem('reims-go-sidebar') !== 'hidden' } catch { return true }
})
const toggleSidebar = () => setSidebarOpen((open) => {
try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch {}
try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch (e) { console.warn('[app] persist sidebar state failed:', e) }
return !open
})
@@ -190,8 +205,8 @@ export const App: React.FC = () => {
setLoadError('')
setSelected((cur) => {
if (PAGE_IDS.includes(cur)) return cur
if ((s.vms ?? []).some((v) => v.name === cur)) return cur
return s.vms && s.vms.length > 0 ? s.vms[0].name : HOST_ID
if ((s.vms ?? []).some((v) => vmRefKey(v) === cur || v.name === cur)) return cur
return s.vms && s.vms.length > 0 ? vmRefKey(s.vms[0]) : HOST_ID
})
if (reloadDetail) setDetailRevision((revision) => revision + 1)
} catch (e) {
@@ -215,6 +230,7 @@ export const App: React.FC = () => {
const offPing = events.onUIPing(() => { events.emitUIPong() })
const offState = events.onStateChanged(() => {
refresh(true)
refreshSubscribedVMStats()
setThemeRevision((r) => r + 1)
})
// Logs never pop the panel open (docs/design-guidelines.md §7.3); errors only bump a badge.
@@ -226,11 +242,11 @@ export const App: React.FC = () => {
}
setLogLines((prev) => appendLog(prev, entry))
})
api.GetActiveTheme().then(setActiveThemePayload).catch(() => {})
api.GetActiveTheme().then(setActiveThemePayload).catch((e) => console.warn('[app] GetActiveTheme failed:', e))
// Tasks: seed from the backend, then follow events.
api.GetTasks().then((list) => {
setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev))
}).catch(() => {})
}).catch((e) => console.warn('[app] GetTasks failed:', e))
const offTask = events.onTask((task) => onTaskRef.current(task))
const onVisibility = () => {
if (!document.hidden) {
@@ -259,15 +275,15 @@ export const App: React.FC = () => {
}, [refresh])
const vms = state?.vms ?? []
const runningVMCount = vms.filter((v) => (state?.transitions[v.name] ?? v.state) === 'running').length
const runningVMCount = vms.filter((v) => (state?.transitions[vmRefKey(v)] ?? v.state) === 'running').length
const selectedVM = !PAGE_IDS.includes(selected)
? vms.find((v) => v.name === selected)
? vms.find((v) => vmRefKey(v) === selected) ?? vms.find((v) => v.name === selected)
: undefined
useEffect(() => {
if (!selectedVM) { setDetail(null); return }
api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
}, [selectedVM?.name, selectedVM?.state, state?.transitions[selectedVM?.name ?? ''], detailRevision])
}, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, state?.transitions[selectedVM ? vmRefKey(selectedVM) : ''], detailRevision])
// Display names (the VM's note, .reims-go-note): shown in place of the VM's
// name in the sidebar and page title; the name itself stays the identifier.
@@ -278,7 +294,7 @@ export const App: React.FC = () => {
for (const vm of vms) {
api.GetVMNote(vm.name)
.then((n) => { if (live) setDisplayNames((m) => ({ ...m, [vm.name]: (n ?? '').trim() })) })
.catch(() => {})
.catch((e) => console.warn('[app] GetVMNote failed:', vm.name, e))
}
return () => { live = false }
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -292,7 +308,7 @@ export const App: React.FC = () => {
for (const vm of vms) {
api.GetVMMacOS(vm.name)
.then((r) => { if (live) setReleases((m) => ({ ...m, [vm.name]: (r ?? '').trim() })) })
.catch(() => {})
.catch((e) => console.warn('[app] GetVMMacOS failed:', vm.name, e))
}
return () => { live = false }
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -324,9 +340,10 @@ export const App: React.FC = () => {
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] ?? []) : []
const effectiveState = selectedVM ? (state?.transitions[vmRefKey(selectedVM)] ?? selectedVM.state) : ''
const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : []
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
const canSuspend = state?.can_suspend ?? false
onTaskRef.current = (task: Task) => {
if (task.kind === 'app-update' && task.status === 'failed' && !notifiedTasks.current.has(task.id)) {
@@ -370,7 +387,7 @@ export const App: React.FC = () => {
const setAppUpdateChannel = async (ch: 'stable' | 'alpha' | 'dev') => {
await api.SetAppUpdateChannel(ch)
setDismissedUpdate('')
try { localStorage.removeItem('reims-go-update-dismissed') } catch {}
try { localStorage.removeItem('reims-go-update-dismissed') } catch (e) { console.warn('[app] clear dismissed update failed:', e) }
await refresh()
try {
setAppUpdate(await api.CheckAppUpdate(true))
@@ -399,7 +416,7 @@ export const App: React.FC = () => {
const dismissUpdate = () => {
if (!appUpdate) return
setDismissedUpdate(appUpdate.latest)
try { localStorage.setItem('reims-go-update-dismissed', appUpdate.latest) } catch {}
try { localStorage.setItem('reims-go-update-dismissed', appUpdate.latest) } catch (e) { console.warn('[app] persist dismissed update failed:', e) }
}
const [confirmUpdate, setConfirmUpdate] = useState(false)
const [installingUpdate, setInstallingUpdate] = useState(false)
@@ -424,7 +441,9 @@ export const App: React.FC = () => {
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 {}
} catch (e) {
console.warn('[app] track last app version failed:', e)
}
}, [state?.app_version, pluginUI !== null])
const importRuntime = async () => {
try {
@@ -442,6 +461,9 @@ export const App: React.FC = () => {
setSetupStage(s?.active_runtime ? null : 'runtime')
}
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
// The data folder opened read-only (internal/dataroot): nothing in it may be
// changed, so the workspace gives way to a screen that explains why.
const showReadOnly = !!state && !showSetup && !!state.data_root_status?.read_only
// UI Contract v1 read-only document state attributes (§5.1).
const currentView = showSetup ? 'setup' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : selected === ABOUT_ID ? 'about' : 'vm'
@@ -459,7 +481,7 @@ export const App: React.FC = () => {
hasError: hasAnyError,
sidebarCollapsed: !sidebarOpen,
safeMode: !!state?.safe_mode,
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[v.name] ?? v.state })),
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[vmRefKey(v)] ?? v.state })),
})
uiStateRef.current = {
appearance: theme,
@@ -473,7 +495,7 @@ export const App: React.FC = () => {
hasError: hasAnyError,
sidebarCollapsed: !sidebarOpen,
safeMode: !!state?.safe_mode,
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[v.name] ?? v.state })),
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[vmRefKey(v)] ?? v.state })),
}
useEffect(() => {
const el = document.documentElement
@@ -486,10 +508,46 @@ export const App: React.FC = () => {
notifyInteractiveThemeState(uiStateRef.current)
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme])
// UI SDK event stream (ui-contract UI_CONTRACT_SDK_EVENTS). emitThemeEvent is
// a no-op unless an interactive theme is loaded; payloads carry no paths.
const selectedRef = selectedVM ? vmRefKey(selectedVM) : ''
useEffect(() => {
emitThemeEvent('view.changed', { view: currentView, vm: selectedRef })
}, [currentView, selectedRef])
const vmStatesRef = useRef<Record<string, string> | null>(null)
useEffect(() => {
const next: Record<string, string> = {}
for (const v of vms) next[vmRefKey(v)] = state?.transitions[vmRefKey(v)] ?? v.state
const prev = vmStatesRef.current
vmStatesRef.current = next
if (!prev) return
for (const v of vms) {
const key = vmRefKey(v)
if (prev[key] !== undefined && prev[key] !== next[key]) {
emitThemeEvent('vm.stateChanged', { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] })
}
}
}, [vms, state?.transitions])
const taskStatesRef = useRef<Record<string, { status: string; percent: number }> | null>(null)
useEffect(() => {
const prev = taskStatesRef.current
const next: Record<string, { status: string; percent: number }> = {}
for (const t of Object.values(taskMap)) next[t.id] = { status: t.status, percent: t.percent }
taskStatesRef.current = next
if (!prev) return
for (const t of Object.values(taskMap)) {
const was = prev[t.id]
const info = { id: t.id, kind: t.kind, vm: t.vm ?? '', percent: t.percent }
if (!was && t.status === 'running') emitThemeEvent('task.started', info)
else if (was?.status === 'running' && t.status === 'running' && was.percent !== t.percent) emitThemeEvent('task.progress', info)
if ((!was || was.status === 'running') && t.status !== 'running') emitThemeEvent('task.finished', { ...info, status: t.status })
}
}, [taskMap])
// Apply active theme pack (zero extra CSS for builtin default theme, §5.1 & §8.1).
useEffect(() => {
api.GetActiveTheme().then(setActiveThemePayload).catch(() => {})
api.GetPluginUIContributions().then(setPluginUI).catch(() => {})
api.GetActiveTheme().then(setActiveThemePayload).catch((e) => console.warn('[app] GetActiveTheme failed:', e))
api.GetPluginUIContributions().then(setPluginUI).catch((e) => console.warn('[app] GetPluginUIContributions failed:', e))
}, [themeRevision, state?.safe_mode])
useEffect(() => {
@@ -500,7 +558,7 @@ export const App: React.FC = () => {
{
toggleSidebar,
openSettings: () => setSelected(SETTINGS_ID),
focusVMWindow: (vmName) => { void api.FocusVMWindow(vmName).catch(() => {}) },
focusVMWindow: (vmName) => { void api.FocusVMWindow(vmName).catch((e) => console.warn('[theme] FocusVMWindow failed:', vmName, e)) },
},
)
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -520,7 +578,8 @@ export const App: React.FC = () => {
const loadVMLog = async (serial: boolean, name = selectedVM?.name) => {
if (!name) return
try {
const text = await api.ReadVMLogs(name, serial)
const logDriverID = vms.find((v) => v.name === name)?.driver_id ?? ''
const text = await api.ReadVMLogsWithDriver(logDriverID, name, serial)
if (serial) setSerialLog(text)
else setQemuLog(text)
} catch (e) {
@@ -546,8 +605,50 @@ export const App: React.FC = () => {
})
}
const activeVMBusy = (name: string): VMAction | undefined => {
const ops = busyOpsRef.current.get(name)
if (!ops || ops.size === 0) return undefined
let latest: VMAction | undefined
for (const act of ops.values()) latest = act
return latest
}
const syncBusyState = () => {
const next: Record<string, VMAction> = Object.create(null)
for (const [vmName, ops] of busyOpsRef.current) {
let latest: VMAction | undefined
for (const act of ops.values()) latest = act
if (latest) next[vmName] = latest
}
setBusy(next)
}
const beginVMBusy = (name: string, action: VMAction): number | null => {
const ops = busyOpsRef.current.get(name)
if (ops && ops.size > 0) {
if (action !== 'forceStop') return null
for (const act of ops.values()) {
if (act === 'forceStop') return null
}
}
const token = ++nextBusyTokenRef.current
const vmOps = ops ?? new Map<number, VMAction>()
vmOps.set(token, action)
busyOpsRef.current.set(name, vmOps)
syncBusyState()
return token
}
const endVMBusy = (name: string, token: number) => {
const ops = busyOpsRef.current.get(name)
if (!ops || !ops.delete(token)) return
if (ops.size === 0) busyOpsRef.current.delete(name)
syncBusyState()
}
const runVMAction = async (name: string, action: VMAction, fn: () => Promise<void>, okTitle?: string) => {
setBusy((b) => ({ ...b, [name]: action }))
const token = beginVMBusy(name, action)
if (token === null) return
try {
await fn()
if (okTitle) toasts.push({ kind: 'ok', title: okTitle })
@@ -555,17 +656,15 @@ export const App: React.FC = () => {
} catch (e) {
fail(tr(failKey[action]), e)
} finally {
setBusy((b) => {
const { [name]: _, ...rest } = b
return rest
})
endVMBusy(name, token)
}
}
// Paste as keystrokes: the backend refuses text a US keyboard can't type
// (ErrNotTypeable in type_flow.go), which gets a message of its own.
const typeInto = async (name: string, fn: () => Promise<number>) => {
setBusy((b) => ({ ...b, [name]: 'type' }))
const token = beginVMBusy(name, 'type')
if (token === null) return
try {
const n = await fn()
toasts.push({ kind: 'ok', title: tr('toastTyped', { n }) })
@@ -576,10 +675,7 @@ export const App: React.FC = () => {
fail(tr('failType'), e)
}
} finally {
setBusy((b) => {
const { [name]: _, ...rest } = b
return rest
})
endVMBusy(name, token)
}
}
@@ -597,7 +693,8 @@ export const App: React.FC = () => {
return
}
}
setBusy((b) => ({ ...b, [name]: 'attachInstaller' }))
const token = beginVMBusy(name, 'attachInstaller')
if (token === null) return
try {
const fileName = await api.AttachInstaller(name, picked)
toasts.push({
@@ -606,10 +703,7 @@ export const App: React.FC = () => {
})
await refresh()
} finally {
setBusy((b) => {
const { [name]: _, ...rest } = b
return rest
})
endVMBusy(name, token)
}
} catch (e) {
fail(tr('failAttachInstaller'), e)
@@ -617,14 +711,35 @@ export const App: React.FC = () => {
}
const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => {
const actionVM = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
const actionDriverID = actionVM?.driver_id ?? ''
name = actionVM?.name ?? name
if (!canSuspend && (action === 'suspend' || action === 'resume')) return
const activeBusy = activeVMBusy(name)
if (
activeBusy
&& action !== 'openFolder'
&& action !== 'openSharedFolder'
&& (action !== 'forceStop' || activeBusy === 'forceStop')
) {
return
}
switch (action) {
case 'start': return runVMAction(name, action, () => api.StartVM(name))
case 'focus': return api.FocusVMWindow(name).catch((e) => fail(tr('failFocus'), e))
case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshot(name), tr('toastScreenshotCopied'))
case 'stop': return runVMAction(name, action, () => api.StopVM(name, false), tr('toastStopped', { name }))
case 'forceStop': return runVMAction(name, action, () => api.StopVM(name, true), tr('toastStopped', { name }))
case 'restart': return runVMAction(name, action, () => api.RestartVM(name))
case 'eject': return runVMAction(name, action, () => api.EjectInstaller(name), tr('toastEjected'))
case 'start': return runVMAction(name, action, () => api.StartVMWithDriver(actionDriverID, name))
case 'suspend': return runVMAction(name, action, () => api.SuspendVMWithDriver(actionDriverID, name), tr('toastSuspended', { name }))
case 'resume': return runVMAction(name, action, () => api.ResumeVMWithDriver(actionDriverID, name), tr('toastResumed', { name }))
case 'discardSuspend': return setDiscardSuspendTarget(actionVM ? vmRefKey(actionVM) : name)
case 'focus': return api.FocusVMWindowWithDriver(actionDriverID, name).catch((e) => fail(tr('failFocus'), e))
case 'fullscreen':
return runVMAction(name, action, async () => {
const isFullscreen = await api.ToggleVMFullscreenWithDriver(actionDriverID, name)
refreshVMStatsWithDriver(actionDriverID, name, { window_fullscreen: isFullscreen })
})
case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshotWithDriver(actionDriverID, name), tr('toastScreenshotCopied'))
case 'stop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, false), tr('toastStopped', { name }))
case 'forceStop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, true), tr('toastStopped', { name }))
case 'restart': return runVMAction(name, action, () => api.RestartVMWithDriver(actionDriverID, name))
case 'eject': return runVMAction(name, action, () => api.EjectInstallerWithDriver(actionDriverID, name), tr('toastEjected'))
case 'finishInstall': return runVMAction(name, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished'))
case 'enterRecovery': return runVMAction(name, action, () => api.EnterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery'))
case 'attachInstaller': return attachInstaller(name, isRunning)
@@ -635,47 +750,62 @@ export const App: React.FC = () => {
case 'upgradeNVMe':
return runVMAction(name, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady'))
case 'exportDiagnostics':
return runVMAction(name, action, async () => { await api.ExportDiagnostics(name) }, tr('toastDiagExported'))
return runVMAction(name, action, async () => { await api.ExportDiagnosticsWithDriver(actionDriverID, name) }, tr('toastDiagExported'))
case 'cloneVM':
return setCloneSource(name)
return setCloneSource({ name, driverID: actionDriverID })
case 'type': return typeInto(name, () => api.TypeClipboard(name))
case 'sendText': return setSendTextTarget(name)
case 'openFolder':
return api.OpenVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
case 'delete': return setDeleteTarget(name)
case 'delete': return setDeleteTarget(actionVM ? vmRefKey(actionVM) : name)
}
}
const onVMAction = (action: VMAction) => {
if (!selectedVM) return
return onVMActionFor(selectedVM.name, action, selectedVM.state === 'running')
return onVMActionFor(vmRefKey(selectedVM), action, selectedVM.state === 'running')
}
const onSidebarContextAction = (name: string, action: VMAction | 'settings') => {
const vm = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
const st = state?.transitions[vm ? vmRefKey(vm) : name] ?? vm?.state ?? 'stopped'
if (action === 'settings') {
if (st === 'suspended' || st === 'suspending' || st === 'resuming') return
setSelected(name)
api.GetVMDetail(name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
api.GetVMDetail(vm?.name ?? name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
return
}
const vm = vms.find((v) => v.name === name)
const st = state?.transitions[name] ?? vm?.state ?? 'stopped'
onVMActionFor(name, action, st === 'running')
}
// The state's own main action (Start, or Show Window while running), shared by
// The state's own main action (Start, Resume while suspended, or Show Window while running), shared by
// Ctrl+Enter and a double-click in the sidebar.
const primaryAction = (name: string) => {
const vm = vms.find((v) => v.name === name)
if (!vm || busy[name]) return
const st = state?.transitions[name] ?? vm.state
if (st === 'stopped') onVMActionFor(name, 'start', false)
else if (st === 'running') onVMActionFor(name, 'focus', true)
const vm = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
if (!vm || activeVMBusy(vm.name)) return
const key = vmRefKey(vm)
const st = state?.transitions[key] ?? vm.state
if (st === 'stopped') onVMActionFor(key, 'start', false)
else if (st === 'suspended') onVMActionFor(key, 'resume', false)
else if (st === 'running') onVMActionFor(key, 'focus', true)
}
const confirmDelete = (keepFiles: boolean) => {
const name = deleteTarget
const target = deleteTarget
setDeleteTarget(null)
if (name) runVMAction(name, 'delete', () => api.DeleteVM(name, keepFiles), tr('toastDeleted', { name }))
const targetVM = vms.find((v) => vmRefKey(v) === target) ?? vms.find((v) => v.name === target)
const name = targetVM?.name ?? target
const driverID = targetVM?.driver_id ?? ''
if (name) runVMAction(name, 'delete', () => api.DeleteVMWithDriver(driverID, name, keepFiles), tr('toastDeleted', { name }))
}
const confirmDiscardSuspend = () => {
const target = discardSuspendTarget
setDiscardSuspendTarget(null)
const targetVM = vms.find((v) => vmRefKey(v) === target) ?? vms.find((v) => v.name === target)
const name = targetVM?.name ?? target
const driverID = targetVM?.driver_id ?? ''
if (name) runVMAction(name, 'discardSuspend', () => api.DiscardSuspendWithDriver(driverID, name), tr('toastDiscardSuspend', { name }))
}
const confirmOnlineRecovery = () => {
@@ -691,9 +821,9 @@ export const App: React.FC = () => {
const src = cloneSource
setCloneSource(null)
if (!src) return
runVMAction(src, 'cloneVM', async () => {
await api.CloneVMCoW(src, cloneName)
setSelected(cloneName)
runVMAction(src.name, 'cloneVM', async () => {
await api.CloneVMCoWWithDriver(src.driverID, src.name, cloneName)
setSelected(vmRefKey({ name: cloneName, driver_id: src.driverID }))
}, tr('toastCloned', { name: cloneName }))
}
@@ -804,16 +934,18 @@ export const App: React.FC = () => {
// Global shortcuts (docs/design-guidelines.md §6). Dialogs own the keyboard while open.
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
const appDialogOpen = showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget ||
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate
shortcutRef.current = (e: KeyboardEvent) => {
if (!e.ctrlKey || e.altKey || e.metaKey) return
if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return
if (appDialogOpen) 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) }
else if (k === ',' && detail && effectiveState !== 'suspended' && effectiveState !== 'suspending' && effectiveState !== 'resuming') { e.preventDefault(); setShowSettings(true) }
else if (k === 'l') { e.preventDefault(); toggleLogs() }
else if (k === 'b' && !showSetup) { e.preventDefault(); toggleSidebar() }
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(selectedVM.name) }
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(vmRefKey(selectedVM)) }
}
useEffect(() => {
const h = (e: KeyboardEvent) => shortcutRef.current(e)
@@ -828,7 +960,11 @@ export const App: React.FC = () => {
useEffect(() => {
const offSelect = events.onTraySelectVM((name) => { setSelected(name) })
const offNew = events.onTrayNewVM(() => { openWizardRef.current() })
return () => { offSelect(); offNew() }
const offDiscard = events.onTrayDiscardSuspend((name) => {
setSelected(name)
setDiscardSuspendTarget(name)
})
return () => { offSelect(); offNew(); offDiscard() }
}, [])
// Native Wails file drag-and-drop delivery into the selected VM's shared folder.
@@ -873,12 +1009,14 @@ export const App: React.FC = () => {
}, [])
return (
<ThemeVisualsProvider payload={activeThemePayload}>
<TooltipProvider>
<div className="app-shell rg-p-shell">
<div className="rg-layer rg-layer-background" data-rg-layer="layer.background" aria-hidden="true" />
<header className="titlebar rg-p-titlebar" onDoubleClick={() => WindowToggleMaximise()}>
{showSetup || !state ? (
{showSetup || showReadOnly || !state ? (
<div className="brand rg-p-brand">
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
<BrandMark className="brand-mark" />
Reims-Go
</div>
) : (
@@ -892,16 +1030,24 @@ export const App: React.FC = () => {
canLight={canLight}
canDark={canDark}
onThemeMode={setThemeMode}
vm={selectedVM ? { name: selectedVM.name, state: effectiveState, busy: !!busy[selectedVM.name] } : null}
vm={selectedVM ? {
name: selectedVM.name,
driver_id: selectedVM.driver_id,
state: effectiveState,
busy: Object.prototype.hasOwnProperty.call(busy, selectedVM.name),
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
canSuspend,
} : null}
onNewVM={openWizard}
onVMAction={onVMAction}
onVMSettings={() => { if (detail) setShowSettings(true) }}
onVMSettings={() => { if (detail && effectiveState !== 'suspended') setShowSettings(true) }}
onVMDelete={() => { if (selectedVM) setDeleteTarget(selectedVM.name) }}
onNavigate={setSelected}
onOpenURL={(url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) }}
appVersion={state.app_version}
/>
)}
<div className="rg-slot-anchor titlebar-center" data-rg-slot="titlebar.center" />
<div className="titlebar-right" onDoubleClick={(e) => e.stopPropagation()}>
{canLight && canDark && (
<Tip label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}>
@@ -941,6 +1087,7 @@ export const App: React.FC = () => {
stage={state.needs_setup ? 'folder' : 'runtime'}
runtimeTask={runtimeTask}
onLocale={setLang}
onPluginsChanged={() => setThemeRevision((r) => r + 1)}
onFolderDone={folderDone}
onFinish={() => setSetupStage(null)}
onError={fail}
@@ -950,6 +1097,14 @@ export const App: React.FC = () => {
onImportRuntime={importRuntime}
/>
</Suspense>
) : showReadOnly && state ? (
<DataRootReadOnly
locale={locale}
status={state.data_root_status}
message={state.data_root_message ?? ''}
onChanged={() => { void refresh() }}
onError={fail}
/>
) : (
<div className={`workspace rg-p-workspace${sidebarOpen ? '' : ' sidebar-hidden'}`}>
{sidebarOpen && <div className="sidebar-backdrop" aria-hidden="true" onClick={toggleSidebar} />}
@@ -957,9 +1112,16 @@ export const App: React.FC = () => {
locale={locale}
vms={vms}
transitions={state?.transitions ?? {}}
busyActions={busy}
selected={selected}
hostReady={hostReady}
onSelect={setSelected}
canSuspend={canSuspend}
onSelect={(id) => {
setSelected(id)
if (sidebarOpen && window.matchMedia('(max-width: 768px)').matches) {
toggleSidebar()
}
}}
displayNames={displayNames}
macosMajors={macosMajors}
onActivate={primaryAction}
@@ -985,19 +1147,34 @@ export const App: React.FC = () => {
<main className="main rg-p-main">
<div className="scroll">
{state?.vm_list_error && <div className="notice notice-error" role="alert">{state.vm_list_error}</div>}
<Suspense fallback={null}>
{!state ? (
<div className="page">
{loadError ? <div className="notice notice-error">{loadError}</div> : <span className="muted">…</span>}
</div>
) : selected === INSTALLERS_ID ? (
<InstallersPage
<ImagesPage
locale={locale}
host={state.host}
tasks={Object.values(taskMap)}
onCreateWithInstaller={openWizardWithInstaller}
onError={fail}
onToast={(title) => toasts.push({ kind: 'ok', title })}
appearance={theme}
pluginUI={pluginUI}
onOpenPlugins={() => setSelected(PLUGINS_ID)}
renderNativeSource={(nativeId, opts) => (
nativeId === 'macos' ? (
<Suspense fallback={null}>
<InstallersPage
locale={locale}
host={state.host}
tasks={Object.values(taskMap)}
refreshSignal={opts.refreshSignal}
onBusyChange={opts.onBusyChange}
onCreateWithInstaller={openWizardWithInstaller}
onError={fail}
onToast={(title) => toasts.push({ kind: 'ok', title })}
/>
</Suspense>
) : null
)}
/>
) : selected === PLUGINS_ID ? (
<PluginsPage
@@ -1007,24 +1184,27 @@ export const App: React.FC = () => {
onRefresh={refresh}
onError={fail}
onThemeChanged={() => setThemeRevision((r) => r + 1)}
onLocaleSwitch={(l) => void setLang(l)}
/>
) : selectedVM ? (
<VMPage
locale={locale}
name={selectedVM.name}
driverID={selectedVM.driver_id ?? ''}
displayName={displayNames[selectedVM.name] ?? ''}
onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))}
macosMajor={macosMajors[selectedVM.name] ?? null}
state={effectiveState}
canSuspend={canSuspend}
guideActive={state.active_guides?.includes(selectedVM.name) ?? false}
installGuideEnabled={!!state.install_guide_enabled}
detail={detail}
host={state.host}
pending={pending}
busyAction={busy[selectedVM.name]}
busyAction={Object.prototype.hasOwnProperty.call(busy, selectedVM.name) ? busy[selectedVM.name] : undefined}
onAction={onVMAction}
onSettings={() => setShowSettings(true)}
onOpenAffinity={() => setAffinityTarget(selectedVM.name)}
onOpenAffinity={() => setAffinityTarget({ name: selectedVM.name, driverID: selectedVM.driver_id ?? '' })}
onDelete={() => setDeleteTarget(selectedVM.name)}
onViewLogs={() => { openLogs('serial'); loadSerial() }}
onCopy={copy}
@@ -1151,13 +1331,14 @@ export const App: React.FC = () => {
<SettingsModal
locale={locale}
detail={detail}
stats={latestVMStats(detail.name)}
driverID={selectedVM?.driver_id ?? ''}
stats={latestVMStatsWithDriver(selectedVM?.driver_id ?? '', detail.name)}
host={state.host}
optimizations={state.optimizations}
running={effectiveState === 'running'}
onCopy={copy}
onDiskChanged={refresh}
onOpenAffinity={() => setAffinityTarget(detail.name)}
onOpenAffinity={() => setAffinityTarget({ name: detail.name, driverID: selectedVM?.driver_id ?? '' })}
affinityVersion={affinityVersion}
onHostChanged={refresh}
onClose={() => setShowSettings(false)}
@@ -1174,8 +1355,9 @@ export const App: React.FC = () => {
<Suspense fallback={null}>
<AffinityDialog
locale={locale}
vmName={affinityTarget}
vcpus={detail?.name === affinityTarget ? detail.cpus : 4}
vmName={affinityTarget.name}
driverID={affinityTarget.driverID}
vcpus={detail?.name === affinityTarget.name ? detail.cpus : 4}
host={state.host}
globalAutoPin={state.config.auto_pin_pcores}
onClose={() => setAffinityTarget(null)}
@@ -1220,11 +1402,26 @@ export const App: React.FC = () => {
<DeleteDialog locale={locale} name={deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
)}
{discardSuspendTarget && (() => {
const targetVM = vms.find((v) => vmRefKey(v) === discardSuspendTarget) ?? vms.find((v) => v.name === discardSuspendTarget)
const targetName = targetVM?.name ?? discardSuspendTarget
return (
<ConfirmDialog
title={tr('discardSuspendTitle', { name: displayNames[targetName] || targetName })}
description={tr('discardSuspendDesc')}
cancelLabel={tr('cancel')}
confirmLabel={tr('discardSuspendConfirm')}
onCancel={() => setDiscardSuspendTarget(null)}
onConfirm={confirmDiscardSuspend}
/>
)
})()}
{cloneSource && (
<CloneDialog
locale={locale}
sourceName={cloneSource}
defaultCloneName={`${cloneSource}-clone`}
sourceName={cloneSource.name}
defaultCloneName={`${cloneSource.name}-clone`}
onCancel={() => setCloneSource(null)}
onConfirm={confirmClone}
/>
@@ -1243,7 +1440,7 @@ export const App: React.FC = () => {
<SendTextDialog
locale={locale}
vmName={sendTextTarget}
guestToolsConnected={Boolean(latestVMStats(sendTextTarget)?.guest_tools_connected ?? detail?.guest_tools_connected)}
guestToolsConnected={Boolean(latestVMStatsWithDriver(selectedVM?.driver_id ?? '', sendTextTarget)?.guest_tools_connected ?? detail?.guest_tools_connected)}
onCancel={() => setSendTextTarget(null)}
onConfirm={(text) => {
const target = sendTextTarget
@@ -1253,8 +1450,12 @@ export const App: React.FC = () => {
/>
)}
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} dir={dir} />
<div className="rg-layer rg-layer-overlay" data-rg-layer="layer.overlay" aria-hidden="true" />
</div>
{/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */}
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} dir={dir} />
<ThemeDecorations payload={activeThemePayload} snap={uiStateRef.current} locale={locale} />
</TooltipProvider>
</ThemeVisualsProvider>
)
}
+69 -17
View File
@@ -1,5 +1,5 @@
import { Copy, Download, ExternalLink, RotateCw, Scale } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import React, { useEffect, useRef, useState } from 'react'
import '../i18n/domains/settings.gen'
import { I18nKey, t } from '../i18n'
import { taskDetail } from '../lib/tasks'
@@ -10,7 +10,9 @@ import { Segmented } from '../ui/settings'
import { api } from '../wails'
import { REPO_URL } from './TitleMenus'
import type { UpdatePhase } from './UpdateCapsule'
import { BrandMark } from '../ui/themeVisuals'
const DISCORD_INVITE_URL = 'https://discord.gg/Tj682rW5rS'
const QQ_GROUP_ID = '1136042744'
export type AppUpdateChannel = 'stable' | 'alpha' | 'dev'
@@ -34,7 +36,7 @@ interface Props {
onError: (title: string, e: unknown) => void
}
/** About page: version and updates, project links and the community group. */
/** About page: version and updates, project links and community channels. */
export const AboutPage: React.FC<Props> = ({
locale, appVersion, appUpdateChannel, onAppUpdateChannel, appUpdate, onAppUpdate, updatePhase, updateTask, installing,
onDownloadUpdate, onCancelUpdate, onInstallUpdate, onCopy, onError,
@@ -49,14 +51,34 @@ export const AboutPage: React.FC<Props> = ({
const [licenseOpen, setLicenseOpen] = useState(false)
const [licenseTab, setLicenseTab] = useState<'notice' | 'license'>('notice')
const [licenses, setLicenses] = useState<{ license: string; notice: string } | null>(null)
const mountedRef = useRef(true)
const loadingLicensesRef = useRef(false)
const licensePreRef = useRef<HTMLPreElement>(null)
const openLicenses = () => {
setLicenseOpen(true)
if (!licenses) {
api.GetLicenseTexts()
.then((res) => setLicenses({ license: res?.license ?? '', notice: res?.notice ?? '' }))
.catch((e) => onError(tr('failGeneric'), e))
const openLicenses = async () => {
if (licenses) {
setLicenseOpen(true)
return
}
if (loadingLicensesRef.current) return
loadingLicensesRef.current = true
try {
// Load embedded license text before mounting the modal so the dialog opens
// with its final content on frame 1 instead of reflowing mid-animation.
const res = await api.GetLicenseTexts()
if (!mountedRef.current) return
setLicenses({ license: res?.license ?? '', notice: res?.notice ?? '' })
setLicenseOpen(true)
} catch (e) {
if (mountedRef.current) onError(tr('failGeneric'), e)
} finally {
loadingLicensesRef.current = false
}
}
const handleLicenseTabChange = (next: 'notice' | 'license') => {
setLicenseTab(next)
if (licensePreRef.current) licensePreRef.current.scrollTop = 0
}
const runUpdateCheck = async (force: boolean) => {
@@ -72,12 +94,16 @@ export const AboutPage: React.FC<Props> = ({
}
useEffect(() => {
mountedRef.current = true
if (!appUpdate) void runUpdateCheck(false)
let cancelled = false
api.CanOpenQQGroup()
.then((ok) => { if (!cancelled) setQQInstalled(!!ok) })
.catch(() => { if (!cancelled) setQQInstalled(false) })
return () => { cancelled = true }
return () => {
mountedRef.current = false
cancelled = true
}
}, [])
const openURL = (url: string) => {
@@ -127,7 +153,7 @@ export const AboutPage: React.FC<Props> = ({
updateSub = (
<>
<div className="row-sub">{tr('updateDownloadingSub', { v: appUpdate?.latest ?? '' })}{updateTask && taskDetail(updateTask) ? ` · ${taskDetail(updateTask)}` : ''}</div>
<span className="progress about-update-progress" aria-hidden="true">
<span className="progress rg-p-progress about-update-progress" aria-hidden="true">
<span className="progress-fill" style={{ transform: `scaleX(${(pct ?? 0) / 100})` }} />
</span>
</>
@@ -158,7 +184,7 @@ export const AboutPage: React.FC<Props> = ({
return (
<div className="page about-page">
<header className="about-hero">
<img className="about-hero-mark" src="/logo.svg" alt="" aria-hidden="true" />
<BrandMark className="about-hero-mark" />
<div className="about-hero-text">
<h1>Reims-Go</h1>
<p>{tr('aboutTagline')}</p>
@@ -172,7 +198,7 @@ export const AboutPage: React.FC<Props> = ({
<div className="row-title">
{tr('appVersionTitle')} <span className="mono">{version}</span>
{appUpdate && !appUpdate.has_update && (
<span className="badge badge-ok">{tr('appUpToDate')}</span>
<span className="badge rg-p-badge badge-ok">{tr('appUpToDate')}</span>
)}
</div>
{updateSub}
@@ -244,7 +270,7 @@ export const AboutPage: React.FC<Props> = ({
<div className="row-sub">{tr('aboutLicensesSub')}</div>
</div>
<div className="row-right">
<Button icon={<Scale size={14} aria-hidden="true" />} onClick={openLicenses}>
<Button icon={<Scale size={14} aria-hidden="true" />} onClick={() => void openLicenses()}>
{tr('aboutLicensesView')}
</Button>
<Button variant="ghost" icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(`${REPO_URL}/blob/main/NOTICE.md`)}>
@@ -252,12 +278,31 @@ export const AboutPage: React.FC<Props> = ({
</Button>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('aboutDiscord')}</div>
<div className="row-sub">{tr('aboutDiscordSub')}</div>
</div>
<div className="row-right">
{onCopy && (
<IconButton
small
label={tr('aboutCopyDiscord')}
icon={<Copy size={14} aria-hidden="true" />}
onClick={() => onCopy(DISCORD_INVITE_URL)}
/>
)}
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(DISCORD_INVITE_URL)}>
{tr('aboutJoinDiscord')}
</Button>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">
{tr('aboutQQGroup')} <span className="mono">{QQ_GROUP_ID}</span>
{qqInstalled === false && (
<span className="badge">{tr('aboutQQNotInstalled')}</span>
<span className="badge rg-p-badge">{tr('aboutQQNotInstalled')}</span>
)}
</div>
{qqInstalled === false ? (
@@ -303,16 +348,23 @@ export const AboutPage: React.FC<Props> = ({
<Segmented
label={tr('aboutLicensesTitle')}
value={licenseTab}
onChange={setLicenseTab}
onChange={handleLicenseTabChange}
options={[
{ value: 'notice', label: tr('aboutLicensesTabNotice') },
{ value: 'license', label: tr('aboutLicensesTabLicense') },
]}
/>
<pre className="license-pre">
<pre
ref={licensePreRef}
className="license-pre"
dir="ltr"
tabIndex={0}
role="region"
aria-label={licenseTab === 'notice' ? tr('aboutLicensesTabNotice') : tr('aboutLicensesTabLicense')}
>
{licenses
? (licenseTab === 'notice' ? licenses.notice : licenses.license)
: '…'}
: ''}
</pre>
</div>
<div className="dialog-foot">
+4 -3
View File
@@ -11,6 +11,7 @@ import { api } from '../wails'
interface Props {
locale: Locale
vmName: string
driverID: string
vcpus: number
host: HostReport
globalAutoPin: boolean
@@ -79,7 +80,7 @@ export function formatAffinitySummary(locale: Locale, status: VMAffinityStatus |
}
export const AffinityDialog: React.FC<Props> = ({
locale, vmName, vcpus, host, globalAutoPin, onClose, onApplied,
locale, vmName, driverID, vcpus, host, globalAutoPin, onClose, onApplied,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const topology = useMemo(() => buildTopology(host), [host])
@@ -99,7 +100,7 @@ export const AffinityDialog: React.FC<Props> = ({
let live = true
setLoading(true)
setErr('')
api.GetVMAffinity(vmName)
api.GetVMAffinityWithDriver(driverID, vmName)
.then((st) => {
if (!live) return
setStatus(st)
@@ -205,7 +206,7 @@ export const AffinityDialog: React.FC<Props> = ({
setSaving(true)
setErr('')
try {
const updated = await api.SetVMAffinity(vmName, {
const updated = await api.SetVMAffinityWithDriver(driverID, vmName, {
mode,
cpus: mode === 'custom' ? selected : [],
disable_eco_qos: disableEcoQoS,
+43 -1
View File
@@ -1,4 +1,5 @@
import React from 'react'
import { PowerOff } from 'lucide-react'
import '../i18n/domains/settings.gen'
import { getLocaleOptions, I18nKey, t } from '../i18n'
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
@@ -27,9 +28,13 @@ export const AppSettingsPage: React.FC<Props> = ({
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { host, config, optimizations } = state
const quitMode = state.quit_mode
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
const missingFontScript = state.missing_font_hint || ''
const memSpecLabel = host.memory_spec?.speed_mhz
? `${host.memory_spec.speed_mhz} MHz${host.memory_spec.type_name ? ` ${host.memory_spec.type_name}` : ''}`
: ''
const guard = (fn: () => Promise<unknown>) => async () => {
try {
@@ -45,6 +50,14 @@ export const AppSettingsPage: React.FC<Props> = ({
if (dir) await api.SetDataRoot(dir)
})
const forceQuit = async () => {
try {
await api.ForceQuitApp()
} catch (e) {
onError(tr('quitFailed'), e)
}
}
return (
<div className="page rg-p-settings">
<header className="page-head">
@@ -65,7 +78,7 @@ export const AppSettingsPage: React.FC<Props> = ({
<div className="row-main">
<div className="row-title">
{tr('autoPinPCores')}
<span className={`badge ${optBadgeClass(pcoreOpt?.status)}`}>
<span className={`badge rg-p-badge ${optBadgeClass(pcoreOpt?.status)}`}>
{optStatusLabel(locale, pcoreOpt?.status)}
</span>
</div>
@@ -84,6 +97,24 @@ export const AppSettingsPage: React.FC<Props> = ({
/>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('syncHostMemorySMBIOS')}</div>
<div className="row-sub">
{memSpecLabel
? tr('syncHostMemorySMBIOSSub', { spec: memSpecLabel })
: tr('syncHostMemorySMBIOSUnavailable')}
</div>
</div>
<div className="row-right">
<Switch
label={tr('syncHostMemorySMBIOS')}
disabled={!memSpecLabel}
checked={!!memSpecLabel && !!config.sync_host_memory_smbios}
onChange={(checked) => guard(() => api.SetSyncHostMemorySMBIOS(checked))()}
/>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('minimizeToTray')}</div>
@@ -97,6 +128,17 @@ export const AppSettingsPage: React.FC<Props> = ({
/>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('forceQuitAppTitle')}</div>
<div className="row-sub">{tr('forceQuitAppSub')}</div>
</div>
<div className="row-right">
<Button variant="danger" onClick={forceQuit} busy={quitMode === 'force'} icon={<PowerOff size={14} aria-hidden="true" />}>
{tr(quitMode === 'force' ? 'forceQuitInProgress' : 'forceQuitAppButton')}
</Button>
</div>
</div>
</div>
</section>
+4 -4
View File
@@ -18,7 +18,7 @@ export const CloneDialog: React.FC<Props> = ({ locale, sourceName, defaultCloneN
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
<div className="dialog-body">
<Alert.Title className="dialog-title">{t(locale, 'cloneTitle', { name: sourceName })}</Alert.Title>
<Alert.Description className="dialog-desc">
@@ -28,7 +28,7 @@ export const CloneDialog: React.FC<Props> = ({ locale, sourceName, defaultCloneN
<label className="field-label" htmlFor="clone-name">{t(locale, 'cloneNameLabel')}</label>
<input
id="clone-name"
className="input mono"
className="input rg-p-input mono"
value={cloneName}
spellCheck={false}
autoComplete="off"
@@ -40,10 +40,10 @@ export const CloneDialog: React.FC<Props> = ({ locale, sourceName, defaultCloneN
</div>
<div className="dialog-foot">
<Alert.Cancel asChild>
<button type="button" className="btn">{t(locale, 'cancel')}</button>
<button type="button" className="btn rg-p-button">{t(locale, 'cancel')}</button>
</Alert.Cancel>
<Alert.Action asChild>
<button type="button" className="btn btn-primary" disabled={!trimmed} onClick={() => onConfirm(trimmed)}>
<button type="button" className="btn rg-p-button btn-primary" disabled={!trimmed} onClick={() => onConfirm(trimmed)}>
{t(locale, 'cloneConfirm')}
</button>
</Alert.Action>
+34 -12
View File
@@ -18,6 +18,8 @@ import {
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
fullscreenDisplayPresets,
FullscreenDisplayPreset,
hidpiLooksLike,
hostDisplayAdvice,
hostDisplayDesc,
@@ -56,7 +58,7 @@ interface Props {
const REVIEW_STEP = 5
// Which wizard step owns each ValidationIssue.field (internal/driver/reims/reims.go ValidateCreate).
// Which wizard step owns each ValidationIssue.field (internal/macos/reims/reims.go ValidateCreate).
const STEP_OF_FIELD: Record<string, number> = {
installer: 1, disk: 1, macos: 1, guest_lang: 1,
cpus: 2, memory: 2,
@@ -89,7 +91,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
useEffect(() => {
let live = true
api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch(() => {})
api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch((e) => console.warn('[wizard] ListDrivers failed:', e))
return () => { live = false }
}, [])
const activeDriver = drivers.find((d) => d.id === driverID)
@@ -157,7 +159,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
useEffect(() => {
if (opts.source_mode !== 'offline' || releases) return
let live = true
api.ListInstallers().then((l) => { if (live) setCached(l ?? []) }).catch(() => {})
api.ListInstallers().then((l) => { if (live) setCached(l ?? []) }).catch((e) => console.warn('[wizard] ListInstallers failed:', e))
api.ListOfflineReleases()
.then((list) => {
if (!live) return
@@ -270,7 +272,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
<SetGroup title={tr('wizardBasics')}>
<SetRow
title={tr('vmName')}
control={<input className="input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
control={<input className="input rg-p-input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
/>
</SetGroup>
{activeDriver.create_schema && (
@@ -306,13 +308,14 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
<span className={`source-icon source-icon-${s.mode}`} aria-hidden="true"><Icon size={20} /></span>
<span className="source-title">
{tr(s.title)}
{s.mode === 'offline' && <span className="badge badge-accent">{tr('recommendedBadge')}</span>}
{s.mode === 'offline' && <span className="badge rg-p-badge badge-accent">{tr('recommendedBadge')}</span>}
</span>
<span className="source-sub">{tr(s.sub)}</span>
</label>
)
})}
</div>
<div className="rg-slot-anchor" data-rg-slot="create.source" />
<SetGroup>
{opts.source_mode === 'apple' && (
@@ -552,17 +555,22 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
title={tr('resolution')}
disabled={opts.graphics !== 'reims-vgpu'}
reason={tr('gpuSvgaReason')}
desc={[hostDisplayDesc(host, tr), hostDisplayAdvice(host, tr)].filter(Boolean).join(' · ') || undefined}
desc={[hostDisplayDesc(host, tr), !opts.borderless ? hostDisplayAdvice(host, tr) : undefined].filter(Boolean).join(' · ') || undefined}
control={
<PopupSelect
id="vm-res"
label={tr('resolution')}
value={opts.resolution}
onChange={(resolution) => set({ resolution })}
options={recommendedDisplayPresets(host).map((p) => ({
options={(opts.borderless ? fullscreenDisplayPresets(host) : recommendedDisplayPresets(host)).map((p: FullscreenDisplayPreset) => ({
value: p.resolution,
label: p.label,
detail: [p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '', p.recommended ? tr('recommendedBadge') : ''].filter(Boolean).join(' · ') || undefined,
detail: [
p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '',
p.scaleBadge ?? '',
p.native ? tr('resNativeBadge') : '',
p.recommended ? tr('recommendedBadge') : '',
].filter(Boolean).join(' · ') || undefined,
}))}
/>
}
@@ -613,8 +621,19 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
/>
<SetRow
title={tr('fullscreenLaunch')}
desc={tr('fullscreenLaunchHint')}
control={<Switch label={tr('fullscreenLaunch')} checked={!!opts.borderless} onChange={(borderless) => set({ borderless })} />}
desc={opts.borderless ? tr('fullscreenDecoupledHint') : tr('fullscreenLaunchHint')}
control={
<Switch
label={tr('fullscreenLaunch')}
checked={!!opts.borderless}
onChange={(borderless) => {
const list = borderless ? fullscreenDisplayPresets(host) : recommendedDisplayPresets(host)
const keep = list.some((p) => p.resolution === opts.resolution)
const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution
set(keep ? { borderless } : { borderless, resolution: fallback })
}}
/>
}
/>
<SetRow
title={tr('enableLogs')}
@@ -775,7 +794,10 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
await navigator.clipboard.writeText(command)
setCopied(true)
setTimeout(() => setCopied(false), 1500)
} catch { /* clipboard unavailable; the text stays selectable */ }
} catch (e) {
// clipboard unavailable; the text stays selectable
console.warn('[wizard] clipboard write failed:', e)
}
}
return (
@@ -784,7 +806,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
<SetRow
title={tr('vmName')}
error={nameIssue}
control={<input className="input name-input" aria-label={tr('vmName')} value={opts.name} onChange={(e) => onName(e.target.value)} spellCheck={false} />}
control={<input className="input rg-p-input name-input" aria-label={tr('vmName')} value={opts.name} onChange={(e) => onName(e.target.value)} spellCheck={false} />}
/>
<SetRow
title={tr('vmDir')}
@@ -0,0 +1,89 @@
import { FolderOpen } from 'lucide-react'
import React, { useState } from 'react'
import { I18nKey, t } from '../i18n'
import { AppState, Locale } from '../types'
import { Button } from '../ui/controls'
import { api } from '../wails'
interface Props {
locale: Locale
status: AppState['data_root_status']
/** Localized reason from the backend (dataroot.Error). */
message: string
/** The folder changed or reopened; the app reloads its state. */
onChanged: () => void
onError: (title: string, e: unknown) => void
}
/**
* Shown instead of the workspace while the data folder is open read-only
* (written by a newer release, damaged version record, failed or concurrent
* upgrade). Nothing in the folder has been changed; the user can repair it,
* try again, or pick another folder.
*/
export const DataRootReadOnly: React.FC<Props> = ({ locale, status, message, onChanged, onError }) => {
const tr = (k: I18nKey) => t(locale, k)
const [busy, setBusy] = useState<'' | 'repair' | 'retry' | 'choose'>('')
const run = async (kind: 'repair' | 'retry' | 'choose', fn: () => Promise<unknown>) => {
setBusy(kind)
try {
await fn()
onChanged()
} catch (e) {
onError(tr('failGeneric'), e)
} finally {
setBusy('')
}
}
const choose = () => run('choose', async () => {
const dir = await api.PickDirectory(tr('dataRootChooseTitle'))
if (dir) await api.SetDataRoot(dir)
})
const canRepair = status.reason === 'damaged'
const canRetry = status.reason === 'busy' || status.reason === 'migration_failed'
return (
<div className="setup">
<div className="setup-card">
<div className="setup-head">
<h1>{tr('dataRootReadOnlyTitle')}</h1>
<p>{message}</p>
</div>
<div className="list">
<div className="row">
<div className="row-main">
<div className="row-title">{tr('dataRootReadOnlyFolder')}</div>
<div className="row-sub mono selectable">{status.dir}</div>
</div>
</div>
</div>
{status.detail && (
<details className="dataroot-detail">
<summary>{tr('dataRootReadOnlyDetail')}</summary>
<pre className="mono selectable">{status.detail}</pre>
</details>
)}
<div className="setup-foot">
<span className="hstack">
{canRepair && (
<Button busy={busy === 'repair'} disabled={!!busy} onClick={() => void run('repair', () => api.ReopenDataRoot(true))}>
{tr('dataRootRepair')}
</Button>
)}
{canRetry && (
<Button busy={busy === 'retry'} disabled={!!busy} onClick={() => void run('retry', () => api.ReopenDataRoot(false))}>
{tr('dataRootRetry')}
</Button>
)}
</span>
<Button variant="primary" icon={<FolderOpen size={14} aria-hidden="true" />} busy={busy === 'choose'} disabled={!!busy} onClick={() => void choose()}>
{tr('dataRootChooseOther')}
</Button>
</div>
</div>
</div>
)
}
+14 -28
View File
@@ -1,7 +1,7 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import React, { useState } from 'react'
import { t } from '../i18n'
import { Locale } from '../types'
import { ConfirmDialog } from '../ui/dialog'
interface Props {
locale: Locale
@@ -13,32 +13,18 @@ interface Props {
export const DeleteDialog: React.FC<Props> = ({ locale, name, onCancel, onConfirm }) => {
const [keepFiles, setKeepFiles] = useState(false)
return (
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<div className="dialog-body">
<Alert.Title className="dialog-title">{t(locale, 'deleteTitle', { name })}</Alert.Title>
<Alert.Description className="dialog-desc">
{t(locale, keepFiles ? 'deleteDescKeep' : 'deleteDesc')}
</Alert.Description>
<label className="choice">
<input type="checkbox" checked={keepFiles} onChange={(e) => setKeepFiles(e.target.checked)} />
{t(locale, 'deleteKeepFiles')}
</label>
</div>
<div className="dialog-foot">
<Alert.Cancel asChild>
<button type="button" className="btn">{t(locale, 'cancel')}</button>
</Alert.Cancel>
<Alert.Action asChild>
<button type="button" className="btn btn-danger" onClick={() => onConfirm(keepFiles)}>
{t(locale, 'deleteConfirm')}
</button>
</Alert.Action>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
<ConfirmDialog
title={t(locale, 'deleteTitle', { name })}
description={t(locale, keepFiles ? 'deleteDescKeep' : 'deleteDesc')}
cancelLabel={t(locale, 'cancel')}
confirmLabel={t(locale, 'deleteConfirm')}
onCancel={onCancel}
onConfirm={() => onConfirm(keepFiles)}
>
<label className="choice">
<input type="checkbox" checked={keepFiles} onChange={(e) => setKeepFiles(e.target.checked)} />
{t(locale, 'deleteKeepFiles')}
</label>
</ConfirmDialog>
)
}
+1 -1
View File
@@ -44,7 +44,7 @@ export class ErrorBoundary extends React.Component<{ children: React.ReactNode }
<div className="error-boundary-actions">
<button
type="button"
className="btn btn-primary"
className="btn rg-p-button btn-primary"
onClick={() => window.location.reload()}
>
{t(loc, 'errorBoundaryReload')}
+14 -9
View File
@@ -33,7 +33,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
useEffect(() => {
let live = true
api.GetStorageBreakdown().then((s) => { if (live) setStorage(s) }).catch(() => {})
api.GetStorageBreakdown().then((s) => { if (live) setStorage(s) }).catch((e) => console.warn('[host] GetStorageBreakdown failed:', e))
return () => { live = false }
}, [state.config.data_root, state.vms?.length, state.runtimes?.length])
@@ -135,7 +135,12 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
{tr('hostRAM')}
</div>
<div className="tile-value">{tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })}</div>
<div className="tile-sub">{tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}</div>
<div className="tile-sub">
{tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}
{host.memory_spec?.speed_mhz
? ` · ${host.memory_spec.speed_mhz} MHz${host.memory_spec.type_name ? ` ${host.memory_spec.type_name}` : ''}`
: ''}
</div>
</div>
<div className="tile">
<div className="tile-head">
@@ -152,7 +157,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
const instPct = (storage.installers_bytes / tot) * 100
const rtPct = (storage.runtimes_bytes / tot) * 100
return (
<section className="card">
<section className="card rg-p-card">
<div className="card-title">
<span>{tr('storageBreakdownTitle')}</span>
<span className="spacer" />
@@ -248,10 +253,10 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
<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>}
<span className={`badge rg-p-badge ${g.kind === 'discrete' ? 'badge-accent' : ''}`}>{gpuKind(g.kind)}</span>
{g.compat === 'unsupported' && <span className="badge rg-p-badge badge-warn">{tr('gpuCompatUnsupported')}</span>}
{g.compat === 'warn' && <span className="badge rg-p-badge badge-warn">{tr('gpuCompatWarn')}</span>}
{isRec && g.compat !== 'warn' && g.compat !== 'unsupported' && <span className="badge rg-p-badge badge-ok">{tr('gpuRecommended')}</span>}
</div>
{meta && <div className="row-sub">{meta}</div>}
{hint && <div className="row-sub warn-text">{hint}</div>}
@@ -272,8 +277,8 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
<div className="row-title">
{d.width} × {d.height}
{d.refresh_hz ? ` @ ${d.refresh_hz}Hz` : ''}
<span className="badge">{d.scale_pct || 100}%</span>
{d.primary && <span className="badge badge-ok">{tr('hostDisplayPrimary')}</span>}
<span className="badge rg-p-badge">{d.scale_pct || 100}%</span>
{d.primary && <span className="badge rg-p-badge badge-ok">{tr('hostDisplayPrimary')}</span>}
</div>
</div>
</div>
+142
View File
@@ -0,0 +1,142 @@
import { Disc3, Puzzle, RefreshCw } from 'lucide-react'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import '../i18n/domains/settings.gen'
import { I18nKey, t } from '../i18n'
import { ImageSourceContribution, Locale, PluginUIContributions } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Segmented } from '../ui/settings'
import { PluginPanelFrame } from './PluginPanelFrame'
import { locText } from './SchemaForm'
import { WordmarkLoader } from './WordmarkLoader'
export interface NativeImageSourceRenderOpts {
refreshSignal: number
onBusyChange: (busy: boolean) => void
}
interface Props {
locale: Locale
appearance: 'light' | 'dark'
pluginUI: PluginUIContributions | null
renderNativeSource?: (nativeId: string, opts: NativeImageSourceRenderOpts) => React.ReactNode
onOpenPlugins: () => void
}
function sourceKey(src: ImageSourceContribution): string {
return `${src.pluginId ?? ''}:${src.id}`
}
/**
* Top-level Images page: hosts plugin-registered image source tabs via a top
* Segmented control. Built-in plugins (such as macOS Images) mount native host
* views; external plugins render in a sandboxed L4 iframe.
*/
export const ImagesPage: React.FC<Props> = ({
locale,
appearance,
pluginUI,
renderNativeSource,
onOpenPlugins,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const sources = useMemo(() => pluginUI?.image_sources ?? [], [pluginUI?.image_sources])
const [selectedKey, setSelectedKey] = useState('')
const [refreshSignals, setRefreshSignals] = useState<Record<string, number>>({})
const [busyByKey, setBusyByKey] = useState<Record<string, boolean>>({})
const activeSource = useMemo(() => {
if (sources.length === 0) return null
return sources.find((s) => sourceKey(s) === selectedKey) ?? sources[0]
}, [sources, selectedKey])
const activeKey = activeSource ? sourceKey(activeSource) : ''
useEffect(() => {
if (activeKey && activeKey !== selectedKey) {
setSelectedKey(activeKey)
}
}, [activeKey, selectedKey])
const activeBusy = activeKey ? !!busyByKey[activeKey] : false
const handleActiveBusyChange = useCallback((busy: boolean) => {
if (!activeKey) return
setBusyByKey((prev) => (prev[activeKey] === busy ? prev : { ...prev, [activeKey]: busy }))
}, [activeKey])
const triggerRefresh = () => {
if (!activeKey) return
setRefreshSignals((prev) => ({ ...prev, [activeKey]: (prev[activeKey] ?? 0) + 1 }))
}
return (
<div className="page installers-page">
<header className="page-head">
<div className="page-title installers-page-title">
<h1>{tr('installersTitle')}</h1>
<span>{tr('installersHint')}</span>
</div>
{activeSource && (
<div className="actions">
<IconButton
label={tr('refresh')}
icon={<RefreshCw size={16} className={activeBusy ? 'spin' : undefined} />}
disabled={activeBusy}
onClick={triggerRefresh}
/>
</div>
)}
</header>
{sources.length > 0 && (
<div className="images-switch">
<Segmented
label={tr('imagesSourcesLabel')}
value={activeKey}
onChange={setSelectedKey}
options={sources.map((src) => ({
value: sourceKey(src),
label: locText(src.title, locale, src.id),
}))}
/>
</div>
)}
{pluginUI === null ? (
<WordmarkLoader className="installers-loader" />
) : !activeSource ? (
<div className="empty-panel images-empty">
<Disc3 size={28} aria-hidden="true" />
<div className="images-empty-title">{tr('imagesNoSourcesTitle')}</div>
<div className="images-empty-desc">{tr('imagesNoSourcesDesc')}</div>
<Button variant="primary" icon={<Puzzle size={14} aria-hidden="true" />} onClick={onOpenPlugins}>
{tr('imagesOpenPlugins')}
</Button>
</div>
) : activeSource.native ? (
renderNativeSource?.(activeSource.native, {
refreshSignal: refreshSignals[activeKey] ?? 0,
onBusyChange: handleActiveBusyChange,
})
) : (
<PluginPanelFrame
key={activeKey}
locale={locale}
panel={{
id: activeSource.id,
slot: 'images.source',
title: activeSource.title,
entry: activeSource.entry || 'index.html',
height: activeSource.height || 560,
pluginId: activeSource.pluginId,
}}
assetToken={pluginUI.asset_token ?? ''}
appearance={appearance}
headless
maxHeight={1200}
refreshSignal={refreshSignals[activeKey] ?? 0}
/>
)}
</div>
)
}
+22 -11
View File
@@ -5,6 +5,7 @@ import { LogLine } from '../lib/logs'
import { taskDetail, taskInstallerPhase, taskStopAction, taskTitle } from '../lib/tasks'
import { HostReport, Locale, Task } from '../types'
import { Button, IconButton, Tip } from '../ui/controls'
import { HostIcon } from '../ui/themeVisuals'
export type LogTab = 'app' | 'serial' | 'qemu'
@@ -127,9 +128,18 @@ export const LogPanel: React.FC<Props> = ({
try {
const saved = Number(localStorage.getItem(LOG_HEIGHT_KEY))
if (Number.isFinite(saved) && saved >= MIN_LOG_HEIGHT && saved <= MAX_LOG_HEIGHT) return saved
} catch {}
} catch (e) {
console.warn('[logPanel] read persisted height failed:', e)
}
return DEFAULT_LOG_HEIGHT
})
const persistHeight = (value: number) => {
try {
localStorage.setItem(LOG_HEIGHT_KEY, String(value))
} catch (e) {
console.warn('[logPanel] persist height failed:', e)
}
}
const [dragging, setDragging] = useState(false)
const dragRef = useRef<{ startY: number; startH: number } | null>(null)
@@ -149,7 +159,7 @@ export const LogPanel: React.FC<Props> = ({
dragRef.current = null
setDragging(false)
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId)
try { localStorage.setItem(LOG_HEIGHT_KEY, String(height)) } catch {}
persistHeight(height)
}
return (
@@ -175,17 +185,18 @@ export const LogPanel: React.FC<Props> = ({
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 {}
persistHeight(next)
}}
onDoubleClick={() => {
setHeight(DEFAULT_LOG_HEIGHT)
try { localStorage.setItem(LOG_HEIGHT_KEY, String(DEFAULT_LOG_HEIGHT)) } catch {}
persistHeight(DEFAULT_LOG_HEIGHT)
}}
>
<span className="log-resize-pill" aria-hidden="true" />
</div>
)}
<div className="logbar rg-p-statusbar">
<span className="rg-slot-inline" data-rg-slot="statusbar.left" />
{task ? (
<>
<Tip
@@ -202,7 +213,7 @@ export const LogPanel: React.FC<Props> = ({
</span>
{task.percent >= 0 && (
<>
<span className="progress" aria-hidden="true">
<span className="progress rg-p-progress" aria-hidden="true">
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
</span>
<span className="task-pct">{Math.floor(task.percent)}%</span>
@@ -231,7 +242,7 @@ export const LogPanel: React.FC<Props> = ({
{!hostReady && onOpenHost && (
<Tip side="top" label={tr('footerHostIssueTip')}>
<button type="button" className="status-metric status-issue" onClick={onOpenHost}>
<AlertTriangle size={12} aria-hidden="true" />
<HostIcon name="warning"><AlertTriangle size={12} aria-hidden="true" /></HostIcon>
<span>{tr('footerHostIssue')}</span>
</button>
</Tip>
@@ -293,7 +304,7 @@ export const LogPanel: React.FC<Props> = ({
</button>
)}
<div
className="tabs"
className="tabs rg-p-tabs"
role="tablist"
onKeyDown={(e) => {
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return
@@ -308,15 +319,15 @@ export const LogPanel: React.FC<Props> = ({
btns[order.indexOf(next)]?.focus()
}}
>
<button type="button" role="tab" className="tab" tabIndex={tab === 'app' ? 0 : -1} aria-selected={tab === 'app'} onClick={() => onTab('app')}>
<button type="button" role="tab" className="tab rg-p-tab" tabIndex={tab === 'app' ? 0 : -1} aria-selected={tab === 'app'} onClick={() => onTab('app')}>
{tr('logActivity')}
</button>
{showSerial && (
<>
<button type="button" role="tab" className="tab" tabIndex={tab === 'serial' ? 0 : -1} aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
<button type="button" role="tab" className="tab rg-p-tab" tabIndex={tab === 'serial' ? 0 : -1} aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
{tr('logSerial')}
</button>
<button type="button" role="tab" className="tab" tabIndex={tab === 'qemu' ? 0 : -1} aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
<button type="button" role="tab" className="tab rg-p-tab" tabIndex={tab === 'qemu' ? 0 : -1} aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
{tr('logQemu')}
</button>
</>
@@ -337,7 +348,7 @@ export const LogPanel: React.FC<Props> = ({
<IconButton small tipSide="top" label={tr('refresh')} icon={<RefreshCw size={14} />} onClick={onRefreshQemu} />
)}
<span className="rg-slot-inline" data-rg-slot="statusbar.right" />
{!open && unseenErrors > 0 && <span className="badge badge-error" aria-hidden="true">{unseenErrors}</span>}
{!open && unseenErrors > 0 && <span className="badge rg-p-badge badge-error" aria-hidden="true">{unseenErrors}</span>}
<Tip label={open ? tr('collapseLogs') : tr('expandLogs')} shortcut="Ctrl+L" side="top">
<button
type="button"
+81
View File
@@ -0,0 +1,81 @@
import {
Boxes, Clipboard, Compass, Cpu, Disc3, Globe, Keyboard,
Layers, Monitor, Palette, Puzzle, RotateCcw,
} from 'lucide-react'
import React from 'react'
import { PermissionSpec } from '../types'
export interface PluginVisualSource {
id?: string
kind?: string
system?: boolean
tier?: string
locales?: string[]
permissions?: Array<PermissionSpec | string>
}
export interface PluginVisual {
tone: string
icon: React.ReactNode
}
const ICON_SIZES = { sm: 16, md: 18, lg: 20 } as const
/**
* Single visual resolver for both installed plugins (PluginInfo) and market
* entries (MarketEntry), so a plugin keeps the same icon and colour across
* Market, Installed and first-run setup.
*/
export function resolvePluginVisual(src: PluginVisualSource, iconSize = 20): PluginVisual {
if (src.system) return { tone: 'indigo', icon: <Boxes size={iconSize} aria-hidden="true" /> }
switch (src.kind) {
case 'theme': return { tone: 'purple', icon: <Palette size={iconSize} aria-hidden="true" /> }
case 'locale': return { tone: 'sky', icon: <Globe size={iconSize} aria-hidden="true" /> }
case 'driver':
case 'runtime': return { tone: 'indigo', icon: <Monitor size={iconSize} aria-hidden="true" /> }
}
const id = (src.id ?? '').toLowerCase()
const perms = new Set((src.permissions ?? []).map((x) => (typeof x === 'string' ? x : x.name)))
if ((src.locales?.length ?? 0) > 0 || id.includes('lang') || id.includes('locale')) {
return { tone: 'sky', icon: <Globe size={iconSize} aria-hidden="true" /> }
}
if (id.includes('theme') || perms.has('ui:script')) {
return { tone: 'purple', icon: <Palette size={iconSize} aria-hidden="true" /> }
}
if (id.includes('driver') || perms.has('driver:vm') || perms.has('runtime:provider')) {
return { tone: 'indigo', icon: <Monitor size={iconSize} aria-hidden="true" /> }
}
if (id.includes('clipboard') || perms.has('host:clipboard')) {
return { tone: 'sky', icon: <Clipboard size={iconSize} aria-hidden="true" /> }
}
if (id.includes('ime') || id.includes('input') || id.includes('wheel') || perms.has('input:filter')) {
return { tone: 'rose', icon: <Keyboard size={iconSize} aria-hidden="true" /> }
}
if (id.includes('reboot')) {
return { tone: 'amber', icon: <RotateCcw size={iconSize} aria-hidden="true" /> }
}
if (id.includes('whpx') || id.includes('irq')) {
return { tone: 'emerald', icon: <Cpu size={iconSize} aria-hidden="true" /> }
}
if (id.includes('guide')) {
return { tone: 'teal', icon: <Compass size={iconSize} aria-hidden="true" /> }
}
if (id.includes('offline') || id.includes('installer') || id.includes('helper') || id.includes('image')) {
return { tone: 'teal', icon: <Disc3 size={iconSize} aria-hidden="true" /> }
}
if (src.tier === 'L3') {
return { tone: 'slate', icon: <Layers size={iconSize} aria-hidden="true" /> }
}
return { tone: 'teal', icon: <Puzzle size={iconSize} aria-hidden="true" /> }
}
/** App Store-inspired squircle icon tile shared by Market, Installed and Setup. */
export const PluginAppIcon: React.FC<{
plugin?: PluginVisualSource
kind?: string
size?: 'sm' | 'md' | 'lg'
}> = ({ plugin, kind, size = 'lg' }) => {
const vis = resolvePluginVisual(plugin ?? { kind }, ICON_SIZES[size])
const sizeCls = size === 'lg' ? '' : ` is-${size}`
return <div className={`plugin-app-icon tone-${vis.tone}${sizeCls}`}>{vis.icon}</div>
}
+387
View File
@@ -0,0 +1,387 @@
import { AlertTriangle, Check, Download, ShieldAlert } from 'lucide-react'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import '../i18n/domains/plugins.gen'
import { I18nKey, t } from '../i18n'
import { Locale, MarketBrowseResult, MarketCatalogItem, PluginInfo } from '../types'
import { Button, Tip } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { api, events, MarketInstallProgress } from '../wails'
import { PluginAppIcon, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
import { locText } from './SchemaForm'
import { WordmarkLoader } from './WordmarkLoader'
// Cards are revealed in pages as the feed scrolls into view.
const PAGE_SIZE = 24
// A manual refresh keeps the loader up at least this long, so it reads as a
// response instead of a flicker.
const MIN_REFRESH_MS = 900
const QUERY_DEBOUNCE_MS = 180
const KIND_LABELS: Record<string, I18nKey> = {
theme: 'pluginMarketKindTheme',
locale: 'pluginMarketKindLocale',
driver: 'pluginMarketKindDriver',
tool: 'pluginMarketKindTool',
template: 'pluginMarketKindTemplate',
runtime: 'pluginMarketKindRuntime',
}
interface Props {
locale: Locale
safeMode?: boolean
/** Installed plugins; a change re-reads install state from the cache. */
installed: PluginInfo[]
/** Bumped by the page's refresh button to force a network fetch. */
refreshSignal: number
onBusyChange: (busy: boolean) => void
/** Called after an install or enable so the page reloads its plugin list. */
onChanged: (opts: { enabled?: PluginInfo }) => Promise<void> | void
onError: (title: string, e: unknown) => void
}
type ProgressMap = Record<string, MarketInstallProgress>
/**
* Plugin market feed: a multi-column card grid that paints from the local
* cache first, revalidates over the network, and reveals cards page by page.
*/
export const PluginMarket: React.FC<Props> = ({
locale, safeMode, installed, refreshSignal, onBusyChange, onChanged, onError,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [query, setQuery] = useState('')
const [kind, setKind] = useState('')
const [result, setResult] = useState<MarketBrowseResult | null>(null)
const [syncing, setSyncing] = useState(false)
const [refreshing, setRefreshing] = useState(false)
const [visible, setVisible] = useState(PAGE_SIZE)
const [progress, setProgress] = useState<ProgressMap>({})
const [prompt, setPrompt] = useState<PluginInfo | null>(null)
const [promptChecked, setPromptChecked] = useState(false)
const [enabling, setEnabling] = useState(false)
const seq = useRef(0)
const synced = useRef(false)
const sentinel = useRef<HTMLDivElement>(null)
const params = useRef({ query, kind })
params.current = { query, kind }
useEffect(() => { onBusyChange(syncing) }, [syncing])
// Network load. Stale responses (an older query) are dropped.
const sync = useCallback(async (force: boolean) => {
const id = ++seq.current
const { query: q, kind: k } = params.current
setSyncing(true)
const started = Date.now()
if (force) setRefreshing(true)
try {
const res = await api.BrowsePluginMarket(q, k, false, force)
if (force) {
const wait = MIN_REFRESH_MS - (Date.now() - started)
if (wait > 0) await new Promise((r) => window.setTimeout(r, wait))
}
if (id !== seq.current) return
setResult(res)
synced.current = true
} catch (e) {
if (id === seq.current) onError(tr('pluginFailMarketLoad'), e)
} finally {
if (id === seq.current) {
setSyncing(false)
setRefreshing(false)
}
}
}, [])
// Cache-only read: instant, no network.
const peek = useCallback(async (keepNetworkState: boolean) => {
const { query: q, kind: k } = params.current
try {
const res = await api.PeekPluginMarket(q, k)
setResult((prev) => {
if (keepNetworkState && prev) {
res.stale = prev.stale
res.fetch_error = prev.fetch_error
}
return res
})
} catch (e) {
// the network load reports errors
console.warn('[market] PeekPluginMarket failed:', e)
}
}, [])
// First open: paint from cache, then revalidate.
useEffect(() => {
void peek(false).then(() => sync(false))
}, [])
// Query and category changes; the first render is handled above.
const firstFilter = useRef(true)
useEffect(() => {
if (firstFilter.current) { firstFilter.current = false; return }
setVisible(PAGE_SIZE)
const timer = window.setTimeout(() => { void sync(false) }, query ? QUERY_DEBOUNCE_MS : 0)
return () => window.clearTimeout(timer)
}, [query, kind])
const firstRefresh = useRef(true)
useEffect(() => {
if (firstRefresh.current) { firstRefresh.current = false; return }
void sync(true)
}, [refreshSignal])
// Install state lives in the plugin list; re-read it without the network.
const firstInstalled = useRef(true)
useEffect(() => {
if (firstInstalled.current) { firstInstalled.current = false; return }
if (synced.current) void peek(true)
}, [installed])
useEffect(() => events.onPluginInstall((p) => {
setProgress((prev) => prev[p.id] ? { ...prev, [p.id]: p } : prev)
}), [])
const items = result?.items ?? []
const shown = items.slice(0, visible)
const hasMore = items.length > visible
// Reveal the next page as the sentinel nears the viewport.
useEffect(() => {
const el = sentinel.current
if (!el || !hasMore || typeof IntersectionObserver === 'undefined') return
const io = new IntersectionObserver((entries) => {
if (entries.some((e) => e.isIntersecting)) setVisible((v) => v + PAGE_SIZE)
}, { rootMargin: '240px 0px' })
io.observe(el)
return () => io.disconnect()
}, [hasMore, visible, items.length])
const install = async (item: MarketCatalogItem) => {
const id = item.entry.id
setProgress((prev) => ({ ...prev, [id]: { id, phase: 'download', done: 0, total: item.entry.size_bytes ?? 0 } }))
try {
const info = await api.InstallMarketPlugin(id, false)
await onChanged({})
if (info && !info.enabled) {
setPromptChecked(false)
setPrompt(info)
}
} catch (e) {
onError(tr('pluginFailMarketInstall'), e)
} finally {
setProgress((prev) => {
const next = { ...prev }
delete next[id]
return next
})
}
}
const enablePrompted = async () => {
if (!prompt) return
setEnabling(true)
try {
const target = prompt
await api.EnablePlugin(target.id, target.needs_approval)
setPrompt(null)
await onChanged({ enabled: target })
} catch (e) {
onError(tr('pluginFailEnable'), e)
} finally {
setEnabling(false)
}
}
const facets = useMemo(() => {
const list = [...(result?.kinds ?? [])]
if (kind && !list.some((f) => f.kind === kind)) list.push({ kind, count: 0 })
return list
}, [result, kind])
const kindLabel = (k: string) => KIND_LABELS[k] ? tr(KIND_LABELS[k]) : k.charAt(0).toUpperCase() + k.slice(1)
const action = (item: MarketCatalogItem) => {
const e = item.entry
const p = progress[e.id]
if (p) {
const pct = p.phase === 'download' && p.total > 0 ? Math.min(100, Math.round((p.done / p.total) * 100)) : null
const text = p.phase === 'install' ? tr('pluginMarketInstalling') : pct === null ? tr('pluginMarketDownloading') : `${pct}%`
return (
<div
className={`market-progress rg-p-progress${pct === null ? ' is-indeterminate' : ''}`}
role="progressbar"
aria-label={tr('pluginMarketDownloading')}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={pct ?? undefined}
>
<span className="market-progress-fill" style={pct === null ? undefined : { transform: `scaleX(${pct / 100})` }} />
<span className="market-progress-text">{text}</span>
</div>
)
}
if (item.withdrawn) {
const why = locText(item.withdrawn.reason, locale, '')
+ (item.withdrawn.instead_id ? ` · ${tr('pluginMarketWithdrawnInstead', { target: item.withdrawn.instead_name || item.withdrawn.instead_id })}` : '')
return <Tip label={why || tr('pluginMarketWithdrawn')}><span tabIndex={0}><Button className="market-btn" disabled>{tr('pluginMarketWithdrawn')}</Button></span></Tip>
}
if (!item.compatible) {
return <Tip label={item.incompatible_reason || tr('pluginMarketIncompatible')}><span tabIndex={0}><Button className="market-btn" disabled>{tr('pluginMarketIncompatible')}</Button></span></Tip>
}
if (item.installed && !item.update_available) {
return <Button className="market-btn" disabled icon={<Check size={13} aria-hidden="true" />}>{tr('pluginMarketInstalled')}</Button>
}
if (item.update_available) {
return (
<Tip label={tr('pluginMarketVersionTip', { installed: item.installed_version ?? '', version: e.version })}>
<span>
<Button className="market-btn" variant="primary" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => void install(item)}>
{tr('pluginMarketUpdateShort')}
</Button>
</span>
</Tip>
)
}
return (
<Button className="market-btn" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => void install(item)}>
{tr('pluginMarketInstall')}
</Button>
)
}
// The loader covers the feed when there is nothing to show yet, or when the
// user asked for a refresh and should see it happen.
const showLoader = refreshing || (syncing && items.length === 0) || (!result && !synced.current)
const emptyAfterSync = !showLoader && items.length === 0
return (
<section className="section plugin-market">
<div className="market-toolbar">
<PluginSearchInput
value={query}
onChange={setQuery}
placeholder={tr('pluginMarketSearchPlaceholder')}
wide
/>
{facets.length > 1 && (
<div className="market-kinds" role="radiogroup" aria-label={tr('pluginMarketKindAll')}>
{[{ kind: '', count: 0 }, ...facets].map((f) => (
<button
key={f.kind || 'all'}
type="button"
role="radio"
aria-checked={kind === f.kind}
className={`plugin-pill${kind === f.kind ? ' is-active' : ''}`}
onClick={() => setKind(f.kind)}
>
{f.kind ? kindLabel(f.kind) : tr('pluginMarketKindAll')}
{f.kind && f.count > 0 && <span className="plugin-pill-count">{f.count}</span>}
</button>
))}
</div>
)}
</div>
{!showLoader && result?.stale && result.fetch_error && (
<div className="notice notice-warn">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('pluginMarketStaleBanner')}</span>
</span>
</div>
)}
{(result?.withdrawn_installed ?? []).map((w) => (
<div className="notice notice-warn" key={w.id}>
<span className="notice-main">
<ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
<span>
{tr('pluginMarketWithdrawnInstalledWarn', { id: w.id, reason: locText(w.reason, locale, '') })}
{w.instead_id ? ` · ${tr('pluginMarketWithdrawnInstead', { target: w.instead_name || w.instead_id })}` : ''}
</span>
</span>
</div>
))}
{showLoader ? (
<WordmarkLoader className="market-loader" label={tr(refreshing || result ? 'pluginMarketSyncing' : 'pluginMarketLoading')} />
) : emptyAfterSync ? (
<div className="plugins-empty">{query || kind ? tr('pluginSearchEmpty') : tr('pluginMarketEmpty')}</div>
) : (
<>
<div className="market-grid">
{shown.map((item, i) => {
const e = item.entry
const desc = locText(e.description, locale, '')
const muted = !!item.withdrawn || !item.compatible
return (
<article
className={`market-card rg-p-card${muted ? ' is-muted' : ''}`}
key={e.id}
style={{ '--i': i % PAGE_SIZE } as React.CSSProperties}
>
<div className="market-card-head">
<PluginAppIcon plugin={e} size="lg" />
<div className="market-card-titles">
<h3 className="market-card-name" title={locText(e.name, locale, e.id)}>{locText(e.name, locale, e.id)}</h3>
<div className="market-card-byline">
<PluginTrustBadge locale={locale} trust={e.trust} publisher={e.publisher} />
<span className="market-card-dot" aria-hidden="true">·</span>
<span className="market-card-version">v{e.version}</span>
</div>
</div>
<div className="market-card-action">{action(item)}</div>
</div>
<p className="market-card-desc" title={desc}>{desc}</p>
</article>
)
})}
</div>
{hasMore
? <div ref={sentinel} className="market-sentinel" aria-hidden="true" />
: items.length > PAGE_SIZE && <div className="market-feed-end">{tr('pluginMarketFeedEnd', { count: items.length })}</div>}
</>
)}
{prompt && (
<Modal
title={tr('pluginEnablePromptTitle', { name: locText(prompt.name, locale, prompt.id) })}
subtitle={`${prompt.publisher || tr('pluginTrustCommunity')} · v${prompt.version}`}
closeLabel={tr('close')}
onClose={() => { if (!enabling) setPrompt(null) }}
>
<div className="dialog-body">
{(prompt.risks?.length ?? 0) > 0 ? (
<>
<p className="plugin-enable-lead">{tr('pluginEnablePromptBody')}</p>
<RiskList locale={locale} risks={prompt.risks} />
</>
) : (
<p className="plugin-enable-lead">{tr('pluginEnablePromptNoRisk')}</p>
)}
{prompt.needs_approval && (
<label className="choice">
<input type="checkbox" checked={promptChecked} onChange={(e) => setPromptChecked(e.target.checked)} />
<span>{tr('pluginApproveCheckbox')}</span>
</label>
)}
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" disabled={enabling} onClick={() => setPrompt(null)}>{tr('pluginEnableLater')}</Button>
<Button
variant="primary"
disabled={enabling || !!safeMode || (prompt.needs_approval && !promptChecked)}
onClick={() => void enablePrompted()}
>
{tr('pluginEnableNow')}
</Button>
</span>
</div>
</Modal>
)}
</section>
)
}
+30 -7
View File
@@ -1,3 +1,4 @@
import { AlertTriangle } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { getPluginMessageBundle, localeDir, parseAppError, t } from '../i18n'
import { Locale, PanelContribution } from '../types'
@@ -7,9 +8,15 @@ import { locText } from './SchemaForm'
interface Props {
locale: Locale
panel: PanelContribution
panel: Omit<PanelContribution, 'convertValues'>
assetToken: string
appearance: 'light' | 'dark'
/** Omit the panel title bar (e.g. when hosted inside a tab/segmented view). */
headless?: boolean
/** Upper bound for the iframe height in px (defaults to 480 for inline panels). */
maxHeight?: number
/** Incrementing this reloads the iframe cleanly. */
refreshSignal?: number
}
/**
@@ -37,13 +44,22 @@ function buildSafePanelSrc(assetToken: string, pluginId: string | undefined, ent
return `/plugin-assets/${encodeURIComponent(assetToken)}/${encodeURIComponent(pluginId)}/${segs.map(encodeURIComponent).join('/')}`
}
export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, appearance }) => {
export const PluginPanelFrame: React.FC<Props> = ({
locale, panel, assetToken, appearance, headless, maxHeight = 480, refreshSignal = 0,
}) => {
const iframeRef = useRef<HTMLIFrameElement>(null)
const localeRef = useRef<Locale>(locale)
localeRef.current = locale
const [failed, setFailed] = useState(false)
const [nonce, setNonce] = useState(0)
useEffect(() => {
if (refreshSignal > 0) {
setFailed(false)
setNonce((n) => n + 1)
}
}, [refreshSignal])
const src = buildSafePanelSrc(assetToken, panel.pluginId, panel.entry)
const syncTheme = () => {
@@ -56,6 +72,10 @@ export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, a
}
const dir = localeDir(locale)
const messages = getPluginMessageBundle(panel.pluginId ?? '', locale)
// bridgeApi 1.0 events (bridgeContract.ts).
win.postMessage({ type: 'reims:event', event: 'theme.changed', data: { appearance, tokens } }, '*')
win.postMessage({ type: 'reims:event', event: 'locale.changed', data: { locale, dir, messages } }, '*')
// Pre-1.0 message types, kept for panels written before the bridge contract.
win.postMessage({ type: 'reims:theme', appearance, locale, dir, tokens, messages }, '*')
win.postMessage({ type: 'reims:i18n', locale, dir, messages }, '*')
}
@@ -109,8 +129,11 @@ export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, a
if (failed || !src) {
return (
<div className="plugin-panel-error">
<span>{t(locale, 'panelLoadFailed')}</span>
<div className="notice notice-error" role="alert">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{t(locale, 'panelLoadFailed')}</span>
</span>
{src && (
<Button onClick={() => { setFailed(false); setNonce((n) => n + 1) }}>
{t(locale, 'installersRetry')}
@@ -121,8 +144,8 @@ export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, a
}
return (
<div className="plugin-panel-wrap">
<div className="plugin-panel-head">{locText(panel.title, locale, panel.id)}</div>
<div className={`plugin-panel-wrap rg-p-plugin-view${headless ? ' is-headless' : ''}`} data-plugin={panel.pluginId}>
{!headless && <div className="plugin-panel-head">{locText(panel.title, locale, panel.id)}</div>}
<iframe
key={nonce}
ref={iframeRef}
@@ -131,7 +154,7 @@ export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, a
src={src}
sandbox="allow-scripts"
referrerPolicy="no-referrer"
style={{ height: Math.max(120, Math.min(480, panel.height || 220)) }}
style={{ height: Math.max(120, Math.min(maxHeight, panel.height || 220)) }}
onLoad={syncTheme}
onError={() => setFailed(true)}
/>
+82
View File
@@ -0,0 +1,82 @@
import {
Activity, BadgeCheck, Binary, Clipboard, Code2, Files, Globe,
Keyboard, Monitor, PanelsTopLeft, Search, ShieldCheck, Users,
} from 'lucide-react'
import React from 'react'
import '../i18n/domains/plugins.gen'
import { I18nKey, t } from '../i18n'
import { Locale } from '../types'
import { Tip } from '../ui/controls'
export { PluginAppIcon, resolvePluginVisual, type PluginVisual, type PluginVisualSource } from './PluginAppIcon'
/** Publisher + trust-tier mark shared by Installed rows and Market cards. */
export const PluginTrustBadge: React.FC<{
locale: Locale
trust: string
publisher?: string
}> = ({ locale, trust, publisher }) => {
const tr = (k: I18nKey) => t(locale, k)
const meta = trust === 'official'
? { cls: 'is-official', icon: <BadgeCheck size={13} aria-hidden="true" />, label: tr('pluginTrustOfficial') }
: trust === 'verified'
? { cls: 'is-verified', icon: <ShieldCheck size={13} aria-hidden="true" />, label: tr('pluginTrustVerified') }
: trust === 'dev'
? { cls: 'is-dev', icon: <Code2 size={13} aria-hidden="true" />, label: tr('pluginTrustDev') }
: { cls: 'is-community', icon: <Users size={13} aria-hidden="true" />, label: tr('pluginTrustCommunity') }
return (
<Tip label={meta.label}>
<span className={`plugin-trust ${meta.cls}`} tabIndex={0}>
{meta.icon}
<span className="plugin-trust-name">{publisher || meta.label}</span>
</span>
</Tip>
)
}
/** Search input with leading magnifying glass, shared by Installed and Market. */
export const PluginSearchInput: React.FC<{
value: string
onChange: (value: string) => void
placeholder: string
wide?: boolean
}> = ({ value, onChange, placeholder, wide }) => (
<div className={`plugin-search-wrap${wide ? ' is-wide' : ''}`}>
<Search size={13} className="plugin-search-icon" aria-hidden="true" />
<input
type="search"
className="input rg-p-input plugin-search"
aria-label={placeholder}
placeholder={placeholder}
value={value}
onChange={(e) => onChange(e.target.value)}
/>
</div>
)
const RISKS: Record<string, { key: I18nKey; icon: React.ReactNode; high: boolean }> = {
native: { key: 'pluginRiskNative', icon: <Binary size={15} aria-hidden="true" />, high: true },
background: { key: 'pluginRiskBackground', icon: <Activity size={15} aria-hidden="true" />, high: true },
network: { key: 'pluginRiskNetwork', icon: <Globe size={15} aria-hidden="true" />, high: true },
files: { key: 'pluginRiskFiles', icon: <Files size={15} aria-hidden="true" />, high: true },
vm: { key: 'pluginRiskVm', icon: <Monitor size={15} aria-hidden="true" />, high: true },
clipboard: { key: 'pluginRiskClipboard', icon: <Clipboard size={15} aria-hidden="true" />, high: true },
input: { key: 'pluginRiskInput', icon: <Keyboard size={15} aria-hidden="true" />, high: false },
ui: { key: 'pluginRiskUi', icon: <PanelsTopLeft size={15} aria-hidden="true" />, high: false },
}
/** Plain-language list of what a plugin can do (backend risk categories). */
export const RiskList: React.FC<{ locale: Locale; risks?: string[] }> = ({ locale, risks }) => {
const known = (risks ?? []).filter((r) => RISKS[r])
if (known.length === 0) return null
return (
<ul className="plugin-risk-list">
{known.map((r) => (
<li key={r} className={`plugin-risk${RISKS[r].high ? ' is-high' : ''}`}>
<span className="plugin-risk-icon">{RISKS[r].icon}</span>
<span>{t(locale, RISKS[r].key)}</span>
</li>
))}
</ul>
)
}
+174 -370
View File
@@ -1,25 +1,27 @@
import {
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,
AlertTriangle, CheckCircle2, FolderOpen, PackagePlus, Palette,
RefreshCw, Settings2, Shield, ShieldAlert, Sparkles, Terminal, Trash2,
} from 'lucide-react'
import React, { useEffect, useMemo, useState } from 'react'
import '../i18n/domains/plugins.gen'
import '../i18n/domains/settings.gen'
import { I18nKey, t } from '../i18n'
import {
ActiveThemePayload, CustomThemeScheme, Locale, MarketBrowseResult, MarketCatalogItem,
PluginInfo, PluginUIContributions, ScanReport,
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions, ScanReport,
} from '../types'
import { Button, IconButton, Tip } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { PopupSelect, Switch } from '../ui/settings'
import { ConfirmDialog, Modal } from '../ui/dialog'
import { PopupSelect, Segmented, Switch } from '../ui/settings'
import { api } from '../wails'
import { PluginMarket } from './PluginMarket'
import { PluginPanelFrame } from './PluginPanelFrame'
import { PluginAppIcon, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
import { SchemaForm, locText } from './SchemaForm'
// Search only earns its space once the list is long enough to scan.
const SEARCH_THRESHOLD = 12
// A manual refresh spins at least this long so the click visibly lands.
const MIN_SPIN_MS = 500
interface Props {
locale: Locale
@@ -28,45 +30,8 @@ interface Props {
onRefresh: () => void
onError: (title: string, e: unknown) => void
onThemeChanged?: () => void
}
interface PluginVisual {
tone: string
icon: React.ReactNode
}
function resolvePluginVisual(p: PluginInfo): PluginVisual {
if (p.system) return { tone: 'indigo', icon: <Boxes size={19} aria-hidden="true" /> }
const id = p.id.toLowerCase()
const perms = new Set((p.permissions ?? []).map((x) => x.name))
if (id.includes('theme') || perms.has('ui:script')) {
return { tone: 'purple', icon: <Palette size={19} aria-hidden="true" /> }
}
if (id.includes('driver') || perms.has('driver:vm') || perms.has('runtime:provider')) {
return { tone: 'indigo', icon: <Monitor size={19} aria-hidden="true" /> }
}
if (id.includes('clipboard') || perms.has('host:clipboard')) {
return { tone: 'sky', icon: <Clipboard size={19} aria-hidden="true" /> }
}
if (id.includes('ime') || id.includes('input') || id.includes('wheel') || perms.has('input:filter')) {
return { tone: 'rose', icon: <Keyboard size={19} aria-hidden="true" /> }
}
if (id.includes('reboot')) {
return { tone: 'amber', icon: <RotateCcw size={19} aria-hidden="true" /> }
}
if (id.includes('whpx') || id.includes('irq')) {
return { tone: 'emerald', icon: <Cpu size={19} aria-hidden="true" /> }
}
if (id.includes('guide')) {
return { tone: 'teal', icon: <Compass size={19} aria-hidden="true" /> }
}
if (id.includes('offline') || id.includes('installer') || id.includes('helper')) {
return { tone: 'teal', icon: <Disc3 size={19} aria-hidden="true" /> }
}
if (p.tier === 'L3') {
return { tone: 'slate', icon: <Layers size={19} aria-hidden="true" /> }
}
return { tone: 'purple', icon: <Puzzle size={19} aria-hidden="true" /> }
/** Switches the app language (used after enabling a language pack). */
onLocaleSwitch?: (l: Locale) => void
}
// The plugin settings dialog shows app-scope fields only; per-VM fields live in
@@ -82,7 +47,7 @@ function hasAppSettings(p: PluginInfo): boolean {
* Grouped inset list, same pattern as the installers page.
*/
export const PluginsPage: React.FC<Props> = ({
locale, appearance, safeMode, onRefresh, onError, onThemeChanged,
locale, appearance, safeMode, onRefresh, onError, onThemeChanged, onLocaleSwitch,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [activeTab, setActiveTab] = useState<'installed' | 'market'>('installed')
@@ -99,6 +64,7 @@ export const PluginsPage: React.FC<Props> = ({
const [settingsValues, setSettingsValues] = useState<Record<string, unknown>>({})
const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null)
const [removeTarget, setRemoveTarget] = useState<PluginInfo | null>(null)
const [disableTarget, setDisableTarget] = useState<PluginInfo | null>(null)
const [deleteSchemeTarget, setDeleteSchemeTarget] = useState<CustomThemeScheme | null>(null)
// Static risk scan modal state (pre-install .zip preview or installed plugin scan)
@@ -109,14 +75,11 @@ export const PluginsPage: React.FC<Props> = ({
} | 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('')
// The market mounts (and touches the network) only once its tab is opened (§8.1).
const [marketOpened, setMarketOpened] = useState(false)
const [marketRefresh, setMarketRefresh] = useState(0)
const [marketBusy, setMarketBusy] = useState(false)
const [reloading, setReloading] = useState(false)
// Theme scheme editor state (§5.1)
const [schemeEditorOpen, setSchemeEditorOpen] = useState(false)
@@ -141,40 +104,46 @@ 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)
const manualReload = async () => {
setReloading(true)
const started = Date.now()
await reload()
const wait = MIN_SPIN_MS - (Date.now() - started)
if (wait > 0) await new Promise((r) => window.setTimeout(r, wait))
setReloading(false)
}
// Enabling a language pack means the user wants that language: switch to
// its first locale unless the current one is already among them.
const adoptPluginLocale = (p: PluginInfo) => {
const tags = p.locales ?? []
if (tags.length > 0 && !tags.includes(locale)) onLocaleSwitch?.(tags[0])
}
const onMarketChanged = async ({ enabled }: { enabled?: PluginInfo }) => {
await reload()
onRefresh()
if (enabled) {
onThemeChanged?.()
adoptPluginLocale(enabled)
}
}
useEffect(() => { void reload() }, [safeMode])
useEffect(() => {
if (activeTab !== 'market') 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])
useEffect(() => { if (activeTab === 'market') setMarketOpened(true) }, [activeTab])
const togglePlugin = async (p: PluginInfo, enable: boolean) => {
const togglePlugin = async (p: PluginInfo, enable: boolean, confirmed = false) => {
// Disabling a plugin that still owns VMs leaves them "driver unavailable": say so first.
if (!enable && p.in_use && !confirmed) {
setDisableTarget(p)
return
}
if (enable && p.needs_approval) {
setApproveChecked(false)
setApproveReport(null)
setApproveTarget(p)
void api.ScanInstalledPlugin(p.id).then(setApproveReport).catch(() => {})
void api.ScanInstalledPlugin(p.id).then(setApproveReport).catch((e) => console.warn('[plugins] ScanInstalledPlugin failed:', p.id, e))
return
}
setBusyID(p.id)
@@ -184,6 +153,7 @@ export const PluginsPage: React.FC<Props> = ({
await reload()
onRefresh()
onThemeChanged?.()
if (enable) adoptPluginLocale(p)
} catch (e) {
onError(tr('pluginFailToggle'), e)
} finally {
@@ -202,6 +172,7 @@ export const PluginsPage: React.FC<Props> = ({
await reload()
onRefresh()
onThemeChanged?.()
adoptPluginLocale(target)
} catch (e) {
onError(tr('pluginFailEnable'), e)
} finally {
@@ -232,7 +203,6 @@ export const PluginsPage: React.FC<Props> = ({
setScanModal(null)
await reload()
onRefresh()
if (marketLoadedOnce) void loadMarket({ forceRefresh: false })
} catch (e) {
onError(tr('pluginFailImport'), e)
} finally {
@@ -252,21 +222,6 @@ export const PluginsPage: React.FC<Props> = ({
}
}
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('')
}
}
const linkDevDir = async () => {
try {
const dir = await api.PickDirectory(tr('pluginLinkDevTitle'))
@@ -377,11 +332,8 @@ export const PluginsPage: React.FC<Props> = ({
return name.includes(q) || desc.includes(q) || p.id.toLowerCase().includes(q)
}
// The always-on core goes first; the optional builtins keep backend order.
const builtins = useMemo(
() => plugins.filter((p) => p.source === 'builtin').sort((a, b) => Number(!!b.system) - Number(!!a.system)),
[plugins],
)
// System plugins are part of the host and never listed; builtins keep backend order.
const builtins = useMemo(() => plugins.filter((p) => p.source === 'builtin'), [plugins])
const external = useMemo(() => plugins.filter((p) => p.source !== 'builtin'), [plugins])
const filteredBuiltins = useMemo(() => builtins.filter(matchesFilter), [builtins, q, locale])
const filteredExternal = useMemo(() => external.filter(matchesFilter), [external, q, locale])
@@ -403,25 +355,16 @@ export const PluginsPage: React.FC<Props> = ({
return base
}, [activeTheme, customSchemes, presetSchemes])
const trustMeta = (trLevel: string) => {
if (trLevel === 'official') return { label: tr('pluginTrustOfficial'), cls: 'is-official', icon: <BadgeCheck size={12} aria-hidden="true" /> }
if (trLevel === 'verified') return { label: tr('pluginTrustVerified'), cls: 'is-verified', icon: <ShieldCheck size={12} aria-hidden="true" /> }
if (trLevel === 'dev') return { label: tr('pluginTrustDev'), cls: 'is-dev', icon: <Code2 size={12} aria-hidden="true" /> }
return { label: tr('pluginTrustCommunity'), cls: 'is-community', icon: <Shield size={12} aria-hidden="true" /> }
}
// The switch already says on/off, so only surface states that need attention.
const stateBadge = (p: PluginInfo) => {
if (p.state === 'degraded') return <span className="badge badge-warn">{tr('pluginStateDegraded')}</span>
if (p.state === 'failed') return <span className="badge badge-warn">{tr('pluginStateFailed')}</span>
if (p.state === 'pending' && p.enabled) return <span className="badge">{tr('pluginStatePending')}</span>
if (p.state === 'degraded') return <span className="badge rg-p-badge badge-warn">{tr('pluginStateDegraded')}</span>
if (p.state === 'failed') return <span className="badge rg-p-badge badge-warn">{tr('pluginStateFailed')}</span>
if (p.state === 'pending' && p.enabled) return <span className="badge rg-p-badge">{tr('pluginStatePending')}</span>
return null
}
const renderRow = (p: PluginInfo) => {
const visual = resolvePluginVisual(p)
const isBuiltin = p.source === 'builtin'
const trust = trustMeta(p.trust)
const perms = p.permissions ?? []
const highPerms = perms.filter((x) => x.level === 'high')
const desc = locText(p.description, locale, '')
@@ -430,7 +373,7 @@ export const PluginsPage: React.FC<Props> = ({
return (
<div className={`row plugin-row${p.enabled ? ' is-enabled' : ''}`} key={p.id}>
<div className={`plugin-app-icon tone-${visual.tone}`}>{visual.icon}</div>
<PluginAppIcon plugin={p} size="md" />
<div className="row-main">
<div className="row-title">
<span className="plugin-row-name">{locText(p.name, locale, p.id)}</span>
@@ -439,7 +382,7 @@ export const PluginsPage: React.FC<Props> = ({
{desc && <div className="row-sub plugin-row-desc" title={desc}>{desc}</div>}
{!isBuiltin && (
<div className="row-sub plugin-row-meta">
<span className={`plugin-trust ${trust.cls}`}>{trust.icon}{p.publisher || trust.label}</span>
<PluginTrustBadge locale={locale} trust={p.trust} publisher={p.publisher} />
<span className="mono">v{p.version}</span>
{perms.length > 0 && (
<Tip label={tr('pluginPermissionsLabel', { list: perms.map((x) => x.name).join(', ') })}>
@@ -484,7 +427,7 @@ export const PluginsPage: React.FC<Props> = ({
) : (
<Switch
label={locText(p.name, locale, p.id)}
disabled={busyID === p.id || (p.enabled && p.in_use) || (!!safeMode && !isBuiltin)}
disabled={busyID === p.id || (!!safeMode && !isBuiltin)}
checked={p.enabled}
onChange={(checked) => void togglePlugin(p, checked)}
/>
@@ -529,7 +472,7 @@ export const PluginsPage: React.FC<Props> = ({
<div className="row" key={`${f.check}-${idx}`}>
<div className="row-main">
<div className="row-title">
<span className="badge badge-danger">{f.check}</span>
<span className="badge rg-p-badge badge-danger">{f.check}</span>
{f.target && <span className="mono">{f.target}</span>}
</div>
<div className="row-sub">{locText(f.localized, locale, f.message)}</div>
@@ -548,7 +491,7 @@ export const PluginsPage: React.FC<Props> = ({
<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 className={`badge rg-p-badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
<span>{locText(c.title, locale, c.id)}</span>
<span className="mono muted" style={{ fontSize: 'var(--fs-11)' }}>{c.id}</span>
</div>
@@ -576,7 +519,7 @@ export const PluginsPage: React.FC<Props> = ({
<div className="row" key={`pend-${f.check}-${idx}`}>
<div className="row-main">
<div className="row-title">
<span className="badge">{f.check}</span>
<span className="badge rg-p-badge">{f.check}</span>
{f.target && <span className="mono">{f.target}</span>}
</div>
<div className="row-sub">{locText(f.localized, locale, f.message)}</div>
@@ -587,7 +530,7 @@ export const PluginsPage: React.FC<Props> = ({
<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={`badge rg-p-badge${ex.declared ? '' : ' badge-danger'}`}>{ex.declared ? 'EXE' : 'UNLISTED'}</span>
<span className="mono">{ex.path}</span>
</div>
<div className="row-sub mono selectable">SHA-256: {ex.sha256}</div>
@@ -601,21 +544,6 @@ export const PluginsPage: React.FC<Props> = ({
)
}
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
@@ -632,22 +560,17 @@ export const PluginsPage: React.FC<Props> = ({
</div>
<div className="actions">
{activeTab === 'installed' && showSearch && (
<div className="plugins-search-wrap">
<Search size={13} className="plugins-search-icon" aria-hidden="true" />
<input
type="search"
className="input plugins-search"
aria-label={tr('pluginSearchPlaceholder')}
placeholder={tr('pluginSearchPlaceholder')}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
</div>
<PluginSearchInput
value={query}
onChange={setQuery}
placeholder={tr('pluginSearchPlaceholder')}
/>
)}
<IconButton
label={activeTab === 'market' ? tr('pluginMarketRefresh') : tr('refresh')}
icon={<RefreshCw size={16} />}
onClick={() => activeTab === 'market' ? void loadMarket({ forceRefresh: true }) : void reload()}
icon={<RefreshCw size={16} className={(activeTab === 'market' ? marketBusy : reloading) ? 'spin' : undefined} />}
disabled={activeTab === 'market' ? marketBusy : reloading}
onClick={() => activeTab === 'market' ? setMarketRefresh((n) => n + 1) : void manualReload()}
/>
<IconButton label={tr('pluginLinkDevBtn')} icon={<FolderOpen size={16} />} onClick={linkDevDir} />
<Button variant="primary" disabled={scanBusy} icon={<PackagePlus size={14} aria-hidden="true" />} onClick={importLocalZip}>
@@ -656,163 +579,33 @@ export const PluginsPage: React.FC<Props> = ({
</div>
</header>
<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 className="plugins-switch">
<Segmented
label={tr('sidebarPlugins')}
value={activeTab}
onChange={setActiveTab}
options={[
{ value: 'installed', label: tr('pluginTabInstalled') },
{ value: 'market', label: tr('pluginTabMarket') },
]}
/>
</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>
{marketOpened && (
<div hidden={activeTab !== 'market'}>
<PluginMarket
locale={locale}
safeMode={safeMode}
installed={plugins}
refreshSignal={marketRefresh}
onBusyChange={setMarketBusy}
onChanged={onMarketChanged}
onError={onError}
/>
</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>
) : (
{activeTab === 'installed' && (
<>
{showThemeHero && (
<section className="section">
@@ -872,10 +665,12 @@ export const PluginsPage: React.FC<Props> = ({
{activeTheme && activeTheme.theme_id !== 'builtin.theme.default' ? (
<div className="theme-scheme-strip">
<span className="muted" style={{ fontSize: 'var(--fs-12)' }}>{tr('pluginColorSchemes')}</span>
<div className="theme-scheme-chips">
<div className="theme-scheme-chips" role="radiogroup" aria-label={tr('pluginColorSchemes')}>
<button
type="button"
className={`plugin-cat-pill${!activeTheme.active_scheme ? ' is-active' : ''}`}
role="radio"
aria-checked={!activeTheme.active_scheme}
className={`plugin-pill${!activeTheme.active_scheme ? ' is-active' : ''}`}
onClick={() => void selectTheme(activeTheme.theme_id, '')}
>
{tr('pluginSchemeDefault')}
@@ -884,7 +679,9 @@ export const PluginsPage: React.FC<Props> = ({
<button
key={s.id}
type="button"
className={`plugin-cat-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
role="radio"
aria-checked={activeTheme.active_scheme === s.id}
className={`plugin-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
onClick={() => void selectTheme(activeTheme.theme_id, s.id)}
>
{s.seeds?.accent && <span className="plugins-scheme-dot" style={{ background: s.seeds.accent }} aria-hidden="true" />}
@@ -895,7 +692,9 @@ export const PluginsPage: React.FC<Props> = ({
<span className="hstack" style={{ gap: 2 }} key={s.id}>
<button
type="button"
className={`plugin-cat-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
role="radio"
aria-checked={activeTheme.active_scheme === s.id}
className={`plugin-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
onClick={() => void selectTheme(activeTheme.theme_id, s.id)}
>
{s.seeds?.accent && <span className="plugins-scheme-dot" style={{ background: s.seeds.accent }} aria-hidden="true" />}
@@ -933,7 +732,17 @@ export const PluginsPage: React.FC<Props> = ({
{!loading && <span className="section-count">{filteredBuiltins.length}</span>}
</div>
{loading ? (
<div className="list"><div className="row plugin-row"><span className="muted">…</span></div></div>
<div className="skeleton-list" role="status" aria-label={tr('sidebarPlugins')}>
{[0, 1, 2].map((i) => (
<div className="skeleton-row" key={i} aria-hidden="true">
<div className="skeleton-stack">
<div className="skeleton-bar w-title" />
<div className="skeleton-bar w-sub" />
</div>
<div className="skeleton-bar w-btn" />
</div>
))}
</div>
) : (
<div className="list">{filteredBuiltins.map(renderRow)}</div>
)}
@@ -966,7 +775,7 @@ export const PluginsPage: React.FC<Props> = ({
closeLabel={tr('close')}
onClose={() => { if (!scanBusy) setScanModal(null) }}
>
<div style={{ padding: 'var(--sp-4)', maxHeight: 440, overflow: 'auto' }}>
<div className="dialog-body">
{renderScanReportBody(scanModal.report)}
</div>
<div className="dialog-foot">
@@ -1000,7 +809,7 @@ export const PluginsPage: React.FC<Props> = ({
closeLabel={tr('close')}
onClose={() => { setApproveTarget(null); setApproveReport(null) }}
>
<div className="stack-3" style={{ padding: 'var(--sp-4)', maxHeight: 440, overflow: 'auto' }}>
<div className="dialog-body">
{(approveTarget.tier === 'L3' || (approveTarget.permissions ?? []).some((p) => p.name === 'ui:script')) && (
<div className="notice notice-warn">
<span className="notice-main">
@@ -1009,6 +818,7 @@ export const PluginsPage: React.FC<Props> = ({
</span>
</div>
)}
<RiskList locale={locale} risks={approveTarget.risks} />
<div className="list">
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginPublisherLicense')}</div><div className="row-sub">{approveTarget.publisher || '—'} · {approveTarget.license || '—'}</div></div></div>
{approveTarget.entry_path && (
@@ -1027,7 +837,7 @@ export const PluginsPage: React.FC<Props> = ({
<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 className={`badge rg-p-badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
<span>{locText(c.title, locale, c.id)}</span>
</div>
<div className="row-sub">{locText(c.summary, locale, '')}</div>
@@ -1037,7 +847,7 @@ export const PluginsPage: React.FC<Props> = ({
</div>
</div>
)}
<label className="hstack" style={{ cursor: 'pointer' }}>
<label className="choice">
<input type="checkbox" checked={approveChecked} onChange={(e) => setApproveChecked(e.target.checked)} />
<span>{tr('pluginApproveCheckbox')}</span>
</label>
@@ -1061,7 +871,7 @@ export const PluginsPage: React.FC<Props> = ({
closeLabel={tr('close')}
onClose={() => setSettingsTarget(null)}
>
<div style={{ padding: 'var(--sp-4)' }}>
<div className="dialog-body">
<SchemaForm
locale={locale}
schema={settingsTarget.settings}
@@ -1077,59 +887,53 @@ export const PluginsPage: React.FC<Props> = ({
</Modal>
)}
{removeTarget && (
<Modal
title={tr('pluginRemove')}
subtitle={locText(removeTarget.name, locale, removeTarget.id)}
closeLabel={tr('close')}
onClose={() => setRemoveTarget(null)}
{disableTarget && (
<ConfirmDialog
title={tr('pluginDisableInUseTitle')}
description={tr('pluginDisableInUseBody')}
cancelLabel={tr('cancel')}
confirmLabel={tr('pluginDisable')}
onCancel={() => setDisableTarget(null)}
onConfirm={() => {
const target = disableTarget
setDisableTarget(null)
void togglePlugin(target, false, true)
}}
>
<div style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
<span className="mono">{removeTarget.id}@{removeTarget.version}</span>
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setRemoveTarget(null)}>{tr('cancel')}</Button>
<Button
variant="danger"
onClick={() => {
const target = removeTarget
setRemoveTarget(null)
void removePlugin(target)
}}
>
{tr('pluginRemove')}
</Button>
</span>
</div>
</Modal>
<div className="row-sub">{locText(disableTarget.name, locale, disableTarget.id)}</div>
</ConfirmDialog>
)}
{removeTarget && (
<ConfirmDialog
title={tr('pluginRemove')}
description={locText(removeTarget.name, locale, removeTarget.id)}
cancelLabel={tr('cancel')}
confirmLabel={tr('pluginRemove')}
onCancel={() => setRemoveTarget(null)}
onConfirm={() => {
const target = removeTarget
setRemoveTarget(null)
void removePlugin(target)
}}
>
<div className="row-sub mono">{removeTarget.id}@{removeTarget.version}</div>
</ConfirmDialog>
)}
{deleteSchemeTarget && (
<Modal
<ConfirmDialog
title={tr('pluginDeleteScheme')}
subtitle={deleteSchemeTarget.name}
closeLabel={tr('close')}
onClose={() => setDeleteSchemeTarget(null)}
>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setDeleteSchemeTarget(null)}>{tr('cancel')}</Button>
<Button
variant="danger"
onClick={() => {
const target = deleteSchemeTarget
setDeleteSchemeTarget(null)
void deleteScheme(target.id)
}}
>
{tr('pluginDeleteScheme')}
</Button>
</span>
</div>
</Modal>
description={deleteSchemeTarget.name}
cancelLabel={tr('cancel')}
confirmLabel={tr('pluginDeleteScheme')}
onCancel={() => setDeleteSchemeTarget(null)}
onConfirm={() => {
const target = deleteSchemeTarget
setDeleteSchemeTarget(null)
void deleteScheme(target.id)
}}
/>
)}
{logTarget && (
@@ -1138,9 +942,9 @@ 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, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
{logTarget.text}
</pre>
<div className="dialog-body">
<pre className="plugin-log-pre mono selectable">{logTarget.text}</pre>
</div>
</Modal>
)}
@@ -1150,19 +954,19 @@ export const PluginsPage: React.FC<Props> = ({
closeLabel={tr('close')}
onClose={() => setSchemeEditorOpen(false)}
>
<div className="stack-3" style={{ padding: 'var(--sp-4)' }}>
<label className="stack-1">
<span>{tr('pluginSchemeName')}</span>
<input className="input" value={schemeName} onChange={(e) => setSchemeName(e.target.value)} placeholder={tr('pluginSchemePlaceholder')} />
<div className="dialog-body">
<label className="field">
<span className="field-label">{tr('pluginSchemeName')}</span>
<input className="input rg-p-input" value={schemeName} onChange={(e) => setSchemeName(e.target.value)} placeholder={tr('pluginSchemePlaceholder')} />
</label>
<label className="hstack">
<span>{tr('pluginAccentSeed')}</span>
<span className="field-label">{tr('pluginAccentSeed')}</span>
<input type="color" value={seedAccent} onChange={(e) => setSeedAccent(e.target.value)} />
<span className="mono">{seedAccent}</span>
</label>
<label className="stack-1">
<span>{tr('pluginSurfaceSeed')}</span>
<input className="input mono" value={seedSurface} onChange={(e) => setSeedSurface(e.target.value)} placeholder="#1d1e23" />
<label className="field">
<span className="field-label">{tr('pluginSurfaceSeed')}</span>
<input className="input rg-p-input mono" value={seedSurface} onChange={(e) => setSeedSurface(e.target.value)} placeholder="#1d1e23" />
</label>
</div>
<div className="dialog-foot">
+2 -2
View File
@@ -60,7 +60,7 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
<div className="row-sub task-inline">
<LoaderCircle size={14} className="spin" aria-hidden="true" />
{task.percent >= 0 && (
<span className="progress" aria-hidden="true">
<span className="progress rg-p-progress" aria-hidden="true">
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
</span>
)}
@@ -108,7 +108,7 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
{tr(active ? 'runtimeUpdate' : 'runtimeInstall')}
</Button>
) : !running && active && remote ? (
<span className="badge badge-ok">{tr('runtimeUpToDate')}</span>
<span className="badge rg-p-badge badge-ok">{tr('runtimeUpToDate')}</span>
) : null}
</div>
</div>
+3 -3
View File
@@ -53,7 +53,7 @@ export const SchemaForm: React.FC<Props> = ({
const eff = prop['x-effect']
if (!eff) return null
const label = t(locale, eff === 'immediate' ? 'effectImmediate' : 'effectNextStart')
return <span className={`badge ${eff === 'immediate' ? 'badge-ok' : ''}`}>{label}</span>
return <span className={`badge rg-p-badge ${eff === 'immediate' ? 'badge-ok' : ''}`}>{label}</span>
}
const renderControl = (k: string, prop: SettingProperty) => {
@@ -114,7 +114,7 @@ export const SchemaForm: React.FC<Props> = ({
return (
<input
type="password"
className="input"
className="input rg-p-input"
aria-label={label}
autoComplete="new-password"
placeholder={isMasked ? SECRET_MASK : undefined}
@@ -127,7 +127,7 @@ export const SchemaForm: React.FC<Props> = ({
return (
<input
type="text"
className="input"
className="input rg-p-input"
aria-label={label}
value={String(cur ?? '')}
onChange={(e) => setKey(k, e.target.value)}
+4 -4
View File
@@ -19,7 +19,7 @@ export const SendTextDialog: React.FC<Props> = ({ locale, vmName, guestToolsConn
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
<div className="dialog-body">
<Alert.Title className="dialog-title">{t(locale, 'sendTextTitle', { name: vmName })}</Alert.Title>
<Alert.Description className="dialog-desc">
@@ -27,7 +27,7 @@ export const SendTextDialog: React.FC<Props> = ({ locale, vmName, guestToolsConn
</Alert.Description>
<div className="field field-spaced">
<textarea
className="input textarea"
className="input rg-p-input textarea"
rows={4}
placeholder={t(locale, 'sendTextPlaceholder')}
value={text}
@@ -44,10 +44,10 @@ export const SendTextDialog: React.FC<Props> = ({ locale, vmName, guestToolsConn
</div>
<div className="dialog-foot">
<Alert.Cancel asChild>
<button type="button" className="btn">{t(locale, 'cancel')}</button>
<button type="button" className="btn rg-p-button">{t(locale, 'cancel')}</button>
</Alert.Cancel>
<Alert.Action asChild>
<button type="button" className="btn btn-primary" disabled={!canSend} onClick={() => onConfirm(text)}>
<button type="button" className="btn rg-p-button btn-primary" disabled={!canSend} onClick={() => onConfirm(text)}>
{t(locale, 'sendTextConfirm')}
</button>
</Alert.Action>
File diff suppressed because it is too large. Load diff
+60 -15
View File
@@ -2,12 +2,13 @@ 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, Task } from '../types'
import { getLocaleOptions, I18nKey, joinNotices, locText, t } from '../i18n'
import { AppState, DataRootCheck, DataRootChoice, Locale, MarketCatalogItem, ResolvedLocalePack, Task } from '../types'
import { Button } from '../ui/controls'
import { PopupSelect } from '../ui/settings'
import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format'
import { api } from '../wails'
import { PluginAppIcon } from './PluginAppIcon'
import { RuntimeOnline } from './RuntimeOnline'
interface Props {
@@ -17,6 +18,8 @@ interface Props {
stage: 'folder' | 'runtime'
runtimeTask: Task | null
onLocale: (l: Locale) => void
/** A plugin was installed or enabled; the app reloads plugin contributions. */
onPluginsChanged: () => void
onFolderDone: () => void
onFinish: () => void
onError: (title: string, e: unknown) => void
@@ -42,13 +45,16 @@ export const Setup: React.FC<Props> = (p) => {
type StepProps = Props & { tr: (k: I18nKey, v?: Record<string, string | number>) => string }
const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale, onFolderDone, onError }) => {
const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale, onPluginsChanged, onFolderDone, onError }) => {
const [choices, setChoices] = useState<DataRootChoice[]>([])
const [custom, setCustom] = useState('')
const [customMode, setCustomMode] = useState(false)
const [selected, setSelected] = useState('')
const [check, setCheck] = useState<DataRootCheck | null>(null)
const [busy, setBusy] = useState(false)
// A market language pack for the OS language, looked up once on first launch.
const [langPack, setLangPack] = useState<MarketCatalogItem | null>(null)
const [langPackOn, setLangPackOn] = useState(true)
useEffect(() => {
api.SuggestDataRoots().then((list) => {
@@ -57,12 +63,18 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
const rec = l.find((c) => c.recommended) ?? l[0]
if (rec) setSelected(rec.path)
}).catch((e) => onError(tr('failGeneric'), e))
api.SuggestLanguagePack().then((p) => { if (p?.entry) setLangPack(p) }).catch((e) => console.warn('[setup] SuggestLanguagePack failed:', e))
}, [])
useEffect(() => {
if (!selected) { setCheck(null); return }
let live = true
api.CheckDataRoot(selected).then((c) => { if (live) setCheck(c) }).catch(() => {})
api.CheckDataRoot(selected)
.then((c) => { if (live) setCheck(c) })
.catch((e) => {
if (live) setCheck(null)
console.warn('[setup] CheckDataRoot failed:', e)
})
return () => { live = false }
}, [selected])
@@ -75,14 +87,29 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
setBusy(true)
try {
await api.CompleteSetup(selected)
onFolderDone()
} catch (e) {
onError(tr('failGeneric'), e)
} finally {
setBusy(false)
return
}
// Plugins live in the data folder, so the pack installs once it exists.
// With the language left on "auto", enabling the pack is enough for the
// UI to switch to the OS language.
if (langPack && langPackOn) {
try {
const info = await api.InstallMarketPlugin(langPack.entry.id, false)
if (info && !info.enabled && !info.needs_approval) await api.EnablePlugin(info.id, false)
onPluginsChanged()
} catch (e) {
onError(tr('setupLangPackFailed'), e)
}
}
setBusy(false)
onFolderDone()
}
const osTag = state.detected_locale || locale
const option = (path: string, meta: React.ReactNode) => (
<label key={path} className="choice-card" data-selected={selected === path}>
<input type="radio" name="data-root" checked={selected === path} onChange={() => setSelected(path)} />
@@ -112,15 +139,15 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
{choices.map((c) => option(c.path, (
<>
{tr('setupFree', { n: c.free_gb.toFixed(0) })}
{c.recommended && <span className="badge badge-accent">{tr('setupRecommended')}</span>}
{c.system && <span className="badge">{tr('setupSystem')}</span>}
{c.external && <span className="badge badge-warn">{tr('setupExternal')}</span>}
{c.recommended && <span className="badge rg-p-badge badge-accent">{tr('setupRecommended')}</span>}
{c.system && <span className="badge rg-p-badge">{tr('setupSystem')}</span>}
{c.external && <span className="badge rg-p-badge badge-warn">{tr('setupExternal')}</span>}
</>
)))}
{customMode ? (
<div className="input-group">
<input
className="input mono"
className="input rg-p-input mono"
aria-label={tr('setupOther')}
value={custom}
placeholder="D:\VMs\reims-go"
@@ -143,6 +170,21 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
{customMode && check && check.path === custom && !check.error && (
<div className="hint">{tr('setupFree', { n: check.free_gb.toFixed(0) })}</div>
)}
{langPack && (
<label className="setup-langpack">
<input type="checkbox" checked={langPackOn} disabled={busy} onChange={(e) => setLangPackOn(e.target.checked)} />
<PluginAppIcon kind="locale" size="sm" />
<span className="setup-langpack-main">
{/* The pack's name and blurb in the OS language: that is who it is for. */}
<span className="setup-langpack-title">
{tr('setupLangPackOffer', { name: locText(langPack.entry.name, osTag, langPack.entry.id) })}
</span>
{locText(langPack.entry.description, osTag) && (
<span className="setup-langpack-sub">{locText(langPack.entry.description, osTag)}</span>
)}
</span>
</label>
)}
<div className="setup-foot">
<PopupSelect
label={tr('language')}
@@ -167,7 +209,7 @@ 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 gpuOK = !host.vulkan_probe_error && !!gpu && gpu.compat !== 'warn' && gpu.compat !== 'unsupported'
const recMem = recommendedMemoryGB(host)
return (
<>
@@ -191,7 +233,7 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
{host.whpx === 'missing' ? (
<Button variant="primary" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
) : (
<span className={`badge ${whpxOK ? 'badge-ok' : 'badge-warn'}`}>
<span className={`badge rg-p-badge ${whpxOK ? 'badge-ok' : 'badge-warn'}`}>
{tr(whpxOK ? 'whpxReady' : host.whpx === 'no_hypervisor' ? 'whpxNoHvShort' : 'whpxUnsupportedShort')}
</span>
)}
@@ -200,11 +242,14 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
<div className="row">
<div className="row-main">
<div className="row-title">{tr('setupGPU')}</div>
<div className="row-sub">{gpu ? shortGPUName(gpu.name) : tr('setupNoGPU')}</div>
{gpu && <div className="row-sub">{shortGPUName(gpu.name)}</div>}
{host.vulkan_probe_error ? (
<div className="row-sub warn-text">{tr('vulkanProbeFailed', { detail: host.vulkan_probe_error })}</div>
) : !gpu && <div className="row-sub">{tr('setupNoGPU')}</div>}
{gpuHint && <div className="row-sub warn-text">{gpuHint}</div>}
</div>
<div className="row-right">
<span className={`badge ${gpuOK ? 'badge-ok' : 'badge-warn'}`}>
<span className={`badge rg-p-badge ${gpuOK ? 'badge-ok' : 'badge-warn'}`}>
{tr(
gpuOK
? 'whpxReady'
@@ -227,7 +272,7 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
</div>
</div>
<div className="row-right">
<span className={`badge ${recMem >= 8 ? 'badge-ok' : 'badge-warn'}`}>{tr('setupRecMem', { n: recMem })}</span>
<span className={`badge rg-p-badge ${recMem >= 8 ? 'badge-ok' : 'badge-warn'}`}>{tr('setupRecMem', { n: recMem })}</span>
</div>
</div>
</div>
+78 -41
View File
@@ -1,10 +1,12 @@
import * as Ctx from '@radix-ui/react-context-menu'
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Pause, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
import React, { useRef } from 'react'
import { I18nKey, t } from '../i18n'
import { I18nKey, localeDir, t } from '../i18n'
import { Locale, VMListItem } from '../types'
import { vmRefKey } from '../lib/vmRef'
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
import { VersionArt } from './VersionArt'
import { VersionArt } from '../macos/VersionArt'
import { BrandMark, HostIcon } from '../ui/themeVisuals'
import { VMAction } from './VMPage'
export const HOST_ID = '__host__'
@@ -20,8 +22,12 @@ interface Props {
locale: Locale
vms: VMListItem[]
transitions: Record<string, string>
/** VM name → currently running action (disables conflicting context menu actions). */
busyActions?: Record<string, VMAction>
selected: string
hostReady: boolean
/** Whether the active runtime supports VM suspend/resume. */
canSuspend: boolean
onSelect: (id: string) => void
/** VM name → display name (its note); empty or missing shows the name. */
displayNames?: Record<string, string>
@@ -42,12 +48,12 @@ interface Props {
}
export const Sidebar: React.FC<Props> = ({
locale, vms, transitions, selected, hostReady, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot,
locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot,
}) => {
const tr = (k: I18nKey) => t(locale, k)
const listRef = useRef<HTMLDivElement>(null)
const ctxOpenedByPointerRef = useRef(false)
const ids = [...vms.map((v) => v.name), INSTALLERS_ID, PLUGINS_ID, HOST_ID, SETTINGS_ID, ABOUT_ID]
const ids = [...vms.map((v) => vmRefKey(v)), INSTALLERS_ID, PLUGINS_ID, HOST_ID, SETTINGS_ID, ABOUT_ID]
// Listbox keyboard model: ↑/↓/Home/End move selection and focus together.
const onKeyDown = (e: React.KeyboardEvent) => {
@@ -73,13 +79,18 @@ export const Sidebar: React.FC<Props> = ({
kind: ReturnType<typeof statusKind> | null,
onDoubleClick?: () => void,
dot?: boolean,
vm?: { state: string; driver: string; busy: boolean },
) => (
<button
key={id}
type="button"
role="option"
data-id={id}
className="nav-item"
className="nav-item rg-p-nav-item"
data-selected={selected === id ? 'true' : 'false'}
data-vm-state={vm?.state}
data-driver={vm?.driver}
data-busy={vm ? (vm.busy ? 'true' : 'false') : undefined}
aria-selected={selected === id}
aria-label={stateLabel ? t(locale, 'sidebarItemAria', { label, state: stateLabel }) : label}
tabIndex={selected === id || (!hasSelectedInList && id === ids[0]) ? 0 : -1}
@@ -94,6 +105,7 @@ export const Sidebar: React.FC<Props> = ({
<span className="hstack"><StatusShape kind={kind} /></span>
</Tip>
)}
{vm && <span className="rg-slot-anchor nav-item-trailing" data-rg-slot="nav.item.trailing" data-rg-key={id} aria-hidden="true" />}
</button>
)
@@ -101,35 +113,41 @@ export const Sidebar: React.FC<Props> = ({
<div className="sidebar-wrap">
<aside className="sidebar rg-p-sidebar">
<div className="sidebar-brand">
<img className="sidebar-brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
<BrandMark className="sidebar-brand-mark" />
<span className="sidebar-brand-name">Reims-Go</span>
</div>
<div className="rg-slot-anchor" data-rg-slot="sidebar.header" />
{updateCard}
<div className="sidebar-head rg-p-sidebar-head">
<span>{tr('sidebarVMs')}</span>
<IconButton small label={tr('newVM')} shortcut="Ctrl+N" icon={<Plus size={15} />} onClick={onNew} tipSide="right" />
<IconButton small label={tr('newVM')} shortcut="Ctrl+N" icon={<HostIcon name="new-vm"><Plus size={15} /></HostIcon>} onClick={onNew} tipSide="right" />
</div>
<div className="nav rg-p-nav" role="listbox" aria-label={tr('sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
<div className="nav-group nav-vms" role="group" aria-label={tr('sidebarVMs')}>
<div className="nav-group rg-p-nav-group nav-vms" role="group" aria-label={tr('sidebarVMs')}>
{vms.length === 0 && <div className="nav-empty rg-p-empty" data-rg-slot="empty.state">{tr('emptyVMs')}</div>}
{vms.map((vm) => {
const st = transitions[vm.name] ?? vm.state
const st = transitions[vmRefKey(vm)] ?? vm.state
const running = st === 'running'
const stopped = st === 'stopped'
const transitioning = st === 'starting' || st === 'stopping'
const suspended = st === 'suspended'
const transitioning = st === 'starting' || st === 'stopping' || st === 'suspending' || st === 'resuming'
const busyAction = Object.prototype.hasOwnProperty.call(busyActions, vm.name) ? busyActions[vm.name] : undefined
const vmBusy = !!busyAction
const label = displayNames[vm.name] || vm.name
const trigger = navBtn(
vm.name,
vmRefKey(vm),
label,
<VersionArt shape="tile" major={macosMajors[vm.name] ?? null} name={label} />,
'nav-icon-art',
t(locale, `state_${st}` as I18nKey),
statusKind(st),
onActivate ? () => onActivate(vm.name) : undefined,
onActivate ? () => onActivate(vmRefKey(vm)) : undefined,
undefined,
{ state: st, driver: vm.driver_id ?? '', busy: vmBusy || transitioning },
)
if (!onVMContextAction) return trigger
return (
<Ctx.Root key={vm.name}>
<Ctx.Root key={vmRefKey(vm)} dir={localeDir(locale)}>
<Ctx.Trigger
asChild
onContextMenu={(e) => {
@@ -140,7 +158,7 @@ export const Sidebar: React.FC<Props> = ({
</Ctx.Trigger>
<Ctx.Portal>
<Ctx.Content
className="menu"
className="menu rg-p-menu"
onCloseAutoFocus={(e) => {
if (
ctxOpenedByPointerRef.current
@@ -151,49 +169,68 @@ export const Sidebar: React.FC<Props> = ({
}}
>
{stopped && (
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'start')}>
<Play size={14} /> {tr('start')}
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'start')}>
<HostIcon name="start"><Play size={14} /></HostIcon> {tr('start')}
</Ctx.Item>
)}
{suspended && (
<>
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy || !canSuspend} onSelect={() => onVMContextAction(vmRefKey(vm), 'resume')}>
<HostIcon name="resume"><Play size={14} /></HostIcon> {tr('resume')}
</Ctx.Item>
{!canSuspend && <Ctx.Label className="menu-group-label">{tr('resumeUnavailable')}</Ctx.Label>}
<Ctx.Item className="menu-item rg-p-menu-item danger" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'discardSuspend')}>
<Power size={14} /> {tr('discardSuspend')}
</Ctx.Item>
</>
)}
{running && (
<>
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'focus')}>
<AppWindow size={14} /> {tr('showWindow')}
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'focus')}>
<HostIcon name="window"><AppWindow size={14} /></HostIcon> {tr('showWindow')}
</Ctx.Item>
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'screenshot')}>
<Camera size={14} /> {tr('copyScreenshot')}
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'fullscreen')}>
<HostIcon name="fullscreen"><Maximize2 size={14} /></HostIcon> {tr('toggleFullscreen')}
</Ctx.Item>
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'stop')}>
<Square size={14} /> {tr('stop')}
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'screenshot')}>
<HostIcon name="screenshot"><Camera size={14} /></HostIcon> {tr('copyScreenshot')}
</Ctx.Item>
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'restart')}>
<RotateCw size={14} /> {tr('restart')}
{canSuspend && (
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'suspend')}>
<HostIcon name="suspend"><Pause size={14} /></HostIcon> {tr('suspend')}
</Ctx.Item>
)}
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'stop')}>
<HostIcon name="stop"><Square size={14} /></HostIcon> {tr('stop')}
</Ctx.Item>
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'restart')}>
<HostIcon name="restart"><RotateCw size={14} /></HostIcon> {tr('restart')}
</Ctx.Item>
</>
)}
{(running || transitioning) && (
<Ctx.Item className="menu-item danger" onSelect={() => onVMContextAction(vm.name, 'forceStop')}>
<Power size={14} /> {tr('forceStop')}
<Ctx.Item className="menu-item rg-p-menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onVMContextAction(vmRefKey(vm), 'forceStop')}>
<HostIcon name="force-stop"><Power size={14} /></HostIcon> {tr('forceStop')}
</Ctx.Item>
)}
<Ctx.Separator className="menu-sep" />
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'settings')}>
<Settings size={14} /> {tr('settingsEllipsis')}
<Ctx.Item className="menu-item rg-p-menu-item" disabled={suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'settings')}>
<HostIcon name="settings"><Settings size={14} /></HostIcon> {tr('settingsEllipsis')}
</Ctx.Item>
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openSharedFolder')}>
<FolderOpen size={14} /> {tr('openSharedFolder')}
<Ctx.Item className="menu-item rg-p-menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openSharedFolder')}>
<HostIcon name="folder"><FolderOpen size={14} /></HostIcon> {tr('openSharedFolder')}
</Ctx.Item>
{stopped && (
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'cloneVM')}>
<CopyPlus size={14} /> {tr('cloneVM')}
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'cloneVM')}>
<HostIcon name="clone"><CopyPlus size={14} /></HostIcon> {tr('cloneVM')}
</Ctx.Item>
)}
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openFolder')}>
<FolderOpen size={14} /> {tr('openFolder')}
<Ctx.Item className="menu-item rg-p-menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openFolder')}>
<HostIcon name="folder"><FolderOpen size={14} /></HostIcon> {tr('openFolder')}
</Ctx.Item>
<Ctx.Separator className="menu-sep" />
<Ctx.Item className="menu-item danger" disabled={running || transitioning} onSelect={() => onVMContextAction(vm.name, 'delete')}>
<Trash size={14} /> {tr('delete')}
<Ctx.Item className="menu-item rg-p-menu-item danger" disabled={vmBusy || running || suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'delete')}>
<HostIcon name="delete"><Trash size={14} /></HostIcon> {tr('delete')}
</Ctx.Item>
</Ctx.Content>
</Ctx.Portal>
@@ -201,7 +238,7 @@ export const Sidebar: React.FC<Props> = ({
)
})}
</div>
<div className="nav-group nav-system" role="group" aria-label={tr('sidebarSystem')}>
<div className="nav-group rg-p-nav-group nav-system" role="group" aria-label={tr('sidebarSystem')}>
{navBtn(
INSTALLERS_ID,
tr('sidebarInstallers'),
@@ -213,7 +250,7 @@ export const Sidebar: React.FC<Props> = ({
{navBtn(
PLUGINS_ID,
tr('sidebarPlugins'),
<Puzzle size={13} />,
<HostIcon name="plugin"><Puzzle size={13} /></HostIcon>,
'nav-icon-plugins',
safeMode ? tr('pluginSafeModeShort') : '',
safeMode ? 'warn' : null,
@@ -229,7 +266,7 @@ export const Sidebar: React.FC<Props> = ({
{navBtn(
SETTINGS_ID,
tr('sidebarSettings'),
<Settings size={13} />,
<HostIcon name="settings"><Settings size={13} /></HostIcon>,
'nav-icon-settings',
'',
null,
@@ -237,7 +274,7 @@ export const Sidebar: React.FC<Props> = ({
{navBtn(
ABOUT_ID,
tr('settingsAbout'),
<Info size={13} />,
<HostIcon name="info"><Info size={13} /></HostIcon>,
'nav-icon-about',
'',
null,
+31 -13
View File
@@ -1,7 +1,8 @@
import * as Menu from '@radix-ui/react-dropdown-menu'
import { Check, PanelLeft } from 'lucide-react'
import React, { useRef, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { I18nKey, localeDir, t } from '../i18n'
import { useVMStats } from '../lib/vmStats'
import { Locale } from '../types'
import { Tip } from '../ui/controls'
import type { ThemeMode } from './AppSettingsPage'
@@ -26,7 +27,7 @@ interface Props {
canDark?: boolean
onThemeMode: (mode: ThemeMode) => void
/** The selected VM and its current state, or null on the system pages. */
vm: { name: string; state: string; busy: boolean } | null
vm: { name: string; driver_id?: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean } | null
onNewVM: () => void
onVMAction: (action: VMAction) => void
onVMSettings: () => void
@@ -61,17 +62,25 @@ export const TitleMenus: React.FC<Props> = ({
const running = vm?.state === 'running'
const stopped = vm?.state === 'stopped'
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping'
const suspended = vm?.state === 'suspended'
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming'
const vmBusy = !vm || vm.busy
const canFullscreen = running && vm?.graphics !== 'vmware-svga'
const stats = useVMStats(vm?.driver_id ?? '', canFullscreen && vm ? vm.name : null, running)
const fullscreenLabel = !canFullscreen || !stats?.running
? tr('toggleFullscreen')
: stats.window_fullscreen
? tr('exitFullscreen')
: tr('enterFullscreen')
const item = (label: string, onSelect: () => void, opts: { shortcut?: string; disabled?: boolean; danger?: boolean } = {}) => (
<Menu.Item className={`menu-item${opts.danger ? ' danger' : ''}`} disabled={opts.disabled} onSelect={onSelect}>
<Menu.Item className={`menu-item rg-p-menu-item${opts.danger ? ' danger' : ''}`} disabled={opts.disabled} onSelect={onSelect}>
<span className="menu-label">{label}</span>
{opts.shortcut && <kbd className="menu-shortcut">{opts.shortcut}</kbd>}
</Menu.Item>
)
const check = (label: string, checked: boolean, onSelect: () => void, shortcut?: string) => (
<Menu.CheckboxItem className="menu-item menu-item-check" checked={checked} onSelect={onSelect}>
<Menu.CheckboxItem className="menu-item rg-p-menu-item menu-item-check" checked={checked} onSelect={onSelect}>
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
<span className="menu-label">{label}</span>
{shortcut && <kbd className="menu-shortcut">{shortcut}</kbd>}
@@ -81,6 +90,7 @@ export const TitleMenus: React.FC<Props> = ({
// `indented`: the menu has check marks, so every row shares their indent.
const menu = (id: MenuId, label: string, content: React.ReactNode, indented = false) => (
<Menu.Root
dir={localeDir(locale)}
modal={false}
open={menuState.id === id}
onOpenChange={(o) => {
@@ -136,8 +146,8 @@ export const TitleMenus: React.FC<Props> = ({
</Menu.Trigger>
<Menu.Portal>
<Menu.Content
className={`menu titlebar-menu-content${indented ? ' menu-indented' : ''}`}
data-menubar-switch={menuState.id === id && menuState.switched ? 'true' : undefined}
className={`menu rg-p-menu titlebar-menu-content${indented ? ' menu-indented' : ''}`}
data-menubar-switch={menuState.switched ? 'true' : undefined}
align="start"
sideOffset={4}
collisionPadding={8}
@@ -150,8 +160,10 @@ export const TitleMenus: React.FC<Props> = ({
pointerClosedRef.current = false
}}
onPointerDownOutside={(e) => {
const target = e.target as Node | null
if (target && navRef.current?.contains(target)) {
const orig = e.detail.originalEvent
const target = e.target instanceof Element ? e.target : (e.target as Node | null)?.parentElement ?? null
const trigger = target?.closest('button.titlebar-menu') ?? null
if (orig.button === 0 && !orig.ctrlKey && trigger && navRef.current?.contains(trigger)) {
e.preventDefault()
return
}
@@ -210,16 +222,22 @@ export const TitleMenus: React.FC<Props> = ({
<Menu.Separator className="menu-sep" />
{running
? item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy })
: item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })}
: suspended
? item(tr('resume'), () => onVMAction('resume'), { shortcut: vm?.canSuspend ? 'Ctrl+Enter' : undefined, disabled: vmBusy || !vm?.canSuspend })
: item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })}
{suspended && !vm?.canSuspend && <Menu.Label className="menu-group-label">{tr('resumeUnavailable')}</Menu.Label>}
{item(fullscreenLabel, () => onVMAction('fullscreen'), { disabled: vmBusy || !canFullscreen })}
{item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })}
{item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })}
{item(tr('restart'), () => onVMAction('restart'), { disabled: vmBusy || !running })}
{item(tr('copyScreenshot'), () => onVMAction('screenshot'), { disabled: vmBusy || !running })}
<Menu.Separator className="menu-sep" />
{item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm })}
{item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm || suspended || transitioning })}
{item(tr('openFolder'), () => onVMAction('openFolder'), { disabled: !vm })}
<Menu.Separator className="menu-sep" />
{suspended && item(tr('discardSuspend'), () => onVMAction('discardSuspend'), { danger: true, disabled: vmBusy })}
{item(tr('forceStop'), () => onVMAction('forceStop'), { danger: true, disabled: !vm || !(running || transitioning) })}
{item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || transitioning })}
{item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || suspended || transitioning })}
</>
))}
{menu('view', tr('menuView'), (
@@ -232,7 +250,7 @@ export const TitleMenus: React.FC<Props> = ({
{(['light', 'dark', 'system'] as const).map((m) => (
<Menu.RadioItem
key={m}
className="menu-item menu-item-check"
className="menu-item rg-p-menu-item menu-item-check"
value={m}
disabled={(m === 'light' && !canLight) || (m === 'dark' && !canDark) || (m === 'system' && (!canLight || !canDark))}
>
+228 -91
View File
@@ -7,6 +7,7 @@ import {
Archive,
Camera,
Check,
ChevronDown,
ChevronRight,
Code2,
Copy,
@@ -22,9 +23,12 @@ import {
Info,
Keyboard,
LifeBuoy,
Maximize2,
MemoryStick,
Minimize2,
Monitor,
Network,
Pause,
Pencil,
Play,
Plus,
@@ -38,8 +42,8 @@ import {
Upload,
UserRound,
} from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { I18nKey, locText, t } from '../i18n'
import React, { useEffect, useId, useRef, useState } from 'react'
import { I18nKey, localeDir, locText, t } from '../i18n'
import {
controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel,
parseMemoryGB, pendingChangeText, resolveGuestLang, sshCommand,
@@ -49,14 +53,19 @@ import { DiskSnapshot, HostReport, Locale, PendingChange, PluginUIContributions,
import { api } from '../wails'
import { Button, IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
import { Switch } from '../ui/settings'
import { VersionArt } from './VersionArt'
import { HostIcon } from '../ui/themeVisuals'
import { VersionArt } from '../macos/VersionArt'
export type VMAction =
| 'start'
| 'suspend'
| 'resume'
| 'discardSuspend'
| 'stop'
| 'forceStop'
| 'restart'
| 'focus'
| 'fullscreen'
| 'screenshot'
| 'eject'
| 'finishInstall'
@@ -83,12 +92,15 @@ interface Props {
locale: Locale
/** The VM's identifier (folder, CLI, reims-ctl). */
name: string
driverID: string
/** What the user calls it (its note); empty shows `name`. */
displayName: string
onDisplayNameSaved: (displayName: string) => void
/** macOS major version (26, 15, …) for the artwork shown before a first frame; null if unknown. */
macosMajor: number | null
state: string
/** Whether the active runtime supports VM suspend/resume. */
canSuspend: boolean
/** Whether the native VM-window installation guide is currently active for this boot. */
guideActive: boolean
/** Whether the builtin.install-guide plugin is enabled. */
@@ -117,6 +129,40 @@ type Tone = '' | ' warn' | ' high'
const meterTone = (pct: number, warn = 75, high = 90): Tone => (pct >= high ? ' high' : pct >= warn ? ' warn' : '')
const clampPct = (v: number) => Math.min(100, Math.max(0, v))
function ShutdownButton({ locale, busyAction, onAction }: Pick<Props, 'locale' | 'busyAction' | 'onAction'>) {
const [mode, setMode] = useState<'stop' | 'forceStop'>('stop')
const forced = mode === 'forceStop'
const variant = forced ? 'danger' : 'secondary'
const label = t(locale, 'shutdownMode')
const Icon = forced ? Power : Square
return (
<div className="shutdown-button" role="group" aria-label={label}>
<Button variant={variant} icon={<Icon size={13} aria-hidden="true" />} busy={busyAction === mode}
disabled={!!busyAction} onClick={() => onAction(mode)}>{t(locale, mode)}</Button>
<Menu.Root dir={localeDir(locale)}>
<Menu.Trigger asChild>
<Button variant={variant} disabled={!!busyAction} aria-label={label} title={label}>
<ChevronDown size={13} aria-hidden="true" />
</Button>
</Menu.Trigger>
<Menu.Portal>
<Menu.Content className="menu rg-p-menu" align="end" sideOffset={4} collisionPadding={8}>
<Menu.RadioGroup value={mode} onValueChange={(v) => setMode(v === 'forceStop' ? 'forceStop' : 'stop')}>
{(['stop', 'forceStop'] as const).map((action) => (
<Menu.RadioItem key={action} value={action} className={`menu-item rg-p-menu-item menu-item-check${action === 'forceStop' ? ' danger' : ''}`}>
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
{t(locale, action)}
</Menu.RadioItem>
))}
</Menu.RadioGroup>
</Menu.Content>
</Menu.Portal>
</Menu.Root>
</div>
)
}
interface Spec {
key: string
/** Shown only in the wide, single-column layout. */
@@ -129,31 +175,37 @@ interface Spec {
}
export const VMPage: React.FC<Props> = ({
locale, name, displayName, onDisplayNameSaved, macosMajor, state, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const busy = busyAction !== undefined
const running = state === 'running'
const suspended = state === 'suspended'
const guestToolsLocked = suspended || state === 'suspending' || state === 'resuming'
const resumeHintId = useId()
const guestToolsHintId = useId()
const installing = !!detail && (detail.has_installer || detail.recovery_mode)
const transitioning = state === 'starting' || state === 'stopping'
const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming'
// Polled here rather than in App so each tick re-renders only this page.
const stats = useVMStats(name, running)
const stats = useVMStats(driverID, name, running)
// Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM
// runs, otherwise the last frame saved. Skipped while this window is hidden;
// the backend also skips it while the VM's own window is in front.
const [thumb, setThumb] = useState<VMThumbnail | null>(null)
useEffect(() => { setThumb(null) }, [name])
useEffect(() => { setThumb(null) }, [driverID, name])
useEffect(() => {
let live = true
const pull = () => {
if (document.hidden) return
api.GetVMThumbnail(name).then((t) => { if (live && t?.data_url) setThumb(t) }).catch(() => {})
api.GetVMThumbnailWithDriver(driverID, name)
.then((t) => { if (live && t?.data_url) setThumb(t) })
.catch((e) => console.warn('[vm] GetVMThumbnailWithDriver failed:', e))
}
pull()
const timer = running ? window.setInterval(pull, 15000) : undefined
return () => { live = false; if (timer) window.clearInterval(timer) }
}, [name, running])
}, [driverID, name, running])
// Display name, stored as the VM's note (.reims-go-note). Clicking the title
// edits it in place; clearing it (or typing the name) falls back to the name.
@@ -193,29 +245,29 @@ export const VMPage: React.FC<Props> = ({
setMoreMenuOpen(false)
setSshMenuOpen(false)
setSshUserDialog(false)
}, [name])
}, [driverID, name])
useEffect(() => {
let live = true
api.GetVMSSHUser(name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
api.GetVMSSHUserWithDriver(driverID, name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
return () => { live = false }
}, [name])
}, [driverID, name])
const openSSHTerminal = () => {
api.OpenSSHTerminal(name, sshUser).catch((e) => onError(tr('failSSH'), e))
api.OpenSSHTerminalWithDriver(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e))
}
const writeSSHConfig = () => {
api.WriteSSHConfig(name, sshUser)
api.WriteSSHConfigWithDriver(driverID, name, sshUser)
.then((alias) => onToast(tr('toastSSHConfigWritten', { alias })))
.catch((e) => onError(tr('failSSH'), e))
}
const openVSCodeSSH = () => {
api.OpenVSCodeSSH(name, sshUser).catch((e) => onError(tr('failSSH'), e))
api.OpenVSCodeSSHWithDriver(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e))
}
const saveSSHUser = async () => {
const next = sshUserDraft.trim()
setSshUserDialog(false)
try {
await api.SetVMSSHUser(name, next)
await api.SetVMSSHUserWithDriver(driverID, name, next)
setSshUser(next)
onToast(tr('toastSSHUserSaved'))
} catch (e) {
@@ -237,7 +289,7 @@ export const VMPage: React.FC<Props> = ({
const toggleGuideStep = (step: number) => {
setDoneSteps((prev) => {
const next = prev.includes(step) ? prev.filter((x) => x !== step) : [...prev, step]
try { localStorage.setItem(guideKey, JSON.stringify(next)) } catch {}
try { localStorage.setItem(guideKey, JSON.stringify(next)) } catch (e) { console.warn('[vm] persist guide progress failed:', e) }
return next
})
}
@@ -253,7 +305,7 @@ export const VMPage: React.FC<Props> = ({
const loadSnapshots = () => {
if (!showSnapshots) { setSnapshots([]); return }
api.ListSnapshots(name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([]))
api.ListSnapshotsWithDriver(driverID, name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([]))
}
useEffect(() => {
setCreatingSnap(false)
@@ -261,14 +313,14 @@ export const VMPage: React.FC<Props> = ({
setRestoreTarget(null)
loadSnapshots()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [name, showSnapshots, state])
}, [driverID, name, showSnapshots, state])
const handleCreateSnapshot = async () => {
const label = snapDraft.trim()
if (!label) return
setSnapBusy('create')
try {
await api.CreateSnapshot(name, label)
await api.CreateSnapshotWithDriver(driverID, name, label)
setSnapDraft('')
setCreatingSnap(false)
onToast(tr('toastSnapshotCreated', { name: label }))
@@ -283,7 +335,7 @@ export const VMPage: React.FC<Props> = ({
setRestoreTarget(null)
setSnapBusy(`restore:${snapName}`)
try {
await api.RestoreSnapshot(name, snapName)
await api.RestoreSnapshotWithDriver(driverID, name, snapName)
onToast(tr('toastSnapshotRestored', { name: snapName }))
loadSnapshots()
} catch (e) {
@@ -295,7 +347,7 @@ export const VMPage: React.FC<Props> = ({
const handleDeleteSnapshot = async (snapName: string) => {
setSnapBusy(`delete:${snapName}`)
try {
await api.DeleteSnapshot(name, snapName)
await api.DeleteSnapshotWithDriver(driverID, name, snapName)
onToast(tr('toastSnapshotDeleted', { name: snapName }))
loadSnapshots()
} catch (e) {
@@ -315,7 +367,7 @@ export const VMPage: React.FC<Props> = ({
}
// One primary action per state (docs/design-guidelines.md §4): Start while
// stopped, Show Window while running. Ctrl+Enter triggers it (App.tsx).
// stopped, Resume while suspended, Show Window while running. Ctrl+Enter triggers it (App.tsx).
let primary: React.ReactNode = null
let secondary: React.ReactNode = null
if (state === 'stopped') {
@@ -326,10 +378,29 @@ export const VMPage: React.FC<Props> = ({
</Button>
</Tip>
)
} else if (suspended) {
primary = (
<Tip label={tr('resume')} shortcut={PRIMARY_SHORTCUT} disabled={!canSuspend}>
<Button
variant={canSuspend ? 'primary' : 'secondary'}
icon={<Play size={14} aria-hidden="true" />}
busy={busyAction === 'resume'}
disabled={busy || !canSuspend}
aria-describedby={!canSuspend ? resumeHintId : undefined}
onClick={() => onAction('resume')}
>
{tr('resume')}
</Button>
</Tip>
)
} else if (state === 'starting') {
primary = <Button variant="primary" busy>{tr('state_starting')}</Button>
} else if (state === 'stopping') {
primary = <Button busy>{tr('state_stopping')}</Button>
} else if (state === 'suspending') {
primary = <Button busy>{tr('state_suspending')}</Button>
} else if (state === 'resuming') {
primary = <Button variant="primary" busy>{tr('state_resuming')}</Button>
} else if (running) {
const showLabel = tr(guideActive ? 'showInstallGuide' : 'showWindow')
primary = (
@@ -340,7 +411,14 @@ export const VMPage: React.FC<Props> = ({
</Tip>
)
secondary = (
<Button icon={<Square size={12} aria-hidden="true" />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')}>{tr('stop')}</Button>
<>
{canSuspend && (
<Button icon={<Pause size={13} aria-hidden="true" />} busy={busyAction === 'suspend'} disabled={busy} onClick={() => onAction('suspend')}>
{tr('suspend')}
</Button>
)}
<ShutdownButton key={name} locale={locale} busyAction={busyAction} onAction={onAction} />
</>
)
} else if (state === 'broken') {
primary = <Button variant="primary" icon={<Terminal size={14} aria-hidden="true" />} onClick={onViewLogs}>{tr('viewLogs')}</Button>
@@ -349,6 +427,7 @@ export const VMPage: React.FC<Props> = ({
// "More" menu, grouped by purpose; destructive items last (docs/design-guidelines.md §5.2).
const menu = (
<Menu.Root
dir={localeDir(locale)}
open={moreMenuOpen}
onOpenChange={(o) => {
if (o) morePointerClosed.current = false
@@ -359,7 +438,7 @@ export const VMPage: React.FC<Props> = ({
<Menu.Trigger asChild>
<button
type="button"
className="icon-btn"
className="icon-btn rg-p-icon-button"
aria-label={tr('more')}
onPointerDown={() => { moreOpenedByPointer.current = true }}
onKeyDown={(e) => {
@@ -374,7 +453,7 @@ export const VMPage: React.FC<Props> = ({
</Tip>
<Menu.Portal>
<Menu.Content
className="menu"
className="menu rg-p-menu"
align="end"
sideOffset={4}
collisionPadding={8}
@@ -403,17 +482,24 @@ export const VMPage: React.FC<Props> = ({
>
{running && (
<>
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('restart')}>
<RotateCw size={14} /> {tr('restart')}
{detail?.graphics !== 'vmware-svga' && (
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('fullscreen')}>
{stats?.window_fullscreen
? <><Minimize2 size={14} /> {tr('exitFullscreen')}</>
: <><Maximize2 size={14} /> {tr('enterFullscreen')}</>}
</Menu.Item>
)}
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('restart')}>
<HostIcon name="restart"><RotateCw size={14} /></HostIcon> {tr('restart')}
</Menu.Item>
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('sendText')}>
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('sendText')}>
<Keyboard size={14} /> {tr('sendText')}
</Menu.Item>
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('type')}>
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('type')}>
<Keyboard size={14} /> {tr('typeClipboard')}
</Menu.Item>
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('screenshot')}>
<Camera size={14} /> {tr('copyScreenshot')}
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('screenshot')}>
<HostIcon name="screenshot"><Camera size={14} /></HostIcon> {tr('copyScreenshot')}
</Menu.Item>
<Menu.Separator className="menu-sep" />
</>
@@ -421,35 +507,35 @@ export const VMPage: React.FC<Props> = ({
{detail && (
<>
{installing ? (
<Menu.Item className="menu-item" disabled={busy || transitioning} onSelect={() => onAction('finishInstall')}>
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy || suspended || transitioning} onSelect={() => onAction('finishInstall')}>
<LifeBuoy size={14} /> {tr('finishInstall')}
</Menu.Item>
) : (
<>
<Menu.Item className="menu-item" disabled={busy || transitioning} onSelect={() => onAction('enterRecovery')}>
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy || suspended || transitioning} onSelect={() => onAction('enterRecovery')}>
<LifeBuoy size={14} /> {tr('enterRecovery')}
</Menu.Item>
<Menu.Item className="menu-item" disabled={running || transitioning || busy} onSelect={() => onAction('cloneVM')}>
<CopyPlus size={14} /> {tr('cloneVM')}
<Menu.Item className="menu-item rg-p-menu-item" disabled={running || suspended || transitioning || busy} onSelect={() => onAction('cloneVM')}>
<HostIcon name="clone"><CopyPlus size={14} /></HostIcon> {tr('cloneVM')}
</Menu.Item>
</>
)}
<Menu.Item className="menu-item" onSelect={onOpenAffinity}>
<Menu.Item className="menu-item rg-p-menu-item" onSelect={onOpenAffinity}>
<Cpu size={14} /> {tr('affinityMenu')}
</Menu.Item>
<Menu.Item className="menu-item" onSelect={() => { renameFromMenu.current = true; startRename() }}>
<Menu.Item className="menu-item rg-p-menu-item" onSelect={() => { renameFromMenu.current = true; startRename() }}>
<Pencil size={14} /> {tr('displayNameEditEllipsis')}
</Menu.Item>
<Menu.Separator className="menu-sep" />
</>
)}
<Menu.Item className="menu-item" onSelect={() => onAction('openFolder')}>
<FolderOpen size={14} /> {tr('openFolder')}
<Menu.Item className="menu-item rg-p-menu-item" onSelect={() => onAction('openFolder')}>
<HostIcon name="folder"><FolderOpen size={14} /></HostIcon> {tr('openFolder')}
</Menu.Item>
<Menu.Item className="menu-item" onSelect={onViewLogs}>
<Terminal size={14} /> {tr('viewLogs')}
<Menu.Item className="menu-item rg-p-menu-item" onSelect={onViewLogs}>
<HostIcon name="logs"><Terminal size={14} /></HostIcon> {tr('viewLogs')}
</Menu.Item>
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('exportDiagnostics')}>
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('exportDiagnostics')}>
<Archive size={14} /> {tr('exportDiagnostics')}
</Menu.Item>
{(pluginUI?.menus ?? [])
@@ -457,7 +543,7 @@ export const VMPage: React.FC<Props> = ({
.map((m) => (
<Menu.Item
key={`${m.pluginId}:${m.id}`}
className="menu-item"
className="menu-item rg-p-menu-item"
onSelect={() => {
void api.InvokePluginCommand(m.pluginId ?? '', m.command, { vm: name })
.then(() => onToast(locText(m.title, locale, m.id)))
@@ -468,13 +554,18 @@ export const VMPage: React.FC<Props> = ({
</Menu.Item>
))}
<Menu.Separator className="menu-sep" />
{(running || transitioning) && (
<Menu.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onAction('forceStop')}>
<Power size={14} /> {tr('forceStop')}
{suspended && (
<Menu.Item className="menu-item rg-p-menu-item danger" disabled={busy} onSelect={() => onAction('discardSuspend')}>
<Power size={14} /> {tr('discardSuspend')}
</Menu.Item>
)}
<Menu.Item className="menu-item danger" disabled={running || transitioning || busy} onSelect={onDelete}>
<Trash size={14} /> {tr('delete')}
{(running || transitioning) && (
<Menu.Item className="menu-item rg-p-menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onAction('forceStop')}>
<HostIcon name="force-stop"><Power size={14} /></HostIcon> {tr('forceStop')}
</Menu.Item>
)}
<Menu.Item className="menu-item rg-p-menu-item danger" disabled={running || suspended || transitioning || busy} onSelect={onDelete}>
<HostIcon name="delete"><Trash size={14} /></HostIcon> {tr('delete')}
</Menu.Item>
</Menu.Content>
</Menu.Portal>
@@ -553,13 +644,25 @@ export const VMPage: React.FC<Props> = ({
onCopy(rows.join('\n'))
}
const pillClass = running ? ' is-running' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : ''
const pillClass = running ? ' is-running' : suspended ? ' is-suspended' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : ''
const dropStyle = detail && !installing
? ({ '--wails-drop-target': 'drop' } as React.CSSProperties)
: undefined
const formatSuspendTime = (iso?: string) => {
if (!iso) return ''
const ms = Date.parse(iso)
if (!Number.isFinite(ms)) return ''
try {
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(ms))
} catch {
return ''
}
}
return (
<div className="page vm-page vm-page-drop rg-p-vm-page" style={dropStyle}>
<div className="page vm-page vm-page-drop rg-p-vm-page" data-vm-state={state} data-driver={driverID} style={dropStyle}>
{dropping && (
<div className="drop-banner" role="status" aria-live="polite">
<Upload size={16} aria-hidden="true" />
@@ -578,10 +681,10 @@ export const VMPage: React.FC<Props> = ({
thumb={thumb}
art={<VersionArt shape="screen" className="vm-screen-art" major={macosMajor} name={shownName} />}
running={running}
startLabel={tr('start')}
startLabel={suspended ? tr('resume') : tr('start')}
showLabel={tr('showWindow')}
shotLabel={tr('copyScreenshot')}
onStart={state === 'stopped' && !busy ? () => onAction('start') : undefined}
onStart={!busy && (state === 'stopped' || (suspended && canSuspend)) ? () => onAction(suspended ? 'resume' : 'start') : undefined}
onShow={running && !busy ? () => onAction('focus') : undefined}
onScreenshot={running && !busy ? () => onAction('screenshot') : undefined}
/>
@@ -618,13 +721,17 @@ export const VMPage: React.FC<Props> = ({
<span>{tr(`state_${state}` as I18nKey)}</span>
{running && stats && stats.uptime_seconds > 0 && <span className="vm-hero-uptime">· {formatUptime(stats.uptime_seconds, locale)}</span>}
</div>
<div className="vm-hero-actions">
<span className="rg-slot-anchor" data-rg-slot="vm.header.trailing" />
<div className="vm-hero-actions rg-p-vm-actions">
{primary}
{secondary}
<Tip label={tr('settings')} shortcut="Ctrl+,">
<Button icon={<Settings size={14} aria-hidden="true" />} disabled={!detail} onClick={onSettings}>{tr('settingsEllipsis')}</Button>
<Tip label={suspended ? tr('suspendedSettingsHint') : tr('settings')} shortcut={suspended ? undefined : 'Ctrl+,'}>
<span>
<Button icon={<Settings size={14} aria-hidden="true" />} disabled={!detail || suspended || transitioning} onClick={onSettings}>{tr('settingsEllipsis')}</Button>
</span>
</Tip>
{menu}
<span className="rg-slot-anchor" data-rg-slot="vm.toolbar" />
</div>
</section>
@@ -657,6 +764,29 @@ export const VMPage: React.FC<Props> = ({
</div>
)}
{suspended && (() => {
const suspTime = formatSuspendTime(detail?.suspend_info?.created_at)
const suspSize = detail?.suspend_info?.vmstate_size
? formatBytes(detail.suspend_info.vmstate_size, locale)
: (detail?.memory ? formatMemory(detail.memory, locale) : '—')
return (
<div className="notice notice-info">
<span className="notice-main">
<Pause size={15} className="notice-icon" aria-hidden="true" />
<span className="notice-text">
<span className="notice-title">{tr('suspendedNoticeTitle')}</span>
<span className="notice-sub">
{suspTime
? tr('suspendedNoticeDescWithTime', { time: suspTime, size: suspSize })
: tr('suspendedNoticeDesc', { size: suspSize })}
</span>
{!canSuspend && <span id={resumeHintId} className="notice-sub">{tr('resumeUnavailable')}</span>}
</span>
</span>
</div>
)
})()}
{pending.length > 0 && (
<div className="notice notice-info">
<span className="notice-main">
@@ -727,10 +857,10 @@ export const VMPage: React.FC<Props> = ({
: 'guideKindOnline'
if (installGuideEnabled) {
return (
<section className="card" aria-labelledby="guide-title">
<section className="card rg-p-card" aria-labelledby="guide-title">
<h2 className="card-title" id="guide-title">
{tr('guideTitle')}{' '}
<span className="badge">{tr(badgeKey)}</span>
<span className="badge rg-p-badge">{tr(badgeKey)}</span>
</h2>
<p className="card-desc">{tr('guideStartHint')}</p>
<div className="card-foot">
@@ -779,10 +909,10 @@ export const VMPage: React.FC<Props> = ({
)
}
return (
<section className="card" aria-labelledby="guide-title">
<section className="card rg-p-card" aria-labelledby="guide-title">
<h2 className="card-title" id="guide-title">
{tr('guideTitle')}{' '}
<span className={`badge ${isOffline ? 'badge-ok' : ''}`}>{tr(badgeKey)}</span>
<span className={`badge rg-p-badge ${isOffline ? 'badge-ok' : ''}`}>{tr(badgeKey)}</span>
</h2>
{!hasInstaller ? (
<>
@@ -843,9 +973,15 @@ export const VMPage: React.FC<Props> = ({
const gtConnected = stats?.guest_tools_connected ?? detail.guest_tools_connected ?? false
const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || ''
const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false
const needsUpgrade = gtConnected && (detail.guest_tools_agent_version ?? 0) > 0 && (detail.guest_tools_agent_version ?? 0) < 3
const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 10
const gtAttachPending = running && pending.some((p) => p.field === 'guest_tools' && p.to === 'attached')
// Plugin switched off: show the state and hide controls that would only fail.
const gtOff = !!detail.guest_tools_disabled
const gtAttached = detail.guest_tools_attached
const showToolsAction = !gtOff && (gtAttached || !gtConnected || needsUpgrade)
const toolsAction = gtAttached ? 'detachGuestTools' : 'attachGuestTools'
const toolsActionLabel = gtAttached ? 'detachGuestTools' : needsUpgrade ? 'gtUpdate' : 'gtInstall'
// One status word per state; how files are shared goes in the tooltip.
let gtTone: 'ok' | 'warn' | 'idle' = 'idle'
@@ -864,7 +1000,7 @@ export const VMPage: React.FC<Props> = ({
} else {
gtStatus = tr('gtStatusNone'); gtTip = tr('gtNotInstalledDesc')
}
const showInstallCmd = !gtOff && detail.guest_tools_attached && (!gtConnected || needsUpgrade)
const showInstallCmd = !gtOff && detail.guest_tools_attached && !gtAttachPending && (!gtConnected || needsUpgrade)
const sshText = sshUser ? `ssh -p ${detail.ssh_port} ${sshUser}@127.0.0.1` : sshCommand(detail.ssh_port)
return (
@@ -885,6 +1021,7 @@ export const VMPage: React.FC<Props> = ({
{tr('sshOpenTerminal')}
</Button>
<Menu.Root
dir={localeDir(locale)}
open={sshMenuOpen}
onOpenChange={(o) => {
if (o) sshPointerClosed.current = false
@@ -895,7 +1032,7 @@ export const VMPage: React.FC<Props> = ({
<Menu.Trigger asChild>
<button
type="button"
className="icon-btn sm"
className="icon-btn rg-p-icon-button sm"
aria-label={tr('sshMore')}
onPointerDown={() => { sshOpenedByPointer.current = true }}
onKeyDown={(e) => {
@@ -910,7 +1047,7 @@ export const VMPage: React.FC<Props> = ({
</Tip>
<Menu.Portal>
<Menu.Content
className="menu"
className="menu rg-p-menu"
align="end"
sideOffset={4}
collisionPadding={8}
@@ -931,14 +1068,14 @@ export const VMPage: React.FC<Props> = ({
}
}}
>
<Menu.Item className="menu-item" onSelect={writeSSHConfig}>
<Menu.Item className="menu-item rg-p-menu-item" onSelect={writeSSHConfig}>
<FileCode2 size={14} /> {tr('sshWriteConfig')}
</Menu.Item>
<Menu.Item className="menu-item" onSelect={openVSCodeSSH}>
<Menu.Item className="menu-item rg-p-menu-item" onSelect={openVSCodeSSH}>
<Code2 size={14} /> {tr('sshOpenVSCode')}
</Menu.Item>
<Menu.Separator className="menu-sep" />
<Menu.Item className="menu-item" onSelect={() => { setSshUserDraft(sshUser); setSshUserDialog(true) }}>
<Menu.Item className="menu-item rg-p-menu-item" onSelect={() => { setSshUserDraft(sshUser); setSshUserDialog(true) }}>
<UserRound size={14} /> {tr('sshSetUser')}
</Menu.Item>
</Menu.Content>
@@ -958,20 +1095,20 @@ export const VMPage: React.FC<Props> = ({
</span>
</Tip>
</div>
{suspended && showToolsAction && (
<span id={guestToolsHintId} className="hint">{tr('suspendedGuestToolsHint')}</span>
)}
<div className="conn-ctrl">
{gtOff ? null : detail.guest_tools_attached ? (
<Button busy={busyAction === 'detachGuestTools'} disabled={busy} onClick={() => onAction('detachGuestTools')}>
{tr('detachGuestTools')}
</Button>
) : (!gtConnected || needsUpgrade) && (
{showToolsAction && (
<Button
variant={detail.guest_tools_configured ? 'secondary' : 'primary'}
icon={<Disc size={13} aria-hidden="true" />}
busy={busyAction === 'attachGuestTools'}
disabled={busy}
onClick={() => onAction('attachGuestTools')}
variant={gtAttached || detail.guest_tools_configured || guestToolsLocked ? 'secondary' : 'primary'}
icon={gtAttached ? undefined : <Disc size={13} aria-hidden="true" />}
busy={busyAction === toolsAction}
disabled={busy || guestToolsLocked}
aria-describedby={suspended ? guestToolsHintId : undefined}
onClick={() => onAction(toolsAction)}
>
{needsUpgrade ? tr('gtUpdate') : tr('gtInstall')}
{tr(toolsActionLabel)}
</Button>
)}
</div>
@@ -1027,16 +1164,16 @@ export const VMPage: React.FC<Props> = ({
<section className="section">
<div className="section-title">
<span className="hstack">
<History size={14} aria-hidden="true" />
<HostIcon name="snapshot"><History size={14} aria-hidden="true" /></HostIcon>
<span>{tr('snapshotsTitle')}</span>
<span className="snap-meta-hint">· {tr('snapshotHint')}</span>
</span>
<Tip label={running || transitioning ? tr('snapshotStopFirst') : tr('snapshotCreate')}>
<Tip label={running || suspended || transitioning ? tr('snapshotStopFirst') : tr('snapshotCreate')}>
<span>
<Button
variant="ghost"
icon={<Plus size={13} aria-hidden="true" />}
disabled={running || transitioning || !!snapBusy}
disabled={running || suspended || transitioning || !!snapBusy}
onClick={() => setCreatingSnap((v) => !v)}
>
{tr('snapshotCreate')}
@@ -1048,7 +1185,7 @@ export const VMPage: React.FC<Props> = ({
{creatingSnap && (
<div className="snap-create-bar">
<input
className="input"
className="input rg-p-input"
value={snapDraft}
maxLength={64}
spellCheck={false}
@@ -1082,7 +1219,7 @@ export const VMPage: React.FC<Props> = ({
<Button
icon={<RotateCcw size={13} aria-hidden="true" />}
busy={snapBusy === `restore:${s.name}`}
disabled={running || transitioning || !!snapBusy}
disabled={running || suspended || transitioning || !!snapBusy}
onClick={() => setRestoreTarget(s.name)}
>
{tr('snapshotRestore')}
@@ -1092,7 +1229,7 @@ export const VMPage: React.FC<Props> = ({
label={tr('snapshotDelete')}
icon={<Trash size={14} />}
busy={snapBusy === `delete:${s.name}`}
disabled={running || transitioning || !!snapBusy}
disabled={running || suspended || transitioning || !!snapBusy}
onClick={() => void handleDeleteSnapshot(s.name)}
/>
</div>
@@ -1143,13 +1280,13 @@ export const VMPage: React.FC<Props> = ({
<Alert.Root open onOpenChange={(open) => { if (!open) setSshUserDialog(false) }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
<div className="dialog-body">
<Alert.Title className="dialog-title">{tr('sshUserTitle')}</Alert.Title>
<Alert.Description className="dialog-desc">{tr('sshUserDesc')}</Alert.Description>
<div className="field field-spaced">
<input
className="input mono"
className="input rg-p-input mono"
value={sshUserDraft}
spellCheck={false}
autoComplete="off"
@@ -1161,9 +1298,9 @@ export const VMPage: React.FC<Props> = ({
</div>
</div>
<div className="dialog-foot">
<Alert.Cancel asChild><button type="button" className="btn">{tr('cancel')}</button></Alert.Cancel>
<Alert.Cancel asChild><button type="button" className="btn rg-p-button">{tr('cancel')}</button></Alert.Cancel>
<Alert.Action asChild>
<button type="button" className="btn btn-primary" onClick={() => void saveSSHUser()}>{tr('save')}</button>
<button type="button" className="btn rg-p-button btn-primary" onClick={() => void saveSSHUser()}>{tr('save')}</button>
</Alert.Action>
</div>
</Alert.Content>
@@ -1175,15 +1312,15 @@ export const VMPage: React.FC<Props> = ({
<Alert.Root open onOpenChange={(open) => { if (!open) setRestoreTarget(null) }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<Alert.Content className="dialog rg-p-dialog sm" data-tone="danger">
<div className="dialog-body">
<Alert.Title className="dialog-title">{tr('snapshotRestoreTitle', { name: restoreTarget })}</Alert.Title>
<Alert.Description className="dialog-desc">{tr('snapshotRestoreDesc')}</Alert.Description>
</div>
<div className="dialog-foot">
<Alert.Cancel asChild><button type="button" className="btn">{tr('cancel')}</button></Alert.Cancel>
<Alert.Cancel asChild><button type="button" className="btn rg-p-button">{tr('cancel')}</button></Alert.Cancel>
<Alert.Action asChild>
<button type="button" className="btn btn-danger" onClick={() => void handleRestoreSnapshot(restoreTarget)}>
<button type="button" className="btn rg-p-button btn-danger" onClick={() => void handleRestoreSnapshot(restoreTarget)}>
{tr('snapshotRestore')}
</button>
</Alert.Action>
+143
View File
@@ -0,0 +1,143 @@
import React, { useEffect, useId, useRef } from 'react'
// Strokes of the Reims-Go wordmark (scripts/brand/wordmark.py), in pen order.
// Coordinates sit in the generator's baseline frame (translate 4 107).
type Stroke =
| { kind: 'path'; d: string; ink: 'ink' | 'dash' | 'brand' }
| { kind: 'dot'; cx: number; cy: number; r: number }
const STROKES: Stroke[] = [
{ kind: 'path', ink: 'ink', d: 'M7.5 -7.5V-36A24 28.5 0 0 1 31.5 -64.5' },
{ kind: 'path', ink: 'ink', d: 'M50.5 -36H107.5A28.5 28.5 0 1 0 100.18 -16.93' },
{ kind: 'path', ink: 'ink', d: 'M133.5 -64.5V-7.5' },
{ kind: 'dot', cx: 133.5, cy: -94, r: 9 },
{ kind: 'path', ink: 'ink', d: 'M159.5 -7.5V-36A22 28.5 0 0 1 203.5 -36V-7.5M203.5 -36A22 28.5 0 0 1 247.5 -36V-7.5' },
{ kind: 'path', ink: 'ink', d: 'M311.05 -59.02A21 14.25 0 0 0 273.5 -50.25A21 14.25 0 0 0 294.5 -36A21 14.25 0 0 1 315.5 -21.75A21 14.25 0 0 1 277.95 -12.98' },
{ kind: 'path', ink: 'dash', d: 'M340.5 -36H358.5' },
{ kind: 'path', ink: 'brand', d: 'M440.5 -36A28.5 28.5 0 1 1 440.5 -36.01' },
{ kind: 'path', ink: 'brand', d: 'M440.5 -64.5V0A28.5 22.5 0 0 1 387.32 11.25' },
{ kind: 'path', ink: 'brand', d: 'M523.5 -36A28.5 28.5 0 1 1 523.5 -36.01' },
]
// Pen timing, in ms. Writing speed is constant, so long strokes take longer.
const PX_PER_MS = 0.62
const LIFT_MS = 70 // pen lift between strokes
const DOT_MS = 140
const HOLD_MS = 900 // finished word stays on screen
const FADE_MS = 420
const REST_MS = 260
const STROKE_EASE = 'cubic-bezier(0.45, 0.05, 0.35, 1)'
interface Props {
/** Rendered width in px; height follows the wordmark's aspect ratio. */
width?: number
label?: string
className?: string
}
/**
* The Reims-Go wordmark written stroke by stroke, on a loop. Used while
* waiting on network I/O. With reduced motion it shows the finished word
* with a slow pulse instead.
*/
export const WordmarkLoader: React.FC<Props> = ({ width = 168, label, className }) => {
const svgRef = useRef<SVGSVGElement>(null)
const gid = `wm-${useId().replace(/[^a-zA-Z0-9_-]/g, '')}`
useEffect(() => {
const svg = svgRef.current
if (!svg || typeof svg.animate !== 'function') return
if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return
const els = Array.from(svg.querySelectorAll<SVGGeometryElement>('[data-stroke]'))
const spans = els.map((el) => {
if (el.tagName.toLowerCase() === 'circle') return DOT_MS
const len = typeof el.getTotalLength === 'function' ? el.getTotalLength() : 60
return Math.max(90, len / PX_PER_MS)
})
const writeEnd = spans.reduce((sum, s) => sum + s, 0) + LIFT_MS * (spans.length - 1)
const total = writeEnd + HOLD_MS + FADE_MS + REST_MS
const at = (ms: number) => Math.min(1, ms / total)
const holdEnd = at(writeEnd + HOLD_MS)
const fadeEnd = at(writeEnd + HOLD_MS + FADE_MS)
let t = 0
const anims = els.map((el, i) => {
const s = at(t)
const e = at(t + spans[i])
t += spans[i] + LIFT_MS
const isDot = el.tagName.toLowerCase() === 'circle'
// Opacity hides the round cap that a fully-offset dash still paints.
const frames: Keyframe[] = isDot
? [
{ offset: 0, opacity: 0, transform: 'scale(0.2)' },
{ offset: s, opacity: 0, transform: 'scale(0.2)', easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)' },
{ offset: e, opacity: 1, transform: 'scale(1)' },
{ offset: holdEnd, opacity: 1, transform: 'scale(1)' },
{ offset: fadeEnd, opacity: 0, transform: 'scale(1)' },
{ offset: 1, opacity: 0, transform: 'scale(0.2)' },
]
: [
{ offset: 0, opacity: 0, strokeDashoffset: 1 },
{ offset: s, opacity: 0, strokeDashoffset: 1 },
{ offset: Math.min(e, s + 0.0005), opacity: 1, strokeDashoffset: 1, easing: STROKE_EASE },
{ offset: e, opacity: 1, strokeDashoffset: 0 },
{ offset: holdEnd, opacity: 1, strokeDashoffset: 0 },
{ offset: fadeEnd, opacity: 0, strokeDashoffset: 0 },
{ offset: 1, opacity: 0, strokeDashoffset: 1 },
]
return el.animate(frames, { duration: total, iterations: Infinity, fill: 'both' })
})
svg.dataset.animated = 'true'
return () => {
anims.forEach((a) => a.cancel())
delete svg.dataset.animated
}
}, [])
return (
<div className={`wordmark-loader${className ? ` ${className}` : ''}`} role="status" aria-live="polite">
<svg
ref={svgRef}
className="wordmark-loader-svg"
viewBox="0 0 539 141"
width={width}
height={Math.round((width * 141) / 539)}
aria-hidden="true"
>
<defs>
<linearGradient id={gid} gradientUnits="userSpaceOnUse" x1="376" y1="0" x2="531" y2="0">
<stop offset="0" stopColor="#3b8cff" />
<stop offset="0.5" stopColor="#6d5dfc" />
<stop offset="1" stopColor="#ff7a9a" />
</linearGradient>
</defs>
<g transform="translate(4 107)" fill="none" strokeWidth="15" strokeLinecap="round" strokeLinejoin="round">
{STROKES.map((s, i) => s.kind === 'dot' ? (
<circle
key={i}
data-stroke=""
className="wordmark-loader-dot"
cx={s.cx}
cy={s.cy}
r={s.r}
style={{ transformOrigin: 'center', transformBox: 'fill-box' }}
/>
) : (
<path
key={i}
data-stroke=""
className={`wordmark-loader-${s.ink}`}
d={s.d}
pathLength={1}
strokeDasharray="1 1"
stroke={s.ink === 'brand' ? `url(#${gid})` : undefined}
/>
))}
</g>
</svg>
{label && <span className="wordmark-loader-label">{label}</span>}
</div>
)
}
+23 -3
View File
@@ -14,6 +14,13 @@ export const coreZh: Record<string, string> = {
"collapseLogs": "收起日志",
"copy": "复制",
"copyTechInfo": "复制技术信息",
"dataRootChooseOther": "选择其他数据目录",
"dataRootChooseTitle": "选择数据目录",
"dataRootReadOnlyDetail": "详细信息",
"dataRootReadOnlyFolder": "数据目录",
"dataRootReadOnlyTitle": "数据目录暂时无法使用",
"dataRootRepair": "修复版本记录",
"dataRootRetry": "重试",
"delete": "删除…",
"deleteEllipsis": "删除…",
"displays": "显示器数量",
@@ -39,7 +46,7 @@ export const coreZh: Record<string, string> = {
"footerMemTip": "系统内存:已用 {used} GB / 共 {total} GB(可用 {avail} GB)",
"footerMemValue": "{used} / {total} GB",
"footerRunningVMs": "{n, plural, other {# 台运行中}}",
"forceStop": "强制关机",
"forceStop": "硬关机",
"gpuErrMissingExt": "缺少必需 Vulkan 扩展({ext}),请更新显卡驱动或改用 VMware SVGA",
"gpuErrVulkanCpu": "软件 Vulkan 实现不满足 vGPU 加速要求,请改用 VMware SVGA",
"gpuErrVulkanTooOld": "Vulkan {ver} 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA",
@@ -108,6 +115,8 @@ export const coreZh: Record<string, string> = {
"panelLoadFailed": "面板加载失败",
"pauseDownload": "暂停下载",
"pluginSafeModeShort": "安全模式",
"quitFailed": "已取消退出",
"quitInProgress": "正在退出…",
"refresh": "刷新",
"resLooksLike": "看起来像 {w} × {h}",
"resizeLogPanel": "拖动调整日志高度",
@@ -122,8 +131,9 @@ export const coreZh: Record<string, string> = {
"shortcutBarFullscreen": "切换全屏",
"shortcutBarRelease": "释放键盘和鼠标",
"showSidebar": "显示侧边栏",
"shutdownMode": "关机方式",
"sidebarHost": "内核",
"sidebarInstallers": "安装包",
"sidebarInstallers": "镜像",
"sidebarItemAria": "{label},{state}",
"sidebarLabel": "侧边栏",
"sidebarPlugins": "插件",
@@ -196,6 +206,13 @@ export const coreEn: Record<string, string> = {
"collapseLogs": "Hide logs",
"copy": "Copy",
"copyTechInfo": "Copy technical details",
"dataRootChooseOther": "Choose another data folder",
"dataRootChooseTitle": "Choose data folder",
"dataRootReadOnlyDetail": "Details",
"dataRootReadOnlyFolder": "Data folder",
"dataRootReadOnlyTitle": "This data folder can’t be used right now",
"dataRootRepair": "Repair version record",
"dataRootRetry": "Try again",
"delete": "Delete…",
"deleteEllipsis": "Delete…",
"displays": "Displays",
@@ -290,6 +307,8 @@ export const coreEn: Record<string, string> = {
"panelLoadFailed": "Panel failed to load",
"pauseDownload": "Pause download",
"pluginSafeModeShort": "Safe mode",
"quitFailed": "Quit canceled",
"quitInProgress": "Quitting…",
"refresh": "Refresh",
"resLooksLike": "Looks like {w} × {h}",
"resizeLogPanel": "Drag to resize log panel",
@@ -304,8 +323,9 @@ export const coreEn: Record<string, string> = {
"shortcutBarFullscreen": "Toggle full screen",
"shortcutBarRelease": "Release keyboard and mouse",
"showSidebar": "Show sidebar",
"shutdownMode": "Shutdown mode",
"sidebarHost": "Engine",
"sidebarInstallers": "Installers",
"sidebarInstallers": "Images",
"sidebarItemAria": "{label}, {state}",
"sidebarLabel": "Sidebar",
"sidebarPlugins": "Plugins",
+51 -9
View File
@@ -14,7 +14,15 @@ export const pluginsZh: Record<string, string> = {
"pluginColorSchemes": "配色方案",
"pluginColorSchemesHint": "修改种子色派生整套界面色阶",
"pluginDeleteScheme": "删除方案",
"pluginDisable": "停用",
"pluginDisableInUseBody": "停用后,这个插件管理的虚拟机会显示为「驱动不可用」,不能启动或修改。虚拟机文件和挂起状态都会保留,重新启用即可恢复。运行中的虚拟机需要先停止或挂起。",
"pluginDisableInUseTitle": "停用仍有虚拟机的插件",
"pluginDone": "完成",
"pluginEnableLater": "暂不启用",
"pluginEnableNow": "启用",
"pluginEnablePromptBody": "要现在启用吗?启用前请了解它会做什么:",
"pluginEnablePromptNoRisk": "此插件没有声明额外能力,可以放心启用。",
"pluginEnablePromptTitle": "「{name}」已安装",
"pluginEntryPath": "入口路径",
"pluginExternalSection": "已安装插件",
"pluginFailDeleteScheme": "删除配色方案失败",
@@ -41,23 +49,28 @@ export const pluginsZh: Record<string, string> = {
"pluginLinkDevTitle": "链接本地开发插件目录",
"pluginLogEmpty": "暂无日志记录",
"pluginLogTitle": "{id} — 日志",
"pluginMarketDownloading": "下载中",
"pluginMarketEmpty": "当前插件市场暂无可用条目,你仍可导入本地 .zip 插件包或配置自定义市场索引地址",
"pluginMarketIncludeAlpha": "显示 Alpha 测试通道",
"pluginMarketFeedEnd": "共 {count} 个插件",
"pluginMarketIncompatible": "不兼容",
"pluginMarketInstall": "安装",
"pluginMarketInstalled": "已安装",
"pluginMarketInstalling": "安装中",
"pluginMarketKindAll": "全部",
"pluginMarketKindDriver": "客体驱动",
"pluginMarketKindLocale": "语言包",
"pluginMarketKindRuntime": "运行时",
"pluginMarketKindTemplate": "模板",
"pluginMarketKindTheme": "主题",
"pluginMarketKindTool": "工具",
"pluginMarketLoading": "正在读取插件市场",
"pluginMarketRefresh": "刷新索引",
"pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签",
"pluginMarketSourceCache": "本地缓存",
"pluginMarketSourceFallback": "离线回退",
"pluginMarketSourceRemote": "在线索引",
"pluginMarketStaleBanner": "远程插件市场暂不可达,当前显示本地缓存或内置回退索引",
"pluginMarketSyncing": "正在同步插件市场",
"pluginMarketUpdate": "更新至 v{version}",
"pluginMarketUpdateShort": "更新",
"pluginMarketVersionTip": "已安装 v{installed},可更新至 v{version}",
"pluginMarketWithdrawn": "已撤回",
"pluginMarketWithdrawnInstalledWarn": "已安装插件 {id} 已从市场撤回:{reason}",
"pluginMarketWithdrawnInstead": "建议改用:{target}",
@@ -68,6 +81,14 @@ export const pluginsZh: Record<string, string> = {
"pluginPublisherLicense": "发布者 / 许可",
"pluginRemove": "卸载",
"pluginRequestedPerms": "请求权限",
"pluginRiskBackground": "该插件可以持久化运行后台代码",
"pluginRiskClipboard": "该插件可以读写系统剪贴板",
"pluginRiskFiles": "该插件会读写文件",
"pluginRiskInput": "该插件会拦截或改写键盘与鼠标输入",
"pluginRiskNative": "该插件包含原生程序,拥有您 Windows 账户的全部权限",
"pluginRiskNetwork": "该插件会访问网络",
"pluginRiskUi": "该插件会修改您看到的用户界面",
"pluginRiskVm": "该插件可以控制虚拟机",
"pluginScanAdvisoriesSection": "提示信息与可执行文件",
"pluginScanArchiveTitle": "导入前安全检查",
"pluginScanBlockedBtn": "已拦截,无法安装",
@@ -90,7 +111,7 @@ export const pluginsZh: Record<string, string> = {
"pluginStatePending": "等待依赖",
"pluginSurfaceSeed": "画布种子色(可选)",
"pluginTabInstalled": "已安装",
"pluginTabMarket": "插件市场",
"pluginTabMarket": "市场",
"pluginThemeEmptyHint": "导入本地主题包(.zip)后可在此切换外观与配色方案",
"pluginThemeHint": "同一时刻仅启用一个主题包,停用后自动回退默认主题",
"pluginThemePackLabel": "主题包",
@@ -116,7 +137,15 @@ export const pluginsEn: Record<string, string> = {
"pluginColorSchemes": "Color schemes",
"pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp",
"pluginDeleteScheme": "Delete scheme",
"pluginDisable": "Disable",
"pluginDisableInUseBody": "Its VMs will show as “Driver unavailable” and can’t be started or changed. Their files and any suspended state are kept; turning the plugin back on restores them. Stop or suspend any running VM first.",
"pluginDisableInUseTitle": "Disable a plugin that still has VMs",
"pluginDone": "Done",
"pluginEnableLater": "Not now",
"pluginEnableNow": "Enable",
"pluginEnablePromptBody": "Enable it now? Here is what it can do:",
"pluginEnablePromptNoRisk": "This plugin declares no extra capabilities.",
"pluginEnablePromptTitle": "“{name}” is installed",
"pluginEntryPath": "Entry path",
"pluginExternalSection": "Installed plugins",
"pluginFailDeleteScheme": "Couldn’t delete color scheme",
@@ -143,23 +172,28 @@ export const pluginsEn: Record<string, string> = {
"pluginLinkDevTitle": "Link local dev plugin folder",
"pluginLogEmpty": "No log entries yet",
"pluginLogTitle": "{id} — Log",
"pluginMarketDownloading": "Downloading",
"pluginMarketEmpty": "No plugins available in the market index yet. You can still import local .zip packages or configure a custom index URL.",
"pluginMarketIncludeAlpha": "Include alpha channel",
"pluginMarketFeedEnd": "{count} plugins",
"pluginMarketIncompatible": "Incompatible",
"pluginMarketInstall": "Install",
"pluginMarketInstalled": "Installed",
"pluginMarketInstalling": "Installing",
"pluginMarketKindAll": "All",
"pluginMarketKindDriver": "Drivers",
"pluginMarketKindLocale": "Languages",
"pluginMarketKindRuntime": "Runtimes",
"pluginMarketKindTemplate": "Templates",
"pluginMarketKindTheme": "Themes",
"pluginMarketKindTool": "Tools",
"pluginMarketLoading": "Loading the plugin market",
"pluginMarketRefresh": "Refresh index",
"pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags",
"pluginMarketSourceCache": "Cached index",
"pluginMarketSourceFallback": "Offline fallback",
"pluginMarketSourceRemote": "Online index",
"pluginMarketStaleBanner": "Remote market index is unreachable; showing cached or offline fallback data",
"pluginMarketSyncing": "Syncing the plugin market",
"pluginMarketUpdate": "Update to v{version}",
"pluginMarketUpdateShort": "Update",
"pluginMarketVersionTip": "v{installed} installed, v{version} available",
"pluginMarketWithdrawn": "Withdrawn",
"pluginMarketWithdrawnInstalledWarn": "Installed plugin {id} has been withdrawn: {reason}",
"pluginMarketWithdrawnInstead": "Recommended replacement: {target}",
@@ -170,6 +204,14 @@ export const pluginsEn: Record<string, string> = {
"pluginPublisherLicense": "Publisher / License",
"pluginRemove": "Remove",
"pluginRequestedPerms": "Requested permissions",
"pluginRiskBackground": "Can keep code running in the background",
"pluginRiskClipboard": "Can read and write the system clipboard",
"pluginRiskFiles": "Reads and writes files",
"pluginRiskInput": "Intercepts or rewrites keyboard and mouse input",
"pluginRiskNative": "Ships a native program with full rights of your Windows account",
"pluginRiskNetwork": "Accesses the network",
"pluginRiskUi": "Changes the interface you see",
"pluginRiskVm": "Can control your virtual machines",
"pluginScanAdvisoriesSection": "Advisories \u0026 executables",
"pluginScanArchiveTitle": "Pre-install security check",
"pluginScanBlockedBtn": "Blocked — cannot install",
+222 -8
View File
@@ -3,8 +3,12 @@ import { registerBuiltinDomain } from '../runtime'
export const settingsZh: Record<string, string> = {
"aboutCommunity": "社区与支持",
"aboutCopyDiscord": "复制邀请链接",
"aboutCopyQQGroup": "复制群号",
"aboutDiscord": "Discord 社区",
"aboutDiscordSub": "交流使用体验、硬件兼容反馈、Alpha 测试与插件开发",
"aboutIssueSub": "遇到问题或有功能建议,在 GitHub 提交 Issue",
"aboutJoinDiscord": "加入服务器",
"aboutJoinQQGroup": "加入群聊",
"aboutLicensesOpenGitHub": "在 GitHub 查看",
"aboutLicensesSub": "Apache-2.0 协议与第三方开源组件声明(离线可查)",
@@ -96,6 +100,10 @@ export const settingsZh: Record<string, string> = {
"coresUnit": "核",
"cpuOverHint": "留给 Windows 的线程不足 2 个,电脑可能变卡",
"cpuRecHint": "推荐 {rec} 核 · 本机共 {n} 线程",
"defenderCopyCommand": "复制排除命令",
"defenderExclusionDesc": "实时扫描可能拖慢虚拟机磁盘访问。可在 Windows 安全中心为数据目录 {path} 添加排除项。",
"defenderExclusionTitle": "Windows Defender 实时防护排除建议",
"defenderOpenSecurity": "打开 Windows 安全中心",
"diskCompactAction": "立即回收",
"diskCompactDesc": "把 macOS 里已删除文件占用的空间还给 Windows,过程中需要与当前占用差不多的空闲空间",
"diskCompactDone": "已回收 {reclaimed}({before} → {after})",
@@ -111,10 +119,19 @@ export const settingsZh: Record<string, string> = {
"diskMode": "使用方式",
"diskModeCopy": "复制一份,不改动原盘",
"diskModeInPlace": "直接使用原盘",
"diskOptimizeAction": "优化磁盘结构",
"diskOptimizeDesc": "默认 64 KiB 簇可划分为 2 KiB 子簇,减少小块写入的开销,同时整理磁盘并回收空间。",
"diskOptimizeDone": "{before} → {after},已回收 {reclaimed}。{status}。",
"diskOptimizeEnabled": "已启用 extended_l2",
"diskOptimizeInactive": "extended_l2 未启用",
"diskOptimizeTitle": "QCOW2 子簇优化",
"diskResizeAction": "扩容",
"diskResizeDesc": "只能增大。扩大后在 macOS 终端运行提示的命令,新空间才能使用",
"diskResizeDone": "已扩大到 {size}。在 macOS 终端运行:",
"diskResizeTitle": "扩大磁盘",
"diskRewriteBusy": "正在进行另一项磁盘操作。",
"diskRewriteOverlay": "此磁盘共享基础镜像,无法直接重写。",
"diskRewriteSnapshots": "请先删除内部恢复点,以免重写磁盘时丢失。",
"diskSize": "磁盘上限",
"diskSizeHint": "按实际占用增长",
"diskUsageSummary": "已占用 {actual},上限 {virtual}",
@@ -135,9 +152,39 @@ export const settingsZh: Record<string, string> = {
"extraArgs": "额外 QEMU 参数",
"extraArgsDesc": "原样追加到 QEMU 命令行",
"failAffinity": "设置处理器相关性失败",
"folderShareAdd": "添加目录…",
"folderShareAddTitle": "宿主机目录",
"folderShareConfirmRWAction": "改为读写",
"folderShareConfirmRWDesc": "允许 macOS 修改或删除「{name}」({path})中的文件,更改会立即同步到宿主机原目录。",
"folderShareConfirmRWTitle": "开启读写权限",
"folderShareDesc": "在 macOS 桌面 ReimsSharedFolders 中访问,立即生效",
"folderShareEmpty": "未添加目录",
"folderShareIssueBlocked": "不支持共享此目录(系统目录、数据目录、盘符根或外接盘)",
"folderShareIssueCorruptConfig": "Guest Tools 配置文件损坏,已保留原文件未覆盖",
"folderShareIssueInvalidMode": "无效的共享权限模式",
"folderShareIssueMissing": "目录不存在或已移动",
"folderShareIssueNotFound": "未找到该共享目录配置",
"folderShareIssueOverlap": "与已有共享目录重复或存在包含关系",
"folderShareIssuePathChanged": "目录已被重定向或替换,已暂停共享",
"folderShareIssueVolumeMismatch": "所在磁盘已变更,已暂停共享",
"folderShareListTitle": "已添加目录",
"folderShareModeDisabled": "停用",
"folderShareModeRO": "只读",
"folderShareModeRW": "读写",
"folderShareNeedsTools": "需要 Guest Tools {version} 以上:在虚拟机页面更新工具盘并重启虚拟机,再在 macOS 中重新运行安装命令",
"folderShareNote": "仅支持本地固定磁盘目录;新增条目默认只读。CoW 克隆不复制目录配置,但克隆盘会沿用源机 Guest Tools 凭证,需在克隆机重新安装 Guest Tools 以隔离",
"folderSharePickTitle": "选择要共享给 macOS 的目录",
"folderShareRemove": "移除目录",
"folderShareTitle": "自定义共享目录",
"folderShareWritableWarn": "读写模式:macOS 中的修改和删除会直接作用于宿主机原目录",
"footerDisk": "磁盘可用 {gb} GB",
"footerMem": "内存 {pct}%",
"footerMemAvail": "可用 {avail} GB",
"forceQuitAppButton": "强制退出",
"forceQuitAppSub": "对所有运行中的虚拟机执行硬关机,未保存的数据可能丢失。",
"forceQuitAppTitle": "强制退出 Reims-Go",
"forceQuitInProgress": "正在强制退出…",
"fullscreenDecoupledHint": "窗口铺满屏幕;下方分辨率可独立设为原生或超采样 HiDPI(如 4K 1.5× = 5120×2880),由 GPU 自动缩放",
"fullscreenLaunch": "无边框全屏启动",
"fullscreenLaunchHint": "启动后直接进入无边框全屏",
"gpuAutoOption": "自动(优先独显)",
@@ -192,6 +239,10 @@ export const settingsZh: Record<string, string> = {
"hostRAMTotal": "共 {n} GB",
"hostRuntime": "运行时",
"hostWHPX": "Windows 虚拟机监控程序平台",
"imagesNoSourcesDesc": "请在「插件」页面启用至少一个镜像源插件(例如 macOS 镜像源)以浏览和下载系统镜像。",
"imagesNoSourcesTitle": "未启用镜像源插件",
"imagesOpenPlugins": "前往插件",
"imagesSourcesLabel": "镜像来源",
"installersAvailable": "Apple 提供的版本",
"installersCreateVM": "新建虚拟机",
"installersDelete": "删除",
@@ -200,8 +251,8 @@ export const settingsZh: Record<string, string> = {
"installersDownloaded": "已下载",
"installersDownloadingForVM": "为 {vm} 下载中",
"installersDownloadingPct": "下载中 {p}%",
"installersEmpty": "还没有下载任何安装包",
"installersHint": "下载好的安装包可以重复用来新建虚拟机",
"installersEmpty": "还没有下载任何镜像",
"installersHint": "下载好的镜像可以重复用来新建虚拟机",
"installersKindOffline": "离线完整包",
"installersKindOnline": "在线恢复镜像",
"installersLatest": "最新",
@@ -211,17 +262,49 @@ export const settingsZh: Record<string, string> = {
"installersQueued": "排队中",
"installersQueuedForVM": "为 {vm} 排队中",
"installersResume": "继续下载",
"installersTitle": "安装包",
"installersTitle": "镜像",
"installersWaitingVM": "{vm} 等待使用",
"kernelIrqchipAuto": "自动",
"kernelIrqchipLabel": "中断加速",
"kernelIrqchipOff": "关闭",
"kernelIrqchipOn": "开启",
"keymapGroupNote": "仅在此虚拟机窗口位于前台时生效。Ctrl+Alt+Win 保留用于释放捕获。",
"keymapGroupTitle": "修饰键映射",
"keymapGuestDefault": "默认",
"keymapGuestDisabled": "禁用",
"keymapGuestEsc": "Esc",
"keymapGuestLcmd": "左 ⌘ Command",
"keymapGuestLctrl": "左 ⌃ Control",
"keymapGuestLopt": "左 ⌥ Option",
"keymapGuestRcmd": "右 ⌘ Command",
"keymapGuestRctrl": "右 ⌃ Control",
"keymapGuestRopt": "右 ⌥ Option",
"keymapHostCapslock": "Caps Lock",
"keymapHostLalt": "左 Alt",
"keymapHostLctrl": "左 Ctrl",
"keymapHostLwin": "左 Win",
"keymapHostRalt": "右 Alt",
"keymapHostRctrl": "右 Ctrl",
"keymapHostRwin": "右 Win",
"keymapInactive": "修饰键映射未启用",
"keymapInputServiceRequired": "请启用宿主输入服务以使用修饰键映射",
"keymapPending": "等待 Guest Tools 启用修饰键映射",
"keymapPresetCustom": "自定义",
"keymapPresetOff": "关闭",
"keymapPresetSwapAltWin": "Alt ↔ Win",
"keymapPresetTitle": "映射预设",
"keymapPresetWinToCmd": "Win → ⌘",
"keymapRunning": "虚拟机获得焦点时生效",
"keymapStopped": "虚拟机启动后生效",
"keymapUpgrade": "请将 Guest Tools 更新到版本 {version}",
"keymapWaiting": "等待 Guest Tools 连接",
"language": "语言",
"languageSub": "内置简体中文与英语,可通过插件扩展更多语言",
"logLevel": "日志级别",
"logLevelCustom": "自定义",
"logLevelDesc": "排查问题时再调高",
"macosSlaButton": "查看许可协议",
"macosSlaNotice": "使用此软件必须接受软件附带的原始许可协议。",
"macosVersion": "macOS 版本",
"memCommitHint": "Windows 还能分配 {avail} GB · 推荐 {rec} GB",
"memOverHint": "超过推荐值,启动时可能分配失败",
@@ -263,6 +346,7 @@ export const settingsZh: Record<string, string> = {
"resCustomSub": "宽 × 高",
"resFullscreen": "全屏",
"resInvalid": "格式为 宽x高,例如 2560x1600",
"resNativeBadge": "原生",
"resetAll": "全部还原",
"resetField": "还原为当前值",
"runtimeDelete": "删除运行时",
@@ -272,6 +356,26 @@ export const settingsZh: Record<string, string> = {
"settingsAppearance": "外观与语言",
"settingsGeneral": "常规",
"settingsTitle": "{name}",
"smbiosApplied": "已写入新的 OpenCore 设备码,下次启动虚拟机生效",
"smbiosApply": "写入新设备码",
"smbiosCheckHint": "建议将序列号复制到 checkcoverage.apple.com 确认显示「无效序列号」(未被真机占用)后再写入。",
"smbiosCopySerial": "复制序列号",
"smbiosDesc": "写入 OpenCore 的序列号、主板号 (MLB) 与 UUID,用于 Apple 服务识别。ROM 与虚拟网卡 MAC 保持同步,换码时不会修改。",
"smbiosDialogSub": "只修改序列号、MLB 与 SystemUUID,保留原 ROM(网卡 MAC)与 NVRAM",
"smbiosDialogTitle": "更换 OpenCore 设备码",
"smbiosGenerate": "随机生成一组",
"smbiosHide": "隐藏",
"smbiosLoadFailed": "无法读取 OpenCore 设备码",
"smbiosMLB": "主板号 (MLB)",
"smbiosModel": "机型",
"smbiosROM": "网卡 ROM",
"smbiosRotateBtn": "一键换码…",
"smbiosSerial": "序列号",
"smbiosShow": "显示完整码",
"smbiosStopRequired": "请先彻底关机(不能处于运行或休眠状态)",
"smbiosTitle": "设备身份 (SMBIOS)",
"smbiosUUID": "系统 UUID",
"smbiosWarning": "换码前请先在 macOS 中退出 Apple 账户并彻底关机;换码后首次开机可能弹出「设置助理」,iCloud / App Store 需重新登录。",
"sourceDisk": "已有虚拟磁盘(.qcow2)",
"sourceInstaller": "本地安装器镜像(.img / .dmg)",
"sshForward": "SSH 端口转发",
@@ -288,9 +392,12 @@ export const settingsZh: Record<string, string> = {
"stopTimeout": "关机等待时间",
"stopTimeoutHint": "0 表示一直等待",
"storageBreakdownTitle": "空间分布",
"storageInstallers": "安装包",
"storageInstallers": "镜像",
"storageRuntimes": "Reims-Go",
"storageVMs": "虚拟机文件",
"syncHostMemorySMBIOS": "同步宿主机内存规格",
"syncHostMemorySMBIOSSub": "在 macOS「关于本机」中显示宿主机真实内存频率与代数(当前:{spec}),下次启动生效",
"syncHostMemorySMBIOSUnavailable": "未能从宿主机 SMBIOS 读取物理内存频率,虚拟机将保持默认的 2666 MHz DDR4",
"themeLabel": "外观",
"themePluginDarkDisabled": "默认主题插件已停用,深色与跟随系统外观不可用",
"themePluginLightDisabled": "当前主题仅支持深色外观",
@@ -318,8 +425,12 @@ export const settingsZh: Record<string, string> = {
export const settingsEn: Record<string, string> = {
"aboutCommunity": "Community \u0026 support",
"aboutCopyDiscord": "Copy invite link",
"aboutCopyQQGroup": "Copy group ID",
"aboutDiscord": "Discord community",
"aboutDiscordSub": "Chat with users, share hardware compatibility, test alphas and build plugins",
"aboutIssueSub": "Report a problem or suggest a feature on GitHub",
"aboutJoinDiscord": "Join server",
"aboutJoinQQGroup": "Join group",
"aboutLicensesOpenGitHub": "View on GitHub",
"aboutLicensesSub": "Apache-2.0 license and third-party notices (available offline)",
@@ -411,6 +522,10 @@ export const settingsEn: Record<string, string> = {
"coresUnit": "cores",
"cpuOverHint": "Leaves Windows fewer than 2 threads; your PC may slow down",
"cpuRecHint": "{rec} cores recommended · this PC has {n} threads",
"defenderCopyCommand": "Copy exclusion command",
"defenderExclusionDesc": "Real-time scanning can slow VM disk access. You can exclude the data folder {path} in Windows Security.",
"defenderExclusionTitle": "Windows Defender real-time protection exclusions",
"defenderOpenSecurity": "Open Windows Security",
"diskCompactAction": "Reclaim now",
"diskCompactDesc": "Gives space from files deleted in macOS back to Windows. Needs about as much free space as the disk uses now",
"diskCompactDone": "Reclaimed {reclaimed} ({before} → {after})",
@@ -426,10 +541,19 @@ export const settingsEn: Record<string, string> = {
"diskMode": "Use disk as",
"diskModeCopy": "A copy — original untouched",
"diskModeInPlace": "In place",
"diskOptimizeAction": "Optimize disk layout",
"diskOptimizeDesc": "Splits default 64 KiB clusters into 2 KiB subclusters to reduce small-write overhead while compacting the disk.",
"diskOptimizeDone": "{before} → {after}, reclaimed {reclaimed}. {status}.",
"diskOptimizeEnabled": "extended_l2 is enabled",
"diskOptimizeInactive": "extended_l2 is inactive",
"diskOptimizeTitle": "QCOW2 subcluster optimization",
"diskResizeAction": "Expand",
"diskResizeDesc": "Grow only. Afterwards, run the command shown in macOS Terminal to use the new space",
"diskResizeDone": "Expanded to {size}. Run this in macOS Terminal:",
"diskResizeTitle": "Expand disk",
"diskRewriteBusy": "Another disk operation is in progress.",
"diskRewriteOverlay": "This disk shares a backing image and cannot be rewritten directly.",
"diskRewriteSnapshots": "Delete internal restore points first to preserve them when rewriting the disk.",
"diskSize": "Disk size",
"diskSizeHint": "Grows as it fills",
"diskUsageSummary": "{actual} used of {virtual}",
@@ -450,9 +574,39 @@ export const settingsEn: Record<string, string> = {
"extraArgs": "Extra QEMU arguments",
"extraArgsDesc": "Appended to the QEMU command line as is",
"failAffinity": "Could not update processor affinity",
"folderShareAdd": "Add folder…",
"folderShareAddTitle": "Host folders",
"folderShareConfirmRWAction": "Enable read-write",
"folderShareConfirmRWDesc": "Allow macOS to modify or delete files in \"{name}\" ({path}). Changes apply directly to the host folder.",
"folderShareConfirmRWTitle": "Enable read-write access",
"folderShareDesc": "Accessible from ReimsSharedFolders on the macOS desktop. Applies immediately",
"folderShareEmpty": "No folders added",
"folderShareIssueBlocked": "This folder cannot be shared (system, data root, drive root, or external volume)",
"folderShareIssueCorruptConfig": "Guest Tools config file is unreadable; original file was kept",
"folderShareIssueInvalidMode": "Invalid shared folder mode",
"folderShareIssueMissing": "Folder is missing or moved",
"folderShareIssueNotFound": "Shared folder entry was not found",
"folderShareIssueOverlap": "Overlaps with an existing shared folder",
"folderShareIssuePathChanged": "Folder target changed or redirected; sharing paused",
"folderShareIssueVolumeMismatch": "Volume identity changed; sharing paused",
"folderShareListTitle": "Added folders",
"folderShareModeDisabled": "Off",
"folderShareModeRO": "Read-only",
"folderShareModeRW": "Read-write",
"folderShareNeedsTools": "Needs Guest Tools {version} or later: mount Guest Tools on the VM page, restart the VM, and run the install command in macOS again",
"folderShareNote": "Internal fixed-disk folders only; new entries default to read-only. CoW clones do not copy folder settings, but keep the source Guest Tools token until Guest Tools is reinstalled on the clone",
"folderSharePickTitle": "Choose a folder to share with macOS",
"folderShareRemove": "Remove folder",
"folderShareTitle": "Custom shared folders",
"folderShareWritableWarn": "Read-write: changes and deletions in macOS modify the host folder directly",
"footerDisk": "Disk {gb} GB free",
"footerMem": "Memory {pct}%",
"footerMemAvail": "{avail} GB free",
"forceQuitAppButton": "Force quit",
"forceQuitAppSub": "Cuts power to running virtual machines. Unsaved data may be lost.",
"forceQuitAppTitle": "Force quit Reims-Go",
"forceQuitInProgress": "Force quitting…",
"fullscreenDecoupledHint": "Fills the monitor; pick native or supersampled HiDPI (e.g. 5120×2880 for 4K 1.5×) below, scaled on the GPU",
"fullscreenLaunch": "Launch borderless fullscreen",
"fullscreenLaunchHint": "Opens macOS in borderless full screen",
"gpuAutoOption": "Automatic (prefers discrete)",
@@ -507,6 +661,10 @@ export const settingsEn: Record<string, string> = {
"hostRAMTotal": "{n} GB total",
"hostRuntime": "Runtime",
"hostWHPX": "Windows Hypervisor Platform",
"imagesNoSourcesDesc": "Enable at least one image source plugin (such as macOS Images) in Plugins to browse and download system images.",
"imagesNoSourcesTitle": "No image source plugins enabled",
"imagesOpenPlugins": "Open Plugins",
"imagesSourcesLabel": "Image sources",
"installersAvailable": "Releases from Apple",
"installersCreateVM": "Create VM",
"installersDelete": "Delete",
@@ -515,8 +673,8 @@ export const settingsEn: Record<string, string> = {
"installersDownloaded": "Downloaded",
"installersDownloadingForVM": "Downloading for {vm}",
"installersDownloadingPct": "Downloading {p}%",
"installersEmpty": "No installers downloaded yet",
"installersHint": "Downloaded installers can be reused for new VMs",
"installersEmpty": "No images downloaded yet",
"installersHint": "Downloaded images can be reused for new VMs",
"installersKindOffline": "Offline installer",
"installersKindOnline": "Online recovery",
"installersLatest": "Latest",
@@ -526,17 +684,49 @@ export const settingsEn: Record<string, string> = {
"installersQueued": "Queued",
"installersQueuedForVM": "Queued for {vm}",
"installersResume": "Resume",
"installersTitle": "Installers",
"installersTitle": "Images",
"installersWaitingVM": "{vm} waiting",
"kernelIrqchipAuto": "Auto",
"kernelIrqchipLabel": "Interrupt acceleration",
"kernelIrqchipOff": "Off",
"kernelIrqchipOn": "On",
"keymapGroupNote": "Applies only while this VM is focused. Ctrl+Alt+Win is reserved for releasing capture.",
"keymapGroupTitle": "Modifier keys",
"keymapGuestDefault": "Default",
"keymapGuestDisabled": "Disabled",
"keymapGuestEsc": "Esc",
"keymapGuestLcmd": "Left ⌘ Command",
"keymapGuestLctrl": "Left ⌃ Control",
"keymapGuestLopt": "Left ⌥ Option",
"keymapGuestRcmd": "Right ⌘ Command",
"keymapGuestRctrl": "Right ⌃ Control",
"keymapGuestRopt": "Right ⌥ Option",
"keymapHostCapslock": "Caps Lock",
"keymapHostLalt": "Left Alt",
"keymapHostLctrl": "Left Ctrl",
"keymapHostLwin": "Left Win",
"keymapHostRalt": "Right Alt",
"keymapHostRctrl": "Right Ctrl",
"keymapHostRwin": "Right Win",
"keymapInactive": "Modifier mapping is inactive",
"keymapInputServiceRequired": "Enable Host Input Service to use modifier mapping",
"keymapPending": "Waiting for Guest Tools to activate modifier mapping",
"keymapPresetCustom": "Custom",
"keymapPresetOff": "Off",
"keymapPresetSwapAltWin": "Alt ↔ Win",
"keymapPresetTitle": "Preset",
"keymapPresetWinToCmd": "Win → ⌘",
"keymapRunning": "Active while this VM is focused",
"keymapStopped": "Applies when this VM is running",
"keymapUpgrade": "Update Guest Tools to version {version}",
"keymapWaiting": "Waiting for Guest Tools to connect",
"language": "Language",
"languageSub": "Simplified Chinese and English built in; add more via plugins",
"logLevel": "Log level",
"logLevelCustom": "Custom",
"logLevelDesc": "Raise only when troubleshooting",
"macosSlaButton": "View SLA",
"macosSlaNotice": "Use of this software requires acceptance of the original license agreement included with the software.",
"macosVersion": "macOS version",
"memCommitHint": "Windows can allocate {avail} GB more · {rec} GB recommended",
"memOverHint": "Above the recommendation; the VM may fail to start",
@@ -578,6 +768,7 @@ export const settingsEn: Record<string, string> = {
"resCustomSub": "Width × height",
"resFullscreen": "Full screen",
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
"resNativeBadge": "Native",
"resetAll": "Revert all",
"resetField": "Revert to current value",
"runtimeDelete": "Delete runtime",
@@ -587,6 +778,26 @@ export const settingsEn: Record<string, string> = {
"settingsAppearance": "Appearance \u0026 language",
"settingsGeneral": "General",
"settingsTitle": "{name}",
"smbiosApplied": "Updated OpenCore SMBIOS identity. Applies on next start",
"smbiosApply": "Write new codes",
"smbiosCheckHint": "Tip: check the serial at checkcoverage.apple.com and verify it reports invalid (not registered to a real Mac) before writing.",
"smbiosCopySerial": "Copy serial",
"smbiosDesc": "Serial, MLB and UUID written to OpenCore for Apple services. ROM stays synced with the virtual NIC MAC and is left unchanged.",
"smbiosDialogSub": "Updates Serial, MLB and SystemUUID only; keeps ROM (NIC MAC) and NVRAM intact",
"smbiosDialogTitle": "Rotate OpenCore SMBIOS",
"smbiosGenerate": "Generate random",
"smbiosHide": "Hide",
"smbiosLoadFailed": "Could not read OpenCore SMBIOS",
"smbiosMLB": "MLB",
"smbiosModel": "Model",
"smbiosROM": "NIC ROM",
"smbiosRotateBtn": "Rotate codes…",
"smbiosSerial": "Serial",
"smbiosShow": "Reveal",
"smbiosStopRequired": "Shut down the VM completely first (not running or suspended)",
"smbiosTitle": "Device identity (SMBIOS)",
"smbiosUUID": "System UUID",
"smbiosWarning": "Sign out of Apple Account in macOS and shut down completely before rotating. First boot may show Setup Assistant and require signing in to iCloud / App Store again.",
"sourceDisk": "Existing virtual disk (.qcow2)",
"sourceInstaller": "Local installer image (.img / .dmg)",
"sshForward": "SSH port forwarding",
@@ -603,9 +814,12 @@ export const settingsEn: Record<string, string> = {
"stopTimeout": "Shutdown timeout",
"stopTimeoutHint": "0 waits indefinitely",
"storageBreakdownTitle": "Storage breakdown",
"storageInstallers": "Installers",
"storageInstallers": "Images",
"storageRuntimes": "Reims-Go",
"storageVMs": "VM files",
"syncHostMemorySMBIOS": "Sync host memory specs",
"syncHostMemorySMBIOSSub": "Show the host's actual memory speed and generation ({spec}) in macOS About This Mac; applies on next start",
"syncHostMemorySMBIOSUnavailable": "Could not read host SMBIOS memory speed; VMs keep the default 2666 MHz DDR4",
"themeLabel": "Appearance",
"themePluginDarkDisabled": "Default theme plugin is disabled; dark and system appearances are unavailable",
"themePluginLightDisabled": "The active theme supports dark appearance only",
+50
View File
@@ -24,12 +24,18 @@ export const vmZh: Record<string, string> = {
"diagBackingChainWarn": "当前系统盘 CoW 派生链深度为 {depth} 层(≥ 2),未分配簇读穿透会拖慢小文件 I/O,建议合并为独立镜像或基于基础镜像重新派生",
"diagExternalDriveWarn": "数据目录在外置或网络盘上({dir}),读写会明显变慢",
"diagHighMemWarn": "宿主内存已用 {pct}%,虚拟机可能会卡顿",
"discardSuspend": "放弃挂起状态",
"discardSuspendConfirm": "放弃并关机",
"discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。",
"discardSuspendTitle": "放弃「{name}」的挂起状态?",
"displayNameEdit": "点按以修改显示名称",
"displayNameEditEllipsis": "修改显示名称…",
"displayNameLabel": "显示名称",
"displayNameTip": "显示名称 · 虚拟机名称为 {name}(点按修改)",
"dropFilesHint": "松开以投递到 macOS 共享目录",
"enterFullscreen": "进入全屏",
"enterRecovery": "进入恢复模式",
"exitFullscreen": "退出全屏",
"exportDiagnostics": "导出排障日志 (.zip)",
"factBackingChain": "CoW 派生链",
"factCPU": "处理器",
@@ -39,18 +45,22 @@ export const vmZh: Record<string, string> = {
"failAttachInstaller": "挂载镜像失败",
"failCloneVM": "派生 CoW 副本失败",
"failDelete": "删除失败",
"failDiscardSuspend": "放弃挂起状态失败",
"failEject": "弹出安装盘失败",
"failEnterRecovery": "进入恢复模式失败",
"failExportDiagnostics": "导出排障日志失败",
"failFinishInstall": "退出恢复模式失败",
"failFocus": "无法定位虚拟机窗口",
"failFullscreen": "无法切换全屏",
"failGuestTools": "Guest Tools 操作失败",
"failOpenFolder": "无法打开文件夹",
"failRestart": "重启失败",
"failResume": "恢复失败",
"failScreenshot": "截屏失败",
"failSnapshot": "恢复点操作失败",
"failStart": "启动失败",
"failStop": "关机失败",
"failSuspend": "挂起失败",
"failType": "键入失败",
"failUpgradeNVMe": "升级到 NVMe 失败",
"fieldAudio": "音频",
@@ -108,6 +118,8 @@ export const vmZh: Record<string, string> = {
"pendingTitle": "下次启动生效",
"pickRecoveryTitle": "选择离线镜像(.img / .dmg)",
"restartToApply": "重启以应用",
"resume": "恢复",
"resumeUnavailable": "切换到支持挂起的内核后可恢复",
"sendText": "发送文本到虚拟机…",
"sendTextConfirm": "发送 (Ctrl+Enter)",
"sendTextDesc": "支持中文、Emoji、宿主机输入法与语音输入,按 Ctrl+Enter 发送到 macOS 当前输入框。",
@@ -152,14 +164,24 @@ export const vmZh: Record<string, string> = {
"state_broken": "出错",
"state_creating": "正在创建",
"state_driver_unavailable": "驱动不可用",
"state_resuming": "恢复中",
"state_running": "运行中",
"state_starting": "启动中",
"state_stopped": "已停止",
"state_stopping": "停止中",
"state_suspended": "已挂起",
"state_suspending": "挂起中",
"suspend": "挂起",
"suspendedGuestToolsHint": "恢复或放弃挂起状态后可更改",
"suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。",
"suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。",
"suspendedNoticeTitle": "已保存运行状态",
"suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置",
"techInfo": "技术信息",
"toastCloned": "已派生 CoW 副本「{name}」",
"toastDeleted": "已删除 {name}",
"toastDiagExported": "已导出脱敏排障日志包 (.zip)",
"toastDiscardSuspend": "已放弃 {name} 的挂起状态",
"toastEjected": "已弹出安装盘",
"toastEnterRecovery": "已进入恢复模式,启动后可在引导菜单选 Recovery",
"toastEnterRecoveryNextStart": "已准备进入恢复模式,重启后显示引导菜单",
@@ -179,12 +201,15 @@ export const vmZh: Record<string, string> = {
"toastOnlineRecoveryStarted": "正在拉取在线恢复镜像(约 1 GB),完成后自动挂载",
"toastPreventSleepOff": "已关闭 macOS 防休眠守护",
"toastPreventSleepOn": "已开启 macOS 防休眠守护",
"toastResumed": "{name} 已恢复",
"toastScreenshotCopied": "已复制虚拟机画面",
"toastSnapshotCreated": "已创建恢复点 {name}",
"toastSnapshotDeleted": "已删除恢复点 {name}",
"toastSnapshotRestored": "已回滚到 {name}",
"toastStopped": "{name} 已关机",
"toastSuspended": "{name} 已挂起",
"toastTyped": "{n, plural, other {已键入 # 个字符}}",
"toggleFullscreen": "切换全屏",
"typeClipboard": "粘贴剪贴板到虚拟机",
"typeIntoVM": "在虚拟机里键入",
"typeUntypeable": "未连接 Guest Tools 时仅支持美式键盘 ASCII 字符;安装并连接 Guest Tools 后即可输入中文与任意 Unicode 文本",
@@ -215,12 +240,18 @@ export const vmEn: Record<string, string> = {
"diagBackingChainWarn": "System disk CoW backing chain is {depth} layers deep (\u003e= 2); read-through slows small-file I/O — consider flattening or re-deriving from the base image",
"diagExternalDriveWarn": "The data folder is on an external or network drive ({dir}); disk access will be slow",
"diagHighMemWarn": "Host memory is {pct}% used; the VM may stutter",
"discardSuspend": "Discard saved state",
"discardSuspendConfirm": "Discard \u0026 Power Off",
"discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.",
"discardSuspendTitle": "Discard saved state for “{name}”?",
"displayNameEdit": "Click to change the display name",
"displayNameEditEllipsis": "Change Display Name…",
"displayNameLabel": "Display name",
"displayNameTip": "Display name · VM name is {name} (click to change)",
"dropFilesHint": "Drop files to send to macOS shared folder",
"enterFullscreen": "Enter full screen",
"enterRecovery": "Enter recovery mode",
"exitFullscreen": "Exit full screen",
"exportDiagnostics": "Export diagnostics (.zip)",
"factBackingChain": "CoW Backing Chain",
"factCPU": "CPU",
@@ -230,18 +261,22 @@ export const vmEn: Record<string, string> = {
"failAttachInstaller": "Couldn’t attach the image",
"failCloneVM": "Couldn’t create CoW clone",
"failDelete": "Couldn’t delete",
"failDiscardSuspend": "Couldn’t discard saved state",
"failEject": "Couldn’t eject the installer",
"failEnterRecovery": "Couldn’t enter recovery mode",
"failExportDiagnostics": "Couldn’t export diagnostics",
"failFinishInstall": "Couldn’t exit recovery mode",
"failFocus": "Could not focus VM window",
"failFullscreen": "Couldn’t toggle full screen",
"failGuestTools": "Guest Tools operation failed",
"failOpenFolder": "Couldn’t open the folder",
"failRestart": "Couldn’t restart",
"failResume": "Couldn’t resume",
"failScreenshot": "Screenshot failed",
"failSnapshot": "Restore point failed",
"failStart": "Couldn’t start",
"failStop": "Couldn’t shut down",
"failSuspend": "Couldn’t suspend",
"failType": "Couldn’t type into the VM",
"failUpgradeNVMe": "Couldn’t upgrade to NVMe",
"fieldAudio": "Audio",
@@ -299,6 +334,8 @@ export const vmEn: Record<string, string> = {
"pendingTitle": "Applies on next start",
"pickRecoveryTitle": "Choose an offline image (.img / .dmg)",
"restartToApply": "Restart to apply",
"resume": "Resume",
"resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM",
"sendText": "Send text to VM…",
"sendTextConfirm": "Send (Ctrl+Enter)",
"sendTextDesc": "Supports Chinese, emoji, host IME, and dictation. Press Ctrl+Enter to inject into the focused macOS field.",
@@ -343,14 +380,24 @@ export const vmEn: Record<string, string> = {
"state_broken": "Error",
"state_creating": "Creating",
"state_driver_unavailable": "Driver unavailable",
"state_resuming": "Resuming",
"state_running": "Running",
"state_starting": "Starting",
"state_stopped": "Stopped",
"state_stopping": "Stopping",
"state_suspended": "Suspended",
"state_suspending": "Suspending",
"suspend": "Suspend",
"suspendedGuestToolsHint": "Resume or discard saved state to make changes",
"suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.",
"suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.",
"suspendedNoticeTitle": "Saved state ready",
"suspendedSettingsHint": "Resume or discard saved state before changing settings",
"techInfo": "Technical details",
"toastCloned": "CoW clone “{name}” created",
"toastDeleted": "{name} deleted",
"toastDiagExported": "Redacted diagnostics archive exported (.zip)",
"toastDiscardSuspend": "Discarded saved state for {name}",
"toastEjected": "Installer ejected",
"toastEnterRecovery": "Recovery mode ready — pick Recovery in OpenCore on next start",
"toastEnterRecoveryNextStart": "Recovery mode ready — restart to open the boot menu",
@@ -370,12 +417,15 @@ export const vmEn: Record<string, string> = {
"toastOnlineRecoveryStarted": "Downloading online recovery image (~1 GB); will attach when ready",
"toastPreventSleepOff": "Prevent-sleep guard disabled",
"toastPreventSleepOn": "Prevent-sleep guard enabled",
"toastResumed": "{name} resumed",
"toastScreenshotCopied": "VM screenshot copied",
"toastSnapshotCreated": "Created restore point {name}",
"toastSnapshotDeleted": "Deleted restore point {name}",
"toastSnapshotRestored": "Restored to {name}",
"toastStopped": "{name} shut down",
"toastSuspended": "{name} suspended",
"toastTyped": "{n, plural, one {Typed # character} other {Typed # characters}}",
"toggleFullscreen": "Toggle full screen",
"typeClipboard": "Send clipboard to VM",
"typeIntoVM": "Type into the VM",
"typeUntypeable": "Only US-keyboard ASCII characters work without Guest Tools; connect Guest Tools for Chinese and Unicode text",
+6
View File
@@ -37,6 +37,8 @@ export const wizardZh: Record<string, string> = {
"setupFree": "可用 {n} GB",
"setupGPU": "显卡(Vulkan)",
"setupImport": "导入本地包…",
"setupLangPackFailed": "语言包安装失败,可稍后在插件页重试",
"setupLangPackOffer": "同时安装「{name}」",
"setupLater": "稍后",
"setupNoGPU": "没有检测到 Vulkan 显卡,只能用软件渲染",
"setupOther": "其他位置…",
@@ -77,6 +79,7 @@ export const wizardZh: Record<string, string> = {
"summarySource": "来源",
"validationChecking": "正在检查…",
"validationPassed": "可以创建",
"vulkanProbeFailed": "Vulkan 探测失败({detail})。请运行 vulkaninfo --summary 检查驱动。",
"wizChooseFile": "选择…",
"wizNoFile": "还没有选择文件",
"wizOptions": "选项",
@@ -122,6 +125,8 @@ export const wizardEn: Record<string, string> = {
"setupFree": "{n} GB free",
"setupGPU": "Graphics (Vulkan)",
"setupImport": "Import a local package…",
"setupLangPackFailed": "Could not install the language pack; you can retry from the Plugins page",
"setupLangPackOffer": "Also install “{name}”",
"setupLater": "Later",
"setupNoGPU": "No Vulkan GPU found; only software rendering will work",
"setupOther": "Other location…",
@@ -162,6 +167,7 @@ export const wizardEn: Record<string, string> = {
"summarySource": "Source",
"validationChecking": "Checking…",
"validationPassed": "Ready to create",
"vulkanProbeFailed": "Vulkan probe failed ({detail}). Run vulkaninfo --summary to check the driver.",
"wizChooseFile": "Choose…",
"wizNoFile": "No file chosen",
"wizOptions": "Options",
+170 -4
View File
@@ -2,8 +2,12 @@
export type I18nKey =
| "aboutCommunity"
| "aboutCopyDiscord"
| "aboutCopyQQGroup"
| "aboutDiscord"
| "aboutDiscordSub"
| "aboutIssueSub"
| "aboutJoinDiscord"
| "aboutJoinQQGroup"
| "aboutLicensesOpenGitHub"
| "aboutLicensesSub"
@@ -123,6 +127,17 @@ export type I18nKey =
| "cpuRecHint"
| "createNow"
| "createStartedHint"
| "dataRootChooseOther"
| "dataRootChooseTitle"
| "dataRootReadOnlyDetail"
| "dataRootReadOnlyFolder"
| "dataRootReadOnlyTitle"
| "dataRootRepair"
| "dataRootRetry"
| "defenderCopyCommand"
| "defenderExclusionDesc"
| "defenderExclusionTitle"
| "defenderOpenSecurity"
| "delete"
| "deleteConfirm"
| "deleteDesc"
@@ -137,6 +152,10 @@ export type I18nKey =
| "diagBackingChainWarn"
| "diagExternalDriveWarn"
| "diagHighMemWarn"
| "discardSuspend"
| "discardSuspendConfirm"
| "discardSuspendDesc"
| "discardSuspendTitle"
| "diskCompactAction"
| "diskCompactDesc"
| "diskCompactDone"
@@ -152,10 +171,19 @@ export type I18nKey =
| "diskMode"
| "diskModeCopy"
| "diskModeInPlace"
| "diskOptimizeAction"
| "diskOptimizeDesc"
| "diskOptimizeDone"
| "diskOptimizeEnabled"
| "diskOptimizeInactive"
| "diskOptimizeTitle"
| "diskResizeAction"
| "diskResizeDesc"
| "diskResizeDone"
| "diskResizeTitle"
| "diskRewriteBusy"
| "diskRewriteOverlay"
| "diskRewriteSnapshots"
| "diskSize"
| "diskSizeHint"
| "diskUsageSummary"
@@ -181,11 +209,13 @@ export type I18nKey =
| "enableLogs"
| "enableNetwork"
| "enableWHPX"
| "enterFullscreen"
| "enterRecovery"
| "errCopyDetails"
| "errRawDetailsToggle"
| "errorBoundaryReload"
| "errorBoundaryTitle"
| "exitFullscreen"
| "expandLogs"
| "exportDiagnostics"
| "extraArgs"
@@ -200,22 +230,26 @@ export type I18nKey =
| "failCloneVM"
| "failCreate"
| "failDelete"
| "failDiscardSuspend"
| "failDownload"
| "failEject"
| "failEnterRecovery"
| "failExportDiagnostics"
| "failFinishInstall"
| "failFocus"
| "failFullscreen"
| "failGeneric"
| "failGuestTools"
| "failOpenFolder"
| "failRestart"
| "failResume"
| "failRuntime"
| "failSSH"
| "failScreenshot"
| "failSnapshot"
| "failStart"
| "failStop"
| "failSuspend"
| "failType"
| "failUpgradeNVMe"
| "fieldAudio"
@@ -229,6 +263,31 @@ export type I18nKey =
| "fieldNetwork"
| "fieldVMName"
| "finishInstall"
| "folderShareAdd"
| "folderShareAddTitle"
| "folderShareConfirmRWAction"
| "folderShareConfirmRWDesc"
| "folderShareConfirmRWTitle"
| "folderShareDesc"
| "folderShareEmpty"
| "folderShareIssueBlocked"
| "folderShareIssueCorruptConfig"
| "folderShareIssueInvalidMode"
| "folderShareIssueMissing"
| "folderShareIssueNotFound"
| "folderShareIssueOverlap"
| "folderShareIssuePathChanged"
| "folderShareIssueVolumeMismatch"
| "folderShareListTitle"
| "folderShareModeDisabled"
| "folderShareModeRO"
| "folderShareModeRW"
| "folderShareNeedsTools"
| "folderShareNote"
| "folderSharePickTitle"
| "folderShareRemove"
| "folderShareTitle"
| "folderShareWritableWarn"
| "fontMissingFoDHint"
| "footerDisk"
| "footerDiskLabel"
@@ -242,7 +301,12 @@ export type I18nKey =
| "footerMemTip"
| "footerMemValue"
| "footerRunningVMs"
| "forceQuitAppButton"
| "forceQuitAppSub"
| "forceQuitAppTitle"
| "forceQuitInProgress"
| "forceStop"
| "fullscreenDecoupledHint"
| "fullscreenLaunch"
| "fullscreenLaunchHint"
| "gpuAuto"
@@ -355,6 +419,10 @@ export type I18nKey =
| "hostReady"
| "hostRuntime"
| "hostWHPX"
| "imagesNoSourcesDesc"
| "imagesNoSourcesTitle"
| "imagesOpenPlugins"
| "imagesSourcesLabel"
| "importRuntime"
| "installersAvailable"
| "installersCreateVM"
@@ -386,6 +454,36 @@ export type I18nKey =
| "kernelIrqchipLabel"
| "kernelIrqchipOff"
| "kernelIrqchipOn"
| "keymapGroupNote"
| "keymapGroupTitle"
| "keymapGuestDefault"
| "keymapGuestDisabled"
| "keymapGuestEsc"
| "keymapGuestLcmd"
| "keymapGuestLctrl"
| "keymapGuestLopt"
| "keymapGuestRcmd"
| "keymapGuestRctrl"
| "keymapGuestRopt"
| "keymapHostCapslock"
| "keymapHostLalt"
| "keymapHostLctrl"
| "keymapHostLwin"
| "keymapHostRalt"
| "keymapHostRctrl"
| "keymapHostRwin"
| "keymapInactive"
| "keymapInputServiceRequired"
| "keymapPending"
| "keymapPresetCustom"
| "keymapPresetOff"
| "keymapPresetSwapAltWin"
| "keymapPresetTitle"
| "keymapPresetWinToCmd"
| "keymapRunning"
| "keymapStopped"
| "keymapUpgrade"
| "keymapWaiting"
| "language"
| "languageSub"
| "localeAuto"
@@ -413,6 +511,8 @@ export type I18nKey =
| "macos.showAllDevices"
| "macos.utilitiesTerminal"
| "macos.volume"
| "macosSlaButton"
| "macosSlaNotice"
| "macosVersion"
| "maximize"
| "memCommitHint"
@@ -493,7 +593,15 @@ export type I18nKey =
| "pluginColorSchemes"
| "pluginColorSchemesHint"
| "pluginDeleteScheme"
| "pluginDisable"
| "pluginDisableInUseBody"
| "pluginDisableInUseTitle"
| "pluginDone"
| "pluginEnableLater"
| "pluginEnableNow"
| "pluginEnablePromptBody"
| "pluginEnablePromptNoRisk"
| "pluginEnablePromptTitle"
| "pluginEntryPath"
| "pluginExternalSection"
| "pluginFailDeleteScheme"
@@ -520,23 +628,28 @@ export type I18nKey =
| "pluginLinkDevTitle"
| "pluginLogEmpty"
| "pluginLogTitle"
| "pluginMarketDownloading"
| "pluginMarketEmpty"
| "pluginMarketIncludeAlpha"
| "pluginMarketFeedEnd"
| "pluginMarketIncompatible"
| "pluginMarketInstall"
| "pluginMarketInstalled"
| "pluginMarketInstalling"
| "pluginMarketKindAll"
| "pluginMarketKindDriver"
| "pluginMarketKindLocale"
| "pluginMarketKindRuntime"
| "pluginMarketKindTemplate"
| "pluginMarketKindTheme"
| "pluginMarketKindTool"
| "pluginMarketLoading"
| "pluginMarketRefresh"
| "pluginMarketSearchPlaceholder"
| "pluginMarketSourceCache"
| "pluginMarketSourceFallback"
| "pluginMarketSourceRemote"
| "pluginMarketStaleBanner"
| "pluginMarketSyncing"
| "pluginMarketUpdate"
| "pluginMarketUpdateShort"
| "pluginMarketVersionTip"
| "pluginMarketWithdrawn"
| "pluginMarketWithdrawnInstalledWarn"
| "pluginMarketWithdrawnInstead"
@@ -547,6 +660,14 @@ export type I18nKey =
| "pluginPublisherLicense"
| "pluginRemove"
| "pluginRequestedPerms"
| "pluginRiskBackground"
| "pluginRiskClipboard"
| "pluginRiskFiles"
| "pluginRiskInput"
| "pluginRiskNative"
| "pluginRiskNetwork"
| "pluginRiskUi"
| "pluginRiskVm"
| "pluginSafeModeShort"
| "pluginScanAdvisoriesSection"
| "pluginScanArchiveTitle"
@@ -581,6 +702,8 @@ export type I18nKey =
| "pluginTrustOfficial"
| "pluginTrustVerified"
| "pluginViewLog"
| "quitFailed"
| "quitInProgress"
| "recommendedBadge"
| "refresh"
| "resCustom"
@@ -588,12 +711,15 @@ export type I18nKey =
| "resFullscreen"
| "resInvalid"
| "resLooksLike"
| "resNativeBadge"
| "resetAll"
| "resetField"
| "resizeLogPanel"
| "resolution"
| "restart"
| "restartToApply"
| "resume"
| "resumeUnavailable"
| "runtimeAlpha"
| "runtimeAlphaHint"
| "runtimeChannel_alpha"
@@ -636,6 +762,8 @@ export type I18nKey =
| "setupFree"
| "setupGPU"
| "setupImport"
| "setupLangPackFailed"
| "setupLangPackOffer"
| "setupLater"
| "setupNoGPU"
| "setupOther"
@@ -655,6 +783,7 @@ export type I18nKey =
| "showInstallGuide"
| "showSidebar"
| "showWindow"
| "shutdownMode"
| "sidebarHost"
| "sidebarInstallers"
| "sidebarItemAria"
@@ -663,6 +792,26 @@ export type I18nKey =
| "sidebarSettings"
| "sidebarSystem"
| "sidebarVMs"
| "smbiosApplied"
| "smbiosApply"
| "smbiosCheckHint"
| "smbiosCopySerial"
| "smbiosDesc"
| "smbiosDialogSub"
| "smbiosDialogTitle"
| "smbiosGenerate"
| "smbiosHide"
| "smbiosLoadFailed"
| "smbiosMLB"
| "smbiosModel"
| "smbiosROM"
| "smbiosRotateBtn"
| "smbiosSerial"
| "smbiosShow"
| "smbiosStopRequired"
| "smbiosTitle"
| "smbiosUUID"
| "smbiosWarning"
| "snapshotCreate"
| "snapshotDelete"
| "snapshotEmpty"
@@ -715,10 +864,13 @@ export type I18nKey =
| "state_broken"
| "state_creating"
| "state_driver_unavailable"
| "state_resuming"
| "state_running"
| "state_starting"
| "state_stopped"
| "state_stopping"
| "state_suspended"
| "state_suspending"
| "statsCPU"
| "statsDisk"
| "statsDiskSub"
@@ -749,6 +901,15 @@ export type I18nKey =
| "summarySSH"
| "summarySSHPort"
| "summarySource"
| "suspend"
| "suspendedGuestToolsHint"
| "suspendedNoticeDesc"
| "suspendedNoticeDescWithTime"
| "suspendedNoticeTitle"
| "suspendedSettingsHint"
| "syncHostMemorySMBIOS"
| "syncHostMemorySMBIOSSub"
| "syncHostMemorySMBIOSUnavailable"
| "taskAppUpdate"
| "taskCreate"
| "taskDownload"
@@ -775,6 +936,7 @@ export type I18nKey =
| "toastCreated"
| "toastDeleted"
| "toastDiagExported"
| "toastDiscardSuspend"
| "toastDownloadPaused"
| "toastEjected"
| "toastEnterRecovery"
@@ -797,6 +959,7 @@ export type I18nKey =
| "toastPreventSleepOff"
| "toastPreventSleepOn"
| "toastQueueCanceled"
| "toastResumed"
| "toastRuntimeReady"
| "toastSSHConfigWritten"
| "toastSSHUserSaved"
@@ -807,7 +970,9 @@ export type I18nKey =
| "toastSnapshotDeleted"
| "toastSnapshotRestored"
| "toastStopped"
| "toastSuspended"
| "toastTyped"
| "toggleFullscreen"
| "typeClipboard"
| "typeIntoVM"
| "typeUntypeable"
@@ -843,6 +1008,7 @@ export type I18nKey =
| "viewLogs"
| "vmDir"
| "vmName"
| "vulkanProbeFailed"
| "welcomeCheckHost"
| "welcomeSub"
| "welcomeTitle"
+91
View File
@@ -0,0 +1,91 @@
// Plugin UI bridge contract, bridgeApi 1.0 (docs/plugin-architecture.md §5.6, §6.3).
//
// Sandboxed plugin views and panels talk to the host only through these
// postMessage envelopes. Stable methods and events are implemented and covered
// by the compatibility promise; experimental ones are part of the published
// shape but the host answers them with an "experimental" error until they are
// promoted. Permissions and rate limits are enforced in Go
// (internal/plugin/contract.go BridgeMethodCatalog); a Go test keeps the method
// lists here and there identical.
export const BRIDGE_API_VERSION = '1.0.0' as const
export const BRIDGE_METHODS = [
'hello',
'i18n.getBundle',
'ui.notify',
'vm.list',
'command.invoke',
] as const
export const BRIDGE_METHODS_EXPERIMENTAL = [
'ui.confirm',
'ui.showForm',
'ui.setTitle',
'ui.setBadge',
'ui.openView',
'ui.close',
'ui.navigate',
'ui.openExternal',
'vm.get',
'settings.get',
'settings.set',
'storage.get',
'storage.set',
'storage.list',
'storage.delete',
'file.pick',
'file.save',
'file.read',
'file.write',
'task.start',
'task.update',
'task.finish',
'net.fetch',
'events.subscribe',
'events.unsubscribe',
] as const
export const BRIDGE_EVENTS = [
'theme.changed',
'locale.changed',
] as const
export const BRIDGE_EVENTS_EXPERIMENTAL = [
'vm.stateChanged',
'view.visibilityChanged',
'task.updated',
] as const
export type BridgeMethod = (typeof BRIDGE_METHODS)[number] | (typeof BRIDGE_METHODS_EXPERIMENTAL)[number]
export type BridgeEventName = (typeof BRIDGE_EVENTS)[number] | (typeof BRIDGE_EVENTS_EXPERIMENTAL)[number]
/** Plugin → host request. `id` is chosen by the plugin and echoed in the result. */
export interface BridgeRequest {
type: 'reims:rpc'
id: string
method: BridgeMethod
params?: Record<string, unknown>
}
/** Host → plugin response to one request. */
export type BridgeResult =
| { type: 'reims:rpc-result'; id: string; ok: true; result: unknown }
| { type: 'reims:rpc-result'; id: string; ok: false; error: string }
/** Host → plugin event. Stable events are always delivered; others only after `events.subscribe`. */
export interface BridgeEvent {
type: 'reims:event'
event: BridgeEventName
data: unknown
}
/** Result of `hello`, the first call a view or panel makes. */
export interface BridgeHello {
bridgeApi: string
uiApi: string
/** Stable host features, e.g. `bridge.vm.list`; feature-detect instead of comparing versions. */
features: string[]
locale: string
dir: 'ltr' | 'rtl'
}
+89
View File
@@ -247,6 +247,95 @@ export function recommendedDisplayPresets(host: HostReport): DisplayPreset[] {
return DEFAULT_DISPLAY_PRESETS
}
export interface FullscreenDisplayPreset extends DisplayPreset {
native?: boolean
scaleBadge?: string
}
/**
* Resolution presets for borderless fullscreen mode, decoupled from the host
* monitor's physical pixels (requires runtime with display-fixed-mode patch
* for non-native sizes). On a 4K screen, 5120x2880 renders 2x HiDPI and
* downscales to 3840x2160 for a crisp 1.5x ("looks like 2560x1440") desktop.
*/
export function fullscreenDisplayPresets(host: HostReport): FullscreenDisplayPreset[] {
const d = host.primary_display
if (!d || d.width <= 0 || d.height <= 0) {
return [
{ resolution: '5120x2880', label: '5120 × 2880', hidpi: true, scaleBadge: '1.5×' },
{ resolution: '3840x2160', label: '3840 × 2160', hidpi: true, native: true, recommended: true },
{ resolution: '2560x1440', label: '2560 × 1440', hidpi: false },
]
}
const w = d.width
const h = d.height
const scalePct = d.scale_pct || 100
const align16 = (n: number) => Math.max(16, Math.floor(n / 16) * 16)
const align2 = (n: number) => Math.max(2, Math.floor(n / 2) * 2)
const out: FullscreenDisplayPreset[] = []
const seen = new Set<string>()
const push = (p: FullscreenDisplayPreset) => {
if (!seen.has(p.resolution)) {
seen.add(p.resolution)
out.push(p)
}
}
// 1.5× HiDPI supersampling for ~4K+ displays (e.g. 3840×2160 -> 5120×2880,
// 3840×2400 -> 5120×3200; macOS renders 2× HiDPI = looks like 2560×1440 / 1600).
if (w >= 3200) {
const sw = align16((w * 4) / 3)
const sh = align2((h * 4) / 3)
if (sw <= 5120 && sh <= 3200 && (sw !== w || sh !== h)) {
push({
resolution: `${sw}x${sh}`,
label: `${sw} × ${sh}`,
hidpi: true,
scaleBadge: '1.5×',
recommended: scalePct >= 125 && scalePct < 175,
})
}
} else if (w >= 1920) {
// Supersampled 2× HiDPI for 1080p / 1440p displays (capped at 5120×3200;
// on 2560×1440, 3840×2160 gives crisp "looks like 1920×1080").
const factor = w <= 1920 ? 2 : 1.5
const sw = Math.min(5120, align16(w * factor))
const sh = Math.min(3200, align2((sw * h) / w))
if (sw >= 3840 && sh >= 2160 && (sw !== w || sh !== h)) {
push({
resolution: `${sw}x${sh}`,
label: `${sw} × ${sh}`,
hidpi: true,
})
}
}
// Native 1:1 monitor resolution (zero-copy blit path).
const nativeRecommended = !out.some((p) => p.recommended)
push({
resolution: `${w}x${h}`,
label: `${w} × ${h}`,
hidpi: !!host.fullscreen_hidpi,
native: true,
recommended: nativeRecommended,
})
// 1× scaled option for 4K+ monitors (e.g. 2560×1440 on 4K = 1.5× logical size without HiDPI).
if (w >= 3840) {
const lw = align16((w * 2) / 3)
const lh = align2((h * 2) / 3)
if (lw >= 1920 && lh >= 1080) {
push({
resolution: `${lw}x${lh}`,
label: `${lw} × ${lh}`,
hidpi: false,
})
}
}
return out
}
export function recommendedResolution(host: HostReport): string {
if (host.recommended_resolution) return host.recommended_resolution
const rec = recommendedDisplayPresets(host).find((p) => p.recommended)
+60 -18
View File
@@ -6,7 +6,7 @@
// declarative state-driven slot decorations.
// - Tier 3 (Interactive theme): lazy-loads `./uiSdk` only when a trusted `ui_script_url` is active.
import { UI_CONTRACT_TOKENS } from '../styles/ui-contract'
import { UI_CONTRACT_LAYOUT_OPTIONS, UI_CONTRACT_TOKENS, type UIContractSDKEvent } from '../styles/ui-contract'
import type { ActiveThemePayload, ThemeDecoration, ThemeDecorationState, TokenDeriveRule } from '../types'
const LEGACY_CACHE_KEY = 'reims-go-theme-tokens-v1'
@@ -55,6 +55,16 @@ export interface ThemeSDKHostActions {
let activeUIScriptCleanup: (() => void) | null = null
let activeUIScriptNotifier: ((snap: UIStateSnapshot) => void) | null = null
let activeUIScriptURL = ''
let activeUIScriptEventSink: ((event: string, data: unknown) => void) | null = null
/**
* Forwards a host event to the interactive theme's `sdk.on` handlers. A no-op
* unless an interactive theme is loaded; payloads carry no paths or secrets.
*/
export function emitThemeEvent(event: UIContractSDKEvent, data: unknown): void {
if (!activeUIScriptEventSink) return
try { activeUIScriptEventSink(event, data) } catch (e) { console.warn('[theme] UI script event handler failed:', event, e) }
}
let applyGeneration = 0
function decodeCSSEscapes(s: string): string {
@@ -109,6 +119,34 @@ function sanitizeRelativeAssetPath(rel: string): string | null {
return cleaned
}
/** Resolves a theme package asset to its served URL, or null when unsafe. */
export function themeAssetURL(payload: ActiveThemePayload | null, rel: string | undefined): string | null {
if (!payload || !rel) return null
const rawBaseURL = payload.asset_base_url ?? ''
if (!RE_ASSET_BASE_URL.test(rawBaseURL) || rawBaseURL.includes('..')) return null
const safe = sanitizeRelativeAssetPath(rel)
return safe ? rawBaseURL + safe : null
}
// Theme `layout` option → <html> attribute (ui-contract UI_CONTRACT_LAYOUT_OPTIONS).
const LAYOUT_ATTRS: Record<string, string> = {
sidebarPosition: 'data-layout-sidebar',
sidebarMode: 'data-layout-sidebar-mode',
density: 'data-layout-density',
titlebar: 'data-layout-titlebar',
}
const ALLOWED_LAYOUT = new Set<string>(UI_CONTRACT_LAYOUT_OPTIONS)
/** Writes the active theme's layout options as data-layout-* attributes; null clears them. */
export function applyThemeLayout(layout: Record<string, unknown> | null | undefined): void {
const el = document.documentElement
for (const [option, attr] of Object.entries(LAYOUT_ATTRS)) {
const value = layout?.[option]
if (typeof value === 'string' && ALLOWED_LAYOUT.has(`${option}=${value}`)) el.setAttribute(attr, value)
else el.removeAttribute(attr)
}
}
/** Verifies stylesheet has balanced braces and no unclosed strings/comments so it cannot escape `@layer theme` (B5). */
export function isBalancedThemeCSS(css: string): boolean {
if (css.toLowerCase().includes('</style')) return false
@@ -162,8 +200,8 @@ function resolveInitialAppearance(): 'light' | 'dark' {
try {
const saved = localStorage.getItem('reims-go-theme')
if (saved === 'dark' || saved === 'light') return saved
} catch {
// ignore storage errors
} catch (e) {
console.warn('[theme] read theme preference failed:', e)
}
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}
@@ -180,8 +218,8 @@ function clearLegacyInlineCache(): void {
}
localStorage.removeItem(LEGACY_CACHE_KEY)
}
} catch {
// ignore
} catch (e) {
console.warn('[theme] clear legacy inline cache failed:', e)
}
}
@@ -217,8 +255,8 @@ export function applyCachedThemeTokensSync(): void {
document.head.appendChild(el)
}
el.textContent = `@layer theme {\n:root {\n${varLines}\n}\n}`
} catch {
// ignore corrupt cache
} catch (e) {
console.warn('[theme] apply cached theme tokens failed:', e)
}
}
@@ -229,8 +267,8 @@ function clearDynamicThemeStyles(): void {
clearLegacyInlineCache()
try {
localStorage.removeItem(THEME_CACHE_KEY)
} catch {
// ignore
} catch (e) {
console.warn('[theme] clear theme token cache failed:', e)
}
}
@@ -436,7 +474,7 @@ export async function applyActiveTheme(
// Always tear down previous interactive theme script if URL changed or disabled.
const nextScriptURL = payload?.ui_script_url ?? ''
if (activeUIScriptCleanup && activeUIScriptURL !== nextScriptURL) {
try { activeUIScriptCleanup() } catch {}
try { activeUIScriptCleanup() } catch (e) { console.warn('[theme] UI script cleanup failed:', e) }
activeUIScriptCleanup = null
activeUIScriptURL = ''
}
@@ -444,10 +482,12 @@ export async function applyActiveTheme(
// Builtin default theme (or safe mode) -> zero extra CSS injected (§8.1).
if (!payload || !payload.theme || payload.theme_id === 'builtin.theme.default') {
clearDynamicThemeStyles()
applyThemeLayout(null)
return
}
const th = payload.theme
applyThemeLayout(th.layout as Record<string, unknown> | undefined)
const rawBaseURL = payload.asset_base_url ?? ''
const baseURL = RE_ASSET_BASE_URL.test(rawBaseURL) && !rawBaseURL.includes('..') ? rawBaseURL : ''
@@ -532,25 +572,27 @@ export async function applyActiveTheme(
}
nextCache[appearance] = sanitizedTokens
localStorage.setItem(THEME_CACHE_KEY, JSON.stringify(nextCache))
} catch {
// ignore storage quota
} catch (e) {
console.warn('[theme] persist theme token cache failed:', e)
}
// 5. Tier 3: lazy-load UI SDK ONLY when an approved interactive theme script is present (§8.1).
if (nextScriptURL && nextScriptURL !== activeUIScriptURL) {
try {
const { mountInteractiveThemeScript, notifyThemeSDKState } = await import('./uiSdk')
const { mountInteractiveThemeScript, notifyThemeSDKState, emitThemeSDKEvent } = await import('./uiSdk')
if (gen !== applyGeneration) return
const cleanup = await mountInteractiveThemeScript(nextScriptURL, getState, actions)
if (gen !== applyGeneration) {
try { cleanup() } catch {}
try { cleanup() } catch (e) { console.warn('[theme] stale UI script cleanup failed:', e) }
return
}
activeUIScriptCleanup = () => {
activeUIScriptNotifier = null
activeUIScriptEventSink = null
cleanup()
}
activeUIScriptNotifier = notifyThemeSDKState
activeUIScriptEventSink = emitThemeSDKEvent
activeUIScriptURL = nextScriptURL
} catch {
if (gen === applyGeneration) {
@@ -610,7 +652,7 @@ export function applyActiveLocaleFonts(
/** Tears down injected theme/locale style nodes and active UI scripts on unmount. */
export function disposeActiveThemeAndLocaleFonts(): void {
if (activeUIScriptCleanup) {
try { activeUIScriptCleanup() } catch {}
try { activeUIScriptCleanup() } catch (e) { console.warn('[theme] dispose UI script cleanup failed:', e) }
activeUIScriptCleanup = null
activeUIScriptNotifier = null
activeUIScriptURL = ''
@@ -632,8 +674,8 @@ export function playThemeSound(payload: ActiveThemePayload | null, eventName: st
try {
const audio = new Audio(payload.asset_base_url + safe)
audio.volume = 0.35
void audio.play().catch(() => {})
} catch {
// ignore audio decode/autoplay errors
void audio.play().catch((e) => console.warn('[theme] sound playback failed:', eventName, e))
} catch (e) {
console.warn('[theme] sound init failed:', eventName, e)
}
}
+77 -15
View File
@@ -1,12 +1,17 @@
// Lazy-loaded Tier-3 Interactive Theme UI SDK (docs/plugin-architecture.md §5.1).
// Loaded ONLY when a trusted interactive theme with `ui:script` is enabled (§8.1).
import { UI_API_VERSION, UI_CONTRACT_PARTS, UI_CONTRACT_SLOTS, type UIContractPart, type UIContractSlot } from '../styles/ui-contract'
import {
UI_API_VERSION, UI_CONTRACT_FEATURES, UI_CONTRACT_LAYERS, UI_CONTRACT_PARTS, UI_CONTRACT_SDK_EVENTS, UI_CONTRACT_SLOTS,
type UIContractLayer, type UIContractPart, type UIContractSDKEvent, type UIContractSlot,
} from '../styles/ui-contract'
import { hideWailsGlobals } from '../wails'
import type { ThemeSDKHostActions, UIStateSnapshot } from './themeEngine'
export interface ReimsUISDK {
readonly uiApi: string
/** Stable host features (e.g. `slot.sidebar.footer`); feature-detect instead of comparing versions. */
readonly features: readonly string[]
/** Registers a cleanup callback run in LIFO order on theme switch/disable. */
onDispose: (fn: () => void) => void
/** Runs a named feature isolated so errors disable only that feature. */
@@ -16,23 +21,44 @@ export interface ReimsUISDK {
subscribeState: (cb: (snap: UIStateSnapshot) => void) => () => void
/** Queries elements strictly by contract part class (`rg-p-*`). */
queryPart: (part: UIContractPart) => HTMLElement | null
/** All elements of a repeated part (e.g. `rg-p-nav-item`), in document order. */
queryParts: (part: UIContractPart) => HTMLElement[]
/** Shared MutationObserver bus scoped to a contract part. */
observePart: (part: UIContractPart, cb: () => void) => () => void
/** Shared RAF read/write batch pipeline to avoid layout thrashing. */
scheduleRead: (fn: () => void) => void
scheduleWrite: (fn: () => void) => void
/** Framework-agnostic DOM mounting into a declared slot anchor. */
mountSlot: (slot: UIContractSlot, node: HTMLElement) => () => void
/**
* Framework-agnostic DOM mounting into a declared slot anchor. Repeated slots
* (`nav.item.trailing`) take the item key from `slotKeys`.
*/
mountSlot: (slot: UIContractSlot, node: HTMLElement, key?: string) => () => void
/** Keys of the currently rendered instances of a repeated slot (VM references). */
slotKeys: (slot: UIContractSlot) => string[]
/** Mounts into a full-window layer (`layer.background` / `layer.overlay`). */
mountLayer: (layer: UIContractLayer, node: HTMLElement) => () => void
/** Subscribes to a host event (VM state, tasks, toasts, view changes). */
on: (event: UIContractSDKEvent, cb: (data: unknown) => void) => () => void
/** Restricted non-destructive UI actions only (no start/stop/delete/config write). */
actions: ThemeSDKHostActions
}
const stateListeners = new Set<(snap: UIStateSnapshot) => void>()
const eventListeners = new Map<string, Set<(data: unknown) => void>>()
/** Delivers a host event to subscribed theme handlers (themeEngine.emitThemeEvent). */
export function emitThemeSDKEvent(event: string, data: unknown): void {
const set = eventListeners.get(event)
if (!set) return
for (const cb of set) {
try { cb(data) } catch (e) { console.warn('[uiSdk] event listener failed:', event, e) }
}
}
export function notifyThemeSDKState(snap: UIStateSnapshot): void {
if (stateListeners.size === 0) return
for (const cb of stateListeners) {
try { cb(snap) } catch {}
try { cb(snap) } catch (e) { console.warn('[uiSdk] state listener failed:', e) }
}
}
@@ -47,8 +73,8 @@ function flushFrame() {
const writes = writeQueue
readQueue = []
writeQueue = []
for (const r of reads) { try { r() } catch {} }
for (const w of writes) { try { w() } catch {} }
for (const r of reads) { try { r() } catch (e) { console.warn('[uiSdk] scheduled read failed:', e) } }
for (const w of writes) { try { w() } catch (e) { console.warn('[uiSdk] scheduled write failed:', e) } }
}
function scheduleRAF() {
@@ -69,31 +95,45 @@ export async function mountInteractiveThemeScript(
const disposers = new Set<() => void>()
const partSet = new Set<string>(UI_CONTRACT_PARTS)
const slotSet = new Set<string>(UI_CONTRACT_SLOTS)
const layerSet = new Set<string>(UI_CONTRACT_LAYERS)
const eventSet = new Set<string>(UI_CONTRACT_SDK_EVENTS)
const addDisposer = (fn: () => void) => {
if (disposed) return
disposers.add(fn)
}
const mountInto = (host: HTMLElement | null, node: HTMLElement) => {
if (disposed || !host) return () => {}
host.appendChild(node)
const off = () => {
node.remove()
disposers.delete(off)
}
addDisposer(off)
return off
}
const disposeAll = () => {
if (disposed) return
disposed = true
const list = Array.from(disposers).reverse()
disposers.clear()
for (const fn of list) {
try { fn() } catch {}
try { fn() } catch (e) { console.warn('[uiSdk] disposer failed:', e) }
}
}
const sdk: ReimsUISDK = {
uiApi: UI_API_VERSION,
features: UI_CONTRACT_FEATURES,
onDispose: addDisposer,
feature: (_name, setup) => {
if (disposed) return
const localDisposers: Array<() => void> = []
const localDispose = () => {
while (localDisposers.length > 0) {
try { localDisposers.pop()?.() } catch {}
try { localDisposers.pop()?.() } catch (e) { console.warn('[uiSdk] feature disposer failed:', e) }
}
}
addDisposer(localDispose)
@@ -122,13 +162,17 @@ export async function mountInteractiveThemeScript(
if (disposed || !partSet.has(part)) return null
return document.querySelector<HTMLElement>(`.${part}`)
},
queryParts: (part) => {
if (disposed || !partSet.has(part)) return []
return Array.from(document.querySelectorAll<HTMLElement>(`.${part}`))
},
observePart: (part, cb) => {
if (disposed || !partSet.has(part)) return () => {}
const target = document.querySelector<HTMLElement>(`.${part}`)
if (!target) return () => {}
const obs = new MutationObserver(() => {
if (disposed) return
try { cb() } catch {}
try { cb() } catch (e) { console.warn('[uiSdk] part observer failed:', part, e) }
})
obs.observe(target, { attributes: true, childList: true, subtree: false })
const off = () => {
@@ -148,13 +192,31 @@ export async function mountInteractiveThemeScript(
writeQueue.push(() => { if (!disposed) fn() })
scheduleRAF()
},
mountSlot: (slot, node) => {
if (disposed || !slotSet.has(slot)) return () => {}
const host = document.querySelector<HTMLElement>(`[data-rg-slot="${CSS.escape(slot)}"]`)
if (!host) return () => {}
host.appendChild(node)
mountSlot: (slot, node, key) => {
if (!slotSet.has(slot)) return () => {}
const sel = `[data-rg-slot="${CSS.escape(slot)}"]` + (key ? `[data-rg-key="${CSS.escape(key)}"]` : '')
return mountInto(document.querySelector<HTMLElement>(sel), node)
},
slotKeys: (slot) => {
if (disposed || !slotSet.has(slot)) return []
return Array.from(document.querySelectorAll<HTMLElement>(`[data-rg-slot="${CSS.escape(slot)}"][data-rg-key]`))
.map((el) => el.dataset.rgKey ?? '')
.filter(Boolean)
},
mountLayer: (layer, node) => {
if (!layerSet.has(layer)) return () => {}
return mountInto(document.querySelector<HTMLElement>(`[data-rg-layer="${CSS.escape(layer)}"]`), node)
},
on: (event, cb) => {
if (disposed || !eventSet.has(event)) return () => {}
let set = eventListeners.get(event)
if (!set) {
set = new Set()
eventListeners.set(event, set)
}
set.add(cb)
const off = () => {
node.remove()
eventListeners.get(event)?.delete(cb)
disposers.delete(off)
}
addDisposer(off)
+9
View File
@@ -0,0 +1,9 @@
export interface VMRefLike {
name: string
driver_id?: string
}
/** Matches driver.VMRef.Key while tolerating pre-VMRef test/host snapshots. */
export function vmRefKey(vm: VMRefLike): string {
return vm.driver_id ? `${vm.driver_id}:${vm.name}` : vm.name
}
+64 -35
View File
@@ -2,13 +2,8 @@ import { useEffect, useState } from 'react'
import { VMStats } from '../types'
import { api } from '../wails'
// Shared VM stats poller (stats_flow.go). Components that show stats
// subscribe with useVMStats, so a tick re-renders only them, not the whole
// App. One timer per VM however many subscribe; it pauses while the window
// is hidden and samples once on return.
// Shared VM stats poller, keyed by VMRef so same-name VMs never share samples.
const RUNNING_MS = 3000
// A stopped VM only changes disk usage, so it is sampled rarely.
const STOPPED_MS = 30000
interface Entry {
@@ -16,70 +11,104 @@ interface Entry {
running: boolean
last: VMStats | null
timer?: number
seq: number
appliedSeq: number
}
const entries = new Map<string, Entry>()
const statsKey = (driverID: string, name: string) => `${driverID}:${name}`
function sample(name: string) {
api.GetVMStats(name)
function sample(key: string, driverID: string, name: string, entryRef: Entry) {
if (entries.get(key) !== entryRef) return
const reqSeq = ++entryRef.seq
api.GetVMStatsWithDriver(driverID, name)
.then((s) => {
const e = entries.get(name)
if (!e) return
e.last = s
e.subs.forEach((f) => f(s))
if (entries.get(key) !== entryRef || reqSeq <= entryRef.appliedSeq) return
entryRef.appliedSeq = reqSeq
entryRef.last = s
entryRef.subs.forEach((f) => f(s))
})
.catch(() => {})
.catch((e) => console.warn('[vmStats] GetVMStatsWithDriver failed:', key, e))
}
function schedule(name: string, e: Entry) {
function schedule(key: string, driverID: string, name: string, e: Entry) {
if (e.timer) window.clearInterval(e.timer)
e.timer = undefined
if (document.hidden || e.subs.size === 0) return
e.timer = window.setInterval(() => sample(name), e.running ? RUNNING_MS : STOPPED_MS)
e.timer = window.setInterval(() => sample(key, driverID, name, e), e.running ? RUNNING_MS : STOPPED_MS)
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => {
entries.forEach((e, name) => {
if (!document.hidden && e.subs.size > 0) sample(name)
schedule(name, e)
entries.forEach((e, key) => {
const split = key.indexOf(':')
const driverID = key.slice(0, split)
const name = key.slice(split + 1)
if (!document.hidden && e.subs.size > 0) sample(key, driverID, name, e)
schedule(key, driverID, name, e)
})
})
}
/** Latest stats seen for a VM, without subscribing (e.g. when a dialog opens). */
export function latestVMStats(name: string | undefined | null): VMStats | null {
return name ? entries.get(name)?.last ?? null : null
export function latestVMStatsWithDriver(driverID: string, name: string | undefined | null): VMStats | null {
return name ? entries.get(statsKey(driverID, name))?.last ?? null : null
}
export function latestVMStats(name: string | undefined | null): VMStats | null { return latestVMStatsWithDriver('', name) }
/** Immediately patch cached stats (if any) and re-sample a VM's stats. */
export function refreshVMStatsWithDriver(driverID: string, name: string, patch?: Partial<VMStats>) {
const key = statsKey(driverID, name)
const e = entries.get(key)
if (!e) return
e.appliedSeq = ++e.seq
if (patch && e.last) {
e.last = { ...e.last, ...patch }
e.subs.forEach((f) => f(e.last!))
}
sample(key, driverID, name, e)
}
export function refreshVMStats(name: string, patch?: Partial<VMStats>) { refreshVMStatsWithDriver('', name, patch) }
/** Re-sample all currently subscribed VMs (e.g. after a tray-triggered state change). */
export function refreshSubscribedVMStats() {
entries.forEach((e, key) => {
if (e.subs.size === 0) return
const split = key.indexOf(':')
e.appliedSeq = ++e.seq
sample(key, key.slice(0, split), key.slice(split + 1), e)
})
}
/** Live stats for one VM; `running` picks the sampling rate. Null name: none. */
export function useVMStats(name: string | null, running: boolean): VMStats | null {
const [stats, setStats] = useState<VMStats | null>(() => latestVMStats(name))
export function useVMStats(driverID: string, name: string | null, running: boolean): VMStats | null {
const [stats, setStats] = useState<VMStats | null>(() => latestVMStatsWithDriver(driverID, name))
useEffect(() => {
if (!name) { setStats(null); return }
let e = entries.get(name)
const key = statsKey(driverID, name)
let e = entries.get(key)
if (!e) {
e = { subs: new Set(), running, last: null }
entries.set(name, e)
e = { subs: new Set(), running, last: null, seq: 0, appliedSeq: 0 }
entries.set(key, e)
}
setStats(e.last)
const sub = (s: VMStats) => setStats(s)
e.subs.add(sub)
// A state change (start/stop) samples at once and re-paces the timer.
e.running = running
sample(name)
schedule(name, e)
if (e.running !== running) {
e.running = running
e.appliedSeq = ++e.seq
}
sample(key, driverID, name, e)
schedule(key, driverID, name, e)
return () => {
const cur = entries.get(name)
if (!cur) return
const cur = entries.get(key)
if (!cur || cur !== e) return
cur.subs.delete(sub)
if (cur.subs.size === 0) {
if (cur.timer) window.clearInterval(cur.timer)
entries.delete(name)
entries.delete(key)
}
}
}, [name, running])
}, [driverID, name, running])
return stats
}
@@ -1,9 +1,10 @@
import { AlertTriangle, Check, ChevronDown, Clock, Download, LoaderCircle, Pause, Plus, RefreshCw, Trash, X } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { AlertTriangle, Check, ChevronDown, Clock, Download, ExternalLink, Info, LoaderCircle, Pause, Plus, Trash, X } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import '../i18n/domains/settings.gen'
import '../i18n/domains/wizard.gen'
import { WordmarkLoader } from '../components/WordmarkLoader'
import { I18nKey, t } from '../i18n'
import { macOSMajor } from '../lib/macosRelease'
import { macOSMajor } from './macosRelease'
import {
ActiveInstallerMatch,
findActiveCachedTask,
@@ -23,10 +24,14 @@ import { Button, IconButton } from '../ui/controls'
import { api } from '../wails'
import { VersionArt } from './VersionArt'
const APPLE_SLA_URL = 'https://www.apple.com/legal/sla'
interface Props {
locale: Locale
host: HostReport
tasks: Task[]
refreshSignal?: number
onBusyChange?: (busy: boolean) => void
onCreateWithInstaller: (item: CachedInstaller) => void
onError: (title: string, e: unknown) => void
onToast: (title: string) => void
@@ -71,13 +76,18 @@ function formatOnlineTitle(version: string): string {
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 }) => {
/** macOS image source view provided by the built-in `builtin.images.macos` plugin. */
export const InstallersPage: React.FC<Props> = ({
locale, host, tasks, refreshSignal = 0, onBusyChange, onCreateWithInstaller, onError, onToast,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [cached, setCached] = useState<CachedInstaller[] | null>(null)
const [releases, setReleases] = useState<Release[] | null>(null)
const [releasesErr, setReleasesErr] = useState('')
const [confirmDelete, setConfirmDelete] = useState('')
const lastRefreshRef = useRef(refreshSignal)
const onBusyChangeRef = useRef(onBusyChange)
onBusyChangeRef.current = onBusyChange
const installerTasks = tasks.filter(isInstallerTask)
const activeInstallerTasks = installerTasks.filter(isActiveInstallerTask)
@@ -95,12 +105,28 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
.catch((e) => setReleasesErr(String(e).replace(/^Error:\s*/, '')))
}
useEffect(() => { loadReleases() }, [])
useEffect(() => {
if (refreshSignal !== lastRefreshRef.current) {
lastRefreshRef.current = refreshSignal
loadCached()
loadReleases()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [refreshSignal])
useEffect(() => {
onBusyChangeRef.current?.(releases === null && !releasesErr)
}, [releases, releasesErr])
useEffect(() => () => { onBusyChangeRef.current?.(false) }, [])
// Refresh the downloaded list whenever an installer download starts, shifts phase, or ends.
useEffect(() => {
setConfirmDelete('')
loadCached()
}, [installerTasksSig])
const openSLA = () => {
api.OpenURL(APPLE_SLA_URL).catch((e) => onError(tr('failGeneric'), e))
}
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)
@@ -138,7 +164,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
<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 rg-p-progress" aria-hidden="true">
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
</span>
)}
@@ -147,20 +173,6 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
)
}
const skeleton = (rows: number, label?: string) => (
<div className="skeleton-list" role="status" aria-label={label}>
{Array.from({ length: rows }).map((_, i) => (
<div className="skeleton-row" key={i} aria-hidden="true">
<div className="skeleton-stack">
<div className="skeleton-bar w-title" />
<div className="skeleton-bar w-sub" />
</div>
<div className="skeleton-bar w-btn" />
</div>
))}
</div>
)
const spaceShort = (r: Release) => !downloaded(r.version) && !activeForRelease(r.version) && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
const releaseAction = (r: Release) => {
@@ -169,10 +181,10 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
const task = active.primary
const queued = taskInstallerPhase(task) === 'queued'
if (queued) {
return <span className="badge" role="status">{tr('installersQueued')}</span>
return <span className="badge rg-p-badge" role="status">{tr('installersQueued')}</span>
}
return (
<span className="badge badge-accent installer-active-status" role="status">
<span className="badge rg-p-badge badge-accent installer-active-status" role="status">
<LoaderCircle size={12} className="spin" aria-hidden="true" />
<span>
{task.percent >= 0
@@ -250,30 +262,27 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
const downloadedRows = [...virtualRows, ...cachedRows].sort((a, b) => rowPriority(a) - rowPriority(b))
const groups = groupReleases(releases ?? [])
const showDownloaded = cached === null || downloadedRows.length > 0
const showDownloaded = downloadedRows.length > 0
return (
<div className="page installers-page">
<header className="page-head">
<div className="page-title installers-page-title">
<h1>{tr('installersTitle')}</h1>
<span>{tr('installersHint')}</span>
</div>
<div className="actions">
<IconButton label={tr('refresh')} icon={<RefreshCw size={16} />} onClick={() => { loadCached(); loadReleases() }} />
</div>
</header>
<div className="macos-images-view">
<div className="notice notice-info macos-sla-notice" role="note">
<span className="notice-main">
<Info size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('macosSlaNotice')}</span>
</span>
<Button icon={<ExternalLink size={13} aria-hidden="true" />} onClick={openSLA}>
{tr('macosSlaButton')}
</Button>
</div>
{showDownloaded && (
<section className="section">
<div className="section-title">
<span>{tr('installersDownloaded')}</span>
{downloadedRows.length > 0 && <span className="section-count">{downloadedRows.length}</span>}
<span className="section-count">{downloadedRows.length}</span>
</div>
{cached === null && downloadedRows.length === 0 ? (
skeleton(1, tr('installersDownloaded'))
) : (
<div className="list installer-list">
<div className="list installer-list">
{downloadedRows.map((row) => {
const c = row.cached
const active = row.active
@@ -292,23 +301,23 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
<div className="row-main">
<div className="row-title">
<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 === 'offline' && !c.partial && <span className="badge rg-p-badge badge-ok">{tr('installersKindOffline')}</span>}
{(!task && c?.kind === 'online' && !c.partial) || (task && row.kind === 'online')
? <span className="badge">{tr('installersKindOnline')}</span>
? <span className="badge rg-p-badge">{tr('installersKindOnline')}</span>
: null}
{c?.partial && !task && <span className="badge badge-warn">{tr('installersPartial')}</span>}
{c?.partial && !task && <span className="badge rg-p-badge badge-warn">{tr('installersPartial')}</span>}
{task && vmName && (
<span className={`badge ${queued ? '' : 'badge-accent'}`}>
<span className={`badge rg-p-badge ${queued ? '' : 'badge-accent'}`}>
{tr(queued ? 'installersQueuedForVM' : 'installersDownloadingForVM', { vm: vmName })}
</span>
)}
{task && !vmName && waitingVMs.length > 0 && (
<span className="badge badge-accent">
<span className="badge rg-p-badge badge-accent">
{tr('installersWaitingVM', { vm: waitingVMs.join(', ') })}
</span>
)}
{task && !vmName && queued && (
<span className="badge">{tr('installersQueued')}</span>
<span className="badge rg-p-badge">{tr('installersQueued')}</span>
)}
</div>
{task ? progress(task) : c ? (
@@ -344,7 +353,6 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
)
})}
</div>
)}
</section>
)}
@@ -359,10 +367,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
<Button onClick={loadReleases}>{tr('installersRetry')}</Button>
</div>
) : releases === null ? (
<>
{skeleton(2, tr('offlineLoading'))}
<span className="hint">{tr('offlineLoading')}</span>
</>
<WordmarkLoader className="installers-loader" label={tr('offlineLoading')} />
) : (
<div className="release-list">
{groups.map((group, groupIndex) => {
@@ -377,7 +382,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
<div className="row-title release-title">
<span>{latest.title}</span>
<strong>{latest.version}</strong>
{groupIndex === 0 && <span className="badge badge-accent">{tr('installersLatest')}</span>}
{groupIndex === 0 && <span className="badge rg-p-badge badge-accent">{tr('installersLatest')}</span>}
{downloaded(latest.version) && <Check size={15} className="ok-text" aria-label={tr('offlineCached')} />}
</div>
{releaseMeta(latest)}
@@ -397,7 +402,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
<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>}
{downloaded(r.version) && <span className="badge rg-p-badge badge-ok">{tr('offlineCached')}</span>}
</div>
{releaseMeta(r)}
</div>
@@ -14,7 +14,7 @@ export const OnlineRecoveryDialog: React.FC<Props> = ({ locale, name, onCancel,
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
<div className="dialog-body">
<Alert.Title className="dialog-title">{t(locale, 'onlineRecoveryTitle')}</Alert.Title>
<Alert.Description className="dialog-desc">
@@ -23,10 +23,10 @@ export const OnlineRecoveryDialog: React.FC<Props> = ({ locale, name, onCancel,
</div>
<div className="dialog-foot">
<Alert.Cancel asChild>
<button type="button" className="btn">{t(locale, 'cancel')}</button>
<button type="button" className="btn rg-p-button">{t(locale, 'cancel')}</button>
</Alert.Cancel>
<Alert.Action asChild>
<button type="button" className="btn btn-primary" onClick={onConfirm}>
<button type="button" className="btn rg-p-button btn-primary" onClick={onConfirm}>
{t(locale, 'onlineRecoveryConfirm')}
</button>
</Alert.Action>
File renamed without changes.
File renamed without changes.
+293 -73
View File
@@ -82,15 +82,15 @@ h1, h2, h3, p { margin: 0; }
/* Left of the title bar: sidebar toggle + a small menu bar. Controls and the
menu bar group opt out of window dragging so sweeping across menus stays smooth. */
.titlebar-left { display: flex; align-items: center; gap: 2px; height: 100%; margin-left: calc(var(--sp-2) * -1); }
.titlebar-left { display: flex; align-items: center; gap: 2px; height: 100%; min-width: 0; margin-inline-start: calc(var(--sp-2) * -1); }
.titlebar-icon, .titlebar-menu {
--wails-draggable: no-drag;
height: 28px; border: none; border-radius: var(--r-sm);
background: transparent; color: var(--text-2); cursor: pointer;
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
}
.titlebar-icon { width: 32px; display: grid; place-items: center; margin-right: 4px; }
.titlebar-menu { padding: 0 10px; font-size: var(--fs-13); font-weight: var(--fw-medium); }
.titlebar-icon { width: 32px; display: grid; place-items: center; margin-inline-end: 4px; flex-shrink: 0; }
.titlebar-menu { padding: 0 10px; font-size: var(--fs-13); font-weight: var(--fw-medium); white-space: nowrap; flex-shrink: 0; }
.titlebar-icon:hover, .titlebar-menu:hover { background: var(--surface-hover); color: var(--text); }
.titlebar-menu[data-state="open"] { background: var(--surface-active); color: var(--text); }
.titlebar-icon:active, .titlebar-menu:active { transform: scale(0.96); }
@@ -100,7 +100,7 @@ h1, h2, h3, p { margin: 0; }
/* Menu rows with a trailing shortcut, check marks and group labels. */
.menu-label { flex: 1; min-width: 0; white-space: nowrap; }
.menu-shortcut {
margin-left: 24px; font-family: var(--font-sans); font-size: var(--fs-12);
margin-inline-start: 24px; font-family: var(--font-sans); font-size: var(--fs-12);
color: var(--text-3); font-variant-numeric: tabular-nums;
}
.menu-item[data-highlighted] .menu-shortcut { color: rgba(255, 255, 255, 0.78); }
@@ -109,7 +109,7 @@ h1, h2, h3, p { margin: 0; }
.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);
width: 30px; height: 28px; margin-inline-end: var(--sp-1);
border: 1px solid var(--border); border-radius: var(--r-md);
background: var(--surface-1); color: var(--text-2);
display: grid; place-items: center; cursor: pointer;
@@ -138,11 +138,16 @@ h1, h2, h3, p { margin: 0; }
display: flex; overflow: hidden;
background: var(--surface-sidebar-rail);
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);
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), visibility 0s linear 0s;
}
/* 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-inline: 0; opacity: 0; border-inline-end-color: transparent; }
contents don't reflow while the rail narrows, and visibility: hidden removes
off-screen buttons from the keyboard Tab order. */
.workspace.sidebar-hidden .sidebar-wrap {
width: 0; padding-inline: 0; opacity: 0; border-inline-end-color: transparent;
visibility: hidden; pointer-events: none;
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), visibility 0s linear var(--dur-modal);
}
.sidebar-wrap > .sidebar { min-width: calc(var(--sidebar-w) - 20px); }
.sidebar {
flex: 1; min-height: 0;
@@ -292,6 +297,10 @@ h1, h2, h3, p { margin: 0; }
.status { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; display: inline-block; }
.status-running { background: var(--status-running); }
.status-stopped { border: 1.5px solid var(--status-idle); }
.status-suspended {
width: 7px; height: 8px; border-radius: 0;
background: linear-gradient(90deg, var(--status-busy) 0 2.5px, transparent 2.5px 4.5px, var(--status-busy) 4.5px 7px);
}
.status-busy { background: conic-gradient(var(--status-busy) 0 50%, transparent 50% 100%); border: 1.5px solid var(--status-busy); animation: pulse 1.4s ease-in-out infinite; }
.status-warn { background: var(--status-busy); }
.status-broken { background: var(--status-error); border-radius: 1.5px; transform: rotate(45deg); width: 7px; height: 7px; }
@@ -366,6 +375,7 @@ h1, h2, h3, p { margin: 0; }
.vm-hero-pill.is-running {
background: var(--ok-soft); border-color: transparent; color: var(--ok-text);
}
.vm-hero-pill.is-suspended,
.vm-hero-pill.is-busy {
background: var(--warn-soft); border-color: transparent; color: var(--warn-text);
}
@@ -524,6 +534,11 @@ h1, h2, h3, p { margin: 0; }
box-shadow: 0 1px 3px rgba(255, 59, 48, 0.28), inset 0 1px 0 rgba(255, 255, 255, 0.18);
}
.btn-danger:hover:not(:disabled) { filter: brightness(1.06); background: var(--danger); }
.shutdown-button { display: inline-flex; }
.shutdown-button > .btn:first-child { border-start-end-radius: 0; border-end-end-radius: 0; }
.shutdown-button > .btn:last-child {
padding-inline: 6px; border-start-start-radius: 0; border-end-start-radius: 0; border-inline-start: 0;
}
.btn-ghost { background: transparent; border-color: transparent; color: var(--text-2); box-shadow: none; }
.btn-ghost:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); }
@@ -697,11 +712,18 @@ h1, h2, h3, p { margin: 0; }
}
.empty-panel > svg { opacity: 0.6; }
/* Installers: one major-version card per system, older point releases folded away. */
/* Images: segmented plugin sources, macOS SLA notice, one major-version card per system. */
.installers-page { max-width: 780px; }
.installers-page .page-head { align-items: flex-start; }
.installers-page-title { flex-direction: column; align-items: flex-start; gap: 1px; }
.installers-page-title > span { color: var(--text-3); font-size: var(--fs-12); line-height: 1.45; }
.images-switch { display: flex; }
.macos-images-view { display: flex; flex-direction: column; gap: 16px; }
.macos-sla-notice { align-items: center; }
.installers-loader { padding: 48px 0 40px; }
.images-empty { gap: 8px; padding: 36px 24px; text-align: center; }
.images-empty-title { font-size: var(--fs-14); font-weight: var(--fw-medium); color: var(--text); }
.images-empty-desc { max-width: 420px; font-size: var(--fs-12); color: var(--text-3); line-height: 1.5; margin-bottom: 6px; }
/* About: brand header, then the update row and community links. */
.about-page { max-width: 680px; }
@@ -711,11 +733,14 @@ h1, h2, h3, p { margin: 0; }
.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-modal-body > .seg { align-self: flex-start; flex-shrink: 0; }
.license-pre {
margin: 0; padding: 14px 16px; min-height: 260px; max-height: 52vh; overflow: auto;
margin: 0; padding: 14px 16px; flex: 0 1 auto; height: min(440px, 50vh); min-height: 120px; overflow: auto;
overscroll-behavior: contain; contain: content;
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;
text-rendering: auto; text-autospace: no-autospace;
}
.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; }
@@ -843,7 +868,8 @@ button.status-issue + .status-metric { margin-left: 6px; }
}
:root[dir="rtl"] .status-mini-fill,
:root[dir="rtl"] .progress-fill,
:root[dir="rtl"] .meter-fill {
:root[dir="rtl"] .meter-fill,
:root[dir="rtl"] .market-progress-fill {
transform-origin: right center;
}
.status-mini-fill.warn { background: var(--status-busy); }
@@ -881,6 +907,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
overflow-y: auto; overscroll-behavior: contain; padding: var(--sp-2) var(--sp-4);
font-family: var(--font-mono); font-size: var(--fs-12); line-height: 1.6; color: var(--text-code);
white-space: pre-wrap; word-break: break-word; user-select: text;
text-rendering: auto; text-autospace: no-autospace;
}
.log-line { display: flex; gap: var(--sp-3); }
.log-ts { color: var(--text-3); flex-shrink: 0; font-variant-numeric: tabular-nums; }
@@ -890,27 +917,30 @@ button.status-issue + .status-metric { margin-left: 6px; }
.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; }
/* No backdrop-filter: main.go sets WebviewGpuIsDisabled: true (software
compositing), where per-frame CPU Gaussian blur over modals/overlays stutters
badly during enter animations and inner scrolling. */
.overlay { position: fixed; inset: 0; background: var(--scrim); z-index: 40; }
.dialog {
position: fixed; z-index: 41; left: 50%; top: 50%; transform: translate(-50%, -50%);
width: 720px; max-width: calc(100vw - 48px); max-height: calc(100vh - 80px);
display: flex; flex-direction: column; overflow: hidden;
background: var(--surface-2); backdrop-filter: var(--blur-overlay);
background: var(--surface-2);
border: 1px solid var(--border); border-radius: var(--r-xl);
box-shadow: var(--shadow-overlay), var(--highlight-top);
}
.dialog.sm { width: 420px; }
.dialog-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding: 14px 14px 14px 22px; border-bottom: 1px solid var(--border); }
.dialog-head { flex-shrink: 0; display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding-block: 14px; padding-inline: 22px 14px; border-bottom: 1px solid var(--border); }
.dialog-title { font-size: var(--fs-16); font-weight: var(--fw-strong); letter-spacing: -0.01em; text-wrap: balance; }
.dialog-desc { font-size: var(--fs-13); color: var(--text-2); margin-top: 2px; }
.dialog-desc { font-size: var(--fs-13); color: var(--text-2); margin-top: 2px; overflow-wrap: anywhere; }
.dialog-body { padding: 20px 22px; overflow-y: auto; overscroll-behavior: contain; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); }
.dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); }
.dialog-foot { flex-shrink: 0; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); }
.dialog.sm .dialog-body { padding: 22px 22px 14px; gap: var(--sp-3); }
.dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: 20px; }
.menu {
min-width: 188px; padding: 5px; z-index: 50;
background: var(--surface-2); backdrop-filter: var(--blur-overlay);
background: var(--surface-2);
border: 1px solid var(--border); border-radius: var(--r-lg);
box-shadow: var(--shadow-overlay), var(--highlight-top);
}
@@ -931,7 +961,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
.tooltip {
z-index: 60; padding: 5px 9px; border-radius: var(--r-sm);
background: var(--surface-2); backdrop-filter: var(--blur-overlay);
background: var(--surface-2);
border: 1px solid var(--border-strong); color: var(--text);
font-size: var(--fs-12); box-shadow: 0 8px 22px rgba(15, 23, 42, 0.16);
display: flex; gap: var(--sp-2); align-items: center;
@@ -942,7 +972,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
.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; flex-direction: column; gap: var(--sp-2); padding: var(--sp-3);
background: var(--surface-2); backdrop-filter: var(--blur-overlay);
background: var(--surface-2);
border: 1px solid var(--border); border-radius: var(--r-lg);
box-shadow: var(--shadow-overlay), var(--highlight-top);
}
@@ -952,8 +982,10 @@ button.status-issue + .status-metric { margin-left: 6px; }
.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; }
: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-main-row { display: flex; align-items: center; gap: var(--sp-3); width: 100%; min-width: 0; }
.toast-main-row > svg { flex-shrink: 0; }
.toast-main-row:has(.toast-desc) { align-items: flex-start; }
.toast-main-row:has(.toast-desc) > svg { margin-top: 2px; }
.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; }
@@ -961,7 +993,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
.toast-title { font-size: var(--fs-13); font-weight: var(--fw-strong); }
.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);
border-radius: 4px; background: var(--surface-active); color: var(--text-2);
}
.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; }
@@ -1109,8 +1141,8 @@ button.status-issue + .status-metric { margin-left: 6px; }
.srow[data-error] { background: var(--danger-soft); }
.srow-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); min-height: 28px; }
.srow-text { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.srow-title { display: flex; align-items: center; gap: 6px; font-size: 13.5px; color: var(--text); }
.srow-desc { font-size: var(--fs-12); color: var(--text-3); line-height: 1.5; }
.srow-title { display: flex; align-items: center; gap: 6px; font-size: 13.5px; color: var(--text); overflow-wrap: anywhere; }
.srow-desc { font-size: var(--fs-12); color: var(--text-3); line-height: 1.5; min-width: 0; }
.res-advice { margin-top: var(--sp-2); color: var(--warn-text); }
.srow-reason { display: inline-flex; align-items: center; gap: 5px; font-size: var(--fs-12); color: var(--text-2); }
.srow-ctrl { display: flex; align-items: center; gap: var(--sp-2); flex-shrink: 0; }
@@ -1123,6 +1155,7 @@ 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; }
.folder-path { display: block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.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; }
@@ -1256,6 +1289,25 @@ button.status-issue + .status-metric { margin-left: 6px; }
.setup-head h1 { font-size: var(--fs-24); font-weight: var(--fw-strong); letter-spacing: -0.02em; text-wrap: balance; }
.setup-head p { margin-top: var(--sp-1); color: var(--text-2); font-size: var(--fs-14); }
.setup-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); }
/* Read-only data folder screen (DataRootReadOnly) */
.dataroot-detail { font-size: var(--fs-12); color: var(--text-2); }
.dataroot-detail summary { cursor: pointer; }
.dataroot-detail pre {
margin: var(--sp-2) 0 0; padding: var(--sp-3); border-radius: var(--r-md);
background: var(--surface-1); border: 1px solid var(--border);
white-space: pre-wrap; word-break: break-word; max-height: 160px; overflow: auto;
}
/* First-run offer of a market language pack for the OS language */
.setup-langpack {
display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4);
border-radius: var(--r-lg); border: 1px solid var(--border); background: var(--surface-1);
cursor: pointer;
}
.setup-langpack:has(input:disabled) { cursor: default; opacity: 0.7; }
.setup-langpack > input { flex-shrink: 0; margin: 0; accent-color: var(--accent); }
.setup-langpack-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.setup-langpack-title { font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text); }
.setup-langpack-sub { font-size: var(--fs-12); color: var(--text-2); line-height: 1.45; }
.choices-list { display: flex; flex-direction: column; gap: var(--sp-2); }
.choice-card {
display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4);
@@ -1300,6 +1352,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
/* ── Motion (emil-design-eng & apple-design) ───────────── */
@keyframes rise-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
@keyframes fade-out { from { opacity: 1; } to { opacity: 0; } }
@keyframes pop-in { from { opacity: 0; transform: translate(-50%, -49%) scale(0.96); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } }
@keyframes menu-in { from { opacity: 0; transform: scale(0.96); } to { opacity: 1; transform: scale(1); } }
@keyframes tip-in { from { opacity: 0; transform: scale(0.96); } to { opacity: 1; transform: scale(1); } }
@@ -1311,10 +1364,13 @@ button.status-issue + .status-metric { margin-left: 6px; }
.page { animation: rise-in var(--dur) var(--ease-out) both; }
.overlay { animation: fade-in var(--dur) var(--ease-out) both; }
.dialog { animation: pop-in var(--dur-modal) var(--ease-out) both; }
.menu { transform-origin: var(--radix-dropdown-menu-content-transform-origin, top); animation: menu-in 160ms var(--ease-out) both; }
.menu[data-menubar-switch="true"] { animation: none; }
.tooltip { animation: tip-in 125ms var(--ease-out) both; }
.tooltip[data-state="instant-open"] { animation-duration: 0ms; }
.menu { transform-origin: var(--radix-dropdown-menu-content-transform-origin, top); }
.menu[data-state="open"] { animation: menu-in 160ms var(--ease-out) both; }
.menu[data-state="open"][data-menubar-switch="true"],
.menu[data-state="closed"] { animation: none; }
.tooltip[data-state="delayed-open"] { animation: tip-in 125ms var(--ease-out) both; }
.tooltip[data-state="instant-open"],
.tooltip[data-state="closed"] { animation: none; }
.pane-anim { display: flex; flex-direction: column; gap: 20px; animation: rise-in var(--dur) var(--ease-out) both; }
.step-anim { display: flex; flex-direction: column; gap: var(--sp-4); animation: rise-in var(--dur) var(--ease-out) both; }
@@ -1362,7 +1418,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
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);
background: rgba(20, 21, 26, 0.84); color: #fff;
font-size: var(--fs-12); font-weight: var(--fw-medium);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
opacity: 0; transform: translateX(-50%) translateY(4px);
@@ -1462,13 +1518,19 @@ button.status-issue + .status-metric { margin-left: 6px; }
/* Reduced motion: stop decorative loops & positional motion */
@media (prefers-reduced-motion: reduce) {
.status-busy, .vm-screen-live, .skeleton-bar { animation: none; }
.status-busy, .vm-screen-live, .skeleton-bar, .market-progress.is-indeterminate .market-progress-fill { animation: none; }
.vm-display-unit, .vm-display-unit.is-actionable:hover, .vm-display-unit.is-actionable:active { transform: none; }
.vm-screen-img, .vm-spec-meter .meter-fill { transition: none; }
.page, .dialog, .menu, .tooltip, .pane-anim, .step-anim, .toast[data-state="open"], .toast[data-state="closed"] {
.page, .dialog, .menu[data-state="open"]:not([data-menubar-switch="true"]), .tooltip[data-state="delayed-open"], .pane-anim, .step-anim, .toast[data-state="open"] {
animation-name: fade-in;
animation-duration: 140ms;
}
.toast[data-state="closed"],
.toast[data-swipe="end"],
:root[dir="rtl"] .toast[data-swipe="end"] {
animation-name: fade-out;
animation-duration: 140ms;
}
}
/* ── v0.2.6 Enhancements: Screenshot, Note, Dropzone, Snapshots, Log Filter, Welcome ── */
@@ -1477,14 +1539,13 @@ button.status-issue + .status-metric { margin-left: 6px; }
position: absolute; right: 8px; bottom: 8px; z-index: 3;
width: 30px; height: 30px; border: 1px solid rgba(255, 255, 255, 0.22); border-radius: 8px;
display: grid; place-items: center; cursor: pointer;
background: rgba(20, 22, 28, 0.68); color: #ffffff;
backdrop-filter: blur(10px);
background: rgba(20, 22, 28, 0.82); color: #ffffff;
opacity: 0; transform: translateY(3px);
transition: opacity var(--dur-fast) var(--ease-out), transform var(--dur-fast) var(--ease-out), background var(--dur-fast) var(--ease-out);
}
.vm-screen:hover .vm-screen-shot,
.vm-screen-shot:focus-visible { opacity: 1; transform: translateY(0); }
.vm-screen-shot:hover { background: rgba(20, 22, 28, 0.88); }
.vm-screen-shot:hover { background: rgba(20, 22, 28, 0.94); }
.vm-screen-shot:active { transform: scale(0.94); }
/* The title is the display name; click to rename in place. The pencil hangs
@@ -1538,9 +1599,8 @@ button.status-issue + .status-metric { margin-left: 6px; }
position: sticky; top: 0; z-index: 20;
display: flex; align-items: center; justify-content: center; gap: 8px;
padding: 12px 16px; border-radius: var(--r-lg);
background: var(--accent-soft); border: 1.5px dashed var(--accent);
background: color-mix(in srgb, var(--surface-canvas) 89%, var(--accent)); border: 1.5px dashed var(--accent);
color: var(--accent-soft-text); font-size: var(--fs-13); font-weight: var(--fw-medium);
backdrop-filter: var(--blur-overlay);
}
/* Interactive install stepper */
@@ -1613,6 +1673,65 @@ button.status-issue + .status-metric { margin-left: 6px; }
.rg-slot-inline { display: inline-flex; align-items: center; gap: 6px; }
.rg-slot-inline:empty { display: none; }
.rg-preview-anchor { position: absolute; z-index: 2; pointer-events: none; }
.titlebar-center {
position: absolute; left: 50%; top: 0; height: 100%; transform: translateX(-50%);
display: flex; align-items: center; gap: 6px; --wails-draggable: no-drag;
}
.nav-item-trailing { display: inline-flex; align-items: center; flex-shrink: 0; }
/* uiApi 2.0 full-window layers (ui-contract.ts): fixed to the window, never
take pointer input or focus, and freeze animations under reduced motion.
The shell is its own stacking context: the background layer (z -1) paints
over the shell's own background and under all of its content (themes make
the shell surfaces translucent to reveal it); the overlay layer (z 30) sits
above the titlebar and status bar (z 10). Dialogs, menus and tooltips are
portaled to body and the toaster sits outside the shell, so they stay on top. */
.app-shell { position: relative; isolation: isolate; }
.rg-layer { position: fixed; inset: 0; pointer-events: none; overflow: hidden; }
.rg-layer:empty { display: none; }
.rg-layer-background { z-index: -1; }
.rg-layer-overlay { z-index: 30; }
[data-motion="reduced"] .rg-layer *,
[data-motion="reduced"] .rg-layer *::before,
[data-motion="reduced"] .rg-layer *::after { animation-play-state: paused !important; transition: none !important; }
/* Theme decorations (ui-contract): images placed into slot anchors and layers. */
.rg-decoration { display: block; max-width: 100%; object-fit: contain; pointer-events: none; user-select: none; }
.rg-layer > .rg-decoration { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
/* Theme icon override: a packaged monochrome SVG tinted with currentColor. */
.rg-icon {
display: inline-block; flex-shrink: 0; background-color: currentColor;
-webkit-mask: var(--rg-icon) center / contain no-repeat; mask: var(--rg-icon) center / contain no-repeat;
}
/* Theme layout options (ui-contract; set from the active theme's `layout` as
data-layout-* on <html>). They move and size regions only. */
:root[data-layout-titlebar="compact"] { --titlebar-h: 34px; }
:root[data-layout-density="compact"] {
--sp-1: 3px; --sp-2: 6px; --sp-3: 9px; --sp-4: 12px; --sp-5: 16px; --sp-6: 20px; --sp-8: 26px;
}
:root[data-layout-density="compact"] .nav-item { height: 30px; }
:root[data-layout-density="comfortable"] {
--sp-1: 5px; --sp-2: 10px; --sp-3: 14px; --sp-4: 20px; --sp-5: 24px; --sp-6: 30px; --sp-8: 40px;
}
:root[data-layout-density="comfortable"] .nav-item { height: 42px; }
:root[data-layout-sidebar="right"] .workspace { flex-direction: row-reverse; }
:root[data-layout-sidebar="right"] .sidebar-wrap { border-inline-end: 0; border-inline-start: 1px solid var(--border); }
:root[data-layout-sidebar-mode="floating"] .sidebar-wrap { background: transparent; border-color: transparent; }
:root[data-layout-sidebar-mode="floating"] .sidebar { box-shadow: var(--shadow-overlay); }
/* Rail: icons only. Labels stay as accessible names and tooltips. */
:root[data-layout-sidebar-mode="rail"] { --sidebar-w: 76px; }
:root[data-layout-sidebar-mode="rail"] .sidebar-brand-name,
:root[data-layout-sidebar-mode="rail"] .sidebar-head > span,
:root[data-layout-sidebar-mode="rail"] .nav-label,
:root[data-layout-sidebar-mode="rail"] .update-capsule-title,
:root[data-layout-sidebar-mode="rail"] .update-capsule-btn { display: none; }
:root[data-layout-sidebar-mode="rail"] .sidebar-brand,
:root[data-layout-sidebar-mode="rail"] .sidebar-head { justify-content: center; padding-inline: 0; }
:root[data-layout-sidebar-mode="rail"] .nav-item { justify-content: center; padding: 0; position: relative; }
:root[data-layout-sidebar-mode="rail"] .nav-item .status { position: absolute; top: 4px; inset-inline-end: 6px; }
:root[data-layout-sidebar-mode="rail"] .nav-item .nav-dot { position: absolute; top: 4px; inset-inline-start: 6px; }
.rg-preview-anchor:empty { display: none; }
.rg-preview-anchor.tl { top: 6px; left: 6px; }
.rg-preview-anchor.tr { top: 6px; right: 6px; }
@@ -1623,37 +1742,35 @@ button.status-issue + .status-metric { margin-left: 6px; }
border: 1px solid var(--border); border-radius: var(--r-lg);
overflow: hidden; background: var(--surface-1); margin-bottom: var(--sp-3);
}
.plugin-panel-wrap.is-headless { margin-bottom: 0; }
.plugin-panel-head {
padding: 8px 12px; font-size: var(--fs-12); font-weight: var(--fw-medium);
color: var(--text-2); border-bottom: 1px solid var(--border);
}
.plugin-panel-frame { display: block; width: 100%; border: 0; background: transparent; }
.plugin-panel-error {
display: flex; align-items: center; justify-content: space-between;
padding: 12px 14px; border: 1px solid var(--danger-border); border-radius: var(--r-md);
background: var(--danger-soft); color: var(--danger-text); font-size: var(--fs-12);
.plugin-search-wrap { position: relative; display: flex; align-items: center; }
.plugin-search-wrap.is-wide { width: 100%; }
.plugin-search-icon {
position: absolute; inset-inline-start: 10px; color: var(--text-3); pointer-events: none;
}
.plugins-search-wrap { position: relative; display: flex; align-items: center; }
.plugins-search-icon {
position: absolute; left: 10px; color: var(--text-3); pointer-events: none;
}
.plugins-search { width: 210px; padding-left: 30px; }
.plugin-search { width: 210px; padding-inline-start: 30px; }
.plugin-search-wrap.is-wide .plugin-search { width: 100%; }
.plugins-scheme-dot {
width: 9px; height: 9px; border-radius: 50%; flex-shrink: 0;
border: 1px solid var(--border-strong); display: inline-block;
}
.plugin-cat-pill {
.plugin-pill {
display: inline-flex; align-items: center; gap: 6px;
height: 26px; padding: 0 11px; border-radius: 999px;
border: 1px solid var(--border); background: var(--surface-1);
color: var(--text-2); font-size: var(--fs-12); font-weight: var(--fw-medium);
cursor: pointer; transition: background 0.12s ease, border-color 0.12s ease, color 0.12s ease;
}
.plugin-cat-pill:hover { background: var(--surface-hover); color: var(--text); }
.plugin-cat-pill.is-active {
background: var(--accent-soft); border-color: var(--accent); color: var(--accent-soft-text);
border: 1px solid transparent; background: transparent;
color: var(--text-2); font: inherit; font-size: var(--fs-12); font-weight: var(--fw-medium);
cursor: pointer; transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out);
}
.plugin-pill:hover { background: var(--surface-hover); color: var(--text); }
.plugin-pill.is-active { background: var(--accent-soft); color: var(--accent-soft-text); }
.plugin-pill-count { color: var(--text-3); font-variant-numeric: tabular-nums; }
.plugin-pill.is-active .plugin-pill-count { color: inherit; opacity: 0.7; }
/* iOS/macOS App Store–inspired squircle icon tiles */
.plugin-app-icon {
@@ -1661,6 +1778,8 @@ button.status-issue + .status-metric { margin-left: 6px; }
display: inline-flex; align-items: center; justify-content: center;
color: #fff; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.28), 0 1px 2px rgba(0, 0, 0, 0.14);
}
.plugin-app-icon.is-md { width: 34px; height: 34px; border-radius: 9px; }
.plugin-app-icon.is-sm { width: 30px; height: 30px; border-radius: 8px; }
.plugin-app-icon.tone-indigo { background: linear-gradient(145deg, #6e7cf0 0%, #4d5be0 100%); }
.plugin-app-icon.tone-purple { background: linear-gradient(145deg, #bf5af2 0%, #8944ab 100%); }
.plugin-app-icon.tone-sky { background: linear-gradient(145deg, #32a0ff 0%, #007aff 100%); }
@@ -1675,8 +1794,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
.plugins-page-title { flex-direction: column; align-items: flex-start; gap: 1px; }
.plugins-page-title > span { color: var(--text-3); font-size: var(--fs-12); line-height: 1.45; }
.plugin-row { gap: 12px; min-height: 60px; }
.plugin-row .plugin-app-icon { width: 34px; height: 34px; border-radius: 9px; }
.plugin-row .plugin-app-icon svg { width: 18px; height: 18px; }
.plugin-row-name { font-weight: var(--fw-medium); }
.plugin-row-desc {
color: var(--text-2); line-height: 1.45;
@@ -1686,19 +1803,115 @@ button.status-issue + .status-metric { margin-left: 6px; }
.plugin-row-alert { display: flex; align-items: center; gap: 5px; color: var(--warn-text); }
.plugin-row-locked { display: inline-flex; border-radius: 999px; }
.plugin-row-locked .switch { pointer-events: none; }
.plugin-trust { display: inline-flex; align-items: center; gap: 3px; font-weight: var(--fw-medium); }
.plugin-trust.is-official, .plugin-trust.is-verified { color: var(--ok-text); }
.plugin-trust.is-dev { color: var(--accent-soft-text); }
.plugin-trust.is-community { color: var(--text-2); }
.plugin-trust {
display: inline-flex; align-items: center; gap: 4px; min-width: 0;
color: var(--text-2); border-radius: var(--r-sm); outline-offset: 2px;
}
.plugin-trust svg { flex-shrink: 0; }
.plugin-trust-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.plugin-trust.is-official svg { color: var(--accent); }
.plugin-trust.is-verified svg { color: var(--ok-text); }
.plugin-trust.is-dev svg { color: var(--accent-soft-text); }
.plugin-trust.is-community svg { color: var(--text-3); }
.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; }
.plugins-switch { display: flex; }
/* Plugin market: cache-first feed of cards in as many columns as fit */
.plugin-market { gap: 12px; }
.market-toolbar { display: flex; flex-direction: column; gap: 10px; }
.market-kinds { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.market-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; }
.market-card {
display: flex; flex-direction: column; gap: 10px; min-width: 0;
padding: 14px 14px 15px; border-radius: var(--r-lg);
background: var(--surface-1); border: 1px solid var(--border); box-shadow: var(--shadow-card);
animation: market-card-in 320ms var(--ease-out) both;
animation-delay: calc(var(--i, 0) * 28ms);
}
@keyframes market-card-in { from { opacity: 0; transform: translateY(6px); } }
.market-card.is-muted .market-card-head > .plugin-app-icon,
.market-card.is-muted .market-card-titles,
.market-card.is-muted .market-card-desc { opacity: 0.55; }
.market-card-head { display: flex; align-items: center; gap: 12px; min-width: 0; }
.market-card-titles { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
.market-card-name {
margin: 0; font-size: var(--fs-14); font-weight: var(--fw-strong); color: var(--text); line-height: 1.3;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.market-card-byline {
display: flex; align-items: center; gap: 5px; min-width: 0;
font-size: var(--fs-12); color: var(--text-3); line-height: 1.4;
}
.market-card-dot { flex-shrink: 0; }
.market-card-version { flex-shrink: 0; font-variant-numeric: tabular-nums; }
.market-card-action { flex-shrink: 0; }
.market-card-action .btn.market-btn { height: 28px; padding: 0 12px; font-size: var(--fs-12); }
.market-card-desc {
margin: 0; font-size: var(--fs-13); color: var(--text-2); line-height: 1.5;
min-height: calc(2 * 1.5em);
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
}
.market-progress {
position: relative; overflow: hidden; isolation: isolate;
width: 84px; height: 28px; border-radius: var(--r-md);
background: var(--surface-active);
display: inline-flex; align-items: center; justify-content: center;
}
.market-progress-fill {
position: absolute; inset: 0; z-index: -1; width: 100%;
background: var(--accent-soft); transform-origin: left center;
transition: transform 160ms linear;
}
.market-progress.is-indeterminate .market-progress-fill {
inset: 0 auto 0 0; width: 40%; animation: market-progress-sweep 1.1s var(--ease-in-out) infinite;
}
@keyframes market-progress-sweep { from { transform: translateX(-100%); } to { transform: translateX(250%); } }
.market-progress-text {
font-size: var(--fs-12); font-weight: var(--fw-medium); color: var(--accent-soft-text);
font-variant-numeric: tabular-nums;
}
.market-loader { padding: 56px 0 48px; }
.market-sentinel { height: 1px; }
.market-feed-end { padding: 4px 0 8px; text-align: center; color: var(--text-3); font-size: var(--fs-12); }
/* Wordmark written stroke by stroke (WordmarkLoader) */
.wordmark-loader { display: flex; flex-direction: column; align-items: center; gap: 14px; }
.wordmark-loader-svg { display: block; overflow: visible; }
.wordmark-loader-ink { stroke: var(--text); }
.wordmark-loader-dash { stroke: var(--text-3); }
.wordmark-loader-dot { fill: #ff7a9a; }
.wordmark-loader-label { font-size: var(--fs-12); color: var(--text-3); }
@media (prefers-reduced-motion: reduce) {
.wordmark-loader-svg { animation: wordmark-pulse 1.6s var(--ease-in-out) infinite alternate; }
.market-card { animation: none; }
}
@keyframes wordmark-pulse { from { opacity: 0.35; } to { opacity: 1; } }
/* What a plugin can do, shown before enabling it */
.plugin-enable-lead { margin: 0; font-size: var(--fs-13); color: var(--text-2); }
.plugin-log-pre {
margin: 0; font-size: var(--fs-12); line-height: 1.55;
white-space: pre-wrap; word-break: break-word;
}
.plugin-risk-list {
margin: 0; padding: 4px 0; list-style: none;
background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg);
}
.plugin-risk {
display: flex; align-items: center; gap: 10px; padding: 8px 14px;
font-size: var(--fs-13); color: var(--text);
}
.plugin-risk-icon {
width: 26px; height: 26px; border-radius: 8px; flex-shrink: 0;
display: inline-flex; align-items: center; justify-content: center;
background: var(--surface-active); color: var(--text-2);
}
.plugin-risk.is-high .plugin-risk-icon { background: var(--warn-soft); color: var(--warn-text); }
.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 { font-size: var(--fs-12); font-weight: var(--fw-strong); 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; }
@@ -1764,6 +1977,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
max-height: 180px; overflow: auto;
background: var(--surface-0); border: 1px solid var(--border);
white-space: pre-wrap; word-break: break-word;
text-rendering: auto; text-autospace: no-autospace;
}
.error-boundary-actions { display: flex; gap: var(--sp-2); justify-content: flex-end; }
@@ -1778,7 +1992,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
.sidebar-backdrop {
display: block; position: absolute;
inset: 0;
background: var(--scrim); backdrop-filter: blur(3px); z-index: 31;
background: var(--scrim); z-index: 31;
}
.sidebar-wrap {
position: absolute; z-index: 32;
@@ -1800,17 +2014,21 @@ button.status-issue + .status-metric { margin-left: 6px; }
.settings-pane { padding: 16px; }
}
@container (max-width: 520px) {
.row, .srow-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); }
.row-main, .srow-text { flex: 1 1 220px; }
.row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; }
}
@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; }
.conn-row, .srow-head, .row, .page-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); }
.row-main, .srow-text { flex: 1 1 220px; }
.conn-ctrl, .row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; }
.plugin-search-wrap, .plugin-search { width: 100%; }
}
}
@@ -1821,4 +2039,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
.rg-p-titlebar { --wails-draggable: drag !important; }
:focus-visible:not(.dialog):not(.menu) { box-shadow: var(--focus-ring) !important; }
.icon-btn, .win-btn { min-width: 28px !important; min-height: 28px !important; }
/* Layers and decorations never take input, whatever a theme says. */
.rg-layer, .rg-layer *, .rg-decoration { pointer-events: none !important; }
}
+8 -6
View File
@@ -90,17 +90,19 @@
--surface-statusbar: #eef3fa;
--surface-1: #f5f6f8;
--surface-card-elevated: #ffffff;
--surface-2: rgba(255, 255, 255, 0.94);
--surface-2: rgba(255, 255, 255, 0.98);
--surface-input: #ffffff;
--surface-hover: rgba(15, 23, 42, 0.048);
--surface-active: rgba(15, 23, 42, 0.085);
--border: rgba(15, 23, 42, 0.08);
--border-strong: rgba(15, 23, 42, 0.14);
--highlight-top: inset 0 1px 0 rgba(255, 255, 255, 0.85);
--scrim: rgba(15, 23, 42, 0.28);
--scrim: rgba(15, 23, 42, 0.34);
--shadow-btn: 0 1px 2px rgba(15, 23, 42, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.7);
--shadow-card: 0 1px 2px rgba(15, 23, 42, 0.025);
--shadow-overlay: 0 22px 58px rgba(15, 23, 42, 0.18), 0 4px 14px rgba(15, 23, 42, 0.06), 0 0 0 1px rgba(15, 23, 42, 0.06);
--shadow-overlay: 0 16px 36px rgba(15, 23, 42, 0.16), 0 3px 10px rgba(15, 23, 42, 0.06), 0 0 0 1px rgba(15, 23, 42, 0.06);
/* Retained for UI Contract v1 (uiApi 1.0.0) theme compatibility; unused by default
base styles while main.go runs WebView2 in software compositing mode. */
--blur-chrome: blur(20px) saturate(180%);
--blur-overlay: blur(18px) saturate(165%);
@@ -167,17 +169,17 @@
--surface-statusbar: #18191e;
--surface-1: rgba(255, 255, 255, 0.048);
--surface-card-elevated: rgba(255, 255, 255, 0.075);
--surface-2: rgba(42, 43, 50, 0.94);
--surface-2: rgba(42, 43, 50, 0.98);
--surface-input: rgba(0, 0, 0, 0.28);
--surface-hover: rgba(255, 255, 255, 0.075);
--surface-active: rgba(255, 255, 255, 0.12);
--border: rgba(255, 255, 255, 0.085);
--border-strong: rgba(255, 255, 255, 0.16);
--highlight-top: inset 0 1px 0 rgba(255, 255, 255, 0.08);
--scrim: rgba(0, 0, 0, 0.56);
--scrim: rgba(0, 0, 0, 0.58);
--shadow-btn: 0 1px 2px rgba(0, 0, 0, 0.30), inset 0 1px 0 rgba(255, 255, 255, 0.06);
--shadow-card: 0 1px 3px rgba(0, 0, 0, 0.18);
--shadow-overlay: 0 26px 68px rgba(0, 0, 0, 0.58), 0 0 0 1px rgba(255, 255, 255, 0.09);
--shadow-overlay: 0 18px 40px rgba(0, 0, 0, 0.52), 0 0 0 1px rgba(255, 255, 255, 0.09);
--text: #f5f5f7;
--text-2: #c2c2ca;
+188 -5
View File
@@ -1,7 +1,17 @@
// Single source of truth for UI Contract v1 (docs/plugin-architecture.md §5.1).
// Renaming or removing any part, state attribute, or token here is a uiApi major bump.
// Single source of truth for UI Contract v2 (docs/plugin-architecture.md §5.1, §6.3).
// Renaming or removing any stable entry here is a uiApi major bump.
//
// Every entry is either stable or experimental. Stable entries must be emitted
// by the host (scripts/check-ui-contract.mjs fails the build otherwise) and are
// covered by the compatibility promise. Experimental entries are part of the
// published shape so plugins can be written against it, but the host does not
// render them yet: `plugin doctor` warns, and they carry no compatibility
// promise until promoted. Promote an entry by moving it into the stable list
// in the same change that renders it. The Go side mirrors slots, layout
// options, icon names and view locations in internal/plugin/contract.go, and a
// Go test keeps both in step.
export const UI_API_VERSION = '1.0.0' as const
export const UI_API_VERSION = '2.0.0' as const
export const UI_CONTRACT_PARTS = [
'rg-p-shell',
@@ -20,10 +30,31 @@ export const UI_CONTRACT_PARTS = [
'rg-p-logpanel',
'rg-p-settings',
'rg-p-empty',
// Control-level parts.
'rg-p-nav-group',
'rg-p-nav-item',
'rg-p-button',
'rg-p-icon-button',
'rg-p-card',
'rg-p-badge',
'rg-p-tabs',
'rg-p-tab',
'rg-p-menu',
'rg-p-menu-item',
'rg-p-dialog',
'rg-p-toast',
'rg-p-tooltip',
'rg-p-input',
'rg-p-switch',
'rg-p-progress',
'rg-p-vm-actions',
'rg-p-plugin-view',
] as const
export type UIContractPart = (typeof UI_CONTRACT_PARTS)[number]
export const UI_CONTRACT_PARTS_EXPERIMENTAL = [] as const
export const UI_CONTRACT_STATE_ATTRS = [
'data-theme',
'data-motion',
@@ -34,23 +65,147 @@ export const UI_CONTRACT_STATE_ATTRS = [
'data-has-error',
'data-sidebar-collapsed',
'data-safe-mode',
// Set from the active theme layout options; absent with the built-in theme.
'data-layout-sidebar',
'data-layout-sidebar-mode',
'data-layout-density',
'data-layout-titlebar',
] as const
export const UI_CONTRACT_STATE_ATTRS_EXPERIMENTAL = [] as const
// Per-item state attributes, written as `<part>:<attribute>`.
export const UI_CONTRACT_ITEM_STATES = [
'rg-p-nav-item:data-vm-state',
'rg-p-nav-item:data-driver',
'rg-p-nav-item:data-selected',
'rg-p-nav-item:data-busy',
'rg-p-vm-page:data-vm-state',
'rg-p-vm-page:data-driver',
'rg-p-button:data-variant',
'rg-p-button:data-busy',
'rg-p-icon-button:data-busy',
'rg-p-dialog:data-tone',
'rg-p-toast:data-tone',
] as const
export const UI_CONTRACT_ITEM_STATES_EXPERIMENTAL = [] as const
// Slot anchors (`data-rg-slot`) that decorations and UI SDK mounts can target.
// `nav.item.trailing` repeats once per VM entry, keyed by `data-rg-key`
// (the VM reference). Which plugin contributions a slot accepts is declared
// on the Go side.
export const UI_CONTRACT_SLOTS = [
'titlebar.center',
'sidebar.header',
'sidebar.footer',
'statusbar.right',
'nav.item.trailing',
'vm.header.trailing',
'vm.toolbar',
'vm.card',
'settings.plugin',
'vm.preview.tl',
'vm.preview.tr',
'vm.preview.bl',
'vm.preview.br',
'statusbar.left',
'statusbar.right',
'empty.state',
'create.source',
'settings.plugin',
] as const
export type UIContractSlot = (typeof UI_CONTRACT_SLOTS)[number]
export const UI_CONTRACT_SLOTS_EXPERIMENTAL = [] as const
// Full-window layers (`data-rg-layer`): never take pointer input or focus;
// animations freeze under reduced motion. Decorations and UI SDK mounts can
// target them like slots.
export const UI_CONTRACT_LAYERS = [
'layer.background',
'layer.overlay',
] as const
export type UIContractLayer = (typeof UI_CONTRACT_LAYERS)[number]
export const UI_CONTRACT_LAYERS_EXPERIMENTAL = [] as const
// Theme `layout` options, written as `<option>=<value>`; each becomes a
// data-layout-* attribute on <html>. They move and size regions only;
// operation entries always stay reachable.
export const UI_CONTRACT_LAYOUT_OPTIONS = [
'sidebarPosition=left',
'sidebarPosition=right',
'sidebarMode=full',
'sidebarMode=rail',
'sidebarMode=floating',
'density=compact',
'density=regular',
'density=comfortable',
'titlebar=standard',
'titlebar=compact',
] as const
export const UI_CONTRACT_LAYOUT_OPTIONS_EXPERIMENTAL = [] as const
// Icon names a theme can map to a packaged monochrome SVG via `icons`.
// Every name is rendered through <HostIcon> somewhere in the host.
export const UI_CONTRACT_ICONS = [
'start',
'stop',
'force-stop',
'restart',
'suspend',
'resume',
'new-vm',
'settings',
'plugin',
'folder',
'logs',
'screenshot',
'fullscreen',
'window',
'snapshot',
'clone',
'delete',
'info',
'warning',
'error',
'vm.state.running',
'vm.state.stopped',
'vm.state.suspended',
'vm.state.busy',
'vm.state.error',
] as const
export type UIContractIcon = (typeof UI_CONTRACT_ICONS)[number]
export const UI_CONTRACT_ICONS_EXPERIMENTAL = [] as const
// Where plugin `views` can appear (§5.6).
export const UI_CONTRACT_VIEW_LOCATIONS = [] as const
export const UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL = [
'sidebar',
'vm.tab',
'settings',
'dialog',
] as const
// UI SDK event stream for interactive themes (`sdk.on(event, cb)`).
export const UI_CONTRACT_SDK_EVENTS = [
'vm.stateChanged',
'task.started',
'task.progress',
'task.finished',
'toast.shown',
'view.changed',
] as const
export type UIContractSDKEvent = (typeof UI_CONTRACT_SDK_EVENTS)[number]
export const UI_CONTRACT_SDK_EVENTS_EXPERIMENTAL = [] as const
export const UI_CONTRACT_TOKENS = [
'--font-sans', '--font-cjk', '--font-mono',
'--body-lh', '--heading-tracking',
@@ -80,6 +235,34 @@ export const UI_CONTRACT = {
uiApi: UI_API_VERSION,
parts: [...UI_CONTRACT_PARTS],
stateAttrs: [...UI_CONTRACT_STATE_ATTRS],
itemStates: [...UI_CONTRACT_ITEM_STATES],
slots: [...UI_CONTRACT_SLOTS],
layers: [...UI_CONTRACT_LAYERS],
layoutOptions: [...UI_CONTRACT_LAYOUT_OPTIONS],
icons: [...UI_CONTRACT_ICONS],
viewLocations: [...UI_CONTRACT_VIEW_LOCATIONS],
sdkEvents: [...UI_CONTRACT_SDK_EVENTS],
tokens: [...UI_CONTRACT_TOKENS],
experimental: {
parts: [...UI_CONTRACT_PARTS_EXPERIMENTAL],
stateAttrs: [...UI_CONTRACT_STATE_ATTRS_EXPERIMENTAL],
itemStates: [...UI_CONTRACT_ITEM_STATES_EXPERIMENTAL],
slots: [...UI_CONTRACT_SLOTS_EXPERIMENTAL],
layers: [...UI_CONTRACT_LAYERS_EXPERIMENTAL],
layoutOptions: [...UI_CONTRACT_LAYOUT_OPTIONS_EXPERIMENTAL],
icons: [...UI_CONTRACT_ICONS_EXPERIMENTAL],
viewLocations: [...UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL],
sdkEvents: [...UI_CONTRACT_SDK_EVENTS_EXPERIMENTAL],
},
}
// Stable host features advertised to themes through the UI SDK (§6.3).
export const UI_CONTRACT_FEATURES: readonly string[] = [
...UI_CONTRACT_SLOTS.map((s) => `slot.${s}`),
...UI_CONTRACT_LAYERS,
'theme.layout',
'theme.icons',
'theme.brandMark',
'theme.decorations',
...UI_CONTRACT_SDK_EVENTS.map((e) => `sdk.event.${e}`),
]
+33 -6
View File
@@ -1,7 +1,7 @@
// Backend types come from the Wails-generated models (wailsjs/go/models.ts,
// regenerated by `wails dev` / `wails build`). This file only adds what Go
// cannot say: string unions, and `| null` for slices Go may send as nil.
import { app, config, driver, host, installer, plugin, reims, runtime, version } from '../wailsjs/go/models'
import { app, config, driver, host, installer, opencore, plugin, reims, runtime, version } from '../wailsjs/go/models'
/** A generated class as a plain data shape (no convertValues helper). */
type Model<T> = Omit<T, 'convertValues'>
@@ -47,8 +47,9 @@ export type RemoteRuntime = Model<runtime.Remote> & {
channel: 'stable' | 'alpha'
}
export type VMListItem = Model<reims.VMListItem> & {
state: 'running' | 'stopped' | 'broken'
export type VMListItem = Model<driver.VMListItem> & {
driver_id?: string
state: 'running' | 'stopped' | 'suspended' | 'broken' | 'driver_unavailable'
}
export type PendingChange = app.PendingChange
@@ -60,12 +61,18 @@ export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizati
runtimes: InstalledRuntime[] | null
active_runtime?: InstalledRuntime
vms: VMListItem[] | null
vm_list_error?: string
}
export type AppUpdateInfo = version.UpdateInfo
export type SuspendInfo = reims.SuspendInfo
export type VMDetail = reims.VMDetail
export type SMBIOSIdentity = opencore.SMBIOSIdentity
export type VMStats = app.VMStats
export type DriveShareSettings = Model<app.DriveShareSettings>
export type SharedFolderInfo = Model<app.SharedFolderInfo>
export type SharedFolderSettings = Model<app.SharedFolderSettings>
export type SharedFolderMode = 'disabled' | 'ro' | 'rw'
export type VMAffinityMode = 'auto' | 'all' | 'pcores' | 'non_lpe' | 'custom'
export type VMAffinityUpdate = {
mode: VMAffinityMode
@@ -79,9 +86,9 @@ export type VMAffinityStatus = Omit<Model<app.VMAffinityStatus>, 'mode' | 'effec
/** One frame of a VM's screen (internal/app/thumbnail_flow.go). Empty data_url: none yet. */
export type VMThumbnail = app.VMThumbnail
export type ValidationIssue = reims.ValidationIssue
export type DiskResizeResult = reims.DiskResizeResult
export type DiskCompactResult = reims.DiskCompactResult
export type DiskSnapshot = reims.DiskSnapshot
export type DiskResizeResult = driver.DiskResizeResult
export type DiskCompactResult = driver.DiskCompactResult
export type DiskSnapshot = driver.DiskSnapshot
export type StorageBreakdown = Model<app.StorageBreakdown>
export type SetOpts = reims.SetOpts
@@ -158,6 +165,7 @@ export type ResolvedLocalePack = Model<plugin.ResolvedLocalePack> & {
export type MenuContribution = plugin.MenuContribution
export type VMCardContribution = plugin.VMCardContribution
export type PanelContribution = plugin.PanelContribution
export type ImageSourceContribution = plugin.ImageSourceContribution
export type StatusItemContribution = plugin.StatusItemContribution
export type PluginUIContributions = app.PluginUIContributions
export type DriverSummary = driver.DriverSummary
@@ -170,3 +178,22 @@ export interface LogEntry {
source: string
line: string
}
export type VMKeymapPreset = 'off' | 'win_to_cmd' | 'swap_alt_win' | 'custom'
export type VMKeymapHostModifier = 'lwin' | 'rwin' | 'lalt' | 'ralt' | 'lctrl' | 'rctrl' | 'capslock'
export type VMKeymapGuestModifier = 'default' | 'lcmd' | 'rcmd' | 'lopt' | 'ropt' | 'lctrl' | 'rctrl' | 'esc' | 'disabled'
export interface VMKeymapUpdate {
preset: VMKeymapPreset
bindings: Partial<Record<VMKeymapHostModifier, VMKeymapGuestModifier>>
}
export interface VMKeymapStatus extends VMKeymapUpdate {
needs_guest_tools: boolean
guest_connected: boolean
guest_agent_version?: number
required_agent_version: number
input_service_available: boolean
guest_keymap_active: boolean
hook_active: boolean
running: boolean
}
+24 -7
View File
@@ -1,6 +1,8 @@
import * as RTooltip from '@radix-ui/react-tooltip'
import { LoaderCircle } from 'lucide-react'
import React from 'react'
import type { UIContractIcon } from '../styles/ui-contract'
import { HostIcon } from './themeVisuals'
export const TooltipProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => (
<RTooltip.Provider delayDuration={400} skipDelayDuration={200}>{children}</RTooltip.Provider>
@@ -24,7 +26,7 @@ export const Tip: React.FC<TipProps> = ({ label, shortcut, side = 'bottom', disa
<RTooltip.Root open={disabled ? false : open} onOpenChange={(next) => setOpen(disabled ? false : next)}>
<RTooltip.Trigger asChild>{children}</RTooltip.Trigger>
<RTooltip.Portal>
<RTooltip.Content className="tooltip" side={side} sideOffset={6} collisionPadding={8}>
<RTooltip.Content className="tooltip rg-p-tooltip" side={side} sideOffset={6} collisionPadding={8}>
{label}
{shortcut && <kbd>{shortcut}</kbd>}
</RTooltip.Content>
@@ -46,7 +48,9 @@ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
<button
ref={ref}
type="button"
className={`btn${variant === 'secondary' ? '' : ` btn-${variant}`}${className ? ` ${className}` : ''}`}
className={`btn rg-p-button${variant === 'secondary' ? '' : ` btn-${variant}`}${className ? ` ${className}` : ''}`}
data-variant={variant}
data-busy={busy ? 'true' : undefined}
disabled={disabled || busy}
aria-busy={busy || undefined}
{...rest}
@@ -75,7 +79,8 @@ export const IconButton = React.forwardRef<HTMLButtonElement, IconButtonProps>(
ref={ref}
type="button"
aria-label={label}
className={`icon-btn${small ? ' sm' : ''}${className ? ` ${className}` : ''}`}
className={`icon-btn rg-p-icon-button${small ? ' sm' : ''}${className ? ` ${className}` : ''}`}
data-busy={busy ? 'true' : undefined}
disabled={disabled || busy}
aria-busy={busy || undefined}
{...rest}
@@ -87,17 +92,29 @@ export const IconButton = React.forwardRef<HTMLButtonElement, IconButtonProps>(
)
IconButton.displayName = 'IconButton'
export type StatusKind = 'running' | 'stopped' | 'busy' | 'broken' | 'warn'
export type StatusKind = 'running' | 'stopped' | 'suspended' | '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 === 'suspended') return 'suspended'
if (state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' || state === 'creating') return 'busy'
if (state === 'driver_unavailable') return 'warn'
if (state === 'broken') return 'broken'
return 'stopped'
}
/** Status shape: differs by shape as well as colour. */
const STATUS_ICON: Record<StatusKind, UIContractIcon> = {
running: 'vm.state.running',
stopped: 'vm.state.stopped',
suspended: 'vm.state.suspended',
busy: 'vm.state.busy',
broken: 'vm.state.error',
warn: 'vm.state.error',
}
/** Status shape: differs by shape as well as colour; themes may replace it by icon name. */
export const StatusShape: React.FC<{ kind: StatusKind }> = ({ kind }) => (
<span className={`status status-${kind}`} aria-hidden="true" />
<HostIcon name={STATUS_ICON[kind]} size={10}>
<span className={`status status-${kind}`} aria-hidden="true" />
</HostIcon>
)
+99 -39
View File
@@ -1,56 +1,116 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import * as RDialog from '@radix-ui/react-dialog'
import { X } from 'lucide-react'
import React from 'react'
import { IconButton } from './controls'
import { Button, IconButton } from './controls'
interface ConfirmDialogProps {
title: string
description: string
cancelLabel: string
confirmLabel: string
onCancel: () => void
onConfirm: () => void
children?: React.ReactNode
}
export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, children }) => {
const prevFocusRef = React.useRef<HTMLElement | null>(
typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
? document.activeElement
: null,
)
return (
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content
className="dialog rg-p-dialog sm"
data-tone="danger"
onCloseAutoFocus={(e) => {
e.preventDefault()
const prev = prevFocusRef.current
if (prev?.isConnected) prev.focus({ preventScroll: true })
}}
>
<div className="dialog-body">
<Alert.Title className="dialog-title">{title}</Alert.Title>
<Alert.Description className="dialog-desc">{description}</Alert.Description>
{children}
</div>
<div className="dialog-foot">
<Alert.Cancel asChild><Button>{cancelLabel}</Button></Alert.Cancel>
<Alert.Action asChild><Button variant="danger" onClick={onConfirm}>{confirmLabel}</Button></Alert.Action>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
)
}
interface Props {
title: string
subtitle?: string
closeLabel: string
/** While false, Esc / outside click / ✕ are ignored (e.g. during a create). */
/** While false, Esc / ✕ are ignored (e.g. during a create). */
dismissable?: boolean
onClose: () => void
/** Extra class on the dialog box, e.g. a wider variant. */
className?: string
/** Exposed as data-tone for themes (ui-contract). */
tone?: 'neutral' | 'danger' | 'warn'
children: React.ReactNode
}
/** Modal frame: head with title and ✕; children supply body/steps/foot sections. */
export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, children }) => (
<RDialog.Root open onOpenChange={(open) => { if (!open && dismissable) onClose() }}>
<RDialog.Portal>
<RDialog.Overlay className="overlay" />
<RDialog.Content
className={className ? `dialog ${className}` : 'dialog'}
onInteractOutside={(e) => e.preventDefault()}
// Focus the first enabled form field, or the dialog container itself when there is
// none, so the top-right ✕ close button's tooltip never pops on open.
onOpenAutoFocus={(e) => {
const root = e.currentTarget as HTMLElement | null
if (!root) return
e.preventDefault()
const first = root.querySelector<HTMLElement>(
'input:not(:disabled):not([type="hidden"]):not([type="radio"]:not(:checked)), select:not(:disabled), textarea:not(:disabled)',
)
if (first) {
first.focus({ preventScroll: true })
}
if (!root.contains(document.activeElement)) {
root.focus({ preventScroll: true })
}
}}
>
<div className="dialog-head">
<div>
<RDialog.Title className="dialog-title">{title}</RDialog.Title>
{subtitle ? <RDialog.Description className="dialog-desc">{subtitle}</RDialog.Description> : <RDialog.Description />}
export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, tone = 'neutral', children }) => {
const prevFocusRef = React.useRef<HTMLElement | null>(
typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
? document.activeElement
: null,
)
return (
<RDialog.Root open onOpenChange={(open) => { if (!open && dismissable) onClose() }}>
<RDialog.Portal>
<RDialog.Overlay className="overlay" />
<RDialog.Content
className={className ? `dialog rg-p-dialog ${className}` : 'dialog rg-p-dialog'}
data-tone={tone}
onInteractOutside={(e) => e.preventDefault()}
// Focus the first enabled form field, or the dialog container itself when there is
// none, so the top-right ✕ close button's tooltip never pops on open.
onOpenAutoFocus={(e) => {
const root = e.currentTarget as HTMLElement | null
if (!root) return
e.preventDefault()
const first = root.querySelector<HTMLElement>(
'input:not(:disabled):not([type="hidden"]):not([type="radio"]:not(:checked)), select:not(:disabled), textarea:not(:disabled)',
)
if (first) {
first.focus({ preventScroll: true })
}
if (!root.contains(document.activeElement)) {
root.focus({ preventScroll: true })
}
}}
onCloseAutoFocus={(e) => {
e.preventDefault()
const prev = prevFocusRef.current
if (prev?.isConnected) prev.focus({ preventScroll: true })
}}
>
<div className="dialog-head">
<div>
<RDialog.Title className="dialog-title">{title}</RDialog.Title>
{subtitle ? <RDialog.Description className="dialog-desc">{subtitle}</RDialog.Description> : <RDialog.Description />}
</div>
<RDialog.Close asChild>
<IconButton label={closeLabel} icon={<X size={16} />} disabled={!dismissable} />
</RDialog.Close>
</div>
<RDialog.Close asChild>
<IconButton label={closeLabel} icon={<X size={16} />} disabled={!dismissable} />
</RDialog.Close>
</div>
{children}
</RDialog.Content>
</RDialog.Portal>
</RDialog.Root>
)
{children}
</RDialog.Content>
</RDialog.Portal>
</RDialog.Root>
)
}
+17 -11
View File
@@ -86,7 +86,7 @@ export const SetValue: React.FC<{ title: string; value: React.ReactNode; mono?:
)
export const Switch: React.FC<{ checked: boolean; onChange: (v: boolean) => void; label: string; disabled?: boolean }> = ({ checked, onChange, label, disabled }) => (
<label className="switch">
<label className="switch rg-p-switch">
<input type="checkbox" role="switch" aria-label={label} checked={checked} disabled={disabled} onChange={(e) => onChange(e.target.checked)} />
<span className="slider" />
</label>
@@ -122,7 +122,10 @@ export function Segmented<V extends string | number>({ options, value, onChange,
return next
})
}
useLayoutEffect(measure, [value, options])
const optionsSig = options.map((o) => `${String(o.value)}\x1f${o.label}`).join('\x1e')
const docDir = typeof document !== 'undefined' ? document.documentElement.dir : ''
// eslint-disable-next-line react-hooks/exhaustive-deps
useLayoutEffect(measure, [value, optionsSig, wide, docDir])
useEffect(() => {
if (!box.current || typeof ResizeObserver === 'undefined') return
let raf = 0
@@ -142,12 +145,13 @@ export function Segmented<V extends string | number>({ options, value, onChange,
}, [])
const onKey = (e: React.KeyboardEvent) => {
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft' && e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return
e.preventDefault()
const enabled = options.filter((o) => !o.disabled)
const i = enabled.findIndex((o) => o.value === value)
const isRTL = box.current ? getComputedStyle(box.current).direction === 'rtl' : false
const delta = (e.key === 'ArrowRight') !== isRTL ? 1 : -1
const forward = e.key === 'ArrowDown' || (e.key === 'ArrowRight' && !isRTL) || (e.key === 'ArrowLeft' && isRTL)
const delta = forward ? 1 : -1
const next = enabled[(i + delta + enabled.length) % enabled.length]
if (next) {
onChange(next.value)
@@ -155,19 +159,20 @@ export function Segmented<V extends string | number>({ options, value, onChange,
}
}
const hasActive = options.some((o) => o.value === value)
const firstEnabled = options.findIndex((o) => !o.disabled)
const hasActive = options.some((o) => !o.disabled && o.value === value)
return (
<div ref={box} className={`seg${wide ? ' seg-wide' : ''}`} role="radiogroup" aria-label={label} onKeyDown={onKey}>
{thumb && <span className="seg-thumb" style={{ transform: `translateX(${thumb.x}px)`, width: thumb.w }} aria-hidden="true" />}
{options.map((o, i) => {
const on = o.value === value
const on = !o.disabled && o.value === value
return (
<button
key={String(o.value)}
type="button"
role="radio"
aria-checked={on}
tabIndex={on || (!hasActive && i === 0) ? 0 : -1}
tabIndex={on || (!hasActive && i === firstEnabled) ? 0 : -1}
disabled={o.disabled}
onClick={() => onChange(o.value)}
>
@@ -352,7 +357,7 @@ export function OptionCards<V extends string>({ options, value, onChange, label,
<span className="opt-card-title" title={o.title}>{o.title}</span>
{o.sub && <span className="opt-card-sub">{o.sub}</span>}
{o.badges && o.badges.length > 0 && (
<span className="opt-card-badges">{o.badges.map((b) => <span key={b} className="badge badge-accent">{b}</span>)}</span>
<span className="opt-card-badges">{o.badges.map((b) => <span key={b} className="badge rg-p-badge badge-accent">{b}</span>)}</span>
)}
</label>
))}
@@ -384,8 +389,9 @@ export function PopupSelect<V extends string>({ value, options, onChange, label,
id?: string
}) {
const cur = options.find((o) => o.value === value)
const dir: 'ltr' | 'rtl' = typeof document !== 'undefined' && document.documentElement.dir === 'rtl' ? 'rtl' : 'ltr'
return (
<Menu.Root modal={false}>
<Menu.Root dir={dir} modal={false}>
<Menu.Trigger asChild>
<button type="button" id={id} className={`popup-btn${wide ? ' popup-wide' : ''}`} aria-label={label}>
<span className="popup-value">
@@ -396,10 +402,10 @@ export function PopupSelect<V extends string>({ value, options, onChange, label,
</button>
</Menu.Trigger>
<Menu.Portal>
<Menu.Content className="menu popup-menu" align="start" sideOffset={4} collisionPadding={8}>
<Menu.Content className="menu rg-p-menu popup-menu" align="start" sideOffset={4} collisionPadding={8}>
<Menu.RadioGroup value={value ?? ''} onValueChange={(v) => onChange(v as V)}>
{options.map((o) => (
<Menu.RadioItem key={o.value} value={o.value} disabled={o.disabled} className="menu-item popup-item">
<Menu.RadioItem key={o.value} value={o.value} disabled={o.disabled} className="menu-item rg-p-menu-item popup-item">
<Menu.ItemIndicator className="popup-check"><Check size={13} /></Menu.ItemIndicator>
<span className="popup-item-label">{o.label}</span>
{o.detail && <span className="popup-detail">{o.detail}</span>}
+175
View File
@@ -0,0 +1,175 @@
// Theme visuals from uiApi 2.0 (docs/plugin-architecture.md §5.1): icon
// overrides, the brand mark, and declarative decorations rendered into slot
// anchors (`data-rg-slot`) and full-window layers (`data-rg-layer`).
// With the built-in theme none of this injects anything.
import React, { createContext, useContext, useEffect, useMemo, useState } from 'react'
import { createPortal } from 'react-dom'
import { locText } from '../i18n'
import { matchDecorationState, themeAssetURL, type UIStateSnapshot } from '../lib/themeEngine'
import { UI_CONTRACT_ICONS, UI_CONTRACT_LAYERS, UI_CONTRACT_SLOTS, type UIContractIcon } from '../styles/ui-contract'
import type { ActiveThemePayload, Locale, ThemeDecoration } from '../types'
const DEFAULT_BRAND_MARK = '/logo.svg'
const KNOWN_ICONS = new Set<string>(UI_CONTRACT_ICONS)
const KNOWN_TARGETS = new Set<string>([...UI_CONTRACT_SLOTS, ...UI_CONTRACT_LAYERS])
export interface ThemeVisuals {
brandMarkURL: string
icons: Partial<Record<UIContractIcon, string>>
}
const EMPTY: ThemeVisuals = { brandMarkURL: DEFAULT_BRAND_MARK, icons: {} }
const ThemeVisualsContext = createContext<ThemeVisuals>(EMPTY)
function isBuiltin(payload: ActiveThemePayload | null): boolean {
return !payload?.theme || payload.theme_id === 'builtin.theme.default'
}
export function resolveThemeVisuals(payload: ActiveThemePayload | null): ThemeVisuals {
if (isBuiltin(payload)) return EMPTY
const th = payload!.theme!
const icons: Partial<Record<UIContractIcon, string>> = {}
for (const [name, rel] of Object.entries(th.icons ?? {})) {
const url = KNOWN_ICONS.has(name) ? themeAssetURL(payload, rel) : null
if (url) icons[name as UIContractIcon] = url
}
return { brandMarkURL: themeAssetURL(payload, th.brandMark) ?? DEFAULT_BRAND_MARK, icons }
}
export const ThemeVisualsProvider: React.FC<{ payload: ActiveThemePayload | null; children: React.ReactNode }> = ({ payload, children }) => {
const value = useMemo(() => resolveThemeVisuals(payload), [payload])
return <ThemeVisualsContext.Provider value={value}>{children}</ThemeVisualsContext.Provider>
}
export function useThemeVisuals(): ThemeVisuals {
return useContext(ThemeVisualsContext)
}
type IconChild = React.ReactElement<{ size?: number | string; 'data-rg-icon'?: string }>
/**
* A host icon a theme can replace by name (ui-contract UI_CONTRACT_ICONS).
* The child is the built-in icon; both carry `data-rg-icon` for styling.
*/
export const HostIcon: React.FC<{ name: UIContractIcon; size?: number; children: IconChild }> = ({ name, size: sizeProp, children }) => {
const { icons } = useThemeVisuals()
const url = icons[name]
if (!url) return React.cloneElement(children, { 'data-rg-icon': name })
const size = sizeProp ?? Number(children.props.size ?? 16)
return (
<span
className="rg-icon"
data-rg-icon={name}
aria-hidden="true"
style={{ width: size, height: size, ['--rg-icon' as string]: `url("${url}")` }}
/>
)
}
/** The product mark, replaceable by a theme's `brandMark`. */
export const BrandMark: React.FC<{ className: string }> = ({ className }) => {
const { brandMarkURL } = useThemeVisuals()
return <img className={className} src={brandMarkURL} alt="" aria-hidden="true" />
}
interface DecorationProps {
urls: string[]
fps: number
reducedMotion: boolean
width?: number
height?: number
alt: string
}
const DecorationImage: React.FC<DecorationProps> = ({ urls, fps, reducedMotion, width, height, alt }) => {
const [frame, setFrame] = useState(0)
const animate = urls.length > 1 && !reducedMotion
useEffect(() => {
setFrame(0)
if (!animate) return
const id = window.setInterval(() => setFrame((f) => (f + 1) % urls.length), 1000 / Math.min(30, Math.max(1, fps || 8)))
return () => window.clearInterval(id)
}, [animate, fps, urls.join('|')])
return (
<img
className="rg-decoration"
src={urls[animate ? frame : 0]}
width={width || undefined}
height={height || undefined}
alt={alt}
aria-hidden={alt ? undefined : true}
draggable={false}
/>
)
}
const anchorSelector = (target: string) => `[data-rg-slot="${CSS.escape(target)}"], [data-rg-layer="${CSS.escape(target)}"]`
/**
* Renders the active theme's decorations into every matching anchor. Anchors
* that repeat per VM (`nav.item.trailing`) evaluate states against that VM.
*/
export const ThemeDecorations: React.FC<{ payload: ActiveThemePayload | null; snap: UIStateSnapshot; locale: Locale }> = ({ payload, snap, locale }) => {
const decorations: ThemeDecoration[] = isBuiltin(payload)
? []
: (payload!.theme!.decorations ?? []).filter((d) => KNOWN_TARGETS.has(d.slot))
const targets = useMemo(() => [...new Set(decorations.map((d) => d.slot))], [decorations.map((d) => d.slot).join('|')])
const [anchors, setAnchors] = useState<Record<string, Element[]>>({})
// Anchors come and go with views; rescan once per frame after DOM changes.
useEffect(() => {
if (targets.length === 0) {
setAnchors({})
return
}
let raf = 0
const scan = () => {
raf = 0
const next: Record<string, Element[]> = {}
for (const target of targets) next[target] = Array.from(document.querySelectorAll(anchorSelector(target)))
setAnchors((prev) => {
const same = targets.every((tg) => (prev[tg]?.length ?? 0) === next[tg].length && next[tg].every((el, i) => prev[tg][i] === el))
return same ? prev : next
})
}
scan()
const obs = new MutationObserver(() => {
if (!raf) raf = requestAnimationFrame(scan)
})
obs.observe(document.body, { childList: true, subtree: true })
return () => {
obs.disconnect()
if (raf) cancelAnimationFrame(raf)
}
}, [targets.join('|')])
if (decorations.length === 0) return null
const reducedMotion = snap.motion === 'reduced'
const portals: React.ReactNode[] = []
for (const dec of decorations) {
for (const [i, anchor] of (anchors[dec.slot] ?? []).entries()) {
// Per-VM anchors read the VM's own state from the enclosing item.
const item = (anchor as HTMLElement).closest<HTMLElement>('[data-vm-state]')
const itemSnap = item && (anchor as HTMLElement).dataset.rgKey ? { ...snap, vmState: item.dataset.vmState ?? '', busy: item.dataset.busy === 'true' } : snap
const st = matchDecorationState(dec, itemSnap)
if (!st) continue
const frames = (st.frames ?? []).map((f) => themeAssetURL(payload, f)).filter((u): u is string => !!u)
const asset = themeAssetURL(payload, st.asset)
const urls = frames.length > 0 ? frames : asset ? [asset] : []
if (urls.length === 0) continue
portals.push(createPortal(
<DecorationImage
urls={urls}
fps={st.fps ?? 0}
reducedMotion={reducedMotion}
width={dec.width}
height={dec.height}
alt={dec.alt ? locText(dec.alt, locale, '') : ''}
/>,
anchor,
`${dec.id}:${i}`,
))
}
}
return <>{portals}</>
}
+9 -5
View File
@@ -1,5 +1,7 @@
import * as RToast from '@radix-ui/react-toast'
import { Check, CircleCheck, CircleX, X } from 'lucide-react'
import { HostIcon } from './themeVisuals'
import { emitThemeEvent } from '../lib/themeEngine'
import React, { useCallback, useState } from 'react'
import { IconButton } from './controls'
@@ -24,6 +26,7 @@ export function useToasts() {
const [items, setItems] = useState<ToastItem[]>([])
const push = useCallback((input: ToastInput) => {
setItems((prev) => [...prev.slice(-3), { ...input, id: seq++ }])
emitThemeEvent('toast.shown', { kind: input.kind, title: input.title })
}, [])
const remove = useCallback((id: number) => setItems((prev) => prev.filter((i) => i.id !== id)), [])
return { items, push, remove }
@@ -53,12 +56,13 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
setCopied(true)
window.setTimeout(() => setCopied(false), 1500)
})
.catch(() => {})
.catch((e) => console.warn('[toast] clipboard write failed:', e))
}
return (
<RToast.Root
className={`toast ${item.kind}${item.rawDetail || item.action ? ' has-extra' : ''}`}
className={`toast rg-p-toast ${item.kind}${item.rawDetail || item.action ? ' has-extra' : ''}`}
data-tone={item.kind}
duration={expanded ? 600_000 : item.kind === 'error' ? 10_000 : item.action ? 8000 : 3000}
onOpenChange={(open) => {
if (!open) onRemove(item.id)
@@ -68,7 +72,7 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
{item.kind === 'ok' ? (
<CircleCheck size={16} aria-hidden="true" />
) : (
<CircleX size={16} aria-hidden="true" />
<HostIcon name="error"><CircleX size={16} aria-hidden="true" /></HostIcon>
)}
<div className="toast-text">
<div className="toast-title-row">
@@ -81,7 +85,7 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
</div>
{item.action && !item.rawDetail && (
<RToast.Action asChild altText={item.action.label}>
<button type="button" className="btn" onClick={item.action.onClick}>
<button type="button" className="btn rg-p-button" onClick={item.action.onClick}>
{item.action.label}
</button>
</RToast.Action>
@@ -110,7 +114,7 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
)}
{item.action && (
<RToast.Action asChild altText={item.action.label}>
<button type="button" className="btn toast-action-btn" onClick={item.action.onClick}>
<button type="button" className="btn rg-p-button toast-action-btn" onClick={item.action.onClick}>
{item.action.label}
</button>
</RToast.Action>
+39 -12
View File
@@ -17,7 +17,7 @@ import {
import type {
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime,
RuntimeKindSpec, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate,
RuntimeKindSpec, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMKeymapStatus, VMKeymapUpdate,
} from './types'
type AnyFn = (...args: never[]) => unknown
@@ -57,8 +57,9 @@ export function hideWailsGlobals(): void {
configurable: false,
enumerable: false,
})
} catch {
} catch (e) {
// non-configurable in some test environments
console.warn('[wails] hide window.go failed:', e)
}
try {
const minimalRuntime = typeof capturedRuntime.ResolveFilePaths === 'function'
@@ -71,8 +72,9 @@ export function hideWailsGlobals(): void {
configurable: false,
enumerable: false,
})
} catch {
} catch (e) {
// ignore if non-configurable
console.warn('[wails] hide window.runtime failed:', e)
}
}
@@ -112,14 +114,23 @@ export function WindowToggleMaximise(): void {
}
function eventsOn<T>(eventName: string, cb: (data: T) => void): () => void {
if (typeof capturedRuntime.EventsOnMultiple === 'function') {
return (capturedRuntime.EventsOnMultiple as (name: string, fn: (data: T) => void, max: number) => () => void)(
eventName,
cb,
-1,
)
const off = typeof capturedRuntime.EventsOnMultiple === 'function'
? (capturedRuntime.EventsOnMultiple as (name: string, fn: (data: T) => void, max: number) => () => void)(
eventName,
cb,
-1,
)
: RawEventsOn(eventName, cb)
// Unsubscribing notifies the backend over IPC, which throws when the bridge
// is down (e.g. a browser preview); a failed unsubscribe must not take the
// unmounting component down with it.
return () => {
try {
off()
} catch (e) {
console.warn('[wails] unsubscribe event failed:', eventName, e)
}
}
return RawEventsOn(eventName, cb)
}
function eventsEmit(eventName: string, ...args: unknown[]): void {
@@ -129,8 +140,9 @@ function eventsEmit(eventName: string, ...args: unknown[]): void {
return
}
;(RawEventsEmit as (name: string, ...data: unknown[]) => void)(eventName, ...args)
} catch {
// ignore if Wails runtime is unavailable (e.g. standalone preview)
} catch (e) {
// Wails runtime may be unavailable (e.g. standalone preview)
console.warn('[wails] emit event failed:', eventName, e)
}
}
@@ -140,6 +152,10 @@ export const api = {
GetTasks: boundGo.GetTasks as () => Promise<Task[]>,
GetVMAffinity: boundGo.GetVMAffinity as (name: string) => Promise<VMAffinityStatus>,
SetVMAffinity: boundGo.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
GetVMAffinityWithDriver: boundGo.GetVMAffinityWithDriver as (driverID: string, name: string) => Promise<VMAffinityStatus>,
SetVMAffinityWithDriver: boundGo.SetVMAffinityWithDriver as (driverID: string, name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
GetVMKeymap: boundGo.GetVMKeymap as (name: string) => Promise<VMKeymapStatus>,
SetVMKeymap: boundGo.SetVMKeymap as (name: string, req: VMKeymapUpdate) => Promise<VMKeymapStatus>,
ListInstallers: boundGo.ListInstallers as () => Promise<CachedInstaller[] | null>,
ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
@@ -147,6 +163,7 @@ export const api = {
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>,
PeekPluginMarket: boundGo.PeekPluginMarket as (query: string, kind: string) => Promise<MarketBrowseResult>,
InstallMarketPlugin: boundGo.InstallMarketPlugin as (id: string, includeAlpha: boolean) => Promise<PluginInfo>,
GetPluginUIContributions: boundGo.GetPluginUIContributions as () => Promise<PluginUIContributions>,
GetActiveTheme: boundGo.GetActiveTheme as () => Promise<ActiveThemePayload>,
@@ -154,13 +171,23 @@ export const api = {
ListRuntimeKinds: boundGo.ListRuntimeKinds as () => Promise<RuntimeKindSpec[] | null>,
}
export interface MarketInstallProgress {
id: string
phase: 'download' | 'install'
done: number
total: number
}
export const events = {
onTask: (cb: (task: Task) => void) => eventsOn('reims:task', cb),
onStateChanged: (cb: () => void) => eventsOn('reims:state-changed', cb),
onLog: (cb: (entry: LogEntry) => void) => eventsOn('reims:log', cb),
// Market install progress (internal/app/plugins_flow.go InstallMarketPlugin).
onPluginInstall: (cb: (p: MarketInstallProgress) => void) => eventsOn('reims:plugin-install', cb),
// Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…".
onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb),
onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb),
onTrayDiscardSuspend: (cb: (name: string) => void) => eventsOn('reims:tray-discard-suspend', cb),
// Renderer health watchdog & crash reporting (internal/app/ui_health.go).
onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb),
emitUIPong: () => eventsEmit('reims:ui-pong'),
+151 -42
View File
@@ -1,5 +1,139 @@
{
"uiApi": "1.0.0",
"uiApi": "2.0.0",
"parts": [
"rg-p-shell",
"rg-p-titlebar",
"rg-p-brand",
"rg-p-workspace",
"rg-p-sidebar",
"rg-p-sidebar-head",
"rg-p-nav",
"rg-p-main",
"rg-p-vm-page",
"rg-p-vm-header",
"rg-p-vm-preview",
"rg-p-vm-summary",
"rg-p-statusbar",
"rg-p-logpanel",
"rg-p-settings",
"rg-p-empty",
"rg-p-nav-group",
"rg-p-nav-item",
"rg-p-button",
"rg-p-icon-button",
"rg-p-card",
"rg-p-badge",
"rg-p-tabs",
"rg-p-tab",
"rg-p-menu",
"rg-p-menu-item",
"rg-p-dialog",
"rg-p-toast",
"rg-p-tooltip",
"rg-p-input",
"rg-p-switch",
"rg-p-progress",
"rg-p-vm-actions",
"rg-p-plugin-view"
],
"stateAttrs": [
"data-theme",
"data-motion",
"data-locale",
"data-view",
"data-vm-state",
"data-busy",
"data-has-error",
"data-sidebar-collapsed",
"data-safe-mode",
"data-layout-sidebar",
"data-layout-sidebar-mode",
"data-layout-density",
"data-layout-titlebar"
],
"itemStates": [
"rg-p-nav-item:data-vm-state",
"rg-p-nav-item:data-driver",
"rg-p-nav-item:data-selected",
"rg-p-nav-item:data-busy",
"rg-p-vm-page:data-vm-state",
"rg-p-vm-page:data-driver",
"rg-p-button:data-variant",
"rg-p-button:data-busy",
"rg-p-icon-button:data-busy",
"rg-p-dialog:data-tone",
"rg-p-toast:data-tone"
],
"slots": [
"titlebar.center",
"sidebar.header",
"sidebar.footer",
"nav.item.trailing",
"vm.header.trailing",
"vm.toolbar",
"vm.card",
"vm.preview.tl",
"vm.preview.tr",
"vm.preview.bl",
"vm.preview.br",
"statusbar.left",
"statusbar.right",
"empty.state",
"create.source",
"settings.plugin"
],
"layers": [
"layer.background",
"layer.overlay"
],
"layoutOptions": [
"sidebarPosition=left",
"sidebarPosition=right",
"sidebarMode=full",
"sidebarMode=rail",
"sidebarMode=floating",
"density=compact",
"density=regular",
"density=comfortable",
"titlebar=standard",
"titlebar=compact"
],
"icons": [
"start",
"stop",
"force-stop",
"restart",
"suspend",
"resume",
"new-vm",
"settings",
"plugin",
"folder",
"logs",
"screenshot",
"fullscreen",
"window",
"snapshot",
"clone",
"delete",
"info",
"warning",
"error",
"vm.state.running",
"vm.state.stopped",
"vm.state.suspended",
"vm.state.busy",
"vm.state.error"
],
"viewLocations": [],
"sdkEvents": [
"vm.stateChanged",
"task.started",
"task.progress",
"task.finished",
"toast.shown",
"view.changed"
],
"tokens": [
"--font-sans",
"--font-cjk",
@@ -89,45 +223,20 @@
"--sidebar-w",
"--page-max"
],
"parts": [
"rg-p-shell",
"rg-p-titlebar",
"rg-p-brand",
"rg-p-workspace",
"rg-p-sidebar",
"rg-p-sidebar-head",
"rg-p-nav",
"rg-p-main",
"rg-p-vm-page",
"rg-p-vm-header",
"rg-p-vm-preview",
"rg-p-vm-summary",
"rg-p-statusbar",
"rg-p-logpanel",
"rg-p-settings",
"rg-p-empty"
],
"stateAttrs": [
"data-theme",
"data-motion",
"data-locale",
"data-view",
"data-vm-state",
"data-busy",
"data-has-error",
"data-sidebar-collapsed",
"data-safe-mode"
],
"slots": [
"sidebar.footer",
"statusbar.right",
"vm.toolbar",
"vm.card",
"settings.plugin",
"vm.preview.tl",
"vm.preview.tr",
"vm.preview.bl",
"vm.preview.br",
"empty.state"
]
"experimental": {
"parts": [],
"stateAttrs": [],
"itemStates": [],
"slots": [],
"layers": [],
"layoutOptions": [],
"icons": [],
"viewLocations": [
"sidebar",
"vm.tab",
"settings",
"dialog"
],
"sdkEvents": []
}
}
+109 -3
View File
@@ -8,6 +8,12 @@ import {driver} from '../models';
import {runtime} from '../models';
import {installer} from '../models';
import {http} from '../models';
import {dataroot} from '../models';
import {opencore} from '../models';
export function AddVMSharedFolder(arg1:string,arg2:string):Promise<app.SharedFolderSettings>;
export function ApplyVMSMBIOS(arg1:string,arg2:opencore.SMBIOSIdentity):Promise<opencore.SMBIOSIdentity>;
export function ApplyVMSettings(arg1:reims.SetOpts):Promise<void>;
@@ -27,14 +33,30 @@ export function CheckDataRoot(arg1:string):Promise<app.DataRootCheck>;
export function CloneVMCoW(arg1:string,arg2:string):Promise<void>;
export function CompactVMDisk(arg1:string):Promise<reims.DiskCompactResult>;
export function CloneVMCoWWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function CompactVMDisk(arg1:string):Promise<driver.DiskCompactResult>;
export function CompactVMDiskWithDriver(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
export function OptimizeVMDisk(arg1:string):Promise<driver.DiskCompactResult>;
export function OptimizeVMDiskWithDriver(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
export function OpenWindowsSecurityExclusions():Promise<void>;
export function GetDefenderExclusionCommand():Promise<string>;
export function CompleteSetup(arg1:string):Promise<void>;
export function CopyVMScreenshot(arg1:string):Promise<void>;
export function CopyVMScreenshotWithDriver(arg1:string,arg2:string):Promise<void>;
export function CreateSnapshot(arg1:string,arg2:string):Promise<void>;
export function CreateSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
export function CreateVMWithDriver(arg1:driver.CreateRequest):Promise<void>;
@@ -45,8 +67,12 @@ export function DeleteInstaller(arg1:string):Promise<void>;
export function DeleteSnapshot(arg1:string,arg2:string):Promise<void>;
export function DeleteSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function DeleteVM(arg1:string,arg2:boolean):Promise<void>;
export function DeleteVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<void>;
export function DeliverFileToGuest(arg1:string):Promise<string>;
export function DeliverPathsToGuest(arg1:string,arg2:Array<string>):Promise<Array<string>>;
@@ -55,6 +81,10 @@ export function DetachGuestTools(arg1:string):Promise<void>;
export function DisablePlugin(arg1:string):Promise<void>;
export function DiscardSuspend(arg1:string):Promise<void>;
export function DiscardSuspendWithDriver(arg1:string,arg2:string):Promise<void>;
export function DismissTask(arg1:string):Promise<void>;
export function DoctorPlugin(arg1:string):Promise<Array<plugin.DoctorFinding>>;
@@ -67,6 +97,8 @@ export function DownloadInstaller(arg1:string):Promise<string>;
export function EjectInstaller(arg1:string):Promise<void>;
export function EjectInstallerWithDriver(arg1:string,arg2:string):Promise<void>;
export function EnablePlugin(arg1:string,arg2:boolean):Promise<void>;
export function EnableWHPX():Promise<void>;
@@ -75,10 +107,18 @@ export function EnterRecovery(arg1:string):Promise<void>;
export function ExportDiagnostics(arg1:string):Promise<string>;
export function ExportDiagnosticsWithDriver(arg1:string,arg2:string):Promise<string>;
export function FinishInstall(arg1:string):Promise<void>;
export function FocusVMWindow(arg1:string):Promise<void>;
export function FocusVMWindowWithDriver(arg1:string,arg2:string):Promise<void>;
export function ForceQuitApp():Promise<void>;
export function GenerateVMSMBIOS(arg1:string):Promise<opencore.SMBIOSIdentity>;
export function GetActiveTheme():Promise<plugin.ActiveThemePayload>;
export function GetLicenseTexts():Promise<app.LicenseTexts>;
@@ -95,22 +135,38 @@ export function GetTasks():Promise<Array<app.Task>>;
export function GetVMAffinity(arg1:string):Promise<app.VMAffinityStatus>;
export function GetVMAffinityWithDriver(arg1:string,arg2:string):Promise<app.VMAffinityStatus>;
export function GetVMKeymap(arg1:string):Promise<app.VMKeymapStatus>;
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
export function GetVMDriveShareSettings(arg1:string):Promise<app.DriveShareSettings>;
export function GetVMInfo(arg1:string,arg2:string):Promise<driver.VMInfo>;
export function GetVMMacOS(arg1:string):Promise<string>;
export function GetVMNote(arg1:string):Promise<string>;
export function GetVMPluginSettings(arg1:string):Promise<Record<string, Record<string, any>>>;
export function GetVMSMBIOS(arg1:string):Promise<opencore.SMBIOSIdentity>;
export function GetVMSSHUser(arg1:string):Promise<string>;
export function GetVMSSHUserWithDriver(arg1:string,arg2:string):Promise<string>;
export function GetVMSharedFolderSettings(arg1:string):Promise<app.SharedFolderSettings>;
export function GetVMStats(arg1:string):Promise<app.VMStats>;
export function GetVMStatsWithDriver(arg1:string,arg2:string):Promise<app.VMStats>;
export function GetVMThumbnail(arg1:string):Promise<app.VMThumbnail>;
export function GetVMThumbnailWithDriver(arg1:string,arg2:string):Promise<app.VMThumbnail>;
export function InspectPluginArchive(arg1:string):Promise<plugin.ScanReport>;
export function InstallAppUpdate():Promise<void>;
@@ -139,7 +195,9 @@ export function ListRemoteRuntimes():Promise<Array<runtime.Remote>>;
export function ListRuntimeKinds():Promise<Array<runtime.KindSpec>>;
export function ListSnapshots(arg1:string):Promise<Array<reims.DiskSnapshot>>;
export function ListSnapshots(arg1:string):Promise<Array<driver.DiskSnapshot>>;
export function ListSnapshotsWithDriver(arg1:string,arg2:string):Promise<Array<driver.DiskSnapshot>>;
export function OpenProcessorScheduling():Promise<void>;
@@ -147,6 +205,8 @@ export function OpenQQGroup():Promise<void>;
export function OpenSSHTerminal(arg1:string,arg2:string):Promise<void>;
export function OpenSSHTerminalWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function OpenSharedFolder(arg1:string):Promise<void>;
export function OpenURL(arg1:string):Promise<void>;
@@ -155,8 +215,12 @@ export function OpenVMFolder(arg1:string):Promise<void>;
export function OpenVSCodeSSH(arg1:string,arg2:string):Promise<void>;
export function OpenVSCodeSSHWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function PanelBridgeCall(arg1:string,arg2:string,arg3:Record<string, any>):Promise<any>;
export function PeekPluginMarket(arg1:string,arg2:string):Promise<plugin.MarketBrowseResult>;
export function PickDirectory(arg1:string):Promise<string>;
export function PickFile(arg1:string,arg2:string):Promise<string>;
@@ -171,18 +235,34 @@ export function ReadPluginLog(arg1:string):Promise<string>;
export function ReadVMLogs(arg1:string,arg2:boolean):Promise<string>;
export function ReadVMLogsWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<string>;
export function RemovePlugin(arg1:string,arg2:boolean):Promise<void>;
export function RemoveRuntime(arg1:string):Promise<void>;
export function RemoveVMSharedFolder(arg1:string,arg2:string):Promise<app.SharedFolderSettings>;
export function ReopenDataRoot(arg1:boolean):Promise<dataroot.Status>;
export function RequestClose():Promise<void>;
export function ResizeVMDisk(arg1:string,arg2:string):Promise<reims.DiskResizeResult>;
export function ResizeVMDisk(arg1:string,arg2:string):Promise<driver.DiskResizeResult>;
export function ResizeVMDiskWithDriver(arg1:string,arg2:string,arg3:string):Promise<driver.DiskResizeResult>;
export function RestartVM(arg1:string):Promise<void>;
export function RestartVMWithDriver(arg1:string,arg2:string):Promise<void>;
export function RestoreSnapshot(arg1:string,arg2:string):Promise<void>;
export function RestoreSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function ResumeVM(arg1:string):Promise<void>;
export function ResumeVMWithDriver(arg1:string,arg2:string):Promise<void>;
export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise<void>;
export function ScanInstalledPlugin(arg1:string):Promise<plugin.ScanReport>;
@@ -205,24 +285,48 @@ export function SetPluginSettings(arg1:string,arg2:string,arg3:Record<string, an
export function SetRuntimeChannel(arg1:string):Promise<void>;
export function SetSyncHostMemorySMBIOS(arg1:boolean):Promise<void>;
export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
export function SetVMAffinityWithDriver(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
export function SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise<app.VMKeymapStatus>;
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
export function SetVMNote(arg1:string,arg2:string):Promise<void>;
export function SetVMSSHUser(arg1:string,arg2:string):Promise<void>;
export function SetVMSSHUserWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function SetVMSharedFolderMode(arg1:string,arg2:string,arg3:string):Promise<app.SharedFolderSettings>;
export function ShowMainWindow():Promise<void>;
export function StartVM(arg1:string):Promise<void>;
export function StartVMWithDriver(arg1:string,arg2:string):Promise<void>;
export function StopVM(arg1:string,arg2:boolean):Promise<void>;
export function StopVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<void>;
export function SuggestDataRoots():Promise<Array<app.DataRootChoice>>;
export function SuggestLanguagePack():Promise<plugin.MarketCatalogItem>;
export function SuspendVM(arg1:string):Promise<void>;
export function SuspendVMWithDriver(arg1:string,arg2:string):Promise<void>;
export function ToggleBorderless(arg1:string,arg2:boolean):Promise<void>;
export function ToggleVMFullscreen(arg1:string):Promise<boolean>;
export function ToggleVMFullscreenWithDriver(arg1:string,arg2:string):Promise<boolean>;
export function TypeClipboard(arg1:string):Promise<number>;
export function TypeText(arg1:string,arg2:string):Promise<number>;
@@ -236,3 +340,5 @@ export function ValidateCreate(arg1:reims.CreateOpts):Promise<Array<reims.Valida
export function ValidateSet(arg1:reims.SetOpts):Promise<Array<reims.ValidationIssue>>;
export function WriteSSHConfig(arg1:string,arg2:string):Promise<string>;
export function WriteSSHConfigWithDriver(arg1:string,arg2:string,arg3:string):Promise<string>;
+208
View File
@@ -2,6 +2,14 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
export function AddVMSharedFolder(arg1, arg2) {
return window['go']['app']['App']['AddVMSharedFolder'](arg1, arg2);
}
export function ApplyVMSMBIOS(arg1, arg2) {
return window['go']['app']['App']['ApplyVMSMBIOS'](arg1, arg2);
}
export function ApplyVMSettings(arg1) {
return window['go']['app']['App']['ApplyVMSettings'](arg1);
}
@@ -38,10 +46,34 @@ export function CloneVMCoW(arg1, arg2) {
return window['go']['app']['App']['CloneVMCoW'](arg1, arg2);
}
export function CloneVMCoWWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['CloneVMCoWWithDriver'](arg1, arg2, arg3);
}
export function CompactVMDisk(arg1) {
return window['go']['app']['App']['CompactVMDisk'](arg1);
}
export function CompactVMDiskWithDriver(arg1, arg2) {
return window['go']['app']['App']['CompactVMDiskWithDriver'](arg1, arg2);
}
export function OptimizeVMDisk(arg1) {
return window['go']['app']['App']['OptimizeVMDisk'](arg1);
}
export function OptimizeVMDiskWithDriver(arg1, arg2) {
return window['go']['app']['App']['OptimizeVMDiskWithDriver'](arg1, arg2);
}
export function OpenWindowsSecurityExclusions() {
return window['go']['app']['App']['OpenWindowsSecurityExclusions']();
}
export function GetDefenderExclusionCommand() {
return window['go']['app']['App']['GetDefenderExclusionCommand']();
}
export function CompleteSetup(arg1) {
return window['go']['app']['App']['CompleteSetup'](arg1);
}
@@ -50,10 +82,18 @@ export function CopyVMScreenshot(arg1) {
return window['go']['app']['App']['CopyVMScreenshot'](arg1);
}
export function CopyVMScreenshotWithDriver(arg1, arg2) {
return window['go']['app']['App']['CopyVMScreenshotWithDriver'](arg1, arg2);
}
export function CreateSnapshot(arg1, arg2) {
return window['go']['app']['App']['CreateSnapshot'](arg1, arg2);
}
export function CreateSnapshotWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['CreateSnapshotWithDriver'](arg1, arg2, arg3);
}
export function CreateVM(arg1) {
return window['go']['app']['App']['CreateVM'](arg1);
}
@@ -74,10 +114,18 @@ export function DeleteSnapshot(arg1, arg2) {
return window['go']['app']['App']['DeleteSnapshot'](arg1, arg2);
}
export function DeleteSnapshotWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['DeleteSnapshotWithDriver'](arg1, arg2, arg3);
}
export function DeleteVM(arg1, arg2) {
return window['go']['app']['App']['DeleteVM'](arg1, arg2);
}
export function DeleteVMWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['DeleteVMWithDriver'](arg1, arg2, arg3);
}
export function DeliverFileToGuest(arg1) {
return window['go']['app']['App']['DeliverFileToGuest'](arg1);
}
@@ -94,6 +142,14 @@ export function DisablePlugin(arg1) {
return window['go']['app']['App']['DisablePlugin'](arg1);
}
export function DiscardSuspend(arg1) {
return window['go']['app']['App']['DiscardSuspend'](arg1);
}
export function DiscardSuspendWithDriver(arg1, arg2) {
return window['go']['app']['App']['DiscardSuspendWithDriver'](arg1, arg2);
}
export function DismissTask(arg1) {
return window['go']['app']['App']['DismissTask'](arg1);
}
@@ -118,6 +174,10 @@ export function EjectInstaller(arg1) {
return window['go']['app']['App']['EjectInstaller'](arg1);
}
export function EjectInstallerWithDriver(arg1, arg2) {
return window['go']['app']['App']['EjectInstallerWithDriver'](arg1, arg2);
}
export function EnablePlugin(arg1, arg2) {
return window['go']['app']['App']['EnablePlugin'](arg1, arg2);
}
@@ -134,6 +194,10 @@ export function ExportDiagnostics(arg1) {
return window['go']['app']['App']['ExportDiagnostics'](arg1);
}
export function ExportDiagnosticsWithDriver(arg1, arg2) {
return window['go']['app']['App']['ExportDiagnosticsWithDriver'](arg1, arg2);
}
export function FinishInstall(arg1) {
return window['go']['app']['App']['FinishInstall'](arg1);
}
@@ -142,6 +206,18 @@ export function FocusVMWindow(arg1) {
return window['go']['app']['App']['FocusVMWindow'](arg1);
}
export function FocusVMWindowWithDriver(arg1, arg2) {
return window['go']['app']['App']['FocusVMWindowWithDriver'](arg1, arg2);
}
export function ForceQuitApp() {
return window['go']['app']['App']['ForceQuitApp']();
}
export function GenerateVMSMBIOS(arg1) {
return window['go']['app']['App']['GenerateVMSMBIOS'](arg1);
}
export function GetActiveTheme() {
return window['go']['app']['App']['GetActiveTheme']();
}
@@ -174,6 +250,14 @@ export function GetVMAffinity(arg1) {
return window['go']['app']['App']['GetVMAffinity'](arg1);
}
export function GetVMAffinityWithDriver(arg1, arg2) {
return window['go']['app']['App']['GetVMAffinityWithDriver'](arg1, arg2);
}
export function GetVMKeymap(arg1) {
return window['go']['app']['App']['GetVMKeymap'](arg1);
}
export function GetVMDetail(arg1) {
return window['go']['app']['App']['GetVMDetail'](arg1);
}
@@ -182,6 +266,10 @@ export function GetVMDriveShareSettings(arg1) {
return window['go']['app']['App']['GetVMDriveShareSettings'](arg1);
}
export function GetVMInfo(arg1, arg2) {
return window['go']['app']['App']['GetVMInfo'](arg1, arg2);
}
export function GetVMMacOS(arg1) {
return window['go']['app']['App']['GetVMMacOS'](arg1);
}
@@ -194,18 +282,38 @@ export function GetVMPluginSettings(arg1) {
return window['go']['app']['App']['GetVMPluginSettings'](arg1);
}
export function GetVMSMBIOS(arg1) {
return window['go']['app']['App']['GetVMSMBIOS'](arg1);
}
export function GetVMSSHUser(arg1) {
return window['go']['app']['App']['GetVMSSHUser'](arg1);
}
export function GetVMSSHUserWithDriver(arg1, arg2) {
return window['go']['app']['App']['GetVMSSHUserWithDriver'](arg1, arg2);
}
export function GetVMSharedFolderSettings(arg1) {
return window['go']['app']['App']['GetVMSharedFolderSettings'](arg1);
}
export function GetVMStats(arg1) {
return window['go']['app']['App']['GetVMStats'](arg1);
}
export function GetVMStatsWithDriver(arg1, arg2) {
return window['go']['app']['App']['GetVMStatsWithDriver'](arg1, arg2);
}
export function GetVMThumbnail(arg1) {
return window['go']['app']['App']['GetVMThumbnail'](arg1);
}
export function GetVMThumbnailWithDriver(arg1, arg2) {
return window['go']['app']['App']['GetVMThumbnailWithDriver'](arg1, arg2);
}
export function InspectPluginArchive(arg1) {
return window['go']['app']['App']['InspectPluginArchive'](arg1);
}
@@ -266,6 +374,10 @@ export function ListSnapshots(arg1) {
return window['go']['app']['App']['ListSnapshots'](arg1);
}
export function ListSnapshotsWithDriver(arg1, arg2) {
return window['go']['app']['App']['ListSnapshotsWithDriver'](arg1, arg2);
}
export function OpenProcessorScheduling() {
return window['go']['app']['App']['OpenProcessorScheduling']();
}
@@ -278,6 +390,10 @@ export function OpenSSHTerminal(arg1, arg2) {
return window['go']['app']['App']['OpenSSHTerminal'](arg1, arg2);
}
export function OpenSSHTerminalWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['OpenSSHTerminalWithDriver'](arg1, arg2, arg3);
}
export function OpenSharedFolder(arg1) {
return window['go']['app']['App']['OpenSharedFolder'](arg1);
}
@@ -294,10 +410,18 @@ export function OpenVSCodeSSH(arg1, arg2) {
return window['go']['app']['App']['OpenVSCodeSSH'](arg1, arg2);
}
export function OpenVSCodeSSHWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['OpenVSCodeSSHWithDriver'](arg1, arg2, arg3);
}
export function PanelBridgeCall(arg1, arg2, arg3) {
return window['go']['app']['App']['PanelBridgeCall'](arg1, arg2, arg3);
}
export function PeekPluginMarket(arg1, arg2) {
return window['go']['app']['App']['PeekPluginMarket'](arg1, arg2);
}
export function PickDirectory(arg1) {
return window['go']['app']['App']['PickDirectory'](arg1);
}
@@ -326,6 +450,10 @@ export function ReadVMLogs(arg1, arg2) {
return window['go']['app']['App']['ReadVMLogs'](arg1, arg2);
}
export function ReadVMLogsWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['ReadVMLogsWithDriver'](arg1, arg2, arg3);
}
export function RemovePlugin(arg1, arg2) {
return window['go']['app']['App']['RemovePlugin'](arg1, arg2);
}
@@ -334,6 +462,14 @@ export function RemoveRuntime(arg1) {
return window['go']['app']['App']['RemoveRuntime'](arg1);
}
export function RemoveVMSharedFolder(arg1, arg2) {
return window['go']['app']['App']['RemoveVMSharedFolder'](arg1, arg2);
}
export function ReopenDataRoot(arg1) {
return window['go']['app']['App']['ReopenDataRoot'](arg1);
}
export function RequestClose() {
return window['go']['app']['App']['RequestClose']();
}
@@ -342,14 +478,34 @@ export function ResizeVMDisk(arg1, arg2) {
return window['go']['app']['App']['ResizeVMDisk'](arg1, arg2);
}
export function ResizeVMDiskWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['ResizeVMDiskWithDriver'](arg1, arg2, arg3);
}
export function RestartVM(arg1) {
return window['go']['app']['App']['RestartVM'](arg1);
}
export function RestartVMWithDriver(arg1, arg2) {
return window['go']['app']['App']['RestartVMWithDriver'](arg1, arg2);
}
export function RestoreSnapshot(arg1, arg2) {
return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2);
}
export function RestoreSnapshotWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['RestoreSnapshotWithDriver'](arg1, arg2, arg3);
}
export function ResumeVM(arg1) {
return window['go']['app']['App']['ResumeVM'](arg1);
}
export function ResumeVMWithDriver(arg1, arg2) {
return window['go']['app']['App']['ResumeVMWithDriver'](arg1, arg2);
}
export function SaveCustomThemeScheme(arg1) {
return window['go']['app']['App']['SaveCustomThemeScheme'](arg1);
}
@@ -394,10 +550,22 @@ export function SetRuntimeChannel(arg1) {
return window['go']['app']['App']['SetRuntimeChannel'](arg1);
}
export function SetSyncHostMemorySMBIOS(arg1) {
return window['go']['app']['App']['SetSyncHostMemorySMBIOS'](arg1);
}
export function SetVMAffinity(arg1, arg2) {
return window['go']['app']['App']['SetVMAffinity'](arg1, arg2);
}
export function SetVMAffinityWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMAffinityWithDriver'](arg1, arg2, arg3);
}
export function SetVMKeymap(arg1, arg2) {
return window['go']['app']['App']['SetVMKeymap'](arg1, arg2);
}
export function SetVMDriveShareSettings(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
}
@@ -410,6 +578,14 @@ export function SetVMSSHUser(arg1, arg2) {
return window['go']['app']['App']['SetVMSSHUser'](arg1, arg2);
}
export function SetVMSSHUserWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMSSHUserWithDriver'](arg1, arg2, arg3);
}
export function SetVMSharedFolderMode(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMSharedFolderMode'](arg1, arg2, arg3);
}
export function ShowMainWindow() {
return window['go']['app']['App']['ShowMainWindow']();
}
@@ -418,18 +594,46 @@ export function StartVM(arg1) {
return window['go']['app']['App']['StartVM'](arg1);
}
export function StartVMWithDriver(arg1, arg2) {
return window['go']['app']['App']['StartVMWithDriver'](arg1, arg2);
}
export function StopVM(arg1, arg2) {
return window['go']['app']['App']['StopVM'](arg1, arg2);
}
export function StopVMWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['StopVMWithDriver'](arg1, arg2, arg3);
}
export function SuggestDataRoots() {
return window['go']['app']['App']['SuggestDataRoots']();
}
export function SuggestLanguagePack() {
return window['go']['app']['App']['SuggestLanguagePack']();
}
export function SuspendVM(arg1) {
return window['go']['app']['App']['SuspendVM'](arg1);
}
export function SuspendVMWithDriver(arg1, arg2) {
return window['go']['app']['App']['SuspendVMWithDriver'](arg1, arg2);
}
export function ToggleBorderless(arg1, arg2) {
return window['go']['app']['App']['ToggleBorderless'](arg1, arg2);
}
export function ToggleVMFullscreen(arg1) {
return window['go']['app']['App']['ToggleVMFullscreen'](arg1);
}
export function ToggleVMFullscreenWithDriver(arg1, arg2) {
return window['go']['app']['App']['ToggleVMFullscreenWithDriver'](arg1, arg2);
}
export function TypeClipboard(arg1) {
return window['go']['app']['App']['TypeClipboard'](arg1);
}
@@ -457,3 +661,7 @@ export function ValidateSet(arg1) {
export function WriteSSHConfig(arg1, arg2) {
return window['go']['app']['App']['WriteSSHConfig'](arg1, arg2);
}
export function WriteSSHConfigWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['WriteSSHConfigWithDriver'](arg1, arg2, arg3);
}
+488 -76
View File
@@ -1,17 +1,68 @@
export namespace app {
export class VMKeymapUpdate {
preset: string;
bindings: Record<string, string>;
static createFrom(source: object | string = {}) {
return new VMKeymapUpdate(source);
}
constructor(source: Partial<VMKeymapUpdate> | string = {}) {
if (typeof source === "string") source = JSON.parse(source) as Partial<VMKeymapUpdate>;
this.preset = source.preset ?? "off";
this.bindings = source.bindings ?? {};
}
}
export class VMKeymapStatus {
preset: string;
bindings: Record<string, string>;
needs_guest_tools: boolean;
guest_connected: boolean;
guest_agent_version?: number;
required_agent_version: number;
input_service_available: boolean;
guest_keymap_active: boolean;
hook_active: boolean;
running: boolean;
static createFrom(source: object | string = {}) {
return new VMKeymapStatus(source);
}
constructor(source: Partial<VMKeymapStatus> | string = {}) {
if (typeof source === "string") source = JSON.parse(source) as Partial<VMKeymapStatus>;
this.preset = source.preset ?? "off";
this.bindings = source.bindings ?? {};
this.needs_guest_tools = source.needs_guest_tools ?? false;
this.guest_connected = source.guest_connected ?? false;
this.guest_agent_version = source.guest_agent_version;
this.required_agent_version = source.required_agent_version ?? 0;
this.input_service_available = source.input_service_available ?? false;
this.guest_keymap_active = source.guest_keymap_active ?? false;
this.hook_active = source.hook_active ?? false;
this.running = source.running ?? false;
}
}
export class AppState {
quit_mode?: string;
config?: config.Config;
host: host.Report;
optimizations: host.Optimization[];
runtimes: runtime.Installed[];
active_runtime?: runtime.Installed;
vms: reims.VMListItem[];
can_suspend: boolean;
vms: driver.VMListItem[];
transitions: Record<string, string>;
pending_changes: Record<string, Array<PendingChange>>;
active_guides?: string[];
install_guide_enabled?: boolean;
needs_setup: boolean;
data_root_status: dataroot.Status;
data_root_message?: string;
app_version: string;
safe_mode?: boolean;
plugin_crash_detected?: boolean;
@@ -25,17 +76,21 @@ export namespace app {
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.quit_mode = source["quit_mode"];
this.config = this.convertValues(source["config"], config.Config);
this.host = this.convertValues(source["host"], host.Report);
this.optimizations = this.convertValues(source["optimizations"], host.Optimization);
this.runtimes = this.convertValues(source["runtimes"], runtime.Installed);
this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed);
this.vms = this.convertValues(source["vms"], reims.VMListItem);
this.can_suspend = source["can_suspend"];
this.vms = this.convertValues(source["vms"], driver.VMListItem);
this.transitions = source["transitions"];
this.pending_changes = this.convertValues(source["pending_changes"], Array<PendingChange>, true);
this.active_guides = source["active_guides"];
this.install_guide_enabled = source["install_guide_enabled"];
this.needs_setup = source["needs_setup"];
this.data_root_status = this.convertValues(source["data_root_status"], dataroot.Status);
this.data_root_message = source["data_root_message"];
this.app_version = source["app_version"];
this.safe_mode = source["safe_mode"];
this.plugin_crash_detected = source["plugin_crash_detected"];
@@ -196,6 +251,7 @@ export namespace app {
settings_pages?: plugin.SettingsPageContribution[];
status_items?: plugin.StatusItemContribution[];
panels?: plugin.PanelContribution[];
image_sources?: plugin.ImageSourceContribution[];
vm_templates?: plugin.VMTemplateContribution[];
themes?: plugin.ThemeContribution[];
locales?: plugin.ResolvedLocalePack[];
@@ -217,6 +273,7 @@ export namespace app {
this.settings_pages = this.convertValues(source["settings_pages"], plugin.SettingsPageContribution);
this.status_items = this.convertValues(source["status_items"], plugin.StatusItemContribution);
this.panels = this.convertValues(source["panels"], plugin.PanelContribution);
this.image_sources = this.convertValues(source["image_sources"], plugin.ImageSourceContribution);
this.vm_templates = this.convertValues(source["vm_templates"], plugin.VMTemplateContribution);
this.themes = this.convertValues(source["themes"], plugin.ThemeContribution);
this.locales = this.convertValues(source["locales"], plugin.ResolvedLocalePack);
@@ -244,6 +301,62 @@ export namespace app {
return a;
}
}
export class SharedFolderInfo {
id: string;
name: string;
host_path: string;
writable: boolean;
enabled: boolean;
available: boolean;
issue?: string;
static createFrom(source: any = {}) {
return new SharedFolderInfo(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.name = source["name"];
this.host_path = source["host_path"];
this.writable = source["writable"];
this.enabled = source["enabled"];
this.available = source["available"];
this.issue = source["issue"];
}
}
export class SharedFolderSettings {
required_agent_version: number;
folders: SharedFolderInfo[];
static createFrom(source: any = {}) {
return new SharedFolderSettings(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.required_agent_version = source["required_agent_version"];
this.folders = this.convertValues(source["folders"], SharedFolderInfo);
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice && a.map) {
return (a as any[]).map(elem => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
export class VMStorageItem {
name: string;
bytes: number;
@@ -397,6 +510,7 @@ export namespace app {
export class VMStats {
name: string;
running: boolean;
window_fullscreen?: boolean;
pid?: number;
cpu_percent: number;
memory_rss_bytes: number;
@@ -405,11 +519,14 @@ export namespace app {
disk_virtual_bytes: number;
disk_format?: string;
disk_backing_depth?: number;
disk_extended_l2?: boolean;
disk_snapshot_count?: number;
disk_backing_broken?: boolean;
disk_backing_depth_warn?: boolean;
uptime_seconds: number;
guest_tools_connected: boolean;
guest_tools_mount_mode?: string;
guest_tools_agent_version?: number;
guest_tools_sleep_guard: boolean;
static createFrom(source: any = {}) {
@@ -420,6 +537,7 @@ export namespace app {
if ('string' === typeof source) source = JSON.parse(source);
this.name = source["name"];
this.running = source["running"];
this.window_fullscreen = source["window_fullscreen"];
this.pid = source["pid"];
this.cpu_percent = source["cpu_percent"];
this.memory_rss_bytes = source["memory_rss_bytes"];
@@ -428,11 +546,14 @@ export namespace app {
this.disk_virtual_bytes = source["disk_virtual_bytes"];
this.disk_format = source["disk_format"];
this.disk_backing_depth = source["disk_backing_depth"];
this.disk_extended_l2 = source["disk_extended_l2"];
this.disk_snapshot_count = source["disk_snapshot_count"];
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"];
this.guest_tools_agent_version = source["guest_tools_agent_version"];
this.guest_tools_sleep_guard = source["guest_tools_sleep_guard"];
}
}
@@ -467,6 +588,7 @@ export namespace config {
runtime_channel?: string;
app_update_channel?: string;
minimize_to_tray?: boolean;
sync_host_memory_smbios?: boolean;
static createFrom(source: any = {}) {
return new Config(source);
@@ -482,6 +604,36 @@ export namespace config {
this.runtime_channel = source["runtime_channel"];
this.app_update_channel = source["app_update_channel"];
this.minimize_to_tray = source["minimize_to_tray"];
this.sync_host_memory_smbios = source["sync_host_memory_smbios"];
}
}
}
export namespace dataroot {
export class Status {
dir: string;
read_only: boolean;
reason?: string;
detail?: string;
version: number;
known: number;
migrated?: string[];
static createFrom(source: any = {}) {
return new Status(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.dir = source["dir"];
this.read_only = source["read_only"];
this.reason = source["reason"];
this.detail = source["detail"];
this.version = source["version"];
this.known = source["known"];
this.migrated = source["migrated"];
}
}
@@ -507,6 +659,62 @@ export namespace driver {
this.options = source["options"];
}
}
export class DiskCompactResult {
extended_l2_enabled?: boolean;
path: string;
before_bytes: number;
after_bytes: number;
reclaimed_bytes: number;
static createFrom(source: any = {}) {
return new DiskCompactResult(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.extended_l2_enabled = source["extended_l2_enabled"];
this.path = source["path"];
this.before_bytes = source["before_bytes"];
this.after_bytes = source["after_bytes"];
this.reclaimed_bytes = source["reclaimed_bytes"];
}
}
export class DiskResizeResult {
path: string;
old_virtual_bytes: number;
new_virtual_bytes: number;
guest_expand_cmd: string;
static createFrom(source: any = {}) {
return new DiskResizeResult(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.path = source["path"];
this.old_virtual_bytes = source["old_virtual_bytes"];
this.new_virtual_bytes = source["new_virtual_bytes"];
this.guest_expand_cmd = source["guest_expand_cmd"];
}
}
export class DiskSnapshot {
id: string;
name: string;
created_at: number;
vm_state_bytes: number;
static createFrom(source: any = {}) {
return new DiskSnapshot(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.name = source["name"];
this.created_at = source["created_at"];
this.vm_state_bytes = source["vm_state_bytes"];
}
}
export class DriverSummary {
id: string;
name: plugin.LocalizedText;
@@ -551,6 +759,66 @@ export namespace driver {
return a;
}
}
export class VMInfo {
name: string;
driver_id: string;
driver_name?: string;
state: string;
pid?: number;
cpus?: number;
memory?: string;
disk_summary?: string;
disk_path?: string;
directory?: string;
network?: boolean;
ssh_port?: number;
capabilities?: string[];
driver_data?: Record<string, any>;
driver_unavailable?: boolean;
static createFrom(source: any = {}) {
return new VMInfo(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.name = source["name"];
this.driver_id = source["driver_id"];
this.driver_name = source["driver_name"];
this.state = source["state"];
this.pid = source["pid"];
this.cpus = source["cpus"];
this.memory = source["memory"];
this.disk_summary = source["disk_summary"];
this.disk_path = source["disk_path"];
this.directory = source["directory"];
this.network = source["network"];
this.ssh_port = source["ssh_port"];
this.capabilities = source["capabilities"];
this.driver_data = source["driver_data"];
this.driver_unavailable = source["driver_unavailable"];
}
}
export class VMListItem {
name: string;
driver_id?: string;
dir: string;
pid?: number;
state: string;
static createFrom(source: any = {}) {
return new VMListItem(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.name = source["name"];
this.driver_id = source["driver_id"];
this.dir = source["dir"];
this.pid = source["pid"];
this.state = source["state"];
}
}
}
@@ -668,6 +936,22 @@ export namespace host {
this.compat_detail = source["compat_detail"];
}
}
export class HostMemorySpec {
speed_mhz?: number;
memory_type?: number;
type_name?: string;
static createFrom(source: any = {}) {
return new HostMemorySpec(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.speed_mhz = source["speed_mhz"];
this.memory_type = source["memory_type"];
this.type_name = source["type_name"];
}
}
export class LogicalCPUInfo {
index: number;
core_index: number;
@@ -746,16 +1030,19 @@ export namespace host {
total_ram_gb: number;
avail_ram_gb: number;
memory_load_pct: number;
memory_spec?: HostMemorySpec;
commit_avail_gb: number;
commit_limit_gb: number;
data_root: string;
data_root_drive_type?: string;
defender_realtime_active?: boolean;
deep_backing_chains?: BackingChainIssue[];
free_disk_gb: number;
whpx: string;
whpx_caps: WHPXCapabilities;
needs_cold_reboot_workaround: boolean;
gpus: GPUInfo[];
vulkan_probe_error?: string;
recommended_gpu?: GPUInfo;
displays?: DisplayInfo[];
primary_display?: DisplayInfo;
@@ -791,16 +1078,19 @@ export namespace host {
this.total_ram_gb = source["total_ram_gb"];
this.avail_ram_gb = source["avail_ram_gb"];
this.memory_load_pct = source["memory_load_pct"];
this.memory_spec = this.convertValues(source["memory_spec"], HostMemorySpec);
this.commit_avail_gb = source["commit_avail_gb"];
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.defender_realtime_active = source["defender_realtime_active"];
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);
this.needs_cold_reboot_workaround = source["needs_cold_reboot_workaround"];
this.gpus = this.convertValues(source["gpus"], GPUInfo);
this.vulkan_probe_error = source["vulkan_probe_error"];
this.recommended_gpu = this.convertValues(source["recommended_gpu"], GPUInfo);
this.displays = this.convertValues(source["displays"], DisplayInfo);
this.primary_display = this.convertValues(source["primary_display"], DisplayInfo);
@@ -868,6 +1158,9 @@ export namespace installer {
build: string;
posted: string;
size: number;
url?: string;
integrity_url?: string;
digest?: string;
static createFrom(source: any = {}) {
return new Release(source);
@@ -881,6 +1174,34 @@ export namespace installer {
this.build = source["build"];
this.posted = source["posted"];
this.size = source["size"];
this.url = source["url"];
this.integrity_url = source["integrity_url"];
this.digest = source["digest"];
}
}
}
export namespace opencore {
export class SMBIOSIdentity {
model: string;
serial: string;
mlb: string;
uuid: string;
rom?: string;
static createFrom(source: any = {}) {
return new SMBIOSIdentity(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.model = source["model"];
this.serial = source["serial"];
this.mlb = source["mlb"];
this.uuid = source["uuid"];
this.rom = source["rom"];
}
}
@@ -966,6 +1287,24 @@ export namespace plugin {
return a;
}
}
export class ThemeLayout {
sidebarPosition?: string;
sidebarMode?: string;
density?: string;
titlebar?: string;
static createFrom(source: any = {}) {
return new ThemeLayout(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.sidebarPosition = source["sidebarPosition"];
this.sidebarMode = source["sidebarMode"];
this.density = source["density"];
this.titlebar = source["titlebar"];
}
}
export class ThemeFont {
family: string;
file: string;
@@ -1078,8 +1417,9 @@ export namespace plugin {
stylesheet?: string;
decorations?: ThemeDecoration[];
uiScript?: string;
layout?: ThemeLayout;
pluginId?: string;
static createFrom(source: any = {}) {
return new ThemeContribution(source);
}
@@ -1103,6 +1443,7 @@ export namespace plugin {
this.stylesheet = source["stylesheet"];
this.decorations = this.convertValues(source["decorations"], ThemeDecoration);
this.uiScript = source["uiScript"];
this.layout = this.convertValues(source["layout"], ThemeLayout);
this.pluginId = source["pluginId"];
}
@@ -1231,16 +1572,18 @@ export namespace plugin {
"reims-go"?: string;
pluginApi?: string;
uiApi?: string;
bridgeApi?: 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"];
this.bridgeApi = source["bridgeApi"];
}
}
export class ExecutableFile {
@@ -1262,6 +1605,20 @@ export namespace plugin {
}
}
export class MarketKindFacet {
kind: string;
count: number;
static createFrom(source: any = {}) {
return new MarketKindFacet(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.kind = source["kind"];
this.count = source["count"];
}
}
export class MarketWithdrawal {
id: string;
reason: LocalizedText;
@@ -1322,6 +1679,7 @@ export namespace plugin {
signer?: string;
changelog?: LocalizedText;
tags?: string[];
locales?: string[];
updated_at?: string;
static createFrom(source: any = {}) {
@@ -1351,6 +1709,7 @@ export namespace plugin {
this.signer = source["signer"];
this.changelog = this.convertValues(source["changelog"], LocalizedText);
this.tags = source["tags"];
this.locales = source["locales"];
this.updated_at = source["updated_at"];
}
@@ -1381,6 +1740,7 @@ export namespace plugin {
incompatible_reason?: string;
withdrawn?: MarketWithdrawal;
high_risk_permissions?: string[];
risks?: string[];
static createFrom(source: any = {}) {
return new MarketCatalogItem(source);
@@ -1396,6 +1756,7 @@ export namespace plugin {
this.incompatible_reason = source["incompatible_reason"];
this.withdrawn = this.convertValues(source["withdrawn"], MarketWithdrawal);
this.high_risk_permissions = source["high_risk_permissions"];
this.risks = source["risks"];
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
@@ -1422,6 +1783,7 @@ export namespace plugin {
fetch_error?: string;
updated_at?: string;
items: MarketCatalogItem[];
kinds: MarketKindFacet[];
withdrawn_installed?: MarketWithdrawal[];
static createFrom(source: any = {}) {
@@ -1435,6 +1797,7 @@ export namespace plugin {
this.fetch_error = source["fetch_error"];
this.updated_at = source["updated_at"];
this.items = this.convertValues(source["items"], MarketCatalogItem);
this.kinds = this.convertValues(source["kinds"], MarketKindFacet);
this.withdrawn_installed = this.convertValues(source["withdrawn_installed"], MarketWithdrawal);
}
@@ -1459,6 +1822,7 @@ export namespace plugin {
export class MenuContribution {
id: string;
slot: string;
@@ -1539,6 +1903,50 @@ export namespace plugin {
return a;
}
}
export class ImageSourceContribution {
id: string;
title: LocalizedText;
description?: LocalizedText;
order?: number;
entry?: string;
height?: number;
native?: string;
pluginId?: string;
static createFrom(source: any = {}) {
return new ImageSourceContribution(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.title = this.convertValues(source["title"], LocalizedText);
this.description = this.convertValues(source["description"], LocalizedText);
this.order = source["order"];
this.entry = source["entry"];
this.height = source["height"];
this.native = source["native"];
this.pluginId = source["pluginId"];
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice && a.map) {
return (a as any[]).map(elem => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
export class PermissionSpec {
name: string;
level: string;
@@ -1666,6 +2074,8 @@ export namespace plugin {
permissions?: PermissionSpec[];
approved_permissions?: string[];
needs_approval: boolean;
risks?: string[];
locales?: string[];
requires?: string[];
provides?: string[];
settings?: SettingsSchema;
@@ -1702,6 +2112,8 @@ export namespace plugin {
this.permissions = this.convertValues(source["permissions"], PermissionSpec);
this.approved_permissions = source["approved_permissions"];
this.needs_approval = source["needs_approval"];
this.risks = source["risks"];
this.locales = source["locales"];
this.requires = source["requires"];
this.provides = source["provides"];
this.settings = this.convertValues(source["settings"], SettingsSchema);
@@ -2165,60 +2577,6 @@ export namespace reims {
this.start = source["start"];
}
}
export class DiskCompactResult {
path: string;
before_bytes: number;
after_bytes: number;
reclaimed_bytes: number;
static createFrom(source: any = {}) {
return new DiskCompactResult(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.path = source["path"];
this.before_bytes = source["before_bytes"];
this.after_bytes = source["after_bytes"];
this.reclaimed_bytes = source["reclaimed_bytes"];
}
}
export class DiskResizeResult {
path: string;
old_virtual_bytes: number;
new_virtual_bytes: number;
guest_expand_cmd: string;
static createFrom(source: any = {}) {
return new DiskResizeResult(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.path = source["path"];
this.old_virtual_bytes = source["old_virtual_bytes"];
this.new_virtual_bytes = source["new_virtual_bytes"];
this.guest_expand_cmd = source["guest_expand_cmd"];
}
}
export class DiskSnapshot {
id: string;
name: string;
created_at: number;
vm_state_bytes: number;
static createFrom(source: any = {}) {
return new DiskSnapshot(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.name = source["name"];
this.created_at = source["created_at"];
this.vm_state_bytes = source["vm_state_bytes"];
}
}
export class SetOpts {
name: string;
cpus?: number;
@@ -2269,6 +2627,52 @@ export namespace reims {
this.guest_lang = source["guest_lang"];
}
}
export class SuspendInfo {
schema_version: number;
vm_name: string;
cpus: number;
memory: string;
graphics: string;
displays: number;
resolution: string;
disk_controller: string;
cpu_model?: string;
audio: boolean;
audio_backend?: string;
network: boolean;
ssh_port: number;
extra_args?: string;
runtime_commit: string;
vendor_qemu_commit?: string;
created_at: string;
vmstate_size: number;
static createFrom(source: any = {}) {
return new SuspendInfo(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.schema_version = source["schema_version"];
this.vm_name = source["vm_name"];
this.cpus = source["cpus"];
this.memory = source["memory"];
this.graphics = source["graphics"];
this.displays = source["displays"];
this.resolution = source["resolution"];
this.disk_controller = source["disk_controller"];
this.cpu_model = source["cpu_model"];
this.audio = source["audio"];
this.audio_backend = source["audio_backend"];
this.network = source["network"];
this.ssh_port = source["ssh_port"];
this.extra_args = source["extra_args"];
this.runtime_commit = source["runtime_commit"];
this.vendor_qemu_commit = source["vendor_qemu_commit"];
this.created_at = source["created_at"];
this.vmstate_size = source["vmstate_size"];
}
}
export class VMDetail {
name: string;
state: string;
@@ -2310,6 +2714,7 @@ export namespace reims {
guest_tools_disabled?: boolean;
shared_dir?: string;
guest_lang?: string;
suspend_info?: SuspendInfo;
static createFrom(source: any = {}) {
return new VMDetail(source);
@@ -2357,25 +2762,26 @@ export namespace reims {
this.guest_tools_disabled = source["guest_tools_disabled"];
this.shared_dir = source["shared_dir"];
this.guest_lang = source["guest_lang"];
}
}
export class VMListItem {
name: string;
dir: string;
pid?: number;
state: string;
static createFrom(source: any = {}) {
return new VMListItem(source);
this.suspend_info = this.convertValues(source["suspend_info"], SuspendInfo);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.name = source["name"];
this.dir = source["dir"];
this.pid = source["pid"];
this.state = source["state"];
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice && a.map) {
return (a as any[]).map(elem => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
export class ValidationIssue {
field: string;
@@ -2539,6 +2945,9 @@ export namespace runtime {
name_en: string;
required_files?: string[];
default_api_version?: string;
control_executable?: string;
utility_executable?: string;
control_qemu_env?: string;
builtin?: boolean;
plugin_id?: string;
@@ -2554,6 +2963,9 @@ export namespace runtime {
this.name_en = source["name_en"];
this.required_files = source["required_files"];
this.default_api_version = source["default_api_version"];
this.control_executable = source["control_executable"];
this.utility_executable = source["utility_executable"];
this.control_qemu_env = source["control_qemu_env"];
this.builtin = source["builtin"];
this.plugin_id = source["plugin_id"];
}
+1
View File
@@ -4,6 +4,7 @@ go 1.26.0
require (
github.com/klauspost/compress v1.20.5
github.com/pelletier/go-toml/v2 v2.4.3
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
@@ -39,6 +39,8 @@ github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy
github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
+31 -7
View File
@@ -4,7 +4,7 @@ import (
"context"
"fmt"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
@@ -57,7 +57,7 @@ func (a *App) findRunningVMPID(ctx context.Context, name string) int {
return 0
}
func buildVMAffinityStatus(detail reims.VMDetail, rep host.Report, globalAutoPin bool, pid int) VMAffinityStatus {
func buildVMAffinityStatus(detail driver.VMInfo, rep host.Report, globalAutoPin bool, pid int) VMAffinityStatus {
cfg := vmstart.ReadVMAffinity(detail.Directory)
res := vmstart.ResolveVMAffinity(cfg, globalAutoPin, rep, detail.CPUs)
savedCPUs := cfg.CPUs
@@ -98,7 +98,14 @@ func buildVMAffinityStatus(detail reims.VMDetail, rep host.Report, globalAutoPin
// GetVMAffinity returns the per-VM processor affinity configuration, resolved
// effective CPU set, and live QEMU process affinity mask when running.
func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
detail, err := a.GetVMDetail(name)
return a.GetVMAffinityWithDriver("", name)
}
func (a *App) GetVMAffinityWithDriver(driverID, name string) (VMAffinityStatus, error) {
vm, err := a.resolveVMInfo(driverID, name)
if err != nil {
return VMAffinityStatus{}, err
}
detail := vm
if err != nil {
return VMAffinityStatus{}, err
}
@@ -109,7 +116,12 @@ func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
rep := host.Inspect(root)
pid := 0
if detail.State == "running" {
pid = a.findRunningVMPID(a.baseCtx(), name)
if listed, ok := a.polledVMForDriver(vm.DriverID, name); ok && listed.PID != nil {
pid = *listed.PID
}
if vm.PID != nil {
pid = *vm.PID
}
}
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), nil
}
@@ -117,7 +129,14 @@ func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
// SetVMAffinity saves a VM's processor affinity mapping and immediately applies
// it (plus EcoQoS power-throttling control) to the running QEMU process if active.
func (a *App) SetVMAffinity(name string, req VMAffinityUpdate) (VMAffinityStatus, error) {
detail, err := a.GetVMDetail(name)
return a.SetVMAffinityWithDriver("", name, req)
}
func (a *App) SetVMAffinityWithDriver(driverID, name string, req VMAffinityUpdate) (VMAffinityStatus, error) {
vm, err := a.resolveVMInfo(driverID, name)
if err != nil {
return VMAffinityStatus{}, err
}
detail := vm
if err != nil {
return VMAffinityStatus{}, err
}
@@ -142,12 +161,17 @@ func (a *App) SetVMAffinity(name string, req VMAffinityUpdate) (VMAffinityStatus
pid := 0
if detail.State == "running" {
pid = a.findRunningVMPID(a.baseCtx(), name)
if listed, ok := a.polledVMForDriver(vm.DriverID, name); ok && listed.PID != nil {
pid = *listed.PID
}
if vm.PID != nil {
pid = *vm.PID
}
}
if pid > 0 {
line, applyErr := vmstart.ApplyVMAffinity(loc, rep, detail.Directory, globalAutoPin, pid, detail.CPUs, true)
if line != "" {
a.emitLog(name, line)
a.emitVMLogForDriver(driverID, name, line)
}
if applyErr != nil {
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), applyErr
+2 -2
View File
@@ -4,7 +4,7 @@ import (
"reflect"
"testing"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/vmstart"
)
@@ -21,7 +21,7 @@ func TestBuildVMAffinityStatus(t *testing.T) {
}
rep := host.Report{LogicalCPUs: 16}
st := buildVMAffinityStatus(reims.VMDetail{
st := buildVMAffinityStatus(driver.VMInfo{
Name: "test-vm",
Directory: dir,
CPUs: 6,
+277 -721
View File
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -6,7 +6,7 @@ import (
"testing"
"time"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/macos/reims"
)
func TestPolledVMsReusesFreshPoll(t *testing.T) {
@@ -82,11 +82,11 @@ func TestReleaseVMTypingDrainsAndRemovesQueue(t *testing.T) {
a := &App{}
typing.mu.Lock()
ch := make(chan remoteTextItem)
typing.remoteQueues[name] = ch
typing.lastHintAt[name] = time.Now()
typing.remoteQueues[vmKey(name)] = ch
typing.lastHintAt[vmKey(name)] = time.Now()
typing.mu.Unlock()
go func() {
a.runRemoteTextQueue(name, ch)
a.runRemoteTextQueue(vmKey(name), name, ch)
close(done)
}()
releaseVMTyping(name)
+8 -9
View File
@@ -17,14 +17,14 @@ import (
"github.com/Nwflower/reims-go/internal/cli"
"github.com/Nwflower/reims-go/internal/fetch"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/netproxy"
"github.com/Nwflower/reims-go/internal/selfupdate"
"github.com/Nwflower/reims-go/internal/version"
)
// appUpdateTaskKind is the task kind the frontend watches for update progress.
// appUpdateTaskKind is the task kind the frontend watches for update host.
const appUpdateTaskKind = "app-update"
// appUpdateReady is the verified download InstallAppUpdate swaps in.
@@ -68,11 +68,10 @@ func (a *App) DownloadAppUpdate() (string, error) {
if err := a.updateSupported(); err != nil {
return "", err
}
a.mu.Lock()
if a.needsSetup {
a.mu.Unlock()
return "", errors.New("choose a data folder first")
if err := a.requireWritableDataRoot(); err != nil {
return "", err
}
a.mu.Lock()
dataRoot := a.cfg.DataRoot
a.mu.Unlock()
@@ -100,8 +99,8 @@ func (a *App) DownloadAppUpdate() (string, error) {
go func() {
defer cancel()
path, sum, err := downloadAppUpdate(ctx, info, appUpdateDir(dataRoot), func(done, total int64) {
tasks.update(id, installer.Update{
Kind: installer.KindProgress, Step: "downloading " + info.AssetName,
tasks.update(id, host.Update{
Kind: host.KindProgress, Step: "downloading " + info.AssetName,
Done: done, Total: total, Percent: percent(done, total),
})
})
@@ -228,7 +227,7 @@ func (a *App) finishAppUpdateWithExe(exe string) {
if a.launch.WaitPID == 0 {
return
}
if !keepOld && dataRoot != "" {
if !keepOld && dataRoot != "" && a.dataRootUsable() {
_ = os.RemoveAll(appUpdateDir(dataRoot))
}
if keepOld {
+15 -133
View File
@@ -1,148 +1,30 @@
package app
import (
"fmt"
"os"
"path/filepath"
"strings"
"errors"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// CloneVMCoW derives a new VM instantaneously from a stopped source VM using a
// qcow2 copy-on-write overlay (`qemu-img create -f qcow2 -b <src> -F qcow2`)
// so the source golden disk is never mutated while the clone gets its own fresh
// OpenCore identity (SMBIOS/serial/MAC) via `reims-ctl create --disk --disk-mode in-place`.
// CloneVMCoW derives a VM through the source VM's owning driver.
func (a *App) CloneVMCoW(sourceName, cloneName string) error {
loc := a.locale()
cloneName = strings.TrimSpace(cloneName)
if cloneName == "" {
return i18n.NewCodedError(loc, "E_VM_CLONE_EMPTY_NAME", "err.clone.missing_name", nil, nil)
}
if strings.EqualFold(sourceName, cloneName) {
return i18n.NewCodedError(loc, "E_VM_CLONE_SAME_NAME", "err.clone.same_name", nil, nil)
}
return a.CloneVMCoWWithDriver("", sourceName, cloneName)
}
func (a *App) CloneVMCoWWithDriver(driverID, sourceName, cloneName string) error {
a.mu.Lock()
cfgCopy := *a.cfg
svc := a.lifecycleSvc
a.mu.Unlock()
cfgCopy.Locale = loc
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
if svc == nil {
return errors.New("driver lifecycle is not initialized")
}
ref := driver.VMRef{DriverID: driverID, Name: sourceName}
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(driverID, cloneName, line) })
if err := svc.CloneCoW(a.baseCtx(), ref, cloneName, w, w); err != nil {
return err
}
c := reims.NewClient(&cfgCopy, *active)
ctx := a.baseCtx()
src, err := a.GetVMDetail(sourceName)
if err != nil {
return err
}
if a.isVMRunning(ctx, c, sourceName, src) {
return i18n.NewCodedError(loc, "E_VM_CLONE_RUNNING", "err.clone.source_running", i18n.Vars{"name": sourceName}, nil)
}
if src.HasInstaller {
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 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 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, loc)
for _, iss := range nameCheck {
if iss.Field == "name" {
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 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 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) })
env := rt.BuildChildEnv(&cfgCopy, *active)
a.emitLog(cloneName, fmt.Sprintf("Creating CoW overlay for %s backed by %s...", cloneName, filepath.Base(srcDisk)))
if err := reims.CreateCoWOverlay(ctx, active.QemuImgPath(), env, srcDisk, overlayPath, w, w); err != nil {
return err
}
audio := src.Audio
network := src.Network
logs := src.Logs
capture := src.Capture
createOpts := reims.CreateOpts{
Name: cloneName,
SourceMode: "disk",
Disk: overlayPath,
DiskMode: "in-place",
DiskController: src.DiskController,
CPUs: src.CPUs,
Memory: src.Memory,
Graphics: src.Graphics,
GPU: src.GPU,
Resolution: src.Resolution,
Displays: src.Displays,
Capture: &capture,
Audio: &audio,
Network: &network,
Logs: &logs,
Start: false,
}
if err := c.Create(ctx, createOpts, w, w); err != nil {
_ = os.Remove(overlayPath)
return err
}
if postSet, ok := reims.PostCreateSetOpts(createOpts); ok {
if serr := c.Set(ctx, postSet, w, w); serr != nil {
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone settings: %v", serr))
}
}
if src.GuestLang != "" || vmstart.HasSavedVMAffinity(src.Directory) {
if cloned, serr := c.Show(ctx, cloneName); serr == nil && cloned.Directory != "" {
if src.GuestLang != "" {
prep, lerr := a.prep(cloneName)
if lerr == nil {
lerr = prep.ApplyGuestLang(ctx, cloned.Directory, src.GuestLang, false)
}
if lerr != nil {
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone language (%s): %v", src.GuestLang, lerr))
}
}
if werr := writeVMMacOS(cloned.Directory, readVMMacOS(src.Directory)); werr != nil {
a.emitLog(cloneName, fmt.Sprintf("Warning: could not copy macOS release: %v", werr))
}
if vmstart.HasSavedVMAffinity(src.Directory) {
if _, aerr := vmstart.SaveVMAffinity(cloned.Directory, vmstart.ReadVMAffinity(src.Directory), rep.LogicalCPUs); aerr != nil {
a.emitLog(cloneName, fmt.Sprintf("Warning: could not copy CPU affinity setting: %v", aerr))
}
}
}
}
a.emitLog(cloneName, fmt.Sprintf("CoW clone %s ready (backing image %s untouched)", cloneName, srcDisk))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.wakePoll()
a.emitLifecycleStateChanged()
return nil
}
+39 -23
View File
@@ -9,14 +9,18 @@ import (
"strings"
"time"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/opencore"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/macos/installer"
"github.com/Nwflower/reims-go/internal/macos/opencore"
"github.com/Nwflower/reims-go/internal/macos/reims"
rt "github.com/Nwflower/reims-go/internal/runtime"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
func (a *App) createVMFlow(opts reims.CreateOpts) error {
if err := a.requireMacOSEnabled(); err != nil {
return err
}
if issues := a.ValidateCreate(opts); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
@@ -37,13 +41,13 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
ctx, cancel := context.WithCancel(a.baseCtx())
defer cancel()
taskID, w, finishTask := a.ctlTaskWriterWithCancel("vm-create", opts.Name, cancel)
a.emitLog(opts.Name, "Creating VM "+opts.Name+"...")
a.emitVMLog(opts.Name, "Creating VM "+opts.Name+"...")
existingVMs, _ := c.List(ctx)
if removed, rerr := reims.CleanAbortedCreateDir(cfgCopy.XDGDataDir(), opts, existingVMs); rerr != nil {
a.emitLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
a.emitVMLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
} else if removed != "" {
a.emitLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
a.emitVMLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
}
// Ensure any requested macOS installer is downloaded via installer.Client
@@ -53,6 +57,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
// the completed image without downloading again.
if dlKind, dlVersion := createInstallerTarget(opts); dlKind != "" {
ic := installer.NewClient(&cfgCopy, *active)
ic.Downloader = a.activeDownloader
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) {
@@ -64,15 +69,15 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
if derr != nil {
if errors.Is(derr, context.Canceled) || ctx.Err() != nil {
finishTask(context.Canceled)
a.emitLog(opts.Name, "Create canceled.")
a.emitVMLog(opts.Name, "Create canceled.")
return context.Canceled
}
finishTask(derr)
a.emitLog(opts.Name, "Create error: "+derr.Error())
a.emitVMLog(opts.Name, "Create error: "+derr.Error())
return derr
}
if res != nil && res.Image != "" {
a.emitLog(opts.Name, "Installer ready: "+res.Image)
a.emitVMLog(opts.Name, "Installer ready: "+res.Image)
}
}
}
@@ -84,17 +89,17 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
perr := installer.EnsureCachedAsset(ctx, cfgCopy.XDGCacheDir(), installer.OcBinaryDataAsset, nil, func(u installer.Update) {
if !loggedPrefetch && u.Kind == installer.KindStep {
loggedPrefetch = true
a.emitLog(opts.Name, opts.Name+": "+u.Message)
a.emitVMLog(opts.Name, opts.Name+": "+u.Message)
}
tasks.update(taskID, u)
})
if perr != nil {
if errors.Is(perr, context.Canceled) || ctx.Err() != nil {
finishTask(context.Canceled)
a.emitLog(opts.Name, "Create canceled.")
a.emitVMLog(opts.Name, "Create canceled.")
return context.Canceled
}
a.emitLog(opts.Name, "Pre-fetch OpenCore resources skipped (reims-ctl will retry): "+perr.Error())
a.emitVMLog(opts.Name, "Pre-fetch OpenCore resources skipped (reims-ctl will retry): "+perr.Error())
}
}
@@ -103,7 +108,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
if opts.Disk != "" && reims.NeedsDiskConversion(opts.Disk) {
convertedTmp = filepath.Join(cfgCopy.TempDir(), fmt.Sprintf("import-%s-%d.qcow2", opts.Name, time.Now().Unix()))
defer os.Remove(convertedTmp)
a.emitLog(opts.Name, fmt.Sprintf("Converting %s to qcow2 via qemu-img...", filepath.Base(opts.Disk)))
a.emitVMLog(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 {
@@ -111,9 +116,9 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
}
finishTask(cerr)
if errors.Is(cerr, context.Canceled) {
a.emitLog(opts.Name, "Create canceled.")
a.emitVMLog(opts.Name, "Create canceled.")
} else {
a.emitLog(opts.Name, "Disk conversion error: "+cerr.Error())
a.emitVMLog(opts.Name, "Disk conversion error: "+cerr.Error())
}
return cerr
}
@@ -128,12 +133,23 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
}
finishTask(err)
if errors.Is(err, context.Canceled) {
a.emitLog(opts.Name, "Create canceled.")
a.emitVMLog(opts.Name, "Create canceled.")
} else {
a.emitLog(opts.Name, "Create error: "+err.Error())
a.emitVMLog(opts.Name, "Create error: "+err.Error())
}
return err
}
createdDir := strings.TrimSpace(opts.Dir)
if det, serr := c.Show(ctx, opts.Name); serr == nil && det.Directory != "" {
createdDir = det.Directory
}
if createdDir == "" {
createdDir = filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms", opts.Name)
}
if err := driver.WriteOwnerDriver(createdDir, driver.BuiltinReimsMacOSDriverID); err != nil {
finishTask(err)
return fmt.Errorf("record VM driver ownership: %w", err)
}
if postSet, ok := reims.PostCreateSetOpts(opts); ok {
var parts []string
if postSet.DiskController != "" {
@@ -142,9 +158,9 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
if postSet.Capture != nil && !*postSet.Capture {
parts = append(parts, "capture=off")
}
a.emitLog(opts.Name, fmt.Sprintf("Applying VM defaults for %s (%s)...", opts.Name, strings.Join(parts, ", ")))
a.emitVMLog(opts.Name, fmt.Sprintf("Applying VM defaults for %s (%s)...", opts.Name, strings.Join(parts, ", ")))
if serr := c.Set(ctx, postSet, w, w); serr != nil {
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not apply post-create defaults (%s): %v", strings.Join(parts, ", "), serr))
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not apply post-create defaults (%s): %v", strings.Join(parts, ", "), serr))
}
}
guestLang := strings.TrimSpace(opts.GuestLang)
@@ -165,7 +181,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
}
}
if werr := writeVMMacOS(vmDir, release); werr != nil {
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not record macOS release (%s): %v", release, werr))
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not record macOS release (%s): %v", release, werr))
}
if guestLang != "" {
prep, lerr := a.prep(opts.Name)
@@ -173,14 +189,14 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
lerr = prep.ApplyGuestLang(ctx, vmDir, guestLang, false)
}
if lerr != nil {
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not apply macOS language (%s): %v", guestLang, lerr))
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not apply macOS language (%s): %v", guestLang, lerr))
}
}
finishTask(nil)
a.emitLog(opts.Name, "VM "+opts.Name+" ready.")
a.emitVMLog(opts.Name, "VM "+opts.Name+" ready.")
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
if startAfterCreate {
return a.StartVM(opts.Name)
return a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, opts.Name)
}
return nil
}
+122
View File
@@ -0,0 +1,122 @@
package app
import (
"errors"
"fmt"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/version"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// openDataRoot opens the current data folder (dataroot.Open: version check,
// migration under the folder lock) and records whether it may be written.
func (a *App) openDataRoot() dataroot.Status {
a.mu.Lock()
dir := a.cfg.DataRoot
a.mu.Unlock()
st := dataroot.Open(dir, version.Version)
a.mu.Lock()
a.root = st
a.mu.Unlock()
a.logDataRoot(st)
return st
}
func (a *App) logDataRoot(st dataroot.Status) {
switch {
case st.ReadOnly:
msg := fmt.Sprintf("Data folder %s opened read-only (%s)", st.Dir, st.Reason)
if st.Detail != "" {
msg += ": " + st.Detail
}
a.emitLog("app", msg)
case len(st.Migrated) > 0:
a.emitLog("app", fmt.Sprintf("Data folder upgraded to layout v%d (%s)", st.Version, strings.Join(st.Migrated, ", ")))
}
}
// dataRootUsable reports whether anything may read the data folder through
// reims-ctl or write to it: not before first-run setup has chosen a folder,
// and not while the folder is open read-only.
func (a *App) dataRootUsable() bool {
a.mu.Lock()
defer a.mu.Unlock()
return !a.needsSetup && !a.root.ReadOnly
}
// requireWritableDataRoot is the guard for bindings that change the data
// folder and can be reached without the main window, such as a VM start
// handed over from the CLI.
func (a *App) requireWritableDataRoot() error {
a.mu.Lock()
defer a.mu.Unlock()
if a.needsSetup {
return i18n.NewCodedError(i18n.EffectiveLocale(a.cfg.Locale), "E_DATAROOT_SETUP", "err.dataroot.needs_setup", nil, nil)
}
return dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root)
}
// saveConfigLocked persists a.cfg; a.mu must be held. Before first-run setup
// a.cfg points at a suggested folder the user has not chosen, so changes stay
// in memory until CompleteSetup writes them into the chosen folder. A folder
// open read-only refuses the write.
func (a *App) saveConfigLocked() error {
if a.needsSetup {
return nil
}
if err := dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root); err != nil {
return err
}
return config.Save("", a.cfg)
}
// ReopenDataRoot opens the current data folder again: after another process
// finished upgrading it, after a failed upgrade, or with repair set, to rebuild
// a damaged version record on the user's request. When the folder becomes
// writable, the parts that were held back start.
func (a *App) ReopenDataRoot(repair bool) (dataroot.Status, error) {
a.mu.Lock()
if a.needsSetup {
st := a.root
a.mu.Unlock()
return st, nil
}
dir := a.cfg.DataRoot
wasReadOnly := a.root.ReadOnly
a.mu.Unlock()
var st dataroot.Status
if repair {
st = dataroot.Repair(dir, version.Version)
} else {
st = dataroot.Open(dir, version.Version)
}
a.mu.Lock()
a.root = st
a.mu.Unlock()
a.logDataRoot(st)
if wasReadOnly && st.Writable() {
a.resetDataRootCaches()
a.reloadPlugins()
a.wakePoll()
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return st, nil
}
// dataRootMessage is the localized explanation the read-only screen shows,
// without the error code and raw detail (shown separately).
func dataRootMessage(loc i18n.Locale, st dataroot.Status) string {
var ce *i18n.CodedError
if errors.As(dataroot.Error(loc, st), &ce) {
return ce.Summary(loc)
}
return ""
}
+90
View File
@@ -0,0 +1,90 @@
package app
import (
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/datamigrate"
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/version"
)
func dirEntries(t *testing.T, dir string) []string {
t.Helper()
var out []string
_ = filepath.Walk(dir, func(p string, _ os.FileInfo, err error) error {
if err == nil && p != dir {
out = append(out, p)
}
return nil
})
return out
}
// Before first-run setup a.cfg only suggests a folder. Picking a language on
// the setup screen or starting plugins must not write anything into it.
func TestNothingWrittenBeforeSetup(t *testing.T) {
dir := t.TempDir()
cfg := config.Default()
cfg.DataRoot = dir
a := &App{cfg: cfg, needsSetup: true}
if err := a.SetLocale("en-US"); err != nil {
t.Fatalf("SetLocale before setup: %v", err)
}
if a.cfg.Locale != "en-US" {
t.Fatalf("locale not kept in memory: %q", a.cfg.Locale)
}
a.initPlugins()
if a.pluginMgr != nil {
t.Fatal("plugins started before setup")
}
a.appendUICrashLog("renderer unresponsive")
if got := dirEntries(t, dir); len(got) != 0 {
t.Fatalf("suggested folder written before setup: %v", got)
}
if err := a.StartVM("mac"); err == nil {
t.Fatal("StartVM before setup must be refused")
}
}
// A folder written by a newer release opens read-only: settings, VM starts
// and plugins are all refused, and the folder is left as it was.
func TestReadOnlyFolderRefusesWrites(t *testing.T) {
dir := t.TempDir()
cfgPath := filepath.Join(dir, "reims-go.json")
if err := os.WriteFile(cfgPath, []byte(`{"data_root": "x", "locale": "zh-CN"}`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, datamigrate.StampFile), []byte(`{"data_version": 999}`), 0o644); err != nil {
t.Fatal(err)
}
before := dirEntries(t, dir)
cfg := config.Default()
cfg.DataRoot = dir
a := &App{cfg: cfg, root: dataroot.Open(dir, version.Version)}
if !a.root.ReadOnly {
t.Fatalf("root = %+v, want read-only", a.root)
}
if err := a.SetLocale("en-US"); err == nil {
t.Fatal("SetLocale on a read-only folder must fail")
}
if raw, _ := os.ReadFile(cfgPath); string(raw) != `{"data_root": "x", "locale": "zh-CN"}` {
t.Fatalf("config rewritten: %s", raw)
}
if err := a.StartVM("mac"); err == nil {
t.Fatal("StartVM on a read-only folder must be refused")
}
a.initPlugins()
if a.pluginMgr != nil {
t.Fatal("plugins started on a read-only folder")
}
a.appendUICrashLog("renderer unresponsive")
if got := dirEntries(t, dir); len(got) != len(before) {
t.Fatalf("read-only folder changed: before %v, after %v", before, got)
}
}
+45 -44
View File
@@ -10,7 +10,7 @@ import (
"strings"
"time"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
@@ -20,7 +20,8 @@ type diagnosticsBundle struct {
HostReport host.Report
Optimizations []host.Optimization
Runtime *rt.Installed
VMDetail *reims.VMDetail
VMDetail any // legacy test/export payload; production uses VMInfo
VMInfo *driver.VMInfo
SerialLog string
QEMULog string
AppLogs []string
@@ -41,7 +42,7 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
if err != nil {
return err
}
_, err = w.Write([]byte(reims.RedactText(content)))
_, err = w.Write([]byte(host.RedactText(content)))
return err
}
addJSON := func(name string, v any) error {
@@ -57,7 +58,7 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
"host": b.HostReport,
"optimizations": b.Optimizations,
}
if code, detail := reims.DiagnoseGPULog(b.QEMULog); code != "" {
if code, detail := host.DiagnoseGPULog(b.QEMULog); code != "" {
hostSummary["gpu_diagnosis"] = map[string]string{
"code": code,
"detail": detail,
@@ -76,10 +77,14 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
}
}
if b.VMDetail != nil {
sanitized := *b.VMDetail
sanitized.NetworkSummary = reims.RedactLogLine(sanitized.NetworkSummary)
sanitized.ExtraArgs = reims.RedactLogLine(sanitized.ExtraArgs)
if err := addJSON("vm-detail.json", sanitized); err != nil {
if err := addJSON("vm-detail.json", b.VMDetail); err != nil {
_ = zw.Close()
_ = f.Close()
return err
}
}
if b.VMInfo != nil {
if err := addJSON("vm-info.json", b.VMInfo); err != nil {
_ = zw.Close()
_ = f.Close()
return err
@@ -120,52 +125,48 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
return f.Close()
}
// ExportDiagnostics collects a redacted troubleshooting zip bundle (host probe,
// runtime manifest, VM detail, serial/QEMU logs, and recent app logs) into
// `<DataRoot>/reports/` and opens the folder in File Explorer.
// ExportDiagnostics collects a redacted troubleshooting zip bundle through the owning driver.
func (a *App) ExportDiagnostics(name string) (string, error) {
return a.ExportDiagnosticsWithDriver("", name)
}
func (a *App) ExportDiagnosticsWithDriver(driverID, name string) (string, error) {
var vm driver.VMInfo
var err error
if strings.TrimSpace(name) != "" {
vm, err = a.resolveVMInfo(driverID, name)
if err != nil {
return "", err
}
}
a.mu.Lock()
cfgCopy := *a.cfg
appLogs := append([]string(nil), a.recentLogs...)
a.mu.Unlock()
rep := host.Inspect(cfgCopy.DataRoot)
var active *rt.Installed
var patchNames []string
if inst, err := rt.ResolveActive(&cfgCopy); err == nil {
active = inst
for _, p := range inst.Manifest.Patches {
patchNames = append(patchNames, p.Name)
}
}
bundle := diagnosticsBundle{
HostReport: rep,
Optimizations: host.EvaluateOptimizations(rep, patchNames),
Runtime: active,
AppLogs: appLogs,
PluginDiagnostics: a.collectPluginDiagnostics(context.Background(), name),
}
active, _ := rt.ResolveActive(&cfgCopy)
bundle := diagnosticsBundle{}
label := "host"
if strings.TrimSpace(name) != "" {
label = name
if c, err := a.client(); err == nil {
ctx := context.Background()
if d, derr := a.GetVMDetail(name); derr == nil {
bundle.VMDetail = &d
}
if serial, serr := c.ReadLogs(ctx, name, true); serr == nil {
bundle.SerialLog = serial
}
if qemuLog, qerr := c.ReadLogs(ctx, name, false); qerr == nil {
bundle.QEMULog = qemuLog
}
pluginKey := ""
var info *driver.VMInfo
if vm.Name != "" {
info = &vm
label = vm.Name
ref := vm.Ref()
pluginKey = ref.Key()
if ref.DriverID != driver.BuiltinReimsMacOSDriverID {
label = sshHostAliasForDriver(ref.DriverID, vm.Name)
}
if serial, err := a.ReadVMLogsWithDriver(ref.DriverID, vm.Name, true); err == nil {
bundle.SerialLog = serial
}
if qemuLog, err := a.ReadVMLogsWithDriver(ref.DriverID, vm.Name, false); err == nil {
bundle.QEMULog = qemuLog
}
}
bundle.HostReport, bundle.Optimizations, bundle.Runtime, bundle.AppLogs = rep, a.evaluateOptimizations(rep), active, appLogs
bundle.VMInfo, bundle.PluginDiagnostics = info, a.collectPluginDiagnostics(context.Background(), pluginKey)
reportsDir := filepath.Join(cfgCopy.DataRoot, "reports")
zipName := fmt.Sprintf("reims-go-diag-%s-%s.zip", label, time.Now().Format("20060102-150405"))
zipPath := filepath.Join(reportsDir, zipName)
zipPath := filepath.Join(reportsDir, fmt.Sprintf("reims-go-diag-%s-%s.zip", label, time.Now().Format("20060102-150405")))
if err := writeDiagnosticsZip(zipPath, bundle); err != nil {
return "", err
}
+1 -1
View File
@@ -7,8 +7,8 @@ import (
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/macos/reims"
)
func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) {
+64 -77
View File
@@ -2,106 +2,93 @@ package app
import (
"context"
"errors"
"fmt"
"strings"
"github.com/Nwflower/reims-go/internal/driver/reims"
rt "github.com/Nwflower/reims-go/internal/runtime"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
"github.com/Nwflower/reims-go/internal/driver"
)
// ResizeVMDisk expands a stopped VM's virtual disk via `qemu-img resize` and
// returns the macOS `diskutil` command needed to grow the APFS container inside
// the guest.
func (a *App) ResizeVMDisk(name, newSize string) (reims.DiskResizeResult, error) {
// ResizeVMDisk expands a stopped VM's virtual disk through its owning driver.
func (a *App) ResizeVMDisk(name, newSize string) (driver.DiskResizeResult, error) {
return a.ResizeVMDiskWithDriver("", name, newSize)
}
func (a *App) ResizeVMDiskWithDriver(driverID, name, newSize string) (driver.DiskResizeResult, error) {
a.mu.Lock()
cfgCopy := *a.cfg
svc := a.lifecycleSvc
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return reims.DiskResizeResult{}, err
if svc == nil {
return driver.DiskResizeResult{}, errors.New("driver lifecycle is not initialized")
}
c := reims.NewClient(&cfgCopy, *active)
ctx := a.baseCtx()
d, err := a.GetVMDetail(name)
if err != nil {
return reims.DiskResizeResult{}, err
}
if a.isVMRunning(ctx, c, name, d) {
return reims.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name)
}
diskPath := resolveVMDiskPath(d)
if diskPath == "" {
return reims.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name)
}
taskCtx, cancel := context.WithCancel(ctx)
ref := driver.VMRef{DriverID: driverID, Name: name}
taskCtx, cancel := context.WithCancel(a.baseCtx())
defer cancel()
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-resize", name, cancel)
a.emitLog(name, fmt.Sprintf("Resizing disk for %s (%s)...", name, strings.TrimSpace(newSize)))
env := rt.BuildChildEnv(&cfgCopy, *active)
res, err := reims.ResizeDisk(taskCtx, active.QemuImgPath(), env, diskPath, newSize, w, w)
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-resize", ref.Key(), cancel)
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Resizing disk for %s (%s)...", name, strings.TrimSpace(newSize)))
res, err := svc.ResizeDisk(taskCtx, ref, newSize, w, w)
if err != nil {
finishTask(err)
a.emitLog(name, "Disk resize error: "+err.Error())
return reims.DiskResizeResult{}, err
a.emitVMLogForDriver(driverID, name, "Disk resize error: "+err.Error())
return driver.DiskResizeResult{}, err
}
finishTask(nil)
a.emitLog(name, fmt.Sprintf("Expanded disk for %s: %.0f GB -> %.0f GB (run diskutil inside macOS to expand APFS)",
name, float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30)))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Expanded disk for %s: %.0f GB -> %.0f GB", name, float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30)))
a.wakePoll()
a.emitLifecycleStateChanged()
return res, nil
}
// CompactVMDisk rewrites a stopped VM's standalone qcow2 image into a freshly
// compacted sparse qcow2 file to reclaim unused/TRIMmed host disk space.
func (a *App) CompactVMDisk(name string) (reims.DiskCompactResult, error) {
// CompactVMDisk reclaims unused host space through the owning driver.
func (a *App) CompactVMDisk(name string) (driver.DiskCompactResult, error) {
return a.CompactVMDiskWithDriver("", name)
}
func (a *App) CompactVMDiskWithDriver(driverID, name string) (driver.DiskCompactResult, error) {
return a.runCompactVMDisk(driverID, name, false)
}
// OptimizeVMDisk rewrites a stopped VM's qcow2 disk with extended L2 subclusters.
func (a *App) OptimizeVMDisk(name string) (driver.DiskCompactResult, error) {
return a.OptimizeVMDiskWithDriver("", name)
}
func (a *App) OptimizeVMDiskWithDriver(driverID, name string) (driver.DiskCompactResult, error) {
return a.runCompactVMDisk(driverID, name, true)
}
func (a *App) runCompactVMDisk(driverID, name string, optimize bool) (driver.DiskCompactResult, error) {
a.mu.Lock()
cfgCopy := *a.cfg
svc := a.lifecycleSvc
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return reims.DiskCompactResult{}, err
if svc == nil {
return driver.DiskCompactResult{}, errors.New("driver lifecycle is not initialized")
}
c := reims.NewClient(&cfgCopy, *active)
ctx := a.baseCtx()
d, err := a.GetVMDetail(name)
if err != nil {
return reims.DiskCompactResult{}, err
}
if a.isVMRunning(ctx, c, name, d) {
return reims.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name)
}
diskPath := resolveVMDiskPath(d)
if diskPath == "" {
return reims.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name)
}
taskCtx, cancel := context.WithCancel(ctx)
ref := driver.VMRef{DriverID: driverID, Name: name}
taskCtx, cancel := context.WithCancel(a.baseCtx())
defer cancel()
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-compact", name, cancel)
a.emitLog(name, fmt.Sprintf("Compacting qcow2 disk for %s to reclaim unused space...", name))
env := rt.BuildChildEnv(&cfgCopy, *active)
res, err := reims.CompactDisk(taskCtx, active.QemuImgPath(), env, diskPath, w, w)
taskKind := "vm-disk-compact"
message := fmt.Sprintf("Compacting disk for %s to reclaim unused space...", name)
if optimize {
taskKind = "vm-disk-optimize"
message = fmt.Sprintf("Optimizing qcow2 disk for %s with extended L2 subclusters...", name)
}
_, w, finishTask := a.ctlTaskWriterWithCancel(taskKind, ref.Key(), cancel)
a.emitVMLogForDriver(driverID, name, message)
var (
res driver.DiskCompactResult
err error
)
if optimize {
res, err = svc.OptimizeDisk(taskCtx, ref, w, w)
} else {
res, err = svc.CompactDisk(taskCtx, ref, w, w)
}
if err != nil {
finishTask(err)
a.emitLog(name, "Disk compact error: "+err.Error())
return reims.DiskCompactResult{}, err
a.emitVMLogForDriver(driverID, name, "Disk rewrite error: "+err.Error())
return driver.DiskCompactResult{}, err
}
finishTask(nil)
a.emitLog(name, fmt.Sprintf("Compacted disk for %s: %.2f GB -> %.2f GB (reclaimed %.2f GB)",
name,
float64(res.BeforeBytes)/float64(1<<30),
float64(res.AfterBytes)/float64(1<<30),
float64(res.ReclaimedBytes)/float64(1<<30)))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Rewrote disk for %s: %.2f GB -> %.2f GB (reclaimed %.2f GB, extended L2: %t)", name, float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30), res.ExtendedL2Enabled))
a.wakePoll()
a.emitLifecycleStateChanged()
return res, nil
}
+70
View File
@@ -0,0 +1,70 @@
package app
import (
"context"
"encoding/binary"
"os"
"path/filepath"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/plugin"
)
func TestGetDefenderExclusionCommand(t *testing.T) {
a := &App{cfg: &config.Config{DataRoot: `D:\Rei's VMs`}}
const want = `Add-MpPreference -ExclusionPath 'D:\Rei''s VMs' -ExclusionProcess 'qemu-system-x86_64.exe'`
if got := a.GetDefenderExclusionCommand(); got != want {
t.Fatalf("GetDefenderExclusionCommand = %q, want %q", got, want)
}
}
func TestVMStatsDiskHeaderMeta(t *testing.T) {
cfg := &config.Config{DataRoot: t.TempDir()}
disk := filepath.Join(cfg.DataRoot, "disk.qcow2")
hdr := make([]byte, 104)
copy(hdr, "QFI\xfb")
binary.BigEndian.PutUint32(hdr[4:8], 3)
binary.BigEndian.PutUint32(hdr[60:64], 2)
binary.BigEndian.PutUint64(hdr[72:80], 0x10)
if err := os.WriteFile(disk, hdr, 0o644); err != nil {
t.Fatal(err)
}
drv := &appSecondDriver{
id: driver.BuiltinReimsMacOSDriverID,
vms: []driver.VMInfo{{
Name: "test",
DriverID: driver.BuiltinReimsMacOSDriverID,
Directory: cfg.DataRoot,
State: "stopped",
DiskPath: disk,
}},
}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "test.macos", Version: "1.0.0"},
Source: plugin.SourceBuiltin,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, drv.id, drv)
return nil
},
}); err != nil {
t.Fatal(err)
}
reg.Reconcile(context.Background())
router := driver.NewRouter(reg, nil)
a := &App{
cfg: cfg,
lastVMsAt: time.Now(),
lifecycleSvc: vmlifecycle.New(reg, router, nil),
}
stats, err := a.GetVMStats("test")
if err != nil || !stats.DiskExtendedL2 || stats.DiskSnapshotCount != 2 {
t.Fatalf("GetVMStats = %+v, %v", stats, err)
}
}
+38 -10
View File
@@ -2,6 +2,7 @@ package app
import (
"fmt"
"os"
"strings"
"github.com/Nwflower/reims-go/internal/guesttools"
@@ -67,12 +68,6 @@ func normalizeDriveSelection(available []host.Drive, selected []string) ([]strin
return out, nil
}
// validatedDriveConfig derives runtime roots only from currently present fixed volumes
// whose stable GUID matches the user's persisted selection. It never saves filtered state.
func validatedDriveConfig(cfg guesttools.VMConfig) guesttools.VMConfig {
return validatedDriveConfigForVolumes(cfg, shareableFixedDrives())
}
func validatedDriveConfigForVolumes(cfg guesttools.VMConfig, available []host.Drive) guesttools.VMConfig {
selected := make(map[string]bool, len(cfg.SharedDrives))
for _, raw := range cfg.SharedDrives {
@@ -82,6 +77,7 @@ func validatedDriveConfigForVolumes(cfg guesttools.VMConfig, available []host.Dr
}
cfg.SharedDrives = []string{}
cfg.DriveRoots = make(map[string]string)
cfg.VerifyDriveRoot = verifyDriveRoot
for _, drive := range available {
if drive.External || drive.VolumeGUID == "" {
continue
@@ -97,6 +93,22 @@ func validatedDriveConfigForVolumes(cfg guesttools.VMConfig, available []host.Dr
return cfg
}
func verifyDriveRoot(root *os.Root, path, guid string) error {
opened, err := root.Open(".")
if err != nil {
return err
}
defer opened.Close()
vol, err := host.ResolveOpenDirectoryVolume(path, opened)
if err != nil {
return err
}
if !vol.FixedInternal || !vol.IsVolumeRoot || !strings.EqualFold(vol.VolumeGUID, guid) {
return os.ErrPermission
}
return nil
}
func selectedVolumeIdentities(available []host.Drive, selected []string) map[string]string {
wanted := make(map[string]bool, len(selected))
for _, letter := range selected {
@@ -146,13 +158,19 @@ func (a *App) GetVMDriveShareSettings(name string) (DriveShareSettings, error) {
if err != nil {
return DriveShareSettings{}, err
}
cfg, _ := guesttools.ReadVMConfig(detail.Directory)
unlock := a.lockGuestToolsVM(name)
defer unlock()
cfg, _, err := guesttools.ReadVMConfigStrict(detail.Directory)
if err != nil {
return DriveShareSettings{}, err
}
return makeDriveShareSettings(cfg, shareableFixedDrives()), nil
}
// SetVMDriveShareSettings persists selected drive letters and applies access control immediately.
func (a *App) SetVMDriveShareSettings(name string, enabled bool, drives []string) (DriveShareSettings, error) {
detail, err := a.GetVMDetail(name)
epoch := a.vmDeleteEpoch(name)
detail, err := a.getVMDetail(name, epoch)
if err != nil {
return DriveShareSettings{}, err
}
@@ -168,6 +186,14 @@ func (a *App) SetVMDriveShareSettings(name string, enabled bool, drives []string
if err != nil {
return DriveShareSettings{}, err
}
unlock := a.lockGuestToolsVM(name)
defer unlock()
if a.vmDeleteEpoch(name) != epoch {
return DriveShareSettings{}, os.ErrNotExist
}
if err := requireGuestToolsVM(detail.Directory); err != nil {
return DriveShareSettings{}, err
}
cfg, err := guesttools.LoadOrCreateVMConfig(detail.Directory, name, a.vmSharedDir(name), port)
if err != nil {
return DriveShareSettings{}, err
@@ -178,8 +204,10 @@ func (a *App) SetVMDriveShareSettings(name string, enabled bool, drives []string
if err := guesttools.SaveVMConfig(detail.Directory, cfg); err != nil {
return DriveShareSettings{}, err
}
srv.RegisterVM(validatedDriveConfig(cfg))
a.emitLog(name, fmt.Sprintf("Read-only Windows drive sharing enabled=%v drives=%v", enabled, normalized))
if err := a.registerGuestToolsConfig(srv, detail.Directory, cfg); err != nil {
return DriveShareSettings{}, err
}
a.emitVMLog(name, fmt.Sprintf("Read-only Windows drive sharing enabled=%v drives=%v", enabled, normalized))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"sort"
"strings"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/macos/installer"
)
const vmNoteFileName = ".reims-go-note"
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/macos/reims"
)
func TestParseDiskSnapshotsJSON(t *testing.T) {
+389
View File
@@ -0,0 +1,389 @@
package app
import (
"crypto/rand"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"runtime"
"slices"
"strings"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
type SharedFolderInfo struct {
ID string `json:"id"`
Name string `json:"name"`
HostPath string `json:"host_path"`
Writable bool `json:"writable"`
Enabled bool `json:"enabled"`
Available bool `json:"available"`
Issue string `json:"issue,omitempty"`
}
type SharedFolderSettings struct {
RequiredAgentVersion int `json:"required_agent_version"`
Folders []SharedFolderInfo `json:"folders"`
}
var folderSlugSeparators = regexp.MustCompile(`[^a-z0-9_-]+`)
func newSharedFolderID(name string) string {
slug := strings.Trim(folderSlugSeparators.ReplaceAllString(strings.ToLower(name), "-"), "-_")
if slug == "" {
return "folder-" + strings.ToLower(rand.Text()[:8])
}
slug = strings.TrimRight(slug[:min(len(slug), 40)], "-_")
return slug + "-" + strings.ToLower(rand.Text()[:6])
}
func pathContains(parent, child string) bool {
parent = strings.ToLower(filepath.Clean(parent))
child = strings.ToLower(filepath.Clean(child))
return child == parent || strings.HasPrefix(child, strings.TrimRight(parent, string(os.PathSeparator))+string(os.PathSeparator))
}
func folderPathsOverlap(first, second string) bool {
return first != "" && second != "" && (pathContains(first, second) || pathContains(second, first))
}
func canonicalPolicyPath(path string) string {
if path == "" {
return ""
}
abs, err := filepath.Abs(path)
if err != nil {
return path
}
if runtime.GOOS == "windows" {
if volume, err := host.ResolveDirectoryVolume(abs); err == nil {
return volume.CanonicalPath
}
}
if resolved, err := filepath.EvalSymlinks(abs); err == nil {
return resolved
}
return abs
}
type folderPathPolicy struct {
dataRoot string
subtrees []string
roots []string
}
func (a *App) folderPolicy() folderPathPolicy {
a.mu.Lock()
dataRoot := a.cfg.DataRoot
a.mu.Unlock()
profile := os.Getenv("USERPROFILE")
systemDrive := os.Getenv("SystemDrive")
policy := folderPathPolicy{
dataRoot: canonicalPolicyPath(dataRoot),
subtrees: []string{os.Getenv("SystemRoot"), os.Getenv("ProgramFiles"), os.Getenv("ProgramFiles(x86)"),
os.Getenv("ProgramData"), os.Getenv("APPDATA"), os.Getenv("LOCALAPPDATA")},
roots: []string{profile},
}
if systemDrive != "" {
root := systemDrive + string(os.PathSeparator)
policy.subtrees = append(policy.subtrees, filepath.Join(root, "Program Files"),
filepath.Join(root, "Program Files (x86)"), filepath.Join(root, "ProgramData"))
policy.roots = append(policy.roots, filepath.Join(root, "Users"))
}
if profile != "" {
policy.subtrees = append(policy.subtrees, filepath.Join(profile, ".ssh"))
}
for i, path := range policy.subtrees {
policy.subtrees[i] = canonicalPolicyPath(path)
}
for i, path := range policy.roots {
policy.roots[i] = canonicalPolicyPath(path)
}
return policy
}
func (p folderPathPolicy) blocked(path string) bool {
if filepath.Dir(path) == path || folderPathsOverlap(p.dataRoot, path) {
return true
}
for _, tree := range p.subtrees {
if folderPathsOverlap(tree, path) {
return true
}
}
for _, root := range p.roots {
if root != "" && pathContains(path, root) {
return true
}
}
return false
}
func (a *App) directoryVolume(path string) (host.DirectoryVolume, error) {
if path == "" || strings.HasPrefix(strings.ReplaceAll(path, `\`, "/"), "//") {
return host.DirectoryVolume{}, os.ErrInvalid
}
if a.resolveFolderVolume != nil {
return a.resolveFolderVolume(path)
}
return host.ResolveDirectoryVolume(path)
}
func folderVolumeIssue(policy folderPathPolicy, vol host.DirectoryVolume, err error) string {
if errors.Is(err, os.ErrNotExist) {
return "missing"
}
if err != nil || !vol.FixedInternal || vol.IsVolumeRoot || (runtime.GOOS == "windows" && vol.VolumeGUID == "") ||
policy.blocked(vol.CanonicalPath) {
return "blocked"
}
return ""
}
func (a *App) resolveSharedFolders(cfg guesttools.VMConfig, policy folderPathPolicy) (SharedFolderSettings, []guesttools.ResolvedSharedFolder) {
settings := SharedFolderSettings{
RequiredAgentVersion: guesttools.SharedFolderAgentVersion,
Folders: make([]SharedFolderInfo, len(cfg.SharedFolders)),
}
if len(cfg.SharedFolders) == 0 {
return settings, nil
}
sharedDir := canonicalPolicyPath(cfg.SharedDir)
volumes := make([]host.DirectoryVolume, len(cfg.SharedFolders))
paths := make([]string, len(cfg.SharedFolders))
ids := make(map[string]int, len(cfg.SharedFolders))
names := make(map[string]int, len(cfg.SharedFolders))
for i, folder := range cfg.SharedFolders {
id, validID := guesttools.NormalizeFolderID(folder.ID)
name := guesttools.SanitizeFolderName(folder.Name)
info := SharedFolderInfo{
ID: id, Name: name, HostPath: folder.HostPath, Writable: folder.Writable, Enabled: folder.Enabled,
}
vol, err := a.directoryVolume(folder.HostPath)
volumes[i] = vol
paths[i] = vol.CanonicalPath
if paths[i] == "" {
paths[i] = folder.HostPath
}
info.Issue = folderVolumeIssue(policy, vol, err)
if err == nil {
switch {
case !strings.EqualFold(folder.VolumeGUID, vol.VolumeGUID):
info.Issue = "volume_mismatch"
case vol.CanonicalPath != folder.HostPath:
info.Issue = "path_changed"
paths[i] = folder.HostPath
}
}
if !validID || name == "" {
info.Issue = "blocked"
}
settings.Folders[i] = info
ids[id]++
names[strings.ToLower(name)]++
}
var resolved []guesttools.ResolvedSharedFolder
for i := range settings.Folders {
info := &settings.Folders[i]
if info.Issue == "" {
if folderPathsOverlap(paths[i], sharedDir) || ids[info.ID] > 1 || names[strings.ToLower(info.Name)] > 1 {
info.Issue = "overlap"
}
for j, other := range paths {
if i != j && folderPathsOverlap(paths[i], other) {
info.Issue = "overlap"
break
}
}
}
info.Available = info.Issue == ""
if info.Available && info.Enabled {
resolved = append(resolved, guesttools.ResolvedSharedFolder{
ID: info.ID, Name: info.Name, RootPath: volumes[i].CanonicalPath,
VolumeGUID: volumes[i].VolumeGUID, Writable: info.Writable,
})
}
}
return settings, resolved
}
func (a *App) validatedShareConfig(cfg guesttools.VMConfig) (guesttools.VMConfig, SharedFolderSettings) {
cfg = validatedDriveConfigForVolumes(cfg, shareableFixedDrives())
if cfg.SharedDir == "" {
cfg.SharedDir = a.vmSharedDir(cfg.VMName)
}
if len(cfg.SharedFolders) == 0 {
cfg.ResolvedFolders = nil
cfg.VerifyFolderRoot = nil
return cfg, SharedFolderSettings{
RequiredAgentVersion: guesttools.SharedFolderAgentVersion, Folders: []SharedFolderInfo{},
}
}
policy := a.folderPolicy()
settings, resolved := a.resolveSharedFolders(cfg, policy)
cfg.ResolvedFolders = resolved
cfg.VerifyFolderRoot = func(root *os.Root, folder guesttools.ResolvedSharedFolder) error {
opened, err := root.Open(".")
if err != nil {
return err
}
defer opened.Close()
vol, err := host.ResolveOpenDirectoryVolume(folder.RootPath, opened)
if err != nil {
return err
}
if folderVolumeIssue(policy, vol, nil) != "" || !strings.EqualFold(vol.VolumeGUID, folder.VolumeGUID) ||
vol.CanonicalPath != folder.RootPath {
return os.ErrPermission
}
return nil
}
return cfg, settings
}
func (a *App) GetVMSharedFolderSettings(name string) (SharedFolderSettings, error) {
detail, err := a.GetVMDetail(name)
if err != nil {
return SharedFolderSettings{}, err
}
unlock := a.lockGuestToolsVM(name)
defer unlock()
cfg, _, err := guesttools.ReadVMConfigStrict(detail.Directory)
if err != nil {
return SharedFolderSettings{}, fmt.Errorf("shared folder: corrupt_config")
}
if cfg.SharedDir == "" {
cfg.SharedDir = a.vmSharedDir(name)
}
settings, _ := a.resolveSharedFolders(cfg, a.folderPolicy())
return settings, nil
}
func (a *App) AddVMSharedFolder(name, hostPath string) (SharedFolderSettings, error) {
epoch := a.vmDeleteEpoch(name)
detail, err := a.getVMDetail(name, epoch)
if err != nil {
return SharedFolderSettings{}, err
}
return a.changeVMSharedFolder(detail.Name, detail.Directory, "", "add", hostPath, epoch)
}
func (a *App) SetVMSharedFolderMode(name, folderID, mode string) (SharedFolderSettings, error) {
if mode != "disabled" && mode != "ro" && mode != "rw" {
return SharedFolderSettings{}, fmt.Errorf("shared folder: invalid_mode")
}
epoch := a.vmDeleteEpoch(name)
detail, err := a.getVMDetail(name, epoch)
if err != nil {
return SharedFolderSettings{}, err
}
return a.changeVMSharedFolder(detail.Name, detail.Directory, folderID, mode, "", epoch)
}
func (a *App) RemoveVMSharedFolder(name, folderID string) (SharedFolderSettings, error) {
epoch := a.vmDeleteEpoch(name)
detail, err := a.getVMDetail(name, epoch)
if err != nil {
return SharedFolderSettings{}, err
}
return a.changeVMSharedFolder(detail.Name, detail.Directory, folderID, "remove", "", epoch)
}
func (a *App) changeVMSharedFolder(vmName, vmDir, folderID, action, hostPath string, epoch uint64) (SharedFolderSettings, error) {
if vmDir == "" {
return SharedFolderSettings{}, fmt.Errorf("VM %s has no directory", vmName)
}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
return SharedFolderSettings{}, err
}
unlock := a.lockGuestToolsVM(vmName)
defer unlock()
if a.vmDeleteEpoch(vmName) != epoch {
return SharedFolderSettings{}, os.ErrNotExist
}
if err := requireGuestToolsVM(vmDir); err != nil {
return SharedFolderSettings{}, err
}
cfg, configured, err := guesttools.ReadVMConfigStrict(vmDir)
if err != nil {
return SharedFolderSettings{}, fmt.Errorf("shared folder: corrupt_config")
}
cfg.VMName, cfg.Port = vmName, port
if cfg.SharedDir == "" {
cfg.SharedDir = a.vmSharedDir(vmName)
}
id, validID := guesttools.NormalizeFolderID(folderID)
index := slices.IndexFunc(cfg.SharedFolders, func(folder guesttools.SharedFolderConfig) bool {
return strings.EqualFold(folder.ID, id)
})
logMode := action
switch action {
case "add":
volume, err := a.directoryVolume(hostPath)
if issue := folderVolumeIssue(a.folderPolicy(), volume, err); issue != "" {
return SharedFolderSettings{}, fmt.Errorf("shared folder: %s", issue)
}
names := make(map[string]bool, len(cfg.SharedFolders))
ids := make(map[string]bool, len(cfg.SharedFolders))
for _, folder := range cfg.SharedFolders {
names[strings.ToLower(guesttools.SanitizeFolderName(folder.Name))] = true
ids[strings.ToLower(folder.ID)] = true
}
baseName := filepath.Base(volume.CanonicalPath)
for id = newSharedFolderID(baseName); ids[id]; {
id = newSharedFolderID(baseName)
}
base := guesttools.SanitizeFolderName(baseName)
if base == "" {
base = id
}
display := base
for n := 2; names[strings.ToLower(display)]; n++ {
display = fmt.Sprintf("%s (%d)", base, n)
}
index = len(cfg.SharedFolders)
cfg.SharedFolders = append(cfg.SharedFolders, guesttools.SharedFolderConfig{
ID: id, Name: display, HostPath: volume.CanonicalPath, Enabled: true, VolumeGUID: volume.VolumeGUID,
})
logMode = "ro"
case "remove", "disabled", "ro", "rw":
if !validID || index < 0 {
return SharedFolderSettings{}, fmt.Errorf("shared folder: not_found")
}
if action == "remove" {
cfg.SharedFolders = slices.Delete(cfg.SharedFolders, index, index+1)
logMode = "disabled"
} else {
cfg.SharedFolders[index].Enabled = action != "disabled"
cfg.SharedFolders[index].Writable = action == "rw"
}
}
validated, settings := a.validatedShareConfig(cfg)
if (logMode == "ro" || logMode == "rw") && !settings.Folders[index].Available {
return SharedFolderSettings{}, fmt.Errorf("shared folder: %s", settings.Folders[index].Issue)
}
if !configured {
initial, err := guesttools.LoadOrCreateVMConfig(vmDir, vmName, cfg.SharedDir, port)
if err != nil {
return SharedFolderSettings{}, err
}
cfg.Token, cfg.PreventSleep = initial.Token, initial.PreventSleep
validated.Token, validated.PreventSleep = cfg.Token, cfg.PreventSleep
}
if err := guesttools.SaveVMConfig(vmDir, cfg); err != nil {
return SharedFolderSettings{}, err
}
srv.RegisterVM(validated)
a.emitVMLog(vmName, fmt.Sprintf("Shared folder id=%s mode=%s count=%d", id, logMode, len(cfg.SharedFolders)))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return settings, nil
}
+476
View File
@@ -0,0 +1,476 @@
package app
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
)
func folderTestDir(t *testing.T, parts ...string) string {
t.Helper()
path := filepath.Join(parts...)
if err := os.MkdirAll(path, 0o755); err != nil {
t.Fatal(err)
}
return path
}
func folderTestVM(t *testing.T, root string) reims.VMDetail {
t.Helper()
dir := folderTestDir(t, root, "vm")
if err := os.WriteFile(filepath.Join(dir, "vm.toml"), nil, 0o600); err != nil {
t.Fatal(err)
}
return reims.VMDetail{Name: "mac", Directory: dir}
}
func TestSharedFolderChangesAndVolumeDrift(t *testing.T) {
t.Setenv("LOCALAPPDATA", "")
tmp := t.TempDir()
root := folderTestDir(t, tmp, "data")
vm := folderTestVM(t, root)
work := folderTestDir(t, tmp, "private", "Work")
second := folderTestDir(t, tmp, "other", "work")
guid := "original"
canonical := work
srv := guesttools.NewTransportServer(nil)
t.Cleanup(func() { srv.Close(context.Background()) })
a := &App{cfg: &config.Config{DataRoot: root}, guestTools: srv}
a.resolveFolderVolume = func(path string) (host.DirectoryVolume, error) {
if path == work {
return host.DirectoryVolume{CanonicalPath: canonical, VolumeGUID: guid, FixedInternal: true}, nil
}
resolved, err := filepath.EvalSymlinks(path)
return host.DirectoryVolume{CanonicalPath: resolved, VolumeGUID: guid, FixedInternal: true}, err
}
change := func(id, action, path string) SharedFolderSettings {
t.Helper()
settings, err := a.changeVMSharedFolder(vm.Name, vm.Directory, id, action, path, a.vmDeleteEpoch(vm.Name))
if err != nil {
t.Fatal(err)
}
return settings
}
list := func() string {
t.Helper()
cfg, ok := guesttools.ReadVMConfig(vm.Directory)
if !ok {
t.Fatal("missing persisted config")
}
req, err := http.NewRequest("GET", fmt.Sprintf("http://127.0.0.1:%d/v1/folders", srv.Port()), nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+cfg.Token)
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil || res.StatusCode != http.StatusOK {
t.Fatalf("list folders: %s %s %v", res.Status, body, err)
}
return string(body)
}
settings := change("", "add", work)
info := settings.Folders[0]
if settings.RequiredAgentVersion != guesttools.SharedFolderAgentVersion || !info.Available || !info.Enabled ||
info.Writable || !strings.EqualFold(info.HostPath, work) || !strings.HasPrefix(list(), info.ID+"|ro|") {
t.Fatalf("initial settings: %+v", settings)
}
if !strings.HasPrefix(info.ID, "work-") {
t.Fatalf("missing readable directory prefix: %q", info.ID)
}
settings = change("", "add", second)
secondInfo := settings.Folders[1]
if strings.EqualFold(secondInfo.Name, info.Name) || secondInfo.ID == info.ID {
t.Fatalf("duplicate names or IDs: %+v", settings)
}
if _, err := a.changeVMSharedFolder(vm.Name, vm.Directory, "", "add", work, a.vmDeleteEpoch(vm.Name)); err == nil || !strings.Contains(err.Error(), "overlap") {
t.Fatalf("duplicate path: %v", err)
}
if _, err := a.changeVMSharedFolder(vm.Name, vm.Directory, "", "add", filepath.Dir(work), a.vmDeleteEpoch(vm.Name)); err == nil || !strings.Contains(err.Error(), "overlap") {
t.Fatalf("overlapping parent: %v", err)
}
if _, err := a.changeVMSharedFolder(vm.Name, vm.Directory, "", "add", folderTestDir(t, work, "child"), a.vmDeleteEpoch(vm.Name)); err == nil || !strings.Contains(err.Error(), "overlap") {
t.Fatalf("overlapping child: %v", err)
}
if got := change(info.ID, "rw", "").Folders[0]; !got.Writable || !strings.Contains(list(), info.ID+"|rw|") {
t.Fatalf("read-write mode: %+v", got)
}
guid = "replacement"
// Refresh the real registration path used by GetVMDetail.
a.populateGuestToolsDetail(&vm, a.vmDeleteEpoch(vm.Name))
cfg, _ := guesttools.ReadVMConfig(vm.Directory)
settings, _ = a.resolveSharedFolders(cfg, a.folderPolicy())
if got := settings.Folders[0]; got.Issue != "volume_mismatch" || got.Available || !got.Enabled ||
cfg.SharedFolders[0].VolumeGUID != "original" || list() != "" {
t.Fatalf("volume drift: %+v", got)
}
guid = "original"
canonical = second
a.populateGuestToolsDetail(&vm, a.vmDeleteEpoch(vm.Name))
cfg, _ = guesttools.ReadVMConfig(vm.Directory)
settings, _ = a.resolveSharedFolders(cfg, a.folderPolicy())
if got := settings.Folders[0]; got.Issue != "path_changed" || got.Available || !got.Enabled ||
!got.Writable || cfg.SharedFolders[0].HostPath != info.HostPath || !strings.HasPrefix(list(), secondInfo.ID+"|ro|") {
t.Fatalf("same-volume path drift: %+v", got)
}
canonical = filepath.Join(filepath.Dir(work), "work")
a.populateGuestToolsDetail(&vm, a.vmDeleteEpoch(vm.Name))
settings, _ = a.resolveSharedFolders(cfg, a.folderPolicy())
if got := settings.Folders[0]; got.Issue != "path_changed" || got.Available || strings.Contains(list(), info.ID+"|") {
t.Fatalf("case-only path drift: %+v", got)
}
canonical = work
if got := change(info.ID, "disabled", "").Folders[0]; got.Enabled || !got.Available || strings.Contains(list(), info.ID+"|") {
t.Fatalf("disabled mode: %+v", got)
}
if got := change(info.ID, "ro", "").Folders[0]; !got.Enabled || got.Writable || !strings.Contains(list(), info.ID+"|ro|") {
t.Fatalf("read-only mode: %+v", got)
}
if got := change(info.ID, "remove", ""); len(got.Folders) != 1 || strings.Contains(list(), info.ID+"|") {
t.Fatalf("removed folder: %+v", got)
}
if _, err := os.Stat(work); err != nil {
t.Fatal(err)
}
if got := change("", "add", work).Folders[1]; got.ID == info.ID {
t.Fatalf("recreating a share reused its ID: %q", got.ID)
}
for _, line := range a.recentLogs {
if strings.Contains(strings.ToLower(line), strings.ToLower(work)) ||
strings.Contains(strings.ToLower(line), strings.ToLower(second)) {
t.Fatalf("host path in log: %s", line)
}
}
}
func TestSharedFolderPathPolicy(t *testing.T) {
base := t.TempDir()
root := folderTestDir(t, base, "app", "data")
win := folderTestDir(t, base, "Windows")
programs := folderTestDir(t, base, "Program Files")
profile := folderTestDir(t, base, "Users", "Rei")
appData := folderTestDir(t, profile, "AppData", "Roaming")
localAppData := folderTestDir(t, profile, "AppData", "Local")
t.Setenv("USERPROFILE", profile)
t.Setenv("SystemRoot", win)
t.Setenv("ProgramFiles", programs)
t.Setenv("APPDATA", appData)
t.Setenv("LOCALAPPDATA", localAppData)
a := &App{cfg: &config.Config{DataRoot: root}}
policy := a.folderPolicy()
for _, path := range []string{root, filepath.Dir(root), filepath.Join(root, "child"),
filepath.Join(win, "System32"), filepath.Join(programs, "child"),
appData, filepath.Dir(appData), filepath.Join(localAppData, "child"), filepath.Join(profile, ".ssh", "keys"),
profile, filepath.Dir(profile), filepath.VolumeName(base) + string(os.PathSeparator)} {
if !policy.blocked(path) {
t.Errorf("allowed blocked path %q", path)
}
}
for _, path := range []string{filepath.Join(profile, "Documents"), filepath.Join(base, "Windows Projects"),
filepath.Join(filepath.Dir(root), "data-sibling")} {
if policy.blocked(path) {
t.Errorf("blocked valid path %q", path)
}
}
for _, path := range []string{`\\host\share`, "//host/share", `\\?\C:\dir`, `\\.\C:\dir`} {
if _, err := a.directoryVolume(path); err == nil {
t.Errorf("accepted %q", path)
}
}
volume := host.DirectoryVolume{CanonicalPath: filepath.Join(profile, "Documents"), VolumeGUID: "id"}
if issue := folderVolumeIssue(policy, volume, nil); issue != "blocked" {
t.Fatalf("external volume: %s", issue)
}
volume.FixedInternal = true
volume.IsVolumeRoot = true
if issue := folderVolumeIssue(policy, volume, nil); issue != "blocked" {
t.Fatalf("allowed a volume mounted at a directory: %q", issue)
}
shared := folderTestDir(t, base, "shared")
a.resolveFolderVolume = func(path string) (host.DirectoryVolume, error) {
return host.DirectoryVolume{CanonicalPath: path, VolumeGUID: "id", FixedInternal: true}, nil
}
for _, path := range []string{shared, strings.ToUpper(filepath.Join(shared, "child")), filepath.Dir(shared)} {
settings, resolved := a.resolveSharedFolders(guesttools.VMConfig{
SharedDir: shared, SharedFolders: []guesttools.SharedFolderConfig{
{ID: "test", Name: "Test", HostPath: path, VolumeGUID: "id", Enabled: true},
},
}, folderPathPolicy{})
if settings.Folders[0].Issue != "overlap" || len(resolved) != 0 {
t.Fatalf("allowed overlap with default folder: %+v", settings)
}
}
}
func TestSharedFolderConcurrentSaveAndRefresh(t *testing.T) {
t.Setenv("LOCALAPPDATA", "")
tmp := t.TempDir()
root := folderTestDir(t, tmp, "data")
vm := folderTestVM(t, root)
srv := guesttools.NewTransportServer(nil)
t.Cleanup(func() { srv.Close(context.Background()) })
a := &App{cfg: &config.Config{DataRoot: root}, guestTools: srv}
a.resolveFolderVolume = func(path string) (host.DirectoryVolume, error) {
return host.DirectoryVolume{CanonicalPath: path, VolumeGUID: "id", FixedInternal: true}, nil
}
const n = 8
var wg sync.WaitGroup
start := make(chan struct{})
_, port, err := a.ensureGuestToolsBridge()
if err != nil {
t.Fatal(err)
}
for i := range n {
path := folderTestDir(t, tmp, fmt.Sprintf("work-%d", i))
wg.Go(func() {
<-start
if _, err := a.changeVMSharedFolder(vm.Name, vm.Directory, "", "add", path, a.vmDeleteEpoch(vm.Name)); err != nil {
t.Error(err)
}
})
wg.Go(func() {
<-start
detail := vm
epoch := a.vmDeleteEpoch(vm.Name)
a.populateGuestToolsDetail(&detail, epoch)
a.registerSavedGuestToolsConfig(srv, port, vm.Name, vm.Directory, epoch)
})
}
close(start)
wg.Wait()
cfg, ok := guesttools.ReadVMConfig(vm.Directory)
if !ok || len(cfg.SharedFolders) != n {
t.Fatalf("persisted %d folders, want %d", len(cfg.SharedFolders), n)
}
req, err := http.NewRequest("GET", fmt.Sprintf("http://127.0.0.1:%d/v1/folders", port), nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+cfg.Token)
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil || res.StatusCode != http.StatusOK || strings.Count(string(body), "\n") != n {
t.Fatalf("published folders: %s %q %v", res.Status, body, err)
}
}
func TestSharedFolderIDUsesASCIISlug(t *testing.T) {
for name, prefix := range map[string]string{
"__My 工作 Files-": "my-files-",
strings.Repeat("X", 50): strings.Repeat("x", 40) + "-",
"共享文件夹": "folder-",
} {
id := newSharedFolderID(name)
suffixLength := 6
if prefix == "folder-" {
suffixLength = 8
}
if normalized, valid := guesttools.NormalizeFolderID(id); !valid || normalized != id ||
!strings.HasPrefix(id, prefix) || len(id) != len(prefix)+suffixLength {
t.Errorf("invalid ID for %q: %q", name, id)
}
}
}
func TestSharedFolderCorruptConfigAndModeErrors(t *testing.T) {
root := t.TempDir()
vm := folderTestVM(t, root)
srv := guesttools.NewTransportServer(nil)
t.Cleanup(func() { srv.Close(context.Background()) })
a := &App{cfg: &config.Config{DataRoot: root}, guestTools: srv}
if _, err := a.SetVMSharedFolderMode(vm.Name, "absent", "invalid"); err == nil || err.Error() != "shared folder: invalid_mode" {
t.Fatalf("invalid mode: %v", err)
}
if _, err := a.changeVMSharedFolder(vm.Name, vm.Directory, "absent", "remove", "", a.vmDeleteEpoch(vm.Name)); err == nil || err.Error() != "shared folder: not_found" {
t.Fatalf("missing folder: %v", err)
}
path := filepath.Join(vm.Directory, guesttools.ConfigFileName)
const broken = "{bad JSON"
if err := os.WriteFile(path, []byte(broken), 0o600); err != nil {
t.Fatal(err)
}
if _, err := a.changeVMSharedFolder(vm.Name, vm.Directory, "", "add", root, a.vmDeleteEpoch(vm.Name)); err == nil || err.Error() != "shared folder: corrupt_config" {
t.Fatalf("corrupt config: %v", err)
}
if contents, err := os.ReadFile(path); err != nil || string(contents) != broken {
t.Fatalf("corrupt config was replaced: %q, %v", contents, err)
}
}
func TestDeletedVMConfigCannotBeSavedOrRegistered(t *testing.T) {
for _, keepFiles := range []bool{false, true} {
t.Run(fmt.Sprintf("keep_files_%v", keepFiles), func(t *testing.T) {
root := t.TempDir()
vm := folderTestVM(t, root)
a := &App{cfg: &config.Config{DataRoot: root}}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { srv.Close(context.Background()) })
epoch := a.vmDeleteEpoch("MAC")
cfg, err := a.loadAndRegisterGuestTools(srv, port, vm.Directory, vm.Name, epoch)
if err != nil {
t.Fatal(err)
}
assertStatus := func(want int) {
t.Helper()
req, err := http.NewRequest("GET", fmt.Sprintf("http://127.0.0.1:%d/v1/config", port), nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+cfg.Token)
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != want {
t.Fatalf("VM config endpoint returned %s, want %d", res.Status, want)
}
}
assertStatus(http.StatusOK)
configPath := filepath.Join(vm.Directory, guesttools.ConfigFileName)
before, err := os.ReadFile(configPath)
if err != nil {
t.Fatal(err)
}
share := folderTestDir(t, root, "work")
a.resolveFolderVolume = func(path string) (host.DirectoryVolume, error) {
return host.DirectoryVolume{CanonicalPath: path, VolumeGUID: "id", FixedInternal: true}, nil
}
var wg sync.WaitGroup
removed, err := a.deleteVMWithGuestTools(vm.Name, func() error {
wg.Go(func() {
a.registerSavedGuestToolsConfig(srv, port+1, vm.Name, vm.Directory, epoch)
detail := vm
a.populateGuestToolsDetail(&detail, epoch)
if keepFiles && detail.GuestToolsConfigured {
t.Error("stale detail loaded kept Guest Tools config")
}
})
wg.Go(func() {
if _, err := a.loadAndRegisterGuestTools(srv, port, vm.Directory, vm.Name, epoch); !errors.Is(err, os.ErrNotExist) {
t.Errorf("save after deletion: %v", err)
}
})
wg.Go(func() {
if _, err := a.changeVMSharedFolder(vm.Name, vm.Directory, "", "add", share, epoch); !errors.Is(err, os.ErrNotExist) {
t.Errorf("folder change after deletion: %v", err)
}
})
if keepFiles {
return nil
}
return os.Rename(vm.Directory, filepath.Join(root, "deleted"))
}, nil)
wg.Wait()
if err != nil || !removed {
t.Fatalf("deletion removed=%v: %v", removed, err)
}
if keepFiles {
if _, err := os.Stat(filepath.Join(vm.Directory, "vm.toml")); err != nil {
t.Fatalf("kept vm.toml: %v", err)
}
after, err := os.ReadFile(configPath)
if err != nil || !bytes.Equal(before, after) {
t.Fatalf("kept Guest Tools config changed: %v", err)
}
} else {
if _, err := os.Stat(vm.Directory); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("deleted VM directory reappeared: %v", err)
}
}
assertStatus(http.StatusUnauthorized)
})
}
}
func TestDeleteBrokenVMUnregistersGuestTools(t *testing.T) {
for _, corrupt := range []bool{false, true} {
t.Run(fmt.Sprintf("corrupt_toml_%v", corrupt), func(t *testing.T) {
root := t.TempDir()
if corrupt {
if err := os.WriteFile(filepath.Join(root, "vm.toml"), []byte("[broken"), 0o600); err != nil {
t.Fatal(err)
}
}
const name, token = "broken", "broken-token"
a := &App{
cfg: &config.Config{DataRoot: root},
transitions: map[string]string{name: "stopping"},
}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { srv.Close(context.Background()) })
srv.RegisterVM(guesttools.VMConfig{VMName: name, Token: token})
assertStatus := func(want int) {
t.Helper()
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/v1/config", port), nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+token)
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != want {
t.Fatalf("VM config endpoint returned %d, want %d", res.StatusCode, want)
}
}
assertStatus(http.StatusOK)
deleteErr := errors.New("disk cleanup failed")
if removed, err := a.deleteVMWithGuestTools(name, func() error {
return deleteErr
}, func() (bool, error) {
return true, nil
}); removed || !errors.Is(err, deleteErr) {
t.Fatalf("failed deletion: removed=%v err=%v", removed, err)
}
assertStatus(http.StatusOK)
if a.vmDeleteEpoch(name) != 0 {
t.Fatal("failed deletion advanced the epoch")
}
var wantErr error
if corrupt {
wantErr = deleteErr
}
called := false
removed, err := a.deleteVMWithGuestTools(name, func() error {
called = true
return wantErr
}, func() (bool, error) { return false, nil })
if !removed || !called || !errors.Is(err, wantErr) || a.vmDeleteEpoch("BROKEN") != 1 {
t.Fatalf("broken VM deletion removed=%v called=%v, error=%v, epoch=%d", removed, called, err, a.vmDeleteEpoch(name))
}
assertStatus(http.StatusUnauthorized)
})
}
}
+162 -45
View File
@@ -8,17 +8,64 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
func (a *App) lockGuestToolsVM(name string) func() {
entry, _ := a.guestToolsConfigLocks.LoadOrStore(strings.ToLower(name), &sync.Mutex{})
mu := entry.(*sync.Mutex)
mu.Lock()
return mu.Unlock
}
func (a *App) vmDeleteEpoch(name string) uint64 {
a.mu.Lock()
defer a.mu.Unlock()
return a.vmDeleteEpochs[strings.ToLower(name)]
}
func requireGuestToolsVM(vmDir string) error {
// reims-ctl can leave the directory and disks behind when deleting a VM.
_, err := os.Stat(filepath.Join(vmDir, "vm.toml"))
return err
}
// Call with the VM's config lock held.
func (a *App) registerGuestToolsConfig(srv *guesttools.Server, vmDir string, cfg guesttools.VMConfig) error {
if err := requireGuestToolsVM(vmDir); err != nil {
return err
}
validated, _ := a.validatedShareConfig(cfg)
srv.RegisterVM(validated)
return nil
}
func (a *App) loadAndRegisterGuestTools(srv *guesttools.Server, port int, vmDir, name string, epoch uint64) (guesttools.VMConfig, error) {
unlock := a.lockGuestToolsVM(name)
defer unlock()
if a.vmDeleteEpoch(name) != epoch {
return guesttools.VMConfig{}, os.ErrNotExist
}
if err := requireGuestToolsVM(vmDir); err != nil {
return guesttools.VMConfig{}, err
}
cfg, err := guesttools.LoadOrCreateVMConfig(vmDir, name, a.vmSharedDir(name), port)
if err == nil {
err = a.registerGuestToolsConfig(srv, vmDir, cfg)
}
return cfg, err
}
func (a *App) vmSharedDir(name string) string {
a.mu.Lock()
dir := filepath.Join(a.cfg.SharedDir(), name)
@@ -33,6 +80,20 @@ func (a *App) guestToolsImagePath(name string) string {
return filepath.Join(cacheDir, "reims-go", "guest-tools", name+"-tools.img")
}
// buildGuestToolsImage runs in the macOS driver after all start hooks pass.
func (a *App) buildGuestToolsImage(vmName, vmDir string) error {
_, port, _, err := a.startGuestToolsServer()
if err != nil {
return err
}
cfg, err := guesttools.LoadOrCreateVMConfig(vmDir, vmName, a.vmSharedDir(vmName), port)
if err != nil {
return err
}
cfg, _ = a.validatedShareConfig(cfg)
return guesttools.BuildToolsDiskImage(a.guestToolsImagePath(vmName), cfg)
}
// startGuestToolsServer starts the shared localhost HTTP bridge once. Only the
// Guest Tools plugin and the no-plugin-manager fallback may call it; created
// reports whether this call made a new server.
@@ -45,16 +106,17 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created
} else {
srv = guesttools.NewServer(nil)
}
srv.SetHostTextHandler(func(vmName, text string) {
srv.SetHostTextHandler(func(vmKey, vmName, text string) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr != nil && !mgr.Registry().IsActive(builtin.IDInput) {
return
}
a.injectRemoteText(vmName, "", text)
a.injectRemoteTextRef(vmKey, vmName, "", text)
})
a.guestTools = srv
srv.SetStatusChangeHandler(func(string) { a.syncKeymapRules() })
created = true
}
a.mu.Unlock()
@@ -97,7 +159,7 @@ func (a *App) guestToolsEnabled() bool {
// inputBridgeEnv returns REIMS_GO_INPUT_URL and REIMS_GO_INPUT_TOKEN env vars
// for the VM's QEMU/reims-vgpu-window child process so direct WM_CHAR / IME
// commits can forward to reims-go's local text router.
func (a *App) inputBridgeEnv(name, vmDir string) []string {
func (a *App) inputBridgeEnv(name, vmDir string, epoch uint64) []string {
if vmDir == "" {
return nil
}
@@ -105,11 +167,12 @@ func (a *App) inputBridgeEnv(name, vmDir string) []string {
if err != nil || port <= 0 {
return nil
}
cfg, err := guesttools.LoadOrCreateVMConfig(vmDir, name, a.vmSharedDir(name), port)
cfg, err := a.loadAndRegisterGuestTools(srv, port, vmDir, name, epoch)
if err != nil || cfg.Token == "" {
return nil
}
srv.RegisterVM(validatedDriveConfig(cfg))
srv.SetKeymapCarrier(name, false)
a.syncKeymapRules()
return []string{
fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port),
"REIMS_GO_INPUT_TOKEN=" + cfg.Token,
@@ -128,6 +191,7 @@ func (a *App) registerExistingGuestTools(ctx context.Context) {
// guest agent that is already running reconnects after reims-go restarts or
// the Guest Tools plugin is switched back on.
func (a *App) registerVMsWithBridge(ctx context.Context, srv *guesttools.Server, port int) {
defer a.syncKeymapRules()
c, err := a.client()
if err != nil {
return
@@ -137,38 +201,78 @@ func (a *App) registerVMsWithBridge(ctx context.Context, srv *guesttools.Server,
return
}
for _, vm := range vms {
epoch := a.vmDeleteEpoch(vm.Name)
det, err := c.Show(ctx, vm.Name)
if err != nil || det.Directory == "" {
continue
}
if cfg, ok := guesttools.ReadVMConfig(det.Directory); ok {
if cfg.SharedDir == "" {
cfg.SharedDir = a.vmSharedDir(vm.Name)
}
if cfg.Port != port {
cfg.Port = port
_ = guesttools.SaveVMConfig(det.Directory, cfg)
}
srv.RegisterVM(validatedDriveConfig(cfg))
}
a.registerSavedGuestToolsConfig(srv, port, vm.Name, det.Directory, epoch)
}
}
func (a *App) populateGuestToolsDetail(d *reims.VMDetail) {
func (a *App) registerSavedGuestToolsConfig(srv *guesttools.Server, port int, name, vmDir string, epoch uint64) {
unlock := a.lockGuestToolsVM(name)
defer unlock()
if a.vmDeleteEpoch(name) != epoch {
return
}
if err := requireGuestToolsVM(vmDir); err != nil {
a.emitLog(name, "Warning: could not register Guest Tools config: "+err.Error())
return
}
cfg, ok, err := guesttools.ReadVMConfigStrict(vmDir)
if err != nil {
a.emitLog(name, "Warning: could not load Guest Tools config: "+err.Error())
return
}
if !ok {
return
}
cfg.VMName = name
if cfg.SharedDir == "" {
cfg.SharedDir = a.vmSharedDir(name)
}
if cfg.Port != port {
cfg.Port = port
if err := guesttools.SaveVMConfig(vmDir, cfg); err != nil {
a.emitLog(name, "Warning: could not save Guest Tools config: "+err.Error())
return
}
}
if err := a.registerGuestToolsConfig(srv, vmDir, cfg); err != nil {
a.emitLog(name, "Warning: could not register Guest Tools config: "+err.Error())
}
}
func (a *App) populateGuestToolsDetail(d *reims.VMDetail, epoch uint64) {
if d == nil || d.Name == "" {
return
}
d.GuestToolsAttached = reims.HasGuestToolsArgs(d.ExtraArgs)
d.GuestToolsDisabled = !a.guestToolsEnabled()
d.SharedDir = a.vmSharedDir(d.Name)
if cfg, ok := guesttools.ReadVMConfig(d.Directory); ok {
unlock := a.lockGuestToolsVM(d.Name)
defer unlock()
if a.vmDeleteEpoch(d.Name) != epoch {
return
}
cfg, ok, err := guesttools.ReadVMConfigStrict(d.Directory)
if err != nil {
a.emitLog(d.Name, "Warning: could not load Guest Tools config: "+err.Error())
return
}
if ok {
cfg.VMName = d.Name
d.GuestToolsConfigured = true
d.GuestToolsPreventSleep = cfg.PreventSleep
if cfg.SharedDir != "" {
d.SharedDir = cfg.SharedDir
}
if srv, _, err := a.ensureGuestToolsBridge(); err == nil {
srv.RegisterVM(validatedDriveConfig(cfg))
if err := a.registerGuestToolsConfig(srv, d.Directory, cfg); err != nil {
a.emitLog(d.Name, "Warning: could not register Guest Tools config: "+err.Error())
return
}
st := srv.Status(d.Name, 15*time.Second)
d.GuestToolsConnected = st.Connected
d.GuestToolsMountMode = st.MountMode
@@ -180,33 +284,37 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail) {
// syncGuestTools ensures the host HTTP bridge is running and refreshes the
// REIMSTOOLS HFS+ image before VM start when Guest Tools is configured or attached.
func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail) {
func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail, epoch uint64) {
if cur.Directory == "" {
return
}
attached := reims.HasGuestToolsArgs(cur.ExtraArgs)
cfg, configured := guesttools.ReadVMConfig(cur.Directory)
unlock := a.lockGuestToolsVM(name)
_, configured, err := guesttools.ReadVMConfigStrict(cur.Directory)
unlock()
if err != nil {
a.emitLog(name, "Warning: could not load Guest Tools config: "+err.Error())
return
}
if !attached && !configured {
return
}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
a.emitLog(name, "Warning: could not start Guest Tools bridge: "+err.Error())
a.emitVMLog(name, "Warning: could not start Guest Tools bridge: "+err.Error())
return
}
sharedDir := a.vmSharedDir(name)
cfg, err = guesttools.LoadOrCreateVMConfig(cur.Directory, name, sharedDir, port)
cfg, err := a.loadAndRegisterGuestTools(srv, port, cur.Directory, name, epoch)
if err != nil {
a.emitLog(name, "Warning: could not load Guest Tools config: "+err.Error())
a.emitVMLog(name, "Warning: could not load Guest Tools config: "+err.Error())
return
}
srv.RegisterVM(validatedDriveConfig(cfg))
if !attached {
return
}
imgPath := a.guestToolsImagePath(name)
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
a.emitLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error())
a.emitVMLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error())
return
}
merged := reims.MergeGuestToolsArgs(cur.ExtraArgs, imgPath)
@@ -221,17 +329,16 @@ func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail)
// and localhost bridge are active, builds the read-only REIMSTOOLS HFS+ disk,
// and attaches it to the VM via `reims-ctl set --extra-args`.
func (a *App) AttachGuestTools(name string) error {
epoch := a.vmDeleteEpoch(name)
c, err := a.client()
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
if d.Directory == "" {
return fmt.Errorf("VM %s has no directory", name)
}
defer release()
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
return err
@@ -240,18 +347,17 @@ func (a *App) AttachGuestTools(name string) error {
if err := os.MkdirAll(sharedDir, 0o755); err != nil {
return err
}
cfg, err := guesttools.LoadOrCreateVMConfig(d.Directory, name, sharedDir, port)
cfg, err := a.loadAndRegisterGuestTools(srv, port, d.Directory, name, epoch)
if err != nil {
return err
}
srv.RegisterVM(validatedDriveConfig(cfg))
imgPath := a.guestToolsImagePath(name)
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
return fmt.Errorf("build REIMSTOOLS disk: %w", err)
}
merged := reims.MergeGuestToolsArgs(d.ExtraArgs, imgPath)
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
ctx := context.Background()
if merged != d.ExtraArgs {
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &merged}, w, w); err != nil {
@@ -260,14 +366,14 @@ func (a *App) AttachGuestTools(name string) error {
}
if a.isVMRunning(ctx, c, name, d) {
a.mu.Lock()
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
Field: "guest_tools",
From: "detached",
To: "attached",
})
a.mu.Unlock()
}
a.emitLog(name, fmt.Sprintf("Guest Tools disk (REIMSTOOLS) attached on 127.0.0.1:%d; shared folder: %s", port, sharedDir))
a.emitVMLog(name, fmt.Sprintf("Guest Tools disk (REIMSTOOLS) attached on 127.0.0.1:%d; shared folder: %s", port, sharedDir))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
@@ -281,20 +387,21 @@ func (a *App) DetachGuestTools(name string) error {
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
stripped := reims.StripGuestToolsArgs(d.ExtraArgs)
ctx := context.Background()
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
if stripped != d.ExtraArgs {
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &stripped}, w, w); err != nil {
return err
}
if a.isVMRunning(ctx, c, name, d) {
a.mu.Lock()
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
Field: "guest_tools",
From: "attached",
To: "ejected",
@@ -302,7 +409,7 @@ func (a *App) DetachGuestTools(name string) error {
a.mu.Unlock()
}
}
a.emitLog(name, "Guest Tools disk (REIMSTOOLS) ejected; clipboard & shared folder bridge remains active")
a.emitVMLog(name, "Guest Tools disk (REIMSTOOLS) ejected; clipboard & shared folder bridge remains active")
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
@@ -321,7 +428,8 @@ func (a *App) OpenSharedFolder(name string) error {
// SetGuestPreventSleep toggles the live macOS prevent-sleep guard (`caffeinate -dims`)
// for a VM and persists the preference in `.reims-go-tools.json`.
func (a *App) SetGuestPreventSleep(name string, enabled bool) error {
d, err := a.GetVMDetail(name)
epoch := a.vmDeleteEpoch(name)
d, err := a.getVMDetail(name, epoch)
if err != nil {
return err
}
@@ -333,6 +441,14 @@ func (a *App) SetGuestPreventSleep(name string, enabled bool) error {
return err
}
sharedDir := a.vmSharedDir(name)
unlock := a.lockGuestToolsVM(name)
defer unlock()
if a.vmDeleteEpoch(name) != epoch {
return os.ErrNotExist
}
if err := requireGuestToolsVM(d.Directory); err != nil {
return err
}
cfg, err := guesttools.LoadOrCreateVMConfig(d.Directory, name, sharedDir, port)
if err != nil {
return err
@@ -341,9 +457,10 @@ func (a *App) SetGuestPreventSleep(name string, enabled bool) error {
if err := guesttools.SaveVMConfig(d.Directory, cfg); err != nil {
return err
}
srv.RegisterVM(validatedDriveConfig(cfg))
srv.SetPreventSleep(name, enabled)
a.emitLog(name, fmt.Sprintf("Guest Tools prevent-sleep guard set to %v", enabled))
if err := a.registerGuestToolsConfig(srv, d.Directory, cfg); err != nil {
return err
}
a.emitVMLog(name, fmt.Sprintf("Guest Tools prevent-sleep guard set to %v", enabled))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
@@ -429,6 +546,6 @@ func (a *App) deliverHostFile(name, picked string) (string, error) {
_ = os.Remove(tmpName)
return "", err
}
a.emitLog(name, fmt.Sprintf("Delivered %s to shared folder (%s)", base, sharedDir))
a.emitVMLog(name, fmt.Sprintf("Delivered %s to shared folder (%s)", base, sharedDir))
return base, nil
}
+163 -47
View File
@@ -10,8 +10,10 @@ import (
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/macos/installer"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -26,7 +28,7 @@ func isRecoveryModeActive(d reims.VMDetail) bool {
if d.HasInstaller {
return true
}
m := vmstart.ReadRecoveryMarker(d.Directory)
m := startprep.ReadRecoveryMarker(d.Directory)
return m == "on" || m == "want"
}
@@ -71,45 +73,77 @@ func (a *App) isVMRunning(ctx context.Context, c *reims.Client, name string, d r
return false
}
// EnterRecovery routes the macOS recovery action through the lifecycle service.
// The legacy path remains available for minimal embedding without a plugin manager.
func (a *App) EnterRecovery(name string) error {
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
return a.enterRecoveryLegacy(name)
}
raw, err := svc.InvokeAction(context.Background(), driver.NewVMRef("", name), "enter_recovery", nil)
if err != nil {
return err
}
result, _ := raw.(map[string]any)
running, _ := result["running"].(bool)
if running {
scheduled, _ := result["scheduled"].(bool)
if scheduled {
a.mu.Lock()
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{Field: "recovery", From: "off", To: "on"})
a.mu.Unlock()
}
a.emitVMLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
} else {
a.emitVMLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
}
a.wakePoll()
a.emitLifecycleStateChanged()
return nil
}
// EnterRecovery enables OpenCore's boot picker (--boot-selection=true) so the
// VM can boot macOS's built-in Recovery volume without needing an external
// installer image (upstream reims-util 7867384 sets HideAuxiliary=false).
// If the VM is running, the change is queued for the next start/restart.
func (a *App) EnterRecovery(name string) error {
func (a *App) enterRecoveryLegacy(name string) error {
c, err := a.client()
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
defer release()
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
ctx := context.Background()
if a.isVMRunning(ctx, c, name, d) {
marker := vmstart.ReadRecoveryMarker(d.Directory)
marker := startprep.ReadRecoveryMarker(d.Directory)
if marker != "on" {
vmstart.WriteRecoveryMarker(d.Directory, "want")
startprep.WriteRecoveryMarker(d.Directory, "want")
a.mu.Lock()
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
Field: "recovery",
From: "off",
To: "on",
})
a.mu.Unlock()
}
a.emitLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
a.emitVMLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
} else {
a.emitLog(name, "Enabling OpenCore boot picker for recovery mode...")
a.emitVMLog(name, "Enabling OpenCore boot picker for recovery mode...")
if err := c.UpdateOpenCore(ctx, name, true, w, w); err != nil {
return err
}
vmstart.WriteRecoveryMarker(d.Directory, "on")
startprep.WriteRecoveryMarker(d.Directory, "on")
if prep, err := a.prep(name); err == nil {
prep.ReplayGuestLang(ctx, d.Directory)
}
a.emitLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
a.emitVMLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
@@ -126,9 +160,22 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
if err != nil {
return "", err
}
d, err := a.GetVMDetail(name)
if err != nil {
return "", err
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
var d reims.VMDetail
if svc == nil {
var release func()
d, release, err = startprep.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return "", err
}
defer release()
} else {
d, err = c.Show(a.baseCtx(), name)
if err != nil {
return "", err
}
}
path := strings.TrimSpace(installerPath)
if path == "" {
@@ -140,17 +187,22 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
return "", errors.New("no cached installer image found")
}
}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
ctx := context.Background()
base := filepath.Base(path)
a.emitLog(name, "Attaching installer image to "+name+": "+base)
if err := c.Insert(ctx, name, path, w, w); err != nil {
a.emitVMLog(name, "Attaching installer image to "+name+": "+base)
if svc != nil {
_, err = svc.InvokeAction(ctx, driver.NewVMRef("", name), "insert", map[string]any{"path": path})
} else {
err = c.Insert(ctx, name, path, w, w)
}
if err != nil {
return "", err
}
if a.isVMRunning(ctx, c, name, d) {
a.mu.Lock()
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
Field: "installer",
From: "ejected",
To: "attached",
@@ -190,7 +242,7 @@ func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, err
}
ctx, cancel := context.WithCancel(base)
id := tasks.start("recovery-download", name, name, cancel)
a.emitLog(name, "Downloading Apple online recovery image (~1 GB) for "+name+"...")
a.emitVMLog(name, "Downloading Apple online recovery image (~1 GB) for "+name+"...")
go func() {
defer cancel()
res, err := a.ensureInstallerForTask(ctx, id, "recovery-download", name, "online", v, func(dlCtx context.Context, onUpdate func(installer.Update)) (*installer.Result, error) {
@@ -198,10 +250,10 @@ func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, err
})
if err != nil {
if errors.Is(err, context.Canceled) || ctx.Err() != nil {
a.emitLog(name, "Online recovery download paused; starting again continues where it stopped")
a.emitVMLog(name, "Online recovery download paused; starting again continues where it stopped")
tasks.finish(id, "", context.Canceled)
} else {
a.emitLog(name, "Online recovery download error: "+err.Error())
a.emitVMLog(name, "Online recovery download error: "+err.Error())
tasks.finish(id, "", err)
}
return
@@ -214,33 +266,79 @@ func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, err
})
attached, err := a.AttachInstaller(name, res.Image)
if err != nil {
a.emitLog(name, "Failed to attach online recovery image: "+err.Error())
a.emitVMLog(name, "Failed to attach online recovery image: "+err.Error())
tasks.finish(id, "", err)
return
}
a.emitLog(name, "Online recovery image attached: "+attached)
a.emitVMLog(name, "Online recovery image attached: "+attached)
tasks.finish(id, attached, nil)
}()
return id, nil
}
// FinishInstall exits recovery through the owning driver and mirrors deferred
// changes into the existing App pending-change model.
func (a *App) FinishInstall(name string) error {
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
return a.finishInstallLegacy(name)
}
raw, err := svc.InvokeAction(context.Background(), driver.NewVMRef("", name), "finish_install", nil)
if err != nil {
return err
}
result, _ := raw.(map[string]any)
running, _ := result["running"].(bool)
if running {
var diffs []PendingChange
if value, _ := result["installer_ejected"].(bool); value {
diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"})
}
if value, _ := result["network_enabled"].(bool); value {
diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"})
}
if value, _ := result["upgraded_nvme"].(bool); value {
from, _ := result["disk_controller_from"].(string)
if from == "" {
from = "ahci"
}
diffs = append(diffs, PendingChange{Field: "disk_controller", From: from, To: "nvme"})
}
if value, _ := result["recovery_pending"].(bool); value {
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
}
if len(diffs) > 0 {
a.mu.Lock()
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], diffs...)
a.mu.Unlock()
}
}
a.emitVMLog(name, "Exited recovery mode")
a.wakePoll()
a.emitLifecycleStateChanged()
return nil
}
// FinishInstall exits recovery mode: ejects any attached installer, removes
// REIMSHELP, enables the network if off, and restores OpenCore direct boot
// (--boot-selection=false) if recovery mode enabled the boot picker.
func (a *App) FinishInstall(name string) error {
func (a *App) finishInstallLegacy(name string) error {
c, err := a.client()
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
defer release()
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
ctx := context.Background()
if d.HasInstaller {
a.emitLog(name, "Ejecting installer from "+name+"...")
a.emitVMLog(name, "Ejecting installer from "+name+"...")
if err := c.Eject(ctx, name, w, w); err != nil {
return err
}
@@ -253,13 +351,13 @@ func (a *App) FinishInstall(name string) error {
on := true
setOpts.Network = &on
needSet = true
a.emitLog(name, "Turning the network on for "+name+"...")
a.emitVMLog(name, "Turning the network on for "+name+"...")
}
if d.HasInstaller && strings.EqualFold(d.DiskController, "ahci") {
setOpts.DiskController = "nvme"
needSet = true
upgradedNVMe = true
a.emitLog(name, "Upgrading disk controller for "+name+" from SATA/AHCI to NVMe...")
a.emitVMLog(name, "Upgrading disk controller for "+name+" from SATA/AHCI to NVMe...")
}
if stripped != d.ExtraArgs {
setOpts.ExtraArgs = &stripped
@@ -272,7 +370,7 @@ func (a *App) FinishInstall(name string) error {
}
running := a.isVMRunning(ctx, c, name, d)
marker := vmstart.ReadRecoveryMarker(d.Directory)
marker := startprep.ReadRecoveryMarker(d.Directory)
if running {
var diffs []PendingChange
if d.HasInstaller {
@@ -286,32 +384,32 @@ func (a *App) FinishInstall(name string) error {
}
switch marker {
case "want":
vmstart.WriteRecoveryMarker(d.Directory, "")
startprep.WriteRecoveryMarker(d.Directory, "")
case "on":
vmstart.WriteRecoveryMarker(d.Directory, "restore")
startprep.WriteRecoveryMarker(d.Directory, "restore")
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
}
if len(diffs) > 0 {
a.mu.Lock()
a.pendingChanges[name] = append(a.pendingChanges[name], diffs...)
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], diffs...)
a.mu.Unlock()
}
} else {
if marker == "on" || marker == "restore" {
a.emitLog(name, "Restoring OpenCore direct boot after exiting recovery mode...")
a.emitVMLog(name, "Restoring OpenCore direct boot after exiting recovery mode...")
if err := c.UpdateOpenCore(ctx, name, false, w, w); err != nil {
a.emitLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
a.emitVMLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
} else {
vmstart.WriteRecoveryMarker(d.Directory, "")
startprep.WriteRecoveryMarker(d.Directory, "")
if prep, err := a.prep(name); err == nil {
prep.ReplayGuestLang(ctx, d.Directory)
}
}
} else if marker != "" {
vmstart.WriteRecoveryMarker(d.Directory, "")
startprep.WriteRecoveryMarker(d.Directory, "")
}
}
a.emitLog(name, "Exited recovery mode")
a.emitVMLog(name, "Exited recovery mode")
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
@@ -325,9 +423,22 @@ func (a *App) UpgradeDiskToNVMe(name string) error {
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
if err != nil {
return err
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
var d reims.VMDetail
if svc == nil {
var release func()
d, release, err = startprep.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
} else {
d, err = c.Show(a.baseCtx(), name)
if err != nil {
return err
}
}
if d.HasInstaller {
return errors.New("exit recovery mode (eject installer) before switching disk controller")
@@ -335,15 +446,20 @@ func (a *App) UpgradeDiskToNVMe(name string) error {
if strings.EqualFold(d.DiskController, "nvme") {
return nil
}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
ctx := context.Background()
a.emitLog(name, "Upgrading disk controller for "+name+" to NVMe...")
if err := c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w); err != nil {
a.emitVMLog(name, "Upgrading disk controller for "+name+" to NVMe...")
if svc != nil {
_, err = svc.InvokeAction(ctx, driver.NewVMRef("", name), "upgrade_nvme", nil)
} else {
err = c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w)
}
if err != nil {
return err
}
if a.isVMRunning(ctx, c, name, d) {
a.mu.Lock()
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
Field: "disk_controller",
From: d.DiskController,
To: "nvme",
+17 -12
View File
@@ -3,11 +3,12 @@ package app
import (
"context"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/installguide"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/vmstart"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/installguide"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -20,7 +21,7 @@ func (a *App) getInstallGuideManager() *installguide.Manager {
if mgr == nil {
return nil
}
raw, ok := mgr.Registry().LookupService(builtin.ServiceInstallGuide)
raw, ok := mgr.Registry().LookupService(guest.ServiceInstallGuide)
if !ok {
return nil
}
@@ -39,7 +40,7 @@ func (a *App) guidePreferences() (i18n.Locale, installguide.Theme) {
rawLoc := a.cfg.Locale
th := a.themeMode
a.mu.Unlock()
return i18n.EffectiveLocale(rawLoc), th
return i18n.EffectiveLocale(rawLoc), installguide.Theme(th)
}
func (a *App) bindGuideEvents(ctx context.Context) {
@@ -51,7 +52,7 @@ func (a *App) bindGuideEvents(ctx context.Context) {
theme := installguide.Theme(raw)
if theme == installguide.ThemeLight || theme == installguide.ThemeDark {
a.mu.Lock()
a.themeMode = theme
a.themeMode = string(theme)
a.mu.Unlock()
}
})
@@ -72,13 +73,17 @@ func installGuideKind(d reims.VMDetail) (installguide.Kind, bool) {
}
return installguide.Online, true
}
return installguide.BuiltIn, vmstart.ReadRecoveryMarker(d.Directory) == "on"
return installguide.BuiltIn, startprep.ReadRecoveryMarker(d.Directory) == "on"
}
func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manager, name string, pid int, d reims.VMDetail, loc i18n.Locale) bool {
func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manager, name string, pid int, vm driver.VMInfo, loc i18n.Locale) bool {
if gm == nil || pid <= 0 || gm.HasActive(name, pid) {
return false
}
d, err := macOSDetailFromVMInfo(vm)
if err != nil {
return false
}
kind, recovery := installGuideKind(d)
g := installguide.Guide{
Name: name,
@@ -137,7 +142,7 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei
_, err := a.AttachInstaller(name, path)
return err
}
g.LogError = func(err error) { a.emitLog(name, "Installation guide: "+err.Error()) }
g.LogError = func(err error) { a.emitVMLog(name, "Installation guide: "+err.Error()) }
g.AttachTools = func() error {
if err := checkBoot(); err != nil {
return err
@@ -148,12 +153,12 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei
if err := checkBoot(); err != nil {
return err
}
stopped, err := a.restartVM(name)
stopped, err := a.restartMacOSVM(name)
if stopped && err != nil {
// The guest window has closed, so report start failures via the tray.
loc, _ := a.guidePreferences()
title := i18n.M(loc, "guide.err.restart_failed", i18n.Vars{"name": name})
a.emitLog(name, title+": "+err.Error())
a.emitVMLog(name, title+": "+err.Error())
a.mu.Lock()
tm := a.trayMgr
a.mu.Unlock()
Loaded 100 of 432 files, more files were not shown because too many files have changed in this diff. Show more