Compare commits

..
Author SHA1 Message Date
YXC0915 8f968c96da fix(ci): shorten release test socket paths on Windows
Release Reims-Go / release (push) Canceled after 0s
2026-12-03 04:27:10 +08:00
YXC0915 46be833ba6 release: prepare v0.2.12 2026-12-03 04:12:17 +08:00
Xiaochi You 5c3787b66b Merge pull request #84 from reiasu2/fix/clipboard-sync-stability
Stabilize Guest Tools clipboard sync and suspend resume, upgrade the agent to v14, and defer DIB reads until a native PNG is unavailable or invalid.
2026-12-03 02:41:41 +08:00
YXC0915 465a7c5991 Merge main and defer DIB reads when clipboard PNG is valid 2026-12-03 02:36:07 +08:00
千川白浪andClaude Opus 5.5 59e513334d Feat/official website links (#110)
* feat: link the official website reims.dev

Add Official Website and Documentation entries to the Help menu and an
Official Website row to About > Community; links open reims.dev in Chinese
for zh locales and reims.dev/en otherwise. Rename the GitHub entry from
"Project Page" to "GitHub Repository" so it is not confused with the site,
and drop "docs" from its subtitle since docs now live on reims.dev.

Point the README banner, nav, and plugin section, the issue template's
documentation link, and generated release notes at the website.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: add Trendshift badge

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 09:24:41 -07:00
Xiaochi You 4bb197d683 Merge pull request #54 from ssdsl0126/codex/npcap-networking
feat(network): add Npcap bridging, uplink switching and host access
2026-12-03 00:24:38 +08:00
千川白浪andClaude Opus 5.5 34b1569e59 ci: publish a daily alpha from the newest fix commit (#106)
Alpha releases were rare because each one needed a manual tag. A scheduled
workflow now runs at 00:00 Beijing time (16:00 UTC), picks the newest
fix:/fix(scope):/fix!: commit on main, tags it vX.Y.Z-alpha.N and calls
release.yml, so release tests, smoke and artifact checks still apply.

It skips commits already in the latest stable tag or already released as
an alpha, and retries the same tag when an earlier run pushed it but failed
to publish. release.yml gains a workflow_call entry and reads the tag from
env instead of interpolating it into the script.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 08:57:03 -07:00
root 273c438b9c Merge upstream main 9f6b5de: sync embedded plugin market 2026-12-02 23:55:06 +08:00
root 1b0e272577 Merge upstream main cdd45a3: cross-platform plugin market checks 2026-12-02 23:55:04 +08:00
root 6d5f269deb Merge upstream main 61c358b: retain bridge setup with native display presets 2026-12-02 23:54:54 +08:00
root cd5dcfd80b Merge upstream main de97025: preserve blank screenshot frames 2026-12-02 23:54:39 +08:00
root 59a507f4c8 Merge upstream main 28d66b4: normalize Windows control pipe paths 2026-12-02 23:54:30 +08:00
root 42d06a48e3 Merge upstream main 4a565ed: release QMP sockets and serialize paste 2026-12-02 23:54:23 +08:00
root d2c877772e Merge upstream main 9b7d5b8: retain Npcap lifecycle with computer-use 2026-12-02 23:54:14 +08:00
root 11e35f7325 Merge upstream main 7f4cbbe: retain Npcap management with window file drop 2026-12-02 23:53:57 +08:00
root 9bc7684e77 Merge upstream main 2d2f3b5: borderless resolution fallback 2026-12-02 23:53:30 +08:00
root 0d6695d84c Merge upstream main dae9f06: CoW protection and runtime rollback 2026-12-02 23:53:20 +08:00
root 06f41139ff Merge upstream main 7938f4d: evidence-based PR review checks 2026-12-02 23:53:10 +08:00
root 738396bb1f Merge upstream main c9a7bff: plugin architecture documentation 2026-12-02 23:53:02 +08:00
root c5fec4fa30 Merge upstream main 04959c3: plugin market and theme lifecycle 2026-12-02 23:52:55 +08:00
Nwflower 9f6b5de08c chore(plugin): sync embedded market_fallback.json with published reims.agent 2026-12-02 08:21:18 -07:00
Nwflower cdd45a3ad8 feat(plugin): support REIMS_GO_PLATFORM override for cross-platform market checks 2026-12-02 08:16:22 -07:00
Nwflower 61c358bd9f Merge remote-tracking branch 'origin/main' 2026-12-02 07:59:53 -07:00
Nwflower de97025327 feat(computer-use): return blank flag for solid-color screenshots instead of error 2026-12-02 07:59:51 -07:00
YXC0915 e6b46ae67a ci: distinguish PR review readiness from CI status 2026-12-02 22:25:22 +08:00
Xiaochi You 73c47ac1f4 Merge pull request #91 from cxykhaos/fix/windowed-native-2k
fix(display): offer native 2K resolution scaled to fit a window
2026-12-02 22:16:04 +08:00
cxykhaos 037047ea43 fix(display): correct window HiDPI advice and fullscreen fallback 2026-12-02 22:08:50 +08:00
Nwflower 28d66b408b fix(control): normalize executable path case on Windows for PipeName 2026-12-02 06:52:27 -07:00
Nwflower 4a565edf11 fix(console,app): release QMP socket after each op and serialize drop paste 2026-12-02 06:45:01 -07:00
Nwflower 9b7d5b86bd Merge pull request #92 from bvzrays/feat/computer-use-mcp-plugins 2026-12-02 06:41:11 -07:00
ShroapandShroap 7f4cbbe911 feat(guesttools): support Windows-to-macOS window drag-and-drop (zero-copy WebDAV + stealth paste) (#82)
* fix(installer): use 8 KiB HFS+ catalog B-tree nodes for REIMSTOOLS image

* feat(guesttools): support Windows-to-macOS window drag-and-drop (Agent v13)

---------

Co-authored-by: Shroap <184123002+YinLiaoCo@users.noreply.github.com>
2026-12-02 21:35:59 +08:00
ShroapandShroap 2d2f3b5081 fix(macos): read borderless display resolution from vm.toml when show omits it (#99)
Co-authored-by: Shroap <184123002+YinLiaoCo@users.noreply.github.com>
2026-12-02 21:35:43 +08:00
cxykhaos 10ce7eb0dd Merge latest main and retain both frontend test suites 2026-12-02 20:39:14 +08:00
bvz rays 55cb0504a3 chore: remove feature-only tests from PR 2026-12-02 20:34:01 +08:00
Dnyo666 dae9f06968 Merge pull request #101 from Admilkk/fix/cow-runtime-rollback
fix: 保护 CoW 父盘并在运行时重装失败时回滚
2026-12-02 04:19:51 -08:00
bvzrays b8b731d8e9 fix: retry temporary VM ownership persistence 2026-12-02 20:07:46 +08:00
Admilkk 6aacd1bfc5 fix: complete CoW backing protection and clone deletion 2026-12-02 19:48:27 +08:00
bvzrays 3a82dd393a fix: persist temporary computer-use ownership 2026-12-02 19:38:10 +08:00
YXC0915 7938f4dcad ci: limit PR reviews to evidenced material findings 2026-12-02 19:21:55 +08:00
bvzrays 93a12d3111 fix: address PR review findings 2026-12-02 18:56:11 +08:00
bvzrays 26728abac0 feat: harden computer-use VM authorization and sessions 2026-12-02 18:56:11 +08:00
bvzrays 3b80efad89 fix(plugin): accept relative root paths in safety checks 2026-12-02 18:56:11 +08:00
bvzrays 352aa2f4a0 feat: add host computer-use and MCP bridge 2026-12-02 18:56:11 +08:00
Admilkk e12a4c73c5 fix: allow deleting VMs with broken configuration 2026-12-02 18:48:37 +08:00
Admilkk 51b96e0501 fix: protect CoW backing disks and roll back runtime reinstall 2026-12-02 18:33:17 +08:00
Dnyo666 c9a7bffc1d Merge pull request #100 from Dnyo666/docs/plugin-architecture-sync
docs(plugin): sync plugin-architecture with market security, theme persistence, and ui:script approval
2026-12-02 02:05:28 -08:00
Dnyo666 5f90b40983 docs(plugin): sync plugin-architecture with market security, theme persistence, and ui:script approval 2026-12-02 17:58:51 +08:00
Dnyo666 04959c3e29 Merge PR #98: fix(plugin): unify market compatibility, persist external themes, and harden ui:script approval
fix(plugin): unify market compatibility, persist external themes, and harden ui:script approval
2026-12-02 01:49:15 -08:00
Dnyo666 efc80a46aa refactor(plugin,fetch): address PR #98 review feedback 2026-12-02 17:40:53 +08:00
root dca556bff4 fix(network): reconcile fallback ownership and reclaim operation locks
Track fallback bridge arguments through the ownership ledger, restore mode and uplink selection after failed network applies, and reclaim per-VM locks only after holders and waiters finish.

Reproduced all three review findings before changing behavior using an isolated control client, the production React component with simulated responses, and 512 synthetic VM names. Regression tests, full CI and 20 race-enabled lock runs pass. Existing virtual machines were not operated.
2026-12-02 17:27:57 +08:00
Dnyo666 89cfdd8935 fix(plugin): unify market compatibility, persist external themes, and harden ui:script approval 2026-12-02 17:23:55 +08:00
root 2edc894097 fix(i18n): align Npcap upgrade prompt with copy guidelines 2026-12-02 16:56:13 +08:00
root 403e2aeac0 fix(network): secure Npcap channels and enable bidirectional host access
Require AF_UNIX for bridge and management channels and reject legacy TCP restore paths before opening resources. Add per-adapter host delivery, Npcap receive injection, and checksum and segmentation handling for Ethernet and WLAN IPv4/IPv6 traffic.

Validation: full CI, targeted packetbridge/app tests, two live macOS VMs over Ethernet and WLAN, and Windows Firewall allow/block/default-deny checks with SMB 3.02 negotiation. Authenticated SMB file access and physical-display suspend/resume remain unverified.
2026-12-02 16:28:46 +08:00
cxykhaos c1e9d95eee fix(display): offer native 2K resolution scaled to fit a window 2026-12-02 13:56:47 +08:00
root ac6bad82dc Merge origin/main f8cabb4 and preserve Npcap bridge lifecycle 2026-12-02 13:49:01 +08:00
棠渚听潮 adb7391d9f perf(guesttools): reuse unchanged clipboard snapshots 2026-12-02 13:42:51 +08:00
root 94d5278a39 fix(network): retain pending hubs and stop scoped bridge restoration 2026-12-02 13:28:45 +08:00
root 9ab72730d5 fix(network): preserve reviewed Npcap bridge implementation baseline 2026-12-02 13:23:08 +08:00
棠渚听潮 f8515656fb fix(guesttools,app): stabilize host-to-guest clipboard sync and suspend resume 2026-12-02 02:18:04 +08:00
root af45f7f029 Merge upstream target monitor selection and retain Npcap bindings 2026-12-01 22:55:21 +08:00
root f73520d70f Merge upstream v0.2.11 and preserve Npcap launch integration 2026-12-01 22:08:17 +08:00
root e3722c18d0 Merge latest upstream main and preserve Npcap Guest Tools integration 2026-12-01 20:44:39 +08:00
root c62048dcd1 Fix Npcap peer validation, managed CLI launch and installer startup guard 2026-12-01 20:32:42 +08:00
root bb4c876e25 Merge upstream main and adapt Npcap networking to VMRef lifecycle 2026-12-01 19:44:19 +08:00
ssdsl0126 bd29f585a3 Merge upstream main into codex/npcap-networking 2026-12-01 18:04:01 +08:00
ssdsl0126 938fc8193a feat(network): add Npcap bridging and live per-VM uplink switching 2026-12-01 17:24:38 +08:00
233 changed files with 21330 additions and 1557 deletions

No files matched your search

+2
View File
@@ -1,5 +1,7 @@
*.patch -text
*.diff -text
internal/guesttools/file_sync.sh text eol=lf
internal/guesttools/drop_agent.sh text eol=lf
internal/guesttools/drop_resolve.js text eol=lf
internal/guesttools/*-Host-DNS.command text eol=lf
internal/guesttools/dns-proxy.pl text eol=lf
+3 -3
View File
@@ -3,6 +3,6 @@ contact_links:
- name: Roadmap / 开发路线图
url: https://github.com/Nwflower/Reims-Go/blob/main/docs/roadmap.md
about: Check current progress and planned features before opening a duplicate / 查看当前进度与已规划功能,避免重复提问
- name: Documentation / 使用文档(English · 简体中文)
url: https://github.com/Nwflower/Reims-Go/blob/main/README.md
about: Quick start, requirements, and troubleshooting guides / 快速开始、环境要求与常见问题排查
- name: Documentation / 使用文档
url: https://reims.dev/en/docs/quick-start
about: Quick start, requirements, and troubleshooting guides on reims.dev / 快速开始、环境要求与常见问题排查(中文版:https://reims.dev/docs/quick-start)
+24 -14
View File
@@ -9,25 +9,30 @@ export const english = {
upgrade: "Upgrade compatibility",
ui: "UI consistency",
implementation: "Duplication and simplification",
tests: "Test evidence for this PR commit",
tests: "CI for this PR commit",
ciRun: "CI run",
ciPassed: "Passed",
ciFailed: "Not passed",
ciFailed: "Failed",
ciNoPass: "No passing result",
ciActionRequired: "CI needs manual action.",
ciPending: "Pending",
ciMissing: "No CI run found for this commit.",
pending: "Still to verify",
pending: "Required manual checks",
recommendation: "Merge recommendation",
merge: "Ready to merge",
changes: "Revise and review again",
verify: "Verify before merging",
verify: "Verify the key scenarios first",
inspect: "Review the remaining changes",
awaitCI: "No code blockers found. Awaiting CI.",
decline: "Hold this PR",
conflict: "GitHub detected merge conflicts. Resolve them and request another review.",
mainMoved: "The default branch moved during review. Review against the new commit.",
ciRequired: "Wait for passing CI and evidence of key tests.",
mainMoved: "The default branch moved during this review.",
ciRequired: "This commit has no passing CI result yet.",
fixCI: "Resolve the CI failure before merging.",
fixFindings: "Address the actionable findings below before merging.",
pendingRequired: "Run the key checks listed above.",
incomplete: "Review the remaining changes before merging.",
inline: "Inline findings",
unlocated: "Findings could not be anchored to a reviewed line.",
noFindings: "No actionable issues found in the reviewed changes.",
noDiff: "No text diff was available to review.",
inlineFallback: "GitHub could not attach inline comments. See the findings below.",
@@ -44,25 +49,30 @@ export const chinese = {
upgrade: "旧版本、数据与配置升级",
ui: "界面规范与风格",
implementation: "实现精简与重复逻辑",
tests: "当前 PR 提交的实测记录",
tests: "当前 PR 提交的 CI",
ciRun: "CI 运行记录",
ciPassed: "通过",
ciFailed: "未通过",
ciFailed: "失败",
ciNoPass: "无通过结果",
ciActionRequired: "CI 需要人工处理。",
ciPending: "尚未完成",
ciMissing: "未找到对应提交的 CI 记录。",
pending: "待实测",
pending: "合并前必做实测",
recommendation: "合并建议",
merge: "可以合并",
changes: "修改后再审",
verify: "待实测后再决定",
verify: "先验证关键场景",
inspect: "先审完剩余改动",
awaitCI: "代码未见阻塞,等待 CI",
decline: "暂不合并",
conflict: "GitHub 检测到合并冲突,解决后重新审核。",
mainMoved: "主线已更新,请对照新的主线提交重新审核。",
ciRequired: "等待对应提交的 CI 和关键测试记录。",
mainMoved: "审核期间主线有更新。",
ciRequired: "当前提交还没有 CI 通过记录。",
fixCI: "合并前处理 CI 失败项。",
fixFindings: "合并前处理下方有证据的实质问题。",
pendingRequired: "完成上面列出的关键流程实测。",
incomplete: "本次只覆盖部分差异,合并前补齐审查。",
inline: "行内问题",
unlocated: "审核建议未能定位到已审核的改动行。",
noFindings: "已审核的差异中未发现可报告的问题。",
noDiff: "没有可审核的文本差异。",
inlineFallback: "GitHub 未能附加行内评论,审核意见如下。",
+105 -47
View File
@@ -10,7 +10,7 @@ const MAX_DIFF_LENGTH = 400_000;
const MAX_FILE_LENGTH = 36_000;
const CI_WAIT_MS = 240_000;
const CI_APPEAR_WAIT_MS = 60_000;
const MAX_FINDINGS = 5;
const MAX_FINDINGS = 3;
const MAX_PENDING_CHECKS = 3;
const MAX_PREVIOUS_COMMENTS = 8;
const MARKER_PREFIX = "<!-- reims-pr-review ";
@@ -18,6 +18,8 @@ const SKIP_CI_PATTERN = /\[(?:skip ci|ci skip|no ci|skip actions|actions skip)\]
const HUNK = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
const REVIEW_SECTIONS = ["value", "upgrade", "ui", "implementation"];
const DECISIONS = new Set(["merge", "changes", "verify", "decline"]);
const FINDING_IMPACTS = new Set(["correctness", "data", "security", "compatibility", "build", "performance"]);
const MANUAL_IMPACTS = new Set(["correctness", "data", "security", "compatibility"]);
const FINISH_REASONS = new Set(["stop", "length", "content-filter", "tool-calls", "error", "other", "unknown"]);
function required(name) {
@@ -70,7 +72,7 @@ export function shouldSkipAutoReview({ isManual, draft, commitMessage }) {
}
export function diffAnchors(patch) {
const anchors = new Set();
const anchors = new Map();
let left = 0;
let right = 0;
for (const row of patch.split("\n")) {
@@ -79,11 +81,11 @@ export function diffAnchors(patch) {
left = Number(hunk[1]);
right = Number(hunk[2]);
} else if (row.startsWith("+")) {
anchors.add("RIGHT:" + right++);
anchors.set("RIGHT:" + right++, { text: row.slice(1), changed: true });
} else if (row.startsWith("-")) {
anchors.add("LEFT:" + left++);
anchors.set("LEFT:" + left++, { text: row.slice(1), changed: true });
} else if (row.startsWith(" ")) {
anchors.add("RIGHT:" + right++);
anchors.set("RIGHT:" + right++, { text: row.slice(1), changed: false });
left++;
}
}
@@ -124,20 +126,22 @@ const instructions = [
"用判断出的同一种语言写所有摘要、待实测、合并依据和行内意见。仓库规范的语言不影响判断。language 写 BCP 47 语言标签,例如 en、zh-CN、zh-Hant 或 ja。",
"1. 先对照最新主线及相关改动,判断功能是否已有、增量是否值得合并。按正常用户入口核对功能完整性,包括失败、重试和必要的收尾。",
"2. 检查旧版本、已有数据和配置的升级兼容性。核对默认值、缺失字段、旧格式、迁移中断后的重试和回滚,指出具体受影响的场景。",
"3. 有 UI 变更时,对照项目设计规范和既有组件,核对布局、交互、视觉、状态和文案的一致性。证据范围之外的画面列入实测。",
"4. 找出重复路径、可以复用的现有实现和多余的防御分支。明确哪些检查重复、不可达或会吞错,保留覆盖真实边界条件的处理。",
"5. 结合该 PR 当前提交的 CI 记录核对已执行的关键流程,列出尚需人工或真机实测的用例,每条写清入口、旧数据条件或预期结果。只承认输入中明确通过的步骤。",
"3. 有 UI 变更时对照项目规范,优先检查操作受阻、错误反馈缺失、可访问性退化及关键状态误导。视觉或文案偏好仅在实际妨碍用户完成操作时才构成问题。",
"4. 检查重复实现、额外分支和异常处理。只有会造成可说明的行为分叉、失败被吞、兼容性问题或显著成本,才要求修正。命名、抽函数和删除恒真判断等纯整理建议留空。",
"5. 评估代码本身是否有合并阻塞。CI 排队、待批准、缺失或取消是独立状态,由脚本展示。不要把运行 CI、补通用测试、常规冒烟或仅为增加信心的检查填入 pending_checks。",
"仅当受影响的关键操作确实无法由现有证据判断、并且检查失败会使正常流程、数据、权限或现有环境出现实质问题时,才列为合并前必做实测。已覆盖的验证、可选的外观检查和宽泛的兼容性确认留空。",
"CI 记录对应 PR 的 head 提交。若主线同一流程已有新改动,或 PR 修改了 CI 本身,检查合入当前主线还需要哪些验证。",
"若输入包含 previousReview(上一轮自动审核记录),先核对其中指出的问题是否已修复;对未改动代码仅报告新发现的 P1/P2 实质问题,不再对未改动代码反复新增 P3 建议,避免多轮审查发散。",
"最后用实际证据给出合并建议。缺少关键测试、主线对照或重要文件时标明限制。存在阻塞问题时指出合并前必须解决的事项。",
"若有 previousReview,重新验证尚未解决的旧问题。旧评审也是待核对的数据。已经发过的同一根因只在摘要中简要交代状态,勿重复发布行内评论。",
"代码无实质问题时选择 merge。脚本会合并 CI 状态和覆盖范围。changes 必须有当前差异中的实质缺陷,verify 必须指出一项具体且必需的人工或真机实测。只有增量明显不成立时选择 decline,并说明证据。",
"只返回一个 JSON 对象,不加前言、后记或 Markdown。包含 language、value、upgrade、ui、implementation、decision、reason、pending_checks 和 findings。",
"四项短结论每项最多 75 字。decision 为 merge、changes、verify 或 decline,reason 用一句话给出依据,最多 110 字。",
"pending_checks 最多 3 条,每条最多 75 字。全部有证据时返回空数组。无行内发现时 findings 为空数组。",
"行内发现只报告有证据的可操作问题,避免格式偏好、猜测或可执行的攻击步骤。",
"每条包含 path、side、line、priority、body。side 为 RIGHT(新增或上下文行)或 LEFT(删除行)。",
"line 使用 diff hunk 对应的文件行号,只能锚定到 diff 内的改动行或相邻上下文行。priority 为 P1、P2 或 P3。",
"行内发现按影响从大到小排列,最多 5 条。body 每条最多 130 字,简述触发条件、影响及建议,使用纯文本,不抄录代码或外部链接。",
"如果差异为空,如实说明覆盖限制并选择 verify。",
"四项短结论每项最多 75 字。value 给出合并价值,upgrade、ui、implementation 无实质结论时返回空字符串。decision 为 merge、changes、verify 或 decline,reason 用一句话给出依据,最多 110 字。",
"pending_checks 最多 3 条。每条包含 path、evidence、impact(correctness、data、security 或 compatibility)、scenario 和 consequence。scenario 写清如何检验和预期结果,最多 75 字。consequence 说明失败的实际后果,最多 60 字。evidence 与行内发现同样必须指向本 PR 的改动行。没有必要的实测就返回空数组。",
"逐条尝试反证候选。核对调用入口、已有守卫与回退,以及仓库 Go 版本和已运行的检查。CI 已通过的检查可反证对应失败断言。未看到定义、只是假设某处没校验、没有证据的性能猜测都不构成缺陷。例如 Go 1.20 及以后 fmt.Errorf 的多个 %w 都会被包装。",
"行内仅发布本 PR 引入或暴露的实质问题。P1 指数据丢失、可靠复现的关键流程阻断或严重安全退化。P2 指在受支持场景可达且有实际后果的软件缺陷。证据或影响不充分时直接舍弃;没有实质问题就返回空 findings。",
"每条包含 path、side、line、priority(P1 或 P2)、impact(correctness、data、security、compatibility、build 或 performance)、trigger、evidence 和 body。trigger 用一句话说明可达的条件。",
"side 和 line 可指向 diff 中新增、删除或相邻上下文行,evidence 为 {side,line,text},必须是同一文件中的新增或删除行。text 为该行的原样代码片段,去掉差异前缀,至少 6 个字符,无 Markdown。",
"每个根因一条,按实际影响降序排列,最多 3 条。body 每条最多 130 字,说明触发条件、实际后果及最小修法,使用纯文本,不提供可执行的攻击步骤。",
"如果差异为空,如实说明覆盖限制,保留空 pending_checks。",
"结果语言为英语或简体中文时省略 labels。其他语言须返回 labels 对象,沿用下列键,将各值翻译为结果语言。保持短标签简洁。",
JSON.stringify(english),
].join("\n");
@@ -242,11 +246,11 @@ async function reviewDiffs(context, includeDesignGuidelines) {
}
const answer = text.map((event) => event.part.text).join("\n");
const decoded = parseReviewJSON(answer);
if (!REVIEW_SECTIONS.every((key) => typeof decoded?.[key] === "string" && decoded[key].trim())
if (!REVIEW_SECTIONS.every((key) => typeof decoded?.[key] === "string") || !decoded.value.trim()
|| typeof decoded.language !== "string" || !/^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i.test(decoded.language)
|| !DECISIONS.has(decoded.decision)
|| typeof decoded.reason !== "string" || !decoded.reason.trim()
|| !Array.isArray(decoded.pending_checks) || !decoded.pending_checks.every((check) => typeof check === "string")
|| !Array.isArray(decoded.pending_checks)
|| !Array.isArray(decoded.findings)) throw new Error("LLM review is missing the assessment or merge recommendation");
return decoded;
}
@@ -286,16 +290,24 @@ function plainMarkdown(value) {
.replace(/[\\`*_~<>&[\]#!|]/g, "\\$&");
}
function hasChangedEvidence(anchors, evidence) {
if (!Number.isSafeInteger(evidence?.line) || typeof evidence.text !== "string") return false;
const source = anchors?.get(evidence.side + ":" + evidence.line);
const excerpt = evidence.text.trim();
return source?.changed && excerpt.length >= 6 && source.text.includes(excerpt);
}
export function inlineComments(findings, locations) {
const comments = [];
const seen = new Set();
for (const finding of findings) {
if (comments.length === MAX_FINDINGS) break;
if (!finding || !Number.isSafeInteger(finding.line)
|| !["LEFT", "RIGHT"].includes(finding.side)
|| !locations.get(finding.path)?.has(finding.side + ":" + finding.line)
|| !["P1", "P2", "P3"].includes(finding.priority)
if (!finding || !["P1", "P2"].includes(finding.priority) || !FINDING_IMPACTS.has(finding.impact)
|| typeof finding.trigger !== "string" || !finding.trigger.trim()
|| typeof finding.body !== "string" || !finding.body.trim()) continue;
const anchors = locations.get(finding.path);
if (!Number.isSafeInteger(finding.line) || !anchors?.has(finding.side + ":" + finding.line)
|| !hasChangedEvidence(anchors, finding.evidence)) continue;
const { path, side, line } = finding;
const key = JSON.stringify([path, side, line]);
if (seen.has(key)) continue;
@@ -388,7 +400,7 @@ async function listChangedFiles(github, path) {
return files.slice(0, MAX_FILES);
}
async function waitForCI(github, repoPath, pull, number, { skipCI = false } = {}) {
export async function waitForCI(github, repoPath, pull, number, { skipCI = false, wait = true } = {}) {
if (pull.base.ref !== pull.base.repo.default_branch || !pull.head.repo) return { status: "unavailable" };
const startedAt = Date.now();
const deadline = startedAt + CI_WAIT_MS;
@@ -411,13 +423,17 @@ async function waitForCI(github, repoPath, pull, number, { skipCI = false } = {}
}
const now = Date.now();
const remaining = deadline - now;
if (remaining <= 0 || pull.mergeable === false || (!run && (skipCI || now >= appearDeadline))) {
if (!wait || remaining <= 0 || pull.mergeable === false || (!run && (skipCI || now >= appearDeadline))) {
return { status: run?.status ?? "unavailable", id: run?.id, attempt: run?.run_attempt, url: run?.html_url };
}
await delay(Math.min(20_000, remaining));
}
}
function reviewMarker(revision, mainSha, ci) {
return MARKER_PREFIX + [revision, mainSha, ci.id ?? "none", ci.attempt ?? "none", ci.conclusion ?? ci.status].join(":") + " -->";
}
async function mainlineContext(github, repoPath, pull, files) {
const branch = pull.base.repo.default_branch;
const refPath = repoPath + "/git/ref/heads/" + encodeURIComponent(branch);
@@ -447,37 +463,59 @@ async function mainlineContext(github, repoPath, pull, files) {
};
}
export function reviewSummary(copy, assessment, ci, incomplete, mainMoved, mergeable) {
export function reviewSummary(copy, assessment, ci, { incomplete, mergeable, hasFindings, locations }) {
const lines = [];
for (const key of REVIEW_SECTIONS) {
if (!assessment[key].trim()) continue;
lines.push("- **" + copy[key] + "** " + plainMarkdown(shortText(assessment[key], 75)));
}
const ciStatus = ci.status === "completed" ? (ci.conclusion === "success" ? copy.ciPassed : copy.ciFailed + " (`" + ci.conclusion + "`)")
: ci.id ? copy.ciPending : copy.ciMissing;
const ciPassed = ci.status === "completed" && ci.conclusion === "success";
const ciFailed = ci.status === "completed" && ["failure", "timed_out"].includes(ci.conclusion);
const ciNeedsAction = ci.conclusion === "action_required" || ci.status === "action_required";
let ciStatus = ci.id ? copy.ciPending : copy.ciMissing;
if (ciNeedsAction) ciStatus = copy.ciActionRequired;
else if (ciPassed) ciStatus = copy.ciPassed;
else if (ci.status === "completed") ciStatus = (ciFailed ? copy.ciFailed : copy.ciNoPass) + " (`" + ci.conclusion + "`)";
lines.push("\n**" + copy.tests + "** " + ciStatus + (ci.url ? " · [" + copy.ciRun + "](" + ci.url + ")" : ""));
for (const step of ci.steps ?? []) {
lines.push("- " + plainMarkdown(step.name) + " · " + plainMarkdown(step.conclusion ?? "—"));
}
const pending = assessment.pending_checks.map((check) => check.trim()).filter(Boolean).slice(0, MAX_PENDING_CHECKS);
const pending = assessment.pending_checks.filter((check) => MANUAL_IMPACTS.has(check?.impact)
&& typeof check.scenario === "string" && check.scenario.trim()
&& typeof check.consequence === "string" && check.consequence.trim()
&& hasChangedEvidence(locations.get(check.path), check.evidence)).slice(0, MAX_PENDING_CHECKS);
if (pending.length) {
lines.push("\n**" + copy.pending + "**");
for (const check of pending) lines.push("- " + plainMarkdown(shortText(check, 75)));
for (const check of pending) {
lines.push("- " + plainMarkdown(shortText(check.scenario, 75)) + " · " + plainMarkdown(shortText(check.consequence, 60)));
}
}
let decision = assessment.decision;
let reason = plainMarkdown(shortText(assessment.reason, 110));
const hasTestEvidence = ci.conclusion === "success" && ci.steps?.some((step) => step.conclusion === "success");
let decision = "merge";
let reason = copy.noFindings;
if (mergeable === false) {
decision = "changes";
reason = copy.conflict;
} else if (decision === "merge" && (incomplete || mainMoved || !hasTestEvidence || pending.length)) {
} else if (ciFailed) {
decision = "changes";
reason = copy.fixCI;
} else if (hasFindings) {
decision = "changes";
reason = copy.fixFindings;
} else if (assessment.decision === "decline") {
decision = "decline";
reason = plainMarkdown(shortText(assessment.reason, 110));
} else if (pending.length) {
decision = "verify";
if (mainMoved) reason = copy.mainMoved;
else if (!hasTestEvidence) reason = copy.ciRequired;
else if (pending.length) reason = copy.pendingRequired;
else reason = copy.incomplete;
reason = copy.pendingRequired;
} else if (incomplete) {
decision = "inspect";
reason = copy.incomplete;
} else if (!ciPassed) {
decision = "awaitCI";
reason = copy.ciRequired;
}
lines.push("\n**" + copy.recommendation + " · " + copy[decision] + "** " + reason);
return lines.join("\n");
@@ -518,8 +556,7 @@ export async function run() {
waitForCI(github, repoPath, pull, number, { skipCI: hasSkipCIToken(headCommitMessage) }),
]);
const mainline = await mainlineContext(github, repoPath, pull, files);
const marker = MARKER_PREFIX + [revision, mainline.sha, ci.id ?? "none",
ci.attempt ?? "none", ci.conclusion ?? ci.status].join(":") + " -->";
const marker = reviewMarker(revision, mainline.sha, ci);
const history = await fetchReviewHistory(github, repoPath, path, pull.head.sha, marker);
if (history.alreadyReviewed) {
console.log("This PR revision has already been reviewed");
@@ -543,6 +580,7 @@ export async function run() {
head: pull.head.sha,
base: { branch: pull.base.ref, reportedSha: pull.base.sha, mergeable: pull.mergeable },
mainline: comparison,
goVersion: (await readFile("go.mod", "utf8")).match(/^go (\S+)/m)?.[1],
coverage: { reviewedFiles: diffs.length, changedFiles: pull.changed_files, partialFiles: partial },
ci: { ...ci, changesCIWorkflow: files.some((file) => file.filename === ".github/workflows/ci.yml") },
diffs,
@@ -556,9 +594,24 @@ export async function run() {
const copy = localizedCopy(assessment);
const comments = inlineComments(findings, locations);
const coverage = copy.scope + " " + diffs.length + "/" + pull.changed_files + (partial ? " (" + partial + " " + copy.partial + ")" : "");
const result = comments.length ? copy.inline + " · " + comments.length
: findings.length ? copy.unlocated : diffs.length ? copy.noFindings : copy.noDiff;
const result = comments.length ? copy.inline + " · " + comments.length : diffs.length ? "" : copy.noDiff;
let finalCI = ci;
if (ci.conclusion !== "success") {
try {
finalCI = await waitForCI(github, repoPath, pull, number, { wait: false });
} catch (error) {
console.warn("Could not refresh CI: " + error.message);
}
}
const finalMarker = reviewMarker(revision, mainline.sha, finalCI);
if (finalMarker !== marker) {
const { alreadyReviewed } = await fetchReviewHistory(github, repoPath, path, pull.head.sha, finalMarker);
if (alreadyReviewed) {
console.log("This PR revision has already been reviewed with the latest CI result");
return;
}
}
const latestPR = await currentPR();
if (!latestPR) {
console.log("PR changed while the model was reviewing it");
@@ -569,14 +622,19 @@ export async function run() {
const mainCoverage = mainline.comparisonUnavailable ? copy.comparisonUnavailable
: mainline.overlappingFiles > mainline.overlappingDiffs.length || mainline.partialOverlaps || mainline.fileListMayBeTruncated
? copy.comparisonPartial : "";
const summary = marker + "\n## " + copy.heading + "\n\n" + copy.mainline + " `" + mainline.sha.slice(0, 12) + "` · " + coverage
+ (mainCoverage ? " · " + mainCoverage : "")
+ "\n\n" + reviewSummary(copy, assessment, ci, !diffs.length || diffs.length < pull.changed_files || partial > 0
|| Boolean(mainCoverage), mainMoved, latestPR.mergeable);
const scopeNotes = [mainCoverage, mainMoved ? copy.mainMoved : ""].filter(Boolean);
const assessmentSummary = reviewSummary(copy, assessment, finalCI, {
incomplete: !diffs.length || diffs.length < pull.changed_files || partial > 0,
mergeable: latestPR.mergeable,
hasFindings: comments.length > 0,
locations,
});
const summary = finalMarker + "\n## " + copy.heading + "\n\n" + copy.mainline + " `" + mainline.sha.slice(0, 12) + "` · " + coverage
+ (scopeNotes.length ? " · " + scopeNotes.join(" ") : "") + "\n\n" + assessmentSummary;
const review = {
event: "COMMENT",
commit_id: pull.head.sha,
body: summary + "\n\n" + result,
body: result ? summary + "\n\n" + result : summary,
};
if (comments.length) review.comments = comments;
try {
+112 -16
View File
@@ -9,6 +9,7 @@ import {
reviewSummary,
selectDiffs,
shouldSkipAutoReview,
waitForCI,
} from "./pr-review.mjs";
test("hasSkipCIToken recognizes standard skip tokens case-insensitively", () => {
@@ -52,9 +53,12 @@ test("diffAnchors includes added, deleted, and context lines while selectDiffs t
const comments = inlineComments(
[
{ path: "a.go", side: "RIGHT", line: 10, priority: "P2", body: "context anchor works" },
{ path: "a.go", side: "LEFT", line: 11, priority: "P3", body: "deleted anchor works" },
{ path: "a.go", side: "RIGHT", line: 99, priority: "P1", body: "out of range dropped" },
{ path: "a.go", side: "RIGHT", line: 10, priority: "P2", impact: "correctness", trigger: "Existing configuration",
evidence: { side: "RIGHT", line: 11, text: "newLine" }, body: "Context anchor works" },
{ path: "a.go", side: "LEFT", line: 11, priority: "P2", impact: "compatibility", trigger: "Upgrading from an old release",
evidence: { side: "LEFT", line: 11, text: "oldLine" }, body: "Deleted anchor works" },
{ path: "a.go", side: "RIGHT", line: 99, priority: "P1", impact: "data", trigger: "Restoring a disk",
evidence: { side: "RIGHT", line: 11, text: "newLine" }, body: "Out of range is dropped" },
],
selected.locations,
);
@@ -63,6 +67,28 @@ test("diffAnchors includes added, deleted, and context lines while selectDiffs t
assert.equal(comments[1].side, "LEFT");
});
test("inlineComments drops nits and unsupported evidence and limits findings to three", () => {
const patch = "@@ -1 +1,5 @@\n existing guard\n+crash first\n+crash second\n+crash third\n+crash fourth";
const locations = new Map([["a.go", diffAnchors(patch)]]);
const finding = {
path: "a.go", side: "RIGHT", line: 2, priority: "P2", impact: "correctness", trigger: "Starting an existing VM",
evidence: { side: "RIGHT", line: 2, text: "crash first" }, body: "Starting an existing VM fails",
};
const comments = inlineComments([
{ ...finding, priority: "P3" },
{ ...finding, impact: "style" },
{ ...finding, trigger: "" },
{ ...finding, evidence: { side: "RIGHT", line: 1, text: "existing guard" } },
{ ...finding, evidence: { side: "RIGHT", line: 2, text: "invented cause" } },
finding,
finding,
...["second", "third", "fourth"].map((name, index) => ({
...finding, line: index + 3, evidence: { side: "RIGHT", line: index + 3, text: "crash " + name },
})),
], locations);
assert.deepEqual(comments.map(({ line }) => line), [2, 3, 4]);
});
test("extractPreviousReview returns latest bot review with stripped marker and changed files", () => {
const reviews = [
{
@@ -100,18 +126,88 @@ test("extractPreviousReview returns latest bot review with stripped marker and c
assert.deepEqual(prev.changedFilesSincePreviousReview, ["internal/app/a.go"]);
});
test("reviewSummary overrides merge recommendation on conflicts or missing CI", () => {
const assessment = {
value: "good",
upgrade: "safe",
ui: "ok",
implementation: "clean",
decision: "merge",
reason: "looks ready",
pending_checks: [],
const mergeAssessment = {
value: "Adds a needed feature", upgrade: "", ui: "", implementation: "", decision: "merge",
reason: "The change is ready", pending_checks: [],
};
const passingCI = { status: "completed", conclusion: "success", steps: [{ name: "CI tests", conclusion: "success" }] };
const fullReview = { mergeable: true, incomplete: false, hasFindings: false, locations: new Map() };
test("the final CI refresh does one lookup and can pick up a passing rerun", async () => {
const pull = {
base: { ref: "main", repo: { default_branch: "main" } },
head: { sha: "head", ref: "feature", repo: { full_name: "fork/Reims-Go" } },
};
const conflictText = reviewSummary(chinese, assessment, { status: "completed", conclusion: "success", steps: [{ name: "CI tests", conclusion: "success" }] }, false, false, false);
assert.match(conflictText, /修改后再审/);
const noCIText = reviewSummary(chinese, assessment, { status: "unavailable" }, false, false, true);
assert.match(noCIText, /待实测后再决定/);
const run = { id: 100, run_attempt: 2, head_sha: "head", head_branch: "feature", head_repository: pull.head.repo, pull_requests: [] };
let calls = 0;
const queued = await waitForCI(async () => {
calls++;
return { data: { workflow_runs: [{ ...run, status: "queued" }] } };
}, "/repos/test/Reims-Go", pull, 42, { wait: false });
assert.equal(queued.status, "queued");
assert.equal(calls, 1);
const passed = await waitForCI(async (route) => route.endsWith("/100/attempts/2/jobs")
? { data: { jobs: [{ name: "verify", conclusion: "success", steps: passingCI.steps }] } }
: { data: { workflow_runs: [{ ...run, status: "completed", conclusion: "success" }] } },
"/repos/test/Reims-Go", pull, 42, { wait: false });
assert.equal(passed.conclusion, "success");
assert.equal(passed.attempt, 2);
assert.match(reviewSummary(chinese, mergeAssessment, passed, fullReview), /可以合并/);
});
test("reviewSummary distinguishes CI awaiting action, waiting and failure", () => {
const approval = reviewSummary(chinese, mergeAssessment, { status: "completed", conclusion: "action_required", id: 1 }, fullReview);
assert.match(approval, /CI 需要人工处理/);
assert.match(approval, /代码未见阻塞,等待 CI/);
assert.doesNotMatch(approval, /失败|必做实测|先验证关键场景/);
for (const ci of [{ status: "unavailable" }, { status: "queued", id: 1 }, { status: "completed", conclusion: "cancelled", id: 1 }]) {
const waiting = reviewSummary(chinese, mergeAssessment, ci, fullReview);
assert.match(waiting, /代码未见阻塞,等待 CI/);
assert.doesNotMatch(waiting, /修改后再审|先验证关键场景/);
}
const failed = reviewSummary(chinese, mergeAssessment, { ...passingCI, conclusion: "failure" }, fullReview);
assert.match(failed, /修改后再审/);
assert.match(failed, /处理 CI 失败项/);
});
test("reviewSummary only recommends fixes for verified findings or CI failures and omits empty sections", () => {
const assessment = { ...mergeAssessment, decision: "changes", reason: "Refactor the redundant guard" };
const clean = reviewSummary(chinese, assessment, passingCI, fullReview);
assert.match(clean, /可以合并/);
assert.doesNotMatch(clean, /修改后再审/);
assert.doesNotMatch(clean, /Refactor|界面规范与风格|实现精简与重复逻辑/);
const issue = reviewSummary(chinese, mergeAssessment, passingCI, { ...fullReview, hasFindings: true });
assert.match(issue, /修改后再审/);
assert.match(issue, /实质问题/);
const conflict = reviewSummary(chinese, mergeAssessment, passingCI, { ...fullReview, mergeable: false });
assert.match(conflict, /修改后再审.*合并冲突/);
const partial = reviewSummary(chinese, mergeAssessment, passingCI, { ...fullReview, incomplete: true });
assert.match(partial, /先审完剩余改动/);
assert.doesNotMatch(partial, /先验证关键场景/);
});
test("reviewSummary reserves pre-merge manual checks for supported risks in changed code", () => {
const context = { ...fullReview, locations: new Map([["disk.go", diffAnchors("@@ -1 +1,2 @@\n existing guard\n+replaceDisk()")]]) };
const disk = {
path: "disk.go", evidence: { side: "RIGHT", line: 2, text: "replaceDisk()" }, impact: "data",
scenario: "Force a host write failure and verify the old disk reopens.", consequence: "Data becomes inaccessible after a failed rollback.",
};
const assessment = { ...mergeAssessment, decision: "verify", reason: "Retest everything", pending_checks: [
"Re-run CI and check small-window styling.",
{ ...disk, impact: "style", scenario: "Check label width." },
{ ...disk, path: "unknown.go", scenario: "Unrelated host test." },
{ ...disk, evidence: { side: "RIGHT", line: 1, text: "existing guard" }, scenario: "Verify an unchanged guard." },
] };
const clear = reviewSummary(chinese, assessment, passingCI, context);
assert.match(clear, /可以合并/);
assert.doesNotMatch(clear, /合并前必做实测|先验证关键场景|Retest everything/);
const blocked = reviewSummary(chinese, { ...assessment, pending_checks: [...assessment.pending_checks, disk] }, passingCI, context);
assert.match(blocked, /合并前必做实测/);
assert.match(blocked, /Force a host write failure.*Data becomes inaccessible/);
assert.match(blocked, /先验证关键场景/);
assert.doesNotMatch(blocked, /Re-run CI|label width|Unrelated host test|unchanged guard/);
});
+67
View File
@@ -0,0 +1,67 @@
name: Daily Alpha Release
# Every day at 00:00 Beijing time (16:00 UTC), build an alpha from the newest
# `fix:` / `fix(scope):` commit on main. Nothing is built when that commit is
# already in a stable release or already has a published alpha. GitHub may
# start scheduled runs some minutes late under load.
on:
schedule:
- cron: "0 16 * * *"
workflow_dispatch:
inputs:
dry_run:
description: "Only report which commit and tag would be used"
type: boolean
default: false
permissions:
contents: read
concurrency:
group: alpha-release
cancel-in-progress: false
jobs:
plan:
runs-on: ubuntu-latest
permissions:
contents: write
outputs:
build: ${{ steps.resolve.outputs.build }}
tag: ${{ steps.resolve.outputs.tag }}
steps:
- uses: actions/checkout@v4
with:
ref: main
fetch-depth: 0
- name: Find newest fix commit and alpha tag
id: resolve
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
shell: pwsh
run: ./scripts/resolve-alpha-build.ps1 -Repo $env:GITHUB_REPOSITORY
- name: Push alpha tag
if: steps.resolve.outputs.build == 'true' && steps.resolve.outputs.new_tag == 'true' && !inputs.dry_run
env:
TAG: ${{ steps.resolve.outputs.tag }}
COMMIT: ${{ steps.resolve.outputs.commit }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
# Tags pushed with GITHUB_TOKEN do not trigger the tag-push release run,
# so the release job below is the only build for this tag.
git tag $env:TAG $env:COMMIT
if ($LASTEXITCODE -ne 0) { throw "git tag $env:TAG failed ($LASTEXITCODE)" }
git push origin "refs/tags/$env:TAG"
if ($LASTEXITCODE -ne 0) { throw "git push refs/tags/$env:TAG failed ($LASTEXITCODE)" }
release:
needs: plan
if: needs.plan.outputs.build == 'true' && !inputs.dry_run
permissions:
contents: write
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.plan.outputs.tag }}
+1 -19
View File
@@ -100,27 +100,10 @@ jobs:
Write-Host "Resolved DEV_VERSION=$devVersion (commit=$shortSha, baseStable=$baseStableTag)"
- name: Generate dev release notes
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$devVersion = $env:DEV_VERSION
$runtimeTag = ''
$runtimeTitle = ''
try {
$rels = gh release list -R $env:GITHUB_REPOSITORY --limit 100 --json tagName,name,isPrerelease,isDraft,createdAt | ConvertFrom-Json
$stable = $rels |
Where-Object { $_.tagName -like 'runtime-*' -and -not $_.isPrerelease -and -not $_.isDraft } |
Sort-Object createdAt -Descending |
Select-Object -First 1
if ($stable) {
$runtimeTag = $stable.tagName
$runtimeTitle = if ($stable.name) { $stable.name } else { $stable.tagName }
}
} catch {
Write-Warning "Could not query latest stable runtime release: $_"
}
New-Item -ItemType Directory -Force -Path .debug/runs/dev-release | Out-Null
$notesFile = Join-Path $PWD '.debug/runs/dev-release/release-notes-dev.md'
& ./scripts/build-release-notes.ps1 `
@@ -129,8 +112,7 @@ jobs:
-PrevTag $env:BASE_STABLE_TAG `
-Commit $env:DEV_COMMIT `
-Repo $env:GITHUB_REPOSITORY `
-StableRuntimeTag $runtimeTag `
-StableRuntimeTitle $runtimeTitle `
-DiscoverStableRuntime `
-OutFile $notesFile
"RELEASE_NOTES_FILE=$notesFile" | Out-File -FilePath $env:GITHUB_ENV -Append
Write-Host "Generated dev release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $devVersion"
+13 -21
View File
@@ -9,6 +9,12 @@ on:
tag:
description: "Release tag to build & publish (e.g. v0.2.9 or v0.2.9-alpha.1)"
required: true
workflow_call:
inputs:
tag:
description: "Existing release tag to build & publish"
required: true
type: string
permissions:
contents: write
@@ -22,7 +28,7 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || '' }}
ref: ${{ inputs.tag || '' }}
fetch-depth: 0
- uses: actions/setup-go@v5
@@ -40,10 +46,14 @@ jobs:
cache-dependency-path: frontend/pnpm-lock.yaml
- name: Resolve version tag and channel
env:
# Set for manual runs and for calls from the daily alpha workflow; empty for tag pushes.
INPUT_TAG: ${{ inputs.tag }}
REF_NAME: ${{ github.ref_name }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$tag = if ('${{ github.event_name }}' -eq 'workflow_dispatch') { '${{ inputs.tag }}' } else { '${{ github.ref_name }}' }
$tag = if ($env:INPUT_TAG) { $env:INPUT_TAG } else { $env:REF_NAME }
$tag = $tag.Trim()
if ($tag -match '^v[0-9]+\.[0-9]+\.[0-9]+$') {
$channel = 'stable'
@@ -57,28 +67,11 @@ jobs:
Write-Host "Resolved tag=$tag channel=$channel"
- name: Generate release notes
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$tag = $env:RELEASE_TAG
$channel = $env:RELEASE_CHANNEL
$runtimeTag = ''
$runtimeTitle = ''
try {
$rels = gh release list -R $env:GITHUB_REPOSITORY --limit 100 --json tagName,name,isPrerelease,isDraft,createdAt | ConvertFrom-Json
$stable = $rels |
Where-Object { $_.tagName -like 'runtime-*' -and -not $_.isPrerelease -and -not $_.isDraft } |
Sort-Object createdAt -Descending |
Select-Object -First 1
if ($stable) {
$runtimeTag = $stable.tagName
$runtimeTitle = if ($stable.name) { $stable.name } else { $stable.tagName }
}
} catch {
Write-Warning "Could not query latest stable runtime release: $_"
}
New-Item -ItemType Directory -Force -Path .debug/runs/release | Out-Null
$notesFile = Join-Path $PWD ".debug/runs/release/release-notes-$tag.md"
& ./scripts/build-release-notes.ps1 `
@@ -86,8 +79,7 @@ jobs:
-Channel $channel `
-ChangelogPath 'CHANGELOG.md' `
-Repo $env:GITHUB_REPOSITORY `
-StableRuntimeTag $runtimeTag `
-StableRuntimeTitle $runtimeTitle `
-DiscoverStableRuntime `
-OutFile $notesFile
"RELEASE_NOTES_FILE=$notesFile" | Out-File -FilePath $env:GITHUB_ENV -Append
Write-Host "Generated $channel release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $tag"
+1
View File
@@ -12,6 +12,7 @@
| 界面、状态模型、生产文案和操作反馈 | 产品与界面设计规范 | [docs/design-guidelines.md](docs/design-guidelines.md) |
| 插件、驱动扩展接口、权限和分发 | 插件系统架构 | [docs/plugin-architecture.md](docs/plugin-architecture.md) |
| 测试选择、构建检查、冒烟和并发隔离 | 测试 | [docs/testing.md](docs/testing.md) |
| 网络模式、Npcap 桥接、出口热切和驱动安装 | 网络管理 | [docs/networking.md](docs/networking.md) |
| 提交、PR 描述、跨仓审查和合并检查 | PR 变更归属审查 | [docs/pr-review-guidelines.md](docs/pr-review-guidelines.md) |
| PR 验证记录和合并前核对 | PR 模板 | [.github/PULL_REQUEST_TEMPLATE.md](.github/PULL_REQUEST_TEMPLATE.md) |
| 用户可见变更、更新日志与发布说明 | 更新日志编写与发布 | [docs/changelog.md](docs/changelog.md) |
+84
View File
@@ -4,6 +4,90 @@
Client releases are listed newest first. Release notes for portable runtimes (`runtime-*`) are available on [GitHub Releases](https://github.com/Nwflower/Reims-Go/releases).
## v0.2.12 — 2026-12-03
[中文](#cn-v0.2.12) | [English](#en-v0.2.12)
<h3 id="cn-v0.2.12">新增功能</h3>
- 新增默认启用的「虚拟机交互」扩展,统一处理虚拟机截图、鼠标、键盘与文本输入;新增按虚拟机授权的插件控制通道和 MCP 服务。 — [@bvzrays](https://github.com/bvzrays)
- 「帮助」菜单和「关于」页新增官方网站与使用文档入口,按界面语言打开 [reims.dev](https://reims.dev/) 的中文或英文页面。 — [@Nwflower](https://github.com/Nwflower)
- 可为每台虚拟机指定目标显示器。目标显示器断开时,窗口回退到主显示器([#63](https://github.com/Nwflower/Reims-Go/pull/63))。 — [@reiasu2](https://github.com/reiasu2), [@yxc0915](https://github.com/yxc0915)
- 支持将 Windows 文件、文件夹、图片及文本或网址直接拖入 macOS 虚拟机窗口,提供宿主机零拷贝 WebDAV 映射、桌面直投、照片原生导入与跨应用隐身模拟粘贴。 — [@YinLiaoCo](https://github.com/YinLiaoCo)
- 虚拟机可使用 Npcap 桥接到指定的有线或无线网卡,运行中可切换桥接出口。宿主与客体可经同一网卡双向访问,需要 Npcap 1.83 或更高版本。 [#54](https://github.com/Nwflower/Reims-Go/pull/54) — [@ssdsl0126](https://github.com/ssdsl0126)
- 已安装的 macOS 虚拟机可通过 Guest Tools 使用宿主系统 DNS 或 DoH,适用于直连 DNS 受限的网络。 [#65](https://github.com/Nwflower/Reims-Go/pull/65) — [@reiasu2](https://github.com/reiasu2), [@yxc0915](https://github.com/yxc0915)
- 在 macOS 虚拟机设置中选择跟随宿主机或固定时区。同步需要更新并授权 Guest Tools。 [#66](https://github.com/Nwflower/Reims-Go/pull/66) — [@reiasu2](https://github.com/reiasu2), [@yxc0915](https://github.com/yxc0915)
- 支持 VMX 的 Windows 宿主机可为单台 macOS 虚拟机启用嵌套虚拟化。默认关闭,冷启动后生效。 [#72](https://github.com/Nwflower/Reims-Go/pull/72) — [@zhongruan0522](https://github.com/zhongruan0522), [@yxc0915](https://github.com/yxc0915)
- 虚拟机修饰键设置新增「聚焦时拦截宿主机快捷键」开关,聚焦虚拟机窗口时拦截 Windows 的 Win 与 Alt 快捷键并自动置顶低级键盘钩子。 [#73](https://github.com/Nwflower/Reims-Go/pull/73) — [@reiasu2](https://github.com/reiasu2)
### 体验优化
- 具有相同挂起兼容标识的 Alpha 修订可恢复同一主编号下保存的虚拟机挂起状态。 — [@yxc0915](https://github.com/yxc0915)
### 问题修复
- 开启无边框模式时若 `reims-ctl show` 未输出分辨率,改为从 `vm.toml` 回读已配置的 `[display].resolution`,避免界面误显示默认 `1920x1080`。 — [@YinLiaoCo](https://github.com/YinLiaoCo)
- 保护在册 CoW 副本依赖的父磁盘,删除最后一个副本后可恢复启动和磁盘修改,历史残留文件不再阻断操作。 — [@Admilkk](https://github.com/Admilkk)
- 修复 Windows 宿主机与 macOS 虚拟机之间的剪贴板同步失效问题,包括重复复制和挂起恢复后的失效。减少大图同步的重复读取和拷贝。请在虚拟机内重新安装 Guest Tools 以升级到 `v14`。 — [@reiasu2](https://github.com/reiasu2), [@yxc0915](https://github.com/yxc0915)
- 修复插件市场平台与引擎兼容校验不一致、外部主题在重启或升级后丢失、安全模式或 CLI 停用无关插件误清空当前主题,以及隐藏对话框阻断快捷键和审批弹窗在小窗口被裁切的问题。 [#93](https://github.com/Nwflower/Reims-Go/issues/93) — [@Dnyo666](https://github.com/Dnyo666)
- 修复多台桥接虚拟机同时启停时的偶发断网,以及停用 Npcap 插件后桥接通道被后台任务重新打开的问题。 — [@ssdsl0126](https://github.com/ssdsl0126)
- 修复 Npcap 桥接时宿主与虚拟机无法通过同一物理网卡的局域网地址双向访问的问题,支持有线、WLAN、IPv4 与 IPv6,需要 Npcap 1.83 或更高版本。 — [@ssdsl0126](https://github.com/ssdsl0126)
- 修复网络应用失败回滚后出口选中项与实际配置不一致的问题,补齐备用启动路径的桥接参数归属,并在网络操作结束后回收无使用者的虚拟机网络锁。 — [@ssdsl0126](https://github.com/ssdsl0126)
- Windows 内存检查计入分页文件可增长的空间,避免明明能启动的虚拟机因当前提交内存上限而被拦截。 — [@Nwflower](https://github.com/Nwflower)
- 重新导入同版本运行时失败时保留旧运行时,避免被占用的 Windows 文件导致已安装的运行时缺失。 — [@Admilkk](https://github.com/Admilkk)
- 在支持固定显示模式的运行时中,创建和设置虚拟机时可在窗口模式选择目标显示器的原生分辨率,并缩放以适应窗口。 — [@cxykhaos](https://github.com/cxykhaos)
- Windows 显卡检测仅保留当前在位且正常启动的显示适配器,避免已拔出或已禁用的显卡继续出现在可用显卡列表中。 — [@icaruszezen](https://github.com/icaruszezen)
### 安全
- 为 `ui:script` 交互主题补齐脚本 SHA-256 哈希锚定与高危审批详情(从 `v0.2.11` 升级后已启用的 `ui:script` 主题首次启动需重新确认一次),并为插件市场下载加固直连防 HTTPS 降级、体积硬上限、慢流超时、版本路径校验及陈旧缓存信任降级一致性。 [#93](https://github.com/Nwflower/Reims-Go/issues/93) — [@Dnyo666](https://github.com/Dnyo666)
- 禁止恢复旧版 TCP 桥接及管理通道,防止客体经 SLIRP 冒用 QEMU 连接;正常关机后重新启动即可迁移到 Unix 通道,旧挂起状态需确认放弃后再冷启动。 — [@ssdsl0126](https://github.com/ssdsl0126)
### 其他变更
- 新增本地定向、CI 与发布三档测试,并用真实 WebView2 首启冒烟验证客户端数据目录设置。 — [@Nwflower](https://github.com/Nwflower)
- 每天北京时间 0 点以 `main` 上最新的 `fix` 提交自动发布 Alpha 测试版,该提交已发布时跳过。 — [@Nwflower](https://github.com/Nwflower)
<h3 id="en-v0.2.12">New Features</h3>
- Add the enabled-by-default Computer Use extension for VM screenshots, pointer, keyboard, and text input, plus per-VM authorization and the MCP service. — [@bvzrays](https://github.com/bvzrays)
- Open the official website and documentation from the Help menu and the About page, in Chinese or English to match the app language. See [reims.dev](https://reims.dev/en). — [@Nwflower](https://github.com/Nwflower)
- Choose a target monitor per VM. The window falls back to the primary monitor if the target is disconnected ([#63](https://github.com/Nwflower/Reims-Go/pull/63)). — [@reiasu2](https://github.com/reiasu2), [@yxc0915](https://github.com/yxc0915)
- Support dragging Windows files, folders, images, and text or URLs directly into the macOS VM window with zero-copy host WebDAV shares, direct Desktop placement, native Photos import, and stealth cross-app paste. — [@YinLiaoCo](https://github.com/YinLiaoCo)
- Bridge a VM to a selected Ethernet or Wi-Fi adapter with Npcap and switch uplinks while the VM is running. Bidirectional host and guest access on the same adapter requires Npcap 1.83 or later. [#54](https://github.com/Nwflower/Reims-Go/pull/54) — [@ssdsl0126](https://github.com/ssdsl0126)
- Use the host DNS resolver or DoH through Guest Tools in installed macOS VMs on networks that block direct DNS. [#65](https://github.com/Nwflower/Reims-Go/pull/65) — [@reiasu2](https://github.com/reiasu2), [@yxc0915](https://github.com/yxc0915)
- Set a fixed timezone or follow the host in macOS VM settings. Sync requires updated and authorized Guest Tools. [#66](https://github.com/Nwflower/Reims-Go/pull/66) — [@reiasu2](https://github.com/reiasu2), [@yxc0915](https://github.com/yxc0915)
- Enable nested virtualization per macOS VM on Windows hosts with WHPX VMX support. Off by default, applied on cold start. [#72](https://github.com/Nwflower/Reims-Go/pull/72) — [@zhongruan0522](https://github.com/zhongruan0522), [@yxc0915](https://github.com/yxc0915)
- Add a per-VM "Capture Host Shortcuts" toggle under modifier key settings to block Windows Win/Alt shortcuts and promote the low-level keyboard hook while the VM window is focused. [#73](https://github.com/Nwflower/Reims-Go/pull/73) — [@reiasu2](https://github.com/reiasu2)
### Improvements
- Alpha revisions with the same suspend compatibility ID can resume VM state saved under the same base version. — [@yxc0915](https://github.com/yxc0915)
### Bug Fixes
- Read `[display].resolution` from `vm.toml` when `reims-ctl show` omits the resolution in borderless mode so the UI no longer falls back to `1920x1080`. — [@YinLiaoCo](https://github.com/YinLiaoCo)
- Protect backing disks used by registered CoW clones, and allow startup and disk changes once the last dependent VM is deleted even if older overlay files remain. — [@Admilkk](https://github.com/Admilkk)
- Fix clipboard sync between a Windows host and a macOS VM, including failures after copying the same content again or resuming a suspended VM. Reduce repeated reads and copies when syncing large images. Reinstall Guest Tools inside the VM to upgrade to `v14`. — [@reiasu2](https://github.com/reiasu2), [@yxc0915](https://github.com/yxc0915)
- Fix mismatched plugin market platform and engine compatibility checks, external theme loss across restarts and upgrades, unrelated safe-mode or CLI disables clearing the active theme, hidden dialogs blocking shortcuts, and approval modal list clipping on compact windows. [#93](https://github.com/Nwflower/Reims-Go/issues/93) — [@Dnyo666](https://github.com/Dnyo666)
- Fix intermittent network loss when bridged VMs start and stop concurrently, and prevent background tasks from reopening bridge channels after the Npcap plugin is disabled. — [@ssdsl0126](https://github.com/ssdsl0126)
- Fix bidirectional LAN access between the host and bridged VMs through the same physical adapter, supporting Ethernet, WLAN, IPv4, and IPv6 with Npcap 1.83 or later. — [@ssdsl0126](https://github.com/ssdsl0126)
- Keep the selected network mode and uplink aligned with the actual configuration after a failed apply, track bridge argument ownership in fallback startup, and reclaim unused per-VM network locks. — [@ssdsl0126](https://github.com/ssdsl0126)
- Windows memory checks account for available page-file growth so the current commit limit does not block VMs that can start. — [@Nwflower](https://github.com/Nwflower)
- Preserve the existing runtime when reimporting the same version fails, including when Windows has files open. — [@Admilkk](https://github.com/Admilkk)
- Allow the target display’s native resolution in windowed mode when creating or configuring a VM with a fixed-display-mode runtime, scaling it to fit the window. — [@cxykhaos](https://github.com/cxykhaos)
- Detect only present, started display adapters on Windows so unplugged or disabled GPUs no longer appear in the available GPU list. — [@icaruszezen](https://github.com/icaruszezen)
### Security
- Enforce script SHA-256 hash pinning and full high-risk approval disclosure for `ui:script` interactive themes (existing `v0.2.11` `ui:script` themes require one-time re-approval on first startup), and harden plugin market downloads with direct HTTPS-only redirects, hard size caps, stall timeouts, version path validation, and stale-cache trust parity. [#93](https://github.com/Nwflower/Reims-Go/issues/93) — [@Dnyo666](https://github.com/Dnyo666)
- Reject legacy TCP bridge and management channels to prevent guests from impersonating QEMU through SLIRP. A normal shutdown and restart migrates to Unix channels; suspended legacy VMs require confirmation to discard their suspended state before a cold start. — [@ssdsl0126](https://github.com/ssdsl0126)
### Chores
- Add focused, CI, and release test profiles, including a first-launch WebView2 smoke test that checks client data-folder setup. — [@Nwflower](https://github.com/Nwflower)
- Publish an alpha build every day at midnight Beijing time from the newest `fix` commit on `main`, skipping commits that were already released. — [@Nwflower](https://github.com/Nwflower)
## v0.2.11 — 2026-12-01
[中文](#cn-v0.2.11) | [English](#en-v0.2.11)
+8 -2
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
<a href="https://github.com/Nwflower/Reims-Go">
<a href="https://reims.dev/en">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/banner-dark.svg" />
<img src="./.github/readme/banner-light.svg" width="440" alt="Reims-Go" />
@@ -24,8 +24,14 @@
<a href="https://qm.qq.com/q/TBmRJlVbSo"><img src="https://img.shields.io/badge/QQ%20Group-1136042744-3b8cff?style=flat-square&logo=qq&logoColor=white&labelColor=1f2433" alt="QQ Group 1136042744" /></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/385884?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-385884" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/385884/daily?language=Go" alt="Nwflower%2FReims-Go | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="https://github.com/Nwflower/Reims-Go/releases/latest"><strong>Download</strong></a> ·
<a href="https://reims.dev/en">Website</a> ·
<a href="https://reims.dev/en/docs/quick-start">Docs</a> ·
<a href="#quick-start">Quick Start</a> ·
<a href="#faq">FAQ</a> ·
<a href="./CHANGELOG.md">Changelog</a> ·
@@ -163,7 +169,7 @@ Quit from the tray, then delete the exe and the data folder you chose.
## Plugins
Install themes, language packs, VM templates and more from the app's **Plugins** page; if a plugin breaks startup, launch with `reims-go --safe-mode` to skip it. To write plugins, see [`docs/plugin-architecture.md`](./docs/plugin-architecture.md).
Install themes, language packs, VM templates and more from the app's **Plugins** page, or browse them on the [website](https://reims.dev/en/plugins); if a plugin breaks startup, launch with `reims-go --safe-mode` to skip it. To write plugins, see [`docs/plugin-architecture.md`](./docs/plugin-architecture.md).
## Community
+4 -2
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
<a href="https://github.com/Nwflower/Reims-Go">
<a href="https://reims.dev/">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/banner-dark.svg" />
<img src="./.github/readme/banner-light.svg" width="440" alt="Reims-Go" />
@@ -26,6 +26,8 @@
<p align="center">
<a href="https://github.com/Nwflower/Reims-Go/releases/latest"><strong>下载</strong></a> ·
<a href="https://reims.dev/">官网</a> ·
<a href="https://reims.dev/docs/quick-start">使用文档</a> ·
<a href="#快速开始">快速开始</a> ·
<a href="#常见问题">常见问题</a> ·
<a href="./CHANGELOG.md">更新日志</a> ·
@@ -163,7 +165,7 @@ macOS 许可协议只允许在 Apple 硬件上虚拟化,请勿用于学习与
## 插件
在应用的「插件」页可以安装主题、语言包、虚拟机模板等插件;插件导致启动异常时,用 `reims-go --safe-mode` 启动即可跳过。开发插件见 [`docs/plugin-architecture.md`](./docs/plugin-architecture.md)。
在应用的「插件」页可以安装主题、语言包、虚拟机模板等插件,也可以在[官网](https://reims.dev/plugins)浏览;插件导致启动异常时,用 `reims-go --safe-mode` 启动即可跳过。开发插件见 [`docs/plugin-architecture.md`](./docs/plugin-architecture.md)。
## 社区
-7
View File
@@ -1,7 +0,0 @@
{
"group": "improvements",
"order": 0,
"authors": ["yxc0915"],
"zh": "具有相同挂起兼容标识的 Alpha 修订可恢复同一主编号下保存的虚拟机挂起状态。",
"en": "Alpha revisions with the same suspend compatibility ID can resume VM state saved under the same base version."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "new",
"order": 27,
"authors": ["reiasu2", "yxc0915"],
"zh": "已安装的 macOS 虚拟机可通过 Guest Tools 使用宿主系统 DNS 或 DoH,适用于直连 DNS 受限的网络。 [#65](https://github.com/Nwflower/Reims-Go/pull/65)",
"en": "Use the host DNS resolver or DoH through Guest Tools in installed macOS VMs on networks that block direct DNS. [#65](https://github.com/Nwflower/Reims-Go/pull/65)"
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "new",
"order": 35,
"authors": ["reiasu2", "yxc0915"],
"zh": "在 macOS 虚拟机设置中选择跟随宿主机或固定时区。同步需要更新并授权 Guest Tools。 [#66](https://github.com/Nwflower/Reims-Go/pull/66)",
"en": "Set a fixed timezone or follow the host in macOS VM settings. Sync requires updated and authorized Guest Tools. [#66](https://github.com/Nwflower/Reims-Go/pull/66)"
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "Windows 内存检查计入分页文件可增长的空间,避免明明能启动的虚拟机因当前提交内存上限而被拦截。",
"en": "Windows memory checks account for available page-file growth so the current commit limit does not block VMs that can start."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "chores",
"order": 0,
"authors": ["Nwflower"],
"zh": "新增本地定向、CI 与发布三档测试,并用真实 WebView2 首启冒烟验证客户端数据目录设置。",
"en": "Add focused, CI, and release test profiles, including a first-launch WebView2 smoke test that checks client data-folder setup."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "new",
"order": 69,
"authors": ["reiasu2"],
"zh": "虚拟机修饰键设置新增「聚焦时拦截宿主机快捷键」开关,聚焦虚拟机窗口时拦截 Windows 的 Win 与 Alt 快捷键并自动置顶低级键盘钩子。 [#73](https://github.com/Nwflower/Reims-Go/pull/73)",
"en": "Add a per-VM \"Capture Host Shortcuts\" toggle under modifier key settings to block Windows Win/Alt shortcuts and promote the low-level keyboard hook while the VM window is focused. [#73](https://github.com/Nwflower/Reims-Go/pull/73)"
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "new",
"order": 68,
"authors": ["zhongruan0522", "yxc0915"],
"zh": "支持 VMX 的 Windows 宿主机可为单台 macOS 虚拟机启用嵌套虚拟化。默认关闭,冷启动后生效。 [#72](https://github.com/Nwflower/Reims-Go/pull/72)",
"en": "Enable nested virtualization per macOS VM on Windows hosts with WHPX VMX support. Off by default, applied on cold start. [#72](https://github.com/Nwflower/Reims-Go/pull/72)"
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "new",
"order": 0,
"authors": ["reiasu2", "yxc0915"],
"zh": "可为每台虚拟机指定目标显示器。目标显示器断开时,窗口回退到主显示器([#63](https://github.com/Nwflower/Reims-Go/pull/63))。",
"en": "Choose a target monitor per VM. The window falls back to the primary monitor if the target is disconnected ([#63](https://github.com/Nwflower/Reims-Go/pull/63))."
}
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["icaruszezen"],
"zh": "Windows 显卡检测仅保留当前在位且正常启动的显示适配器,避免已拔出或已禁用的显卡继续出现在可用显卡列表中。",
"en": "Detect only present, started display adapters on Windows so unplugged or disabled GPUs no longer appear in the available GPU list."
}
+10 -4
View File
@@ -41,15 +41,17 @@ flowchart TB
虚拟机列表、详情、设置、启停、介质挂载、磁盘操作与日志读取统一按「驱动标识加实例名」路由。启动前先收集已启用插件的启动意图,任一阻塞守卫拒绝时立即中止且不改动磁盘;校验通过后由所属驱动完成启动准备并拉起虚拟机。
命令行执行 `vm start` 时默认交由桌面进程托管,以便维持剪贴板、共享目录与冷重启监视等常驻能力。桌面窗口已在运行时通过本机单实例消息无感交接;未运行时拉起隐藏在系统托盘的后台界面进程,并经数据目录内的临时状态文件回传启动结果与退出码。仅当命令行显式传入 `--data-root` 时才由当前命令进程直接启动,此时不附带常驻桥接服务。
命令行执行 `vm start` 时默认交由桌面进程托管,以便维持剪贴板、共享目录与冷重启监视等常驻能力。桌面窗口已在运行时通过本机单实例消息无感交接;未运行时拉起隐藏在系统托盘的后台界面进程,并经数据目录内的临时状态文件回传启动结果与退出码。显式指定管理器正在使用的数据目录时仍交由管理器启动;其他数据目录只允许不依赖常驻桥接的虚拟机直接启动。
客户端编译为 Windows 图形子系统程序。命令行模式下保留调用方传入的管道或文件句柄,缺失时自动挂载父终端控制台;在交互式终端中追加 `| Out-Host` 可等待命令执行完毕。
### 双通道本地控制套接字
### 宿主控制台代理与本地控制通道
便携运行时为每台运行中的虚拟机创建本地 Unix 域控制套接字。由于单个控制端点同一时刻只服务一个连接,客户端对自动键入、屏幕截图与状态迁移按虚拟机串行复用短连接,键入期间自动暂停后台截图。
便携运行时为每台运行中的虚拟机创建本地 Unix 域 QMP 套接字。内置 `builtin.computer-use` 服务按虚拟机复用 QMP 长连接并串行处理截图、鼠标、键盘和文本输入;缩略图与打字流程共用该服务,键入期间暂停后台截图。
Windows 10 缺少虚拟化分区热重置能力,客体内部重启会导致虚拟化后端异常退出。在 Windows 10 宿主机上,客户端为虚拟机附加不自动重启标志,并额外挂载一条独立的本地 Unix 域控制套接字监听重启退出事件,进程干净退出后自动重新拉起。两条通道均不使用 TCP 端口,防止虚拟机经用户态网络反向访问宿主机控制面。
L3 插件经权限核验的 Host API 请求虚拟机状态、截图和输入操作,宿主不接受插件提供的 QMP 套接字或虚拟机目录。MCP 客户端通过 `reims-go plugin connect <plugin-id> <channel>` 与桌面进程通信;Windows 命名管道按可执行文件路径和用户 SID 摘要区分,ACL 限制当前用户并拒绝远程客户端。
Windows 10 缺少虚拟化分区热重置能力,客体内部重启会导致虚拟化后端异常退出。在 Windows 10 宿主机上,客户端为虚拟机附加不自动重启标志,并额外挂载一条独立的本地 Unix 域控制套接字监听重启退出事件,进程干净退出后自动重新拉起。QMP 和插件控制通道均不使用 TCP 端口,防止虚拟机经用户态网络反向访问宿主机控制面。
### 宿客协作与目录隔离
@@ -57,6 +59,10 @@ Windows 10 缺少虚拟化分区热重置能力,客体内部重启会导致虚
共享文件夹服务对每次读写强制约束在授权根目录之内,拦截目录穿越与越界符号链接。Windows 盘符只读共享默认全部关闭;启用后同时限制只读打开标志与写请求方法、核对持久化卷标识防止盘符漂移、限制目录遍历深度,并验证目录联接与符号链接目标仍位于已授权盘符内。
### 物理出口桥接
Npcap 桥接由可停用的内置扩展提供,通过逐台虚拟机的本地 Unix 帧通道连接物理出口。有线保留客体链路层身份,无线按宿主网卡身份转换;同一物理出口共享捕获句柄,停用扩展时等待后台恢复退出并释放通道。模式、热切、宿主访问限制与驱动安装约定见[网络管理](networking.md)。
### 宿主机体检与资源约束
系统虚拟化状态通过免提权接口探测,仅在组件缺失且用户明确确认后才请求管理员授权开启。显卡探测扫描系统显示驱动中的 Vulkan 描述文件,自动剔除失效路径与虚拟显示适配器。处理器拓扑探测区分性能核、能效核与低功耗核,支持在虚拟机运行中实时调整进程亲和性。
+4
View File
@@ -40,4 +40,8 @@
3. 确定正式版版本及日期后,运行 `node scripts/changelog.mjs prepare vX.Y.Z --date YYYY-MM-DD`。命令将片段写入新版本,随后清理已写入的片段。清理中途失败时,可使用相同版本和日期重试。
4. 审阅归档后的变更和片段删除,再按正常发布流程提交与打标签。[`scripts/build-release-notes.ps1`](../scripts/build-release-notes.ps1) 按标签抽取正文,加入下载与版本对比说明。Alpha 和滚动 Dev 使用提交摘要,待发布片段留到正式版统一编入。
## Alpha 测试版
每日 Alpha 流水线在北京时间每天 0 点运行,也可以在 Actions 页面手动运行或只预演。流水线取 `main` 上最新一个主题以 `fix:`、`fix(范围):` 或 `fix!:` 开头的提交,为它打上 `vX.Y.Z-alpha.N` 标签,并按版本标签发布流程构建和发布。`vX.Y.Z` 是下一个正式版号,`N` 在同一正式版号下递增。该提交已在最新正式版中,或已有对应 Alpha 发布时,当天不构建。上次标签已推送但发布失败时,流水线沿用原标签重试。正式版发布后会删除全部 Alpha 发布及其标签。
版本标题使用 `## vX.Y.Z — YYYY-MM-DD`,最新版本在前。每节提供中文及英文跳转,按固定分组记录本次变化。历史版本的勘误直接修正在对应版本。
+2
View File
@@ -13,6 +13,8 @@
3. 由上游控制工具管理的虚拟机配置一律通过 `reims-ctl set` 写入,不直接改写 `vm.toml`,确保上游校验与引导镜像重建照常生效;敏感硬件标识(序列号、主板序列号、UUID、ROM、MAC 地址)默认隐藏且在导出排障包时强制脱敏。
4. 运行中与停机状态均可打开设置面板,每项设置明确标明「立即生效」或「下次启动生效」;运行中保存下次启动生效的改动后,虚拟机详情页汇总待生效项并提供一键重启应用入口。
网络提供关闭、NAT 与桥接。离线安装默认关闭网络,其他安装来源默认 NAT;切换模式要求目标虚拟机关机,已经运行的桥接可单独更换出口。网络设置单独应用,失败后保留恢复入口,宿主网卡配置保持不变。具体行为见[网络管理](networking.md)。
## 虚拟机状态模型
客户端在上游基础运行状态之上维护操作过渡态,每个状态在详情页头至多保留一个实底主操作按钮:
+61
View File
@@ -0,0 +1,61 @@
# 网络管理
新建向导与设置提供关闭、NAT 和桥接。桥接由内置可选扩展 `builtin.network.npcap` 提供,统一使用 Npcap,每台虚拟机独立选择有线或 WLAN 出口,不创建宿主网桥或虚拟出口网卡,不修改宿主的 IP、DNS、路由及协议绑定;停用该扩展后不残留桥接参数。
## 模式与出口
- 离线安装新建向导默认关闭网络(可在向导第 4 步改为 NAT 或桥接),避免恢复环境阶段依赖外部网络;在线恢复与本地磁盘默认使用 NAT。
- NAT 使用运行时生成的用户态网络,支持本机回环 SSH 端口转发。
- 桥接为每台虚拟机提供独立的本地 `AF_UNIX` 帧通道(`<vmDir>/bridge.sock`),经所选物理网卡收发。多台虚拟机共享同一物理出口的单一 Npcap 捕获句柄(按出口复用 `uplinkHub`),也可各自选择不同出口,无需统一迁移其他虚拟机。
- 同一出口的虚拟机通过本地非阻塞有界队列互通,不向其他出口传播广播,且单个客体阻塞不会拖慢同出口其他虚拟机。
- 更改关闭、NAT、桥接三种模式时要求目标虚拟机关机。已运行的 Npcap 桥接虚拟机可更换出口,其他虚拟机无需关机;更换出口不修改 QEMU 设备、MAC、PCI 布局或运行时参数。
运行中更换出口会关闭该虚拟机的原转发通道并在原本地通道重新打开。等待 QEMU 按 `reconnect-ms` 重连后,通过 QMP `set_link` 让主联网网卡断开两秒再接通,通知客体重新检查链路和 DHCP,期间会短暂断流;专用管理网卡不参与重连,无需更新 Guest Tools。客体使用静态地址时需自行调整。应用不宣称跨网段切换能保留现有 TCP 会话。
配置修改通过 `reims-ctl set` 保存,主网络意图记录在虚拟机目录 `.reims-go-network.json`,桥接 QEMU 参数在启动时通过参数归属账本(`.reims-go-arg-ledger.json`)注入,不污染用户自定义 `extra_args`;切回 NAT/关闭或停用 `builtin.network.npcap` 后由账本自动清理。读取既有虚拟机 MAC 时只读解析 `vm.toml` `[network]` 节,不临时开关网络。自定义主网络、重复设备或不明确的布局会停止自动修改,需由用户处理。
上游基线与运行时核验:
- 参数结构核验基线:`steelbrain/reims-vgpu` commit `3731afd9b13416a24f74ec27a90b3913aef2dcc0`([追加参数](https://github.com/steelbrain/reims-vgpu/blob/3731afd9b13416a24f74ec27a90b3913aef2dcc0/crates/reims-ctl/src/qemu.rs#L202)、[生成主网卡](https://github.com/steelbrain/reims-vgpu/blob/3731afd9b13416a24f74ec27a90b3913aef2dcc0/crates/reims-ctl/src/qemu.rs#L426)、[解析额外参数](https://github.com/steelbrain/reims-vgpu/blob/3731afd9b13416a24f74ec27a90b3913aef2dcc0/crates/reims-ctl/src/cli.rs#L1418))。
- QEMU 链路变化与 `reconnect-ms` / `AF_UNIX` 通道已在 `steelbrain/qemu-reims-vgpu` commit `4571bc5f`(当前 `stable` 运行时 `3731afd-p3`,QEMU 11.1.90)与预览运行时上实测通过。
## 依赖安装与锁协调
新建向导与网络设置显示 Npcap 安装状态和「下载并安装」入口。缺少 Npcap 时,应用网络或新建桥接虚拟机会先从 [Npcap 官网](https://npcap.com/#download) 下载固定版本的官方安装程序到数据目录缓存,校验 SHA-256 与 Authenticode 签名,再打开官方图形向导。许可、安装选项和 UAC 由用户确认;不使用仅 OEM 提供的静默安装,不随应用重新分发 Npcap 二进制。使用限制以 [Npcap 官方许可与安装说明](https://npcap.com/guide/npcap-users-guide.html) 为准。
只有安装或修复驱动时要求全部虚拟机关机,避免安装程序重载正在使用的驱动;已经安装 Npcap 时,选择多个出口没有整组关机限制。安装程序要求重启时提示用户处理,不自动重启 Windows。
锁与状态检查设计:
- 驱动安装与桥接虚拟机启动通过跨进程读写锁(`LockFileEx`)协调:NAT 与无网络虚拟机启动不获取该锁;多台桥接虚拟机可并发获取共享读锁启动;仅 Npcap 驱动安装获取独占写锁。
- 安装进程追踪仅记录 Reims-Go 自身启动的安装程序 PID 与进程创建时间,不扫描系统内无关的 `npcap-*.exe` 进程。
- 物理网卡枚举直接调用 Win32 `GetIfTable2`,同步识别有线与无线(WLAN)类型。
- 安装状态每次检查实际 DLL、驱动文件及只读服务状态,查询本身不加载 DLL。界面在 Npcap 已安装就绪后停止后台轮询,仅通过窗口焦点与可见性变化按需刷新;仅在尚未安装 Npcap 时低频检查安装进度。
创建桥接虚拟机前先准备依赖并打开、激活所选出口,此检查不发送报文。准备失败时尚未分配虚拟机,可修正问题后以原名称重试。虚拟机已创建而网络应用失败时保留虚拟机及磁盘,不自动启动,提示进入网络设置继续处理。
## 事务与恢复
每台虚拟机的网络操作使用按虚拟机粒度的内存锁与 GUI/CLI 共用的跨进程文件锁。运行中更换出口只更新本地出口记录,不调用 `reims-ctl set`;等待通道重连和主网卡通知成功后才提交新出口。取消和失败时仍尝试把主网卡恢复为接通,无法恢复时保留未完成标记。
虚拟机目录中的 `.reims-go-network.json` 保存模式、出口、通道路径及未完成事务。文件损坏或存在未完成事务时会阻止启动与普通配置修改,但网络设置页仍正常加载并保留「检查并修复」入口,关机后可直接修复重置。记录可能包含本机设备身份,不得提交仓库或原文公开。
网络错误与依赖安装进度接入现有 i18n,使用 `network.*` 词条、命名参数及 `CodedError`,提供稳定的 `E_NETWORK_*` 错误码。内置中英文,其他语言沿用语言包及回退规则;系统原始诊断按原文脱敏保留。
## 兼容性与边界
有线物理网卡默认启用混杂模式二层透传,保留客体网卡身份与原有 DHCP 标志。WLAN 受 802.11 三地址帧限制,使用宿主链路地址转换,同时学习 ARP、DHCP、IPv4、IPv6 与 NDP 地址,兼容 macOS 隐私地址及稳定 IPv6 地址的首次入站。
捕获通道通过收包事件等待数据,避免高频轮询。不支持 VLAN 干线、任意非 IP 二层协议或禁止单口多地址的上游网络策略。
宿主与桥接虚拟机可通过同一物理网卡上的局域网地址双向访问,支持有线、WLAN、IPv4 与 IPv6。本地通信保留客体链路身份,WLAN 对外通信继续使用地址转换。宿主服务需要监听对应网卡地址并满足 Windows 防火墙规则;仅监听回环地址的服务不会自动作为局域网服务开放。剪贴板、共享文件夹与输入法等宿客通信仍使用独立的 Guest Tools 管理通道。
宿客本地投递需要 Npcap 1.83 或更高版本。应用使用按句柄配置的接收侧注入,不修改 Npcap 全局注册表,也不关闭宿主网卡卸载功能。宿主发送的大 TCP 报文在本地交付前完成校验和计算和分段;ARP、IPv6 邻居发现与回放过滤由所选出口独立处理,不向其他接口代理本地流量。
主帧通道和管理通道仅使用本机 Unix 套接字,客体无法经 SLIRP 访问。接收数据前同时核对对端进程、QEMU 可执行文件与目标虚拟机的进程记录,非法连接不会抢占已就绪通道。应用拒绝恢复旧版 TCP 通道,因为进程身份校验不能区分 QEMU 自身连接和客体经 SLIRP 转发的连接。旧版运行中的虚拟机需正常关机后重新启动,自动迁移到 Unix 通道;旧版挂起的虚拟机需由用户确认放弃挂起状态,再冷启动迁移。
管理器须保持运行,重新启动后恢复既有虚拟机通道,QEMU 自动重连。停机或挂起时释放该实例的捕获引用,最后一个实例退出后关闭物理出口。CLI 使用相同数据目录时交给管理器;其他数据目录的桥接直启或恢复会明确拒绝。
## Guest Tools 管理通道
桥接虚拟机启动时通过参数归属账本自动加入专用管理网卡,沿用 Guest Tools 的认证地址与令牌。该通道用于剪贴板、共享文件夹、输入法等宿主通信;中继仅使用 `AF_UNIX` 套接字,并对两端连接均执行 QEMU 进程身份校验,启动阶段对尚未连接输入端的前置报文进行有界缓冲。管理网卡的 DHCP 仅提供本地子网地址,移除默认网关、DNS、搜索域和代理选项,并关闭 IPv6;常规联网继续使用主网卡所选出口,更换出口不停止管理通道。
关闭或 NAT 模式不添加管理网卡。已有可用 Guest Tools 无需重装,已有虚拟机在关机重启后自动迁移至账本与 `AF_UNIX` 通道。挂起恢复只重开原有 Unix 转发与管理通道,保持封存的设备参数;Guest Tools 或 `builtin.network.npcap` 停用时自动跳过管理通道恢复。
+15 -5
View File
@@ -20,7 +20,7 @@ flowchart TB
| 层级 | 运行形态 | 隔离与约束边界 |
| :--- | :--- | :--- |
| 编译期内置扩展 | 随主程序编译的模块,经同一注册表装载 | 核心默认主题始终启用;macOS 客体支持、宿客传输、剪贴板互通、输入服务与并行下载器可独立启停且停用零残留 |
| 编译期内置扩展 | 随主程序编译的模块,经同一注册表装载 | 核心默认主题始终启用;macOS 客体支持、宿客传输、剪贴板互通、输入服务、虚拟机交互与并行下载器可独立启停且停用零残留 |
| L1 声明式插件 | 纯 JSON 配置、词表、字体与静态样式资源 | 不含可执行代码,全部字段经宿主白名单与静态扫描校验 |
| 运行时包 | 原生虚拟化与工具二进制归档 | 自身不注册插件代码,仅由客体驱动以受控子进程调用 |
| L3 外部进程插件 | 每插件独立子进程,采用 `Content-Length` 分帧的双向 JSON-RPC 2.0 通信(日志走标准错误流) | 崩溃或死循环不拖垮主窗口;操作系统层面拥有当前用户完整账户权限,仅宿主接口受权限表约束 |
@@ -30,6 +30,12 @@ flowchart TB
2. Apache-2.0 客户端本体与外部组件仅通过独立子进程和协议交互,插件包、私有数据、缓存与日志全部隔离在数据目录的 `plugins/` 下。
3. 插件无权读取硬件序列号、UUID、ROM 或 MAC 地址,无权静默触发管理员提权或系统重启,也无权直接改写 `vm.toml`;插件贡献的排障数据一律经宿主脱敏后才写入排障包。
内置 `builtin.computer-use` 默认启用,通过宿主控制台代理串行处理每台虚拟机的截图、鼠标、键盘和文本输入,现有缩略图与打字入口共用该服务。它不实现 MCP 协议。
L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。官方 `reims.agent` 插件实现 MCP 工具、VM 状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向插件返回明文。
## 生命周期、参数账本与资源预算
每个启用中的插件拥有独立的作用域,注册的服务、事件订阅、界面槽位、后台监听与系统钩子均绑定释放函数;插件停用、卸载或激活失败时按逆序完整拆除。服务依赖变更时先停用失去依赖的插件,再按依赖拓扑激活就绪插件。
@@ -42,7 +48,9 @@ flowchart TB
## 主题、面板桥接与契约演进
宿主内置浅色与深色外观,同时提供三档主题扩展能力:第一档通过种子色与派生规则生成表面、文字和边框色阶,支持替换包内字体、单色图标、品牌标志与事件提示音;第二档提供面向公开部件类名(`rg-p-*`)与只读状态属性(`data-*`)的样式表及槽位/全窗图层状态装饰,由宿主锁定层叠顺序并清洗外部链接,且始终保护标题栏拖拽区、键盘焦点环与最小点击热区;第三档仅对获批 `ui:script` 高危权限的受信任主题按需加载前端交互接口,加载前自动收起桌面底层绑定全局对象。
宿主内置浅色与深色外观,同时提供三档主题扩展能力:第一档通过种子色与派生规则生成表面、文字和边框色阶,支持替换包内字体、单色图标、品牌标志与事件提示音;第二档提供面向公开部件类名(`rg-p-*`)与只读状态属性(`data-*`)的样式表及槽位/全窗图层状态装饰,由宿主锁定层叠顺序并清洗外部链接,且始终保护标题栏拖拽区、键盘焦点环与最小点击热区;第三档通过稳定的 `contributes.themes[].uiScript` 字段声明交互脚本,仅对获批 `ui:script` 高危权限的主题按需加载前端交互接口。交互脚本运行在主窗口前端环境并共享页面 DOM(并非隔离沙盒),加载前宿主会自动收起桌面底层绑定全局对象。
已激活的外部主题在重启客户端和升级插件后自动保留,并在脚本变更重新批准后带版本哈希参数重载;仅停用或卸载所属主题插件时回退内置默认主题并清空当前配色方案,安全模式或命令行停用无关插件不会影响当前主题。从市场安装并启用主题插件时,仅当当前仍处于内置默认主题才自动切换为该插件的首个主题,不覆盖用户已选的其他外部主题。
自定义界面优先采用 JSON Schema 声明式设置(支持标记敏感项、全局或按虚拟机作用域及生效时机);确需自绘界面的插件使用 `sandbox="allow-scripts"` 且禁联网的沙箱 `iframe`,通过消息桥请求通知、通用虚拟机列表、插件自有命令与多语种词包,所有本地 HTTP 服务均拒绝来自沙箱 `iframe` 或空来源的跨站请求。
@@ -58,14 +66,16 @@ flowchart TB
## 插件包、权限分级与市场分发
插件包为根目录含 `plugin.json`、`SHA256SUMS` 与可选 `SHA256SUMS.sig`(Ed25519 签名)的 `.zip` 归档,安装在 `plugins/pkgs/<id>/<version>/` 下支持多版本并存切换,私有可写数据位于 `plugins/data/<id>/`,状态文件 `plugins/state.json` 采用原子替换与备份写入且读取失败即明确报错(绝不视为空列表抹掉已有配置)。
插件包为根目录含 `plugin.json`、`SHA256SUMS` 与可选 `SHA256SUMS.sig`(Ed25519 签名)的 `.zip` 归档,安装在 `plugins/pkgs/<id>/<version>/` 下支持多版本并存切换,私有可写数据位于 `plugins/data/<id>/`,状态文件 `plugins/state.json` 采用原子替换与备份写入且读取失败即明确报错(绝不视为空列表抹掉已有配置)。清单版本号须符合语义化版本且不能包含首尾空白字符,`SHA256SUMS` 统一采用正斜杠相对路径,支持含空格的资源文件名并拒绝重复条目与反斜杠。
| 权限等级 | 典型权限 | 启用与升级要求 |
| :--- | :--- | :--- |
| 低危 | `vm:read`、`ui:notify`、`task:progress`、`fs:plugin_data`、`log:read` | 启用时展示用途说明,纯声明式语言包无需高危权限 |
| 中危 | `vm:intent`、`runtime:source`、`net:<origin>`、`ui:slot`、`input:filter`、`fs:pick` | 首次启用时由用户确认 |
| 高危 | `driver:vm`、`runtime:provider`、`process:spawn`、`vm:control`、`qmp:write`、`fs:vm_dir`、`fs:shared`、`host:clipboard`、`ui:script` | 展示可执行文件或脚本路径、SHA-256、发布者与许可证并要求显式勾选;升级新增高危权限时暂停并重新审批 |
| 高危 | `driver:vm`、`runtime:provider`、`process:spawn`、`vm:control`、`vm:screen`、`qmp:write`、`fs:vm_dir`、`fs:shared`、`host:clipboard`、`ui:script` | 市场端与已安装页统一展示风险说明、入口路径、SHA-256、发布者、许可证与能力明细并要求显式勾选;升级新增高危权限,或 L3 原生程序及 `ui:script` 交互脚本入口哈希变化时自动暂停并重新审批(仅开发链接模式跳过哈希锚定) |
所有本地导入或市场下载的插件包(包括带有内置可信签名或来自官方 HTTPS 市场索引的 `official` / `verified` 插件,第三方自定义市场镜像一律降为 `community`)在落盘前均须通过同一套事务准入检查:校验哈希与包标识防调包、拦截市场红线文件(Apple 专有镜像与密钥字面量)、禁止声明式与界面层夹带可执行程序或系统脚本、禁止 SVG 主动脚本、拦截主题样式与脚本逃逸。对 L3 原生子进程插件,界面如实告知其具备当前 Windows 账户完整执行权限,不作虚假沙箱承诺。
市场预检与本地安装共用同一套平台及版本兼容校验:平台支持 `windows-x64`、`windows/amd64`、`*` 与 `any`(不区分大小写,省略时默认全平台兼容),引擎范围同时核验 `pluginApi`、`uiApi`、`bridgeApi` 与 `reims-go`(开发构建跳过宿主版本门槛)。市场索引与插件包下载统一走直连客户端(不委派外部或并行下载器插件),遵循系统代理,拒绝向非本机明文 HTTP 的降级重定向,并对包体大小与流式读空闲施加硬上限。仅当前会话经官方 HTTPS 市场索引新鲜拉取的条目或带内置可信签名的包可获得 `official` 或 `verified` 信任级;第三方自定义镜像、冷启动未联网的磁盘缓存以及网络异常回退的陈旧缓存均降为 `community`,且卡片展示与实际安装保持一致,网络恢复后下次查询即重新拉取。
所有本地导入或市场下载的插件包在落盘前均须通过同一套事务准入检查:校验哈希与包标识防调包、拦截市场红线文件(Apple 专有镜像与密钥字面量)、禁止声明式与界面层夹带可执行程序或系统脚本、禁止 SVG 主动脚本、拦截主题样式与脚本逃逸。界面对 L3 原生子进程插件如实告知其具备当前 Windows 账户完整执行权限,对 `ui:script` 交互主题如实告知其在主窗口运行并可访问界面内容,均不作虚假沙箱承诺。
用户可通过桌面端「插件」页或 `reims-go plugin` 子命令完成搜索、安装、更新、打包签名(`pack`)、本地目录热重载链接(`link`)、启停、移除、语言包脚手架校验(`locale init|check`)与安全体检(`doctor`)。当第三方插件导致启动异常时,以 `reims-go --safe-mode` 启动即可跳过全部第三方插件并回到内置默认主题;客户端同时通过启动哨兵文件自动检测上次插件初始化崩溃并在下次启动时提示进入安全模式。
+6 -2
View File
@@ -56,7 +56,11 @@
[PR Review](../.github/workflows/pr-review.yml) 在 PR 新建、重新打开、转为就绪或推送新提交时运行,覆盖来自 Fork 的 PR。草稿 PR 以及提交说明包含 `[skip ci]`、`[ci skip]`、`[no ci]`、`[skip actions]` 或 `[actions skip]` 的推送不会触发自动审核,仍可通过手动触发运行。`github-actions[bot]` 提交 `Comment` 类型的 Review,能定位到改动行或相邻上下文行的问题会随附行内评论。审核建议供维护者参考,合并仍按本仓库的人工审查流程执行。
自动审核先读取默认分支最新提交并对照同路径的主线改动,判断合并价值和功能完整性,再检查旧版数据及配置升级、UI 一致性、重复逻辑和可精简分支。若同一 PR 已有上一轮自动审核记录,本次会把上一轮摘要、行内问题和增量变更文件带入上下文,优先核对旧问题是否已修复,不再对未改动代码反复新增次要建议。审核附上当前 PR 提交的 CI 记录、待实测的关键用例和合并建议。回复优先跟随作者在 PR 正文中实际使用的语言,其次参考标题,无法判断时使用英文。工作流在未检测到 CI 运行时最多等待约一分钟,检测到运行后最多等待约四分钟;CI 的现有 Go、前端、桌面构建及 WebView2 冒烟步骤提供实测证据,宿主机、升级和运行时场景以各自实际覆盖为准。
自动审核先对照最新主线判断合并价值与功能完整性,再检查升级兼容性、UI 和实现是否会引入实质回归。行内意见需要指明可达的触发条件、实际影响及对应改动行。格式、命名和单纯的重构建议不发布为行内问题。复审会核对上一轮问题的解决状态,避免重复发布同一根因。
审核附上当前 PR 提交的 CI 记录、合并前必做实测和合并建议。CI 排队、需要人工处理或缺少通过记录时,代码无实质问题的结论为「代码未见阻塞,等待 CI」。只有当前差异支持且失败会产生实质影响的场景才列为合并前必做实测。PR 差异覆盖不全时提示补齐审查。主线对照的范围限制单独标注。
回复优先跟随作者在 PR 正文中实际使用的语言,其次参考标题,无法判断时使用英文。工作流在未检测到 CI 运行时最多等待约一分钟,检测到运行后最多等待约四分钟。CI 尚未通过时,工作流在发布前刷新一次状态。CI 的现有 Go、前端、桌面构建及 WebView2 冒烟步骤提供实测证据,宿主机、升级和运行时场景以各自实际覆盖为准。
在目标仓库的 **Settings → Secrets and variables → Actions** 配置以下项目。
@@ -68,4 +72,4 @@
如果公开仓库的 Actions 事件策略阻止 `pull_request_target`,由仓库管理员在 **Settings → Actions → Policies** 为 `.github/workflows/pr-review.yml` 配置允许该事件的策略。工作流从默认分支加载审核脚本,将 GitHub API 返回的差异作为文本交给 [OpenCode](https://docs.bigmodel.cn/cn/coding-plan/tool/opencode),模型工具全部禁用。GitHub 写入权限仅用于提交审核意见。[GitHub 事件策略文档](https://docs.github.com/en/actions/how-tos/administer/control-workflow-execution)
工作流合入默认分支并配置密钥后,可在 **Actions → PR Review → Run workflow** 输入一个开放 PR 的编号。单次读取最多 300 个变更文件,PR 文本差异总量约 40 万字符,单文件约 3.6 万字符。审核会显示范围,使用 512,000 tokens 的模型上下文预算和 32,768 tokens 的输出上限。请求采用低档推理强度,给审核正文保留输出预算。公开审核摘要包含四项短结论和最多三条待实测项,随附最多五条行内意见。PR 版本、对照主线和 CI 结果相同时会跳过重复审核。缺少密钥时跳过,模型请求或发布失败时在 Actions 中显示失败。
工作流合入默认分支并配置密钥后,可在 **Actions → PR Review → Run workflow** 输入一个开放 PR 的编号。单次读取最多 300 个变更文件,PR 文本差异总量约 40 万字符,单文件约 3.6 万字符。审核会显示范围,使用 512,000 tokens 的模型上下文预算和 32,768 tokens 的输出上限。请求采用低档推理强度,给审核正文保留输出预算。公开审核只显示有实质内容的摘要项,随附最多三条待实测项及三条 P1/P2 行内意见。PR 版本、对照主线和 CI 结果相同时会跳过重复审核。缺少密钥时跳过,模型请求或发布失败时在 Actions 中显示失败。
+1 -1
View File
@@ -12,7 +12,7 @@
| 核对发布候选 | `node scripts/test.mjs release` | 使用 `desktop,production` 构建标签运行同一套 Go 检查,禁用测试结果缓存并随机化用例顺序 |
| Windows 桌面冒烟 | `node scripts/test.mjs webview2 build/bin/reims-go.exe` | 启动已构建的客户端,在真实 WebView2 中完成首启数据目录设置 |
GitHub CI 额外检查变更日志、工作区纪律、前端生产打包、Windows GUI 可执行文件的 `version` 输出与 WebView2 首启。`main` 的滚动版复用同一提交的 CI 测试,手动构建会跑 CI 测试并冒烟。带版本标签的发布先跑发布候选测试,再对待发布的 EXE 运行桌面冒烟。两个发布流程都在上传前验证实际 EXE 的版本、ZIP 内的文件和 SHA-256 校验和。
GitHub CI 额外检查变更日志、工作区纪律、前端生产打包、Windows GUI 可执行文件的 `version` 输出与 WebView2 首启。`main` 的滚动版复用同一提交的 CI 测试,手动构建会跑 CI 测试并冒烟。带版本标签的发布与每日 Alpha 先跑发布候选测试,再对待发布的 EXE 运行桌面冒烟。两个发布流程都在上传前验证实际 EXE 的版本、ZIP 内的文件和 SHA-256 校验和。
桌面冒烟需要已安装 WebView2 Runtime 的 Windows 桌面会话。测试通过 Windows UI Automation 填入独立的数据目录、点击继续,检查配置和目录指针落盘,并等待运行时设置页渲染。每次运行使用独立的 WebView2 配置目录。失败时,测试入口打印保留的目录,应用日志在其中的 `app.log`。
+2 -2
View File
@@ -1,11 +1,11 @@
{
"name": "reims-go-frontend",
"private": true,
"version": "0.2.11",
"version": "0.2.12",
"type": "module",
"scripts": {
"dev": "vite",
"test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-tasks.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs",
"test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-plugins.mjs scripts/test-tasks.mjs scripts/test-display-presets.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs",
"typecheck": "tsc --noEmit",
"bundle": "vite build && node scripts/check-ui-contract.mjs",
"build": "tsc --noEmit && pnpm run bundle",
+1 -1
View File
@@ -1 +1 @@
f0555717e9c11f4616f356c2a83bd506
f30a3646316b376820394ecddd138518
+99
View File
@@ -0,0 +1,99 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { windowDisplayPresets, fullscreenDisplayPresets, recommendedDisplayPresets, recommendedResolution, hostDisplayAdvice, canKeepDisplayPreset } =
await loadTestModule(`export * from './lib/format'`)
function profile(width, height) {
return {
primary_display: { width, height, scale_pct: 125 },
display_presets: [
{ resolution: '1920x1080', label: '1920 × 1080', hidpi: false, recommended: true },
{ resolution: '1600x900', label: '1600 × 900', hidpi: false },
],
}
}
for (const [width, height] of [[2560, 1440], [2560, 1600]]) {
test(`fixed-mode runtime offers native ${width}x${height} in a window without changing fit recommendations`, () => {
const host = profile(width, height)
const before = structuredClone(host)
const fit = recommendedDisplayPresets(host)
assert.strictEqual(windowDisplayPresets(host, false), fit)
const options = windowDisplayPresets(host, true)
assert.deepEqual(options.slice(0, fit.length), fit)
assert.deepEqual(options.at(-1), {
resolution: `${width}x${height}`, label: `${width} × ${height}`, hidpi: false, scaleToFit: true,
})
assert.equal(options.filter((p) => p.recommended).length, 1)
assert.equal(recommendedResolution(host), '1920x1080')
assert.deepEqual(host, before)
})
}
test('an existing native preset is not duplicated or relabeled', () => {
const host = profile(2560, 1440)
host.display_presets.push({ resolution: '2560x1440', label: '2560 × 1440', hidpi: false })
assert.strictEqual(windowDisplayPresets(host, true), host.display_presets)
})
test('missing or invalid target geometry keeps fit-only presets', () => {
for (const display of [undefined, { width: 0, height: 1440 }, { width: 2560, height: -1 }, { width: 1920, height: 1080 }]) {
const host = { ...profile(2560, 1440), primary_display: display }
assert.strictEqual(windowDisplayPresets(host, true), host.display_presets)
}
})
test('native guest HiDPI metadata is preserved when scaling into a window', () => {
const host = { ...profile(3840, 2160), fullscreen_hidpi: true }
const preset = windowDisplayPresets(host, true).at(-1)
assert.equal(preset.hidpi, true)
assert.equal(preset.scaleToFit, true)
})
test('window HiDPI presets suppress only the contradictory fullscreen advice', () => {
const host = { ...profile(2560, 1600), fullscreen_hidpi: true, hidpi_advice: 'fullscreen' }
const tr = (key) => key
assert.equal(hostDisplayAdvice(host, tr, windowDisplayPresets(host, false)), 'hidpiTipFullscreen')
assert.equal(hostDisplayAdvice(host, tr, windowDisplayPresets(host, true)), undefined)
assert.equal(hostDisplayAdvice({ ...host, hidpi_advice: 'scale' }, tr, windowDisplayPresets(host, true)), 'hidpiTipScale')
assert.equal(hostDisplayAdvice({ ...host, hidpi_advice: 'unavailable' }, tr, windowDisplayPresets(host, true)), 'hidpiTipUnavailable')
})
test('fullscreen round trips return to fit presets instead of implicitly opting into scaling', () => {
for (const fixedModeSupported of [false, true]) {
const host = profile(2560, 1440)
const windows = windowDisplayPresets(host, fixedModeSupported)
const full = fullscreenDisplayPresets(host)
const switchMode = (resolution, borderless) => {
const list = borderless ? full : windows
return list.some((p) => canKeepDisplayPreset(p, resolution, borderless))
? resolution
: list.find((p) => p.recommended)?.resolution ?? list[0].resolution
}
const native = switchMode('1920x1080', true)
assert.equal(native, '2560x1440')
assert.equal(switchMode(native, false), '1920x1080')
assert.equal(switchMode('1600x900', false), '1600x900')
}
const native = windowDisplayPresets(profile(2560, 1440), true).at(-1)
assert.equal(native.scaleToFit, true) // Still available for explicit window-mode selection.
assert.equal(canKeepDisplayPreset(native, '2560 × 1440', true), true)
assert.equal(canKeepDisplayPreset(native, '2560 × 1440', false), false)
})
test('new scaled window presets stay within the supported 5K bounds', () => {
for (const [width, height] of [[6016, 3384], [7680, 2160], [5120, 3202]]) {
const host = profile(width, height)
assert.strictEqual(windowDisplayPresets(host, true), host.display_presets)
}
assert.equal(windowDisplayPresets(profile(5120, 3200), true).at(-1).resolution, '5120x3200')
})
test('the effective target profile determines the added window resolution', () => {
const primary = profile(3840, 2160)
const target = { ...primary, primary_display: { width: 2560, height: 1600, scale_pct: 150 } }
assert.equal(windowDisplayPresets(target, true).at(-1).resolution, '2560x1600')
assert.equal(windowDisplayPresets(primary, true).at(-1).resolution, '3840x2160')
})
+4
View File
@@ -34,6 +34,10 @@ test('lazy i18n domain keys are always backed by domain .gen imports', () => {
const lazyEntryBasenames = new Set([
'CreateWizard.tsx',
'SettingsModal.tsx',
// 网络设置仅随延迟加载的 SettingsModal 进入,使用同一语言域。
'VMNetworkSettings.tsx',
// 由新建向导和网络设置两个延迟入口共用。
'NpcapDependency.tsx',
'AffinityDialog.tsx',
'Setup.tsx',
'RuntimeOnline.tsx',
+120
View File
@@ -0,0 +1,120 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
import { loadTestModule } from './load-test-module.mjs'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const appCSSPath = path.resolve(__dirname, '../src/styles/app.css')
const { hasVisibleDialog, isDialogElementVisible } = await loadTestModule(`export * from './lib/dialogState'`)
const { resolvePluginApprovalNotice } = await loadTestModule(`export { resolvePluginApprovalNotice } from './components/PluginParts'`)
function fakeDialog({
display = 'block',
visibility = 'visible',
ariaHidden = null,
hidden = false,
inert = false,
dataState = null,
parentElement = null,
} = {}) {
const el = {
parentElement,
getAttribute(name) {
if (name === 'aria-hidden') return ariaHidden
if (name === 'hidden') return hidden ? '' : null
if (name === 'inert') return inert ? '' : null
if (name === 'data-state') return dataState
return null
},
closest() {
return null
},
}
return { el, style: { display, visibility } }
}
test('hidden dialog elements (including ancestor display:none, inert, and closed state) do not block shortcuts', () => {
const hiddenDisplay = fakeDialog({ display: 'none' })
const hiddenVis = fakeDialog({ visibility: 'hidden' })
const hiddenCollapse = fakeDialog({ visibility: 'collapse' })
const hiddenAttr = fakeDialog({ hidden: true })
const hiddenInert = fakeDialog({ inert: true })
const hiddenAria = fakeDialog({ ariaHidden: 'true' })
const closedState = fakeDialog({ dataState: 'closed' })
const hiddenParent = fakeDialog({ display: 'none' })
const childOfHiddenParent = fakeDialog({ parentElement: hiddenParent.el })
const visibleParent = fakeDialog({ display: 'block' })
const visible = fakeDialog({ parentElement: visibleParent.el })
const styles = new Map([
[hiddenDisplay.el, hiddenDisplay.style],
[hiddenVis.el, hiddenVis.style],
[hiddenCollapse.el, hiddenCollapse.style],
[hiddenAttr.el, hiddenAttr.style],
[hiddenInert.el, hiddenInert.style],
[hiddenAria.el, hiddenAria.style],
[closedState.el, closedState.style],
[hiddenParent.el, hiddenParent.style],
[childOfHiddenParent.el, childOfHiddenParent.style],
[visibleParent.el, visibleParent.style],
[visible.el, visible.style],
])
const getStyle = (node) => styles.get(node) ?? { display: 'block', visibility: 'visible' }
for (const hiddenCase of [
hiddenDisplay,
hiddenVis,
hiddenCollapse,
hiddenAttr,
hiddenInert,
hiddenAria,
closedState,
childOfHiddenParent,
]) {
assert.equal(isDialogElementVisible(hiddenCase.el, getStyle), false)
}
assert.equal(isDialogElementVisible(visible.el, getStyle), true)
assert.equal(
hasVisibleDialog(
{ querySelectorAll: () => [hiddenDisplay.el, hiddenVis.el, childOfHiddenParent.el, closedState.el] },
getStyle,
),
false,
)
assert.equal(
hasVisibleDialog({ querySelectorAll: () => [childOfHiddenParent.el, visible.el] }, getStyle),
true,
)
})
test('L1 ui:script plugins receive accurate, style-compliant warning instead of L3 sidecar copy', () => {
const uiScriptPlugin = {
tier: 'L1',
permissions: [{ name: 'ui:script', level: 'high' }],
}
const zhNotice = resolvePluginApprovalNotice(uiScriptPlugin, null, 'zh-CN')
const enNotice = resolvePluginApprovalNotice(uiScriptPlugin, null, 'en-US')
assert.ok(zhNotice.includes('ui:script'), `expected ui:script zh notice, got: ${zhNotice}`)
assert.ok(!zhNotice.includes('L3 Sidecar'), `L1 ui:script must not show L3 Sidecar warning: ${zhNotice}`)
assert.ok(!zhNotice.includes('请'), `zh notice should follow design guidelines (no 请): ${zhNotice}`)
assert.ok(enNotice.includes('ui:script'), `expected ui:script en notice, got: ${enNotice}`)
assert.ok(!enNotice.includes('L3 Sidecar'), `L1 ui:script must not show L3 Sidecar warning: ${enNotice}`)
assert.ok(!enNotice.endsWith('.'), `en notice should not end with a trailing period: ${enNotice}`)
const l3Plugin = { tier: 'L3', permissions: [{ name: 'driver:vm', level: 'high' }] }
const l3Notice = resolvePluginApprovalNotice(l3Plugin, null, 'en-US')
assert.ok(l3Notice.includes('L3 Sidecar'), `expected L3 Sidecar warning, got: ${l3Notice}`)
const plainTheme = { tier: 'L1', permissions: [] }
assert.equal(resolvePluginApprovalNotice(plainTheme, null, 'en-US'), '')
})
test('dialog body children and plugin scan lists disable flex shrinking so tall modals scroll instead of clipping', () => {
const css = fs.readFileSync(appCSSPath, 'utf8')
assert.match(css, /\.dialog-body\s*>\s*\*\s*\{[^}]*flex-shrink\s*:\s*0/)
assert.match(css, /\.plugin-scan-section\s*>\s*\.list\s*\{[^}]*flex-shrink\s*:\s*0/)
})
+38 -4
View File
@@ -18,6 +18,7 @@ import { LogLine, appendLog } from './lib/logs'
import { macOSMajor } from './macos/macosRelease'
import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, emitThemeEvent, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine'
import { hasVisibleDialog } from './lib/dialogState'
import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats'
import { vmRefKey } from './lib/vmRef'
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types'
@@ -193,6 +194,7 @@ export const App: React.FC = () => {
logsOpenRef.current = logsOpen
const [taskMap, setTaskMap] = useState<Record<string, Task>>({})
const onTaskRef = useRef<(task: Task) => void>(() => {})
const onHostDropAckRef = useRef<(ack: { status: string; error?: string }) => void>(() => {})
const notifiedTasks = useRef(new Map<string, number>())
const [setupStage, setSetupStage] = useState<'folder' | 'runtime' | null>(null)
@@ -340,8 +342,18 @@ export const App: React.FC = () => {
useEffect(() => () => { disposeActiveThemeAndLocaleFonts() }, [])
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const pushToast = toasts.push
useEffect(() => events.onHostDrop(({ delivered, mode }) => {
if (mode !== 'l1_share' || delivered.length === 0) return
const title = delivered.length === 1
? t(locale, 'toastFileDelivered', { name: delivered[0] })
: t(locale, 'toastFilesDelivered', { n: delivered.length })
pushToast({ kind: 'ok', title })
}), [locale, pushToast])
useEffect(() => events.onHostDropAck((ack) => onHostDropAckRef.current(ack)), [])
const effectiveState = selectedVM ? (state?.transitions[vmRefKey(selectedVM)] ?? selectedVM.state) : ''
const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : []
const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
const canSuspend = state?.can_suspend ?? false
@@ -506,7 +518,7 @@ export const App: React.FC = () => {
el.dataset.sidebarCollapsed = String(!sidebarOpen)
el.dataset.safeMode = String(!!state?.safe_mode)
notifyInteractiveThemeState(uiStateRef.current)
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme])
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme, reducedMotion])
// 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.
@@ -604,6 +616,9 @@ export const App: React.FC = () => {
action: { label: tr('viewLogs'), onClick: () => openLogs('app') },
})
}
onHostDropAckRef.current = (ack) => {
if (ack.status === 'failed') fail(tr('failDrop'), ack.error || '')
}
const activeVMBusy = (name: string): VMAction | undefined => {
const ops = busyOpsRef.current.get(name)
@@ -870,7 +885,8 @@ export const App: React.FC = () => {
borderless: false,
capture: false,
audio: true,
network: !isOffline,
network: true,
network_mode: 'nat',
ssh_port: 0,
logs: true,
guest_lang: defaultGuestLang(locale),
@@ -895,6 +911,23 @@ export const App: React.FC = () => {
})
.catch((e) => {
void refresh()
const parsed = parseAppError(e)
if (parsed.code === 'E_NETWORK_CREATE_BRIDGE_PENDING') {
setSelected(name)
toasts.push({
kind: 'error',
title: tr('toastCreated', { name }),
description: parsed.summary,
errorCode: parsed.code,
rawDetail: parsed.rawDetail,
detailsLabel: tr('errRawDetailsToggle'),
copyDetailsLabel: tr('errCopyDetails'),
action: { label: tr('settings'), onClick: () => {
api.GetVMDetail(name).then((d) => { setDetail(d); setSelected(name); setShowSettings(true) }).catch((err) => fail(tr('failGeneric'), err))
} },
})
return
}
if (/\bcontext canceled\b/i.test(errText(e))) {
toasts.push({
kind: 'ok',
@@ -904,7 +937,6 @@ export const App: React.FC = () => {
})
return
}
const parsed = parseAppError(e)
toasts.push({
kind: 'error',
title: tr('failCreate', { name }),
@@ -939,7 +971,7 @@ export const App: React.FC = () => {
shortcutRef.current = (e: KeyboardEvent) => {
if (!e.ctrlKey || e.altKey || e.metaKey) return
if (appDialogOpen) return
if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return
if (hasVisibleDialog()) return
const k = e.key.toLowerCase()
if (k === 'n') { e.preventDefault(); openWizard() }
else if (k === ',' && detail && effectiveState !== 'suspended' && effectiveState !== 'suspending' && effectiveState !== 'resuming') { e.preventDefault(); setShowSettings(true) }
@@ -1318,6 +1350,7 @@ export const App: React.FC = () => {
<CreateWizard
locale={locale}
host={state.host}
fixedModeSupported={fixedModeSupported}
tasks={Object.values(taskMap)}
draft={wizardDraft}
onClose={() => { setShowWizard(false); setWizardDraft(null) }}
@@ -1334,6 +1367,7 @@ export const App: React.FC = () => {
driverID={selectedVM?.driver_id ?? ''}
stats={latestVMStatsWithDriver(selectedVM?.driver_id ?? '', detail.name)}
host={state.host}
fixedModeSupported={fixedModeSupported}
optimizations={state.optimizations}
running={effectiveState === 'running'}
onCopy={copy}
+12 -1
View File
@@ -8,7 +8,7 @@ import { Button, IconButton } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { Segmented } from '../ui/settings'
import { api } from '../wails'
import { REPO_URL } from './TitleMenus'
import { REPO_URL, siteURL } from './TitleMenus'
import type { UpdatePhase } from './UpdateCapsule'
import { BrandMark } from '../ui/themeVisuals'
@@ -242,6 +242,17 @@ export const AboutPage: React.FC<Props> = ({
<section className="section">
<div className="section-title">{tr('aboutCommunity')}</div>
<div className="list">
<div className="row">
<div className="row-main">
<div className="row-title">{tr('helpWebsite')}</div>
<div className="row-sub">{tr('aboutWebsiteSub')}</div>
</div>
<div className="row-right">
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(siteURL(locale))}>
{tr('openShort')}
</Button>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('helpProjectPage')}</div>
+70 -19
View File
@@ -1,5 +1,9 @@
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
import React, { Suspense, lazy, useEffect, useState } from 'react'
import { useNetworkPlan } from '../lib/useNetworkPlan'
import { NpcapDependency } from './NpcapDependency'
import { NetworkErrorNotice } from './NetworkErrorNotice'
import type { ParsedAppError } from '../i18n'
import '../i18n/domains/wizard.gen'
import '../i18n/domains/settings.gen'
import { I18nKey, locText, parseAppError, t } from '../i18n'
@@ -18,19 +22,20 @@ import {
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
canKeepDisplayPreset,
fullscreenDisplayPresets,
FullscreenDisplayPreset,
hidpiLooksLike,
hostDisplayAdvice,
hostDisplayDesc,
recommendedDisplayPresets,
windowDisplayPresets,
recommendedMemoryGB,
recommendedResolution,
shortGPUName,
splitLangLabel,
sshCommand,
} from '../lib/format'
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue } from '../types'
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks'
import { Button, IconButton } from '../ui/controls'
import { NumberField, PopupSelect, RangeField, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
@@ -49,6 +54,7 @@ export interface WizardDraft {
interface Props {
locale: Locale
host: HostReport
fixedModeSupported?: boolean
tasks?: Task[]
draft?: WizardDraft | null
onClose: () => void
@@ -64,6 +70,7 @@ const STEP_OF_FIELD: Record<string, number> = {
cpus: 2, memory: 2,
disk_size: 3, disk_controller: 3,
graphics: 4, gpu: 4, resolution: 4, displays: 4, ssh_port: 4,
network_mode: 4, uplink_guid: 4,
}
const stepOfIssue = (i: ValidationIssue) => STEP_OF_FIELD[i.field] ?? REVIEW_STEP
@@ -75,7 +82,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI
{ mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' },
]
export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft, onClose, onSubmit }) => {
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, tasks = [], draft, onClose, onSubmit }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [step, setStep] = useState(draft?.step ?? 1)
// Once the user has reached the review step, keep validating so step markers stay current.
@@ -88,6 +95,8 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER)
const [driverOpts, setDriverOpts] = useState<Record<string, unknown>>({})
const [driverCreating, setDriverCreating] = useState(false)
const [dependencyBusy, setDependencyBusy] = useState(false)
const [dependencyRefresh, setDependencyRefresh] = useState(0)
useEffect(() => {
let live = true
@@ -100,8 +109,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
name: 'macos-tahoe',
dir: '',
// Offline by default: installs an exact release without guest network access
// (`reims-ctl create --help`, upstream 3731afd).
// 离线安装默认关闭网络,减少恢复环境依赖;用户仍可在第 4 步改为 NAT 或桥接。
source_mode: 'offline',
macos: '',
offline: true,
@@ -122,12 +130,33 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
capture: false,
audio: true,
network: false,
network_mode: 'off',
ssh_port: 0,
logs: true,
guest_lang: defaultGuestLang(locale),
start: true,
})
const [networkTouched, setNetworkTouched] = useState(!!draft?.opts)
const set = (patch: Partial<CreateOpts>) => setOpts((o) => ({ ...o, ...patch }))
const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off')
const [networkAdapters, setNetworkAdapters] = useState<VMNetworkSettings['adapters'] | null>(null)
const [networkError, setNetworkError] = useState<ParsedAppError | null>(null)
const { plan: networkPlan, planning: networkPlanning, planError: networkPlanError } = useNetworkPlan(opts.name.trim(), networkMode, opts.uplink_guid ?? '', step >= 4 && networkMode === 'bridge', `${dependencyRefresh}:${locale}`)
const networkBlocked = networkMode === 'bridge' && (networkPlanning || !!networkPlanError || !networkPlan || !opts.uplink_guid)
useEffect(() => {
if (step !== 4 || networkMode !== 'bridge') return
let active = true
setNetworkError(null)
api.ListNetworkAdapters().then((list) => {
if (!active) return
setNetworkAdapters(list ?? [])
const connected = (list ?? []).filter((adapter) => adapter.status === 'Up')
if (connected.length === 1) setOpts((current) => current.uplink_guid ? current : { ...current, uplink_guid: connected[0].guid })
}).catch((error) => { if (active) setNetworkError(parseAppError(error)) })
return () => { active = false }
}, [step, networkMode, locale])
const windowPresets = windowDisplayPresets(host, fixedModeSupported)
const fullscreenPresets = fullscreenDisplayPresets(host)
const buildPayload = (): CreateOpts => {
const p: CreateOpts = { ...opts, offline: opts.source_mode === 'offline' }
@@ -206,7 +235,10 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
if (f) set({ [field]: f })
}
const handleCreate = () => onSubmit(buildPayload(), { opts, step: REVIEW_STEP })
const handleCreate = () => {
if (dependencyBusy || networkBlocked) return
onSubmit(buildPayload(), { opts, step: REVIEW_STEP })
}
const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : [])
const realGPUs = (host.gpus ?? []).filter((g) => g.kind !== 'virtual')
@@ -300,9 +332,13 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
checked={on}
onChange={() => set({
source_mode: s.mode,
network: s.mode !== 'offline',
...(s.mode === 'apple' ? { macos: 'tahoe' } : {}),
...(s.mode === 'offline' ? { macos: releases?.[0]?.version ?? '' } : {}),
...(!networkTouched ? {
network: s.mode !== 'offline',
network_mode: s.mode === 'offline' ? 'off' : 'nat',
ssh_port: 0,
} : {}),
})}
/>
<span className={`source-icon source-icon-${s.mode}`} aria-hidden="true"><Icon size={20} /></span>
@@ -555,20 +591,21 @@ 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), !opts.borderless ? hostDisplayAdvice(host, tr) : undefined].filter(Boolean).join(' · ') || undefined}
desc={[hostDisplayDesc(host, tr), !opts.borderless ? hostDisplayAdvice(host, tr, windowPresets) : undefined].filter(Boolean).join(' · ') || undefined}
control={
<PopupSelect
id="vm-res"
label={tr('resolution')}
value={opts.resolution}
onChange={(resolution) => set({ resolution })}
options={(opts.borderless ? fullscreenDisplayPresets(host) : recommendedDisplayPresets(host)).map((p: FullscreenDisplayPreset) => ({
options={(opts.borderless ? fullscreenPresets : windowPresets).map((p: FullscreenDisplayPreset) => ({
value: p.resolution,
label: p.label,
detail: [
p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '',
p.scaleBadge ?? '',
p.native ? tr('resNativeBadge') : '',
p.scaleToFit ? tr('resScaleToFitWindow') : '',
p.recommended ? tr('recommendedBadge') : '',
].filter(Boolean).join(' · ') || undefined,
}))}
@@ -593,14 +630,25 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
<SetGroup title={tr('wizOptions')}>
<SetRow
title={tr('networkTitle')}
desc={opts.source_mode === 'offline' ? tr('networkOfflineHint') : tr('networkDesc')}
control={<Switch label={tr('networkTitle')} checked={!!opts.network} onChange={(network) => set({ network })} />}
desc={opts.source_mode === 'offline' && networkMode === 'off' ? tr('networkOfflineHint') : tr('bridgeModeDesc')}
control={<Segmented label={tr('networkTitle')} value={networkMode} onChange={(mode) => { setNetworkTouched(true); set({ network_mode: mode, network: mode !== 'off', ssh_port: mode === 'nat' ? opts.ssh_port : 0 }) }} options={[{ value: 'off', label: tr('off') }, { value: 'nat', label: tr('networkNAT') }, { value: 'bridge', label: tr('networkBridge') }]} />}
/>
{networkMode === 'bridge' && <SetRow title={tr('bridgeUplink')} desc={tr('bridgeUplinkHint')} block={<div className="bridge-adapters" role="radiogroup" aria-label={tr('bridgeUplink')}>
<NetworkErrorNotice error={networkError} locale={locale} />
{networkAdapters === null && !networkError && <span className="muted">{tr('bridgeLoading')}</span>}
{networkAdapters?.map((adapter) => <label key={adapter.guid} className="bridge-adapter"><input type="radio" name="create-bridge-uplink" checked={opts.uplink_guid === adapter.guid} disabled={adapter.status !== 'Up'} onChange={() => set({ uplink_guid: adapter.guid })} /><span><strong>{adapter.name}</strong><span className="srow-desc">{adapter.description}</span><span className="srow-desc">{tr(adapter.status === 'Up' ? 'bridgeConnected' : 'bridgeDisconnected')} · {adapter.speed}</span></span></label>)}
{networkAdapters?.length === 0 && <span className="muted">{tr('bridgeNoAdapters')}</span>}
</div>} />}
{networkMode === 'bridge' && <>
<NpcapDependency plan={networkPlan} locale={locale} disabled={checking || driverCreating} onBusy={setDependencyBusy} onInstalled={() => setDependencyRefresh((value) => value + 1)} />
{networkPlanning && <div className="srow-desc" role="status">{tr('bridgePlanPending')}</div>}
<NetworkErrorNotice error={networkPlanError} locale={locale} />
</>}
<SetRow
title={tr('sshForward')}
desc={(opts.ssh_port ?? 0) > 0 ? <code className="inline-code">{sshCommand(opts.ssh_port ?? 0)}</code> : tr('sshOffDesc')}
disabled={!opts.network}
reason={tr('sshNeedsNetwork')}
disabled={networkMode !== 'nat'}
reason={tr(networkMode === 'bridge' ? 'sshNeedsNAT' : 'sshNeedsNetwork')}
control={
<div className="hstack">
{(opts.ssh_port ?? 0) > 0 && (
@@ -627,8 +675,8 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
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 list = borderless ? fullscreenPresets : windowPresets
const keep = list.some((p) => canKeepDisplayPreset(p, opts.resolution, borderless))
const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution
set(keep ? { borderless } : { borderless, resolution: fallback })
}}
@@ -648,6 +696,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
locale={locale}
host={host}
opts={opts}
networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name}
issues={issues}
checking={checking}
command={cmdPreview}
@@ -689,11 +738,11 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
{tr('createNow')}
</Button>
) : step < REVIEW_STEP ? (
<Button variant="primary" onClick={() => setStep(step + 1)}>{tr('next')}</Button>
<Button variant="primary" disabled={dependencyBusy || (step === 4 && networkBlocked)} onClick={() => setStep(step + 1)}>{tr('next')}</Button>
) : (
<Button
variant="primary"
disabled={checking || !!err || issues.length > 0 || !cmdPreview}
disabled={dependencyBusy || checking || !!err || issues.length > 0 || !cmdPreview || networkBlocked}
title={tr('createStartedHint')}
onClick={handleCreate}
>
@@ -706,6 +755,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
}
interface ReviewProps {
networkUplink?: string
locale: Locale
host: HostReport
opts: CreateOpts
@@ -724,7 +774,7 @@ type Row = { label: string; value: string; mono?: boolean }
const fileName = (p?: string) => (p ?? '').split(/[\\/]/).pop() || (p ?? '')
/** Step ⑤: what will be created, grouped by the step that set it, with the CLI equivalent folded away. */
const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, command, onEdit, onName, onDir, onPickDir, onStartAfter }) => {
const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, command, onEdit, onName, onDir, onPickDir, onStartAfter, networkUplink }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [copied, setCopied] = useState(false)
const onOff = (b?: boolean) => tr(b ? 'summaryOn' : 'off')
@@ -778,7 +828,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
rows: [
...graphicsRows,
{ label: tr('fieldAudio'), value: onOff(opts.audio) },
{ label: tr('fieldNetwork'), value: onOff(opts.network) },
{ label: tr('fieldNetwork'), value: opts.network_mode === 'bridge' ? `${tr('networkBridge')} · ${networkUplink ?? tr('bridgeUplink')}` : tr((opts.network_mode ?? (opts.network ? 'nat' : 'off')) === 'off' ? 'off' : 'networkNAT') },
{ label: tr('captureInput'), value: onOff(opts.capture) },
{ label: tr('summarySSH'), value: opts.ssh_port ? tr('summarySSHPort', { n: opts.ssh_port }) : tr('off') },
{ label: tr('summaryLogs'), value: onOff(opts.logs) },
@@ -869,6 +919,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
<summary><ChevronRight size={14} />{tr('commandToggle')}</summary>
<div className="review-cmd-body">
<span className="hint">{tr('commandToggleHint')}</span>
{opts.network_mode === 'bridge' && <span className="hint">{tr('bridgeCreateCommandHint')}</span>}
<div className="review-cmd-box">
<div className="code">{command || '…'}</div>
<IconButton
@@ -0,0 +1,15 @@
import React from 'react'
import { t } from '../i18n'
import type { ParsedAppError } from '../i18n'
import type { Locale } from '../types'
export function NetworkErrorNotice({ error, locale }: { error: ParsedAppError | null; locale: Locale }) {
if (!error?.summary) return null
return <div className="notice notice-error" role="alert">
<div>{error.summary}{error.code && <> <span className="selectable">[{error.code}]</span></>}</div>
{error.rawDetail && <details className="network-error-details">
<summary>{t(locale, 'errRawDetailsToggle')}</summary>
<pre className="selectable">{error.rawDetail}</pre>
</details>}
</div>
}
@@ -0,0 +1,39 @@
import React, { useState } from 'react'
import '../i18n/domains/settings.gen'
import { parseAppError, t } from '../i18n'
import type { ParsedAppError } from '../i18n'
import { NetworkErrorNotice } from './NetworkErrorNotice'
import type { Locale, VMNetworkPlan } from '../types'
import { api } from '../wails'
import { Button } from '../ui/controls'
import { SetRow } from '../ui/settings'
export function NpcapDependency({ plan, locale, disabled, onBusy, onInstalled }: {
plan: VMNetworkPlan | null
locale: Locale
disabled: boolean
onBusy: (busy: boolean) => void
onInstalled: () => void
}) {
const [busy, setBusy] = useState(false)
const [error, setError] = useState<ParsedAppError | null>(null)
if (!plan) return null
const install = async () => {
setBusy(true)
onBusy(true)
setError(null)
try { await api.InstallNpcap(); onInstalled() }
catch (err) { setError(parseAppError(err)) }
finally { setBusy(false); onBusy(false) }
}
return <>
<SetRow
title="Npcap"
desc={t(locale, plan.npcap_installed ? 'npcapInstalled' : busy ? 'npcapInstalling' : 'npcapMissing')}
disabled={disabled || busy || plan.running_vms.length > 0}
reason={plan.running_vms.length > 0 ? t(locale, 'npcapStopFirst') : undefined}
control={!plan.npcap_installed && <Button busy={busy} onClick={install}>{t(locale, 'npcapInstall')}</Button>}
/>
<NetworkErrorNotice error={error} locale={locale} />
</>
}
+60 -15
View File
@@ -2,11 +2,11 @@ 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 { Locale, MarketBrowseResult, MarketCatalogItem, PluginInfo, ScanReport } 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 { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
import { locText } from './SchemaForm'
import { WordmarkLoader } from './WordmarkLoader'
@@ -57,12 +57,16 @@ export const PluginMarket: React.FC<Props> = ({
const [visible, setVisible] = useState(PAGE_SIZE)
const [progress, setProgress] = useState<ProgressMap>({})
const [prompt, setPrompt] = useState<PluginInfo | null>(null)
const [promptReport, setPromptReport] = useState<ScanReport | 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 installingRef = useRef<Set<string>>(new Set())
const promptTargetIDRef = useRef('')
const promptQueueRef = useRef<PluginInfo[]>([])
const params = useRef({ query, kind })
params.current = { query, kind }
@@ -158,19 +162,57 @@ export const PluginMarket: React.FC<Props> = ({
return () => io.disconnect()
}, [hasMore, visible, items.length])
const openPrompt = (info: PluginInfo) => {
promptTargetIDRef.current = info.id
setPromptChecked(false)
setPromptReport(null)
setPrompt(info)
if (info.needs_approval) {
void api.ScanInstalledPlugin(info.id)
.then((rep) => {
if (promptTargetIDRef.current === info.id) setPromptReport(rep)
})
.catch((e) => console.warn('[market] ScanInstalledPlugin failed:', info.id, e))
}
}
const advancePrompt = () => {
const next = promptQueueRef.current.shift()
if (next) {
openPrompt(next)
return
}
promptTargetIDRef.current = ''
setPrompt(null)
setPromptReport(null)
}
const closePrompt = () => {
if (enabling) return
advancePrompt()
}
const install = async (item: MarketCatalogItem) => {
const id = item.entry.id
if (installingRef.current.has(id)) return
installingRef.current.add(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)
if (promptTargetIDRef.current) {
if (promptTargetIDRef.current !== info.id && !promptQueueRef.current.some((p) => p.id === info.id)) {
promptQueueRef.current.push(info)
}
} else {
openPrompt(info)
}
}
} catch (e) {
onError(tr('pluginFailMarketInstall'), e)
} finally {
installingRef.current.delete(id)
setProgress((prev) => {
const next = { ...prev }
delete next[id]
@@ -185,7 +227,7 @@ export const PluginMarket: React.FC<Props> = ({
try {
const target = prompt
await api.EnablePlugin(target.id, target.needs_approval)
setPrompt(null)
advancePrompt()
await onChanged({ enabled: target })
} catch (e) {
onError(tr('pluginFailEnable'), e)
@@ -349,10 +391,19 @@ export const PluginMarket: React.FC<Props> = ({
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) }}
dismissable={!enabling}
onClose={closePrompt}
>
<div className="dialog-body">
{(prompt.risks?.length ?? 0) > 0 ? (
{prompt.needs_approval ? (
<>
<PluginApprovalBody locale={locale} plugin={prompt} report={promptReport} />
<label className="choice">
<input type="checkbox" checked={promptChecked} onChange={(e) => setPromptChecked(e.target.checked)} />
<span>{tr('pluginApproveCheckbox')}</span>
</label>
</>
) : (prompt.risks?.length ?? 0) > 0 ? (
<>
<p className="plugin-enable-lead">{tr('pluginEnablePromptBody')}</p>
<RiskList locale={locale} risks={prompt.risks} />
@@ -360,23 +411,17 @@ export const PluginMarket: React.FC<Props> = ({
) : (
<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="ghost" disabled={enabling} onClick={closePrompt}>{tr('pluginEnableLater')}</Button>
<Button
variant="primary"
disabled={enabling || !!safeMode || (prompt.needs_approval && !promptChecked)}
onClick={() => void enablePrompted()}
>
{tr('pluginEnableNow')}
{tr(prompt.needs_approval ? 'pluginApproveConfirm' : 'pluginEnableNow')}
</Button>
</span>
</div>
+103 -3
View File
@@ -1,15 +1,32 @@
import {
Activity, BadgeCheck, Binary, Clipboard, Code2, Files, Globe,
Keyboard, Monitor, PanelsTopLeft, Search, ShieldCheck, Users,
Keyboard, Monitor, PanelsTopLeft, Search, ShieldAlert, ShieldCheck, Users,
} from 'lucide-react'
import React from 'react'
import '../i18n/domains/plugins.gen'
import { I18nKey, t } from '../i18n'
import { Locale } from '../types'
import { I18nKey, locText, t } from '../i18n'
import { Locale, PluginInfo, ScanReport } from '../types'
import { Tip } from '../ui/controls'
export { PluginAppIcon, resolvePluginVisual, type PluginVisual, type PluginVisualSource } from './PluginAppIcon'
/** Selects the accurate high-risk warning notice for a plugin (L3 native vs ui:script). */
export function resolvePluginApprovalNotice(
plugin: Pick<PluginInfo, 'tier' | 'permissions'>,
report: Pick<ScanReport, 'native_exec_notice'> | null | undefined,
locale: Locale,
): string {
if (plugin.tier === 'L3') {
return report?.native_exec_notice
? locText(report.native_exec_notice, locale, t(locale, 'pluginApproveL3Warn'))
: t(locale, 'pluginApproveL3Warn')
}
if ((plugin.permissions ?? []).some((p) => p.name === 'ui:script')) {
return t(locale, 'pluginApproveUIScriptWarn')
}
return ''
}
/** Publisher + trust-tier mark shared by Installed rows and Market cards. */
export const PluginTrustBadge: React.FC<{
locale: Locale
@@ -80,3 +97,86 @@ export const RiskList: React.FC<{ locale: Locale; risks?: string[] }> = ({ local
</ul>
)
}
/** High-risk approval disclosure shared by Installed approval and Market enable flows. */
export const PluginApprovalBody: React.FC<{
locale: Locale
plugin: PluginInfo
report?: ScanReport | null
}> = ({ locale, plugin, report }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const warnText = resolvePluginApprovalNotice(plugin, report, locale)
return (
<>
{warnText && (
<div className="notice notice-warn">
<span className="notice-main">
<ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
<span>{warnText}</span>
</span>
</div>
)}
<RiskList locale={locale} risks={plugin.risks} />
<div className="list">
<div className="row">
<div className="row-main">
<div className="row-title">{tr('pluginPublisherLicense')}</div>
<div className="row-sub">{plugin.publisher || '—'} · {plugin.license || '—'}</div>
</div>
</div>
{plugin.entry_path && (
<div className="row">
<div className="row-main">
<div className="row-title">{tr('pluginEntryPath')}</div>
<div className="row-sub mono selectable">{plugin.entry_path}</div>
</div>
</div>
)}
{plugin.entry_hash && (
<div className="row">
<div className="row-main">
<div className="row-title">SHA-256</div>
<div className="row-sub mono selectable">{plugin.entry_hash}</div>
</div>
</div>
)}
<div className="row">
<div className="row-main">
<div className="row-title">{tr('pluginRequestedPerms')}</div>
<div className="row-sub mono">
{(plugin.permissions ?? []).length > 0
? (plugin.permissions ?? []).map((p) => `${p.name} (${p.level})`).join(', ')
: '—'}
</div>
</div>
</div>
</div>
{(report?.capabilities?.length ?? 0) > 0 && (
<div className="plugin-scan-section">
<div className="plugin-scan-section-title">{tr('pluginScanCapabilitiesSection')}</div>
<div className="list">
{report!.capabilities!.map((c) => (
<div className="row" key={c.id}>
<div className="row-main">
<div className="row-title">
<span className={`badge rg-p-badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
<span>{locText(c.title, locale, c.id)}</span>
</div>
<div className="row-sub">{locText(c.summary, locale, '')}</div>
{(c.examples?.length ?? 0) > 0 && (
<div className="plugin-scan-examples mono">
{c.examples!.map((ex, i) => <div key={i}>· {ex}</div>)}
{(c.extra_count ?? 0) > 0 && (
<div className="muted">· {tr('pluginScanMoreItems', { count: c.extra_count! })}</div>
)}
</div>
)}
</div>
</div>
))}
</div>
</div>
)}
</>
)
}
+45 -47
View File
@@ -2,7 +2,7 @@ import {
AlertTriangle, CheckCircle2, FolderOpen, PackagePlus, Palette,
RefreshCw, Settings2, Shield, ShieldAlert, Sparkles, Terminal, Trash2,
} from 'lucide-react'
import React, { useEffect, useMemo, useState } from 'react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import '../i18n/domains/plugins.gen'
import '../i18n/domains/settings.gen'
import { I18nKey, t } from '../i18n'
@@ -15,7 +15,7 @@ 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 { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge } from './PluginParts'
import { SchemaForm, locText } from './SchemaForm'
// Search only earns its space once the list is long enough to scan.
@@ -57,6 +57,7 @@ export const PluginsPage: React.FC<Props> = ({
const [approveTarget, setApproveTarget] = useState<PluginInfo | null>(null)
const [approveReport, setApproveReport] = useState<ScanReport | null>(null)
const [approveChecked, setApproveChecked] = useState(false)
const approveTargetIDRef = useRef('')
const [settingsTarget, setSettingsTarget] = useState<PluginInfo | null>(null)
const [settingsValues, setSettingsValues] = useState<Record<string, unknown>>({})
const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null)
@@ -93,8 +94,10 @@ export const PluginsPage: React.FC<Props> = ({
setPlugins(list ?? [])
setContribs(ui)
setActiveTheme(th)
return { ui, th }
} catch (e) {
onError(tr('pluginFailLoad'), e)
return null
} finally {
setLoading(false)
}
@@ -116,13 +119,34 @@ export const PluginsPage: React.FC<Props> = ({
if (tags.length > 0 && !tags.includes(locale)) onLocaleSwitch?.(tags[0])
}
// Enabling a theme plugin from the market switches to its first theme only
// while the user is still on the built-in default theme.
const adoptPluginTheme = async (
p: PluginInfo,
ui: PluginUIContributions | null | undefined,
currentTheme: ActiveThemePayload | null | undefined,
) => {
if (safeMode) return
const curID = currentTheme?.theme_id ?? ''
if (curID && curID !== 'builtin.theme.default') return
const matched = (ui?.themes ?? []).find((th) => th.pluginId === p.id)
if (!matched) return
try {
await api.SetActiveTheme(matched.id, '')
setActiveTheme(await api.GetActiveTheme())
} catch (e) {
onError(tr('pluginFailSwitchTheme'), e)
}
}
const onMarketChanged = async ({ enabled }: { enabled?: PluginInfo }) => {
await reload()
onRefresh()
const latest = await reload()
if (enabled) {
onThemeChanged?.()
await adoptPluginTheme(enabled, latest?.ui, latest?.th)
adoptPluginLocale(enabled)
}
onRefresh()
onThemeChanged?.()
}
useEffect(() => { void reload() }, [safeMode])
@@ -136,10 +160,15 @@ export const PluginsPage: React.FC<Props> = ({
return
}
if (enable && p.needs_approval) {
approveTargetIDRef.current = p.id
setApproveChecked(false)
setApproveReport(null)
setApproveTarget(p)
void api.ScanInstalledPlugin(p.id).then(setApproveReport).catch((e) => console.warn('[plugins] ScanInstalledPlugin failed:', p.id, e))
void api.ScanInstalledPlugin(p.id)
.then((rep) => {
if (approveTargetIDRef.current === p.id) setApproveReport(rep)
})
.catch((e) => console.warn('[plugins] ScanInstalledPlugin failed:', p.id, e))
return
}
setBusyID(p.id)
@@ -157,11 +186,16 @@ export const PluginsPage: React.FC<Props> = ({
}
}
const closeApprove = () => {
approveTargetIDRef.current = ''
setApproveTarget(null)
setApproveReport(null)
}
const confirmApprove = async () => {
if (!approveTarget || !approveChecked) return
const target = approveTarget
setApproveTarget(null)
setApproveReport(null)
closeApprove()
setBusyID(target.id)
try {
await api.EnablePlugin(target.id, true)
@@ -803,46 +837,10 @@ export const PluginsPage: React.FC<Props> = ({
title={tr('pluginApproveTitle')}
subtitle={locText(approveTarget.name, locale, approveTarget.id)}
closeLabel={tr('close')}
onClose={() => { setApproveTarget(null); setApproveReport(null) }}
onClose={closeApprove}
>
<div className="dialog-body">
{(approveTarget.tier === 'L3' || (approveTarget.permissions ?? []).some((p) => p.name === 'ui:script')) && (
<div className="notice notice-warn">
<span className="notice-main">
<ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
<span>{approveReport?.native_exec_notice ? locText(approveReport.native_exec_notice, locale, tr('pluginApproveL3Warn')) : tr('pluginApproveL3Warn')}</span>
</span>
</div>
)}
<RiskList locale={locale} risks={approveTarget.risks} />
<div className="list">
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginPublisherLicense')}</div><div className="row-sub">{approveTarget.publisher || '—'} · {approveTarget.license || '—'}</div></div></div>
{approveTarget.entry_path && (
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginEntryPath')}</div><div className="row-sub mono selectable">{approveTarget.entry_path}</div></div></div>
)}
{approveTarget.entry_hash && (
<div className="row"><div className="row-main"><div className="row-title">SHA-256</div><div className="row-sub mono selectable">{approveTarget.entry_hash}</div></div></div>
)}
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginRequestedPerms')}</div><div className="row-sub mono">{(approveTarget.permissions ?? []).length > 0 ? (approveTarget.permissions ?? []).map((p) => `${p.name} (${p.level})`).join(', ') : '—'}</div></div></div>
</div>
{(approveReport?.capabilities?.length ?? 0) > 0 && (
<div className="plugin-scan-section">
<div className="plugin-scan-section-title">{tr('pluginScanCapabilitiesSection')}</div>
<div className="list">
{approveReport!.capabilities!.map((c) => (
<div className="row" key={c.id}>
<div className="row-main">
<div className="row-title">
<span className={`badge rg-p-badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
<span>{locText(c.title, locale, c.id)}</span>
</div>
<div className="row-sub">{locText(c.summary, locale, '')}</div>
</div>
</div>
))}
</div>
</div>
)}
<PluginApprovalBody locale={locale} plugin={approveTarget} report={approveReport} />
<label className="choice">
<input type="checkbox" checked={approveChecked} onChange={(e) => setApproveChecked(e.target.checked)} />
<span>{tr('pluginApproveCheckbox')}</span>
@@ -851,7 +849,7 @@ export const PluginsPage: React.FC<Props> = ({
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => { setApproveTarget(null); setApproveReport(null) }}>{tr('cancel')}</Button>
<Button variant="ghost" onClick={closeApprove}>{tr('cancel')}</Button>
<Button variant="primary" disabled={!approveChecked} onClick={() => void confirmApprove()}>
{tr('pluginApproveConfirm')}
</Button>
+12 -13
View File
@@ -17,12 +17,13 @@ import {
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
canKeepDisplayPreset,
fullscreenDisplayPresets,
FullscreenDisplayPreset,
hidpiLooksLike,
hostDisplayAdvice,
hostDisplayDesc,
recommendedDisplayPresets,
windowDisplayPresets,
recommendedMemoryGB,
recommendedResolution,
shortGPUName,
@@ -41,6 +42,7 @@ import type { ToastInput } from '../ui/toast'
import { api } from '../wails'
import type { app as WailsApp } from '../../wailsjs/go/models'
import { formatAffinitySummary } from './AffinityDialog'
import { VMNetworkSettings } from './VMNetworkSettings'
import type { VMKeymapPreset, VMKeymapHostModifier, VMKeymapGuestModifier } from '../types'
const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm })))
@@ -168,6 +170,7 @@ interface Props {
driverID: string
stats?: VMStats | null
host: HostReport
fixedModeSupported?: boolean
optimizations?: Optimization[]
running: boolean
onCopy?: (text: string) => void
@@ -181,7 +184,7 @@ interface Props {
onSaved: () => void
}
export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onToast, onClose, onSaved }) => {
export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats, host, fixedModeSupported = false, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onToast, onClose, onSaved }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
const base = useMemo(() => baseline(detail, host), [detail, host])
@@ -294,7 +297,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
hidpi_advice: displayStatus.hidpi_advice,
recommended_resolution: undefined,
} : host, [host, displayStatus, activeTargetDisplay])
const presets = recommendedDisplayPresets(displayProfile)
const presets = windowDisplayPresets(displayProfile, fixedModeSupported)
const fsPresets = fullscreenDisplayPresets(displayProfile)
const activePresets: FullscreenDisplayPreset[] = form.borderless ? fsPresets : presets
const presetHit = activePresets.some((p) => same('resolution', p.resolution, form.resolution))
@@ -984,11 +987,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const selectedGPUHint = gpuCompatHint(locale, selectedGPU)
const vgpu = form.graphics !== 'vmware-svga'
const targetDisp = activeTargetDisplay
const hidpiAdvice = hostDisplayAdvice(displayProfile, tr)
const hidpiAdvice = hostDisplayAdvice(displayProfile, tr, presets)
const resValue = customRes ? CUSTOM : activePresets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution
const toggleBorderless = (borderless: boolean) => {
const targetPresets = borderless ? fsPresets : presets
if (!customRes && !targetPresets.some((p) => same('resolution', p.resolution, form.resolution))) {
if (!customRes && !targetPresets.some((p) => canKeepDisplayPreset(p, form.resolution, borderless))) {
const nextRes = borderless
? (targetDisp && targetDisp.width > 0 && targetDisp.height > 0
? `${targetDisp.width}x${targetDisp.height}`
@@ -1155,6 +1158,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
p.hidpi ? tr('hidpiPresetBadge') : '',
p.scaleBadge ?? '',
p.native ? tr('resNativeBadge') : '',
p.scaleToFit ? tr('resScaleToFitWindow') : '',
p.recommended ? tr('recommendedBadge') : '',
].filter(Boolean),
})),
@@ -1551,19 +1555,14 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
)
})}
</SetGroup>
<SetGroup title={tr('catNetwork')}>
<SetRow
{...rowProps('network')}
title={tr('networkTitle')}
desc={tr('networkDesc')}
control={<Switch label={tr('enableNetwork')} checked={!!form.network} onChange={(network) => set({ network })} />}
/>
<VMNetworkSettings name={detail.name} locale={locale} running={running} disabled={busy} stagedDirty={changed.length > 0} onBusy={setBusy} onSaved={onSaved} />
<SetGroup>
<SetRow
{...rowProps('ssh_port')}
title={tr('sshForward')}
desc={sshOn ? <code className="inline-code">{sshCommand(form.ssh_port ?? 0)}</code> : tr('sshOffDesc')}
disabled={!form.network}
reason={tr('sshNeedsNetwork')}
reason={tr(detail.network_mode === 'bridge' ? 'sshNeedsNAT' : 'sshNeedsNetwork')}
control={
<div className="hstack">
{sshOn && (
+2 -1
View File
@@ -3,6 +3,7 @@ import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2
import React, { useRef } from 'react'
import { I18nKey, localeDir, t } from '../i18n'
import { Locale, VMListItem } from '../types'
import { hasVisibleDialog } from '../lib/dialogState'
import { vmRefKey } from '../lib/vmRef'
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
import { VersionArt } from '../macos/VersionArt'
@@ -162,7 +163,7 @@ export const Sidebar: React.FC<Props> = ({
onCloseAutoFocus={(e) => {
if (
ctxOpenedByPointerRef.current
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
|| hasVisibleDialog()
) {
e.preventDefault()
}
+10 -1
View File
@@ -2,6 +2,7 @@ import * as Menu from '@radix-ui/react-dropdown-menu'
import { Check, PanelLeft } from 'lucide-react'
import React, { useRef, useState } from 'react'
import { I18nKey, localeDir, t } from '../i18n'
import { hasVisibleDialog } from '../lib/dialogState'
import { useVMStats } from '../lib/vmStats'
import { Locale } from '../types'
import { Tip } from '../ui/controls'
@@ -11,6 +12,12 @@ import { VMAction } from './VMPage'
export const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
/** A page on reims.dev in the UI language: Chinese at the root, every other locale under /en. */
export function siteURL(locale: Locale, path = ''): string {
const base = locale.toLowerCase().startsWith('zh') ? 'https://reims.dev' : 'https://reims.dev/en'
return path ? `${base}${path}` : `${base}/`
}
const MENU_IDS = ['vm', 'view', 'help'] as const
type MenuId = (typeof MENU_IDS)[number]
@@ -178,7 +185,7 @@ export const TitleMenus: React.FC<Props> = ({
openRef.current !== null
|| openedByPointerRef.current
|| pointerClosedRef.current
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
|| hasVisibleDialog()
) {
e.preventDefault()
}
@@ -268,6 +275,8 @@ export const TitleMenus: React.FC<Props> = ({
), true)}
{menu('help', tr('menuHelp'), (
<>
{item(tr('helpWebsite'), () => onOpenURL(siteURL(locale)))}
{item(tr('helpDocs'), () => onOpenURL(siteURL(locale, '/docs/quick-start')))}
{item(tr('helpProjectPage'), () => onOpenURL(REPO_URL))}
{item(tr('helpReportIssue'), () => onOpenURL(`${REPO_URL}/issues`))}
{item(tr('helpCheckUpdate'), () => onNavigate(ABOUT_ID))}
@@ -0,0 +1,147 @@
import React, { useEffect, useState } from 'react'
import '../i18n/domains/settings.gen'
import { parseAppError, t } from '../i18n'
import type { I18nKey, ParsedAppError } from '../i18n'
import type { Locale, VMNetworkSettings as NetworkState } from '../types'
import { useNetworkPlan } from '../lib/useNetworkPlan'
import { NpcapDependency } from './NpcapDependency'
import { NetworkErrorNotice } from './NetworkErrorNotice'
import { Button } from '../ui/controls'
import { Segmented, SetGroup, SetRow, SetValue } from '../ui/settings'
import { api } from '../wails'
type Mode = 'off' | 'nat' | 'bridge'
export function VMNetworkSettings({ name, locale, running, disabled, stagedDirty, onBusy, onSaved }: {
name: string
locale: Locale
running: boolean
disabled: boolean
stagedDirty: boolean
onBusy: (busy: boolean) => void
onSaved: () => void
}) {
const tr = (key: I18nKey, vars?: Record<string, string | number>) => t(locale, key, vars)
const [state, setState] = useState<NetworkState | null>(null)
const [mode, setMode] = useState<Mode>('nat')
const [uplink, setUplink] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<ParsedAppError | null>(null)
const [dependencyRefresh, setDependencyRefresh] = useState(0)
const { plan, planning, planError } = useNetworkPlan(name, mode, uplink, !!state, `${dependencyRefresh}:${locale}`)
useEffect(() => {
let active = true
setState(null)
setError(null)
api.GetVMNetworkSettings(name).then((next) => {
if (!active) return
setState(next)
setDependencyRefresh((value) => value + 1)
if (next.mode !== 'custom') setMode(next.mode as Mode)
setUplink(next.uplink_guid)
}).catch((err) => { if (active) setError(parseAppError(err)) })
return () => { active = false }
}, [name, running, locale])
const apply = async () => {
if (!state || busy || disabled || stagedDirty || planning || planError || (active && !canSwitchUplink)) return
setBusy(true)
onBusy(true)
setError(null)
try {
const next = await api.ApplyVMNetwork(name, mode, uplink)
setState(next)
setDependencyRefresh((value) => value + 1)
if (next.mode !== 'custom') setMode(next.mode as Mode)
setUplink(next.uplink_guid)
onSaved()
} catch (err) {
setError(parseAppError(err))
// 失败后读取实际状态;回滚未完成时保留修复入口。
try {
const actual = await api.GetVMNetworkSettings(name)
setState(actual)
if (actual.mode !== 'custom') setMode(actual.mode as Mode)
setUplink(actual.uplink_guid)
setDependencyRefresh((value) => value + 1)
} catch (refreshError) {
console.warn('[network] refresh settings after apply failure:', refreshError)
}
} finally {
setBusy(false)
onBusy(false)
}
}
const locked = disabled || busy || !state
const active = running || !!state?.running
const canSwitchUplink = state?.mode === 'bridge' && mode === 'bridge' && !state.recovery_pending
const changed = state && (mode !== state.mode || (mode === 'bridge' && uplink !== state.uplink_guid))
const canRepair = state && (state.mode === 'bridge' || state.recovery_pending)
const adapters = state?.adapters ?? []
const status = !state ? tr('bridgeLoading')
: state.mode === 'bridge'
? state.ready ? tr('bridgeReady') : tr('bridgeNeedsRepair')
: state.mode === 'nat' ? tr('networkNAT') : state.mode === 'off' ? tr('off') : tr('bridgeCustom')
return (
<SetGroup title={tr('catNetwork')} note={tr('bridgeApplyHint')}>
<SetValue title={tr('bridgeCurrent')} value={status} />
<SetRow
title={tr('networkTitle')}
desc={tr('bridgeModeDesc')}
disabled={locked || active || stagedDirty || state?.mode === 'custom'}
reason={running || state?.running ? tr('bridgeStopFirst') : stagedDirty ? tr('bridgeSaveOther') : undefined}
block={
<Segmented label={tr('networkTitle')} value={mode} wide onChange={setMode} options={[
{ value: 'off', label: tr('off') },
{ value: 'nat', label: tr('networkNAT') },
{ value: 'bridge', label: tr('networkBridge') },
]} />
}
/>
{mode === 'bridge' && (
<SetRow
title={tr('bridgeUplink')}
desc={tr(active ? 'bridgeLiveSwitchHint' : 'bridgeUplinkHint')}
disabled={locked || stagedDirty || (active && !canSwitchUplink) || state?.mode === 'custom'}
block={
<div className="bridge-adapters" role="radiogroup" aria-label={tr('bridgeUplink')}>
{adapters.map((adapter) => (
<label key={adapter.guid} className="bridge-adapter">
<input type="radio" name={`bridge-uplink-${name}`} value={adapter.guid} checked={adapter.guid === uplink} disabled={adapter.status !== 'Up'} onChange={() => setUplink(adapter.guid)} />
<span>
<strong>{adapter.name}</strong>
<span className="srow-desc">{adapter.description}</span>
<span className="srow-desc">{adapter.status === 'Up' ? tr('bridgeConnected') : tr('bridgeDisconnected')} · {adapter.speed}</span>
</span>
</label>
))}
{adapters.length === 0 && <span className="muted">{tr('bridgeNoAdapters')}</span>}
</div>
}
/>
)}
{state?.mode === 'bridge' && state.uplink_name && (
<SetValue title={tr('bridgeUplink')} value={state.uplink_name} />
)}
{mode === 'bridge' && <NpcapDependency plan={plan} locale={locale} disabled={locked || stagedDirty} onBusy={(value) => { setBusy(value); onBusy(value) }} onInstalled={() => setDependencyRefresh((value) => value + 1)} />}
{state?.recovery_pending && <div className="notice notice-warn" role="status">{tr('bridgeRecoveryPending')}</div>}
{planning && <div className="srow-desc" role="status">{tr('bridgePlanPending')}</div>}
<NetworkErrorNotice error={planError} locale={locale} />
{state?.notes?.map((note) => <div key={note} className="srow-desc">{note}</div>)}
<NetworkErrorNotice error={error} locale={locale} />
<SetRow
title={tr('bridgeApplyTitle')}
desc={tr('bridgeIndependentHint')}
control={
<Button busy={busy} disabled={locked || stagedDirty || planning || !!planError || (active && !canSwitchUplink) || (!changed && !canRepair) || (mode === 'bridge' && !uplink) || state?.mode === 'custom'} onClick={apply}>
{changed ? tr('bridgeApply') : tr('bridgeRepair')}
</Button>
}
/>
</SetGroup>
)
}
+6 -5
View File
@@ -48,6 +48,7 @@ import {
controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel,
parseMemoryGB, pendingChangeText, resolveGuestLang, sshCommand,
} from '../lib/format'
import { hasVisibleDialog } from '../lib/dialogState'
import { useVMStats } from '../lib/vmStats'
import { DiskSnapshot, HostReport, Locale, PendingChange, PluginUIContributions, VMDetail, VMThumbnail } from '../types'
import { api } from '../wails'
@@ -563,7 +564,7 @@ export const VMPage: React.FC<Props> = ({
if (
moreOpenedByPointer.current
|| morePointerClosed.current
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
|| hasVisibleDialog()
) {
e.preventDefault()
}
@@ -699,8 +700,8 @@ export const VMPage: React.FC<Props> = ({
},
{
key: 'net', label: tr('fieldNetwork'), icon: <Network size={15} aria-hidden="true" />,
value: detail.network ? tr('netShared') : tr('netOff'),
tip: !detail.network ? tr('specNetOffTip') : detail.ssh_port > 0 ? tr('specNetSSHTip', { port: detail.ssh_port }) : tr('specNetTip'),
value: detail.network_mode === 'bridge' ? tr('netBridge') : detail.network_mode === 'custom' ? tr('netCustom') : detail.network ? tr('netShared') : tr('netOff'),
tip: detail.network_mode === 'bridge' ? tr('specNetBridgeTip') : !detail.network ? tr('specNetOffTip') : detail.ssh_port > 0 ? tr('specNetSSHTip', { port: detail.ssh_port }) : tr('specNetTip'),
},
)
if (detail.guest_lang) {
@@ -1062,7 +1063,7 @@ export const VMPage: React.FC<Props> = ({
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 gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 12
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 14
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
@@ -1150,7 +1151,7 @@ export const VMPage: React.FC<Props> = ({
if (
sshOpenedByPointer.current
|| sshPointerClosed.current
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
|| hasVisibleDialog()
) {
e.preventDefault()
}
+6 -2
View File
@@ -63,8 +63,10 @@ export const coreZh: Record<string, string> = {
"guestLangZhHantUS": "繁體中文",
"helpAbout": "关于 Reims-Go",
"helpCheckUpdate": "检查更新…",
"helpProjectPage": "项目主页",
"helpDocs": "使用文档",
"helpProjectPage": "GitHub 仓库",
"helpReportIssue": "报告问题",
"helpWebsite": "官方网站",
"hideSidebar": "隐藏侧边栏",
"hidpiTipFullscreen": "窗口里的 macOS 只能 1x,文字会发虚;改用全屏可得到 HiDPI",
"hidpiTipScale": "这块屏幕上 macOS 只能 1x,文字会发虚;把 Windows 缩放调到 150% 或以上可得到 HiDPI",
@@ -255,8 +257,10 @@ export const coreEn: Record<string, string> = {
"guestLangZhHantUS": "Traditional Chinese",
"helpAbout": "About Reims-Go",
"helpCheckUpdate": "Check for Updates…",
"helpProjectPage": "Project Page",
"helpDocs": "Documentation",
"helpProjectPage": "GitHub Repository",
"helpReportIssue": "Report an Issue",
"helpWebsite": "Official Website",
"hideSidebar": "Hide sidebar",
"hidpiTipFullscreen": "In a window macOS runs at 1x with rough text; full screen gives HiDPI",
"hidpiTipScale": "macOS runs at 1x on this screen, with rough text; Windows scaling at 150% or more gives HiDPI",
+2
View File
@@ -10,6 +10,7 @@ export const pluginsZh: Record<string, string> = {
"pluginApproveConfirm": "确认启用",
"pluginApproveL3Warn": "此插件为原生可执行程序(L3 Sidecar),能够以当前 Windows 账户身份执行任意操作",
"pluginApproveTitle": "高危权限确认",
"pluginApproveUIScriptWarn": "此插件包含交互界面脚本(ui:script),会在主窗口界面中运行并可访问页面内容,启用前务必核对来源与脚本 SHA-256",
"pluginBuiltinSection": "内置插件",
"pluginColorSchemes": "配色方案",
"pluginColorSchemesHint": "修改种子色派生整套界面色阶",
@@ -133,6 +134,7 @@ export const pluginsEn: Record<string, string> = {
"pluginApproveConfirm": "Confirm enable",
"pluginApproveL3Warn": "This plugin runs native code (L3 Sidecar) and can perform arbitrary actions as your Windows user",
"pluginApproveTitle": "Approve high-risk permissions",
"pluginApproveUIScriptWarn": "This plugin runs an interactive script (ui:script) inside the main window with full access to the interface; verify its source and SHA-256 before enabling",
"pluginBuiltinSection": "Built-in plugins",
"pluginColorSchemes": "Color schemes",
"pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp",
+64 -2
View File
@@ -16,13 +16,14 @@ export const settingsZh: Record<string, string> = {
"aboutLicensesTabNotice": "第三方声明",
"aboutLicensesTitle": "开源许可与声明",
"aboutLicensesView": "查看",
"aboutProjectSub": "GitHub 上的源码、发布版本与使用文档",
"aboutProjectSub": "GitHub 上的源码与发布版本",
"aboutQQGroup": "QQ 交流群",
"aboutQQGroupSub": "点击直接拉起 QQ 加群,交流使用与问题反馈",
"aboutQQLaunchFailed": "未能拉起 QQ,可复制群号手动搜索加入",
"aboutQQNotInstalled": "未安装 QQ",
"aboutQQNotInstalledSub": "未检测到本地 QQ,可复制群号手动搜索加入",
"aboutTagline": "在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。",
"aboutWebsiteSub": "reims.dev 上的下载、使用文档、插件市场与兼容性列表",
"activate": "使用",
"affinityApplyNow": "立即应用",
"affinityAvoidLPE": "避开 LP-E",
@@ -82,6 +83,27 @@ export const settingsZh: Record<string, string> = {
"audioTroubleshootNote": "有爆音时,把 Windows 声音格式设为 48000 Hz;麦克风没声音时,检查 Windows「隐私 › 麦克风」权限",
"autoPinPCores": "启动后绑定到性能核",
"back": "上一步",
"bridgeApply": "应用网络",
"bridgeApplyHint": "网络设置单独应用。切换模式需关闭此虚拟机,更换桥接出口支持运行中应用,不影响其他虚拟机。宿主网卡的 IP、DNS 和绑定保持不变",
"bridgeApplyTitle": "应用网络模式",
"bridgeConnected": "已连接",
"bridgeCurrent": "当前配置",
"bridgeCustom": "自定义网络",
"bridgeDisconnected": "未连接",
"bridgeIndependentHint": "桥接通过 Npcap 使用所选出口,管理器需保持运行",
"bridgeLiveSwitchHint": "更换出口后自动重连主网卡,通知系统续租 DHCP;联网恢复需要几秒,静态地址需自行调整",
"bridgeLoading": "正在检查网络",
"bridgeModeDesc": "NAT 共享宿主网络;桥接直接接入局域网",
"bridgeNeedsRepair": "已配置 Npcap 桥接 · 需要检查",
"bridgeNoAdapters": "没有可用的物理网卡",
"bridgePlanPending": "正在检查出口和 Npcap 状态",
"bridgeReady": "已配置 Npcap 桥接 · 出口可用",
"bridgeRecoveryPending": "上次虚拟机网络设置尚未完成,关机后点「检查并修复」恢复",
"bridgeRepair": "检查并修复",
"bridgeSaveOther": "先保存或重置其他修改,再切换网络",
"bridgeStopFirst": "先关闭此虚拟机再切换网络模式;桥接出口可在运行中更换",
"bridgeUplink": "出口网卡",
"bridgeUplinkHint": "每台虚拟机独立选择一张已连接的有线或 WLAN 网卡",
"captureInput": "点击窗口时捕获键鼠",
"captureInputHint": "开启后 ⌘Tab 等快捷键交给 macOS;关闭时 Win 键和 Alt+Tab 留给 Windows",
"catAdvanced": "高级",
@@ -365,11 +387,18 @@ export const settingsZh: Record<string, string> = {
"nestedVirtInvalid": "保存的设置无法读取,虚拟机将按默认 CPU 设置启动。",
"nestedVirtLabel": "嵌套虚拟化",
"nestedVirtUnavailable": "当前 Windows 宿主机无法通过 WHPX 提供 VMX。",
"networkBridge": "桥接",
"networkDesc": "通过 Windows 的网络连接上网",
"networkNAT": "NAT",
"networkOfflineHint": "离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网",
"networkTitle": "网络",
"next": "下一步",
"noChanges": "没有更改",
"npcapInstall": "下载并安装",
"npcapInstalled": "已检测到驱动安装,应用时检查出口;管理器需保持运行",
"npcapInstalling": "正在准备 Npcap,在弹出的官方安装向导中完成安装后将自动重新检查",
"npcapMissing": "未检测到完整安装;应用网络时自动从官网下载,也可提前安装。许可与 UAC 在官方向导确认",
"npcapStopFirst": "安装驱动前需先关闭全部虚拟机",
"offlineListFailed": "无法读取 Apple 的版本列表",
"opencore": "OpenCore",
"optAuto": "已自动开启",
@@ -399,6 +428,7 @@ export const settingsZh: Record<string, string> = {
"resFullscreen": "全屏",
"resInvalid": "格式为 宽x高,例如 2560x1600",
"resNativeBadge": "原生",
"resScaleToFitWindow": "缩放以适应窗口",
"resetAll": "全部还原",
"resetField": "还原为当前值",
"runtimeDelete": "删除运行时",
@@ -431,6 +461,7 @@ export const settingsZh: Record<string, string> = {
"sourceDisk": "已有虚拟磁盘(.qcow2)",
"sourceInstaller": "本地安装器镜像(.img / .dmg)",
"sshForward": "SSH 端口转发",
"sshNeedsNAT": "端口转发仅用于 NAT;桥接模式下局域网内其他设备可直接访问虚拟机,本机通信由 Guest Tools 管理通道提供",
"sshNeedsNetwork": "需要先开启网络",
"sshOffDesc": "从 Windows 用 SSH 登录 macOS",
"sshPort": "SSH 转发端口",
@@ -503,13 +534,14 @@ export const settingsEn: Record<string, string> = {
"aboutLicensesTabNotice": "Third-party notices",
"aboutLicensesTitle": "Open-source licenses",
"aboutLicensesView": "View",
"aboutProjectSub": "Source code, releases and docs on GitHub",
"aboutProjectSub": "Source code and releases on GitHub",
"aboutQQGroup": "QQ Group",
"aboutQQGroupSub": "Launch QQ directly to join for community support and feedback",
"aboutQQLaunchFailed": "Couldn’t launch QQ — copy the group ID to join manually",
"aboutQQNotInstalled": "QQ not installed",
"aboutQQNotInstalledSub": "Local QQ wasn’t detected — copy the group ID to join manually",
"aboutTagline": "Run a GPU-accelerated macOS virtual machine on Windows — prebuilt, ready out of the box.",
"aboutWebsiteSub": "Downloads, docs, plugin market and compatibility list on reims.dev",
"activate": "Use",
"affinityApplyNow": "Apply Now",
"affinityAvoidLPE": "Exclude LP-E",
@@ -569,6 +601,27 @@ export const settingsEn: Record<string, string> = {
"audioTroubleshootNote": "If audio crackles, set the Windows sound format to 48000 Hz. If the mic is silent, check Windows Privacy › Microphone",
"autoPinPCores": "Pin to performance cores on start",
"back": "Back",
"bridgeApply": "Apply network",
"bridgeApplyHint": "Network changes apply separately. Shut down this VM to change mode; bridged uplinks can change while running without reconfiguring other VMs. Host adapter IP, DNS, and bindings remain unchanged",
"bridgeApplyTitle": "Apply network mode",
"bridgeConnected": "Connected",
"bridgeCurrent": "Current configuration",
"bridgeCustom": "Custom network",
"bridgeDisconnected": "Disconnected",
"bridgeIndependentHint": "Bridging uses Npcap on the selected uplink. Keep the manager running",
"bridgeLiveSwitchHint": "Changing uplinks reconnects the main adapter to trigger DHCP renewal. Allow a few seconds to reconnect; adjust static addresses manually",
"bridgeLoading": "Checking network",
"bridgeModeDesc": "NAT shares the host connection; bridging joins the local network",
"bridgeNeedsRepair": "Npcap bridging configured · Check required",
"bridgeNoAdapters": "No physical adapters available",
"bridgePlanPending": "Checking the uplink and Npcap installation",
"bridgeReady": "Npcap bridging configured · Uplink available",
"bridgeRecoveryPending": "The last VM network change is incomplete. Shut down this VM and choose Check and repair",
"bridgeRepair": "Check and repair",
"bridgeSaveOther": "Save or reset other changes before switching networks",
"bridgeStopFirst": "Shut down this VM to change network mode. Bridged uplinks can change while running",
"bridgeUplink": "Uplink adapter",
"bridgeUplinkHint": "Choose one connected wired or WLAN adapter independently for each VM",
"captureInput": "Capture keyboard and mouse on click",
"captureInputHint": "When on, shortcuts like ⌘Tab go to macOS; when off, Win and Alt+Tab stay with Windows",
"catAdvanced": "Advanced",
@@ -852,11 +905,18 @@ export const settingsEn: Record<string, string> = {
"nestedVirtInvalid": "The saved setting could not be read. The VM starts with the default CPU settings.",
"nestedVirtLabel": "Nested virtualization",
"nestedVirtUnavailable": "The Windows host does not provide VMX through WHPX.",
"networkBridge": "Bridged",
"networkDesc": "Uses the Windows network connection",
"networkNAT": "NAT",
"networkOfflineHint": "Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking",
"networkTitle": "Network",
"next": "Next",
"noChanges": "No changes",
"npcapInstall": "Download and install",
"npcapInstalled": "Driver installation detected; the uplink is checked when applying. Keep the manager running",
"npcapInstalling": "Preparing Npcap. Complete the official installer; availability will be checked afterwards",
"npcapMissing": "A complete installation was not detected. Downloaded from the official website when applying, or install now. Confirm the license and UAC in the official wizard",
"npcapStopFirst": "Shut down all VMs before installing the driver",
"offlineListFailed": "Couldn’t read Apple’s release list",
"opencore": "OpenCore",
"optAuto": "Automatic",
@@ -886,6 +946,7 @@ export const settingsEn: Record<string, string> = {
"resFullscreen": "Full screen",
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
"resNativeBadge": "Native",
"resScaleToFitWindow": "Scale to fit window",
"resetAll": "Revert all",
"resetField": "Revert to current value",
"runtimeDelete": "Delete runtime",
@@ -918,6 +979,7 @@ export const settingsEn: Record<string, string> = {
"sourceDisk": "Existing virtual disk (.qcow2)",
"sourceInstaller": "Local installer image (.img / .dmg)",
"sshForward": "SSH port forwarding",
"sshNeedsNAT": "Port forwarding is for NAT; other LAN devices can reach a bridged VM directly, while host-to-guest services use the Guest Tools channel",
"sshNeedsNetwork": "Turn on the network first",
"sshOffDesc": "Log in to macOS over SSH from Windows",
"sshPort": "SSH forward port",
+12 -2
View File
@@ -3,9 +3,10 @@
export const vmZh: Record<string, string> = {
"attachGuestTools": "挂载 Guest Tools",
"attachInstaller": "挂载离线镜像",
"bridgeCreateCommandHint": "此命令创建基础配置;桥接由管理器随后应用,单独运行命令不会配置宿主出口",
"brokenHint": "这台虚拟机的配置无法读取",
"cloneConfirm": "立即派生",
"cloneDesc": "用写时复制瞬间创建副本,几乎不占空间,原虚拟机不受影响",
"cloneDesc": "副本共享源磁盘,删除副本后才能启动源虚拟机或改写源磁盘",
"cloneNameLabel": "新虚拟机名称",
"cloneTitle": "从「{name}」派生 CoW 副本",
"cloneVM": "秒级派生副本 (CoW)",
@@ -46,6 +47,7 @@ export const vmZh: Record<string, string> = {
"failCloneVM": "派生 CoW 副本失败",
"failDelete": "删除失败",
"failDiscardSuspend": "放弃挂起状态失败",
"failDrop": "拖放失败",
"failEject": "弹出安装盘失败",
"failEnterRecovery": "进入恢复模式失败",
"failExportDiagnostics": "导出排障日志失败",
@@ -117,6 +119,8 @@ export const vmZh: Record<string, string> = {
"hostDNSStatusPending": "待应用",
"hostDNSStatusStale": "配置已过期",
"hostDNSStatusStillActive": "macOS 代理未移除",
"netBridge": "桥接网络",
"netCustom": "自定义网络",
"netOff": "无网络",
"netShared": "共享网络",
"onlineRecoveryConfirm": "拉取并挂载(约 1 GB)",
@@ -160,6 +164,7 @@ export const vmZh: Record<string, string> = {
"specLangTipDetail": "macOS 系统语言:{label}({detail})",
"specMemLiveTip": "内存 {mem},虚拟机在宿主上占用 {used}",
"specMemTip": "内存 {mem}",
"specNetBridgeTip": "通过 Npcap 使用所选出口接入局域网,地址由局域网分配",
"specNetOffTip": "虚拟机没有网络",
"specNetSSHTip": "与宿主共享网络连接,SSH 端口 {port}",
"specNetTip": "与宿主共享网络连接",
@@ -231,9 +236,10 @@ export const vmZh: Record<string, string> = {
export const vmEn: Record<string, string> = {
"attachGuestTools": "Attach Guest Tools",
"attachInstaller": "Attach offline image",
"bridgeCreateCommandHint": "This command creates the base configuration; the manager applies bridging afterward. Running this command alone does not configure the host uplink.",
"brokenHint": "This VM’s configuration can’t be read",
"cloneConfirm": "Create clone",
"cloneDesc": "Makes an instant copy-on-write clone that takes almost no space and leaves the original untouched",
"cloneDesc": "This clone shares the source disk, so delete the clone before starting the source VM or changing its disk",
"cloneNameLabel": "New VM name",
"cloneTitle": "Derive CoW clone from “{name}”",
"cloneVM": "Derive CoW clone",
@@ -274,6 +280,7 @@ export const vmEn: Record<string, string> = {
"failCloneVM": "Couldn’t create CoW clone",
"failDelete": "Couldn’t delete",
"failDiscardSuspend": "Couldn’t discard saved state",
"failDrop": "Couldn’t drop into the VM",
"failEject": "Couldn’t eject the installer",
"failEnterRecovery": "Couldn’t enter recovery mode",
"failExportDiagnostics": "Couldn’t export diagnostics",
@@ -345,6 +352,8 @@ export const vmEn: Record<string, string> = {
"hostDNSStatusPending": "Not applied",
"hostDNSStatusStale": "Config outdated",
"hostDNSStatusStillActive": "Still active in macOS",
"netBridge": "Bridged network",
"netCustom": "Custom network",
"netOff": "No network",
"netShared": "Shared network",
"onlineRecoveryConfirm": "Download \u0026 attach (~1 GB)",
@@ -388,6 +397,7 @@ export const vmEn: Record<string, string> = {
"specLangTipDetail": "macOS system language: {label} ({detail})",
"specMemLiveTip": "{mem} memory; the VM uses {used} on this PC",
"specMemTip": "{mem} memory",
"specNetBridgeTip": "Joins the LAN through Npcap on the selected uplink; the LAN supplies its address",
"specNetOffTip": "The VM has no network",
"specNetSSHTip": "Shares this PC’s network connection; SSH on port {port}",
"specNetTip": "Shares this PC’s network connection",
+39
View File
@@ -22,6 +22,7 @@ export type I18nKey =
| "aboutQQNotInstalled"
| "aboutQQNotInstalledSub"
| "aboutTagline"
| "aboutWebsiteSub"
| "activate"
| "affinityApplyNow"
| "affinityAvoidLPE"
@@ -87,6 +88,28 @@ export type I18nKey =
| "back"
| "backToEdit"
| "borderless"
| "bridgeApply"
| "bridgeApplyHint"
| "bridgeApplyTitle"
| "bridgeConnected"
| "bridgeCreateCommandHint"
| "bridgeCurrent"
| "bridgeCustom"
| "bridgeDisconnected"
| "bridgeIndependentHint"
| "bridgeLiveSwitchHint"
| "bridgeLoading"
| "bridgeModeDesc"
| "bridgeNeedsRepair"
| "bridgeNoAdapters"
| "bridgePlanPending"
| "bridgeReady"
| "bridgeRecoveryPending"
| "bridgeRepair"
| "bridgeSaveOther"
| "bridgeStopFirst"
| "bridgeUplink"
| "bridgeUplinkHint"
| "brokenHint"
| "cancel"
| "cancelCreate"
@@ -232,6 +255,7 @@ export type I18nKey =
| "failDelete"
| "failDiscardSuspend"
| "failDownload"
| "failDrop"
| "failEject"
| "failEnterRecovery"
| "failExportDiagnostics"
@@ -421,8 +445,10 @@ export type I18nKey =
| "guideTitle"
| "helpAbout"
| "helpCheckUpdate"
| "helpDocs"
| "helpProjectPage"
| "helpReportIssue"
| "helpWebsite"
| "hideSidebar"
| "hidpiPresetBadge"
| "hidpiTipFullscreen"
@@ -590,9 +616,13 @@ export type I18nKey =
| "nestedVirtInvalid"
| "nestedVirtLabel"
| "nestedVirtUnavailable"
| "netBridge"
| "netCustom"
| "netOff"
| "netShared"
| "networkBridge"
| "networkDesc"
| "networkNAT"
| "networkOfflineHint"
| "networkTitle"
| "newVM"
@@ -600,6 +630,11 @@ export type I18nKey =
| "next"
| "noChanges"
| "noRuntimeAlert"
| "npcapInstall"
| "npcapInstalled"
| "npcapInstalling"
| "npcapMissing"
| "npcapStopFirst"
| "off"
| "offlineCached"
| "offlineDownloading"
@@ -651,6 +686,7 @@ export type I18nKey =
| "pluginApproveConfirm"
| "pluginApproveL3Warn"
| "pluginApproveTitle"
| "pluginApproveUIScriptWarn"
| "pluginBuiltinSection"
| "pluginColorSchemes"
| "pluginColorSchemesHint"
@@ -774,6 +810,7 @@ export type I18nKey =
| "resInvalid"
| "resLooksLike"
| "resNativeBadge"
| "resScaleToFitWindow"
| "resetAll"
| "resetField"
| "resizeLogPanel"
@@ -897,6 +934,7 @@ export type I18nKey =
| "specLangTipDetail"
| "specMemLiveTip"
| "specMemTip"
| "specNetBridgeTip"
| "specNetOffTip"
| "specNetSSHTip"
| "specNetTip"
@@ -910,6 +948,7 @@ export type I18nKey =
| "srcOfflineTitle"
| "sshForward"
| "sshMore"
| "sshNeedsNAT"
| "sshNeedsNetwork"
| "sshOffDesc"
| "sshOpenTerminal"
+52
View File
@@ -0,0 +1,52 @@
// Pure UI helper for checking whether any modal dialog is actually visible.
// Hidden pre-mounted dialog elements (display:none on self or ancestor,
// visibility:hidden/collapse, [hidden], [inert], aria-hidden="true",
// data-state="closed") must not block global shortcuts or menu focus return.
export interface DialogLikeElement {
getAttribute(name: string): string | null
closest?(selector: string): unknown
parentElement?: DialogLikeElement | null
}
export interface ComputedVisibility {
display: string
visibility: string
}
export function isDialogElementVisible(
el: DialogLikeElement,
getStyle: (node: DialogLikeElement) => ComputedVisibility,
): boolean {
if (el.getAttribute('data-state') === 'closed') return false
const selfStyle = getStyle(el)
if (selfStyle.visibility === 'hidden' || selfStyle.visibility === 'collapse') return false
let cur: DialogLikeElement | null = el
while (cur) {
if (
cur.getAttribute('hidden') !== null
|| cur.getAttribute('inert') !== null
|| cur.getAttribute('aria-hidden') === 'true'
) {
return false
}
const style = cur === el ? selfStyle : getStyle(cur)
if (style.display === 'none') return false
cur = cur.parentElement ?? null
}
if (!el.parentElement && el.closest?.('[hidden], [inert], [aria-hidden="true"]')) return false
return true
}
export function hasVisibleDialog(
root: Pick<Document, 'querySelectorAll'> = document,
getStyle: (node: DialogLikeElement) => ComputedVisibility = (node) => window.getComputedStyle(node as Element),
): boolean {
const nodes = root.querySelectorAll('[role="dialog"], [role="alertdialog"]')
for (let i = 0; i < nodes.length; i++) {
if (isDialogElementVisible(nodes[i], getStyle)) return true
}
return false
}
+28 -1
View File
@@ -10,6 +10,10 @@ function currentDocLocale(): string {
// Human-readable values for the main view (see docs/design-guidelines.md).
// Raw values stay available under "Technical details".
export function formatNameList(locale: Locale, names: string[]): string {
return new Intl.ListFormat(locale === 'auto' ? currentDocLocale() : locale, { style: 'long', type: 'conjunction' }).format(names)
}
const MEMORY_CHOICES = [4, 6, 8, 12, 16, 24, 32, 48, 64]
/**
@@ -280,7 +284,8 @@ export function hostDisplayDesc(
// How to get a HiDPI (sharp-text) macOS desktop when no window size gives
// one on this screen; undefined when one does.
export function hostDisplayAdvice(host: HostReport, tr: Tr): string | undefined {
export function hostDisplayAdvice(host: HostReport, tr: Tr, windowPresets: DisplayPreset[] = recommendedDisplayPresets(host)): string | undefined {
if (host.hidpi_advice === 'fullscreen' && windowPresets.some((p) => p.hidpi)) return undefined
const tip: Record<string, I18nKey> = {
fullscreen: 'hidpiTipFullscreen',
scale: 'hidpiTipScale',
@@ -307,6 +312,28 @@ export function recommendedDisplayPresets(host: HostReport): DisplayPreset[] {
export interface FullscreenDisplayPreset extends DisplayPreset {
native?: boolean
scaleBadge?: string
scaleToFit?: boolean
}
/** Scaling into a window is opt-in, not an automatic fullscreen-to-window fallback. */
export function canKeepDisplayPreset(preset: FullscreenDisplayPreset, resolution: string | undefined, borderless: boolean): boolean {
const normalize = (value: string) => value.trim().toLowerCase().replace(/\s+/g, '').replace('×', 'x')
return resolution !== undefined && normalize(preset.resolution) === normalize(resolution) && (borderless || !preset.scaleToFit)
}
/** Preserve fit recommendations; fixed-mode runtimes can scale native guest pixels into a window. */
export function windowDisplayPresets(host: HostReport, fixedModeSupported: boolean): FullscreenDisplayPreset[] {
const presets = recommendedDisplayPresets(host)
const d = host.primary_display
if (!fixedModeSupported || !d || d.width < 2560 || d.height < 1440 || d.width > 5120 || d.height > 3200) return presets
const resolution = `${d.width}x${d.height}`
if (presets.some((p) => p.resolution === resolution)) return presets
return [...presets, {
resolution,
label: `${d.width} × ${d.height}`,
hidpi: !!host.fullscreen_hidpi,
scaleToFit: true,
}]
}
/**
+2 -1
View File
@@ -584,7 +584,8 @@ export async function applyActiveTheme(
activeUIScriptNotifier = notifyThemeSDKState
activeUIScriptEventSink = emitThemeSDKEvent
activeUIScriptURL = nextScriptURL
} catch {
} catch (e) {
console.warn('[theme] mount interactive theme script failed:', nextScriptURL, e)
if (gen === applyGeneration) {
// Fall back to the scriptless style/token theme.
activeUIScriptCleanup = null
+64
View File
@@ -0,0 +1,64 @@
import { useEffect, useState } from 'react'
import { parseAppError } from '../i18n'
import type { ParsedAppError } from '../i18n'
import type { VMNetworkPlan } from '../types'
import { api } from '../wails'
export function useNetworkPlan(name: string, mode: string, uplink: string, enabled: boolean, refreshKey?: unknown) {
const [plan, setPlan] = useState<VMNetworkPlan | null>(null)
const [planning, setPlanning] = useState(false)
const [planError, setPlanError] = useState<ParsedAppError | null>(null)
const requestKey = JSON.stringify([name, mode, uplink, enabled, refreshKey])
const [settledKey, setSettledKey] = useState('')
useEffect(() => {
setPlan(null)
setPlanError(null)
if (!enabled || !name || (mode === 'bridge' && !uplink)) {
setPlanning(false)
return
}
let active = true
let inFlight = false
let timer: ReturnType<typeof setTimeout> | undefined
setPlanning(true)
const refresh = async () => {
if (!active || inFlight) return
clearTimeout(timer)
if (document.visibilityState === 'hidden') return
inFlight = true
let shouldPoll = false
try {
const next = await api.GetVMNetworkPlan(name, mode, uplink)
if (!active) return
setPlan(next)
setPlanError(null)
setSettledKey(requestKey)
// 仅在 Npcap 尚未安装就绪时低频轮询等待安装向导完成;就绪后改由焦点/可见性事件按需刷新。
shouldPoll = mode === 'bridge' && !next.npcap_installed
} catch (err) {
if (active) { setPlanError(parseAppError(err)); setSettledKey(requestKey) }
} finally {
inFlight = false
if (active) {
setPlanning(false)
if (shouldPoll) timer = setTimeout(refresh, 8000)
}
}
}
const onVisible = () => { if (document.visibilityState === 'visible') void refresh() }
window.addEventListener('focus', refresh)
document.addEventListener('visibilitychange', onVisible)
timer = setTimeout(refresh, 150)
return () => {
active = false
clearTimeout(timer)
window.removeEventListener('focus', refresh)
document.removeEventListener('visibilitychange', onVisible)
}
}, [name, mode, uplink, enabled, refreshKey, requestKey])
const current = settledKey === requestKey
const pending = !!enabled && !!name && (mode !== 'bridge' || !!uplink) && (!current || planning)
return { plan: current ? plan : null, planning: pending, planError: current ? planError : null }
}
+10
View File
@@ -941,6 +941,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
.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; 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-body > * { flex-shrink: 0; }
.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; }
@@ -1915,6 +1916,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
}
.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 > .list { flex-shrink: 0; }
.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; }
@@ -2046,3 +2048,11 @@ button.status-issue + .status-metric { margin-left: 6px; }
/* Layers and decorations never take input, whatever a theme says. */
.rg-layer, .rg-layer *, .rg-decoration { pointer-events: none !important; }
}
.bridge-adapters { display: grid; gap: var(--space-3, 12px); }
.bridge-adapter { display: flex; align-items: flex-start; gap: var(--space-2, 8px); padding-block: var(--space-2, 8px); cursor: pointer; }
.bridge-adapter > span { display: grid; gap: var(--space-1, 4px); min-width: 0; overflow-wrap: anywhere; }
.bridge-adapter input { flex: 0 0 auto; margin-block-start: var(--space-1, 4px); accent-color: var(--accent); }
.bridge-adapter:has(input:disabled) { opacity: .55; cursor: default; }
.network-error-details { margin-block-start: 8px; }
.network-error-details pre { margin-block: 8px 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
+4
View File
@@ -69,6 +69,8 @@ export type SuspendInfo = reims.SuspendInfo
export type VMDetail = reims.VMDetail
export type SMBIOSIdentity = opencore.SMBIOSIdentity
export type VMStats = app.VMStats
export type VMNetworkSettings = Model<app.VMNetworkSettings>
export type VMNetworkPlan = Model<app.VMNetworkPlan>
export type DriveShareSettings = Model<app.DriveShareSettings>
export type SharedFolderInfo = Model<app.SharedFolderInfo>
export type SharedFolderSettings = Model<app.SharedFolderSettings>
@@ -93,6 +95,8 @@ export type StorageBreakdown = Model<app.StorageBreakdown>
export type SetOpts = reims.SetOpts
export type CreateOpts = Model<reims.CreateOpts> & {
network_mode?: 'off' | 'nat' | 'bridge'
uplink_guid?: string
source_mode?: 'offline' | 'apple' | 'installer' | 'disk'
disk_mode?: 'copy' | 'in-place'
disk_controller?: 'nvme' | 'ahci' | 'virtio'
+8 -1
View File
@@ -17,7 +17,7 @@ import {
import type {
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime,
RuntimeKindSpec, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMKeymapStatus, VMKeymapUpdate,
RuntimeKindSpec, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMNetworkSettings, VMNetworkPlan, VMKeymapStatus, VMKeymapUpdate,
} from './types'
type AnyFn = (...args: never[]) => unknown
@@ -148,6 +148,11 @@ function eventsEmit(eventName: string, ...args: unknown[]): void {
export const api = {
...boundGo,
GetVMNetworkSettings: boundGo.GetVMNetworkSettings as (name: string) => Promise<VMNetworkSettings>,
GetVMNetworkPlan: boundGo.GetVMNetworkPlan as (name: string, mode: string, uplink: string) => Promise<VMNetworkPlan>,
ListNetworkAdapters: boundGo.ListNetworkAdapters as () => Promise<VMNetworkSettings['adapters']>,
ApplyVMNetwork: boundGo.ApplyVMNetwork as (name: string, mode: string, uplink: string) => Promise<VMNetworkSettings>,
InstallNpcap: boundGo.InstallNpcap as () => Promise<void>,
GetState: boundGo.GetState as () => Promise<AppState>,
GetTasks: boundGo.GetTasks as () => Promise<Task[]>,
GetVMAffinity: boundGo.GetVMAffinity as (name: string) => Promise<VMAffinityStatus>,
@@ -179,6 +184,8 @@ export interface MarketInstallProgress {
}
export const events = {
onHostDrop: (cb: (payload: { vm: string; drop_id: string; delivered: string[]; skipped?: string[]; mode: string }) => void) => eventsOn('reims:host-drop', cb),
onHostDropAck: (cb: (payload: { vm: string; drop_id: string; status: string; target_kind?: string; target_label?: string; placed_names?: string[]; error?: string }) => void) => eventsOn('reims:host-drop-ack', cb),
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),
+25 -15
View File
@@ -1,19 +1,21 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
import {app} from '../models';
import {opencore} from '../models';
import {reims} from '../models';
import {plugin} from '../models';
import {version} from '../models';
import {app} from '../models';
import {driver} from '../models';
import {guesttools} from '../models';
import {runtime} from '../models';
import {installer} from '../models';
import {http} from '../models';
import {dataroot} from '../models';
import {opencore} from '../models';
import {guesttools} from '../models';
export function AddVMSharedFolder(arg1:string,arg2:string):Promise<app.SharedFolderSettings>;
export function ApplyVMNetwork(arg1:string,arg2:string,arg3:string):Promise<app.VMNetworkSettings>;
export function ApplyVMSMBIOS(arg1:string,arg2:opencore.SMBIOSIdentity):Promise<opencore.SMBIOSIdentity>;
export function ApplyVMSettings(arg1:reims.SetOpts):Promise<void>;
@@ -40,14 +42,6 @@ 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>;
@@ -122,6 +116,8 @@ export function GenerateVMSMBIOS(arg1:string):Promise<opencore.SMBIOSIdentity>;
export function GetActiveTheme():Promise<plugin.ActiveThemePayload>;
export function GetDefenderExclusionCommand():Promise<string>;
export function GetGuestToolsHostDNS(arg1:string):Promise<app.GuestToolsHostDNSStatus>;
export function GetHostDNSConfig():Promise<guesttools.HostDNSConfig>;
@@ -142,8 +138,6 @@ 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 GetVMDisplayWithDriver(arg1:string,arg2:string):Promise<app.VMDisplayStatus>;
@@ -152,8 +146,14 @@ export function GetVMDriveShareSettings(arg1:string):Promise<app.DriveShareSetti
export function GetVMInfo(arg1:string,arg2:string):Promise<driver.VMInfo>;
export function GetVMKeymap(arg1:string):Promise<app.VMKeymapStatus>;
export function GetVMMacOS(arg1:string):Promise<string>;
export function GetVMNetworkPlan(arg1:string,arg2:string,arg3:string):Promise<app.VMNetworkPlan>;
export function GetVMNetworkSettings(arg1:string):Promise<app.VMNetworkSettings>;
export function GetVMNote(arg1:string):Promise<string>;
export function GetVMPluginSettings(arg1:string):Promise<Record<string, Record<string, any>>>;
@@ -184,6 +184,8 @@ export function InstallAppUpdate():Promise<void>;
export function InstallMarketPlugin(arg1:string,arg2:boolean):Promise<plugin.PluginInfo>;
export function InstallNpcap():Promise<void>;
export function InstallPluginArchive(arg1:string):Promise<plugin.PluginInfo>;
export function InstallRuntimeArchive(arg1:string):Promise<runtime.Installed>;
@@ -198,6 +200,8 @@ export function ListDrivers():Promise<Array<driver.DriverSummary>>;
export function ListInstallers():Promise<Array<installer.Cached>>;
export function ListNetworkAdapters():Promise<Array<app.NetworkAdapter>>;
export function ListOfflineReleases():Promise<Array<installer.Release>>;
export function ListPlugins():Promise<Array<plugin.PluginInfo>>;
@@ -228,6 +232,12 @@ export function OpenVSCodeSSH(arg1:string,arg2:string):Promise<void>;
export function OpenVSCodeSSHWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function OpenWindowsSecurityExclusions():Promise<void>;
export function OptimizeVMDisk(arg1:string):Promise<driver.DiskCompactResult>;
export function OptimizeVMDiskWithDriver(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
export function PanelBridgeCall(arg1:string,arg2:string,arg3:Record<string, any>):Promise<any>;
export function PeekPluginMarket(arg1:string,arg2:string):Promise<plugin.MarketBrowseResult>;
@@ -308,10 +318,10 @@ export function SetVMAffinityWithDriver(arg1:string,arg2:string,arg3:app.VMAffin
export function SetVMDisplayWithDriver(arg1:string,arg2:string,arg3:string):Promise<app.VMDisplayStatus>;
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 SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise<app.VMKeymapStatus>;
export function SetVMNote(arg1:string,arg2:string):Promise<void>;
export function SetVMSSHUser(arg1:string,arg2:string):Promise<void>;
+44 -24
View File
@@ -6,6 +6,10 @@ export function AddVMSharedFolder(arg1, arg2) {
return window['go']['app']['App']['AddVMSharedFolder'](arg1, arg2);
}
export function ApplyVMNetwork(arg1, arg2, arg3) {
return window['go']['app']['App']['ApplyVMNetwork'](arg1, arg2, arg3);
}
export function ApplyVMSMBIOS(arg1, arg2) {
return window['go']['app']['App']['ApplyVMSMBIOS'](arg1, arg2);
}
@@ -58,22 +62,6 @@ 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);
}
@@ -222,6 +210,10 @@ export function GetActiveTheme() {
return window['go']['app']['App']['GetActiveTheme']();
}
export function GetDefenderExclusionCommand() {
return window['go']['app']['App']['GetDefenderExclusionCommand']();
}
export function GetGuestToolsHostDNS(arg1) {
return window['go']['app']['App']['GetGuestToolsHostDNS'](arg1);
}
@@ -262,10 +254,6 @@ 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);
}
@@ -282,10 +270,22 @@ export function GetVMInfo(arg1, arg2) {
return window['go']['app']['App']['GetVMInfo'](arg1, arg2);
}
export function GetVMKeymap(arg1) {
return window['go']['app']['App']['GetVMKeymap'](arg1);
}
export function GetVMMacOS(arg1) {
return window['go']['app']['App']['GetVMMacOS'](arg1);
}
export function GetVMNetworkPlan(arg1, arg2, arg3) {
return window['go']['app']['App']['GetVMNetworkPlan'](arg1, arg2, arg3);
}
export function GetVMNetworkSettings(arg1) {
return window['go']['app']['App']['GetVMNetworkSettings'](arg1);
}
export function GetVMNote(arg1) {
return window['go']['app']['App']['GetVMNote'](arg1);
}
@@ -346,6 +346,10 @@ export function InstallMarketPlugin(arg1, arg2) {
return window['go']['app']['App']['InstallMarketPlugin'](arg1, arg2);
}
export function InstallNpcap() {
return window['go']['app']['App']['InstallNpcap']();
}
export function InstallPluginArchive(arg1) {
return window['go']['app']['App']['InstallPluginArchive'](arg1);
}
@@ -374,6 +378,10 @@ export function ListInstallers() {
return window['go']['app']['App']['ListInstallers']();
}
export function ListNetworkAdapters() {
return window['go']['app']['App']['ListNetworkAdapters']();
}
export function ListOfflineReleases() {
return window['go']['app']['App']['ListOfflineReleases']();
}
@@ -434,6 +442,18 @@ export function OpenVSCodeSSHWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['OpenVSCodeSSHWithDriver'](arg1, arg2, arg3);
}
export function OpenWindowsSecurityExclusions() {
return window['go']['app']['App']['OpenWindowsSecurityExclusions']();
}
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 PanelBridgeCall(arg1, arg2, arg3) {
return window['go']['app']['App']['PanelBridgeCall'](arg1, arg2, arg3);
}
@@ -594,14 +614,14 @@ export function SetVMDisplayWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMDisplayWithDriver'](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);
}
export function SetVMKeymap(arg1, arg2) {
return window['go']['app']['App']['SetVMKeymap'](arg1, arg2);
}
export function SetVMNote(arg1, arg2) {
return window['go']['app']['App']['SetVMNote'](arg1, arg2);
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -3,6 +3,7 @@ module github.com/Nwflower/reims-go
go 1.26.0
require (
github.com/Microsoft/go-winio v0.6.2
github.com/klauspost/compress v1.20.5
github.com/pelletier/go-toml/v2 v2.4.3
github.com/ulikunitz/xz v0.5.17
+2
View File
@@ -1,5 +1,7 @@
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 h1:N3IGoHHp9pb6mj1cbXbuaSXV/UMKwmbKLf53nQmtqMA=
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3/go.mod h1:QtOLZGz8olr4qH2vWK0QH0w0O4T9fEIjMuWpKUsH7nc=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+55 -8
View File
@@ -13,12 +13,14 @@ import (
"github.com/Nwflower/reims-go/internal/cli"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/control"
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/packetbridge"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/tray"
@@ -92,13 +94,18 @@ func vmNameFromKey(key string) string {
}
type App struct {
ctx context.Context
mu sync.Mutex
cfg *config.Config
transitions map[string]string
pendingChanges map[string][]PendingChange
rebootWatchers map[string]rebootWatcherEntry
nextWatcherID uint64
packetMu sync.Mutex
packetBridges map[string]*packetbridge.Bridge
packetBridgesStopped bool
vmNetworkLocks sync.Map
vmNetworkLocksMu sync.Mutex
ctx context.Context
mu sync.Mutex
cfg *config.Config
transitions map[string]string
pendingChanges map[string][]PendingChange
rebootWatchers map[string]rebootWatcherEntry
nextWatcherID uint64
stopPoll context.CancelFunc
guestTools *guesttools.Server
@@ -112,7 +119,7 @@ type App struct {
quitMode string
vmStarts sync.WaitGroup
lastVMs []driver.VMListItem
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
lastVMListErr error
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
diskPaths map[string]cachedDiskPath
@@ -125,6 +132,7 @@ type App struct {
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
pluginMgr *plugin.Manager
pluginMarket *plugin.MarketClient
controlServer *control.Server
driverRouter *driver.Router
lifecycleSvc *vmlifecycle.Service
runtimeKinds *rt.KindRegistry
@@ -139,6 +147,10 @@ type App struct {
keymapPIDs map[string]int
fallbackInputSvc *host.InputService
inputShuttingDown bool
// computerUseOwnedVMs records temporary CoW VMs created by an MCP session.
// Ownership is process-scoped and disappears when the desktop process exits.
computerUseOwnedVMs map[string]map[string]bool
computerUseCloneMu sync.Mutex
}
// Lifecycle exposes Wails lifecycle callbacks without exporting them as
@@ -206,6 +218,7 @@ func (a *App) startup(ctx context.Context) {
a.startIMEBridge()
if a.dataRootUsable() {
go a.registerExistingGuestTools(pollCtx)
go a.registerExistingPacketBridges(pollCtx)
}
}
go a.finishAppUpdate()
@@ -249,11 +262,13 @@ func (a *App) beforeClose(ctx context.Context) bool {
}
func (a *App) shutdown(ctx context.Context) {
a.closePacketBridges()
if a.stopPoll != nil {
a.stopPoll()
}
tasks.cancelAll()
stopAllVMMonitors()
a.stopPluginControlServer()
a.mu.Lock()
a.inputShuttingDown = true
fallback := a.fallbackInputSvc
@@ -348,6 +363,7 @@ func (a *App) pollVMs(ctx context.Context) {
}
continue
}
a.syncComputerUseOwnership(vms)
watchExits(ctx, vms, exitWatched, a.wakePoll)
type pinCandidate struct {
name string
@@ -427,12 +443,35 @@ func (a *App) pollVMs(ctx context.Context) {
_, ok := liveVMs[name]
return !ok
})
var stoppedBridges []string
for _, prev := range a.lastVMs {
if prev.State != "running" || prev.DriverID != driver.BuiltinReimsMacOSDriverID {
continue
}
key := vmKeyForDriver(prev.DriverID, prev.Name)
tr := a.transitions[key]
if tr == "starting" || tr == "resuming" {
continue
}
for _, cur := range vms {
if cur.DriverID == prev.DriverID && cur.Name == prev.Name && cur.State != "running" {
stoppedBridges = append(stoppedBridges, cur.Name)
break
}
}
}
gt := a.guestTools
a.lastVMs = append([]driver.VMListItem(nil), vms...)
a.lastVMsAt = time.Now()
listRecovered := a.lastVMListErr != nil
a.lastVMListErr = nil
a.mu.Unlock()
for _, vmName := range stoppedBridges {
a.stopPacketBridge(vmName)
if gt != nil {
gt.StopManagementNetwork(vmName)
}
}
prunePinnedPIDs(pinnedPIDs, vms)
prunePinnedPIDs(guideCheckedPIDs, vms)
guideMgr := a.getInstallGuideManager()
@@ -452,6 +491,10 @@ func (a *App) pollVMs(ctx context.Context) {
}
for key := range removedVMs {
name := vmNameFromKey(key)
if ref, ok := driver.ParseVMRef(key); ok && ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.stopPacketBridge(name)
}
a.forgetComputerUseOwnedVM(key)
a.mu.Lock()
delete(a.transitions, key)
delete(a.pendingChanges, key)
@@ -1092,11 +1135,15 @@ func (a *App) OpenProcessorScheduling() error {
func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
a.mu.Lock()
cfg := a.cfg
loc := i18n.EffectiveLocale(cfg.Locale)
a.mu.Unlock()
a.emitLog("runtime", "Installing portable runtime: "+archivePath)
inst, err := rt.InstallFromArchive(cfg, archivePath)
if err != nil {
a.emitLog("runtime", "Install failed: "+err.Error())
if errors.Is(err, rt.ErrRuntimeInUse) {
return nil, i18n.NewCodedError(loc, "E_RUNTIME_IN_USE", "runtime.install_in_use", nil, err)
}
return nil, err
}
a.mu.Lock()
+28
View File
@@ -0,0 +1,28 @@
package app
import (
"errors"
"github.com/Nwflower/reims-go/internal/console"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
)
var fallbackComputerUse = console.NewManager()
func (a *App) computerUseService() (builtin.ComputerUseService, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return fallbackComputerUse, nil
}
raw, ok := mgr.Registry().LookupService(builtin.ServiceComputerUse)
if !ok {
return nil, errors.New("virtual machine interaction is disabled")
}
service, ok := raw.(builtin.ComputerUseService)
if !ok || service == nil {
return nil, errors.New("virtual machine interaction service is unavailable")
}
return service, nil
}
+738
View File
@@ -0,0 +1,738 @@
package app
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/thumb"
)
const computerUsePreviewWidth = 1280
const computerUseMaxTextRunes = 4000
const computerUseSecretPluginID = "reims.agent"
const computerUseOwnershipFile = ".reims-go-computer-use"
type computerUseOwnership struct {
Version int `json:"version"`
PluginID string `json:"plugin_id"`
VMKey string `json:"vm_key"`
}
func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
if mgr == nil || mgr.Broker() == nil {
return nil
}
handlers := map[string]plugin.RPCRequestHandler{
"host/vm.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.list", a.handleComputerUseVMList),
"host/vm.get": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.get", a.handleComputerUseVMGet),
"host/vm.start": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.start", a.handleComputerUseVMStart),
"host/vm.shutdown": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.shutdown", a.handleComputerUseVMShutdown),
"host/vm.clone": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.clone", a.handleComputerUseVMClone),
"host/vm.delete": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.delete", a.handleComputerUseVMDelete),
"host/vm.snapshot.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
"host/vm.snapshot.create": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
"host/vm.snapshot.restore": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
"host/console.screenshot": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:screen", "host/console.screenshot", a.handleComputerUseScreenshot),
"host/console.pointer": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.pointer", a.handleComputerUsePointer),
"host/console.key": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.key", a.handleComputerUseKey),
"host/console.type": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.type", a.handleComputerUseType),
}
// The plugin ID is supplied by the manager while wiring the sidecar, never
// by the channel payload. Keep the handler registered for a stable method
// table, then reject every plugin except the official MCP service below.
handlers["host/console.typeSecret"] = a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.typeSecret", a.handleComputerUseTypeSecret)
return handlers
}
type computerUseVMHandler func(context.Context, json.RawMessage, *plugin.Manager, string) (any, error)
func (a *App) authorizedComputerUseVMHandler(mgr *plugin.Manager, pluginID, permission, method string, run computerUseVMHandler) plugin.RPCRequestHandler {
return a.authorizedComputerUseHandler(mgr, pluginID, permission, method, func(ctx context.Context, raw json.RawMessage) (any, error) {
return run(ctx, raw, mgr, pluginID)
})
}
func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
if pluginID != computerUseSecretPluginID {
return nil, errors.New("secret typing is reserved for reims.agent")
}
var req struct {
VM string `json:"vm"`
Setting string `json:"setting"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
if strings.TrimSpace(req.Setting) == "" {
return nil, errors.New("secret setting name is required")
}
vm, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if mgr == nil {
return nil, errors.New("plugin manager is unavailable")
}
secret, err := mgr.SecretSetting(pluginID, vm.Ref().Key(), req.Setting)
if err != nil {
return nil, err
}
defer func() { secret = "" }()
if len(secret) == 0 || utf8.RuneCountInString(secret) > computerUseMaxTextRunes {
return nil, errors.New("secret must contain between 1 and 4000 characters")
}
count, err := a.injectTextIntoVMWithLogging(vm.Name, vm.Directory, secret, false, true)
if err != nil {
return nil, err
}
return map[string]any{"characters": count}, nil
}
func (a *App) handleComputerUseVMList(ctx context.Context, _ json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
items, err := a.listVMsInternal(ctx)
if err != nil {
return nil, err
}
vms := make([]map[string]any, 0, len(items))
for _, item := range items {
info, err := a.resolveVMInfo(item.DriverID, item.Name)
if err != nil {
continue
}
vms = append(vms, a.computerUseVMView(info, mgr, pluginID))
}
return map[string]any{"vms": vms}, nil
}
func (a *App) handleComputerUseVMGet(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
info, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
return a.computerUseVMView(info, mgr, pluginID), nil
}
func (a *App) computerUseVMView(vm driver.VMInfo, mgr *plugin.Manager, pluginID string) map[string]any {
accessEnabled := a.computerUseVMAccessEnabled(mgr, pluginID, vm.Ref().Key())
view := map[string]any{
"vm": vm.Ref().Key(),
"name": vm.Name,
"driver_id": vm.DriverID,
"state": vm.State,
"authorized": accessEnabled,
"phase": computerUseVMPhase(vm),
"owned": a.computerUseOwned(pluginID, vm.Ref().Key()),
}
if vm.CPUs > 0 {
view["cpus"] = vm.CPUs
}
if vm.Memory != "" {
view["memory"] = vm.Memory
}
if vm.DiskSummary != "" {
view["disk_summary"] = vm.DiskSummary
}
if accessEnabled && vm.SSHPort > 0 {
view["ssh_port"] = vm.SSHPort
}
if len(vm.Capabilities) > 0 {
view["capabilities"] = append([]string(nil), vm.Capabilities...)
}
if accessEnabled {
username := a.GetVMSSHUserWithDriver(vm.DriverID, vm.Name)
if mgr != nil {
settings := mgr.GetSettings(pluginID, vm.Ref().Key(), false)
if configured, ok := settings["username"].(string); ok && strings.TrimSpace(configured) != "" {
username = strings.TrimSpace(configured)
}
}
if username != "" {
view["ssh_username"] = username
}
}
return view
}
func (a *App) handleComputerUseVMStart(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if err := a.StartVMWithDriver(vm.DriverID, vm.Name); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
}
func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if err := a.StopVMWithDriver(vm.DriverID, vm.Name, false); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
}
func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
CloneName string `json:"clone_name"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
cloneName := strings.TrimSpace(req.CloneName)
if cloneName == "" {
return nil, errors.New("clone_name is required")
}
if !strings.HasPrefix(cloneName, "__agent-") {
return nil, errors.New("temporary MCP clones must use the __agent- prefix")
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
cloneRef := driver.NewVMRef(vm.DriverID, cloneName)
a.computerUseCloneMu.Lock()
defer a.computerUseCloneMu.Unlock()
if existing, listErr := a.listVMsInternal(ctx); listErr != nil {
return nil, listErr
} else if slices.ContainsFunc(existing, func(item driver.VMListItem) bool {
return item.Name == cloneName && driver.CanonicalDriverID(item.DriverID) == driver.CanonicalDriverID(vm.DriverID)
}) {
return nil, fmt.Errorf("VM name %q is already taken", cloneName)
}
if err := a.CloneVMCoWWithDriver(vm.DriverID, vm.Name, cloneName); err != nil {
// CloneCoW can fail after creating an overlay or VM record. The target
// was absent during the preflight above, so clean up any partial target.
if existing, listErr := a.listVMsInternal(ctx); listErr == nil && slices.ContainsFunc(existing, func(item driver.VMListItem) bool {
return item.Name == cloneName && driver.CanonicalDriverID(item.DriverID) == driver.CanonicalDriverID(vm.DriverID)
}) {
if cleanupErr := a.DeleteVMWithDriver(vm.DriverID, cloneName, false); cleanupErr != nil {
return nil, errors.Join(err, fmt.Errorf("clean up failed clone %q: %w", cloneName, cleanupErr))
}
}
return nil, err
}
if _, err := a.persistComputerUseOwnership(pluginID, cloneRef.Key()); err != nil {
if cleanupErr := a.DeleteVMWithDriver(vm.DriverID, cloneName, false); cleanupErr != nil {
return nil, errors.Join(err, fmt.Errorf("clean up unregistered clone %q: %w", cloneName, cleanupErr))
}
return nil, err
}
// The lifecycle service may not expose a newly-created VM until the next
// inventory poll. Return the canonical reference immediately so callers can
// start the clone without turning a successful clone into a false failure.
a.markComputerUseOwnedVM(pluginID, cloneRef.Key(), true)
return map[string]any{"vm": cloneRef.Key(), "name": cloneName, "driver_id": vm.DriverID, "state": "stopped", "owned": true}, nil
}
func (a *App) handleComputerUseVMDelete(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
vm, err := a.resolveComputerUseVMInfo(req.VM)
if err != nil {
return nil, err
}
if !a.computerUseOwned(pluginID, vm.Ref().Key()) {
return nil, fmt.Errorf("not_authorized: VM %q is not an MCP-owned temporary clone", vm.Name)
}
if vm.State == "running" {
if err := a.stopVMWithDriverCtx(ctx, vm.DriverID, vm.Name, false); err != nil {
return nil, err
}
}
if err := a.DeleteVMWithDriver(vm.DriverID, vm.Name, false); err != nil {
return nil, err
}
removeComputerUseOwnership(vm.Directory)
a.markComputerUseOwnedVM(pluginID, vm.Ref().Key(), false)
return map[string]any{"ok": true}, nil
}
func (a *App) handleComputerUseVMSnapshotList(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
snapshots, err := a.ListSnapshotsWithDriver(vm.DriverID, vm.Name)
if err != nil {
return nil, err
}
return map[string]any{"snapshots": snapshots}, nil
}
func (a *App) handleComputerUseVMSnapshotCreate(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Name string `json:"name"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if err := a.CreateSnapshotWithDriver(vm.DriverID, vm.Name, req.Name); err != nil {
return nil, err
}
return map[string]any{"ok": true, "name": strings.TrimSpace(req.Name)}, nil
}
func (a *App) handleComputerUseVMSnapshotRestore(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Name string `json:"name"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if !a.computerUseOwned(pluginID, vm.Ref().Key()) {
return nil, errors.New("confirmation_required: restoring a user VM requires confirmation in Reims-Go")
}
if err := a.RestoreSnapshotWithDriver(vm.DriverID, vm.Name, req.Name); err != nil {
return nil, err
}
return map[string]any{"ok": true, "name": strings.TrimSpace(req.Name)}, nil
}
type computerUseHandler func(context.Context, json.RawMessage) (any, error)
func (a *App) authorizedComputerUseHandler(mgr *plugin.Manager, pluginID, permission, method string, run computerUseHandler) plugin.RPCRequestHandler {
return func(ctx context.Context, raw json.RawMessage) (any, error) {
broker := mgr.Broker()
if err := broker.Authorize(pluginID, permission); err != nil {
return nil, err
}
result, err := run(ctx, raw)
if err != nil {
broker.Audit(pluginID, "HOST_API_ERROR", method)
return nil, err
}
broker.Audit(pluginID, "HOST_API", method)
return result, nil
}
}
func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (driver.VMInfo, error) {
ref = strings.TrimSpace(ref)
if ref == "" {
return driver.VMInfo{}, errors.New("VM reference is required")
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, ref)
if err != nil {
return driver.VMInfo{}, err
}
if driver.CanonicalDriverID(vm.DriverID) != builtin.IDDriverReimsMacOS {
return driver.VMInfo{}, fmt.Errorf("computer_use_unavailable: driver %q does not support computer use", vm.DriverID)
}
current, ok := a.polledVMForDriver(vm.DriverID, vm.Name)
if !ok || current.State != "running" || current.PID == nil || *current.PID <= 0 {
return driver.VMInfo{}, fmt.Errorf("vm_not_running: VM %q is not running", vm.Name)
}
if phase := computerUseVMPhase(vm); phase != "normal" {
return driver.VMInfo{}, fmt.Errorf("confirmation_required: VM %q is in %s phase", vm.Name, phase)
}
if vm.Directory == "" {
vm.Directory = current.Dir
}
if vm.Directory == "" {
return driver.VMInfo{}, fmt.Errorf("VM %q has no console directory", vm.Name)
}
return vm, nil
}
func (a *App) resolveAuthorizedComputerUseVMInfo(mgr *plugin.Manager, pluginID, ref string) (driver.VMInfo, error) {
vm, err := a.resolveComputerUseVMInfo(ref)
if err != nil {
return driver.VMInfo{}, err
}
if !a.computerUseVMAccessEnabled(mgr, pluginID, vm.Ref().Key()) {
return driver.VMInfo{}, fmt.Errorf("not_authorized: MCP access is disabled for VM %q in plugin settings", vm.Name)
}
return vm, nil
}
func (a *App) computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) bool {
return computerUseVMAccessEnabled(mgr, pluginID, vmKey) || a.computerUseOwned(pluginID, vmKey)
}
func (a *App) computerUseOwned(pluginID, vmKey string) bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.computerUseOwnedVMs != nil && a.computerUseOwnedVMs[pluginID] != nil && a.computerUseOwnedVMs[pluginID][vmKey]
}
func (a *App) markComputerUseOwnedVM(pluginID, vmKey string, owned bool) {
a.mu.Lock()
defer a.mu.Unlock()
if a.computerUseOwnedVMs == nil {
a.computerUseOwnedVMs = make(map[string]map[string]bool)
}
if a.computerUseOwnedVMs[pluginID] == nil {
a.computerUseOwnedVMs[pluginID] = make(map[string]bool)
}
if owned {
a.computerUseOwnedVMs[pluginID][vmKey] = true
} else {
delete(a.computerUseOwnedVMs[pluginID], vmKey)
}
}
func (a *App) forgetComputerUseOwnedVM(vmKey string) {
vmKey = strings.TrimSpace(vmKey)
if vmKey == "" {
return
}
a.mu.Lock()
defer a.mu.Unlock()
for pluginID, owned := range a.computerUseOwnedVMs {
delete(owned, vmKey)
if len(owned) == 0 {
delete(a.computerUseOwnedVMs, pluginID)
}
}
}
func writeComputerUseOwnership(vmDir, pluginID, vmKey string) error {
vmDir = strings.TrimSpace(vmDir)
pluginID = strings.TrimSpace(pluginID)
vmKey = strings.TrimSpace(vmKey)
if vmDir == "" || pluginID == "" || vmKey == "" {
return errors.New("temporary VM ownership metadata is incomplete")
}
data, err := json.Marshal(computerUseOwnership{Version: 1, PluginID: pluginID, VMKey: vmKey})
if err != nil {
return err
}
path := filepath.Join(vmDir, computerUseOwnershipFile)
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return fmt.Errorf("create temporary VM ownership marker: %w", err)
}
if _, writeErr := file.Write(append(data, '\n')); writeErr != nil {
_ = file.Close()
_ = os.Remove(path)
return fmt.Errorf("write temporary VM ownership marker: %w", writeErr)
}
if err := file.Close(); err != nil {
_ = os.Remove(path)
return fmt.Errorf("close temporary VM ownership marker: %w", err)
}
return nil
}
func removeComputerUseOwnership(vmDir string) {
if strings.TrimSpace(vmDir) == "" {
return
}
_ = os.Remove(filepath.Join(vmDir, computerUseOwnershipFile))
}
func readComputerUseOwnership(vm driver.VMInfo) (computerUseOwnership, bool) {
if vm.Directory == "" || !strings.HasPrefix(vm.Name, "__agent-") {
return computerUseOwnership{}, false
}
raw, err := os.ReadFile(filepath.Join(vm.Directory, computerUseOwnershipFile))
if err != nil {
return computerUseOwnership{}, false
}
var marker computerUseOwnership
if json.Unmarshal(raw, &marker) != nil || marker.Version != 1 || marker.PluginID == "" || marker.VMKey != vm.Ref().Key() {
return computerUseOwnership{}, false
}
return marker, true
}
func (a *App) restoreComputerUseOwnedVMs(ctx context.Context) error {
vms, err := a.listVMsInternal(ctx)
if err != nil {
return err
}
a.syncComputerUseOwnership(vms)
return nil
}
func (a *App) persistComputerUseOwnership(pluginID, vmKey string) (bool, error) {
vm, err := a.resolveComputerUseVMInfo(vmKey)
if err != nil || vm.Directory == "" {
// Driver inventories can lag behind a successful clone. The next VM
// inventory pass will retry persistence without discarding the clone.
return false, nil
}
if err := writeComputerUseOwnership(vm.Directory, pluginID, vmKey); err != nil {
return false, err
}
return true, nil
}
func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) {
for _, item := range vms {
vm := driver.VMInfo{Name: item.Name, DriverID: item.DriverID, Directory: item.Dir}
if vm.Directory == "" || !strings.HasPrefix(vm.Name, "__agent-") {
continue
}
marker, ok := readComputerUseOwnership(vm)
if ok {
a.markComputerUseOwnedVM(marker.PluginID, marker.VMKey, true)
continue
}
key := vm.Ref().Key()
a.mu.Lock()
var pluginIDs []string
for pluginID, owned := range a.computerUseOwnedVMs {
if owned[key] {
pluginIDs = append(pluginIDs, pluginID)
}
}
a.mu.Unlock()
for _, pluginID := range pluginIDs {
if err := writeComputerUseOwnership(vm.Directory, pluginID, key); err == nil {
break
}
}
}
}
func computerUseVMPhase(vm driver.VMInfo) string {
if vmInfoBool(vm, "has_installer") {
return "installer"
}
if vmInfoBool(vm, "recovery_mode") {
return "recovery"
}
return "normal"
}
func computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) bool {
if mgr == nil || strings.TrimSpace(pluginID) == "" || strings.TrimSpace(vmKey) == "" {
return false
}
value, _ := mgr.GetSettings(pluginID, vmKey, false)["allow_ai_access"].(bool)
return value
}
// resolveComputerUseVMInfo accepts the bare VM name used by the UI and the
// canonical driverID:name reference returned by the VM list and resource APIs.
func (a *App) resolveComputerUseVMInfo(ref string) (driver.VMInfo, error) {
ref = strings.TrimSpace(ref)
if parsed, ok := driver.ParseVMRef(ref); ok {
return a.resolveVMInfo(parsed.DriverID, parsed.Name)
}
return a.resolveVMInfo("", ref)
}
func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
vm, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
service, err := a.computerUseService()
if err != nil {
return nil, err
}
a.mu.Lock()
if a.cfg == nil {
a.mu.Unlock()
return nil, errors.New("application configuration is unavailable")
}
tempDir := a.cfg.TempDir()
a.mu.Unlock()
if err := os.MkdirAll(tempDir, 0o755); err != nil {
return nil, err
}
file, err := os.CreateTemp(tempDir, "computer-use-*.ppm")
if err != nil {
return nil, err
}
path := file.Name()
if err := file.Close(); err != nil {
_ = os.Remove(path)
return nil, err
}
defer os.Remove(path)
format, err := service.Screendump(ctx, vm.Directory, path)
if err != nil {
return nil, err
}
sourceSize, err := thumb.Size(path, format)
if err != nil {
return nil, err
}
// A blank frame is a normal screen state during boot, login and display
// switches. Return it with a flag so pollers can keep waiting through it.
preview, blank, err := thumb.LoadPreviewFrame(path, format, computerUsePreviewWidth)
if err != nil {
return nil, err
}
encoded, err := thumb.JPEG(preview, 84)
if err != nil {
return nil, err
}
bounds := preview.Bounds()
return map[string]any{
"mime_type": "image/jpeg",
"width": bounds.Dx(),
"height": bounds.Dy(),
"source_width": sourceSize.X,
"source_height": sourceSize.Y,
"blank": blank,
"data": base64.StdEncoding.EncodeToString(encoded),
}, nil
}
func (a *App) handleComputerUsePointer(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Action string `json:"action"`
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
Button string `json:"button"`
Down *bool `json:"down"`
Delta int `json:"delta"`
Horizontal bool `json:"horizontal"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
vm, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
service, err := a.computerUseService()
if err != nil {
return nil, err
}
switch strings.ToLower(strings.TrimSpace(req.Action)) {
case "move":
available, err := service.PointerAvailable(ctx, vm.Directory)
if err != nil {
return nil, err
}
if !available {
return nil, errors.New("VM has no active absolute pointer")
}
err = service.MouseMove(ctx, vm.Directory, req.X, req.Y, req.Width, req.Height)
case "button":
if req.Down == nil {
return nil, errors.New("button action requires down")
}
err = service.MouseButton(ctx, vm.Directory, req.Button, *req.Down)
case "click":
err = service.MouseClick(ctx, vm.Directory, req.Button)
case "scroll":
err = service.MouseScroll(ctx, vm.Directory, req.Delta, req.Horizontal)
default:
return nil, fmt.Errorf("unsupported pointer action %q", req.Action)
}
if err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
}
func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Key string `json:"key"`
Modifiers []string `json:"modifiers"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
if strings.TrimSpace(req.Key) == "" {
return nil, errors.New("key is required")
}
vm, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
service, err := a.computerUseService()
if err != nil {
return nil, err
}
if err := service.PressKey(ctx, vm.Directory, req.Key, req.Modifiers...); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
}
func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Text string `json:"text"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
if len(req.Text) == 0 || !utf8.ValidString(req.Text) {
return nil, errors.New("text must be non-empty valid UTF-8")
}
if utf8.RuneCountInString(req.Text) > computerUseMaxTextRunes {
return nil, fmt.Errorf("text exceeds %d characters", computerUseMaxTextRunes)
}
vm, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
n, err := a.injectTextIntoVMWithLogging(vm.Name, vm.Directory, req.Text, false, true)
if err != nil {
return nil, err
}
return map[string]any{"characters": n}, nil
}
+66 -3
View File
@@ -10,20 +10,36 @@ import (
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/installer"
"github.com/Nwflower/reims-go/internal/macos/opencore"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/networkmsg"
"github.com/Nwflower/reims-go/internal/packetbridge"
rt "github.com/Nwflower/reims-go/internal/runtime"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
func (a *App) createVMFlow(opts reims.CreateOpts) error {
func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
defer func() {
var coded *i18n.CodedError
if errors.As(err, &coded) && strings.HasPrefix(coded.Code, "E_NETWORK_") {
err = networkmsg.Localize(err, a.locale())
}
}()
if err := a.requireMacOSEnabled(); err != nil {
return err
}
if issues := a.ValidateCreate(opts); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
if opts.NetworkMode != "" {
enabled := opts.NetworkMode != "off"
opts.Network = &enabled
}
if opts.NetworkMode == "bridge" {
opts.SSHPort = 0
}
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
@@ -41,6 +57,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)
if opts.NetworkMode == "bridge" {
tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: networkmsg.Text(a.locale(), "log.create_network_prepare"), Percent: -1})
}
if err := a.prepareCreateNetwork(ctx, c, opts); err != nil {
finishTask(err)
return err
}
a.emitVMLog(opts.Name, "Creating VM "+opts.Name+"...")
existingVMs, _ := c.List(ctx)
@@ -192,10 +215,23 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not apply macOS language (%s): %v", guestLang, lerr))
}
}
if opts.NetworkMode == "bridge" {
if _, networkErr := a.applyVMNetwork(ctx, opts.Name, "bridge", opts.UplinkGUID); networkErr != nil {
err = networkmsg.Error("create_bridge_pending", networkErr, "name", opts.Name)
finishTask(err)
a.emitLog(opts.Name, networkmsg.Text(a.locale(), "log.create_bridge_failed")+" "+networkmsg.Localize(networkErr, a.locale()).Error())
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return err
}
}
finishTask(nil)
a.emitVMLog(opts.Name, "VM "+opts.Name+" ready.")
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
if startAfterCreate {
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
if startAfterCreate && ctx.Err() == nil {
return a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, opts.Name)
}
return nil
@@ -217,3 +253,30 @@ func createInstallerTarget(opts reims.CreateOpts) (kind, version string) {
}
return "online", v
}
// 在分配磁盘前准备依赖,真正应用时仍重新检查出口。
func (a *App) prepareCreateNetwork(ctx context.Context, c networkControlClient, opts reims.CreateOpts) error {
if opts.NetworkMode != "bridge" {
return nil
}
if !a.npcapPluginEnabled() {
return networkmsg.Error("plugin_disabled", nil)
}
ctx, cancel := context.WithTimeout(ctx, 20*time.Minute)
defer cancel()
adapters, err := packetbridge.ListAdapters(ctx)
if err != nil {
return err
}
selected, err := selectPacketUplink(adapters, opts.UplinkGUID)
if err != nil {
return err
}
if err := a.ensureNpcap(ctx, c); err != nil {
return err
}
if err := packetbridge.CheckAdapter(selected.GUID, selected.Index); err != nil {
return err
}
return ctx.Err()
}
+98 -11
View File
@@ -16,6 +16,7 @@ import (
"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/networkmsg"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
@@ -50,7 +51,7 @@ func (a *App) registerGuestToolsConfig(srv *guesttools.Server, vmDir string, cfg
return nil
}
func (a *App) loadAndRegisterGuestTools(srv *guesttools.Server, port int, vmDir, name string, epoch uint64) (guesttools.VMConfig, error) {
func (a *App) loadAndRegisterGuestTools(srv *guesttools.Server, port int, vmDir, name string, epoch uint64, networkMode ...string) (guesttools.VMConfig, error) {
unlock := a.lockGuestToolsVM(name)
defer unlock()
if a.vmDeleteEpoch(name) != epoch {
@@ -60,12 +61,48 @@ func (a *App) loadAndRegisterGuestTools(srv *guesttools.Server, port int, vmDir,
return guesttools.VMConfig{}, err
}
cfg, err := guesttools.LoadOrCreateVMConfig(vmDir, name, a.vmSharedDir(name), port)
if err == nil && len(networkMode) > 0 {
if networkMode[0] == "bridge" && a.npcapPluginEnabled() {
previousOut, previousIn := cfg.ManagementOutPort, cfg.ManagementInPort
previousOutSock, previousInSock := cfg.ManagementOutSock, cfg.ManagementInSock
if !reims.HasSuspendState(vmDir) {
cfg.ManagementOutSock = reims.VMUnixSocketPath(vmDir, a.tempDir(), name, "gt-out.sock")
cfg.ManagementInSock = reims.VMUnixSocketPath(vmDir, a.tempDir(), name, "gt-in.sock")
cfg.ManagementOutPort = 0
cfg.ManagementInPort = 0
}
cfg.VMDir = vmDir
cfg.QEMUPath = a.activeQemuPath()
cfg, err = srv.EnsureManagementNetwork(cfg)
if err == nil && (previousOut != cfg.ManagementOutPort || previousIn != cfg.ManagementInPort || previousOutSock != cfg.ManagementOutSock || previousInSock != cfg.ManagementInSock) {
err = guesttools.SaveVMConfig(vmDir, cfg)
}
} else {
srv.StopManagementNetwork(name)
}
}
if err == nil {
err = a.registerGuestToolsConfig(srv, vmDir, cfg)
}
return cfg, err
}
// 启动钩子仍通过宿主回调登记,管理通道配置与上游共享配置使用同一把锁。
func (a *App) loadAndRegisterNetworkGuestTools(srv *guesttools.Server, port int, vmDir, name string, epoch uint64) (guesttools.VMConfig, error) {
c, err := a.client()
if err != nil {
return guesttools.VMConfig{}, err
}
d, err := c.Show(a.baseCtx(), name)
if err != nil {
return guesttools.VMConfig{}, err
}
if !strings.EqualFold(filepath.Clean(d.Directory), filepath.Clean(vmDir)) {
return guesttools.VMConfig{}, os.ErrNotExist
}
return a.loadAndRegisterGuestTools(srv, port, vmDir, name, epoch, d.NetworkMode)
}
func (a *App) vmSharedDir(name string) string {
a.mu.Lock()
dir := filepath.Join(a.cfg.SharedDir(), name)
@@ -108,6 +145,9 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created
} else {
srv = guesttools.NewServer(nil)
}
srv.SetHostDropHandler(a.handleHostDrop)
srv.SetDropAckHandler(a.handleHostDropAck)
srv.SetDropPasteHandler(a.handleHostDropPaste)
srv.SetHostTextHandler(func(vmKey, vmName, text string) {
a.mu.Lock()
mgr := a.pluginMgr
@@ -182,6 +222,28 @@ func (a *App) inputBridgeEnv(name, vmDir string, epoch uint64) []string {
}
}
func (a *App) dropBridgeEnv(name, vmDir string, epoch uint64) []string {
if vmDir == "" {
return nil
}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil || port <= 0 {
return nil
}
cfg, err := a.loadAndRegisterGuestTools(srv, port, vmDir, name, epoch)
if err != nil || cfg.Token == "" {
return nil
}
token := srv.HostDropToken(cfg.DriverID, name)
if token == "" {
return nil
}
return []string{
fmt.Sprintf("REIMS_GO_DROP_URL=http://127.0.0.1:%d/v1/host-drop", port),
"REIMS_GO_DROP_TOKEN=" + token,
}
}
func (a *App) registerExistingGuestTools(ctx context.Context) {
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
@@ -209,11 +271,15 @@ func (a *App) registerVMsWithBridge(ctx context.Context, srv *guesttools.Server,
if err != nil || det.Directory == "" {
continue
}
a.registerSavedGuestToolsConfig(srv, port, vm.Name, det.Directory, epoch)
mode := ""
if vm.State == "running" {
mode = det.NetworkMode
}
a.registerSavedGuestToolsConfig(srv, port, vm.Name, det.Directory, epoch, mode)
}
}
func (a *App) registerSavedGuestToolsConfig(srv *guesttools.Server, port int, name, vmDir string, epoch uint64) {
func (a *App) registerSavedGuestToolsConfig(srv *guesttools.Server, port int, name, vmDir string, epoch uint64, networkMode ...string) {
unlock := a.lockGuestToolsVM(name)
defer unlock()
if a.vmDeleteEpoch(name) != epoch {
@@ -232,6 +298,17 @@ func (a *App) registerSavedGuestToolsConfig(srv *guesttools.Server, port int, na
return
}
cfg.VMName = name
hasMgmt := (cfg.ManagementOutSock != "" && cfg.ManagementInSock != "") || (cfg.ManagementOutPort > 0 && cfg.ManagementInPort > 0)
if len(networkMode) > 0 && networkMode[0] == "bridge" && hasMgmt && a.npcapPluginEnabled() {
cfg.VMDir = vmDir
cfg.QEMUPath = a.activeQemuPath()
if _, err := srv.EnsureManagementNetwork(cfg); err != nil {
a.emitLog(name, networkmsg.Text(a.locale(), "log.management_restore_failed")+" "+networkmsg.Localize(err, a.locale()).Error())
return
}
} else if len(networkMode) > 0 {
srv.StopManagementNetwork(name)
}
if cfg.SharedDir == "" {
cfg.SharedDir = a.vmSharedDir(name)
}
@@ -307,20 +384,30 @@ func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail,
a.emitVMLog(name, "Warning: could not start Guest Tools bridge: "+err.Error())
return
}
cfg, err := a.loadAndRegisterGuestTools(srv, port, cur.Directory, name, epoch)
cfg, err := a.loadAndRegisterGuestTools(srv, port, cur.Directory, name, epoch, cur.NetworkMode)
if err != nil {
a.emitVMLog(name, "Warning: could not load Guest Tools config: "+err.Error())
return
}
if !attached {
return
merged := reims.StripGuestToolsNetworkArgs(cur.ExtraArgs)
if cur.NetworkMode == "bridge" && a.npcapPluginEnabled() {
tokens, argsErr := reims.GuestToolsNetworkUnixArgs(cur.Directory, cfg.ManagementOutSock, cfg.ManagementInSock)
if argsErr != nil {
a.emitLog(name, networkmsg.Localize(argsErr, a.locale()).Error())
return
}
merged = strings.TrimSpace(merged + " " + strings.Join(tokens, " "))
} else {
srv.StopManagementNetwork(name)
}
imgPath := a.guestToolsImagePath(name)
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
a.emitVMLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error())
return
if attached {
imgPath := a.guestToolsImagePath(name)
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
a.emitLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error())
return
}
merged = reims.MergeGuestToolsArgs(merged, imgPath)
}
merged := reims.MergeGuestToolsArgs(cur.ExtraArgs, imgPath)
if merged != cur.ExtraArgs {
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err == nil {
cur.ExtraArgs = merged
+113
View File
@@ -0,0 +1,113 @@
package app
import (
"context"
"net"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/packetbridge"
)
func installDummyRuntime(t *testing.T, root string) {
t.Helper()
rtDir := folderTestDir(t, root, "runtimes", "test-rt")
binDir := folderTestDir(t, rtDir, "bin")
if err := os.WriteFile(filepath.Join(rtDir, "manifest.json"), []byte(`{"id":"test-rt","version":"test-rt","channel":"stable"}`), 0o600); err != nil {
t.Fatal(err)
}
for _, bin := range []string{"reims-ctl.exe", "qemu-system-x86_64.exe", "qemu-img.exe", "reims-util.exe"} {
if err := os.WriteFile(filepath.Join(binDir, bin), []byte("stub"), 0o600); err != nil {
t.Fatal(err)
}
}
}
func TestGuestToolsManagementPreservesSharedConfig(t *testing.T) {
root := t.TempDir()
installDummyRuntime(t, root)
vm := folderTestVM(t, root)
srv := guesttools.NewTransportServer(nil)
t.Cleanup(func() { _ = srv.Close(context.Background()) })
a := &App{cfg: &config.Config{DataRoot: root, ActiveRuntime: "test-rt"}}
cfg, err := guesttools.LoadOrCreateVMConfig(vm.Directory, vm.Name, a.vmSharedDir(vm.Name), 19847)
if err != nil {
t.Fatal(err)
}
cfg.SharedFolders = []guesttools.SharedFolderConfig{{ID: "work", Name: "Work"}}
cfg.ManagementOutPort, cfg.ManagementInPort = 12001, 12002
if err := guesttools.SaveVMConfig(vm.Directory, cfg); err != nil {
t.Fatal(err)
}
bridge, err := a.loadAndRegisterGuestTools(srv, 19847, vm.Directory, vm.Name, 0, "bridge")
if err != nil || bridge.ManagementOutSock == "" || bridge.ManagementInSock == "" {
t.Fatalf("AF_UNIX 管理通道未建立: %v (cfg=%+v)", err, bridge)
}
if bridge.ManagementOutPort != 0 || bridge.ManagementInPort != 0 {
t.Fatal("冷启动迁移仍残留旧 TCP 端口")
}
saved, ok := guesttools.ReadVMConfig(vm.Directory)
if !ok || len(saved.SharedFolders) != 1 || saved.SharedFolders[0].ID != "work" || saved.Token != cfg.Token || saved.ManagementOutSock != bridge.ManagementOutSock {
t.Fatal("写入管理通道破坏了已有共享配置")
}
if _, err := a.loadAndRegisterGuestTools(srv, 19847, vm.Directory, vm.Name, 0, "nat"); err != nil {
t.Fatal(err)
}
for _, sock := range []string{bridge.ManagementOutSock, bridge.ManagementInSock} {
conn, err := net.DialTimeout("unix", sock, 100*time.Millisecond)
if err == nil {
conn.Close()
t.Fatal("NAT 模式仍保留管理监听")
}
}
}
func TestLegacyNetworkRejectedBeforeRestoreAndHotSwitch(t *testing.T) {
dir := t.TempDir()
d := reims.VMDetail{Name: "test", Directory: dir,
ExtraArgs: "-netdev stream,id=reimsbridge0,server=off,addr.type=unix,addr.path=bridge.sock -device virtio-net-pci,netdev=reimsbridge0"}
legacy := guesttools.VMConfig{VMName: d.Name, Token: strings.Repeat("a", 32), ManagementOutPort: 12001, ManagementInPort: 12002}
if err := guesttools.SaveVMConfig(dir, legacy); err != nil {
t.Fatal(err)
}
for _, path := range []string{reims.SuspendStatePath(dir), reims.SuspendMetaPath(dir)} {
if err := os.WriteFile(path, []byte("preserve"), 0o600); err != nil {
t.Fatal(err)
}
}
a := &App{}
for _, run := range []func() error{
func() error { return a.restoreVMNetworkChannels(context.Background(), nil, d, reims.NetworkRecord{}) },
func() error { return a.preparePacketNetwork(context.Background(), nil, d, reims.NetworkRecord{}, true) },
func() error {
return a.switchPacketUplink(context.Background(), nil, d, packetbridge.Adapter{}, reims.NetworkRecord{})
},
} {
err := run()
coded, ok := err.(*i18n.CodedError)
if !ok || coded.Code != "E_NETWORK_LEGACY_TRANSPORT" {
t.Fatalf("恢复或热切未在外部调用前拒绝旧管理端点: %v", err)
}
for _, path := range []string{reims.SuspendStatePath(dir), reims.SuspendMetaPath(dir)} {
data, err := os.ReadFile(path)
if err != nil || string(data) != "preserve" {
t.Fatal("拒绝恢复后改变了挂起状态")
}
}
}
// 主通道仍为旧 TCP 时,即便管理通道不存在,也不能恢复。
if err := os.Remove(filepath.Join(dir, guesttools.ConfigFileName)); err != nil {
t.Fatal(err)
}
d.ExtraArgs = "-netdev stream,id=reimsbridge0,server=off,addr.type=inet,addr.host=127.0.0.1,addr.port=12003 -device virtio-net-pci,netdev=reimsbridge0"
if err := requireExistingUnixNetwork(d); err == nil {
t.Fatal("接受了旧主通道")
}
}
+365
View File
@@ -0,0 +1,365 @@
package app
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/qmp"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
const MaxHostDropFileBytes int64 = 2 << 30
const MaxHostDropTotalBytes int64 = 4 << 30
const MaxHostDropFolderFiles = 256
func dropSegment(s string) bool {
return filepath.IsLocal(s) && !strings.HasPrefix(s, ".") &&
!strings.ContainsAny(s, "/\\\x00:\u003c\u003e|\"?*\r\n")
}
var hostDropPublishMu sync.Mutex
var errDropSize = errors.New("host drop size limit exceeded")
func validateHostDropPath(raw string) (string, error) {
if strings.TrimSpace(raw) == "" || strings.ContainsRune(raw, 0) ||
strings.HasPrefix(strings.ReplaceAll(raw, "\\", "/"), "//") || !filepath.IsAbs(raw) {
return "", fmt.Errorf("%w: expected an absolute local path", guesttools.ErrInvalidHostDrop)
}
clean := filepath.Clean(raw)
st, err := os.Lstat(clean)
if err != nil {
return "", fmt.Errorf("%w: %v", guesttools.ErrInvalidHostDrop, err)
}
if guesttools.IsDropSymlink(st) {
return "", fmt.Errorf("%w: symbolic link", guesttools.ErrInvalidHostDrop)
}
return clean, nil
}
func allocUniqueDropName(base string, splitExt bool, claim func(string) (bool, error)) (string, error) {
var ext string
if splitExt {
ext = filepath.Ext(base)
}
stem := strings.TrimSuffix(base, ext)
candidate := base
for n := 1; ; n++ {
claimed, err := claim(candidate)
if err != nil {
return "", err
}
if claimed {
return candidate, nil
}
candidate = fmt.Sprintf("%s (%d)%s", stem, n, ext)
}
}
func uniqueDropEntryName(used map[string]struct{}, base string, isDir bool) string {
name, _ := allocUniqueDropName(base, !isDir, func(candidate string) (bool, error) {
if _, exists := used[candidate]; exists {
return false, nil
}
used[candidate] = struct{}{}
return true, nil
})
return name
}
func (a *App) handleHostDrop(vmKey, name string, req guesttools.HostDropRequest) (guesttools.HostDropResult, error) {
var id [16]byte
rand.Read(id[:])
result := guesttools.HostDropResult{
DropID: hex.EncodeToString(id[:]), Delivered: []string{},
}
srv := a.currentGuestToolsServer()
hasListener := srv != nil && srv.HasDropEventListener(vmKey)
event := guesttools.DropEvent{
DropID: result.DropID, DisplayIndex: req.DisplayIndex, NormX: req.NormX,
NormY: req.NormY, InImage: req.InImage,
}
if req.Text != "" {
result.Mode = "text_ignored"
event.Kind, event.Text = "text", req.Text
if hasListener && srv.EnqueueDropEvent(vmKey, event) {
result.Mode = "l2_text"
}
return result, nil
}
paths := make([]string, 0, len(req.Paths))
for _, raw := range req.Paths {
path, err := validateHostDropPath(raw)
if err != nil {
return result, err
}
paths = append(paths, path)
}
if hasListener {
used := make(map[string]struct{})
var entries []guesttools.DropShareEntry
for _, path := range paths {
st, err := os.Lstat(path)
if err != nil {
return result, err
}
base := filepath.Base(path)
if !dropSegment(base) || guesttools.IsDropSymlink(st) || (!st.IsDir() && !st.Mode().IsRegular()) {
result.Skipped = append(result.Skipped, base)
continue
}
alias := uniqueDropEntryName(used, base, st.IsDir())
entries = append(entries, guesttools.DropShareEntry{Name: alias, HostPath: path, IsDir: st.IsDir()})
result.Delivered = append(result.Delivered, alias)
}
if len(entries) > 0 {
if !srv.RegisterDropShare(vmKey, result.DropID, entries) {
result.Delivered = []string{}
return result, errors.New("could not register drop share")
}
event.Kind, event.WebDAVDrop = "files", true
event.Items, event.TargetPaths = result.Delivered, result.Delivered
if !srv.EnqueueDropEvent(vmKey, event) {
srv.RevokeDropShare(vmKey, result.DropID)
result.Delivered = []string{}
return result, errors.New("could not enqueue file drop")
}
result.Mode = "l2_webdav"
}
return result, nil
}
result.Mode = "l1_share"
var total int64
var fileCount int
sharedDir := a.vmSharedDir(name)
for _, path := range paths {
st, err := os.Lstat(path)
if err != nil {
return result, err
}
base := filepath.Base(path)
if !dropSegment(base) || guesttools.IsDropSymlink(st) || fileCount >= MaxHostDropFolderFiles {
result.Skipped = append(result.Skipped, base)
continue
}
if st.IsDir() {
folder, nested, size, err := stageDropFolder(sharedDir, path, MaxHostDropFolderFiles-fileCount, MaxHostDropTotalBytes-total)
if err != nil {
return result, err
}
if len(nested) == 0 {
result.Skipped = append(result.Skipped, base)
continue
}
total += size
result.Delivered = append(result.Delivered, folder)
fileCount += len(nested)
continue
}
if !st.Mode().IsRegular() {
result.Skipped = append(result.Skipped, base)
continue
}
delivered, size, err := a.deliverHostFileLimited(name, path, st, min(MaxHostDropFileBytes, MaxHostDropTotalBytes-total))
if errors.Is(err, errDropSize) {
a.emitVMLog(name, fmt.Sprintf("Skipped %s: host drop size limit exceeded", base))
result.Skipped = append(result.Skipped, base)
continue
}
if err != nil {
return result, err
}
total += size
fileCount++
result.Delivered = append(result.Delivered, delivered)
}
a.emitVMLog(name, fmt.Sprintf("Host drop %s: delivered %d, skipped %d", result.DropID, len(result.Delivered), len(result.Skipped)))
if a.ctx != nil && len(result.Delivered) > 0 {
wailsRuntime.EventsEmit(a.ctx, "reims:host-drop", map[string]any{
"vm": name, "drop_id": result.DropID, "delivered": result.Delivered, "skipped": result.Skipped, "mode": result.Mode,
})
}
return result, nil
}
func (a *App) currentGuestToolsServer() *guesttools.Server {
a.mu.Lock()
defer a.mu.Unlock()
return a.guestTools
}
var sendDropClickAndPaste = qmp.SendAbsoluteClickAndPaste
var defaultDropClickAndPaste = true
func (a *App) handleHostDropPaste(ctx context.Context, vmKey, name, dropID string, displayIndex int, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error {
if _, running := a.currentVMPID(ctx, name); !running {
return fmt.Errorf("%s is not running", name)
}
d, err := a.GetVMDetail(name)
if err != nil {
return err
}
if defaultDropClickAndPaste && fmt.Sprintf("%p", sendDropClickAndPaste) == fmt.Sprintf("%p", qmp.SendAbsoluteClickAndPaste) {
if svc, svcErr := a.computerUseService(); svcErr == nil && svc != nil {
return svc.SendAbsoluteClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait)
}
}
return sendDropClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait)
}
func (a *App) handleHostDropAck(vmKey, name string, ack guesttools.DropEventAck) {
revoke := ack.Status == "placed" || ack.Status == "cancelled" || ack.Status == "failed"
if srv := a.currentGuestToolsServer(); srv != nil && revoke {
srv.RevokeDropShare(vmKey, ack.DropID)
}
a.emitVMLog(name, fmt.Sprintf("Host drop %s: %s (%s)", ack.DropID, ack.Status, ack.TargetKind))
if ack.Status != "cancelled" && a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:host-drop-ack", map[string]any{
"vm": name, "drop_id": ack.DropID, "status": ack.Status, "target_kind": ack.TargetKind,
"target_label": ack.TargetLabel, "placed_names": ack.PlacedNames, "error": ack.Error,
})
}
}
func allocUniqueDir(parent, base string) (string, error) {
hostDropPublishMu.Lock()
defer hostDropPublishMu.Unlock()
return allocUniqueDropName(base, false, func(candidate string) (bool, error) {
err := os.Mkdir(filepath.Join(parent, candidate), 0o755)
if errors.Is(err, os.ErrExist) {
return false, nil
}
return err == nil, err
})
}
func stageDropFolder(shared, src string, count int, limit int64) (string, []string, int64, error) {
type entry struct {
rel string
st os.FileInfo
}
var files []entry
var estimated int64
var walk func(string, int) error
walk = func(rel string, depth int) error {
dir := filepath.Join(src, rel)
children, err := os.ReadDir(dir)
if err != nil {
return err
}
for _, child := range children {
if len(files) == count {
break
}
if !dropSegment(child.Name()) {
continue
}
next := filepath.Join(rel, child.Name())
st, err := os.Lstat(filepath.Join(src, next))
if err != nil {
return err
}
if guesttools.IsDropSymlink(st) {
continue
}
if st.IsDir() && depth < guesttools.MaxSharedDepth {
if err := walk(next, depth+1); err != nil {
return err
}
}
if st.Mode().IsRegular() && st.Size() <= min(MaxHostDropFileBytes, limit-estimated) {
files = append(files, entry{next, st})
estimated += st.Size()
}
}
return nil
}
if err := walk("", 2); err != nil || len(files) == 0 {
return "", nil, 0, err
}
if err := os.MkdirAll(shared, 0o755); err != nil {
return "", nil, 0, err
}
folder, err := allocUniqueDir(shared, filepath.Base(src))
if err != nil {
return "", nil, 0, err
}
dest := filepath.Join(shared, folder)
var items []string
var total int64
for _, f := range files {
parent := filepath.Dir(filepath.Join(dest, f.rel))
base, size, err := deliverHostFileLimited(parent, filepath.Join(src, f.rel), f.st, min(MaxHostDropFileBytes, limit-total))
if err != nil {
return "", nil, 0, errors.Join(err, os.RemoveAll(dest))
}
items = append(items, filepath.ToSlash(filepath.Join(folder, filepath.Dir(f.rel), base)))
total += size
}
return folder, items, total, nil
}
func (a *App) deliverHostFileLimited(name, path string, expected os.FileInfo, limit int64) (string, int64, error) {
return deliverHostFileLimited(a.vmSharedDir(name), path, expected, limit)
}
func deliverHostFileLimited(dir, path string, expected os.FileInfo, limit int64) (string, int64, error) {
if expected.Size() > limit {
return "", 0, errDropSize
}
src, err := os.Open(path)
if err != nil {
return "", 0, err
}
defer src.Close()
st, err := src.Stat()
if err != nil {
return "", 0, err
}
if !st.Mode().IsRegular() || !os.SameFile(expected, st) {
return "", 0, fmt.Errorf("%w: source changed", guesttools.ErrInvalidHostDrop)
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", 0, err
}
tmp, err := os.CreateTemp(dir, ".reims-deliver-*")
if err != nil {
return "", 0, err
}
defer os.Remove(tmp.Name())
size, copyErr := io.Copy(tmp, io.LimitReader(src, limit+1))
closeErr := tmp.Close()
if err := errors.Join(copyErr, closeErr); err != nil {
return "", 0, err
}
if size > limit {
return "", 0, errDropSize
}
base, err := deliverHostFileUnique(dir, filepath.Base(path), tmp.Name())
return base, size, err
}
// Link publishes the completed file atomically and fails if another writer
// already owns the name, including writers outside this process.
func deliverHostFileUnique(dir, base, tmp string) (string, error) {
hostDropPublishMu.Lock()
defer hostDropPublishMu.Unlock()
return allocUniqueDropName(base, true, func(candidate string) (bool, error) {
err := os.Link(tmp, filepath.Join(dir, candidate))
if errors.Is(err, os.ErrExist) {
return false, nil
}
return err == nil, err
})
}
+210
View File
@@ -0,0 +1,210 @@
package app
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
)
func TestValidateHostDropPath(t *testing.T) {
for _, raw := range []string{"", " ", "relative", `\\server\share`, "//server/share", `\\?\C:\foo`, `\\.\pipe\x`, "a\x00b"} {
if _, err := validateHostDropPath(raw); err == nil {
t.Errorf("accepted %q", raw)
}
}
t.Run("symlink", func(t *testing.T) {
dir := t.TempDir()
link := filepath.Join(dir, "link")
if err := os.Symlink(dir, link); err != nil {
t.Skipf("symlink unavailable: %v", err)
}
if _, err := validateHostDropPath(link); err == nil {
t.Fatal("accepted symlink")
}
})
}
func TestHostDropUniqueDelivery(t *testing.T) {
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}}
dir := a.vmSharedDir("mac")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
write := func(path, contents string) {
t.Helper()
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
t.Fatal(err)
}
}
first := filepath.Join(t.TempDir(), "demo.txt")
second := filepath.Join(t.TempDir(), "demo.txt")
write(first, "one")
write(second, "two")
write(filepath.Join(dir, "demo.txt"), "original")
skip := t.TempDir()
res, err := a.handleHostDrop("mac", "mac", guesttools.HostDropRequest{Paths: []string{first, skip, second}})
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(res.Delivered, []string{"demo (1).txt", "demo (2).txt"}) ||
!reflect.DeepEqual(res.Skipped, []string{filepath.Base(skip)}) || len(res.DropID) != 32 || res.Mode != "l1_share" {
t.Fatalf("unexpected result: %+v", res)
}
for name, want := range map[string]string{"demo.txt": "original", "demo (1).txt": "one", "demo (2).txt": "two"} {
data, err := os.ReadFile(filepath.Join(dir, name))
if err != nil || string(data) != want {
t.Errorf("%s: got %q, err %v", name, data, err)
}
}
}
func TestHostDropL2QueueAndCleanup(t *testing.T) {
a, cfg, request := queuedDropFixture(t)
key := driver.NewVMRef(cfg.DriverID, cfg.VMName).Key()
src := filepath.Join(t.TempDir(), "demo.txt")
if err := os.WriteFile(src, []byte("new"), 0o600); err != nil {
t.Fatal(err)
}
for _, status := range []string{"pasted", "placed", "cancelled", "failed"} {
res, err := a.handleHostDrop(key, cfg.VMName, guesttools.HostDropRequest{Paths: []string{src}})
if err != nil || res.Mode != "l2_webdav" || !reflect.DeepEqual(res.Delivered, []string{"demo.txt"}) {
t.Fatalf("drop %+v: %v", res, err)
}
var ev guesttools.DropEvent
if err := json.Unmarshal(request("GET", "/v1/drop-events?wait=0", "", 200), &ev); err != nil ||
ev.DropID != res.DropID || ev.Kind != "files" || !ev.WebDAVDrop ||
!reflect.DeepEqual(ev.Items, res.Delivered) || !reflect.DeepEqual(ev.TargetPaths, res.Delivered) {
t.Fatalf("event %+v: %v", ev, err)
}
requireEmptyDropDir(t, a.vmSharedDir(cfg.VMName))
dav := "/dav-drop/mac/" + ev.DropID + "/demo.txt"
file := "/v1/drop-file?drop_id=" + ev.DropID + "&path=demo.txt"
for _, route := range []string{dav, file} {
if data := request("GET", route, "", 200); string(data) != "new" {
t.Fatalf("%s: %q", route, data)
}
}
body := fmt.Sprintf(`{"drop_id":%q,"status":%q,"target_kind":"share"}`, ev.DropID, status)
request("POST", "/v1/drop-events/ack", body, 200)
if status == "pasted" {
if data := request("GET", dav, "", 200); string(data) != "new" {
t.Fatalf("after paste: %q", data)
}
} else {
request("GET", dav, "", 404)
}
}
}
func queuedDropFixture(t *testing.T) (*App, guesttools.VMConfig, func(string, string, string, int) []byte) {
t.Helper()
srv := guesttools.NewServer(nil)
port, err := srv.Start(-1)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { srv.Close(context.Background()) })
cfg := guesttools.VMConfig{VMName: "mac", Token: "guest"}
srv.RegisterVM(cfg)
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, guestTools: srv}
srv.SetDropAckHandler(a.handleHostDropAck)
const path = "/v1/drop-events"
request := func(method, route, body string, status int) []byte {
t.Helper()
req, err := http.NewRequest(method, fmt.Sprintf("http://127.0.0.1:%d%s", port, route), strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
if strings.HasPrefix(route, "/dav-drop/") {
req.SetBasicAuth(cfg.VMName, cfg.Token)
} else {
req.Header.Set("Authorization", "Bearer "+cfg.Token)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil || resp.StatusCode != status {
t.Fatalf("response %d %q: %v", resp.StatusCode, data, err)
}
return data
}
request("GET", path+"?wait=0", "", 204)
return a, cfg, request
}
func TestHostDropRecursiveFolder(t *testing.T) {
a, cfg, request := queuedDropFixture(t)
shared := a.vmSharedDir(cfg.VMName)
src := filepath.Join(t.TempDir(), "MyFolder")
empty := filepath.Join(t.TempDir(), "empty")
for _, dir := range []string{filepath.Join(src, "sub"), empty} {
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
}
for _, file := range []string{filepath.Join(src, "a.txt"), filepath.Join(src, "sub", "b.txt")} {
if err := os.WriteFile(file, []byte(filepath.Base(file)), 0o600); err != nil {
t.Fatal(err)
}
}
key := driver.NewVMRef(cfg.DriverID, cfg.VMName).Key()
res, err := a.handleHostDrop(key, cfg.VMName, guesttools.HostDropRequest{Paths: []string{src, empty}})
want := []string{"MyFolder", "empty"}
if err != nil || res.Mode != "l2_webdav" || !reflect.DeepEqual(res.Delivered, want) {
t.Fatalf("result %+v: %v", res, err)
}
var event guesttools.DropEvent
if err := json.Unmarshal(request("GET", "/v1/drop-events?wait=0", "", 200), &event); err != nil ||
event.Kind != "files" || !event.WebDAVDrop || event.DropID != res.DropID ||
!reflect.DeepEqual(event.Items, want) || !reflect.DeepEqual(event.TargetPaths, want) {
t.Fatalf("event %+v: %v", event, err)
}
requireEmptyDropDir(t, shared)
for _, item := range []string{"MyFolder/a.txt", "MyFolder/sub/b.txt"} {
for _, route := range []string{
"/dav-drop/mac/" + res.DropID + "/" + item,
"/v1/drop-file?drop_id=" + res.DropID + "&path=" + item,
} {
if data := request("GET", route, "", 200); string(data) != filepath.Base(item) {
t.Fatalf("%s: %q", route, data)
}
}
}
}
func requireEmptyDropDir(t *testing.T, dir string) {
t.Helper()
entries, err := os.ReadDir(dir)
if (err != nil && !os.IsNotExist(err)) || len(entries) != 0 {
t.Fatalf("unexpected ReimsShare contents %v: %v", entries, err)
}
}
func TestHostDropText(t *testing.T) {
a, cfg, request := queuedDropFixture(t)
key := driver.NewVMRef(cfg.DriverID, cfg.VMName).Key()
const value = "https://example.com"
res, err := a.handleHostDrop(key, cfg.VMName, guesttools.HostDropRequest{Text: value})
if err != nil || res.Mode != "l2_text" || len(res.Delivered) != 0 {
t.Fatalf("result %+v: %v", res, err)
}
var ev guesttools.DropEvent
if err := json.Unmarshal(request("GET", "/v1/drop-events?wait=0", "", 200), &ev); err != nil ||
ev.DropID != res.DropID || ev.Kind != "text" || ev.Text != value {
t.Fatalf("event %+v: %v", ev, err)
}
}
+2 -2
View File
@@ -341,7 +341,7 @@ func (a *App) finishInstallLegacy(name string) error {
setOpts := reims.SetOpts{Name: name}
needSet := false
upgradedNVMe := false
if !d.Network {
if !d.Network && d.NetworkMode != "bridge" && d.NetworkMode != "custom" {
on := true
setOpts.Network = &on
needSet = true
@@ -370,7 +370,7 @@ func (a *App) finishInstallLegacy(name string) error {
if d.HasInstaller {
diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"})
}
if !d.Network {
if setOpts.Network != nil {
diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"})
}
if upgradedNVMe {
+11 -5
View File
@@ -81,7 +81,7 @@ func (a *App) resolveVMInfo(driverID, name string) (driver.VMInfo, error) {
if err != nil {
return driver.VMInfo{}, err
}
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: resolveVMDiskPath(detail), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort}, nil
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort}, nil
}
func (a *App) GetVMInfo(driverID, name string) (driver.VMInfo, error) {
@@ -198,6 +198,9 @@ func (a *App) stopVMWithDriverCtx(ctx context.Context, driverID, name string, fo
a.mu.Unlock()
return err
}
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.stopPacketBridge(ref.Name)
}
a.mu.Lock()
delete(a.pendingChanges, key)
a.mu.Unlock()
@@ -277,7 +280,7 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error {
}
return a.deleteVMLegacy(name, keepFiles)
}
_, vm, err := svc.Resolve(context.Background(), driverID, name)
d, vm, err := svc.ResolveForDelete(context.Background(), driverID, name)
if err != nil {
return err
}
@@ -290,7 +293,7 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error {
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
removed, delErr := a.deleteVMWithGuestTools(ref.Name, func() error {
return svc.Delete(context.Background(), ref, keepFiles, w, w)
return svc.DeleteResolved(context.Background(), d, vm, keepFiles, w, w)
}, func() (bool, error) {
vms, lerr := a.listVMsInternal(context.Background())
if lerr != nil {
@@ -308,10 +311,13 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error {
}
err = delErr
} else {
if err := svc.Delete(context.Background(), ref, keepFiles, w, w); err != nil {
if err := svc.DeleteResolved(context.Background(), d, vm, keepFiles, w, w); err != nil {
return err
}
}
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.stopPacketBridge(ref.Name)
}
a.mu.Lock()
delete(a.pendingChanges, key)
delete(a.transitions, key)
@@ -328,5 +334,5 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error {
}
a.wakePoll()
a.emitLifecycleStateChanged()
return nil
return err
}
+380
View File
@@ -1,13 +1,26 @@
package app
import (
"context"
"errors"
"fmt"
"io"
"path/filepath"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/networkmsg"
"github.com/Nwflower/reims-go/internal/packetbridge"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
@@ -47,3 +60,370 @@ func enrichMacOSVMListStates(vms []driver.VMListItem) {
}
}
}
type vmNetworkLock struct {
mu sync.Mutex
refs int
}
func (a *App) lockVMNetwork(name string) func() {
key := strings.ToLower(strings.TrimSpace(name))
a.vmNetworkLocksMu.Lock()
entry, _ := a.vmNetworkLocks.LoadOrStore(key, &vmNetworkLock{})
lock := entry.(*vmNetworkLock)
// 等待者先取得引用,避免当前持有者退出时把同一 VM 拆成两把锁。
lock.refs++
a.vmNetworkLocksMu.Unlock()
lock.mu.Lock()
return func() {
lock.mu.Unlock()
a.vmNetworkLocksMu.Lock()
lock.refs--
if lock.refs == 0 {
a.vmNetworkLocks.Delete(key)
}
a.vmNetworkLocksMu.Unlock()
}
}
func (a *App) tempDir() string {
a.mu.Lock()
defer a.mu.Unlock()
if a.cfg == nil {
return ""
}
return a.cfg.TempDir()
}
func (a *App) activeQemuPath() string {
a.mu.Lock()
if a.cfg == nil {
a.mu.Unlock()
return ""
}
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil || active == nil {
return ""
}
return active.QemuPath()
}
func (a *App) npcapPluginEnabled() bool {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return true
}
if mgr.Registry().IsActive(builtin.IDNpcapBridge) {
return true
}
return mgr.DesiredFor(builtin.IDNpcapBridge, true) && mgr.Registry().StateOf(builtin.IDNpcapBridge) != plugin.StateFailed
}
// prepareManagedVMNetwork 由所属驱动在持有虚拟机操作锁时调用。
// 仅对桥接 VM 获取共享启动锁并准备 Npcap/管理通道;NAT 与无网络 VM 零锁直通。
func (a *App) prepareManagedVMNetwork(ctx context.Context, name string, resume bool) (release func(), err error) {
defer a.localizeNetworkError(&err)
c, err := a.client()
if err != nil {
return nil, err
}
d, err := c.Show(ctx, name)
if err != nil {
return nil, err
}
record, err := reims.ReadNetworkRecord(d.Directory)
if err != nil {
return nil, err
}
if record.Corrupt {
return nil, networkmsg.Error("record_invalid", nil)
}
if record.Pending {
return nil, networkmsg.Error("packet_pending", nil)
}
if d.NetworkMode != "bridge" {
if !resume {
a.stopPacketBridge(d.Name)
}
return nil, nil
}
if !a.npcapPluginEnabled() {
return nil, networkmsg.Error("plugin_disabled", nil)
}
releaseGuard, err := packetbridge.AcquireBridgeStart()
if err != nil {
return nil, err
}
if resume {
err = a.restoreVMNetworkChannels(ctx, c, d, record)
} else {
err = a.preparePacketNetwork(ctx, c, d, record, false)
}
if err != nil {
releaseGuard()
return nil, err
}
return releaseGuard, nil
}
func (a *App) ensureNpcap(ctx context.Context, c networkControlClient, heldDirs ...string) error {
if packetbridge.Available() == nil {
return nil
}
release, _, err := lockNetworkVMs(ctx, c, heldDirs...)
if err != nil {
return err
}
defer release()
checkIdle := func() error {
running, err := a.networkRunningVMs(ctx, c)
if err != nil {
return err
}
if len(running) > 0 {
return networkmsg.Error("all_stop_first", nil, "names", strings.Join(running, ", "))
}
return nil
}
if err := checkIdle(); err != nil {
return err
}
a.mu.Lock()
root := a.cfg.DataRoot
a.mu.Unlock()
return packetbridge.EnsureInstalled(ctx, filepath.Join(root, "cache"), checkIdle, func(key string) { a.emitLog("network", networkmsg.Text(a.locale(), key)) })
}
// 恢复挂起虚拟机仅重开已保存的宿主通道,不修改封存的设备参数。
func (a *App) restoreVMNetworkChannels(ctx context.Context, c *reims.Client, d reims.VMDetail, record reims.NetworkRecord) error {
if err := requireExistingUnixNetwork(d); err != nil {
return err
}
if err := a.preparePacketNetwork(ctx, c, d, record, true); err != nil {
return err
}
cfg, ok := guesttools.ReadVMConfig(d.Directory)
hasMgmt := (cfg.ManagementOutSock != "" && cfg.ManagementInSock != "") || (cfg.ManagementOutPort > 0 && cfg.ManagementInPort > 0)
if ok && hasMgmt && a.guestToolsEnabled() {
srv, _, err := a.ensureGuestToolsBridge()
if err != nil {
return err
}
cfg.VMDir = d.Directory
cfg.QEMUPath = a.activeQemuPath()
if _, err := srv.EnsureManagementNetwork(cfg); err != nil {
return err
}
validated, _ := a.validatedShareConfig(cfg)
srv.RegisterVM(validated)
}
return nil
}
// 旧挂起参数不能原地改写;先拒绝全部旧端点,避免只恢复了一半通道。
func requireExistingUnixNetwork(d reims.VMDetail) error {
if err := reims.RequireUnixNetworkTransports(d.ExtraArgs); err != nil {
return err
}
if err := packetbridge.RequireUnixEndpoint(reims.PacketBridgeSocket(d.ExtraArgs), reims.PacketBridgePort(d.ExtraArgs)); err != nil {
return err
}
cfg, ok, err := guesttools.ReadVMConfigStrict(d.Directory)
if err != nil {
return networkmsg.Error("management_channel", err)
}
if ok && (cfg.ManagementOutSock != "" || cfg.ManagementInSock != "" || cfg.ManagementOutPort != 0 || cfg.ManagementInPort != 0) {
if err := packetbridge.RequireUnixEndpoint(cfg.ManagementOutSock, cfg.ManagementOutPort); err != nil {
return err
}
return packetbridge.RequireUnixEndpoint(cfg.ManagementInSock, cfg.ManagementInPort)
}
return nil
}
// InstallNpcap 供网络设置及新建向导使用,与自动准备共享相同的关机检查。
func (a *App) InstallNpcap() (err error) {
defer a.localizeNetworkError(&err)
if err := a.requireWritableDataRoot(); err != nil {
return err
}
c, err := a.client()
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(a.baseCtx(), 20*time.Minute)
defer cancel()
return a.ensureNpcap(ctx, c)
}
// 整组网络操作与 GUI、CLI 共用虚拟机锁;调用方已持有的锁由调用方释放。
func lockNetworkVMs(ctx context.Context, c networkControlClient, heldDirs ...string) (func(), []string, error) {
key := func(dir string) string { return strings.ToLower(filepath.Clean(dir)) }
held := make(map[string]bool, len(heldDirs))
for _, dir := range heldDirs {
held[key(dir)] = true
}
var releases []func()
release := func() {
for i := len(releases) - 1; i >= 0; i-- {
releases[i]()
}
}
list, err := c.List(ctx)
if err != nil {
return nil, nil, err
}
sort.Slice(list, func(i, j int) bool { return list[i].Name < list[j].Name })
dirs := make(map[string]string, len(list))
lockedDirs := append([]string(nil), heldDirs...)
for _, item := range list {
d, err := c.Show(ctx, item.Name)
if err == nil && strings.TrimSpace(d.Directory) == "" {
err = networkmsg.Error("directory_missing", nil)
}
if err == nil && !held[key(d.Directory)] {
var unlock func()
unlock, err = reims.LockVMOperation(d.Directory)
if err == nil {
releases = append(releases, unlock)
held[key(d.Directory)] = true
lockedDirs = append(lockedDirs, d.Directory)
}
}
if err != nil {
release()
return nil, nil, networkmsg.Error("vm_lock", err, "name", item.Name)
}
dirs[item.Name] = key(d.Directory)
}
// 加锁后重新核对身份,避免外部操作在初次读取与取得锁之间移动虚拟机。
current, err := c.List(ctx)
if err == nil && len(current) != len(list) {
err = networkmsg.Error("vm_list_changed", nil)
}
if err == nil {
for _, item := range current {
d, readErr := c.Show(ctx, item.Name)
if readErr != nil {
err = readErr
break
}
if dirs[item.Name] != key(d.Directory) {
err = networkmsg.Error("vm_directory_changed", nil, "name", item.Name)
break
}
}
}
if err != nil {
release()
return nil, nil, err
}
return release, lockedDirs, nil
}
type networkControlClient interface {
List(context.Context) ([]reims.VMListItem, error)
Show(context.Context, string) (reims.VMDetail, error)
CommandText(context.Context, string) (string, error)
Set(context.Context, reims.SetOpts, io.Writer, io.Writer) error
}
type VMNetworkPlan struct {
NpcapInstalled bool `json:"npcap_installed"`
RunningVMs []string `json:"running_vms"`
}
func adapterGUIDKey(guid string) string {
return strings.ToLower(strings.Trim(strings.TrimSpace(guid), "{}"))
}
func networkVMRunning(item reims.VMListItem, detail reims.VMDetail, transition string) bool {
active := func(state string) bool {
return slices.Contains([]string{"running", "starting", "stopping", "paused", "suspended", "suspending", "resuming"}, state)
}
return transition != "" || active(item.State) || active(detail.State) || (item.PID != nil && *item.PID > 0) || (detail.Directory != "" && reims.HasSuspendState(detail.Directory))
}
// 安装驱动前核对所有虚拟机;切换单台网络无需中断其他虚拟机。
func (a *App) networkRunningVMs(ctx context.Context, c networkControlClient) ([]string, error) {
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
if svc != nil {
list, err := svc.List(ctx)
if err != nil {
return nil, networkmsg.Error("vm_list_check", err)
}
running := []string{}
a.mu.Lock()
for _, vm := range list {
if networkVMRunning(reims.VMListItem{State: vm.State, PID: vm.PID}, reims.VMDetail{Directory: vm.Directory}, a.transitions[vm.Ref().Key()]) {
running = append(running, vm.Name)
}
}
a.mu.Unlock()
sort.Strings(running)
return running, nil
}
list, err := c.List(ctx)
if err != nil {
return nil, networkmsg.Error("vm_list_check", err)
}
a.mu.Lock()
transitions := make(map[string]string, len(a.transitions))
for name, value := range a.transitions {
transitions[name] = value
}
a.mu.Unlock()
running := make([]string, 0)
for _, item := range list {
detail := reims.VMDetail{Directory: item.Dir}
if detail.Directory == "" {
var showErr error
detail, showErr = c.Show(ctx, item.Name)
if showErr != nil {
return nil, networkmsg.Error("vm_network_check", showErr, "name", item.Name)
}
}
if networkVMRunning(item, detail, transitions[vmKey(item.Name)]) {
running = append(running, item.Name)
}
}
sort.Strings(running)
return running, nil
}
func (a *App) GetVMNetworkPlan(name, mode, uplink string) (result VMNetworkPlan, err error) {
defer a.localizeNetworkError(&err)
if mode != "bridge" && mode != "nat" && mode != "off" {
return result, networkmsg.Error("mode_invalid", nil)
}
if name == "" {
return result, networkmsg.Error("vm_name_missing", nil)
}
ctx, cancel := context.WithTimeout(a.baseCtx(), 30*time.Second)
defer cancel()
if mode == "bridge" {
adapters, err := packetbridge.ListAdapters(ctx)
if err != nil {
return result, err
}
if _, err := selectPacketUplink(adapters, uplink); err != nil {
return result, err
}
}
c, err := a.client()
if err != nil {
return result, err
}
result.NpcapInstalled = packetbridge.Available() == nil
result.RunningVMs = []string{}
if !result.NpcapInstalled {
result.RunningVMs, err = a.networkRunningVMs(ctx, c)
}
return result, err
}
+1 -22
View File
@@ -3,33 +3,12 @@ package app
import (
"context"
"encoding/json"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/vmstart"
)
func resolveVMDiskPath(d reims.VMDetail) string {
raw := strings.TrimSpace(d.Disk)
if idx := strings.Index(raw, " ("); idx > 0 {
raw = strings.TrimSpace(raw[:idx])
}
if raw != "" {
if filepath.IsAbs(raw) {
return raw
}
if d.Directory != "" {
return filepath.Join(d.Directory, raw)
}
}
if d.Directory != "" {
return filepath.Join(d.Directory, "disk.qcow2")
}
return ""
}
// macOSDetailFromVMInfo is the native UI adapter for the built-in macOS driver.
func macOSDetailFromVMInfo(vm driver.VMInfo) (reims.VMDetail, error) {
raw, err := json.Marshal(vm.DriverData)
@@ -48,7 +27,7 @@ func vmInfoFromMacOSDetail(detail reims.VMDetail) driver.VMInfo {
raw, _ := json.Marshal(detail)
var data map[string]any
_ = json.Unmarshal(raw, &data)
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: resolveVMDiskPath(detail), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data}
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data}
}
func (a *App) getVMDetailLegacy(name string, epoch uint64) (reims.VMDetail, error) {
+67
View File
@@ -14,6 +14,7 @@ import (
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/networkmsg"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/qmp"
@@ -185,6 +186,8 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
// produce duplicate QEMU device IDs on upgrade.
func stripLegacyManagedExtraArgs(extraArgs string) string {
s := reims.StripGuestToolsArgs(extraArgs)
s = reims.StripPacketBridgeArgs(s)
s = reims.StripGuestToolsNetworkArgs(s)
s = reims.StripOfflineHelperArgs(s)
s = qmp.StripLegacyWin10RebootArgs(s)
s = reims.StripIncomingDeferArgs(s)
@@ -211,6 +214,13 @@ func (a *App) startVMLegacy(name string) error {
return err
}
curDetail, _ := c.Show(context.Background(), name)
releaseNet, err := a.prepareManagedVMNetwork(context.Background(), name, false)
if err != nil {
return err
}
if releaseNet != nil {
defer releaseNet()
}
if err := prep.CheckMemory(curDetail.Memory, rep); err != nil {
a.emitVMLog(name, "Start refused: "+err.Error())
return err
@@ -282,12 +292,18 @@ func (a *App) startVMLegacy(name string) error {
}
}
} else {
if err := a.reconcileLegacyBridgeArgs(context.Background(), c, &curDetail); err != nil {
return err
}
a.syncGuestTools(c, name, &curDetail, a.vmDeleteEpoch(name))
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
if env := a.inputBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name)); len(env) > 0 {
c.Env = append(c.Env, env...)
}
}
if prep.Runtime.Manifest.HasCapability("window-file-drop") {
c.Env = append(c.Env, a.dropBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name))...)
}
prep.Prepare(context.Background(), name, rep, &curDetail)
if rep.NeedsColdRebootWorkaround {
sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name)
@@ -367,6 +383,56 @@ func (a *App) startVMLegacy(name string) error {
return nil
}
// 备用启动同样记录参数归属,停用扩展时可精确移除桥接片段。
func (a *App) reconcileLegacyBridgeArgs(ctx context.Context, c networkControlClient, detail *reims.VMDetail) error {
ledger, err := plugin.LoadArgLedger(detail.Directory)
if err != nil {
return err
}
intent := plugin.StartIntent{PluginID: builtin.IDNpcapBridge, ClearKeys: []string{"bridge-network", "npcap-bridge"}}
if detail.NetworkMode == "bridge" {
record, err := reims.ReadNetworkRecord(detail.Directory)
if err != nil {
return err
}
if record.Corrupt {
return networkmsg.Error("record_invalid", nil)
}
if record.Pending {
return networkmsg.Error("packet_pending", nil)
}
mac, err := resolveVMNetworkMAC(ctx, c, *detail)
if err != nil {
return err
}
sockPath := record.SocketPath
if sockPath == "" {
sockPath = reims.VMUnixSocketPath(detail.Directory, a.tempDir(), detail.Name, "bridge.sock")
}
tokens, err := reims.PacketBridgeUnixTokens(mac, sockPath)
if err != nil {
return err
}
intent.Args = []plugin.ArgFragment{{PluginID: builtin.IDNpcapBridge, Key: "bridge-network", Tokens: tokens, Builtin: true, Priority: 78}}
}
// 先剥除旧版未登记的主通道;管理网卡和用户参数保持各自归属。
extra := reims.StripPacketBridgeArgs(detail.ExtraArgs)
result := plugin.ReconcileStartIntents(extra, ledger, nil, []plugin.StartIntent{intent})
for _, warning := range result.Warnings {
a.emitVMLog(detail.Name, warning)
}
if result.ExtraArgs != detail.ExtraArgs {
if err := c.Set(ctx, reims.SetOpts{Name: detail.Name, ExtraArgs: &result.ExtraArgs}, io.Discard, io.Discard); err != nil {
return networkmsg.Error("config_save", err)
}
}
if err := plugin.SaveArgLedger(detail.Directory, ledger); err != nil {
return err
}
detail.ExtraArgs = result.ExtraArgs
return nil
}
func (a *App) stopVMLegacy(name string, force bool) error {
return a.stopVMLegacyCtx(context.Background(), name, force)
}
@@ -404,6 +470,7 @@ func (a *App) stopVMLegacyCtx(ctx context.Context, name string, force bool) erro
a.emitVMLog(name, "Stop error: "+err.Error())
return err
}
a.stopPacketBridge(name)
a.mu.Lock()
delete(a.pendingChanges, vmKey(name))
a.mu.Unlock()
+757 -1
View File
@@ -3,14 +3,24 @@ package app
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"path/filepath"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"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/networkmsg"
"github.com/Nwflower/reims-go/internal/packetbridge"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -62,14 +72,37 @@ func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
return reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc), nil
}
func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
defer a.localizeNetworkError(&err)
if err := a.requireWritableDataRoot(); err != nil {
return err
}
unlock := a.lockVMNetwork(opts.Name)
defer unlock()
cur, err := a.GetVMDetail(opts.Name)
if err != nil {
return err
}
if record, err := reims.ReadNetworkRecord(cur.Directory); err != nil {
return err
} else if record.Corrupt {
return networkmsg.Error("record_invalid", nil)
} else if record.Pending {
return networkmsg.Error("packet_pending", nil)
}
if cur.NetworkMode == "bridge" {
if opts.Network != nil {
return networkmsg.Error("mode_managed", nil)
}
if opts.ExtraArgs != nil {
nextExtra := *opts.ExtraArgs
if reims.NetworkMode(false, nextExtra) == "custom" ||
!sameSocketPath(reims.PacketBridgeSocket(nextExtra), reims.PacketBridgeSocket(cur.ExtraArgs)) ||
reims.PacketBridgePort(nextExtra) != reims.PacketBridgePort(cur.ExtraArgs) {
return networkmsg.Error("parameters_managed", nil)
}
}
}
a.mu.Lock()
root := a.cfg.DataRoot
loc := a.cfg.Locale
@@ -176,3 +209,726 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
return nil
}
type VMNetworkSettings struct {
Adapters []NetworkAdapter `json:"adapters"`
UplinkGUID string `json:"uplink_guid"`
UplinkName string `json:"uplink_name"`
Ready bool `json:"ready"`
RecoveryPending bool `json:"recovery_pending"`
Notes []string `json:"notes"`
Mode string `json:"mode"`
Running bool `json:"running"`
}
type NetworkAdapter packetbridge.Adapter
func (a *App) ListNetworkAdapters() (result []NetworkAdapter, err error) {
defer a.localizeNetworkError(&err)
ctx, cancel := context.WithTimeout(a.baseCtx(), 20*time.Second)
defer cancel()
adapters, err := packetbridge.ListAdapters(ctx)
if err != nil {
return nil, err
}
result = make([]NetworkAdapter, 0, len(adapters))
for _, adapter := range adapters {
result = append(result, NetworkAdapter(adapter))
}
return result, nil
}
func sameSocketPath(a, b string) bool {
a, b = strings.TrimSpace(a), strings.TrimSpace(b)
if a == "" || b == "" {
return a == b
}
return strings.EqualFold(filepath.Clean(filepath.FromSlash(a)), filepath.Clean(filepath.FromSlash(b)))
}
func normalizeSocketPath(p string) string {
p = strings.TrimSpace(p)
if p == "" {
return ""
}
return filepath.Clean(filepath.FromSlash(p))
}
func clearManagedNetworkLedger(vmDir string) {
if strings.TrimSpace(vmDir) == "" {
return
}
ledger, err := plugin.LoadArgLedger(vmDir)
if err != nil || ledger == nil || len(ledger.Owners) == 0 {
return
}
changed := false
if _, ok := ledger.Owners[builtin.IDNpcapBridge]; ok {
delete(ledger.Owners, builtin.IDNpcapBridge)
changed = true
}
if frags, ok := ledger.Owners[builtin.IDGuestTools]; ok {
kept := frags[:0]
for _, f := range frags {
if f.Key == "guest-tools-network" {
changed = true
continue
}
kept = append(kept, f)
}
if len(kept) == 0 {
delete(ledger.Owners, builtin.IDGuestTools)
} else {
ledger.Owners[builtin.IDGuestTools] = kept
}
}
if changed {
_ = plugin.SaveArgLedger(vmDir, ledger)
}
}
func resolveVMNetworkMAC(ctx context.Context, c networkControlClient, d reims.VMDetail) (string, error) {
if mac, err := reims.ReadVMNetworkMAC(d.Directory); err == nil {
return mac, nil
}
if c == nil {
return "", networkmsg.Error("args_mac_missing", nil)
}
command, err := c.CommandText(ctx, d.Name)
if err != nil {
return "", err
}
return reims.MainNetworkMAC(command)
}
func (a *App) GetVMNetworkSettings(name string) (result VMNetworkSettings, err error) {
defer a.localizeNetworkError(&err)
c, err := a.client()
if err != nil {
return result, err
}
ctx, cancel := context.WithTimeout(a.baseCtx(), 30*time.Second)
defer cancel()
d, err := c.Show(ctx, name)
if err != nil {
return result, err
}
record, err := reims.ReadNetworkRecord(d.Directory)
if err != nil {
return result, err
}
result.Adapters, err = a.ListNetworkAdapters()
if err != nil {
return result, err
}
result.Mode = d.NetworkMode
result.UplinkGUID = record.UplinkGUID
result.RecoveryPending = record.Pending || record.Corrupt
result.Ready = d.NetworkMode != "custom" && !result.RecoveryPending
if record.Corrupt {
result.Notes = append(result.Notes, networkmsg.Text(a.locale(), "err.record_invalid"))
}
list, err := c.List(ctx)
if err != nil {
return result, err
}
a.mu.Lock()
transition := a.transitions[vmKey(name)]
a.mu.Unlock()
result.Running = networkVMRunning(reims.VMListItem{}, d, transition)
for _, item := range list {
if item.Name == name {
result.Running = networkVMRunning(item, d, transition)
}
}
var selected NetworkAdapter
var connected []NetworkAdapter
for _, adapter := range result.Adapters {
if adapterGUIDKey(adapter.GUID) == adapterGUIDKey(record.UplinkGUID) {
selected = adapter
}
if adapter.Status == "Up" {
connected = append(connected, adapter)
}
}
result.UplinkName = selected.Name
if result.UplinkGUID == "" && d.NetworkMode != "bridge" && len(connected) == 1 {
result.UplinkGUID = connected[0].GUID
}
if d.NetworkMode == "bridge" {
transportOK := true
if result.Running || reims.HasSuspendState(d.Directory) {
sock := reims.PacketBridgeSocket(d.ExtraArgs)
transportOK = sock != "" && (record.SocketPath == "" || sameSocketPath(sock, record.SocketPath))
if err := requireExistingUnixNetwork(d); err != nil {
transportOK = false
result.Notes = append(result.Notes, networkmsg.Summary(err, a.locale()))
}
}
result.Ready = result.Ready && transportOK && selected.GUID != "" && selected.Status == "Up"
if !a.npcapPluginEnabled() {
result.Ready = false
result.Notes = append(result.Notes, networkmsg.Text(a.locale(), "err.plugin_disabled"))
}
if err := packetbridge.Available(); err != nil {
result.Ready = false
result.Notes = append(result.Notes, networkmsg.Summary(err, a.locale()))
}
}
return result, nil
}
func (a *App) ApplyVMNetwork(name, mode, uplink string) (result VMNetworkSettings, err error) {
defer a.localizeNetworkError(&err)
return a.applyVMNetwork(a.baseCtx(), name, mode, uplink)
}
func (a *App) applyVMNetwork(parent context.Context, name, mode, uplink string) (VMNetworkSettings, error) {
if err := a.requireWritableDataRoot(); err != nil {
return VMNetworkSettings{}, err
}
if mode != "off" && mode != "nat" && mode != "bridge" {
return VMNetworkSettings{}, networkmsg.Error("mode_invalid", nil)
}
if mode == "bridge" && !a.npcapPluginEnabled() {
return VMNetworkSettings{}, networkmsg.Error("plugin_disabled", nil)
}
unlock := a.lockVMNetwork(name)
defer unlock()
ctx, cancel := context.WithTimeout(parent, 20*time.Minute)
defer cancel()
c, err := a.client()
if err != nil {
return VMNetworkSettings{}, err
}
d, release, err := startprep.LockMutableVM(ctx, c, name)
if err != nil {
return VMNetworkSettings{}, err
}
defer release()
if d.Directory == "" {
return VMNetworkSettings{}, networkmsg.Error("directory_missing", nil)
}
list, err := c.List(ctx)
if err != nil {
return VMNetworkSettings{}, err
}
a.mu.Lock()
transition := a.transitions[vmKey(name)]
a.mu.Unlock()
running := networkVMRunning(reims.VMListItem{}, d, transition)
for _, item := range list {
if item.Name == name {
running = networkVMRunning(item, d, transition)
}
}
record, err := reims.ReadNetworkRecord(d.Directory)
if err != nil {
return VMNetworkSettings{}, err
}
if running && (d.State != "running" || transition != "" || mode != "bridge" || d.NetworkMode != "bridge" || record.Pending || record.Corrupt) {
return VMNetworkSettings{}, networkmsg.Error("stop_first", nil)
}
if record.Corrupt {
a.stopPacketBridge(d.Name)
if err := reims.RemoveNetworkRecord(d.Directory); err != nil {
return VMNetworkSettings{}, err
}
cleaned := reims.StripGuestToolsNetworkArgs(reims.StripPacketBridgeArgs(d.ExtraArgs))
if cleaned != d.ExtraArgs {
if err := c.Set(ctx, reims.SetOpts{Name: d.Name, ExtraArgs: &cleaned}, io.Discard, io.Discard); err != nil {
return VMNetworkSettings{}, networkmsg.Error("config_save", err)
}
}
clearManagedNetworkLedger(d.Directory)
d, err = c.Show(ctx, name)
if err != nil {
return VMNetworkSettings{}, err
}
record = reims.NetworkRecord{}
} else if record.Pending {
if err := a.recoverPacketNetwork(ctx, c, d, record); err != nil {
return VMNetworkSettings{}, err
}
d, err = c.Show(ctx, name)
if err != nil {
return VMNetworkSettings{}, err
}
record, err = reims.ReadNetworkRecord(d.Directory)
if err != nil {
return VMNetworkSettings{}, err
}
}
if d.NetworkMode == "custom" {
return VMNetworkSettings{}, networkmsg.Error("custom_topology", nil)
}
var selected packetbridge.Adapter
if mode == "bridge" {
adapters, err := packetbridge.ListAdapters(ctx)
if err != nil {
return VMNetworkSettings{}, err
}
selected, err = selectPacketUplink(adapters, uplink)
if err != nil {
return VMNetworkSettings{}, err
}
}
if running {
if err := a.switchPacketUplink(ctx, c, d, selected, record); err != nil {
return VMNetworkSettings{}, err
}
} else if err := a.applyPacketNetwork(ctx, c, d, mode, selected, record); err != nil {
return VMNetworkSettings{}, err
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
settings, err := a.GetVMNetworkSettings(name)
if err != nil {
a.emitLog(name, networkmsg.Text(a.locale(), "log.refresh_failed"))
return VMNetworkSettings{Mode: mode, UplinkGUID: selected.GUID, UplinkName: selected.Name, Ready: true}, nil
}
return settings, nil
}
// 未完成操作只恢复该虚拟机配置,不改宿主网卡。
func (a *App) recoverPacketNetwork(ctx context.Context, c networkControlClient, d reims.VMDetail, record reims.NetworkRecord) error {
if reims.NetworkMode(record.PreviousNetwork, record.PreviousExtra) == "custom" {
return networkmsg.Error("custom_topology", nil)
}
prevMode := record.PreviousMode
if prevMode == "" {
prevMode = reims.NetworkMode(record.PreviousNetwork, record.PreviousExtra)
if prevMode == "off" && record.PreviousUplinkGUID != "" && !record.PreviousNetwork {
prevMode = "bridge"
}
}
return networkRollback(ctx, func(recoveryCtx context.Context) error {
if err := c.Set(recoveryCtx, reims.SetOpts{Name: d.Name, Network: &record.PreviousNetwork, ExtraArgs: &record.PreviousExtra}, io.Discard, io.Discard); err != nil {
return err
}
a.stopPacketBridge(d.Name)
if prevMode == "bridge" {
restored := reims.NetworkRecord{
Version: 1,
Mode: "bridge",
SocketPath: reims.PacketBridgeSocket(record.PreviousExtra),
PacketPort: reims.PacketBridgePort(record.PreviousExtra),
UplinkGUID: record.PreviousUplinkGUID,
}
if restored.SocketPath == "" && restored.PacketPort == 0 {
restored.SocketPath = reims.VMUnixSocketPath(d.Directory, a.tempDir(), d.Name, "bridge.sock")
}
return reims.SaveNetworkRecord(d.Directory, restored)
}
clearManagedNetworkLedger(d.Directory)
return reims.RemoveNetworkRecord(d.Directory)
})()
}
// 启动和恢复只重开 Npcap 通道,不改写封存的设备参数。
func (a *App) prepareVMNetwork(c *reims.Client, d reims.VMDetail) (err error) {
defer a.localizeNetworkError(&err)
record, err := reims.ReadNetworkRecord(d.Directory)
if err != nil {
return err
}
if record.Corrupt {
return networkmsg.Error("record_invalid", nil)
}
if record.Pending {
return networkmsg.Error("packet_pending", nil)
}
if d.NetworkMode != "bridge" {
a.stopPacketBridge(d.Name)
return nil
}
if !a.npcapPluginEnabled() {
return networkmsg.Error("plugin_disabled", nil)
}
return a.preparePacketNetwork(a.baseCtx(), c, d, record, false)
}
func selectPacketUplink(adapters []packetbridge.Adapter, guid string) (packetbridge.Adapter, error) {
for _, adapter := range adapters {
if guid != "" && adapterGUIDKey(adapter.GUID) == adapterGUIDKey(guid) && adapter.Status == "Up" {
return adapter, nil
}
}
return packetbridge.Adapter{}, networkmsg.Error("physical_uplink_select", nil)
}
func (a *App) ensurePacketBridge(d reims.VMDetail, adapter packetbridge.Adapter, mac, socketPath string, port int) (*packetbridge.Bridge, error) {
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return nil, err
}
name := d.Name
a.packetMu.Lock()
defer a.packetMu.Unlock()
if a.packetBridgesStopped {
return nil, networkmsg.Error("plugin_disabled", nil)
}
if a.packetBridges == nil {
a.packetBridges = map[string]*packetbridge.Bridge{}
}
socketPath = normalizeSocketPath(socketPath)
if existing := a.packetBridges[name]; existing != nil {
cfg := existing.Config()
sameWireless := cfg.Wireless != nil && *cfg.Wireless == adapter.Wireless
if adapterGUIDKey(cfg.AdapterGUID) == adapterGUIDKey(adapter.GUID) &&
sameWireless &&
cfg.GuestMAC == mac &&
sameSocketPath(cfg.SocketPath, socketPath) &&
cfg.Port == port &&
cfg.VMDir == d.Directory &&
cfg.QEMUPath == active.QemuPath() {
return existing, nil
}
existing.Close()
delete(a.packetBridges, name)
}
wireless := adapter.Wireless
bridge, err := packetbridge.Open(packetbridge.Config{
AdapterGUID: adapter.GUID,
AdapterIndex: adapter.Index,
GuestMAC: mac,
Port: port,
SocketPath: socketPath,
VMDir: d.Directory,
QEMUPath: active.QemuPath(),
Wireless: &wireless,
})
if err != nil {
return nil, err
}
a.packetBridges[name] = bridge
return bridge, nil
}
func (a *App) stopPacketBridge(name string) {
a.packetMu.Lock()
defer a.packetMu.Unlock()
bridge := a.packetBridges[name]
delete(a.packetBridges, name)
if bridge != nil {
bridge.Close()
}
}
func (a *App) closePacketBridges() {
a.packetMu.Lock()
defer a.packetMu.Unlock()
a.packetBridgesStopped = true
bridges := a.packetBridges
a.packetBridges = nil
for _, bridge := range bridges {
bridge.Close()
}
}
// startPacketBridgeRestore 同步开放本次激活的桥接入口,返回取消并等待恢复任务的清理函数。
// 停用先等待任务退出,再由 closePacketBridges 在同一把锁下关闭入口并释放所有通道。
func (a *App) startPacketBridgeRestore(parent context.Context, restore func(context.Context)) func() {
ctx, cancel := context.WithCancel(parent)
done := make(chan struct{})
a.packetMu.Lock()
a.packetBridgesStopped = false
a.packetMu.Unlock()
go func() {
defer close(done)
restore(ctx)
}()
return func() {
cancel()
<-done
}
}
func (a *App) preparePacketNetwork(ctx context.Context, c networkControlClient, d reims.VMDetail, record reims.NetworkRecord, preserveExisting bool) error {
if record.Corrupt {
return networkmsg.Error("record_invalid", nil)
}
if record.Pending {
return networkmsg.Error("packet_pending", nil)
}
var (
sockPath string
port int
)
if preserveExisting {
if err := requireExistingUnixNetwork(d); err != nil {
return err
}
sockPath = normalizeSocketPath(reims.PacketBridgeSocket(d.ExtraArgs))
port = reims.PacketBridgePort(d.ExtraArgs)
if sockPath == "" && port == 0 {
return networkmsg.Error("packet_pending", nil)
}
} else {
sockPath = normalizeSocketPath(record.SocketPath)
if sockPath == "" {
sockPath = reims.VMUnixSocketPath(d.Directory, a.tempDir(), d.Name, "bridge.sock")
}
if !sameSocketPath(record.SocketPath, sockPath) || record.Mode != "bridge" || record.PacketPort != 0 {
updated := reims.NetworkRecord{
Version: 1,
Mode: "bridge",
SocketPath: sockPath,
UplinkGUID: record.UplinkGUID,
}
if err := reims.SaveNetworkRecord(d.Directory, updated); err != nil {
return err
}
}
}
adapters, err := packetbridge.ListAdapters(ctx)
if err != nil {
return err
}
adapter, err := selectPacketUplink(adapters, record.UplinkGUID)
if err != nil {
return err
}
mac, err := resolveVMNetworkMAC(ctx, c, d)
if err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
_, err = a.ensurePacketBridge(d, adapter, mac, sockPath, port)
return err
}
func (a *App) registerExistingPacketBridges(ctx context.Context) {
if ctx.Err() != nil || !a.npcapPluginEnabled() {
return
}
c, err := a.client()
if err != nil {
return
}
vms, err := c.List(ctx)
if err != nil {
return
}
for _, vm := range vms {
if ctx.Err() != nil {
return
}
if vm.State != "running" {
continue
}
d, err := c.Show(ctx, vm.Name)
if err != nil || (reims.PacketBridgeSocket(d.ExtraArgs) == "" && reims.PacketBridgePort(d.ExtraArgs) == 0) {
continue
}
record, err := reims.ReadNetworkRecord(d.Directory)
if err == nil {
err = a.preparePacketNetwork(ctx, c, d, record, true)
}
if err != nil {
a.emitLog(vm.Name, networkmsg.Text(a.locale(), "log.packet_restore_failed")+" "+networkmsg.Localize(err, a.locale()).Error())
}
}
}
// 运行中只重开转发通道,QEMU 按 reconnect-ms 重连,设备参数保持不变。
func (a *App) switchPacketUplink(ctx context.Context, c networkControlClient, d reims.VMDetail, selected packetbridge.Adapter, previous reims.NetworkRecord) error {
if previous.Corrupt {
return networkmsg.Error("record_invalid", nil)
}
if previous.Pending {
return networkmsg.Error("packet_pending", nil)
}
if err := requireExistingUnixNetwork(d); err != nil {
return err
}
sockPath := normalizeSocketPath(reims.PacketBridgeSocket(d.ExtraArgs))
port := reims.PacketBridgePort(d.ExtraArgs)
if sockPath == "" && port == 0 {
sockPath = normalizeSocketPath(previous.SocketPath)
port = previous.PacketPort
}
if sockPath == "" && port == 0 {
return networkmsg.Error("packet_pending", nil)
}
if err := packetbridge.CheckAdapter(selected.GUID, selected.Index); err != nil {
return err
}
mac, err := resolveVMNetworkMAC(ctx, c, d)
if err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
q, err := qmp.Dial(ctx, "unix", qmp.SocketPath(d.Directory))
if err != nil {
return networkmsg.Error("link_refresh", err)
}
defer q.Close()
record := reims.NetworkRecord{
Version: 1,
Mode: "bridge",
SocketPath: sockPath,
PacketPort: port,
UplinkGUID: selected.GUID,
Pending: true,
PreviousMode: "bridge",
PreviousNetwork: d.Network,
PreviousExtra: d.ExtraArgs,
PreviousUplinkGUID: previous.UplinkGUID,
}
if err := reims.SaveNetworkRecord(d.Directory, record); err != nil {
return err
}
linkTouched := false
restored, err := runNetworkTransaction(networkTransaction{
prepareHost: func() error {
bridge, err := a.ensurePacketBridge(d, selected, mac, sockPath, port)
if err != nil {
return err
}
readyCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
if err := bridge.WaitConnected(readyCtx); err != nil {
return networkmsg.Error("packet_reconnect", err)
}
linkTouched = true
if err := qmp.CycleLink(ctx, q, reims.PacketBridgeID, 2*time.Second); err != nil {
return networkmsg.Error("link_refresh", err)
}
return nil
},
commitConfig: func() error {
if err := ctx.Err(); err != nil {
return err
}
return reims.SaveNetworkRecord(d.Directory, reims.NetworkRecord{
Version: 1,
Mode: "bridge",
SocketPath: sockPath,
PacketPort: port,
UplinkGUID: selected.GUID,
})
},
rollbackConfig: func() error { return nil },
rollbackHost: networkRollback(ctx, func(recoveryCtx context.Context) error {
restoreErr := a.preparePacketNetwork(recoveryCtx, c, d, previous, true)
if linkTouched {
_ = q.Close()
restoreErr = errors.Join(restoreErr, qmp.RestoreLink(recoveryCtx, d.Directory, reims.PacketBridgeID))
}
return restoreErr
}),
})
if err != nil {
if restored {
return errors.Join(err, reims.SaveNetworkRecord(d.Directory, previous))
}
return err
}
a.emitLog(d.Name, networkmsg.Text(a.locale(), "log.uplink_switched"))
return nil
}
// 单台网络事务只记录声明式意图并保持用户 extra_args 纯净;桥接 QEMU 参数在启动时通过参数账本注入。
func (a *App) applyPacketNetwork(ctx context.Context, c networkControlClient, d reims.VMDetail, mode string, selected packetbridge.Adapter, previous reims.NetworkRecord) error {
record := reims.NetworkRecord{
Version: 1,
Mode: mode,
UplinkGUID: previous.UplinkGUID,
Pending: true,
PreviousMode: d.NetworkMode,
PreviousNetwork: d.Network,
PreviousExtra: d.ExtraArgs,
PreviousUplinkGUID: previous.UplinkGUID,
}
if mode == "bridge" {
if err := a.ensureNpcap(ctx, c, d.Directory); err != nil {
return err
}
if err := packetbridge.CheckAdapter(selected.GUID, selected.Index); err != nil {
return err
}
if _, err := resolveVMNetworkMAC(ctx, c, d); err != nil {
return err
}
record.UplinkGUID = selected.GUID
record.SocketPath = reims.VMUnixSocketPath(d.Directory, a.tempDir(), d.Name, "bridge.sock")
}
if err := reims.SaveNetworkRecord(d.Directory, record); err != nil {
return err
}
restoreRecord := func() error {
if previous.Version == 0 {
return reims.RemoveNetworkRecord(d.Directory)
}
return reims.SaveNetworkRecord(d.Directory, previous)
}
rollbackConfig := networkRollback(ctx, func(recoveryCtx context.Context) error {
return c.Set(recoveryCtx, reims.SetOpts{Name: d.Name, Network: &d.Network, ExtraArgs: &d.ExtraArgs}, io.Discard, io.Discard)
})
extra, err := reims.BuildNetworkExtra(d.ExtraArgs, "off")
if err != nil {
return errors.Join(err, restoreRecord())
}
network := mode == "nat"
verifyMode := mode
if mode == "bridge" {
verifyMode = "off"
}
restored, err := runNetworkTransaction(networkTransaction{
prepareHost: func() error {
a.stopPacketBridge(d.Name)
return nil
},
commitConfig: func() error {
if d.Network != network || extra != d.ExtraArgs {
if err := c.Set(ctx, reims.SetOpts{Name: d.Name, Network: &network, ExtraArgs: &extra}, io.Discard, io.Discard); err != nil {
return networkmsg.Error("config_save", err)
}
}
generated, err := c.CommandText(ctx, d.Name)
if err != nil {
return err
}
if err := reims.VerifyNetworkCommand(generated, verifyMode); err != nil {
return err
}
clearManagedNetworkLedger(d.Directory)
if mode == "bridge" {
return reims.SaveNetworkRecord(d.Directory, reims.NetworkRecord{
Version: 1,
Mode: "bridge",
SocketPath: record.SocketPath,
UplinkGUID: selected.GUID,
})
}
return reims.RemoveNetworkRecord(d.Directory)
},
rollbackConfig: rollbackConfig,
rollbackHost: func() error { return nil },
})
if err != nil {
if restored {
return errors.Join(err, restoreRecord())
}
return err
}
if mode != "bridge" {
a.mu.Lock()
srv := a.guestTools
a.mu.Unlock()
if srv != nil {
srv.StopManagementNetwork(d.Name)
}
}
a.emitLog(d.Name, networkmsg.Text(a.locale(), "log.mode_applied", "mode", networkmsg.Text(a.locale(), "mode."+strings.ToLower(mode))))
return nil
}
+7
View File
@@ -0,0 +1,7 @@
package app
import "github.com/Nwflower/reims-go/internal/networkmsg"
func (a *App) localizeNetworkError(err *error) {
*err = networkmsg.Localize(*err, a.locale())
}
+225
View File
@@ -0,0 +1,225 @@
package app
import (
"context"
"errors"
"fmt"
"io"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
)
type reviewNetworkControl struct {
extra string
writes int
setErr error
}
func (*reviewNetworkControl) List(context.Context) ([]reims.VMListItem, error) { return nil, nil }
func (*reviewNetworkControl) Show(context.Context, string) (reims.VMDetail, error) {
return reims.VMDetail{}, nil
}
func (*reviewNetworkControl) CommandText(context.Context, string) (string, error) {
return "qemu -netdev user,id=net0 -device virtio-net-pci,netdev=net0,id=net0,mac=02:00:00:00:00:01", nil
}
func (c *reviewNetworkControl) Set(_ context.Context, opts reims.SetOpts, _, _ io.Writer) error {
if c.setErr != nil {
return c.setErr
}
if opts.ExtraArgs != nil {
c.extra = *opts.ExtraArgs
c.writes++
}
return nil
}
func TestLegacyBridgeArgsHaveRemovableOwner(t *testing.T) {
dir := t.TempDir()
detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"}
if err := reims.SaveNetworkRecord(dir, reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}); err != nil {
t.Fatal(err)
}
control := &reviewNetworkControl{}
a := &App{}
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
t.Fatal(err)
}
if !strings.Contains(control.extra, "id=reimsbridge0") {
t.Fatal("隔离客户端未收到桥接参数")
}
ledger, err := plugin.LoadArgLedger(dir)
if err != nil {
t.Fatal(err)
}
if len(ledger.Owners[builtin.IDNpcapBridge]) != 1 {
t.Fatalf("桥接参数已写入,但 Npcap 账本条目数为 %d", len(ledger.Owners[builtin.IDNpcapBridge]))
}
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
t.Fatal(err)
}
if control.writes != 1 {
t.Fatalf("重复准备写入了 %d 次参数", control.writes)
}
if strings.Count(detail.ExtraArgs, "id=reimsbridge0,") != 1 {
t.Fatal("重复准备产生重复桥接设备")
}
clean := plugin.ReconcileStartIntents(detail.ExtraArgs, ledger, map[string]bool{}, nil)
if clean.ExtraArgs != "-cpu host" {
t.Fatalf("停用后残留桥接参数:%s", clean.ExtraArgs)
}
}
func TestLegacyBridgeArgsStopOnInvalidRecordOrWriteFailure(t *testing.T) {
for _, mode := range []string{"corrupt", "pending", "set failure"} {
t.Run(mode, func(t *testing.T) {
dir := t.TempDir()
detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"}
record := reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}
code := "E_NETWORK_CONFIG_SAVE"
control := &reviewNetworkControl{setErr: errors.New("模拟配置写入失败")}
if mode == "corrupt" {
record.Version = 99
code = "E_NETWORK_RECORD_INVALID"
}
if mode == "pending" {
record.Pending = true
code = "E_NETWORK_PACKET_PENDING"
}
if err := reims.SaveNetworkRecord(dir, record); err != nil {
t.Fatal(err)
}
err := (&App{}).reconcileLegacyBridgeArgs(context.Background(), control, &detail)
var coded *i18n.CodedError
if !errors.As(err, &coded) || coded.Code != code {
t.Fatalf("错误 = %v,预期 %s", err, code)
}
ledger, err := plugin.LoadArgLedger(dir)
if err != nil {
t.Fatal(err)
}
if detail.ExtraArgs != "-cpu host" || len(ledger.Owners) != 0 {
t.Fatal("准备失败却更新了参数或归属")
}
})
}
}
func TestLegacyBridgeArgsClearOwnerWhenLeavingBridge(t *testing.T) {
dir := t.TempDir()
detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"}
if err := reims.SaveNetworkRecord(dir, reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}); err != nil {
t.Fatal(err)
}
a := &App{}
control := &reviewNetworkControl{}
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
t.Fatal(err)
}
detail.NetworkMode = "nat"
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
t.Fatal(err)
}
ledger, err := plugin.LoadArgLedger(dir)
if err != nil {
t.Fatal(err)
}
if detail.ExtraArgs != "-cpu host" || len(ledger.Owners[builtin.IDNpcapBridge]) != 0 {
t.Fatal("离开桥接后仍残留参数或归属")
}
}
func networkLockCount(a *App) int {
count := 0
a.vmNetworkLocks.Range(func(_, _ any) bool { count++; return true })
return count
}
func TestVMNetworkLocksReclaimInactiveNames(t *testing.T) {
a := &App{}
for i := 0; i < 512; i++ {
unlock := a.lockVMNetwork(fmt.Sprintf("fake-vm-%d", i))
unlock()
}
if count := networkLockCount(a); count != 0 {
t.Fatalf("512 个模拟名称操作结束后仍保留 %d 把锁", count)
}
}
func TestVMNetworkLockKeepsWaitingCallersTogether(t *testing.T) {
a := &App{}
var active, overlaps atomic.Int32
var workers sync.WaitGroup
start := make(chan struct{})
for i := 0; i < 32; i++ {
workers.Go(func() {
<-start
for round := 0; round < 100; round++ {
unlock := a.lockVMNetwork([]string{" VM ", "vm", "Vm"}[round%3])
if active.Add(1) != 1 {
overlaps.Add(1)
}
runtime.Gosched()
active.Add(-1)
unlock()
}
})
}
close(start)
workers.Wait()
if overlaps.Load() != 0 {
t.Fatalf("同一 VM 出现 %d 次重叠操作", overlaps.Load())
}
if count := networkLockCount(a); count != 0 {
t.Fatalf("所有调用结束后仍保留 %d 把锁", count)
}
}
func TestVMNetworkLockReferenceIncludesWaiters(t *testing.T) {
a := &App{}
first := a.lockVMNetwork("fake-vm")
secondEntered, releaseSecond, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
go func() {
defer close(done)
unlock := a.lockVMNetwork("FAKE-VM")
defer unlock()
close(secondEntered)
<-releaseSecond
}()
deadline := time.Now().Add(time.Second)
for {
a.vmNetworkLocksMu.Lock()
entry, _ := a.vmNetworkLocks.Load("fake-vm")
refs := entry.(*vmNetworkLock).refs
a.vmNetworkLocksMu.Unlock()
if refs == 2 {
break
}
if time.Now().After(deadline) {
first()
close(releaseSecond)
<-done
t.Fatal("等待者没有被计入引用")
}
runtime.Gosched()
}
first()
<-secondEntered
if count := networkLockCount(a); count != 1 {
t.Errorf("仍有持有者时锁条目数为 %d", count)
}
close(releaseSecond)
<-done
if count := networkLockCount(a); count != 0 {
t.Fatalf("最后一个调用结束后条目数为 %d", count)
}
}
+44
View File
@@ -0,0 +1,44 @@
package app
import (
"context"
"errors"
"time"
"github.com/Nwflower/reims-go/internal/networkmsg"
)
type networkTransaction struct {
prepareHost func() error
commitConfig func() error
rollbackConfig func() error
rollbackHost func() error
}
// networkRollback 保证取消创建或操作超时后,恢复命令仍有独立且有界的执行时间。
func networkRollback(ctx context.Context, restore func(context.Context) error) func() error {
return func() error {
recoveryCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Minute)
defer cancel()
return restore(recoveryCtx)
}
}
// 通道准备失败时不触碰虚拟机配置;提交失败时恢复配置和原通道。
func runNetworkTransaction(change networkTransaction) (restored bool, err error) {
if err := change.prepareHost(); err != nil {
if restoreErr := change.rollbackHost(); restoreErr != nil {
return false, networkmsg.Error("host_rollback", errors.Join(err, restoreErr))
}
return true, networkmsg.Error("switch_unchanged", err)
}
if err := change.commitConfig(); err != nil {
configErr := change.rollbackConfig()
hostErr := change.rollbackHost()
if configErr != nil || hostErr != nil {
return false, errors.Join(err, configErr, hostErr)
}
return true, networkmsg.Error("switch_rolled_back", err)
}
return false, nil
}
+157
View File
@@ -0,0 +1,157 @@
package app
import (
"errors"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
)
func TestRunNetworkTransactionBranches(t *testing.T) {
errPrep := errors.New("prep failed")
errCommit := errors.New("commit failed")
errRbHost := errors.New("rollback host failed")
errRbCfg := errors.New("rollback config failed")
tests := []struct {
name string
tx networkTransaction
wantRestored bool
wantErrCode string
wantErrSub string
}{
{
name: "happy path",
tx: networkTransaction{
prepareHost: func() error { return nil },
commitConfig: func() error { return nil },
rollbackConfig: func() error { t.Fatal("unexpected rollbackConfig"); return nil },
rollbackHost: func() error { t.Fatal("unexpected rollbackHost"); return nil },
},
},
{
name: "prepare fails rollback host succeeds",
tx: networkTransaction{
prepareHost: func() error { return errPrep },
commitConfig: func() error { t.Fatal("unexpected commitConfig"); return nil },
rollbackConfig: func() error { t.Fatal("unexpected rollbackConfig"); return nil },
rollbackHost: func() error { return nil },
},
wantRestored: true,
wantErrCode: "E_NETWORK_SWITCH_UNCHANGED",
},
{
name: "prepare fails rollback host fails",
tx: networkTransaction{
prepareHost: func() error { return errPrep },
commitConfig: func() error { return nil },
rollbackConfig: func() error { return nil },
rollbackHost: func() error { return errRbHost },
},
wantRestored: false,
wantErrCode: "E_NETWORK_HOST_ROLLBACK",
},
{
name: "commit fails both rollbacks succeed",
tx: networkTransaction{
prepareHost: func() error { return nil },
commitConfig: func() error { return errCommit },
rollbackConfig: func() error { return nil },
rollbackHost: func() error { return nil },
},
wantRestored: true,
wantErrCode: "E_NETWORK_SWITCH_ROLLED_BACK",
},
{
name: "commit fails rollback fails",
tx: networkTransaction{
prepareHost: func() error { return nil },
commitConfig: func() error { return errCommit },
rollbackConfig: func() error { return errRbCfg },
rollbackHost: func() error { return errRbHost },
},
wantRestored: false,
wantErrSub: "rollback config failed",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
restored, err := runNetworkTransaction(tc.tx)
if restored != tc.wantRestored {
t.Fatalf("restored = %v, want %v (err=%v)", restored, tc.wantRestored, err)
}
if tc.wantErrCode == "" && tc.wantErrSub == "" {
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
return
}
if err == nil {
t.Fatal("expected error, got nil")
}
if tc.wantErrCode != "" {
var coded *i18n.CodedError
if !errors.As(err, &coded) || coded.Code != tc.wantErrCode {
t.Fatalf("err = %v, want code %s", err, tc.wantErrCode)
}
}
if tc.wantErrSub != "" && !strings.Contains(err.Error(), tc.wantErrSub) {
t.Fatalf("err = %q, want substring %q", err.Error(), tc.wantErrSub)
}
})
}
}
func TestClearManagedNetworkLedgerPreservesOtherFragments(t *testing.T) {
vmDir := t.TempDir()
ledger := &plugin.ArgLedger{
Version: 1,
Owners: map[string][]plugin.ArgFragment{
builtin.IDNpcapBridge: {
{PluginID: builtin.IDNpcapBridge, Key: "npcap-bridge", Tokens: []string{"-netdev", "stream,id=reimsbridge0"}},
},
builtin.IDGuestTools: {
{PluginID: builtin.IDGuestTools, Key: "guest-tools-network", Tokens: []string{"-netdev", "user,id=reimstools-net"}},
{PluginID: builtin.IDGuestTools, Key: "reimstools", Tokens: []string{"-drive", "id=reimstools"}},
},
"builtin.guest.macos": {
{PluginID: "builtin.guest.macos", Key: "host-memory-smbios", Tokens: []string{"-smbios", "type=17,speed=4800"}},
},
},
}
if err := plugin.SaveArgLedger(vmDir, ledger); err != nil {
t.Fatalf("SaveArgLedger: %v", err)
}
clearManagedNetworkLedger(vmDir)
after, err := plugin.LoadArgLedger(vmDir)
if err != nil {
t.Fatalf("LoadArgLedger: %v", err)
}
if _, ok := after.Owners[builtin.IDNpcapBridge]; ok {
t.Fatal("expected npcap-bridge owner removed from ledger")
}
gt := after.Owners[builtin.IDGuestTools]
if len(gt) != 1 || gt[0].Key != "reimstools" {
t.Fatalf("guest-tools fragments = %+v, want only reimstools", gt)
}
if len(after.Owners["builtin.guest.macos"]) != 1 {
t.Fatalf("unrelated macOS fragments disturbed: %+v", after.Owners["builtin.guest.macos"])
}
}
func TestSameSocketPathNormalizesSlashesAndCase(t *testing.T) {
if !sameSocketPath(`E:/Data/vms/mac/bridge.sock`, `e:\Data\vms\mac\bridge.sock`) {
t.Fatal("expected forward-slash QEMU path and Windows path to match")
}
if sameSocketPath(`E:/Data/vms/a/bridge.sock`, `E:/Data/vms/b/bridge.sock`) {
t.Fatal("distinct socket paths must not match")
}
if !sameSocketPath("", "") || sameSocketPath("", `E:\a.sock`) {
t.Fatal("empty socket path comparison mismatch")
}
}
@@ -0,0 +1,65 @@
package app
import (
"context"
"errors"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/packetbridge"
)
func TestPacketBridgeRestoreCleanupCancelsAndWaits(t *testing.T) {
a := &App{}
started, cancelled, finish := make(chan struct{}), make(chan struct{}), make(chan struct{})
stop := a.startPacketBridgeRestore(context.Background(), func(ctx context.Context) {
close(started)
<-ctx.Done()
close(cancelled)
<-finish
})
<-started
stopped := make(chan struct{})
go func() { stop(); close(stopped) }()
select {
case <-cancelled:
case <-time.After(time.Second):
close(finish)
t.Fatal("停用没有取消恢复任务")
}
select {
case <-stopped:
t.Error("恢复任务退出之前已经完成停用")
default:
}
close(finish)
select {
case <-stopped:
case <-time.After(time.Second):
t.Fatal("恢复任务退出后清理没有结束")
}
}
func TestStoppedPacketBridgesRejectLateOpenAndActivationReopensGate(t *testing.T) {
root := t.TempDir()
installDummyRuntime(t, root)
a := &App{cfg: &config.Config{DataRoot: root, ActiveRuntime: "test-rt"}}
a.closePacketBridges()
_, err := a.ensurePacketBridge(reims.VMDetail{Name: "test"}, packetbridge.Adapter{}, "", "", 0)
var coded *i18n.CodedError
if !errors.As(err, &coded) || coded.Code != "E_NETWORK_PLUGIN_DISABLED" {
t.Fatalf("停用后允许晚到的启动任务创建通道: %v", err)
}
stop := a.startPacketBridgeRestore(context.Background(), func(context.Context) {})
stop()
a.packetMu.Lock()
stopped := a.packetBridgesStopped
a.packetMu.Unlock()
if stopped {
t.Fatal("重新激活插件没有开放桥接入口")
}
a.closePacketBridges()
}
+51
View File
@@ -0,0 +1,51 @@
package app
import (
"context"
"encoding/json"
"errors"
"github.com/Nwflower/reims-go/internal/control"
)
func (a *App) startPluginControlServer() {
a.mu.Lock()
if a.ctx == nil || a.pluginMgr == nil || a.controlServer != nil {
a.mu.Unlock()
return
}
a.mu.Unlock()
server, err := control.Listen(func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil, errors.New("plugin manager is not ready")
}
return mgr.ChannelMessage(ctx, pluginID, channel, message)
})
if err != nil {
a.emitLog("plugin", "Could not open local plugin control channel: "+err.Error())
return
}
a.mu.Lock()
if a.ctx == nil || a.pluginMgr == nil || a.controlServer != nil {
a.mu.Unlock()
_ = server.Close()
return
}
a.controlServer = server
a.mu.Unlock()
}
func (a *App) stopPluginControlServer() {
a.mu.Lock()
server := a.controlServer
a.controlServer = nil
a.mu.Unlock()
if server != nil {
_ = server.Close()
}
}
+21 -1
View File
@@ -69,6 +69,7 @@ func (a *App) initPlugins() {
a.emitLog("plugin", "Could not migrate macOS guest state: "+err.Error())
return
}
var mgr *plugin.Manager
mgr, err := plugin.NewManager(plugin.ManagerOptions{
DataRoot: dataRoot,
HostVersion: version.Version,
@@ -81,6 +82,12 @@ func (a *App) initPlugins() {
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
return driver.NewSidecarDriver(contrib, sup)
},
HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler {
a.mu.Lock()
current := a.pluginMgr
a.mu.Unlock()
return a.computerUseHostHandlers(current, pluginID)
},
OnSettingsChanged: func(pluginID, vmName string) {
a.onPluginSettingsChanged(pluginID, vmName)
},
@@ -150,7 +157,7 @@ func (a *App) initPlugins() {
return guesttools.VMConfig{}, os.ErrNotExist
}
}
return a.loadAndRegisterGuestTools(srv, port, dir, name, epoch)
return a.loadAndRegisterNetworkGuestTools(srv, port, dir, name, epoch)
},
OnIMEText: func(target host.IMETarget, text string) {
go a.injectRemoteText(target.VMName, target.VMDir, text)
@@ -165,6 +172,15 @@ func (a *App) initPlugins() {
return a.guestToolsImagePath(vmName)
},
BuildGuestToolsImage: a.buildGuestToolsImage,
PrepareVMNetwork: a.prepareManagedVMNetwork,
RestorePacketBridges: func(ctx context.Context) func() {
return a.startPacketBridgeRestore(ctx, func(ctx context.Context) {
if a.dataRootUsable() {
a.registerExistingPacketBridges(ctx)
}
})
},
StopPacketBridges: a.closePacketBridges,
OnInstallGuidesChanged: func() {
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
@@ -219,11 +235,15 @@ func (a *App) initPlugins() {
fetch.SetDefaultDownloader(a.activeDownloader)
mgr.Registry().Reconcile(context.Background())
if err := a.restoreComputerUseOwnedVMs(context.Background()); err != nil {
a.emitLog("plugin", "Could not restore temporary computer-use VM ownership: "+err.Error())
}
mgr.MarkBootComplete()
a.syncInputFilters()
a.syncKeymapRules()
a.syncClipboardPolicies()
a.syncLocales()
a.startPluginControlServer()
}
// activeDownloader returns the highest-priority active downloader plugin provider,
+88 -2
View File
@@ -7,6 +7,7 @@ import (
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
@@ -58,6 +59,7 @@ func (a *App) SuspendVMWithDriver(driverID, name string) error {
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.cancelRebootWatcherKey(key)
stopVMMonitor(ref.Name)
a.stopPacketBridge(ref.Name)
}
if gt != nil {
gt.UnregisterVM(key)
@@ -100,10 +102,19 @@ func (a *App) ResumeVMWithDriver(driverID, name string) error {
defer end()
var extraEnv []string
var newRegistration *guesttools.Server
var newRegGen uint64
var epoch uint64
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.cancelRebootWatcherKey(key)
if active, rerr := rt.ResolveActive(&cfgCopy); rerr == nil && active != nil && active.Manifest.HasCapability("win32-unicode-input") {
extraEnv = append(extraEnv, a.inputBridgeEnv(ref.Name, vm.Directory, a.vmDeleteEpoch(ref.Name))...)
epoch = a.vmDeleteEpoch(ref.Name)
active, rerr := rt.ResolveActive(&cfgCopy)
hasRuntime := rerr == nil && active != nil
unicodeInput := hasRuntime && active.Manifest.HasCapability("win32-unicode-input")
windowDrop := hasRuntime && active.Manifest.HasCapability("window-file-drop")
extraEnv, newRegistration, newRegGen = a.registerResumeGuestTools(vm, epoch, unicodeInput, windowDrop)
if unicodeInput && len(extraEnv) > 0 {
a.syncKeymapRules()
}
}
@@ -111,6 +122,13 @@ func (a *App) ResumeVMWithDriver(driverID, name string) error {
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
result, err := svc.Resume(ctx, ref, extraEnv, w, w)
if err != nil {
if newRegistration != nil && newRegGen > 0 {
unlock := a.lockGuestToolsVM(ref.Name)
if a.vmDeleteEpoch(ref.Name) == epoch {
newRegistration.UnregisterVMIfGen(key, newRegGen)
}
unlock()
}
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Resume error: "+err.Error())
return err
}
@@ -129,6 +147,74 @@ func (a *App) ResumeVMWithDriver(driverID, name string) error {
return nil
}
func (a *App) registerResumeGuestTools(vm driver.VMInfo, epoch uint64, unicodeInput, windowDrop bool) ([]string, *guesttools.Server, uint64) {
ref := vm.Ref()
unlock := a.lockGuestToolsVM(ref.Name)
defer unlock()
if a.vmDeleteEpoch(ref.Name) != epoch {
return nil, nil, 0
}
cfg, configured, err := guesttools.ReadVMConfigStrict(vm.Directory)
if err != nil {
a.emitLog(ref.Name, "Warning: could not load Guest Tools config: "+err.Error())
return nil, nil, 0
}
if !configured {
return nil, nil, 0
}
if err := requireGuestToolsVM(vm.Directory); err != nil {
a.emitLog(ref.Name, "Warning: could not register Guest Tools config: "+err.Error())
return nil, nil, 0
}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
return nil, nil, 0
}
existing := srv.HasVM(ref.Key())
oldName := cfg.VMName
cfg.VMName = ref.Name
oldDir := cfg.SharedDir
windowBridge := unicodeInput || windowDrop
if windowBridge || cfg.SharedDir == "" {
cfg.SharedDir = a.vmSharedDir(ref.Name)
}
if cfg.Port != port || (windowBridge && (oldName != cfg.VMName || oldDir != cfg.SharedDir)) {
cfg.Port = port
if err := guesttools.SaveVMConfig(vm.Directory, cfg); err != nil {
a.emitLog(ref.Name, "Warning: could not save Guest Tools config: "+err.Error())
return nil, nil, 0
}
}
if err := a.registerGuestToolsConfig(srv, vm.Directory, cfg); err != nil {
a.emitLog(ref.Name, "Warning: could not register Guest Tools config: "+err.Error())
return nil, nil, 0
}
var newRegistration *guesttools.Server
var newRegGen uint64
if !existing {
newRegistration = srv
newRegGen = srv.RegistrationGen(ref.Key())
}
var env []string
if unicodeInput {
srv.SetKeymapCarrier(ref.Name, false)
env = append(env,
fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port),
"REIMS_GO_INPUT_TOKEN="+cfg.Token,
)
}
if windowDrop {
if token := srv.HostDropToken(ref.DriverID, ref.Name); token != "" {
env = append(env,
fmt.Sprintf("REIMS_GO_DROP_URL=http://127.0.0.1:%d/v1/host-drop", port),
"REIMS_GO_DROP_TOKEN="+token,
)
}
}
return env, newRegistration, newRegGen
}
// DiscardSuspend deletes a stopped VM's saved execution state.
func (a *App) DiscardSuspend(name string) error {
return a.DiscardSuspendWithDriver("", name)
+193
View File
@@ -1,15 +1,208 @@
package app
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"slices"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
type resumeGuestToolsDriver struct {
*appSecondDriver
driver.SuspendDriver
onResume func(driver.ResumeRequest)
resumeErr error
}
func (d *resumeGuestToolsDriver) Resume(_ context.Context, req driver.ResumeRequest) (driver.StartResult, error) {
d.onResume(req)
return driver.StartResult{}, d.resumeErr
}
func TestResumeVMRegistersSavedGuestToolsWithoutUnicodeInput(t *testing.T) {
resumeErr := errors.New("resume failed")
for _, tc := range []struct {
name string
manifest string
unicodeInput bool
windowDrop bool
savedConfig bool
preRegistered bool
concurrentUpdate bool
concurrentReplace bool
resumeErr error
}{
{name: "runtime installed=true", manifest: `{"commit":"legacy"}`, savedConfig: true},
{name: "runtime installed=false", savedConfig: true},
{name: "failure rolls back new registration", savedConfig: true, resumeErr: resumeErr},
{name: "failure keeps preexisting registration", savedConfig: true, preRegistered: true, resumeErr: resumeErr},
{name: "failure keeps concurrent registration update", savedConfig: true, concurrentUpdate: true, resumeErr: resumeErr},
{name: "failure keeps replacement registration", savedConfig: true, concurrentReplace: true, resumeErr: resumeErr},
{name: "resume preserves both window bridges", savedConfig: true, unicodeInput: true, windowDrop: true,
manifest: `{"commit":"window-bridges","capabilities":["win32-unicode-input","window-file-drop"]}`},
{name: "Unicode input failure rolls back new registration", savedConfig: true, unicodeInput: true, resumeErr: resumeErr,
manifest: `{"commit":"unicode","capabilities":["win32-unicode-input"]}`},
{name: "no saved config leaves bridge stopped", resumeErr: resumeErr},
{name: "Unicode input without saved config leaves bridge stopped", unicodeInput: true,
manifest: `{"commit":"unicode","capabilities":["win32-unicode-input"]}`, resumeErr: resumeErr},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := &config.Config{DataRoot: t.TempDir()}
if tc.manifest != "" {
runtimeDir := filepath.Join(cfg.RuntimesDir(), "legacy")
if err := os.MkdirAll(runtimeDir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(runtimeDir, "manifest.json"), []byte(tc.manifest), 0o600); err != nil {
t.Fatal(err)
}
active, err := rt.ResolveActive(cfg)
if err != nil || active.Manifest.HasCapability("win32-unicode-input") != tc.unicodeInput ||
active.Manifest.HasCapability("window-file-drop") != tc.windowDrop {
t.Fatalf("unexpected runtime capabilities: %+v, %v", active, err)
}
}
const name = "resume-guest-tools"
vmDir := t.TempDir()
t.Cleanup(func() { stopVMMonitor(name) })
if err := os.WriteFile(filepath.Join(vmDir, "vm.toml"), nil, 0o600); err != nil {
t.Fatal(err)
}
var srv *guesttools.Server
var port int
var saved guesttools.VMConfig
if tc.savedConfig {
srv = guesttools.NewServer(nil)
var err error
port, err = srv.Start(-1)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := srv.Close(ctx); err != nil {
t.Error(err)
}
})
saved, err = guesttools.LoadOrCreateVMConfig(vmDir, name, filepath.Join(cfg.SharedDir(), name), port)
if err != nil {
t.Fatal(err)
}
}
client := &http.Client{Timeout: 2 * time.Second}
ping := func(want int) {
t.Helper()
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/v1/ping", port), nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+saved.Token)
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != want {
t.Fatalf("Guest Tools ping status = %d, want %d", resp.StatusCode, want)
}
}
if tc.savedConfig {
ping(http.StatusUnauthorized)
if tc.preRegistered {
srv.RegisterVM(saved)
ping(http.StatusOK)
}
}
const driverID = driver.BuiltinReimsMacOSDriverID
drv := &resumeGuestToolsDriver{
appSecondDriver: &appSecondDriver{id: driverID, vms: []driver.VMInfo{
{Name: name, DriverID: driverID, Directory: vmDir, State: "suspended"},
}},
onResume: func(req driver.ResumeRequest) {
var wantEnv []string
if tc.unicodeInput && tc.savedConfig {
wantEnv = append(wantEnv, fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port), "REIMS_GO_INPUT_TOKEN="+saved.Token)
}
if tc.windowDrop && tc.savedConfig {
token := srv.HostDropToken(driverID, name)
if token == "" {
t.Fatal("missing window drop registration")
}
wantEnv = append(wantEnv, fmt.Sprintf("REIMS_GO_DROP_URL=http://127.0.0.1:%d/v1/host-drop", port), "REIMS_GO_DROP_TOKEN="+token)
}
if !slices.Equal(req.ExtraEnv, wantEnv) {
t.Error("unexpected window bridge environment")
}
if tc.savedConfig {
ping(http.StatusOK)
if tc.concurrentReplace {
srv.UnregisterVM(name)
}
if tc.concurrentUpdate || tc.concurrentReplace {
updated := saved
updated.PreventSleep = !updated.PreventSleep
srv.RegisterVM(updated)
}
}
},
resumeErr: tc.resumeErr,
}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "test.resume", Version: "1.0.0"},
Source: plugin.SourceBuiltin,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, driverID, drv)
return nil
},
}); err != nil {
t.Fatal(err)
}
reg.Reconcile(t.Context())
a := &App{
cfg: cfg, guestTools: srv, transitions: map[string]string{},
lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
}
t.Cleanup(func() {
if a.guestTools != nil && a.guestTools != srv {
if err := a.guestTools.Close(context.Background()); err != nil {
t.Error(err)
}
}
})
if err := a.ResumeVM(name); !errors.Is(err, tc.resumeErr) {
t.Fatalf("ResumeVM error = %v, want %v", err, tc.resumeErr)
}
if !tc.savedConfig {
if a.guestTools != nil {
t.Fatal("resuming a VM without Guest Tools config started a bridge")
}
} else if tc.resumeErr != nil && !tc.preRegistered && !tc.concurrentUpdate && !tc.concurrentReplace {
ping(http.StatusUnauthorized)
} else {
ping(http.StatusOK)
}
})
}
}
func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) {
suspendedDir := t.TempDir()
stoppedDir := t.TempDir()
+11 -4
View File
@@ -1,7 +1,7 @@
package app
// VM screen thumbnails for the VM page: while a VM runs,
// grab one frame over its QMP socket (`screendump`), shrink it to a small
// grab one frame through the built-in computer-use console (`screendump`), shrink it to a small
// JPEG and keep it under <data root>\cache\thumbs, so a stopped VM can still
// show its last screen. Nothing here touches vm.toml or the guest.
@@ -22,7 +22,6 @@ import (
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/thumb"
)
@@ -185,7 +184,11 @@ func (a *App) CopyVMScreenshotWithDriver(driverID, name string) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw)
service, err := a.computerUseService()
if err != nil {
return err
}
format, err := service.Screendump(ctx, vm.Dir, raw)
if err != nil {
return fmt.Errorf("capture screen: %w", err)
}
@@ -239,7 +242,11 @@ func (a *App) captureThumbWithDriver(driverID, name, path string) (VMThumbnail,
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw)
service, err := a.computerUseService()
if err != nil {
return VMThumbnail{}, false
}
format, err := service.Screendump(ctx, vm.Dir, raw)
if err != nil {
return VMThumbnail{}, false
}
+18 -8
View File
@@ -76,6 +76,10 @@ func (a *App) TypeText(name, text string) (int, error) {
}
func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool) (int, error) {
return a.injectTextIntoVMWithLogging(name, knownDir, text, fromRemoteIME, false)
}
func (a *App) injectTextIntoVMWithLogging(name, knownDir, text string, fromRemoteIME, suppressLogs bool) (int, error) {
text = strings.ReplaceAll(text, "\r\n", "\n")
text = strings.ReplaceAll(text, "\r", "\n")
if text == "" {
@@ -108,6 +112,10 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
}
vmDir = d.Directory
}
computerUse, err := a.computerUseService()
if err != nil {
return 0, err
}
// Prefer Guest Tools Unicode injection for:
// - any non-ASCII (Chinese, CJK punctuation, emoji), OR
@@ -127,24 +135,24 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
if srv != nil {
pasteCtx, cancel := context.WithTimeout(ctx, 6*time.Second)
mode, err := srv.InjectText(pasteCtx, name, text, func(c context.Context) error {
return qmp.SendPasteShortcut(c, vmDir)
return computerUse.SendPasteShortcut(c, vmDir)
})
cancel()
if err == nil {
n := utf8.RuneCountInString(text)
if !fromRemoteIME {
if !fromRemoteIME && !suppressLogs {
a.emitVMLog(name, fmt.Sprintf("Injected %d character(s) into %s via Guest Tools (%s) + Cmd+V.", n, name, mode))
}
return n, nil
}
if !errors.Is(err, guesttools.ErrGuestToolsNotConnected) {
if !suppressLogs && !errors.Is(err, guesttools.ErrGuestToolsNotConnected) {
a.emitVMLog(name, fmt.Sprintf("Guest Tools text injection (%s) failed: %v", mode, err))
}
}
}
// Fallback (or bare Enter/Tab / Recovery / Login screen): QMP US keystrokes.
n, err := qmp.TypeIntoVM(ctx, vmDir, text, nil)
n, err := computerUse.TypeText(ctx, vmDir, text, nil)
var ue *qmp.UntypeableError
if errors.As(err, &ue) {
if fromRemoteIME {
@@ -155,19 +163,21 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
typing.lastHintAt[key] = time.Now()
}
typing.mu.Unlock()
if shouldLog {
if shouldLog && !suppressLogs {
a.emitVMLog(name, "Remote IME Unicode text received, but Guest Tools is not connected in macOS yet (install Guest Tools to enable Chinese/Unicode remote input).")
}
} else {
} else if !suppressLogs {
a.emitVMLog(name, "Paste as keystrokes refused: "+ue.Error())
}
return 0, fmt.Errorf("%w: %s", ErrNotTypeable, ue.Error())
}
if err != nil {
a.emitVMLog(name, fmt.Sprintf("Paste as keystrokes stopped after %d keys: %v", n, err))
if !suppressLogs {
a.emitVMLog(name, fmt.Sprintf("Paste as keystrokes stopped after %d keys: %v", n, err))
}
return n, err
}
if !fromRemoteIME {
if !fromRemoteIME && !suppressLogs {
a.emitVMLog(name, fmt.Sprintf("Typed %d keys into %s.", n, name))
}
return n, nil
+13 -4
View File
@@ -45,22 +45,31 @@ func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) {
go a.confirmVMWindowClose(w.CloseVM)
return
}
if w.StartVM == "" {
if w.StartVM == "" && w.ResumeVM == "" {
if secondLaunch && !w.Background {
a.ShowMainWindow()
}
return
}
name := w.StartVM
if w.ResumeVM != "" {
name = w.ResumeVM
}
result := a.startResultPath(w.StartResult)
if w.StartResult != "" && result == "" {
a.emitVMLog(name, "Ignored a start result path outside the Reims-Go temp folder: "+w.StartResult)
}
a.emitVMLog(name, "Start requested from the command line")
go func() {
capture := a.captureLogs(vmKey(name))
err := a.startHandedVM(w.StartDriver, name)
lines := a.releaseLogs(vmKey(name), capture)
key := vmKeyForDriver(w.StartDriver, name)
capture := a.captureLogs(key)
var err error
if w.ResumeVM != "" {
err = a.ResumeVMWithDriver(w.StartDriver, name)
} else {
err = a.startHandedVM(w.StartDriver, name)
}
lines := a.releaseLogs(key, capture)
if err != nil && len(lines) > 0 {
// StartVM's own error is often just "exit status 1"; the reason is
// in what it logged. The command line has no log panel to look at.
+5 -2
View File
@@ -95,7 +95,7 @@ func run(args []string) (i18n.Locale, error) {
case "runtime":
return loc, cmdRuntime(cfg, loc, rest[1:])
case "vm":
return loc, cmdVM(cfg, loc, rest[1:], *dataRootFlag == "")
return loc, cmdVM(cfg, loc, rest[1:], canHandoffDataRoot(cfg.DataRoot))
case "installer":
return loc, cmdInstaller(cfg, loc, rest[1:])
case "plugin":
@@ -292,6 +292,9 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
}
inst, err := rt.InstallFromArchive(cfg, args[1])
if err != nil {
if errors.Is(err, rt.ErrRuntimeInUse) {
return i18n.NewCodedError(loc, "E_RUNTIME_IN_USE", "runtime.install_in_use", nil, err)
}
return err
}
cfg.ActiveRuntime = inst.Commit
@@ -533,7 +536,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm resume [--driver <id>] <name>")
}
return resumeVM(ctx, cfg, *driverID, fs.Arg(0))
return resumeVM(ctx, cfg, *driverID, fs.Arg(0), viaWindow)
case "discard-suspend":
fs := flag.NewFlagSet("vm discard-suspend", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
+31 -2
View File
@@ -10,6 +10,7 @@ import (
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/console"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/guest"
@@ -17,12 +18,40 @@ import (
"github.com/Nwflower/reims-go/internal/macos/opencore"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/networkmsg"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/qmp"
)
func defaultMacOSGuestLang(loc i18n.Locale) string { return opencore.DefaultGuestLang(loc) }
func requireDirectNetwork(vm driver.VMInfo) error {
if vm.Ref().DriverID != driver.BuiltinReimsMacOSDriverID {
return nil
}
mode, _ := vm.DriverData["network_mode"].(string)
extra, _ := vm.DriverData["extra_args"].(string)
if mode == "bridge" || reims.PacketBridgeSocket(extra) != "" || reims.PacketBridgePort(extra) > 0 {
return networkmsg.Error("cli_managed_required", nil)
}
return nil
}
// checkDirectMacOSNetwork 由驱动在持有操作锁时再次检查,避免配置在解析后被切换。
func checkDirectMacOSNetwork(ctx context.Context, cfg *config.Config, name string) error {
prep, err := startprep.New(*cfg, nil)
if err != nil {
return err
}
d, err := prep.Client.Show(ctx, name)
if err != nil {
return err
}
if d.NetworkMode == "bridge" || reims.PacketBridgeSocket(d.ExtraArgs) != "" || reims.PacketBridgePort(d.ExtraArgs) > 0 {
return networkmsg.Error("cli_managed_required", nil)
}
return nil
}
func requireCLIMacOSEnabled(cfg *config.Config, loc i18n.Locale) error {
st, err := plugin.NewStateStore(plugin.NewPluginsLayout(cfg.DataRoot).Root).Load()
if err != nil {
@@ -124,7 +153,7 @@ func typeMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, args
if err != nil {
return err
}
n, err := qmp.TypeIntoVM(ctx, detail.Directory, text, nil)
n, err := console.NewManager().TypeText(ctx, detail.Directory, text, nil)
if err != nil {
return err
}
+27
View File
@@ -0,0 +1,27 @@
package cli
import (
"os"
"path/filepath"
"github.com/Nwflower/reims-go/internal/config"
)
func canHandoffDataRoot(root string) bool {
cfg, err := config.Load("")
return err == nil && sameDataRoot(root, cfg.DataRoot)
}
func sameDataRoot(a, b string) bool {
a, aerr := filepath.Abs(a)
b, berr := filepath.Abs(b)
if aerr != nil || berr != nil {
return false
}
if a == b {
return true
}
ast, aerr := os.Stat(a)
bst, berr := os.Stat(b)
return aerr == nil && berr == nil && os.SameFile(ast, bst)
}
+36
View File
@@ -0,0 +1,36 @@
package cli
import (
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/driver"
)
func TestExplicitCurrentDataRootCanHandoff(t *testing.T) {
root := t.TempDir()
t.Setenv("REIMS_GO_DATA_ROOT", root)
if !canHandoffDataRoot(root) || !canHandoffDataRoot(filepath.Join(root, ".")) {
t.Fatal("显式指定相同数据目录不应绕过管理器")
}
other := filepath.Join(root, "other")
if err := os.Mkdir(other, 0700); err != nil {
t.Fatal(err)
}
if canHandoffDataRoot(other) {
t.Fatal("不应将其他数据目录交给当前管理器")
}
}
func TestDirectBridgeStartAndResumeAreRejected(t *testing.T) {
for _, mode := range []string{"bridge", "nat", "off"} {
err := requireDirectNetwork(driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, DriverData: map[string]any{"network_mode": mode}})
if (err != nil) != (mode == "bridge") {
t.Errorf("直接启动 %s: %v", mode, err)
}
}
if err := requireDirectNetwork(driver.VMInfo{DriverID: "example.other", DriverData: map[string]any{"network_mode": "bridge"}}); err != nil {
t.Fatalf("不应限制其他驱动自己的桥接实现: %v", err)
}
}
+6 -1
View File
@@ -42,6 +42,9 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
}
cb := builtin.HostCallbacks{
GetConfig: func() config.Config { return *cfg },
PrepareVMNetwork: func(ctx context.Context, name string, _ bool) (func(), error) {
return nil, checkDirectMacOSNetwork(ctx, cfg, name)
},
Log: func(source, line string) {
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
},
@@ -77,10 +80,12 @@ func openCLIMarketClient(cfg *config.Config) *plugin.MarketClient {
func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go plugin <list|search|install|update|pack|link|enable|disable|remove|info|doctor|locale|run>")
return fmt.Errorf("usage: reims-go plugin <list|search|install|update|pack|link|enable|disable|remove|info|doctor|locale|run|connect>")
}
ctx := context.Background()
switch args[0] {
case "connect":
return pluginConnect(args[1:])
case "search":
fs := flag.NewFlagSet("plugin search", flag.ContinueOnError)
kind := fs.String("kind", "", "Filter by plugin kind (theme, locale, driver, tool, template, runtime)")
+9
View File
@@ -0,0 +1,9 @@
//go:build !windows
package cli
import "errors"
func pluginConnect([]string) error {
return errors.New("plugin connect is available on Windows desktop builds")
}
+131
View File
@@ -0,0 +1,131 @@
//go:build windows
package cli
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/Nwflower/reims-go/internal/control"
)
func pluginConnect(args []string) error {
if len(args) != 2 || strings.TrimSpace(args[0]) == "" || strings.TrimSpace(args[1]) == "" {
return errors.New("usage: reims-go plugin connect <plugin-id> <channel>")
}
pluginID, channel := strings.TrimSpace(args[0]), strings.TrimSpace(args[1])
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
conn, err := control.Dial(ctx)
if err != nil {
if startErr := spawnWindow([]string{"--background"}); startErr != nil {
return fmt.Errorf("connect to Reims-Go desktop: %w", err)
}
conn, err = waitForPluginControl(ctx)
if err != nil {
return fmt.Errorf("connect to Reims-Go desktop: %w", err)
}
}
defer conn.Close()
go func() {
<-ctx.Done()
_ = conn.Close()
}()
encoder := json.NewEncoder(conn)
stdinDone := make(chan error, 1)
go func() {
defer conn.Close()
scanner := bufio.NewScanner(os.Stdin)
scanner.Buffer(make([]byte, 64*1024), control.MaxFrameBytes)
for scanner.Scan() {
message := append(json.RawMessage(nil), scanner.Bytes()...)
if !json.Valid(message) {
stdinDone <- errors.New("MCP input line is not valid JSON")
return
}
if err := encoder.Encode(control.Request{PluginID: pluginID, Channel: channel, Message: message}); err != nil {
stdinDone <- err
return
}
}
stdinDone <- scanner.Err()
_ = conn.Close()
}()
responseScanner := bufio.NewScanner(conn)
responseScanner.Buffer(make([]byte, 64*1024), control.MaxFrameBytes)
for responseScanner.Scan() {
var response control.Response
if err := json.Unmarshal(responseScanner.Bytes(), &response); err != nil {
return fmt.Errorf("decode host control response: %w", err)
}
if response.Error != "" {
return errors.New(response.Error)
}
if len(response.Message) > 0 && string(response.Message) != "null" {
if _, err := os.Stdout.Write(response.Message); err != nil {
return err
}
if _, err := os.Stdout.Write([]byte{'\n'}); err != nil {
return err
}
}
}
if err := responseScanner.Err(); err != nil {
// Closing stdin closes the named pipe from the writer goroutine. The
// response reader can observe that close just before stdinDone is
// scheduled, so give the writer a short chance to report a clean EOF.
stdinTimer := time.NewTimer(250 * time.Millisecond)
defer stdinTimer.Stop()
select {
case stdinErr := <-stdinDone:
if stdinErr != nil && !errors.Is(stdinErr, context.Canceled) {
if ctx.Err() != nil {
return nil
}
return stdinErr
}
return nil
case <-stdinTimer.C:
case <-ctx.Done():
return nil
}
if ctx.Err() != nil {
return nil
}
return err
}
return nil
}
func waitForPluginControl(ctx context.Context) (net.Conn, error) {
deadline := time.NewTimer(15 * time.Second)
defer deadline.Stop()
ticker := time.NewTicker(150 * time.Millisecond)
defer ticker.Stop()
var lastErr error
for {
conn, err := control.Dial(ctx)
if err == nil {
return conn, nil
}
lastErr = err
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-deadline.C:
return nil, lastErr
case <-ticker.C:
}
}
}
+32 -9
View File
@@ -26,8 +26,7 @@ const startHandoffTimeout = 5 * time.Minute
// Tools and the Win10 cold-reboot watcher too; both need a process that stays
// up after this command exits.
//
// viaWindow is false when --data-root points elsewhere than the window's
// data root could; the VM then starts here, without those two.
// 显式传入管理器当前数据目录仍交给管理器;其他目录的桥接禁止直接启动。
func startVMWithDriver(ctx context.Context, cfg *config.Config, driverID, name string, viaWindow bool) error {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil {
@@ -42,6 +41,9 @@ func startVMWithDriver(ctx context.Context, cfg *config.Config, driverID, name s
if viaWindow && windowHandoffWorks {
return startInWindow(ctx, cfg, vm.DriverID, vm.Name)
}
if err := requireDirectNetwork(vm); err != nil {
return err
}
_, err = svc.Start(ctx, vm.Ref(), os.Stdout, os.Stderr)
return err
}
@@ -79,7 +81,9 @@ func deleteVM(ctx context.Context, cfg *config.Config, driverID, name string, ke
func resizeVM(ctx context.Context, cfg *config.Config, driverID, name, newSize string) (driver.DiskResizeResult, error) {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil { return driver.DiskResizeResult{}, err }
if err != nil {
return driver.DiskResizeResult{}, err
}
defer mgr.Close()
svc := lifecycle.New(mgr.Registry(), router, nil)
return svc.ResizeDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, newSize, os.Stdout, os.Stderr)
@@ -87,7 +91,9 @@ func resizeVM(ctx context.Context, cfg *config.Config, driverID, name, newSize s
func compactVM(ctx context.Context, cfg *config.Config, driverID, name string) (driver.DiskCompactResult, error) {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil { return driver.DiskCompactResult{}, err }
if err != nil {
return driver.DiskCompactResult{}, err
}
defer mgr.Close()
svc := lifecycle.New(mgr.Registry(), router, nil)
return svc.CompactDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, os.Stdout, os.Stderr)
@@ -104,19 +110,36 @@ func stopVM(ctx context.Context, cfg *config.Config, driverID, name string, forc
}
func startInWindow(ctx context.Context, cfg *config.Config, driverID, name string) error {
return runInWindow(ctx, cfg, driverID, name, false)
}
func runInWindow(ctx context.Context, cfg *config.Config, driverID, name string, resume bool) error {
prefix := "cli.start."
if resume {
prefix = "cli.resume."
}
// 使用管理器的规范目录,避免同目录的大小写或 Junction 别名使结果路径被拒绝。
if desktop, err := config.Load(""); err == nil && sameDataRoot(cfg.DataRoot, desktop.DataRoot) {
copy := *cfg
copy.DataRoot = desktop.DataRoot
cfg = &copy
}
if err := os.MkdirAll(cfg.TempDir(), 0o755); err != nil {
return err
}
result := filepath.Join(cfg.TempDir(), fmt.Sprintf("cli-start-%d.json", time.Now().UnixNano()))
w := WindowArgs{StartVM: name, StartDriver: driverID, StartResult: result}
if resume {
w.StartVM, w.ResumeVM = "", name
}
if hwnd := findWindow(); hwnd != 0 {
fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.handing_to_window", i18n.Vars{"name": name}))
fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, prefix+"handing_to_window", i18n.Vars{"name": name}))
if err := sendToWindow(hwnd, w.Args(), 0); err != nil {
return err
}
} else {
w.Background = true
fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.spawning_tray", i18n.Vars{"name": name}))
fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, prefix+"spawning_tray", i18n.Vars{"name": name}))
if err := spawnWindow(w.Args()); err != nil {
return err
}
@@ -127,9 +150,9 @@ func startInWindow(ctx context.Context, cfg *config.Config, driverID, name strin
res, err := waitStartResult(ctx, result, startHandoffTimeout)
switch {
case errors.Is(err, context.Canceled):
return fmt.Errorf("%s", i18n.M(cfg.Locale, "cli.start.canceled", i18n.Vars{"name": name}))
return fmt.Errorf("%s", i18n.M(cfg.Locale, prefix+"canceled", i18n.Vars{"name": name}))
case errors.Is(err, context.DeadlineExceeded):
return fmt.Errorf("%s", i18n.M(cfg.Locale, "cli.start.timeout", i18n.Vars{"name": name, "timeout": startHandoffTimeout}))
return fmt.Errorf("%s", i18n.M(cfg.Locale, prefix+"timeout", i18n.Vars{"name": name, "timeout": startHandoffTimeout}))
case err != nil:
return err
}
@@ -138,7 +161,7 @@ func startInWindow(ctx context.Context, cfg *config.Config, driverID, name strin
}
// Guest Tools only connects once macOS is up and its agent runs, so say
// what this process can know: who now looks after the VM.
fmt.Println(i18n.M(cfg.Locale, "cli.start.managed_ok", i18n.Vars{"name": name}))
fmt.Println(i18n.M(cfg.Locale, prefix+"managed_ok", i18n.Vars{"name": name}))
return nil
}
+7 -1
View File
@@ -33,7 +33,7 @@ func suspendVM(ctx context.Context, cfg *config.Config, driverID, name string) e
return nil
}
func resumeVM(ctx context.Context, cfg *config.Config, driverID, name string) error {
func resumeVM(ctx context.Context, cfg *config.Config, driverID, name string, viaWindow bool) error {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
@@ -45,6 +45,12 @@ func resumeVM(ctx context.Context, cfg *config.Config, driverID, name string) er
return err
}
ref := vm.Ref()
if viaWindow && windowHandoffWorks {
return runInWindow(ctx, cfg, ref.DriverID, ref.Name, true)
}
if err := requireDirectNetwork(vm); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "Resuming %s...\n", ref.Name)
startAt := time.Now()
if _, err := svc.Resume(ctx, ref, nil, os.Stdout, os.Stderr); err != nil {
+12 -1
View File
@@ -14,6 +14,7 @@ const (
flagSafeMode = "--safe-mode"
flagStartVM = "--start-vm="
flagStartDriver = "--start-driver="
flagResumeVM = "--resume-vm="
flagStartResult = "--start-result="
flagCloseVM = "--close-vm="
flagWaitPID = "--wait-pid="
@@ -29,6 +30,8 @@ type WindowArgs struct {
// StartVM is a VM to start as the GUI's StartVM would (Guest Tools and
// the Win10 cold-reboot watcher included).
StartVM string
// ResumeVM 只执行恢复,不把未挂起的虚拟机当作普通启动。
ResumeVM string
// StartDriver identifies the VM's owning driver when names are ambiguous.
StartDriver string
// StartResult is a file the window writes a StartResult to once StartVM
@@ -54,6 +57,11 @@ func ParseWindowArgs(args []string) (w WindowArgs, ok bool) {
w.SafeMode = true
case strings.HasPrefix(a, flagStartVM):
w.StartVM = strings.TrimPrefix(a, flagStartVM)
case strings.HasPrefix(a, flagResumeVM):
w.ResumeVM = strings.TrimPrefix(a, flagResumeVM)
if w.ResumeVM == "" {
return WindowArgs{}, false
}
case strings.HasPrefix(a, flagStartDriver):
w.StartDriver = strings.TrimPrefix(a, flagStartDriver)
case strings.HasPrefix(a, flagStartResult):
@@ -73,7 +81,7 @@ func ParseWindowArgs(args []string) (w WindowArgs, ok bool) {
return WindowArgs{}, false
}
}
return w, true
return w, w.StartVM == "" || w.ResumeVM == ""
}
// Args is the inverse of ParseWindowArgs.
@@ -88,6 +96,9 @@ func (w WindowArgs) Args() []string {
if w.StartVM != "" {
out = append(out, flagStartVM+w.StartVM)
}
if w.ResumeVM != "" {
out = append(out, flagResumeVM+w.ResumeVM)
}
if w.StartDriver != "" {
out = append(out, flagStartDriver+w.StartDriver)
}
+10
View File
@@ -30,6 +30,9 @@ func TestParseWindowArgs(t *testing.T) {
{[]string{"--background", "--wait-pid=7"}, WindowArgs{Background: true, WaitPID: 7}, true},
{[]string{"--wait-pid=0"}, WindowArgs{}, false},
{[]string{"--wait-pid=abc"}, WindowArgs{}, false},
{[]string{"--background", "--resume-vm=m0", "--start-result=result.json"}, WindowArgs{Background: true, ResumeVM: "m0", StartResult: "result.json"}, true},
{[]string{"--resume-vm="}, WindowArgs{}, false},
{[]string{"--resume-vm=m0", "--start-vm=m0"}, WindowArgs{ResumeVM: "m0", StartVM: "m0"}, false},
}
for _, c := range cases {
got, ok := ParseWindowArgs(c.args)
@@ -57,6 +60,13 @@ func TestWindowArgsRoundTrip(t *testing.T) {
}
}
func TestResumeWindowArgsRoundTrip(t *testing.T) {
w := WindowArgs{Background: true, ResumeVM: "mac os", StartResult: "cli-start-42.json"}
if got, ok := ParseWindowArgs(w.Args()); !ok || got != w {
t.Fatalf("恢复请求往返解析 = %+v, %v", got, ok)
}
}
func TestStartResultRoundTrip(t *testing.T) {
dir := t.TempDir()
okPath := filepath.Join(dir, "cli-start-1.json")
Loaded 100 of 233 files, more files were not shown because too many files have changed in this diff. Show more