Compare commits

..
Author SHA1 Message Date
YXC0915 542792f7e4 feat: support the QEMU Stambha ARM64 preview runtime 2026-12-04 18:40:29 +08:00
121 changed files with 2823 additions and 3945 deletions

No files matched your search

+44
View File
@@ -16,11 +16,33 @@ export const english = {
coverageComplete: "Complete for the selected scope",
findings: "Reported defects",
withheld: "Candidates missing required evidence fields",
evidenceIncomplete: "Some candidates lack the evidence needed to assess them.",
questions: "Decisions needed before merging",
clarify: "Clarify the expected behavior",
clarifyReason: "Resolve the contract questions above before merging.",
warnings: "Incomplete review tasks",
tests: "CI for this PR commit",
ciRun: "CI run",
ciPassed: "Passed",
ciFailed: "Failed",
ciNoPass: "No passing result",
ciActionRequired: "CI needs manual action.",
ciPending: "Pending",
ciMissing: "No CI run found for this commit.",
recommendation: "Merge recommendation",
merge: "Ready to merge",
changes: "Revise and review again",
inspect: "Review the remaining changes",
awaitCI: "No code blockers found. Awaiting CI.",
conflict: "GitHub detected merge conflicts. Resolve them and request another review.",
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.",
incomplete: "Some changes or review tasks were not covered; complete the review before merging.",
inline: "Inline findings",
unanchored: "Findings without a stable inline diff anchor",
noFindings: "No actionable issues found in the reviewed changes.",
noDiff: "No reviewable text changes remained after generated and lock files were excluded.",
inlineFallback: "GitHub could not attach inline comments. See the findings below.",
};
@@ -43,11 +65,33 @@ export const chinese = {
coverageComplete: "已完成所选范围",
findings: "已报告缺陷",
withheld: "缺少必需证据字段的候选意见",
evidenceIncomplete: "部分候选意见缺少必要证据,需要人工核对。",
questions: "合并前需确认的问题",
clarify: "确认预期行为",
clarifyReason: "合并前确认上方列出的行为约定。",
warnings: "未完成的审查任务",
tests: "当前 PR 提交的 CI",
ciRun: "CI 运行记录",
ciPassed: "通过",
ciFailed: "失败",
ciNoPass: "无通过结果",
ciActionRequired: "CI 需要人工处理。",
ciPending: "尚未完成",
ciMissing: "未找到对应提交的 CI 记录。",
recommendation: "合并建议",
merge: "可以合并",
changes: "修改后再审",
inspect: "先审完剩余改动",
awaitCI: "代码未见阻塞,等待 CI",
conflict: "GitHub 检测到合并冲突,解决后重新审核。",
mainMoved: "审核期间主线有更新。",
ciRequired: "当前提交还没有 CI 通过记录。",
fixCI: "合并前处理 CI 失败项。",
fixFindings: "合并前处理下方有证据的实质问题。",
incomplete: "部分改动或审查任务未覆盖,合并前补齐审查。",
inline: "行内问题",
unanchored: "无法稳定定位到差异行的有效问题",
noFindings: "已审核的差异中未发现可报告的问题。",
noDiff: "排除生成文件与锁文件后,没有可审核的文本改动。",
inlineFallback: "GitHub 未能附加行内评论,审核意见如下。",
};
+68 -3
View File
@@ -434,6 +434,25 @@ async function listChangedFiles(github, path) {
return files.slice(0, MAX_FILES);
}
export async function waitForCI(github, repoPath, pull, number, { wait = false } = {}) {
if (wait) throw new Error("CI polling is disabled for PR review");
if (pull.base.ref !== pull.base.repo.default_branch || !pull.head.repo) return { status: "unavailable" };
const path = repoPath + "/actions/workflows/ci.yml/runs?event=pull_request&per_page=20&head_sha=" + pull.head.sha;
const { data } = await github(path);
const run = data.workflow_runs.find((run) => run.head_sha === pull.head.sha
&& run.head_repository?.full_name === pull.head.repo.full_name && run.head_branch === pull.head.ref
&& (!run.pull_requests.length || run.pull_requests.some((pr) => pr.number === Number(number))));
if (run?.status !== "completed") return { status: run?.status ?? "unavailable", id: run?.id, attempt: run?.run_attempt, url: run?.html_url };
const { data: jobs } = await github(repoPath + "/actions/runs/" + run.id + "/attempts/" + run.run_attempt + "/jobs");
const verify = jobs.jobs.find((job) => job.name === "verify");
const steps = verify?.steps.filter((step) => /^(CI tests|Frontend test|Go test|Bundle frontend|Build reims-go|WebView2)/.test(step.name));
return {
status: "completed", id: run.id, attempt: run.run_attempt, url: run.html_url,
conclusion: verify?.conclusion ?? run.conclusion,
steps: (steps ?? []).map(({ name, conclusion }) => ({ name, conclusion })),
};
}
async function mainlineContext(github, repoPath, pull, files) {
const branch = pull.base.repo.default_branch;
const refPath = repoPath + "/git/ref/heads/" + encodeURIComponent(branch);
@@ -463,12 +482,21 @@ async function mainlineContext(github, repoPath, pull, files) {
};
}
export function reviewSummary(copy, assessment, { incomplete, total = 0, withheld = 0, questions = [], fallback = [] }) {
export function reviewSummary(copy, assessment, ci, { incomplete, mergeable, total = 0, withheld = 0, questions = [], fallback = [] }) {
const lines = [];
lines.push("- **" + copy.coverage + "** " + (incomplete ? copy.coveragePartial : copy.coverageComplete));
lines.push("- **" + copy.findings + "** " + total);
if (withheld) lines.push("- **" + copy.withheld + "** " + withheld);
if (assessment.warnings?.length) lines.push("- **" + copy.warnings + "** " + assessment.warnings.length);
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 ?? "—"));
if (fallback.length) {
lines.push("\n**" + copy.unanchored + "**");
for (const finding of fallback) lines.push(summaryFinding(finding));
@@ -477,6 +505,31 @@ export function reviewSummary(copy, assessment, { incomplete, total = 0, withhel
lines.push("\n**" + copy.questions + "**");
for (const question of questions) lines.push("- " + plainMarkdown(shortText(question, 500)));
}
let decision = "merge";
let reason = copy.noFindings;
if (mergeable === false) {
decision = "changes";
reason = copy.conflict;
} else if (ciFailed) {
decision = "changes";
reason = copy.fixCI;
} else if (total > 0) {
decision = "changes";
reason = copy.fixFindings;
} else if (incomplete) {
decision = "inspect";
reason = copy.incomplete;
} else if (withheld) {
decision = "inspect";
reason = copy.evidenceIncomplete;
} else if (questions.length) {
decision = "clarify";
reason = copy.clarifyReason;
} else if (!ciPassed) {
decision = "awaitCI";
reason = copy.ciRequired;
}
lines.push("\n**" + copy.recommendation + " · " + copy[decision] + "** " + reason);
return lines.join("\n");
}
@@ -914,6 +967,18 @@ export async function run() {
return current.state === "open" && snapshot(current).join(":") === revision ? current : null;
}
if (!(await currentPR())) {
console.log("PR changed while the review was running");
return;
}
let ci;
try {
ci = await waitForCI(github, repoPath, pull, number, { wait: false });
} catch (error) {
console.warn("Could not read current CI status: " + error.message);
ci = { status: "unavailable" };
}
const latestPR = await currentPR();
if (!latestPR) {
console.log("PR changed before the review could be published");
return;
}
@@ -935,8 +1000,8 @@ export async function run() {
const incremental = range.incremental ? "\n\n" + copy.incremental + " `" + range.lastHeadSha.slice(0, 12) + "`" : "";
const incomplete = assessment.status === "partial" || assessment.status === "completed_with_errors"
|| assessment.warnings.length > 0 || (assessment.status === "skipped" && stats.files > 0);
const summaryBody = reviewSummary(copy, assessment, {
incomplete, total, withheld, questions, fallback,
const summaryBody = reviewSummary(copy, assessment, ci, {
incomplete, mergeable: latestPR.mergeable, total, withheld, questions, fallback,
});
const publishedMarker = reviewMarker(pull, mainline.sha, incomplete);
const summary = publishedMarker + "\n## " + copy.heading + "\n\n" + copy.mainline + " `" + mainline.sha.slice(0, 12) + "` · " + coverage
+40 -16
View File
@@ -29,6 +29,7 @@ import {
reviewWithOCR,
selectReviewRange,
shouldSkipAutoReview,
waitForCI,
} from "./pr-review.mjs";
const A = "a".repeat(40);
@@ -224,8 +225,8 @@ test("finding filtering sorts severity and renders plain single-line and multi-l
assert.doesNotMatch(result.comments[1].body, /suggestion|keepOldConfig/);
assert.equal(result.fallback.length, 1);
assert.equal(result.total, 3);
assert.match(reviewSummary(chinese, { comments: [], warnings: [] }, {
incomplete: false, total: 3, fallback: result.fallback,
assert.match(reviewSummary(chinese, { comments: [], warnings: [] }, { status: "completed", conclusion: "success" }, {
incomplete: false, mergeable: true, total: 3, fallback: result.fallback,
}), /无法稳定定位到差异行的有效问题[\s\S]*99.*backup is rejected/);
});
@@ -240,7 +241,7 @@ test("public reviews retain prose around model code blocks and require opt-in fo
assert.doesNotMatch(comment.body, /callMissingMethod|cancelTask|```/);
const [suggestion] = classifyFindings(input, locations, { publishSuggestions: true }).comments;
assert.match(suggestion.body, /```suggestion\ncancelTask\(id\)\n```/);
const summary = reviewSummary(english, { message: "One issue found.\n~~~js\nignoreThis()\n~~~" }, {});
const summary = reviewSummary(english, { message: "One issue found.\n~~~js\nignoreThis()\n~~~" }, {}, {});
assert.match(summary, /Reported defects.*0/);
assert.doesNotMatch(summary, /One issue found/);
assert.doesNotMatch(summary, /ignoreThis/);
@@ -274,27 +275,50 @@ test("publication requires evidence and keeps merge-relevant contract questions
assert.equal(result.withheld, 3);
assert.equal(result.questions.length, 1);
assert.ok(result.comments.every(({ body }) => !/Trigger:|Impact:|Evidence:/.test(body)));
const summary = reviewSummary(english, { warnings: [{}], message: "8 findings" }, { ...result, incomplete: true });
const summary = reviewSummary(english, { warnings: [{}], message: "8 findings" }, { status: "completed", conclusion: "success" }, { ...result, incomplete: true });
assert.match(summary, /Review coverage.*Incomplete/);
assert.match(summary, /Reported defects.*3/);
assert.match(summary, /Decisions needed before merging[\s\S]*Should an open dialog close/);
assert.doesNotMatch(summary, /8 findings/);
const questionOnly = reviewSummary(english, {}, { incomplete: false, questions: result.questions });
assert.match(questionOnly, /Decisions needed before merging/);
const withheldOnly = reviewSummary(english, {}, { withheld: 3 });
assert.match(withheldOnly, /Candidates missing required evidence fields.*3/);
const questionOnly = reviewSummary(english, {}, { status: "completed", conclusion: "success" }, { incomplete: false, questions: result.questions });
assert.match(questionOnly, /Clarify the expected behavior/);
const withheldOnly = reviewSummary(english, {}, { status: "completed", conclusion: "success" }, { withheld: 3 });
assert.match(withheldOnly, /Some candidates lack the evidence/);
assert.doesNotMatch(withheldOnly, /Ready to merge/);
});
test("a code-only review reports coverage and defects without restating GitHub checks", () => {
const complete = reviewSummary(english, { warnings: [] }, { incomplete: false });
assert.match(complete, /Review coverage.*Complete for the selected scope/);
assert.match(complete, /Reported defects.*0/);
assert.doesNotMatch(complete, /CI|merge/i);
const partial = reviewSummary(chinese, { warnings: [{}] }, { incomplete: true });
assert.match(partial, /审查覆盖.*部分完成/);
const pull = {
base: { ref: "main", repo: { default_branch: "main" } },
head: { sha: B, ref: "feature", repo: { full_name: "fork/Reims-Go" } },
};
const run = { id: 100, run_attempt: 2, head_sha: B, head_branch: "feature", head_repository: pull.head.repo, pull_requests: [] };
test("CI publication lookup is a single non-blocking request and preserves step summaries", async () => {
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: [{ name: "Go test", conclusion: "success" }] }] } }
: { data: { workflow_runs: [{ ...run, status: "completed", conclusion: "success", html_url: "https://github.com/test/run/100" }] } },
"/repos/test/Reims-Go", pull, 42, { wait: false });
const summary = reviewSummary(english, { message: "No issues", comments: [], warnings: [] }, passed, { incomplete: false, mergeable: true, hasFindings: false });
assert.match(summary, /Go test · success/);
assert.match(summary, /Ready to merge/);
const waiting = reviewSummary(chinese, { comments: [], warnings: [] }, queued, { incomplete: false, mergeable: true, hasFindings: false });
assert.match(waiting, /代码未见阻塞,等待 CI/);
});
test("CI failures and incomplete OCR results affect the final recommendation independently", () => {
const failed = reviewSummary(chinese, { comments: [], warnings: [] }, { status: "completed", conclusion: "failure" }, { incomplete: false, mergeable: true, hasFindings: false });
assert.match(failed, /修改后再审/);
assert.match(failed, /处理 CI 失败项/);
const partial = reviewSummary(chinese, { comments: [], warnings: [{}] }, { status: "completed", conclusion: "success" }, { incomplete: true, mergeable: true, hasFindings: false });
assert.match(partial, /先审完剩余改动/);
assert.match(partial, /未完成的审查任务/);
assert.doesNotMatch(partial, /CI|合并建议/);
});
async function fakeOCR(t, { exitCode = 0, stdout = null } = {}) {
+1
View File
@@ -25,6 +25,7 @@
| :--- | :--- | :--- |
| 挂起恢复所用运行时的编号和兼容判定 | Alpha 运行时编号与挂起兼容性规范 | [reims-go/reims-vgpu 的 packaging/windows-runtime/versioning.md](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/versioning.md) |
| 运行时源码、依赖补丁和补丁退役 | 运行时源码与依赖补丁 | [reims-go/reims-vgpu 的 packaging/windows-runtime/patches/README.md](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) |
| ARM macOS 实验运行时和准备启动介质 | ARM macOS 实验版 | [docs/arm64-preview.md](docs/arm64-preview.md) |
| FileVault 开机输入与启动镜像 | FileVault 开机输入镜像构建 | [scripts/filevault-input/README.md](scripts/filevault-input/README.md) |
| 虚拟机系统盘性能测量 | 系统盘小文件 I/O 基准与采样工具 | [scripts/io-bench/README.md](scripts/io-bench/README.md) |
| 跨会话工单与 Agent 交接 | 调试工单模板 | [scripts/debug/work-template.md](scripts/debug/work-template.md) |
-94
View File
@@ -4,100 +4,6 @@
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.13 — 2026-12-04
[中文](#cn-v0.2.13) | [English](#en-v0.2.13)
<h3 id="cn-v0.2.13">新增功能</h3>
- 支持在 Windows 与 macOS 虚拟机之间复制粘贴文件和文件夹。Windows 中剪切的文件可粘贴到 macOS,原文件和剪切状态会保留。可在插件页或虚拟机设置中调整文件同步和传输上限。已有虚拟机可更新至 Guest Tools `v21`,一并获得双向文件同步和最新拖放修复。 [#108](https://github.com/Nwflower/Reims-Go/pull/108) — [@YinLiaoCo](https://github.com/YinLiaoCo), [@staytomorrow](https://github.com/staytomorrow), [@yxc0915](https://github.com/yxc0915)
- 可在设置中开启快捷键,在虚拟机窗口内切换无边框全屏。默认关闭,默认组合键为 `Ctrl+Shift+F`,可自行录制。 — [@reiasu2](https://github.com/reiasu2), [@Nwflower](https://github.com/Nwflower)
- 支持由插件接入非 macOS 虚拟机,可在客户端查看其状态,并通过 SSH、WSL、远程桌面、Hyper-V 连接或 ADB 打开。插件契约升级为 `pluginApi 1.2` 和 `uiApi 2.1`,并公开 `pkg/drivertest` 契约测试套件([#74](https://github.com/Nwflower/Reims-Go/issues/74))。 — [@icaruszezen](https://github.com/icaruszezen), [@Nwflower](https://github.com/Nwflower)
- 启用内置的「macOS 应用窗口」插件后,可从运行中的虚拟机菜单把单屏 macOS 客体的前台应用打开为 Windows 无边框窗口,并在宿主与客体之间复制粘贴。 [#118](https://github.com/Nwflower/Reims-Go/pull/118) — [@yxc0915](https://github.com/yxc0915)
- 沙箱页面插件新增四种视图位置、宿主表单与导航、虚拟机和设置访问、授权文件读写、任务进度、受控网络请求及事件订阅,并支持确认、复制、外链和私有存储。 — [@Nwflower](https://github.com/Nwflower)
- 「内核」页新增 QEMU ASLR 开关,默认关闭。启用后,虚拟机冷启动时可能恢复 Dock 图标。规则随运行时版本切换,关闭时仅移除自动添加的规则。 — [@ELDment](https://github.com/ELDment)
- 「设置」页新增默认关闭的「Hyper-V 启动切换」选项,开启后可确认切换 Windows Hypervisor 下次启动状态以兼容独占模式的 VMware,并在「内核」页区分 Hypervisor 关闭与 BIOS 虚拟化未开启。 [#122](https://github.com/Nwflower/Reims-Go/issues/122) — [@Dnyo666](https://github.com/Dnyo666)
### 体验优化
- 运行时改从 `reims-go/reims-vgpu` 下载。`REIMS_GO_RELEASES_REPO` 现在只影响应用更新,运行时仓库改用 `REIMS_GO_RUNTIME_RELEASES_REPO` 指定。 — [@Nwflower](https://github.com/Nwflower)
### 问题修复
- 修复 macOS 剪贴板含有无法读取的格式时,无法粘贴从 Windows 复制的文件的问题。 — [@YinLiaoCo](https://github.com/YinLiaoCo)
- 修复虚拟机交互期间的启停、挂起和截图输入竞争,清理桌面重启后遗留的 MCP 临时虚拟机,并确保 MCP 控制通道在长请求、输入结束和请求失败时正确传递响应。登录密码通过键盘输入,不再经过客体剪贴板。 — [@bvzrays](https://github.com/bvzrays)
- 文件拖放通过 WebDAV 挂载导入文件,而 Guest Tools 后台以 `sh` 运行。修复全新 macOS 虚拟机首次拖放时未弹出 `sh`「网络宗卷」授权提示导致失败的问题;若权限被拒,拖放会立即提示「文件拖放受限」并在连接卡显示开启路径。开启权限后,拖入访达窗口或照片时会自动重挂仍无法获取文件引用的陈旧挂载;其他挂载故障及文件剪贴板仍保留下载兜底。已有虚拟机需将 Guest Tools 更新至 `v21`。 — [@YinLiaoCo](https://github.com/YinLiaoCo)
- Windows 文件复制到 macOS 时,挂载文件不可读会改用下载回退。诊断报告会记录客体确认写入文件剪贴板的次数。 — [@yxc0915](https://github.com/yxc0915)
- 修复 QEMU 的 Metal 精度提示误标为错误,避免这些提示增加未读错误计数。 — [@yxc0915](https://github.com/yxc0915)
- 修复放入默认共享文件夹的文件在虚拟机中不显示或同步过慢的问题,移动便携目录后共享文件夹也会使用新位置。升级后需在虚拟机内重新安装 Guest Tools。 — [@reiasu2](https://github.com/reiasu2), [@Nwflower](https://github.com/Nwflower)
- 清理无法恢复的挂起残留,并在 Windows 短暂占用文件时重试封存和清理。挂起和恢复支持存放在长路径下的虚拟机。已有可恢复状态时,启动会提示先恢复或放弃该状态。 [#109](https://github.com/Nwflower/Reims-Go/pull/109) — [@reiasu2](https://github.com/reiasu2), [@Nwflower](https://github.com/Nwflower)
- 修复物理网卡绑定 Hyper-V 外部虚拟交换机后无法启用 Npcap 桥接的问题,自动使用关联管理虚拟网卡的地址转发宿客流量。 — [@ssdsl0126](https://github.com/ssdsl0126)
- 修复文件同步或 WebDAV 挂载耗时较长时,虚拟机中的 Win → ⌘ 快捷键意外打开 Windows 开始菜单的问题。 — [@reiasu2](https://github.com/reiasu2)
- 修复 MCP 创建临时 macOS 虚拟机时的名称校验错误,并开放已授权虚拟机的挂起和恢复操作。 — [@Nwflower](https://github.com/Nwflower)
- 在插件列表和设置中提示当前运行时不支持的插件设置。 — [@cosimawei](https://github.com/cosimawei)
- 修复插件设置中的已保存密钥在清空后仍显示旧掩码,以及连续修改同一设置时保存顺序错乱的问题。 — [@bvzrays](https://github.com/bvzrays)
- 修复分段选项在保存期间短暂禁用后,当前选项的高亮可能消失的问题。 — [@Nwflower](https://github.com/Nwflower)
- 从命令行启动虚拟机失败时,一并显示 Guest Tools 和网络相关的日志。 — [@Nwflower](https://github.com/Nwflower)
- 修复删除虚拟机后可能因文件句柄占用残留旧目录并在重建同名虚拟机时报错的问题。删除前先等待日志监控退出并关闭桥接通道,注销后目录仍被短暂占用时自动重试清理;同时在新建向导、命令行与克隆前提前校验目标目录是否非空,避免保留文件或残留目录拖到建机阶段才失败。删除和清理残留目录前检查其中是否有其他已注册虚拟机的数据。 — [@icaruszezen](https://github.com/icaruszezen), [@Nwflower](https://github.com/Nwflower)
- 修复只用名称指定虚拟机时读不到 SSH 端口等设置的问题。智能体工具此前会因此误报未启用 SSH 端口转发。 — [@Nwflower](https://github.com/Nwflower)
### 移除
- 主题清单不再支持从未生效的 `sounds` 字段。带交互脚本的主题可以自行播放提示音。 — [@Nwflower](https://github.com/Nwflower)
### 其他变更
- 新建 Issue 后自动提示补充信息、疑似重复和提交位置,并定期诊断代码、创建改进 Issue。 — [@Nwflower](https://github.com/Nwflower)
- PR 自动审查改用 OpenCodeReview,支持隔离的只读仓库分析、跨提交增量审查和即时 CI 状态。 — [@Nwflower](https://github.com/Nwflower)
- 提高 PR 自动审查的 token 预算,部分任务出错时仍发布已完成的审查结果。 — [@Nwflower](https://github.com/Nwflower)
- 自动审查要求说明缺陷触发条件、实际后果和代码证据,并在摘要中显示覆盖状态。 — [@Nwflower](https://github.com/Nwflower)
- 自动审查意见优先说明触发条件和实际后果,默认省略代码建议。 — [@Nwflower](https://github.com/Nwflower)
<h3 id="en-v0.2.13">New Features</h3>
- Copy and paste files and folders between Windows and macOS VMs. Pasting files cut in Windows into macOS preserves the original files and the Windows cut state. Adjust file sync and transfer limits in the plugin or VM settings. Update Guest Tools to `v21` in existing VMs for bidirectional file sync and the latest drag-and-drop fixes. [#108](https://github.com/Nwflower/Reims-Go/pull/108) — [@YinLiaoCo](https://github.com/YinLiaoCo), [@staytomorrow](https://github.com/staytomorrow), [@yxc0915](https://github.com/yxc0915)
- Add an optional shortcut in Settings to toggle borderless full screen from the VM window. It is off by default, uses `Ctrl+Shift+F`, and can be customized. — [@reiasu2](https://github.com/reiasu2), [@Nwflower](https://github.com/Nwflower)
- Let plugins add non-macOS VMs, with their state shown in the app and access through SSH, WSL, Remote Desktop, VMConnect, or ADB. The plugin contracts move to `pluginApi 1.2` and `uiApi 2.1`, and the `pkg/drivertest` contract test suite is public ([#74](https://github.com/Nwflower/Reims-Go/issues/74)). — [@icaruszezen](https://github.com/icaruszezen), [@Nwflower](https://github.com/Nwflower)
- Enable the built-in macOS App Windows plugin to open the foreground app from a running, single-display macOS VM in a borderless Windows window, with copy and paste between host and guest. [#118](https://github.com/Nwflower/Reims-Go/pull/118) — [@yxc0915](https://github.com/yxc0915)
- Add four view locations, host forms and navigation, VM and settings access, authorized file I/O, task progress, controlled HTTP requests, and event subscriptions to sandboxed plugins, alongside confirmations, clipboard copy, external links, and private storage. — [@Nwflower](https://github.com/Nwflower)
- Add an opt-in QEMU ASLR switch on the Engine page. It may restore missing Dock icons after a cold start. Rules follow the selected runtime. Turning it off removes only Reims-Go's rules. — [@ELDment](https://github.com/ELDment)
- Add an opt-in Hyper-V boot switch in Settings to toggle Windows Hypervisor launch on next boot for exclusive-mode VMware coexistence, and distinguish hypervisor launch off from disabled BIOS virtualization on the Engine page. [#122](https://github.com/Nwflower/Reims-Go/issues/122) — [@Dnyo666](https://github.com/Dnyo666)
### Improvements
- Runtimes are now downloaded from `reims-go/reims-vgpu`. `REIMS_GO_RELEASES_REPO` now only affects app updates; set the runtime repository with `REIMS_GO_RUNTIME_RELEASES_REPO`. — [@Nwflower](https://github.com/Nwflower)
### Bug Fixes
- Fix pasting files copied from Windows when the macOS clipboard contains an unreadable format. — [@YinLiaoCo](https://github.com/YinLiaoCo)
- Fix races between VM lifecycle and console operations, clean up orphaned MCP temporary VMs after desktop restarts, and preserve MCP control-channel responses during long requests, input shutdown, and request failures. Login passwords are entered as keystrokes without passing through the guest clipboard. — [@bvzrays](https://github.com/bvzrays)
- File drops transfer files over a WebDAV mount read by the Guest Tools background agent (`sh`). macOS now prompts for `sh` Network Volumes access when needed during a drop. If access is denied, drops fail immediately with a File drop limited toast and a Connection card notice showing where to enable it. After access is granted, drops into Finder windows or Photos automatically remount stale WebDAV mounts whose file references are unavailable. Other mount failures and file clipboard sync keep download fallback. Update Guest Tools to `v21` in existing VMs. — [@YinLiaoCo](https://github.com/YinLiaoCo)
- When Windows clipboard files cannot be read from the mounted share on macOS, Guest Tools uses the download fallback. Diagnostics count file clipboard writes confirmed by the guest. — [@yxc0915](https://github.com/yxc0915)
- Show QEMU Metal precision notes as informational logs so they do not increase the unread error count. — [@yxc0915](https://github.com/yxc0915)
- Fix files added to the default shared folder not appearing or syncing slowly in the VM, and use the new location after moving a portable directory. Reinstall Guest Tools in the VM after upgrading. — [@reiasu2](https://github.com/reiasu2), [@Nwflower](https://github.com/Nwflower)
- Clean up orphaned suspend files and retry sealing or cleaning up state when Windows briefly holds the files open. Suspend and resume support VMs stored under long paths. Starting a VM with a recoverable state asks you to resume or discard it first. [#109](https://github.com/Nwflower/Reims-Go/pull/109) — [@reiasu2](https://github.com/reiasu2), [@Nwflower](https://github.com/Nwflower)
- Fix Npcap bridging when a physical adapter is bound to a Hyper-V external virtual switch by using its associated management adapter for host and guest traffic. — [@ssdsl0126](https://github.com/ssdsl0126)
- Fix Win → Command shortcuts opening the Windows Start menu during slow file sync or WebDAV mounting. — [@reiasu2](https://github.com/reiasu2)
- Fix name validation for temporary macOS VMs created by MCP and expose suspend and resume for authorized VMs. — [@Nwflower](https://github.com/Nwflower)
- Show which settings the active runtime does not support in the plugin list and settings dialog. — [@cosimawei](https://github.com/cosimawei)
- Fix saved plugin secrets remaining masked after being cleared and preserve save order when the same setting is edited repeatedly. — [@bvzrays](https://github.com/bvzrays)
- Keep the highlight on the current option of a segmented control after it was briefly disabled while saving. — [@Nwflower](https://github.com/Nwflower)
- Include Guest Tools and network log lines when a VM fails to start from the command line. — [@Nwflower](https://github.com/Nwflower)
- Fix deleted VMs leaving behind their directory on Windows due to transient file locks and breaking subsequent creation of a VM with the same name. Wait for the log monitor to exit and close bridge sockets before deletion, retry directory removal if the VM was already unregistered, and validate non-empty target directories upfront in the create wizard, CLI, and clone flows. Check whether another registered VM uses the directory before removing it. — [@icaruszezen](https://github.com/icaruszezen), [@Nwflower](https://github.com/Nwflower)
- Fixed missing settings such as the SSH port when a VM is identified by name only. Agent tools used to report that SSH port forwarding was off. — [@Nwflower](https://github.com/Nwflower)
### Removals
- Theme manifests no longer accept the `sounds` field, which never took effect. Themes with an interactive script can play their own sounds. — [@Nwflower](https://github.com/Nwflower)
### Chores
- Guide new issues with missing details, possible duplicates, and where to submit them, and regularly diagnose the code to open improvement issues. — [@Nwflower](https://github.com/Nwflower)
- Use OpenCodeReview for PR reviews with isolated read-only repository analysis, incremental commit ranges, and non-blocking CI status. — [@Nwflower](https://github.com/Nwflower)
- Raise the token budget for automated PR reviews and publish completed results when some review tasks fail. — [@Nwflower](https://github.com/Nwflower)
- Require automated review findings to include a trigger, impact, and code evidence, and report coverage in the summary. — [@Nwflower](https://github.com/Nwflower)
- Automated PR reviews lead with the trigger and impact and omit code suggestions by default. — [@Nwflower](https://github.com/Nwflower)
## v0.2.12 — 2026-12-03
[中文](#cn-v0.2.12) | [English](#en-v0.2.12)
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["YinLiaoCo"],
"zh": "修复 macOS 剪贴板含有无法读取的格式时,无法粘贴从 Windows 复制的文件的问题。",
"en": "Fix pasting files copied from Windows when the macOS clipboard contains an unreadable format."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["YinLiaoCo", "staytomorrow", "yxc0915"],
"zh": "支持在 Windows 与 macOS 虚拟机之间复制粘贴文件和文件夹。Windows 中剪切的文件可粘贴到 macOS,原文件和剪切状态会保留。可在插件页或虚拟机设置中调整文件同步和传输上限。已有虚拟机需将 Guest Tools 更新至 `v16` 以使用双向文件同步。",
"en": "Copy and paste files and folders between Windows and macOS VMs. Pasting files cut in Windows into macOS preserves the original files and the Windows cut state. Adjust file sync and transfer limits in the plugin or VM settings. Update Guest Tools to `v16` in existing VMs for bidirectional file sync."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["bvzrays"],
"zh": "修复虚拟机交互期间的启停、挂起和截图输入竞争,清理桌面重启后遗留的 MCP 临时虚拟机,并确保 MCP 控制通道在长请求、输入结束和请求失败时正确传递响应。登录密码通过键盘输入,不再经过客体剪贴板。",
"en": "Fix races between VM lifecycle and console operations, clean up orphaned MCP temporary VMs after desktop restarts, and preserve MCP control-channel responses during long requests, input shutdown, and request failures. Login passwords are entered as keystrokes without passing through the guest clipboard."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["YinLiaoCo"],
"zh": "文件拖放通过 WebDAV 挂载导入文件,而 Guest Tools 后台以 `sh` 运行。修复全新 macOS 虚拟机首次拖放时未弹出 `sh`「网络宗卷」授权提示导致失败的问题;若权限被拒,拖放会立即提示「文件拖放受限」并在连接卡显示开启路径。开启权限后,拖入访达窗口或照片时会自动重挂仍无法获取文件引用的陈旧挂载;其他挂载故障及文件剪贴板仍保留下载兜底。已有虚拟机需将 Guest Tools 更新至 `v21`。",
"en": "File drops transfer files over a WebDAV mount read by the Guest Tools background agent (`sh`). macOS now prompts for `sh` Network Volumes access when needed during a drop. If access is denied, drops fail immediately with a File drop limited toast and a Connection card notice showing where to enable it. After access is granted, drops into Finder windows or Photos automatically remount stale WebDAV mounts whose file references are unavailable. Other mount failures and file clipboard sync keep download fallback. Update Guest Tools to `v21` in existing VMs."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["yxc0915"],
"zh": "Windows 文件复制到 macOS 时,挂载文件不可读会改用下载回退。诊断报告会记录客体确认写入文件剪贴板的次数。",
"en": "When Windows clipboard files cannot be read from the mounted share on macOS, Guest Tools uses the download fallback. Diagnostics count file clipboard writes confirmed by the guest."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["reiasu2", "Nwflower"],
"zh": "修复放入默认共享文件夹的文件在虚拟机中不显示或同步过慢的问题,移动便携目录后共享文件夹也会使用新位置。升级后需在虚拟机内重新安装 Guest Tools。",
"en": "Fix files added to the default shared folder not appearing or syncing slowly in the VM, and use the new location after moving a portable directory. Reinstall Guest Tools in the VM after upgrading."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["reiasu2", "Nwflower"],
"zh": "自动清理无法恢复的挂起残留,避免它们阻止再次挂起,并修复 Windows 上文件仍被短暂占用时挂起封存或清理失败的问题。挂起与恢复支持存放在长路径下的虚拟机。已保存可恢复快照的虚拟机在启动时会改为拒绝并提示先恢复或放弃挂起状态,旧版启动入口同样适用,不再直接冷启动覆盖快照。",
"en": "Clear orphaned suspend files that block later suspend attempts and avoid snapshot publication or cleanup failures when Windows files are briefly still in use. Suspend and resume also support VMs stored under long paths. A VM that holds a recoverable snapshot now refuses to start and asks you to resume or discard that state first, including through the older start path, instead of cold-starting over the snapshot."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["reiasu2", "Nwflower"],
"zh": "可在设置中开启快捷键,在虚拟机窗口内切换无边框全屏。默认关闭,默认组合键为 `Ctrl+Shift+F`,可自行录制。",
"en": "Add an optional shortcut in Settings to toggle borderless full screen from the VM window. It is off by default, uses `Ctrl+Shift+F`, and can be customized."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["icaruszezen", "Nwflower"],
"zh": "支持由插件接入非 macOS 虚拟机,可在客户端查看其状态,并通过 SSH、WSL、远程桌面、Hyper-V 连接或 ADB 打开。插件契约升级为 `pluginApi 1.2` 和 `uiApi 2.1`,并公开 `pkg/drivertest` 契约测试套件([#74](https://github.com/Nwflower/Reims-Go/issues/74))。",
"en": "Let plugins add non-macOS VMs, with their state shown in the app and access through SSH, WSL, Remote Desktop, VMConnect, or ADB. The plugin contracts move to `pluginApi 1.2` and `uiApi 2.1`, and the `pkg/drivertest` contract test suite is public ([#74](https://github.com/Nwflower/Reims-Go/issues/74))."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["ssdsl0126"],
"zh": "修复物理网卡绑定 Hyper-V 外部虚拟交换机后无法启用 Npcap 桥接的问题,自动使用关联管理虚拟网卡的地址转发宿客流量。",
"en": "Fix Npcap bridging when a physical adapter is bound to a Hyper-V external virtual switch by using its associated management adapter for host and guest traffic."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "chores",
"order": 0,
"authors": ["Nwflower"],
"zh": "新建 Issue 后自动提示补充信息、疑似重复和提交位置,并定期诊断代码、创建改进 Issue。",
"en": "Guide new issues with missing details, possible duplicates, and where to submit them, and regularly diagnose the code to open improvement issues."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["reiasu2"],
"zh": "修复文件同步或 WebDAV 挂载耗时较长时,虚拟机中的 Win → ⌘ 快捷键意外打开 Windows 开始菜单的问题。",
"en": "Fix Win → Command shortcuts opening the Windows Start menu during slow file sync or WebDAV mounting."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["yxc0915"],
"zh": "启用「macOS 应用窗口」内置插件后,可在 Windows 无边框窗口中操作虚拟机的前台应用,并在宿主与客体之间复制粘贴。",
"en": "Enable the built-in macOS App Windows plugin to use a VM’s foreground app in a borderless Windows window with bidirectional copy and paste."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "修复 MCP 创建临时 macOS 虚拟机时的名称校验错误,并开放已授权虚拟机的挂起和恢复操作。",
"en": "Fix name validation for temporary macOS VMs created by MCP and expose suspend and resume for authorized VMs."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "chores",
"order": 0,
"authors": ["Nwflower"],
"zh": "PR 自动审查改用 OpenCodeReview,支持隔离的只读仓库分析、跨提交增量审查和即时 CI 状态。",
"en": "Use OpenCodeReview for PR reviews with isolated read-only repository analysis, incremental commit ranges, and non-blocking CI status."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["cosimawei"],
"zh": "在插件列表和设置中提示当前运行时不支持的插件设置。",
"en": "Show which settings the active runtime does not support in the plugin list and settings dialog."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["bvzrays"],
"zh": "修复插件设置中的已保存密钥在清空后仍显示旧掩码,以及连续修改同一设置时保存顺序错乱的问题。",
"en": "Fix saved plugin secrets remaining masked after being cleared and preserve save order when the same setting is edited repeatedly."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["Nwflower"],
"zh": "沙箱页面插件新增四种视图位置、宿主表单与导航、虚拟机和设置访问、授权文件读写、任务进度、受控网络请求及事件订阅,并支持确认、复制、外链和私有存储。",
"en": "Add four view locations, host forms and navigation, VM and settings access, authorized file I/O, task progress, controlled HTTP requests, and event subscriptions to sandboxed plugins, alongside confirmations, clipboard copy, external links, and private storage."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "chores",
"order": 0,
"authors": ["Nwflower"],
"zh": "提高 PR 自动审查的 token 预算,部分任务出错时仍发布已完成的审查结果。",
"en": "Raise the token budget for automated PR reviews and publish completed results when some review tasks fail."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "chores",
"order": 0,
"authors": ["Nwflower"],
"zh": "自动审查要求说明缺陷触发条件、实际后果和代码证据,并在摘要中显示覆盖状态。",
"en": "Require automated review findings to include a trigger, impact, and code evidence, and report coverage in the summary."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "chores",
"order": 0,
"authors": ["Nwflower"],
"zh": "自动审查意见优先说明触发条件和实际后果,默认省略代码建议。",
"en": "Automated PR reviews lead with the trigger and impact and omit code suggestions by default."
}
+9
View File
@@ -0,0 +1,9 @@
{
"group": "improvements",
"order": 0,
"authors": [
"Nwflower"
],
"zh": "运行时改从 `reims-go/reims-vgpu` 下载。`REIMS_GO_RELEASES_REPO` 现在只影响应用更新,运行时仓库改用 `REIMS_GO_RUNTIME_RELEASES_REPO` 指定。",
"en": "Runtimes are now downloaded from `reims-go/reims-vgpu`. `REIMS_GO_RELEASES_REPO` now only affects app updates; set the runtime repository with `REIMS_GO_RUNTIME_RELEASES_REPO`."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "修复分段选项在保存期间短暂禁用后,当前选项的高亮可能消失的问题。",
"en": "Keep the highlight on the current option of a segmented control after it was briefly disabled while saving."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["Dnyo666"],
"zh": "「设置」页新增默认关闭的「Hyper-V 启动切换」选项,开启后可确认切换 Windows Hypervisor 下次启动状态以兼容独占模式的 VMware,并在「内核」页区分 Hypervisor 关闭与 BIOS 虚拟化未开启。 [#122](https://github.com/Nwflower/Reims-Go/issues/122)",
"en": "Add an opt-in Hyper-V boot switch in Settings to toggle Windows Hypervisor launch on next boot for exclusive-mode VMware coexistence, and distinguish hypervisor launch off from disabled BIOS virtualization on the Engine page. [#122](https://github.com/Nwflower/Reims-Go/issues/122)"
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["yxc0915"],
"zh": "支持在 Windows x86-64 上使用 Stambha 实验运行时启动 ARM macOS。导入配套运行时后,可从已有的启动介质和虚拟磁盘创建虚拟机。",
"en": "Run ARM macOS on Windows x86-64 with the Stambha preview runtime. Import the matching runtime to create a VM from existing boot media and a virtual disk."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "从命令行启动虚拟机失败时,一并显示 Guest Tools 和网络相关的日志。",
"en": "Include Guest Tools and network log lines when a VM fails to start from the command line."
}
+9
View File
@@ -0,0 +1,9 @@
{
"group": "removals",
"order": 0,
"authors": [
"Nwflower"
],
"zh": "主题清单不再支持从未生效的 `sounds` 字段。带交互脚本的主题可以自行播放提示音。",
"en": "Theme manifests no longer accept the `sounds` field, which never took effect. Themes with an interactive script can play their own sounds."
}
+9
View File
@@ -0,0 +1,9 @@
{
"group": "fixes",
"order": 0,
"authors": [
"Nwflower"
],
"zh": "修复只用名称指定虚拟机时读不到 SSH 端口等设置的问题。智能体工具此前会因此误报未启用 SSH 端口转发。",
"en": "Fixed missing settings such as the SSH port when a VM is identified by name only. Agent tools used to report that SSH port forwarding was off."
}
+28
View File
@@ -0,0 +1,28 @@
# 运行 ARM macOS 实验版
ARM 实验运行时通过 QEMU/WHPX 和 Stambha 在 Windows x86-64 上运行 ARM macOS。使用同一预览配套的 Reims-Go 客户端和 `stambha-hosted` 运行时包。运行时可以和现有 Intel macOS 运行时共存。
## 准备
- Windows x86-64 主机,启用 Windows 虚拟机监控程序平台(WHPX),安装支持 Vulkan 的显卡驱动。
- 一套你自己的 Stambha 启动介质和与之匹配的 ARM macOS 虚拟磁盘。启动目录至少包含 `EFI/stela/stela.cfg`,其中的磁盘分区标识须与虚拟磁盘一致。从目录启动时,客户端在 VM 的独立引导目录中放入运行时自带的 Stambha EFI。
- 为每台运行中的虚拟机准备独立可写副本或 QCOW2 写入层。来宾写入保存在该磁盘文件中。运行时包内提供启动程序、固件和显卡组件,系统文件由用户自行准备。
macOS 27.2.1 的实验配置使用 8 个 vCPU 和 16 GiB 内存。首次登录后,系统索引和缓存初始化会影响交互速度。
## 启动
在客户端的运行时页面导入 ARM 运行时包。新建虚拟机时选择「macOS ARM64(预览)」,填写启动目录和虚拟磁盘路径,创建后点击启动。GPU 加速窗口由运行时打开。
也可在 PowerShell 中操作。将示例路径替换成自己的文件位置。
```powershell
.\reims-go.exe runtime install .\reims-stambha-runtime-win-x64-stambha-arm64-preview.1.tar.zst
.\reims-go.exe vm create --driver builtin.driver.stambha --boot-volume .\arm-boot --disk .\arm-system.qcow2 --cpus 8 --memory 16G arm-macos
.\reims-go.exe vm start --driver builtin.driver.stambha arm-macos
.\reims-go.exe vm stop --driver builtin.driver.stambha arm-macos
```
如果配置使用原始安装介质,可以用 `--usb-image` 指定文件。原始介质须预先包含与托管 Reims vGPU 相容的 Stambha EFI。首次从 IPSW 制作 ARM 安装介质仍是独立流程。
日常关机请在 macOS 的苹果菜单中选择「关机」。客户端的停止操作会向来宾发送电源按键事件。若来宾没有退出,可回到桌面完成关机。只在来宾无响应时使用强制停止。
+2 -2
View File
@@ -75,9 +75,9 @@ OCR 输出中的 `critical`、`high`、`medium` 且非 style/documentation 问
发布前检查每条缺陷是否说明当前代码中的触发条件、可观察后果,以及已有保护为何无法阻止它。审核规则要求核对实际调用方、权限、掩码和事件过滤。影响本次合并且需要维护者明确约定的问题只在摘要展示。摘要分别显示审查覆盖、已报告缺陷和缺少必需字段的候选意见数。
自动代码审核与 CI 并行运行。Review 摘要只展示代码审查结果,CI 状态和合并条件由 GitHub 的检查列表与合并区展示。OCR 部分完成、存在失败任务、主线对照覆盖不全或 PR 文件列表截断时会标明覆盖限制。回复语言由 PR 正文去除代码块、引用和模板标题后的文字决定,含中文时使用中文,否则参考标题并使用英文。
审核启动后不再等待 CI。发布 Review 前只做一次即时查询,附上当前 PR 提交的 CI 记录和关键步骤。CI 排队、需要人工处理或缺少通过记录时,代码无实质问题的结论为「代码未见阻塞,等待 CI」。OCR 部分完成、存在失败任务、主线对照覆盖不全或 PR 文件列表截断时会标明覆盖限制。回复语言由 PR 正文去除代码块、引用和模板标题后的文字决定,含中文时使用中文,否则参考标题并使用英文。
工作流直接缓存并校验官方 Release 的单个静态二进制,不安装 Node 依赖或运行 `npm install`。全部外部 Action 固定到 commit SHA,workflow 顶层 `permissions` 为空。GitHub App 需要读取 Contents、写入 Pull requests,并仅安装到目标仓库。
工作流直接缓存并校验官方 Release 的单个静态二进制,不安装 Node 依赖或运行 `npm install`。全部外部 Action 固定到 commit SHA,workflow 顶层 `permissions` 为空。GitHub App 需要读取 Contents 和 Actions、写入 Pull requests,并仅安装到目标仓库。
在目标仓库的 **Settings → Secrets and variables → Actions** 配置以下项目。
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "reims-go-frontend",
"private": true,
"version": "0.2.13",
"version": "0.2.12",
"type": "module",
"scripts": {
"dev": "vite",
+1 -1
View File
@@ -1 +1 @@
5cadb9d7959628b248656a4d92bd9c1a
548bdba60bd8bd89e3828b675ad94fc2
-31
View File
@@ -1,31 +0,0 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { createLogLine } = await loadTestModule(`export * from './lib/logs'`)
const renderSelector = 'newRenderPipelineStateWithDescriptor:error:'
const computeSelector = 'newComputePipelineStateWithDescriptor:options:reflection:error:'
const precisionNote = (selector, code) =>
`[QEMU] reims-vgpu: ${selector}: metal2vulkan-runtime made it with a precision note (metal2vulkan-degrade-${code}): its answers there can differ from Metal's on this device; the first of its kind, each make that carries it counted`
test('successful render and compute precision notes keep their text as informational logs', () => {
for (const line of [
precisionNote(renderSelector, 'device-denormals'),
precisionNote(computeSelector, 'simdgroup-access-order'),
]) {
const row = createLogLine({ line })
assert.equal(row.level, 'info')
assert.equal(row.line, line)
}
})
test('pipeline refusals and fatal errors retain their error level', () => {
for (const line of [
`[QEMU] reims-vgpu: platform call ${renderSelector}: the runtime refused it`,
'[QEMU] reims-vgpu: fatal: Vulkan device was lost',
`${precisionNote(renderSelector, 'device-denormals')}; error: failed to submit the command buffer`,
]) {
assert.equal(createLogLine({ line }).level, 'error')
}
})
+11 -24
View File
@@ -14,9 +14,9 @@ import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Si
import { VMPage } from './components/VMPage'
import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
import { hasStambhaRuntime, isMacOSDriver, liveVMInfo, splitEndpoints, STAMBHA_DRIVER_ID, vmFeatures } from './lib/endpoints'
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
import { LogLine, appendLog, createLogLine } from './lib/logs'
import { LogLine, appendLog } from './lib/logs'
import { macOSMajor } from './macos/macosRelease'
import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState } from './lib/themeEngine'
@@ -200,11 +200,11 @@ export const App: React.FC = () => {
// Logs never pop the panel open (see docs/design-guidelines.md); errors only bump a badge.
const offLog = events.onLog((entry) => {
if (!entry || typeof entry !== 'object') return
const line = createLogLine(entry)
if (!logsOpenRef.current && line.level === 'error') {
const lineText = typeof entry.line === 'string' ? entry.line : String(entry.line ?? '')
if (!logsOpenRef.current && /\b(error|failed|fatal|panic)\b/i.test(lineText)) {
setUnseenErrors((n) => n + 1)
}
setLogLines((prev) => appendLog(prev, line))
setLogLines((prev) => appendLog(prev, entry))
})
// Tasks: seed from the backend, then follow events.
api.GetTasks().then((list) => {
@@ -451,17 +451,6 @@ 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.onRuntimeWarning((message) => {
const { summary, code, rawDetail } = parseAppError(message)
pushToast({
kind: 'warning',
title: summary,
errorCode: code,
rawDetail,
detailsLabel: t(locale, 'errRawDetailsToggle'),
copyDetailsLabel: t(locale, 'errCopyDetails'),
})
}), [locale, pushToast])
useEffect(() => events.onHostDrop(({ delivered, mode }) => {
if (mode !== 'l1_share' || delivered.length === 0) return
const title = delivered.length === 1
@@ -473,7 +462,8 @@ export const App: React.FC = () => {
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 stambhaAvailable = hasStambhaRuntime(state?.runtimes)
const hostReady = !!state && state.host.whpx === 'ready' && (!!state.active_runtime || stambhaAvailable)
const canSuspend = state?.can_suspend ?? false
const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled
? resolveFullscreenHotkey(state.config.fullscreen_hotkey)
@@ -545,14 +535,13 @@ export const App: React.FC = () => {
await api.InstallRuntimeArchive(file)
await refresh()
} catch (e) {
if (parseAppError(e).code === 'E_RUNTIME_ACTIVATION') await refresh()
fail(tr('failRuntime'), e)
}
}
const folderDone = async () => {
const s = await api.GetState().catch(() => null)
if (s) setState(s)
setSetupStage(s?.active_runtime ? null : 'runtime')
setSetupStage(s?.active_runtime || hasStambhaRuntime(s?.runtimes) ? null : 'runtime')
}
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
// The data folder opened read-only (internal/dataroot): nothing in it may be
@@ -665,10 +654,8 @@ export const App: React.FC = () => {
const loadQemu = (name?: string) => loadVMLog(false, name)
const fail = (title: string, e: unknown) => {
const toast = errorToast(locale, title, e)
toasts.push({
...toast,
title: toast.errorCode === 'E_RUNTIME_ACTIVATION' ? tr('runtimeActivationFailed') : title,
...errorToast(locale, title, e),
action: { label: tr('viewLogs'), onClick: () => openLogs('app') },
})
}
@@ -889,7 +876,7 @@ export const App: React.FC = () => {
}
const openWizard = () => {
if (!state?.active_runtime) {
if (!state?.active_runtime && !stambhaAvailable) {
setSelected(HOST_ID)
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
return
@@ -1349,7 +1336,6 @@ export const App: React.FC = () => {
runtimeTask={runtimeTask}
onChannel={setChannel}
onInstallRuntime={installRuntime}
onImportRuntime={importRuntime}
onCancelTask={cancelTask}
/>
)}
@@ -1391,6 +1377,7 @@ export const App: React.FC = () => {
locale={locale}
host={state.host}
fixedModeSupported={fixedModeSupported}
initialDriverID={!state.active_runtime && stambhaAvailable ? STAMBHA_DRIVER_ID : undefined}
tasks={Object.values(taskMap)}
draft={wizardDraft}
onClose={() => { setShowWizard(false); setWizardDraft(null) }}
+18 -20
View File
@@ -1,6 +1,7 @@
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 { STAMBHA_DRIVER_ID } from '../lib/endpoints'
import { NpcapDependency } from './NpcapDependency'
import { NetworkErrorNotice } from './NetworkErrorNotice'
import type { ParsedAppError } from '../i18n'
@@ -53,6 +54,7 @@ interface Props {
locale: Locale
host: HostReport
fixedModeSupported?: boolean
initialDriverID?: string
tasks?: Task[]
draft?: WizardDraft | null
onClose: () => void
@@ -80,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, fixedModeSupported = false, tasks = [], draft, onClose, onSubmit }) => {
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, initialDriverID = BUILTIN_MACOS_DRIVER, 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.
@@ -90,12 +92,11 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const [issues, setIssues] = useState<ValidationIssue[]>([])
const [cmdPreview, setCmdPreview] = useState('')
const [drivers, setDrivers] = useState<DriverSummary[]>([])
const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER)
const [driverID, setDriverID] = useState(initialDriverID)
const [driverOpts, setDriverOpts] = useState<Record<string, unknown>>({})
const [driverCreating, setDriverCreating] = useState(false)
const [dependencyBusy, setDependencyBusy] = useState(false)
const [dependencyRefresh, setDependencyRefresh] = useState(0)
const [validationRefresh, setValidationRefresh] = useState(0)
useEffect(() => {
let live = true
@@ -106,7 +107,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
name: 'macos-tahoe',
name: initialDriverID === STAMBHA_DRIVER_ID ? 'macos-arm64' : 'macos-tahoe',
dir: '',
// 离线安装默认关闭网络,减少恢复环境依赖;用户仍可在第 4 步改为 NAT 或桥接。
source_mode: 'offline',
@@ -205,13 +206,6 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
? Math.ceil((chosenRelease.size * 1.1) / 1e9)
: 0
useEffect(() => {
if (!reviewed || issues.length === 0) return
const onFocus = () => setValidationRefresh((n) => n + 1)
window.addEventListener('focus', onFocus)
return () => window.removeEventListener('focus', onFocus)
}, [reviewed, issues.length])
useEffect(() => {
if (!reviewed && step !== REVIEW_STEP) return
let live = true
@@ -229,7 +223,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
.finally(() => { if (live) setChecking(false) })
}, 200)
return () => { live = false; clearTimeout(timer) }
}, [step, reviewed, opts, validationRefresh])
}, [step, reviewed, opts])
const pickDir = async () => {
const dir = await api.PickDirectory(tr('vmDir'))
@@ -261,7 +255,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
return (
<Modal className="wizard-dialog" title={tr('wizardTitle')} closeLabel={tr('close')} onClose={onClose}>
<nav className="wizard-steps" aria-label={tr('wizardTitle')}>
{driverID !== STAMBHA_DRIVER_ID && <nav className="wizard-steps" aria-label={tr('wizardTitle')}>
{steps.map((key, idx) => {
const n = idx + 1
const bad = issueSteps.has(n) && n !== REVIEW_STEP
@@ -279,7 +273,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
</button>
)
})}
</nav>
</nav>}
<div className="dialog-body">
{err && <div className="notice notice-error">{err}</div>}
@@ -295,11 +289,11 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
<PopupSelect
label={tr('wizardDriverType')}
value={driverID}
options={drivers.map((d) => ({
options={drivers.filter((d) => initialDriverID !== STAMBHA_DRIVER_ID || d.id !== BUILTIN_MACOS_DRIVER).map((d) => ({
value: d.id,
label: locText(d.name, locale, d.id),
}))}
onChange={(id) => { setDriverID(id); setErr('') }}
onChange={(id) => { setDriverID(id); setDriverOpts({}); setErr('') }}
/>
}
/>
@@ -320,6 +314,12 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
schema={activeDriver.create_schema}
values={driverOpts}
onChange={setDriverOpts}
pathFields={driverID === STAMBHA_DRIVER_ID ? {
boot_volume: true,
raw_disk: '*.qcow2;*.raw;*.img',
usb_image: '*.raw;*.img;*.bin',
} : undefined}
onPickError={(e) => setErr(parseAppError(e).summary)}
/>
</Suspense>
)}
@@ -730,7 +730,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
await api.CreateVMWithDriver({
driver_id: driverID,
name: opts.name.trim(),
dir: opts.dir,
dir: driverID === STAMBHA_DRIVER_ID ? '' : opts.dir,
options: driverOpts,
})
onClose()
@@ -843,8 +843,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
]
const nameIssue = issues.find((i) => i.field === 'name')?.message
const dirIssue = issues.find((i) => i.field === 'dir')?.message
const general = issues.filter((i) => stepOfIssue(i) === REVIEW_STEP && i.field !== 'name' && i.field !== 'dir')
const general = issues.filter((i) => stepOfIssue(i) === REVIEW_STEP && i.field !== 'name')
const copy = async () => {
try {
@@ -868,7 +867,6 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
<SetRow
title={tr('vmDir')}
desc={opts.dir ? <span className="mono path-text" title={opts.dir}>{opts.dir}</span> : tr('summaryDefaultDir')}
error={dirIssue}
control={
<div className="hstack">
{opts.dir && <Button variant="ghost" onClick={() => onDir('')}>{tr('useDefault')}</Button>}
+47 -58
View File
@@ -5,30 +5,28 @@ import '../i18n/domains/wizard.gen'
import { I18nKey, t } from '../i18n'
import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format'
import { describeHostWHPX } from '../lib/hypervisor'
import { hasStambhaRuntime, STAMBHA_RUNTIME_KIND } from '../lib/endpoints'
import { AppState, Locale, StorageBreakdown, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Switch } from '../ui/settings'
import { api } from '../wails'
import { RuntimeOnline } from './RuntimeOnline'
interface Props {
state: AppState
locale: Locale
onRefresh: () => Promise<void>
onRefresh: () => void
onNewVM?: () => void
onError: (title: string, e: unknown) => void
onToast?: (title: string) => void
runtimeTask: Task | null
onChannel: (alpha: boolean) => void
onInstallRuntime: (commit: string) => void
onImportRuntime: () => Promise<void>
onCancelTask: (id: string) => void
}
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, onError, onToast, runtimeTask, onChannel, onInstallRuntime, onImportRuntime, onCancelTask }) => {
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, onError, onToast, runtimeTask, onChannel, onInstallRuntime, onCancelTask }) => {
const [importing, setImporting] = useState(false)
const [enabling, setEnabling] = useState(false)
const [savingASLR, setSavingASLR] = useState(false)
const [confirmDelete, setConfirmDelete] = useState('')
const [removing, setRemoving] = useState('')
const [storage, setStorage] = useState<StorageBreakdown | null>(null)
@@ -46,7 +44,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
const guard = (fn: () => Promise<unknown>) => async () => {
try {
await fn()
await onRefresh()
onRefresh()
} catch (e) {
onError(tr('failGeneric'), e)
}
@@ -66,19 +64,13 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
}
}
const setQEMUASLR = async (enabled: boolean) => {
setSavingASLR(true)
await guard(() => api.SetQEMUASLR(enabled))()
setSavingASLR(false)
}
const importRuntime = async () => {
setImporting(true)
try {
await onImportRuntime()
} finally {
setImporting(false)
}
await guard(async () => {
const file = await api.PickFile(tr('importRuntime'), '*.tar.zst;*.zip')
if (file) await api.InstallRuntimeArchive(file)
})()
setImporting(false)
}
const removeRuntime = async (commit: string) => {
@@ -109,7 +101,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
</div>
</header>
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && !!state.active_runtime && onNewVM && (
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && (!!state.active_runtime || hasStambhaRuntime(runtimes)) && onNewVM && (
<section className="welcome-card">
<h1>{tr('welcomeTitle')}</h1>
<p>{tr('welcomeSub')}</p>
@@ -216,47 +208,44 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
onInstall={onInstallRuntime}
onCancel={onCancelTask}
/>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('qemuASLR')}</div>
<div className="row-sub">{tr('qemuASLRHint')}</div>
</div>
<div className="row-right">
<Switch label={tr('qemuASLR')} checked={!!config.qemu_aslr} disabled={savingASLR} onChange={setQEMUASLR} />
</div>
</div>
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
<div className="row" key={rt.commit}>
<div className="row-main">
<div className="row-title"><span className="mono">{rt.commit}</span></div>
<div className="row-sub">{rt.manifest.qemu_version.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => {
const stambha = rt.kind === STAMBHA_RUNTIME_KIND
const ref = stambha ? STAMBHA_RUNTIME_KIND + '/' + rt.commit : rt.commit
return (
<div className="row" key={ref}>
<div className="row-main">
<div className="row-title"><span className="mono">{stambha ? rt.manifest.name || rt.commit : rt.commit}</span></div>
<div className="row-sub">{rt.manifest.qemu_version?.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
</div>
<div className="row-right">
{confirmDelete === ref ? (
<>
<Button variant="ghost" disabled={removing === ref} onClick={() => setConfirmDelete('')}>
{tr('cancel')}
</Button>
<Button variant="danger" busy={removing === ref} onClick={() => removeRuntime(ref)}>
{tr('runtimeDeleteConfirm')}
</Button>
</>
) : (
<>
{!stambha && (
<Button disabled={removing === ref} onClick={guard(() => api.UseRuntime(rt.commit))}>
{tr('activate')}
</Button>
)}
<IconButton
label={tr('runtimeDelete')}
icon={<Trash size={15} />}
disabled={removing !== ''}
onClick={() => setConfirmDelete(ref)}
/>
</>
)}
</div>
</div>
<div className="row-right">
{confirmDelete === rt.commit ? (
<>
<Button variant="ghost" disabled={removing === rt.commit} onClick={() => setConfirmDelete('')}>
{tr('cancel')}
</Button>
<Button variant="danger" busy={removing === rt.commit} onClick={() => removeRuntime(rt.commit)}>
{tr('runtimeDeleteConfirm')}
</Button>
</>
) : (
<>
<Button disabled={removing === rt.commit} onClick={guard(() => api.UseRuntime(rt.commit))}>
{tr('activate')}
</Button>
<IconButton
label={tr('runtimeDelete')}
icon={<Trash size={15} />}
disabled={removing !== ''}
onClick={() => setConfirmDelete(rt.commit)}
/>
</>
)}
</div>
</div>
))}
)
})}
</div>
</section>
+28 -1
View File
@@ -4,6 +4,8 @@ import '../i18n/domains/settings.gen'
import { locText, t } from '../i18n'
import { Locale, SettingProperty, SettingsSchema } from '../types'
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
import { Button } from '../ui/controls'
import { api } from '../wails'
interface Props {
locale: Locale
@@ -13,6 +15,8 @@ interface Props {
groupFilter?: string
onChange: (next: Record<string, unknown>, patch: Record<string, unknown>) => void
hideGroupHeader?: boolean
pathFields?: Readonly<Record<string, string | true>>
onPickError?: (error: unknown) => void
}
const SECRET_MASK = '••••••••'
@@ -20,7 +24,7 @@ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
/** Lazy-loaded JSON Schema form renderer supporting x-secret, x-effect, and x-scope. */
export const SchemaForm: React.FC<Props> = ({
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader,
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader, pathFields, onPickError,
}) => {
const propsMap = schema.properties ?? {}
const keys = (schema['x-order'] && schema['x-order'].length > 0
@@ -134,6 +138,29 @@ export const SchemaForm: React.FC<Props> = ({
)
}
const pathField = pathFields?.[k]
if (pathField !== undefined) {
return (
<div className="input-group">
<input
type="text"
className="input rg-p-input"
aria-label={label}
value={String(cur ?? '')}
onChange={(e) => setKey(k, e.target.value)}
/>
<Button onClick={async () => {
try {
const path = pathField === true ? await api.PickDirectory(label) : await api.PickFile(label, pathField)
if (path) setKey(k, path)
} catch (error) {
onPickError?.(error)
}
}}>{t(locale, 'choose')}</Button>
</div>
)
}
return (
<input
type="text"
+2 -23
View File
@@ -8,6 +8,7 @@ import { Button } from '../ui/controls'
import { PopupSelect } from '../ui/settings'
import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format'
import { describeHostWHPX } from '../lib/hypervisor'
import { hasStambhaRuntime } from '../lib/endpoints'
import { api } from '../wails'
import { PluginAppIcon } from './PluginAppIcon'
import { RuntimeOnline } from './RuntimeOnline'
@@ -200,21 +201,9 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
}
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFolderDone, onFinish, onError }) => {
const ready = !!state.active_runtime
const ready = !!state.active_runtime || hasStambhaRuntime(state.runtimes)
const { host } = state
const [enabling, setEnabling] = useState(false)
const [activating, setActivating] = useState('')
const activate = async (commit: string) => {
setActivating(commit)
try {
await api.UseRuntime(commit)
onFolderDone()
} catch (e) {
onError(tr('runtimeActivationFailed'), e)
} finally {
setActivating('')
}
}
const enableWHPX = async () => {
setEnabling(true)
try {
@@ -306,16 +295,6 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
onInstall={onInstallRuntime}
onCancel={onCancelTask}
/>
{(state.runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
<div className="row" key={rt.commit}>
<div className="row-main"><div className="row-title mono">{rt.commit}</div></div>
<div className="row-right">
<Button busy={activating === rt.commit} disabled={!!activating} onClick={() => activate(rt.commit)}>
{tr('activate')}
</Button>
</div>
</div>
))}
</div>
<div className="setup-foot">
<Button variant="ghost" onClick={onImportRuntime}>{tr('setupImport')}</Button>
-2
View File
@@ -142,7 +142,6 @@ export const coreZh: Record<string, string> = {
"resizeLogPanel": "拖动调整日志高度",
"resolution": "分辨率",
"restart": "重启",
"runtimeActivationFailed": "运行时激活失败",
"safeModeBanner": "安全模式已启用:已跳过全部第三方插件并回退至内置默认主题",
"safeModeManagePlugins": "管理插件",
"save": "保存",
@@ -354,7 +353,6 @@ export const coreEn: Record<string, string> = {
"resizeLogPanel": "Drag to resize log panel",
"resolution": "Resolution",
"restart": "Restart",
"runtimeActivationFailed": "Runtime activation failed",
"safeModeBanner": "Safe mode is active: all third-party plugins are disabled and the built-in theme is restored",
"safeModeManagePlugins": "Manage plugins",
"save": "Save",
@@ -443,8 +443,6 @@ export const settingsZh: Record<string, string> = {
"optUnavailable": "不可用",
"pendingChanges": "{n, plural, other {# 项更改,下次启动生效}}",
"platformReadonly": "机型、序列号等平台身份信息不在界面显示",
"qemuASLR": "自动为 QEMU 启用 ASLR",
"qemuASLRHint": "设置随运行时版本切换,虚拟机关机后再启动时生效,可能解决 macOS Dock 图标空白的问题",
"recommendedBadge": "推荐",
"resCustom": "自定义",
"resCustomSub": "宽 × 高",
@@ -987,8 +985,6 @@ export const settingsEn: Record<string, string> = {
"optUnavailable": "Unavailable",
"pendingChanges": "{n, plural, one {# change · applies on next start} other {# changes · applies on next start}}",
"platformReadonly": "Model, serial number and other platform identity are never shown",
"qemuASLR": "Automatically enable ASLR for QEMU",
"qemuASLRHint": "Applies to the selected runtime and may restore blank macOS Dock icons after you shut down and start the VM again",
"recommendedBadge": "Recommended",
"resCustom": "Custom",
"resCustomSub": "Width × height",
-3
View File
@@ -862,8 +862,6 @@ export type I18nKey =
| "pluginTrustOfficial"
| "pluginTrustVerified"
| "pluginViewLog"
| "qemuASLR"
| "qemuASLRHint"
| "quitFailed"
| "quitInProgress"
| "recommendedBadge"
@@ -882,7 +880,6 @@ export type I18nKey =
| "restartToApply"
| "resume"
| "resumeUnavailable"
| "runtimeActivationFailed"
| "runtimeAlpha"
| "runtimeAlphaHint"
| "runtimeChannel_alpha"
+7 -1
View File
@@ -1,9 +1,15 @@
import type { VMEndpoint, VMInfo, VMListItem } from '../types'
import type { InstalledRuntime, VMEndpoint, VMInfo, VMListItem } from '../types'
// Guest family, driver capabilities and endpoint ordering for non-macOS guests.
// Everything here is pure so node:test can load it (scripts/test-endpoints.mjs).
const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
export const STAMBHA_DRIVER_ID = 'builtin.driver.stambha'
export const STAMBHA_RUNTIME_KIND = 'stambha-hosted'
export function hasStambhaRuntime(runtimes?: InstalledRuntime[] | null): boolean {
return runtimes?.some((rt) => rt.kind === STAMBHA_RUNTIME_KIND && rt.manifest.runtime_api === '0.1.0') ?? false
}
export type GuestFamily = 'macos' | 'linux' | 'windows' | 'android' | ''
+4 -7
View File
@@ -14,21 +14,18 @@ const MAX_LOG_LINES = 2000
// backend tags them explicitly.
const ERROR_RE = /\b(error|failed|fatal|panic)\b/i
const WARN_RE = /\bwarn(ing)?\b/i
// Successful vGPU precision notes include the Metal selector's error: argument.
const PRECISION_NOTE_PREFIX = /^(?:\[QEMU\] )?reims-vgpu: [\w:]+: metal2vulkan-runtime made it with a precision note \(metal2vulkan-degrade-[a-z0-9-]+\): /
let nextId = 1
export function createLogLine(entry: LogEntry): LogLine {
function classify(entry: LogEntry): LogLine {
const ts = typeof entry?.ts === 'string' ? entry.ts : ''
const source = typeof entry?.source === 'string' ? entry.source : ''
const line = typeof entry?.line === 'string' ? entry.line : String(entry?.line ?? '')
const message = line.replace(PRECISION_NOTE_PREFIX, '')
const level: LogLevel = ERROR_RE.test(message) ? 'error' : WARN_RE.test(message) ? 'warn' : 'info'
const level: LogLevel = ERROR_RE.test(line) ? 'error' : WARN_RE.test(line) ? 'warn' : 'info'
return { ts, source, line, id: nextId++, level }
}
export function appendLog(prev: LogLine[], line: LogLine): LogLine[] {
const next = [...prev, line]
export function appendLog(prev: LogLine[], entry: LogEntry): LogLine[] {
const next = [...prev, classify(entry)]
return next.length > MAX_LOG_LINES ? next.slice(next.length - MAX_LOG_LINES) : next
}
+1 -2
View File
@@ -999,7 +999,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
.toast-main-row:has(.toast-desc) { align-items: flex-start; }
.toast-main-row:has(.toast-desc) > svg { margin-top: 2px; }
.toast.ok .toast-main-row > svg { color: var(--status-running); }
.toast.warning .toast-main-row > svg { color: var(--status-busy); }
.toast.error .toast-main-row > svg { color: var(--status-error); }
.toast-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.toast-title-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
@@ -1161,7 +1160,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
.srow-fieldset { border: 0; padding: 0; margin: 0; min-width: 0; transition: opacity var(--dur-fast) var(--ease-out); }
.srow-fieldset:disabled { opacity: 0.42; }
.srow[data-disabled] .srow-title { color: var(--text-2); }
.srow-error { display: flex; align-items: flex-start; gap: 6px; font-size: var(--fs-12); color: var(--danger-text); overflow-wrap: anywhere; }
.srow-error { display: flex; align-items: flex-start; gap: 6px; font-size: var(--fs-12); color: var(--danger-text); }
.srow-error svg { flex-shrink: 0; margin-top: 2px; }
.srow-kv .srow-value { min-width: 0; text-align: right; font-size: var(--fs-13); color: var(--text-2); overflow-wrap: anywhere; user-select: text; font-variant-numeric: tabular-nums; }
.dirty-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); flex-shrink: 0; }
+3 -5
View File
@@ -1,5 +1,5 @@
import * as RToast from '@radix-ui/react-toast'
import { AlertTriangle, Check, CircleCheck, CircleX, X } from 'lucide-react'
import { Check, CircleCheck, CircleX, X } from 'lucide-react'
import { HostIcon } from './themeVisuals'
import { emitThemeEvent } from '../lib/themeEngine'
import React, { useCallback, useState } from 'react'
@@ -8,7 +8,7 @@ import type { Locale } from '../types'
import { IconButton } from './controls'
export interface ToastInput {
kind: 'ok' | 'warning' | 'error'
kind: 'ok' | 'error'
title: string
description?: string
errorCode?: string
@@ -79,7 +79,7 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
<RToast.Root
className={`toast rg-p-toast ${item.kind}${item.rawDetail || item.action ? ' has-extra' : ''}`}
data-tone={item.kind}
duration={expanded ? 600_000 : item.kind !== 'ok' ? 10_000 : item.action ? 8000 : 3000}
duration={expanded ? 600_000 : item.kind === 'error' ? 10_000 : item.action ? 8000 : 3000}
onOpenChange={(open) => {
if (!open) onRemove(item.id)
}}
@@ -87,8 +87,6 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
<div className="toast-main-row">
{item.kind === 'ok' ? (
<CircleCheck size={16} aria-hidden="true" />
) : item.kind === 'warning' ? (
<HostIcon name="warning"><AlertTriangle size={16} aria-hidden="true" /></HostIcon>
) : (
<HostIcon name="error"><CircleX size={16} aria-hidden="true" /></HostIcon>
)}
-1
View File
@@ -200,7 +200,6 @@ export const events = {
onTask: (cb: (task: Task) => void) => eventsOn('reims:task', cb),
onStateChanged: (cb: () => void) => eventsOn('reims:state-changed', cb),
onLog: (cb: (entry: LogEntry) => void) => eventsOn('reims:log', cb),
onRuntimeWarning: (cb: (message: string) => void) => eventsOn('reims:runtime-warning', cb),
// Market install progress (internal/app/plugins_flow.go InstallMarketPlugin).
onPluginInstall: (cb: (p: MarketInstallProgress) => void) => eventsOn('reims:plugin-install', cb),
// Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…".
-2
View File
@@ -268,8 +268,6 @@ export function SetMinimizeToTray(arg1:boolean):Promise<void>;
export function SetPluginSettings(arg1:string,arg2:string,arg3:Record<string, any>):Promise<void>;
export function SetQEMUASLR(arg1:boolean):Promise<void>;
export function SetRuntimeChannel(arg1:string):Promise<void>;
export function SetSyncHostMemorySMBIOS(arg1:boolean):Promise<void>;
-4
View File
@@ -514,10 +514,6 @@ export function SetPluginSettings(arg1, arg2, arg3) {
return window['go']['app']['App']['SetPluginSettings'](arg1, arg2, arg3);
}
export function SetQEMUASLR(arg1) {
return window['go']['app']['App']['SetQEMUASLR'](arg1);
}
export function SetRuntimeChannel(arg1) {
return window['go']['app']['App']['SetRuntimeChannel'](arg1);
}
-2
View File
@@ -809,7 +809,6 @@ export namespace config {
auto_pin_pcores: boolean;
default_gpu?: string;
runtime_channel?: string;
qemu_aslr?: boolean;
app_update_channel?: string;
minimize_to_tray?: boolean;
sync_host_memory_smbios?: boolean;
@@ -831,7 +830,6 @@ export namespace config {
this.auto_pin_pcores = source["auto_pin_pcores"];
this.default_gpu = source["default_gpu"];
this.runtime_channel = source["runtime_channel"];
this.qemu_aslr = source["qemu_aslr"];
this.app_update_channel = source["app_update_channel"];
this.minimize_to_tray = source["minimize_to_tray"];
this.sync_host_memory_smbios = source["sync_host_memory_smbios"];
+79 -156
View File
@@ -100,8 +100,6 @@ type App struct {
vmNetworkLocksMu sync.Mutex
ctx context.Context
mu sync.Mutex
configMu sync.Mutex // serializes config writes and data root changes
selectionMu sync.Mutex // keeps a GUI selection in its data root across UAC
cfg *config.Config
transitions map[string]string
pendingChanges map[string][]PendingChange
@@ -367,8 +365,8 @@ func (a *App) emitLog(source, line string) {
func (a *App) GetState() AppState {
a.noteUIAlive()
cfgCopy := a.runtimeConfig()
a.mu.Lock()
cfgCopy := *a.cfg
trCopy := make(map[string]string, len(a.transitions))
for k, v := range a.transitions {
trCopy[k] = v
@@ -449,10 +447,9 @@ func (a *App) GetState() AppState {
}
func (a *App) SetLocale(raw string) error {
if err := a.setPreference(func(cfg *config.Config) { cfg.Locale = i18n.ParsePreference(raw) }); err != nil {
return err
}
a.mu.Lock()
a.cfg.Locale = i18n.ParsePreference(raw)
err := a.saveConfigLocked()
eff := i18n.EffectiveLocale(a.cfg.Locale)
mgr := a.pluginMgr
a.mu.Unlock()
@@ -460,19 +457,30 @@ func (a *App) SetLocale(raw string) error {
mgr.NotifyLocaleChanged(eff)
}
a.emitStateChanged()
return nil
return err
}
func (a *App) SetAutoPinPCores(enabled bool) error {
return a.setPreference(func(cfg *config.Config) { cfg.AutoPinPCores = enabled })
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.AutoPinPCores = enabled
return a.saveConfigLocked()
}
func (a *App) SetMinimizeToTray(enabled bool) error {
return a.setPreference(func(cfg *config.Config) { cfg.MinimizeToTray = &enabled })
a.mu.Lock()
v := enabled
a.cfg.MinimizeToTray = &v
err := a.saveConfigLocked()
a.mu.Unlock()
return err
}
func (a *App) SetSyncHostMemorySMBIOS(enabled bool) error {
return a.setPreference(func(cfg *config.Config) { cfg.SyncHostMemorySMBIOS = enabled })
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.SyncHostMemorySMBIOS = enabled
return a.saveConfigLocked()
}
// showMainWindow restores and focuses the Wails window from the system tray.
@@ -506,9 +514,9 @@ func (a *App) startTray() {
OnVMAction: a.trayVMAction,
OnQuit: a.QuitApp,
GetSnapshot: func() tray.Snapshot {
cfgCopy := a.runtimeConfig()
a.mu.Lock()
loc := cfgCopy.Locale
cfgCopy := *a.cfg
loc := a.cfg.Locale
cached := append([]driver.VMListItem(nil), a.lastVMs...)
transitions := make(map[string]string, len(a.transitions))
for k, v := range a.transitions {
@@ -623,40 +631,38 @@ func (a *App) resetDataRootCaches() {
}
func (a *App) SetDataRoot(dir string) error {
return a.setDataRoot(dir, host.SyncQEMUASLR)
}
func (a *App) checkDataRootSwitch(loc i18n.Locale) error {
a.mu.Lock()
defer a.mu.Unlock()
loc := i18n.EffectiveLocale(a.cfg.Locale)
prev := a.cfg.DataRoot
curLocalePref := a.cfg.Locale
curAutoPin := a.cfg.AutoPinPCores
curRuntimeChannel := a.cfg.RuntimeChannel
curAppUpdateChannel := a.cfg.AppUpdateChannel
curMinToTray := a.cfg.MinimizeToTray
curSyncHostMemSMBIOS := a.cfg.SyncHostMemorySMBIOS
curEnableHvSwitch := a.cfg.EnableHypervisorSwitch
curHostDNS := a.hostDNSConfigLocked()
curFullscreenHotkeyEnabled := a.cfg.FullscreenHotkeyEnabled
curFullscreenHotkey := a.cfg.FullscreenHotkey
for _, v := range a.lastVMs {
if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
}
}
for _, tr := range a.transitions {
if tr != "" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
}
}
a.mu.Unlock()
// Plugin tasks do not block the switch; resetDataRootCaches cancels them.
if hostTaskRunning() {
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_TASKS", "err.dataroot.busy_tasks", nil, nil)
}
return nil
}
func (a *App) setDataRoot(dir string, syncPolicy func(context.Context, string, string) error) (err error) {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
a.mu.Lock()
prev := *a.cfg
wasReadOnly, setup := a.root.ReadOnly, a.needsSetup
a.mu.Unlock()
loc := i18n.EffectiveLocale(prev.Locale)
if err := a.checkDataRootSwitch(loc); err != nil {
return err
}
dir = strings.TrimSpace(dir)
if dir != "" {
dir = filepath.Clean(dir)
@@ -669,95 +675,41 @@ func (a *App) setDataRoot(dir string, syncPolicy func(context.Context, string, s
return dataroot.Error(loc, st)
}
target := config.Config{DataRoot: dir}
if err := target.EnsureDirs(); err != nil {
cfgPath := filepath.Join(dir, "reims-go.json")
nextCfg, err := config.Load(cfgPath)
if err != nil {
return fmt.Errorf("read %s: %w", cfgPath, err)
}
nextCfg.DataRoot = dir
if _, statErr := os.Stat(cfgPath); statErr != nil {
nextCfg.Locale = curLocalePref
nextCfg.AutoPinPCores = curAutoPin
nextCfg.RuntimeChannel = curRuntimeChannel
nextCfg.AppUpdateChannel = curAppUpdateChannel
nextCfg.MinimizeToTray = curMinToTray
nextCfg.SyncHostMemorySMBIOS = curSyncHostMemSMBIOS
nextCfg.EnableHypervisorSwitch = curEnableHvSwitch
nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = curHostDNS.Mode, curHostDNS.DoHURL
nextCfg.FullscreenHotkeyEnabled = curFullscreenHotkeyEnabled
nextCfg.FullscreenHotkey = curFullscreenHotkey
}
if err := nextCfg.EnsureDirs(); err != nil {
return err
}
if err := writable(dir); err != nil {
return err
}
st := dataroot.Open(dir, version.Version)
if st.ReadOnly {
return dataroot.Error(loc, st)
}
ctx := a.baseCtx()
changed := !sameDataFolder(prev.DataRoot, dir)
source := ""
if changed && !setup && !wasReadOnly {
if _, err := os.Stat(prev.DataRoot); err == nil {
source = prev.RuntimesDir()
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
}
release, err := lockDataRootSelections(ctx, source, target.RuntimesDir())
if err != nil {
return err
}
defer release()
if changed && !setup && !wasReadOnly {
if err := rt.RefreshSelection(&prev); err != nil {
// A damaged source config must still allow switching to a healthy folder.
a.emitLog("runtime", "Read previous runtime selection: "+err.Error())
}
}
cfgPath := filepath.Join(dir, "reims-go.json")
nextCfg, err := config.LoadExisting(cfgPath)
fresh := errors.Is(err, os.ErrNotExist)
if fresh {
nextCfg = config.Default()
nextCfg.Locale = prev.Locale
nextCfg.QEMUASLR = prev.QEMUASLR
} else if err != nil {
return fmt.Errorf("read %s: %w", cfgPath, err)
}
nextCfg.DataRoot = dir
if changed && !setup {
restore, policyErr := a.moveDataRootASLR(ctx, &prev, nextCfg, fresh, syncPolicy)
if policyErr != nil {
return policyErr
}
defer func() {
if err != nil {
err = errors.Join(err, restore())
}
}()
}
a.configMu.Lock()
defer a.configMu.Unlock()
if err := a.checkDataRootSwitch(loc); err != nil {
return err
}
if fresh {
// Keep preference edits made while Windows was asking for consent.
a.mu.Lock()
cur := *a.cfg
a.mu.Unlock()
nextCfg.Locale = cur.Locale
nextCfg.AutoPinPCores = cur.AutoPinPCores
nextCfg.RuntimeChannel = cur.RuntimeChannel
nextCfg.AppUpdateChannel = cur.AppUpdateChannel
nextCfg.MinimizeToTray = cur.MinimizeToTray
nextCfg.SyncHostMemorySMBIOS = cur.SyncHostMemorySMBIOS
nextCfg.EnableHypervisorSwitch = cur.EnableHypervisorSwitch
nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = cur.HostDNSMode, cur.HostDNSDoHURL
nextCfg.FullscreenHotkeyEnabled = cur.FullscreenHotkeyEnabled
nextCfg.FullscreenHotkey = cur.FullscreenHotkey
} else {
// Preserve independent preference saves in the destination during UAC.
nextCfg, err = config.LoadExisting(cfgPath)
if err != nil {
return err
}
nextCfg.DataRoot = dir
}
if err := rt.SavePreferences(nextCfg); err != nil {
if err := config.Save(cfgPath, nextCfg); err != nil {
return err
}
if err := config.SaveLocation(dir); err != nil {
return err
}
// A folder created just now gets its version stamp here.
st := dataroot.Open(dir, version.Version)
a.mu.Lock()
wasReadOnly := a.root.ReadOnly
a.cfg = nextCfg
if a.guestTools != nil {
a.guestTools.SetHostDNSConfig(a.hostDNSConfigLocked())
@@ -769,7 +721,7 @@ func (a *App) setDataRoot(dir string, syncPolicy func(context.Context, string, s
// Leaving a read-only folder starts the plugins and polling it held back,
// even when the user picked the same folder again after fixing it.
rootChanged := changed || wasReadOnly
rootChanged := filepath.Clean(prev) != filepath.Clean(dir) || wasReadOnly
if rootChanged {
a.resetDataRootCaches()
}
@@ -811,14 +763,11 @@ func (a *App) OpenProcessorScheduling() error {
func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
a.mu.Lock()
cfg := *a.cfg
cfg := a.cfg
loc := i18n.EffectiveLocale(cfg.Locale)
a.mu.Unlock()
if err := a.requireWritableDataRoot(); err != nil {
return nil, err
}
a.emitLog("runtime", "Installing portable runtime: "+archivePath)
inst, err := rt.InstallFromArchive(&cfg, archivePath)
inst, err := rt.InstallFromArchive(cfg, archivePath)
if err != nil {
a.emitLog("runtime", "Install failed: "+err.Error())
if errors.Is(err, rt.ErrRuntimeInUse) {
@@ -826,59 +775,33 @@ func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
}
return nil, err
}
if err := a.activateInstalledRuntime(&cfg, inst.Commit); err != nil {
inst.Active = false
a.emitLog("runtime", err.Error())
return inst, err
if inst.Active {
a.mu.Lock()
a.cfg.ActiveRuntime = inst.Commit
saveErr := a.saveConfigLocked()
a.mu.Unlock()
if saveErr != nil {
return nil, saveErr
}
}
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed & activated -> %s", inst.Commit, inst.Dir))
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed -> %s", inst.Commit, inst.Dir))
return inst, nil
}
func (a *App) UseRuntime(commit string) error {
return a.activateRuntime("", commit)
}
func (a *App) activateInstalledRuntime(cfg *config.Config, commit string) error {
if err := a.activateRuntime(cfg.DataRoot, commit); err != nil {
return i18n.NewCodedError(i18n.EffectiveLocale(cfg.Locale), "E_RUNTIME_ACTIVATION",
"runtime.installed_not_activated", i18n.Vars{"commit": commit}, err)
}
return nil
}
func (a *App) activateRuntime(dataRoot, commit string) error {
return a.updateSelection(func(cfg *config.Config) error {
if dataRoot != "" && cfg.DataRoot != dataRoot {
return errors.New("data folder changed during runtime install")
}
return rt.Activate(a.baseCtx(), cfg, commit, a.warnRuntime)
})
}
func (a *App) warnRuntime(warning error) {
message := warning.Error()
a.emitLog("runtime", message)
a.emit("reims:runtime-warning", message)
}
func (a *App) SetQEMUASLR(enabled bool) error {
return a.updateSelection(func(cfg *config.Config) error {
return rt.SetQEMUASLR(a.baseCtx(), cfg, enabled)
})
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.ActiveRuntime = commit
return a.saveConfigLocked()
}
func (a *App) RemoveRuntime(commit string) error {
a.mu.Lock()
if err := a.requireWritableDataRootLocked(); err != nil {
a.mu.Unlock()
return err
}
cfg := *a.cfg
loc := i18n.EffectiveLocale(cfg.Locale)
cfg := a.cfg
loc := i18n.EffectiveLocale(a.cfg.Locale)
a.mu.Unlock()
inst, err := rt.Remove(&cfg, commit)
inst, err := rt.Remove(cfg, commit)
if err != nil {
switch {
case errors.Is(err, rt.ErrNotFound):
+8 -22
View File
@@ -39,7 +39,9 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
if opts.NetworkMode == "bridge" {
opts.SSHPort = 0
}
cfgCopy := a.runtimeConfig()
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return err
@@ -63,27 +65,11 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
}
a.emitVMLog(opts.Name, "Creating VM "+opts.Name+"...")
targetDir := reims.ResolveCreateTargetDir(cfgCopy.XDGDataDir(), opts)
if reims.IsAbortedCreateDir(targetDir) {
vms, err := a.listVMsInternal(ctx)
if err != nil {
finishTask(err)
return err
}
registered := make([]reims.VMListItem, 0, len(vms))
for _, vm := range vms {
registered = append(registered, reims.VMListItem{Name: vm.Name, Dir: vm.Dir})
}
if issue := reims.ValidateCreateTargetDir(cfgCopy.XDGDataDir(), opts, registered, cfgCopy.Locale); issue != nil {
err := errors.New(issue.Message)
finishTask(err)
return err
}
if removed, rerr := reims.CleanAbortedCreateDir(cfgCopy.XDGDataDir(), opts, registered); rerr != nil {
a.emitVMLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
} else if removed != "" {
a.emitVMLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
}
existingVMs, _ := c.List(ctx)
if removed, rerr := reims.CleanAbortedCreateDir(cfgCopy.XDGDataDir(), opts, existingVMs); rerr != nil {
a.emitVMLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
} else if removed != "" {
a.emitVMLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
}
// Ensure any requested macOS installer is downloaded via installer.Client
-90
View File
@@ -1,90 +0,0 @@
package app
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func sameDataFolder(a, b string) bool {
if rel, err := filepath.Rel(a, b); err == nil && rel == "." {
return true
}
left, errA := os.Stat(a)
right, errB := os.Stat(b)
return errA == nil && errB == nil && os.SameFile(left, right)
}
// Order both selection locks so simultaneous switches in opposite directions
// cannot deadlock. Ordinary preference saves can finish during the switch.
func lockDataRootSelections(ctx context.Context, source, target string) (func(), error) {
if source == "" || sameDataFolder(source, target) {
return rt.LockSelection(ctx, target)
}
if strings.ToLower(source) > strings.ToLower(target) {
source, target = target, source
}
first, err := rt.LockSelection(ctx, source)
if err != nil {
return nil, err
}
second, err := rt.LockSelection(ctx, target)
if err != nil {
first()
return nil, err
}
return func() {
second()
first()
}, nil
}
// Return a rollback for a later config or location save failure. Existing
// destination preferences already authorize their own rule.
func (a *App) moveDataRootASLR(ctx context.Context, prev, next *config.Config, fresh bool, syncPolicy func(context.Context, string, string) error) (func() error, error) {
path, err := rt.QEMUASLRPath(next)
if err != nil {
return nil, err
}
restoreSource := func() error {
oldPath, err := rt.QEMUASLRPath(prev)
if err != nil || oldPath == "" {
return err
}
return syncPolicy(context.WithoutCancel(ctx), prev.RuntimesDir(), oldPath)
}
if err := syncPolicy(ctx, prev.RuntimesDir(), ""); err != nil {
report := rt.QEMUASLRPolicyError(prev, err)
if errors.Is(err, host.ErrElevationDeclined) || errors.Is(err, context.Canceled) {
return nil, report
}
return nil, errors.Join(report, restoreSource())
}
if path == "" {
return restoreSource, nil
}
restore := func() error {
var err error
if fresh {
err = syncPolicy(context.WithoutCancel(ctx), next.RuntimesDir(), "")
}
return errors.Join(err, restoreSource())
}
if err := syncPolicy(ctx, next.RuntimesDir(), path); err != nil {
if errors.Is(err, host.ErrQEMUASLRImagePolicy) {
a.warnRuntime(rt.QEMUASLRPolicyError(next, err))
return restoreSource, nil
}
if errors.Is(err, host.ErrElevationDeclined) || errors.Is(err, context.Canceled) {
return nil, errors.Join(rt.QEMUASLRPolicyError(next, err), restoreSource())
}
return nil, errors.Join(err, restore())
}
return restore, nil
}
-172
View File
@@ -1,172 +0,0 @@
package app
import (
"context"
"errors"
"os"
"path/filepath"
"reflect"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestDataRootSwitchCarriesASLRAndCleansSource(t *testing.T) {
dir := t.TempDir()
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(dir, "location.json"))
old := config.Config{DataRoot: filepath.Join(dir, "old")}
a := &App{cfg: &old}
saved := old
saved.QEMUASLR = true // The CLI enabled it after the desktop opened.
saved.ActiveRuntime = "cli-selection"
if err := config.Save("", &saved); err != nil {
t.Fatal(err)
}
target := filepath.Join(dir, "new")
calls := 0
err := a.setDataRoot(target, func(_ context.Context, root, path string) error {
calls++
if root != old.RuntimesDir() || path != "" {
t.Fatalf("unexpected policy update %q, %q", root, path)
}
// A preference save must finish while the Windows consent prompt is open.
if _, err := a.SetFullscreenHotkey(FullscreenHotkeyConfig{Enabled: true, Hotkey: "F9"}); err != nil {
return err
}
return a.SetSyncHostMemorySMBIOS(true)
})
if err != nil || calls != 1 {
t.Fatalf("switch: calls=%d err=%v", calls, err)
}
stored, err := config.LoadExisting(filepath.Join(target, "reims-go.json"))
if err != nil || !stored.QEMUASLR || !stored.SyncHostMemorySMBIOS || a.cfg.DataRoot != target {
t.Fatalf("new config: %+v, %v", stored, err)
}
if !stored.FullscreenHotkeyEnabled || stored.FullscreenHotkey != "F9" {
t.Fatalf("new folder lost the fullscreen shortcut: %+v", stored)
}
source, err := config.LoadExisting(filepath.Join(old.DataRoot, "reims-go.json"))
if err != nil || !source.QEMUASLR || source.ActiveRuntime != saved.ActiveRuntime {
t.Fatalf("shortcut save replaced the CLI selection: %+v, %v", source, err)
}
if err := a.setDataRoot(target, func(context.Context, string, string) error {
t.Fatal("same directory must retain its rule")
return nil
}); err != nil {
t.Fatal(err)
}
}
func TestDataRootSwitchUsesDestinationPolicy(t *testing.T) {
for _, enabled := range []bool{false, true} {
dir := t.TempDir()
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(dir, "location.json"))
old := config.Config{DataRoot: filepath.Join(dir, "old"), QEMUASLR: !enabled}
next := config.Config{DataRoot: filepath.Join(dir, "next"), QEMUASLR: enabled, ActiveRuntime: "new"}
if err := config.Save("", &next); err != nil {
t.Fatal(err)
}
runtimeDir := folderTestDir(t, next.RuntimesDir(), "new")
if err := os.WriteFile(filepath.Join(runtimeDir, "manifest.json"), []byte("{}"), 0o600); err != nil {
t.Fatal(err)
}
a := &App{cfg: &old}
var updates [][2]string
err := a.setDataRoot(next.DataRoot, func(_ context.Context, root, path string) error {
updates = append(updates, [2]string{root, path})
return nil
})
want := [][2]string{{old.RuntimesDir(), ""}}
if enabled {
runtime := rt.Installed{Dir: runtimeDir}
want = append(want, [2]string{next.RuntimesDir(), runtime.QemuPath()})
}
if err != nil || a.cfg.QEMUASLR != enabled || !reflect.DeepEqual(updates, want) {
t.Fatalf("destination enabled=%v: cfg=%+v updates=%v err=%v", enabled, a.cfg, updates, err)
}
}
}
func TestDataRootSwitchRestoresSourceOnPublishFailure(t *testing.T) {
dir := t.TempDir()
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(dir, "location.json"))
old := config.Config{DataRoot: filepath.Join(dir, "old"), QEMUASLR: true, ActiveRuntime: "old"}
if err := config.SaveLocation(old.DataRoot); err != nil {
t.Fatal(err)
}
runtimeDir := folderTestDir(t, old.RuntimesDir(), "old")
if err := os.WriteFile(filepath.Join(runtimeDir, "manifest.json"), []byte("{}"), 0o600); err != nil {
t.Fatal(err)
}
next := filepath.Join(dir, "next")
a := &App{cfg: &old}
var paths []string
err := a.setDataRoot(next, func(_ context.Context, root, path string) error {
if root != old.RuntimesDir() {
return errors.New("unexpected registry root")
}
paths = append(paths, path)
if path == "" {
// The destination can no longer accept the config after the source rule was cleared.
folderTestDir(t, next, "reims-go.json")
}
return nil
})
runtime := rt.Installed{Dir: runtimeDir}
location, ok := config.ReadLocation()
if err == nil || a.cfg.DataRoot != old.DataRoot || !ok || location != old.DataRoot || !reflect.DeepEqual(paths, []string{"", runtime.QemuPath()}) {
t.Fatalf("failed switch: cfg=%+v, location=%s, updates=%v err=%v", a.cfg, location, paths, err)
}
}
func TestDataRootSwitchRollsBackPartialPolicyWrites(t *testing.T) {
dir := t.TempDir()
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(dir, "location.json"))
old := config.Config{DataRoot: filepath.Join(dir, "old"), QEMUASLR: true, ActiveRuntime: "installed"}
next := config.Config{DataRoot: filepath.Join(dir, "next")}
if err := config.SaveLocation(old.DataRoot); err != nil {
t.Fatal(err)
}
for _, cfg := range []config.Config{old, next} {
dir := folderTestDir(t, cfg.RuntimesDir(), "installed")
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), []byte("{}"), 0o600); err != nil {
t.Fatal(err)
}
}
oldRuntime := rt.Installed{Dir: filepath.Join(old.RuntimesDir(), "installed")}
nextRuntime := rt.Installed{Dir: filepath.Join(next.RuntimesDir(), "installed")}
clearOld := [2]string{old.RuntimesDir(), ""}
restoreOld := [2]string{old.RuntimesDir(), oldRuntime.QemuPath()}
enableNext := [2]string{next.RuntimesDir(), nextRuntime.QemuPath()}
clearNext := [2]string{next.RuntimesDir(), ""}
partial := errors.New("incomplete registry write")
for _, tc := range []struct {
name string
failAt [2]string
err error
want [][2]string
}{
{"source", clearOld, partial, [][2]string{clearOld, restoreOld}},
{"target", enableNext, partial, [][2]string{clearOld, enableNext, clearNext, restoreOld}},
{"declined", clearOld, host.ErrElevationDeclined, [][2]string{clearOld}},
} {
t.Run(tc.name, func(t *testing.T) {
var updates [][2]string
a := &App{cfg: &old}
err := a.setDataRoot(next.DataRoot, func(_ context.Context, root, path string) error {
operation := [2]string{root, path}
updates = append(updates, operation)
if operation == tc.failAt {
return tc.err
}
return nil
})
location, ok := config.ReadLocation()
if !errors.Is(err, tc.err) || !reflect.DeepEqual(updates, tc.want) || a.cfg.DataRoot != old.DataRoot || !ok || location != old.DataRoot {
t.Fatalf("updates=%v, location=%q, cfg=%+v, err=%v", updates, location, a.cfg, err)
}
})
}
}
+10 -71
View File
@@ -8,7 +8,6 @@ import (
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
)
@@ -55,80 +54,24 @@ func (a *App) dataRootUsable() bool {
func (a *App) requireWritableDataRoot() error {
a.mu.Lock()
defer a.mu.Unlock()
return a.requireWritableDataRootLocked()
}
func (a *App) requireWritableDataRootLocked() error {
if a.needsSetup {
return i18n.NewCodedError(i18n.EffectiveLocale(a.cfg.Locale), "E_DATAROOT_SETUP", "err.dataroot.needs_setup", nil, nil)
}
return dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root)
}
func (a *App) setPreference(edit func(*config.Config)) error {
a.configMu.Lock()
defer a.configMu.Unlock()
a.mu.Lock()
cfg := *a.cfg
setup := a.needsSetup
err := a.requireWritableDataRootLocked()
a.mu.Unlock()
if err != nil && !setup {
// saveConfigLocked persists a.cfg; a.mu must be held. Before first-run setup
// a.cfg points at a suggested folder the user has not chosen, so changes stay
// in memory until CompleteSetup writes them into the chosen folder. A folder
// open read-only refuses the write.
func (a *App) saveConfigLocked() error {
if a.needsSetup {
return nil
}
if err := dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root); err != nil {
return err
}
edit(&cfg)
if !setup {
if err := rt.SavePreferences(&cfg); err != nil {
return err
}
}
a.mu.Lock()
a.cfg = &cfg
a.mu.Unlock()
return nil
}
// Runtime policy may wait for UAC. Publish only its two fields over the
// current settings once the disk transaction has finished.
func (a *App) updateSelection(persist func(*config.Config) error) error {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
a.mu.Lock()
err := a.requireWritableDataRootLocked()
cfg := *a.cfg
a.mu.Unlock()
if err != nil {
return err
}
if err := persist(&cfg); err != nil {
return err
}
a.configMu.Lock()
defer a.configMu.Unlock()
a.mu.Lock()
latest := *a.cfg
latest.ActiveRuntime, latest.QEMUASLR = cfg.ActiveRuntime, cfg.QEMUASLR
a.cfg = &latest
a.mu.Unlock()
return nil
}
// runtimeConfig includes the last selection made by either the GUI or CLI.
func (a *App) runtimeConfig() config.Config {
a.mu.Lock()
if a.cfg == nil {
a.mu.Unlock()
return config.Config{}
}
cfg := *a.cfg
usable := !a.needsSetup && !a.root.ReadOnly
a.mu.Unlock()
if usable {
if err := rt.RefreshSelection(&cfg); err != nil {
a.emitLog("runtime", "Read runtime selection: "+err.Error())
}
}
return cfg
return config.Save("", a.cfg)
}
// ReopenDataRoot opens the current data folder again: after another process
@@ -136,10 +79,6 @@ func (a *App) runtimeConfig() config.Config {
// a damaged version record on the user's request. When the folder becomes
// writable, the parts that were held back start.
func (a *App) ReopenDataRoot(repair bool) (dataroot.Status, error) {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
a.configMu.Lock()
defer a.configMu.Unlock()
a.mu.Lock()
if a.needsSetup {
st := a.root
+1 -1
View File
@@ -135,8 +135,8 @@ func (a *App) ExportDiagnostics(driverID, name string) (string, error) {
return "", err
}
}
cfgCopy := a.runtimeConfig()
a.mu.Lock()
cfgCopy := *a.cfg
appLogs := append([]string(nil), a.recentLogs...)
a.mu.Unlock()
rep := host.Inspect(cfgCopy.DataRoot)
+12 -8
View File
@@ -3,7 +3,6 @@ package app
import (
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
)
@@ -50,15 +49,20 @@ func (a *App) SetFullscreenHotkey(req FullscreenHotkeyConfig) (FullscreenHotkeyS
if err != nil {
return FullscreenHotkeyStatus{}, err
}
if err := a.setPreference(func(cfg *config.Config) {
if req.Enabled != cfg.FullscreenHotkeyEnabled && strings.TrimSpace(req.Hotkey) == "" {
canonical = effectiveFullscreenHotkey(cfg.FullscreenHotkey)
}
cfg.FullscreenHotkeyEnabled = req.Enabled
cfg.FullscreenHotkey = canonical
}); err != nil {
a.mu.Lock()
oldEnabled, oldHotkey := a.cfg.FullscreenHotkeyEnabled, a.cfg.FullscreenHotkey
if req.Enabled != oldEnabled && strings.TrimSpace(req.Hotkey) == "" {
canonical = effectiveFullscreenHotkey(oldHotkey)
}
a.cfg.FullscreenHotkeyEnabled = req.Enabled
a.cfg.FullscreenHotkey = canonical
if err := a.saveConfigLocked(); err != nil {
a.cfg.FullscreenHotkeyEnabled = oldEnabled
a.cfg.FullscreenHotkey = oldHotkey
a.mu.Unlock()
return FullscreenHotkeyStatus{}, err
}
a.mu.Unlock()
a.syncFullscreenHotkeyTargets()
a.emitStateChanged()
+7 -7
View File
@@ -5,7 +5,6 @@ import (
"os"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/guesttools"
)
@@ -23,15 +22,16 @@ func (a *App) SetHostDNSConfig(cfg guesttools.HostDNSConfig) error {
if err := cfg.Validate(); err != nil {
return err
}
if err := a.setPreference(func(c *config.Config) {
c.HostDNSMode, c.HostDNSDoHURL = cfg.Mode, cfg.DoHURL
}); err != nil {
return err
}
a.mu.Lock()
defer a.mu.Unlock()
prev := a.hostDNSConfigLocked()
a.cfg.HostDNSMode, a.cfg.HostDNSDoHURL = cfg.Mode, cfg.DoHURL
if err := a.saveConfigLocked(); err != nil {
a.cfg.HostDNSMode, a.cfg.HostDNSDoHURL = prev.Mode, prev.DoHURL
return err
}
if a.guestTools != nil {
a.guestTools.SetHostDNSConfig(a.hostDNSConfigLocked())
a.guestTools.SetHostDNSConfig(cfg)
}
return nil
}
+11 -5
View File
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
@@ -21,11 +20,18 @@ var (
// Hyper-V / WHPX boot switch in Settings. Toggling this flag alone never runs
// any system virtualization or boot configuration command.
func (a *App) SetEnableHypervisorSwitch(enabled bool) error {
if err := a.setPreference(func(cfg *config.Config) { cfg.EnableHypervisorSwitch = enabled }); err != nil {
return err
a.mu.Lock()
prev := a.cfg.EnableHypervisorSwitch
a.cfg.EnableHypervisorSwitch = enabled
err := a.saveConfigLocked()
if err != nil {
a.cfg.EnableHypervisorSwitch = prev
}
a.emitStateChanged()
return nil
a.mu.Unlock()
if err == nil {
a.emitStateChanged()
}
return err
}
// SetHypervisorBoot prompts for UAC and updates Windows hypervisor boot launch
+3 -1
View File
@@ -13,7 +13,9 @@ import (
)
func (a *App) installerClient() (*installer.Client, error) {
cfg := a.runtimeConfig()
a.mu.Lock()
cfg := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfg)
if err != nil {
return nil, err
+10 -18
View File
@@ -307,14 +307,12 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error {
if err != nil {
return err
}
ref := vm.Ref()
removedVM := false
err = a.withComputerUseVM(context.Background(), vm.Directory, func(ctx context.Context) error {
return a.withComputerUseVM(context.Background(), vm.Directory, func(ctx context.Context) error {
ref := vm.Ref()
key := ref.Key()
if vm.State != "running" && ref.DriverID == driver.BuiltinReimsMacOSDriverID {
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.cancelRebootWatcher(ref.Name)
stopVMMonitor(ref.Name)
a.stopPacketBridge(ref.Name)
}
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
var deleteErr error
@@ -340,10 +338,7 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error {
} else if err := svc.DeleteResolved(ctx, d, vm, keepFiles, w, w); err != nil {
return err
}
removedVM = true
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.cancelRebootWatcher(ref.Name)
stopVMMonitor(ref.Name)
a.stopPacketBridge(ref.Name)
}
a.mu.Lock()
@@ -353,6 +348,13 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error {
delete(a.procSamples, key)
gt := a.guestTools
a.mu.Unlock()
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
releaseVMTyping(ref.Name)
releaseVMThumbnail(ref.Name)
} else {
releaseVMTypingForDriver(ref.DriverID, ref.Name)
releaseVMThumbnailForDriver(ref.DriverID, ref.Name)
}
a.stateTable().Delete(ref)
a.discardMaterializedSecretsForVM(key)
if gt != nil {
@@ -362,14 +364,4 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error {
a.emitStateChanged()
return deleteErr
})
if removedVM {
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
releaseVMTyping(ref.Name)
releaseVMThumbnail(ref.Name)
} else {
releaseVMTypingForDriver(ref.DriverID, ref.Name)
releaseVMThumbnailForDriver(ref.DriverID, ref.Name)
}
}
return err
}
-225
View File
@@ -11,62 +11,17 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/tray"
"github.com/Nwflower/reims-go/internal/vmstart"
)
func TestMacOSLaunchUsesLatestRuntimeSelection(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "current", QEMUASLR: true}
for _, version := range []string{"current", "backup"} {
dir := folderTestDir(t, cfg.RuntimesDir(), version)
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), []byte("{}"), 0o600); err != nil {
t.Fatal(err)
}
}
a := &App{cfg: &cfg}
d := macosdriver.NewReimsMacOSDriver(a.runtimeConfig, macosdriver.Options{OwnerID: "test.macos"})
ref := driver.NewVMRef(d.ID(), "test")
for _, version := range []string{"current", "backup", "current"} {
saved := cfg
saved.ActiveRuntime = version
if err := config.Save("", &saved); err != nil {
t.Fatal(err)
}
want := rt.Installed{Dir: filepath.Join(cfg.RuntimesDir(), version)}
prep, err := a.prep(ref.Name)
if err != nil {
t.Fatal(err)
}
c, err := a.client()
if err != nil {
t.Fatal(err)
}
if c.Binary != want.ControlPath() || prep.Client.Binary != c.Binary || a.activeQemuPath() != want.QemuPath() {
t.Fatalf("%s: native clients or bridge selected the wrong runtime", version)
}
// Only manifests are installed. The attempted control executable
// identifies which runtime the same driver used for each new request.
_, startErr := d.Start(t.Context(), driver.StartRequest{Ref: ref})
_, resumeErr := d.Resume(t.Context(), driver.ResumeRequest{Ref: ref})
for _, err := range []error{startErr, resumeErr} {
if err == nil || !strings.Contains(err.Error(), want.ControlPath()) {
t.Fatalf("expected a launch attempt with %q, got %v", want.ControlPath(), err)
}
}
}
}
func TestPrepareLegacyColdStart(t *testing.T) {
log := func(line string) { t.Log(line) }
t.Run("recoverable snapshot", func(t *testing.T) {
@@ -356,183 +311,3 @@ func TestSameNameVMsAcrossDriversStayIndependent(t *testing.T) {
t.Fatalf("tray restart: mac stops=%d starts=%d, linux stops=%d starts=%d", mac.stops, mac.starts, lin.stops, lin.starts)
}
}
func TestStopVMMonitorWaitsForExitAndAllowsDirRemoval(t *testing.T) {
vmDir := t.TempDir()
logDir := filepath.Join(vmDir, "logs")
if err := os.MkdirAll(logDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(logDir, "qemu.log"), []byte("boot\n"), 0o644); err != nil {
t.Fatal(err)
}
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}}
if _, err := vmstart.SaveVMDisplay(vmDir, vmstart.VMDisplayConfig{TargetDisplay: "DISPLAY2"}); err != nil {
t.Fatal(err)
}
const vmName = "monitor-wait-test"
a.startVMMonitor(vmName, driver.VMInfo{
Name: vmName,
DriverID: driver.BuiltinReimsMacOSDriverID,
Directory: vmDir,
}, time.Now())
stopVMMonitor(vmName)
vmMonitors.mu.Lock()
_, stillRegistered := vmMonitors.entries[vmName]
vmMonitors.mu.Unlock()
if stillRegistered {
t.Fatal("monitor entry still registered after stopVMMonitor")
}
if err := os.RemoveAll(vmDir); err != nil {
t.Fatalf("removing VM dir after stopVMMonitor failed: %v", err)
}
}
func TestStoppingVMMonitorStaysRegisteredUntilExit(t *testing.T) {
const name = "monitor-concurrent-stop-test"
ctx, cancel := context.WithCancel(t.Context())
done := make(chan struct{})
vmMonitors.mu.Lock()
vmMonitors.entries[name] = vmMonitorEntry{cancel: cancel, done: done}
vmMonitors.mu.Unlock()
t.Cleanup(func() {
vmMonitors.mu.Lock()
delete(vmMonitors.entries, name)
vmMonitors.mu.Unlock()
})
stopped := make(chan struct{})
go func() {
stopVMMonitor(name)
close(stopped)
}()
defer func() {
close(done)
<-stopped
}()
select {
case <-ctx.Done():
case <-time.After(time.Second):
t.Fatal("stop did not cancel the monitor")
}
vmMonitors.mu.Lock()
entry, ok := vmMonitors.entries[name]
vmMonitors.mu.Unlock()
if !ok || entry.done != done {
t.Fatal("concurrent callers lost the monitor completion channel before exit")
}
}
func TestStopVMMonitorRespectsTimeoutWhenStuck(t *testing.T) {
origTimeout := vmMonitorStopTimeout
vmMonitorStopTimeout = 30 * time.Millisecond
t.Cleanup(func() { vmMonitorStopTimeout = origTimeout })
const name = "monitor-stuck-timeout-test"
ctx, cancel := context.WithCancel(t.Context())
done := make(chan struct{})
vmMonitors.mu.Lock()
vmMonitors.entries[name] = vmMonitorEntry{cancel: cancel, done: done}
vmMonitors.mu.Unlock()
t.Cleanup(func() {
vmMonitors.mu.Lock()
delete(vmMonitors.entries, name)
vmMonitors.mu.Unlock()
close(done)
})
finished := make(chan struct{})
go func() {
stopVMMonitor(name)
close(finished)
}()
select {
case <-finished:
case <-time.After(time.Second):
t.Fatal("stopVMMonitor hung indefinitely when monitor goroutine did not exit")
}
if ctx.Err() == nil {
t.Fatal("stopVMMonitor did not cancel the monitor context")
}
allFinished := make(chan struct{})
go func() {
stopAllVMMonitors()
close(allFinished)
}()
select {
case <-allFinished:
case <-time.After(time.Second):
t.Fatal("stopAllVMMonitors hung indefinitely when monitor goroutine did not exit")
}
}
func TestValidateCreateProtectsDirectoryOfAnotherDriver(t *testing.T) {
const driverID = "test.driver.linux"
target := t.TempDir()
child := filepath.Join(target, "ubuntu")
if err := os.Mkdir(child, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(target, ".reims-ctl-creating"), nil, 0o600); err != nil {
t.Fatal(err)
}
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: child}}}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test.linux", 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: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil)}
issues := a.ValidateCreate(reims.CreateOpts{Name: "new-mac", Dir: target})
for _, issue := range issues {
if issue.Field == "dir" && issue.Code == "dir_not_empty" {
return
}
}
t.Fatalf("expected directory conflict for VM registered by another driver, got %+v", issues)
}
func TestValidateCreateRejectsLeftoverNonEmptyVMDir(t *testing.T) {
dataRoot := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: dataRoot}}
leftoverDir := filepath.Join(a.cfg.XDGDataDir(), "reims-ctl", "vms", "macos-tahoe2")
if err := os.MkdirAll(leftoverDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(leftoverDir, "vm.toml"), []byte("name = \"macos-tahoe2\"\n"), 0o644); err != nil {
t.Fatal(err)
}
opts := reims.CreateOpts{
Name: "macos-tahoe2",
SourceMode: "apple",
MacOS: "tahoe",
CPUs: 2,
Memory: "4G",
DiskSize: "64G",
}
hasDirIssue := func(issues []reims.ValidationIssue) bool {
for _, is := range issues {
if is.Field == "dir" && is.Code == "dir_not_empty" {
return true
}
}
return false
}
if issues := a.ValidateCreate(opts); !hasDirIssue(issues) {
t.Fatalf("expected dir_not_empty issue for leftover directory, got %+v", issues)
}
if err := os.RemoveAll(leftoverDir); err != nil {
t.Fatal(err)
}
if issues := a.ValidateCreate(opts); hasDirIssue(issues) {
t.Fatalf("unexpected dir_not_empty issue after clearing directory: %+v", issues)
}
}
+11 -6
View File
@@ -43,12 +43,14 @@ func (a *App) client() (*reims.Client, error) {
if err := a.requireMacOSEnabled(); err != nil {
return nil, err
}
cfg := a.runtimeConfig()
active, err := rt.ResolveActive(&cfg)
a.mu.Lock()
cfg := a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(cfg)
if err != nil {
return nil, fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
}
return reims.NewClient(&cfg, *active), nil
return reims.NewClient(cfg, *active), nil
}
func enrichMacOSVMListStates(vms []driver.VMListItem) {
@@ -94,11 +96,14 @@ func (a *App) tempDir() string {
}
func (a *App) activeQemuPath() string {
cfg := a.runtimeConfig()
if cfg.DataRoot == "" {
a.mu.Lock()
if a.cfg == nil {
a.mu.Unlock()
return ""
}
active, err := rt.ResolveActive(&cfg)
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil || active == nil {
return ""
}
+18 -40
View File
@@ -599,55 +599,33 @@ func (a *App) deleteMacOSVM(name string, keepFiles bool) error {
if err != nil {
return err
}
removed := false
err = a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
return a.deleteMacOSVMLocked(ctx, detail, keepFiles, c, &removed)
return a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
return a.deleteMacOSVMLocked(ctx, name, keepFiles, c)
})
if removed {
releaseVMTyping(name)
releaseVMThumbnail(name)
}
return err
}
func (a *App) deleteMacOSVMLocked(ctx context.Context, detail reims.VMDetail, keepFiles bool, c *reims.Client, removed *bool) error {
name := detail.Name
if detail.State != "running" {
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.stopPacketBridge(name)
}
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
a.emitVMLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
deleted, deleteErr := a.deleteVMWithGuestTools(name, func() error {
return c.Delete(ctx, name, keepFiles, w, w)
}, func() (bool, error) {
vms, err := c.List(ctx)
if err != nil {
return false, err
}
for _, vm := range vms {
if strings.EqualFold(vm.Name, name) {
return true, nil
}
}
return false, nil
})
if deleteErr != nil {
a.emitVMLog(name, "Delete error: "+deleteErr.Error())
}
if !deleted {
return deleteErr
}
*removed = true
func (a *App) deleteMacOSVMLocked(ctx context.Context, name string, keepFiles bool, c *reims.Client) error {
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.stopPacketBridge(name)
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
a.emitVMLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
if err := c.Delete(ctx, name, keepFiles, w, w); err != nil {
a.emitVMLog(name, "Delete error: "+err.Error())
return err
}
a.mu.Lock()
delete(a.pendingChanges, vmKey(name))
delete(a.transitions, vmKey(name))
delete(a.diskPaths, vmKey(name))
delete(a.procSamples, vmKey(name))
gt := a.guestTools
a.mu.Unlock()
releaseVMTyping(name)
releaseVMThumbnail(name)
if gt != nil {
gt.UnregisterVM(name)
}
a.mu.Lock()
delMgr := a.pluginMgr
a.mu.Unlock()
if delMgr != nil {
@@ -658,7 +636,7 @@ func (a *App) deleteMacOSVMLocked(ctx context.Context, detail reims.VMDetail, ke
}
a.wakePoll()
a.emitStateChanged()
return deleteErr
return nil
}
// OpenVMFolder shows the VM's directory in File Explorer.
+5 -23
View File
@@ -27,37 +27,17 @@ import (
func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
a.mu.Lock()
root := a.cfg.DataRoot
xdgDataDir := ""
if strings.TrimSpace(root) != "" {
xdgDataDir = a.cfg.XDGDataDir()
}
loc := i18n.EffectiveLocale(a.cfg.Locale)
a.mu.Unlock()
issues := reims.ValidateCreate(opts, host.Inspect(root), loc)
// reims-ctl refuses a name already registered; say so before the create runs.
var registered []reims.VMListItem
nameTaken := false
if vms, err := a.listVMsInternal(context.Background()); err == nil {
for _, vm := range vms {
registered = append(registered, reims.VMListItem{Name: vm.Name, Dir: vm.Dir})
if !nameTaken && strings.EqualFold(vm.Name, strings.TrimSpace(opts.Name)) {
nameTaken = true
if strings.EqualFold(vm.Name, strings.TrimSpace(opts.Name)) {
issues = append(issues, reims.ValidationIssue{Field: "name", Code: "name_taken", Message: i18n.T(loc, "validate.name_taken", vm.Name)})
break
}
}
} else if regVMs, regErr := reims.ListRegisteredVMs(root); regErr == nil {
for _, vm := range regVMs {
registered = append(registered, reims.VMListItem{Name: vm.Name, Dir: vm.Directory})
if !nameTaken && strings.EqualFold(vm.Name, strings.TrimSpace(opts.Name)) {
nameTaken = true
issues = append(issues, reims.ValidationIssue{Field: "name", Code: "name_taken", Message: i18n.T(loc, "validate.name_taken", vm.Name)})
}
}
}
if !nameTaken || strings.TrimSpace(opts.Dir) != "" {
if issue := reims.ValidateCreateTargetDir(xdgDataDir, opts, registered, loc); issue != nil {
issues = append(issues, *issue)
}
}
return issues
}
@@ -547,7 +527,9 @@ func selectPacketUplink(adapters []packetbridge.Adapter, guid string) (packetbri
}
func (a *App) ensurePacketBridge(d reims.VMDetail, adapter packetbridge.Adapter, mac, socketPath string, port int) (*packetbridge.Bridge, error) {
cfgCopy := a.runtimeConfig()
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return nil, err
+10 -3
View File
@@ -33,7 +33,10 @@ func (a *App) prep(name string) (*startprep.Prep, error) {
if err := a.requireMacOSEnabled(); err != nil {
return nil, err
}
return startprep.New(a.runtimeConfig(), func(line string) { a.emitVMLog(name, line) })
a.mu.Lock()
cfg := *a.cfg
a.mu.Unlock()
return startprep.New(cfg, func(line string) { a.emitVMLog(name, line) })
}
// GetVMSMBIOS reads the VM's OpenCore PlatformInfo > Generic identity
@@ -43,7 +46,9 @@ func (a *App) GetVMSMBIOS(name string) (opencore.SMBIOSIdentity, error) {
if err := a.requireMacOSEnabled(); err != nil {
return opencore.SMBIOSIdentity{}, err
}
cfgCopy := a.runtimeConfig()
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return opencore.SMBIOSIdentity{}, err
@@ -81,7 +86,9 @@ func (a *App) ApplyVMSMBIOS(name string, id opencore.SMBIOSIdentity) (opencore.S
if err != nil {
return opencore.SMBIOSIdentity{}, err
}
cfgCopy := a.runtimeConfig()
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return opencore.SMBIOSIdentity{}, err
+10 -3
View File
@@ -16,6 +16,7 @@ import (
"unicode"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/downloader"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/fetch"
@@ -129,7 +130,12 @@ func (a *App) initPlugins() {
})
cb := builtin.HostCallbacks{
GetConfig: a.runtimeConfig,
GetConfig: func() config.Config {
a.mu.Lock()
cp := *a.cfg
a.mu.Unlock()
return cp
},
Log: func(source, line string) {
a.emitLog(source, line)
},
@@ -643,11 +649,12 @@ func buildHostFacts(rep host.Report, rtCaps []string) map[string]any {
func (a *App) ListPlugins() []plugin.PluginInfo {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
a.mu.Unlock()
return nil
}
cfg := a.runtimeConfig()
cfg := *a.cfg
a.mu.Unlock()
reg := mgr.Registry()
infos := mgr.LocalizePluginInfos(reg.ListVisible())
active, _ := rt.ResolveActive(&cfg)
+16 -8
View File
@@ -77,11 +77,11 @@ func (a *App) SetRuntimeChannel(channel string) error {
default:
return fmt.Errorf("unknown channel %q", channel)
}
if err := a.setPreference(func(cfg *config.Config) { cfg.RuntimeChannel = channel }); err != nil {
return err
}
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.RuntimeChannel = channel
forgetRemoteRuntimes()
return nil
return a.saveConfigLocked()
}
// InstallRuntimeOnline downloads, verifies and installs a published runtime
@@ -90,9 +90,9 @@ func (a *App) SetRuntimeChannel(channel string) error {
// which resumes on the next install.
func (a *App) InstallRuntimeOnline(commit string) (string, error) {
a.mu.Lock()
if err := a.requireWritableDataRootLocked(); err != nil {
if a.needsSetup {
a.mu.Unlock()
return "", err
return "", errors.New("choose a data folder first")
}
cfg := *a.cfg
a.mu.Unlock()
@@ -165,7 +165,11 @@ func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, ta
r.Commit = inst.Commit
}
if err := a.activateInstalledRuntime(cfg, r.Commit); err != nil {
a.mu.Lock()
a.cfg.ActiveRuntime = r.Commit
err = a.saveConfigLocked()
a.mu.Unlock()
if err != nil {
return "", err
}
a.emitLog("runtime", fmt.Sprintf("Runtime %s (%s) installed and active", r.Commit, r.Channel))
@@ -196,7 +200,11 @@ func (a *App) SetAppUpdateChannel(channel string) error {
default:
return fmt.Errorf("unknown app update channel %q", channel)
}
if err := a.setPreference(func(cfg *config.Config) { cfg.AppUpdateChannel = channel }); err != nil {
a.mu.Lock()
a.cfg.AppUpdateChannel = channel
err := a.saveConfigLocked()
a.mu.Unlock()
if err != nil {
return err
}
appUpdateCache.Lock()
-176
View File
@@ -1,176 +0,0 @@
package app
import (
"archive/zip"
"bytes"
"errors"
"os"
"path/filepath"
"testing"
"testing/fstest"
"testing/synctest"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/filelock"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestArchiveActivationCanRetryWithoutImport(t *testing.T) {
dir := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: dir}}
var archive bytes.Buffer
w := zip.NewWriter(&archive)
if err := w.AddFS(fstest.MapFS{"manifest.json": {Data: []byte(`{"commit":"candidate"}`)}}); err != nil {
t.Fatal(err)
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
path := filepath.Join(dir, "runtime.zip")
if err := os.WriteFile(path, archive.Bytes(), 0o600); err != nil {
t.Fatal(err)
}
blockActivation := filepath.Join(dir, "reims-go.json")
if err := os.Mkdir(blockActivation, 0o755); err != nil {
t.Fatal(err)
}
inst, err := a.InstallRuntimeArchive(path)
var partial *i18n.CodedError
if !errors.As(err, &partial) || partial.Code != "E_RUNTIME_ACTIVATION" || inst == nil || inst.Active {
t.Fatalf("partial install = %+v, %v", inst, err)
}
list, err := rt.List(a.cfg)
if err != nil || len(list) != 1 || list[0].Commit != "candidate" || list[0].Active {
t.Fatalf("installed list = %+v, %v", list, err)
}
for _, item := range []string{path, blockActivation} {
if err := os.Remove(item); err != nil {
t.Fatal(err)
}
}
if err := a.UseRuntime(inst.Commit); err != nil || a.cfg.ActiveRuntime != "candidate" {
t.Fatalf("activation retry = %q, %v", a.cfg.ActiveRuntime, err)
}
}
func TestRuntimeConfigFollowsExternalSelection(t *testing.T) {
dir := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: dir, ActiveRuntime: "current"}}
stored := *a.cfg
stored.ActiveRuntime, stored.QEMUASLR = "backup", true
if err := config.Save("", &stored); err != nil {
t.Fatal(err)
}
got := a.runtimeConfig()
if got.ActiveRuntime != "backup" || !got.QEMUASLR {
t.Fatalf("desktop reads stale selection: %+v", got)
}
if err := a.SetSyncHostMemorySMBIOS(true); err != nil {
t.Fatal(err)
}
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
if err != nil {
t.Fatal(err)
}
if saved.ActiveRuntime != "backup" || !saved.QEMUASLR || !saved.SyncHostMemorySMBIOS {
t.Fatalf("saving an unrelated setting lost the selection: %+v", saved)
}
}
func TestPreferencesDoNotOverwriteDamagedConfig(t *testing.T) {
dir := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: dir}}
path := filepath.Join(dir, "reims-go.json")
if err := os.WriteFile(path, []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
if err := a.SetSyncHostMemorySMBIOS(true); err == nil {
t.Fatal("saved preferences over an unreadable selection")
}
if data, err := os.ReadFile(path); err != nil || string(data) != "{" {
t.Fatalf("damaged config replaced: %q, %v", data, err)
}
}
func TestConfigWaitDoesNotBlockApp(t *testing.T) {
for _, tc := range []struct {
name string
save func(*App) error
}{
{"ASLR", func(a *App) error { return a.SetQEMUASLR(true) }},
{"runtime", func(a *App) error { return a.UseRuntime("backup") }},
{"preference", func(a *App) error { return a.SetSyncHostMemorySMBIOS(true) }},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := &config.Config{DataRoot: t.TempDir()}
if err := cfg.EnsureDirs(); err != nil {
t.Fatal(err)
}
// All saves will stop before a registry write after the lock releases.
if err := os.WriteFile(filepath.Join(cfg.DataRoot, "reims-go.json"), []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
release, err := filelock.Acquire(t.Context(), filepath.Join(cfg.RuntimesDir(), ".reims-go-runtime.lock"), 0)
if err != nil {
t.Fatal(err)
}
a := &App{cfg: cfg}
synctest.Test(t, func(t *testing.T) {
done := make(chan error, 1)
go func() { done <- tc.save(a) }()
synctest.Wait()
available := a.mu.TryLock()
if available {
a.mu.Unlock()
a.emitLog("test", "while waiting")
}
release()
if err := <-done; err == nil || !available {
t.Fatalf("global lock available = %v, save error = %v", available, err)
}
if a.cfg.QEMUASLR || a.cfg.ActiveRuntime != "" || a.cfg.SyncHostMemorySMBIOS {
t.Fatalf("failed save published %+v", a.cfg)
}
})
})
}
}
func TestConcurrentSelectionAndPreferenceSurvive(t *testing.T) {
dir := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: dir}}
synctest.Test(t, func(t *testing.T) {
resume := make(chan struct{})
results := make(chan error, 2)
go func() {
results <- a.updateSelection(func(cfg *config.Config) error {
<-resume
// Model the registry operation returning and committing over
// the preferences saved while consent was pending.
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
if err != nil {
return err
}
saved.ActiveRuntime, saved.QEMUASLR = "backup", true
cfg.ActiveRuntime, cfg.QEMUASLR = saved.ActiveRuntime, saved.QEMUASLR
return config.Save("", saved)
})
}()
synctest.Wait()
if err := a.SetSyncHostMemorySMBIOS(true); err != nil {
t.Fatal(err)
}
close(resume)
if err := <-results; err != nil {
t.Fatal(err)
}
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
if err != nil || saved.ActiveRuntime != "backup" || !saved.QEMUASLR || !saved.SyncHostMemorySMBIOS {
t.Fatalf("concurrent updates lost: %+v, %v", saved, err)
}
if a.cfg.ActiveRuntime != saved.ActiveRuntime || !a.cfg.QEMUASLR || !a.cfg.SyncHostMemorySMBIOS {
t.Fatalf("in-memory settings diverged: %+v", a.cfg)
}
})
}
+1 -6
View File
@@ -15,7 +15,6 @@ import (
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
)
@@ -102,10 +101,6 @@ func (a *App) CheckDataRoot(dir string) DataRootCheck {
// existing reims-go config there (its runtimes and VMs), records the choice for
// the next launch and leaves first-launch setup.
func (a *App) CompleteSetup(dir string) error {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
a.configMu.Lock()
defer a.configMu.Unlock()
a.mu.Lock()
locale := a.cfg.Locale
a.mu.Unlock()
@@ -134,7 +129,7 @@ func (a *App) CompleteSetup(dir string) error {
if err := writable(dir); err != nil {
return err
}
if err := rt.SavePreferences(cfg); err != nil {
if err := config.Save(cfgPath, cfg); err != nil {
return err
}
if err := config.SaveLocation(dir); err != nil {
+2 -2
View File
@@ -79,6 +79,7 @@ func (a *App) ResumeVM(driverID, name string) error {
}
a.mu.Lock()
svc := a.lifecycleSvc
cfgCopy := *a.cfg
a.mu.Unlock()
if svc == nil {
return errors.New("driver lifecycle is not initialized")
@@ -103,8 +104,7 @@ func (a *App) ResumeVM(driverID, name string) error {
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.cancelRebootWatcherKey(key)
epoch = a.vmDeleteEpoch(ref.Name)
cfg := a.runtimeConfig()
active, rerr := rt.ResolveActive(&cfg)
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")
+24 -77
View File
@@ -20,77 +20,33 @@ import (
var vmMonitors = struct {
mu sync.Mutex
seq uint64
entries map[string]vmMonitorEntry
entries map[string]struct {
id uint64
cancel context.CancelFunc
}
}{
entries: map[string]vmMonitorEntry{},
}
type vmMonitorEntry struct {
id uint64
cancel context.CancelFunc
done chan struct{}
}
var (
vmMonitorStopTimeout = 5 * time.Second
vmMonitorPollTimeout = 5 * time.Second
)
func waitVMMonitorDone(done <-chan struct{}) {
if done == nil {
return
}
timeout := vmMonitorStopTimeout
if timeout <= 0 {
<-done
return
}
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-done:
case <-timer.C:
}
entries: map[string]struct {
id uint64
cancel context.CancelFunc
}{},
}
func stopVMMonitor(name string) {
vmMonitors.mu.Lock()
cur, ok := vmMonitors.entries[name]
if ok {
if cur, ok := vmMonitors.entries[name]; ok {
cur.cancel()
delete(vmMonitors.entries, name)
}
vmMonitors.mu.Unlock()
if ok {
waitVMMonitorDone(cur.done)
}
}
func stopAllVMMonitors() {
vmMonitors.mu.Lock()
waiters := make([]chan struct{}, 0, len(vmMonitors.entries))
for _, cur := range vmMonitors.entries {
for name, cur := range vmMonitors.entries {
cur.cancel()
if cur.done != nil {
waiters = append(waiters, cur.done)
}
delete(vmMonitors.entries, name)
}
vmMonitors.mu.Unlock()
timeout := vmMonitorStopTimeout
if timeout <= 0 {
for _, done := range waiters {
<-done
}
return
}
timer := time.NewTimer(timeout)
defer timer.Stop()
for _, done := range waiters {
select {
case <-done:
case <-timer.C:
return
}
}
}
func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Time) {
@@ -99,20 +55,17 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim
return
}
ctx, cancel := context.WithCancel(a.baseCtx())
done := make(chan struct{})
var prevDone chan struct{}
vmMonitors.mu.Lock()
if cur, ok := vmMonitors.entries[name]; ok {
cur.cancel()
prevDone = cur.done
}
vmMonitors.seq++
myID := vmMonitors.seq
vmMonitors.entries[name] = vmMonitorEntry{id: myID, cancel: cancel, done: done}
vmMonitors.entries[name] = struct {
id uint64
cancel context.CancelFunc
}{id: myID, cancel: cancel}
vmMonitors.mu.Unlock()
if prevDone != nil {
waitVMMonitorDone(prevDone)
}
if vmstart.ReadVMDisplay(detail.Directory).TargetDisplay != "" {
go func() {
@@ -130,7 +83,6 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim
defer func() {
cancel()
vmMonitors.mu.Lock()
close(done)
if cur, ok := vmMonitors.entries[name]; ok && cur.id == myID {
delete(vmMonitors.entries, name)
}
@@ -185,19 +137,11 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim
}
case <-hbTicker.C:
loc := a.locale()
hbCtx, hbCancel := context.WithTimeout(ctx, vmMonitorPollTimeout)
pid, running := a.currentVMPID(hbCtx, name)
hbCancel()
if ctx.Err() != nil {
return
}
pid, running := a.currentVMPID(ctx, name)
if !running {
a.emitVMLog(name, i18n.T(loc, "monitor.exited"))
return
}
if pid <= 0 {
continue
}
now := time.Now()
dt := now.Sub(lastSampleAt).Seconds()
if dt <= 0 {
@@ -404,9 +348,12 @@ func fileSizeBytes(path string) int64 {
}
func (a *App) emitStartSummary(name string, detail driver.VMInfo, rep host.Report, qmpAddr string) {
cfg := a.runtimeConfig()
rtCommit := cfg.ActiveRuntime
loc := i18n.EffectiveLocale(cfg.Locale)
a.mu.Lock()
rawLoc := a.cfg.Locale
rtCommit := a.cfg.ActiveRuntime
pinPCores := a.cfg.AutoPinPCores
a.mu.Unlock()
loc := i18n.EffectiveLocale(rawLoc)
if rtCommit == "" {
rtCommit = "auto"
}
@@ -418,7 +365,7 @@ func (a *App) emitStartSummary(name string, detail driver.VMInfo, rep host.Repor
case strings.Contains(lowExtra, "kernel-irqchip=on"):
irqMode = "on"
}
pinStr := vmstart.AffinitySummary(loc, rep, detail.Directory, cfg.AutoPinPCores, detail.CPUs)
pinStr := vmstart.AffinitySummary(loc, rep, detail.Directory, pinPCores, detail.CPUs)
coldStr := i18n.T(loc, "monitor.start.off")
if qmpAddr != "" {
coldStr = i18n.T(loc, "monitor.start.on")
+84 -18
View File
@@ -281,12 +281,6 @@ func formatGPUCompatNote(loc i18n.Locale, g host.GPUInfo) string {
}
}
func activateRuntime(ctx context.Context, cfg *config.Config, loc i18n.Locale, commit string) error {
return rt.Activate(ctx, cfg, commit, func(warning error) {
fmt.Fprintln(os.Stderr, i18n.FormatCLIError(loc, warning))
})
}
func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go runtime <available|fetch|install|list|use|remove>")
@@ -303,8 +297,11 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
}
return err
}
if err := activateRuntime(context.Background(), cfg, loc, inst.Commit); err != nil {
return err
if inst.Active {
cfg.ActiveRuntime = inst.Commit
if err := config.Save("", cfg); err != nil {
return err
}
}
fmt.Println(i18n.T(loc, "runtime.installed", inst.Commit, inst.Dir))
return nil
@@ -338,14 +335,24 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) < 2 {
return fmt.Errorf("usage: reims-go runtime use <commit>")
}
if err := activateRuntime(context.Background(), cfg, loc, args[1]); err != nil {
if errors.Is(err, rt.ErrNotFound) {
return errors.New(i18n.T(loc, "runtime.not_found", args[1]))
}
list, err := rt.List(cfg)
if err != nil {
return err
}
fmt.Println(i18n.T(loc, "runtime.activated", args[1]))
return nil
for _, item := range list {
if item.Commit == args[1] {
if item.Kind == rt.StambhaKind {
return errors.New("Stambha VMs automatically use an installed compatible Stambha runtime")
}
cfg.ActiveRuntime = item.Commit
if err := config.Save("", cfg); err != nil {
return err
}
fmt.Println(i18n.T(loc, "runtime.activated", item.Commit))
return nil
}
}
return fmt.Errorf("%s", i18n.T(loc, "runtime.not_found", args[1]))
case "remove", "rm", "delete":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go runtime remove <commit>")
@@ -407,11 +414,16 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
}
return startVM(ctx, cfg, driverID, name, viaWindow)
case "stop":
driverID, name, err := parseVMTarget(args)
if err != nil {
fs := flag.NewFlagSet("vm stop", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
force := fs.Bool("force", false, "Force stop without waiting for guest shutdown")
if err := fs.Parse(args[1:]); err != nil {
return err
}
return stopVM(ctx, cfg, driverID, name)
if fs.NArg() != 1 {
return errors.New("usage: reims-go vm stop [--driver <id>] [--force] <name>")
}
return stopVM(ctx, cfg, *driverID, fs.Arg(0), *force)
case "suspend":
driverID, name, err := parseVMTarget(args)
if err != nil {
@@ -506,6 +518,7 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
logs := fs.Bool("logs", true, "Keep graphics and serial logs")
guestLang := fs.String("guest-lang", defaultMacOSGuestLang(loc), "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)")
start := fs.Bool("start", false, "Start VM immediately after creation")
stambhaFlags := registerStambhaVMFlags(fs)
if err := fs.Parse(args); err != nil {
return err
}
@@ -513,6 +526,10 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
return fmt.Errorf("usage: reims-go vm create [flags] <name>")
}
name := fs.Arg(0)
stambhaOpts := collectStambhaVMFlags(fs, stambhaFlags)
if len(stambhaOpts) > 0 && *driverID != driver.BuiltinStambhaDriverID {
return fmt.Errorf("Stambha VM flags require --driver %s", driver.BuiltinStambhaDriverID)
}
// Route non-reims guest drivers through the plugin Driver Router (§5.3, §10).
if strings.TrimSpace(*driverID) != "" && *driverID != driver.BuiltinReimsMacOSDriverID {
mgr, router, err := openCLIPluginManager(cfg, false)
@@ -534,6 +551,13 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
"disk_size": *diskSize,
},
}
if drv.ID() == driver.BuiltinStambhaDriverID {
delete(req.Options, "disk_size")
req.Options["gpu"] = *gpu
for key, value := range stambhaOpts {
req.Options[key] = value
}
}
if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
@@ -560,13 +584,17 @@ func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
audioBackend := fs.String("audio-backend", "", "Audio backend (auto, dsound, none, wav)")
guestLang := fs.String("guest-lang", "", "macOS boot/recovery language prev-lang:kbd")
nestedVirt := fs.Bool("nested-virt", false, "Enable nested virtualization on the next cold start (macOS only)")
stambhaFlags := registerStambhaVMFlags(fs)
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm set [--driver <id>] [flags] <name>")
}
changes := map[string]any{}
changes := collectStambhaVMFlags(fs, stambhaFlags)
if len(changes) > 0 && *driverID != driver.BuiltinStambhaDriverID {
return fmt.Errorf("Stambha VM flags require --driver %s", driver.BuiltinStambhaDriverID)
}
if *cpus != 0 {
changes["cpus"] = *cpus
}
@@ -593,6 +621,44 @@ func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
return setVM(ctx, cfg, *driverID, fs.Arg(0), changes)
}
type stambhaVMFlag struct {
option string
value func() any
}
func registerStambhaVMFlags(fs *flag.FlagSet) map[string]stambhaVMFlag {
boot := fs.String("boot-volume", "", "Stambha boot folder containing EFI/stela/stela.cfg")
usb := fs.String("usb-image", "", "Stambha RAW boot image")
bus := fs.String("media-bus", "", "Stambha RAW boot image bus (usb or nvme)")
disk := fs.String("disk", "", "Stambha writable RAW or QCOW2 virtual disk")
fs.StringVar(disk, "raw-disk", "", "Alias for --disk")
accelerator := fs.String("accelerator", "", "Stambha accelerator (whpx or tcg)")
hosted := fs.Bool("hosted-gpu", true, "Use Reims vGPU for a Stambha VM")
headless := fs.Bool("headless", false, "Run Stambha without a display window")
args := fs.String("stela-args", "", "Additional Stambha options for a boot folder")
return map[string]stambhaVMFlag{
"boot-volume": {"boot_volume", func() any { return *boot }},
"usb-image": {"usb_image", func() any { return *usb }},
"media-bus": {"media_bus", func() any { return *bus }},
"disk": {"raw_disk", func() any { return *disk }},
"raw-disk": {"raw_disk", func() any { return *disk }},
"accelerator": {"accelerator", func() any { return *accelerator }},
"hosted-gpu": {"hosted_gpu", func() any { return *hosted }},
"headless": {"display", func() any { return !*headless }},
"stela-args": {"stela_args", func() any { return *args }},
}
}
func collectStambhaVMFlags(fs *flag.FlagSet, declared map[string]stambhaVMFlag) map[string]any {
options := make(map[string]any)
fs.Visit(func(f *flag.Flag) {
if spec, ok := declared[f.Name]; ok {
options[spec.option] = spec.value()
}
})
return options
}
func printJSON(v any) error {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
+2 -10
View File
@@ -80,16 +80,8 @@ func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in
}
client := prep.Client
opts := reims.CreateOpts{Name: in.Name, Dir: in.Dir, MacOS: in.MacOS, CPUs: in.CPUs, Memory: in.Memory, DiskSize: in.DiskSize, GPU: in.GPU, Capture: &in.Capture, Logs: &in.Logs, GuestLang: strings.TrimSpace(in.GuestLang), Start: false}
existingVMs, err := client.List(ctx)
if err != nil {
return fmt.Errorf("check existing VMs before create: %w", err)
}
if issue := reims.ValidateCreateTargetDir(cfg.XDGDataDir(), opts, existingVMs, loc); issue != nil {
return errors.New(issue.Message)
}
if removed, rerr := reims.CleanAbortedCreateDir(cfg.XDGDataDir(), opts, existingVMs); rerr != nil {
return fmt.Errorf("clean unfinished VM directory: %w", rerr)
} else if removed != "" {
existingVMs, _ := client.List(ctx)
if removed, rerr := reims.CleanAbortedCreateDir(cfg.XDGDataDir(), opts, existingVMs); rerr == nil && removed != "" {
fmt.Fprintf(os.Stderr, "Removed unfinished directory from earlier interrupted create: %s\n", removed)
}
if installer.ShouldPrefetchOcBinaryData(prep.Runtime.Manifest.UtilCommit, prep.Runtime.Manifest.UtilVersion) {
+2 -1
View File
@@ -90,7 +90,8 @@ func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
_ = os.Remove(path)
r.Commit = inst.Commit
}
if err := activateRuntime(ctx, cfg, loc, r.Commit); err != nil {
cfg.ActiveRuntime = r.Commit
if err := config.Save("", cfg); err != nil {
return err
}
fmt.Println(i18n.T(loc, "runtime.activated", r.Commit))
+59
View File
@@ -0,0 +1,59 @@
package cli
import (
"context"
"encoding/json"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
)
func TestStambhaCLIUsesPreviewMediaWithoutAnIntelRuntime(t *testing.T) {
if runtime.GOOS != "windows" || runtime.GOARCH != "amd64" {
t.Skip("the built-in Stambha driver runs on Windows x86-64")
}
dir := t.TempDir()
cfg := &config.Config{DataRoot: filepath.Join(dir, "data-root")}
boot := filepath.Join(dir, "boot")
bootConfig := filepath.Join(boot, "EFI", "stela", "stela.cfg")
if err := os.MkdirAll(filepath.Dir(bootConfig), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(bootConfig, []byte("--system\n"), 0o644); err != nil {
t.Fatal(err)
}
disk := filepath.Join(dir, "system.qcow2")
if err := os.WriteFile(disk, []byte("fixture"), 0o644); err != nil {
t.Fatal(err)
}
ctx := context.Background()
args := []string{"--driver", driver.BuiltinStambhaDriverID, "--boot-volume", boot, "--disk", disk, "arm"}
if err := vmCreate(ctx, cfg, i18n.Detect(), args, false); err != nil {
t.Fatal(err)
}
args = []string{"--driver", driver.BuiltinStambhaDriverID, "--hosted-gpu=false", "--headless", "arm"}
if err := vmSet(ctx, cfg, args); err != nil {
t.Fatal(err)
}
raw, err := os.ReadFile(filepath.Join(cfg.XDGDataDir(), "stambha", "vms", "arm", "stambha.json"))
if err != nil {
t.Fatal(err)
}
var profile struct {
Disk string `json:"raw_disk"`
Display bool `json:"display"`
HostedGPU bool `json:"hosted_gpu"`
Accelerator string `json:"accelerator"`
}
if err := json.Unmarshal(raw, &profile); err != nil {
t.Fatal(err)
}
if profile.Disk != disk || profile.Display || profile.HostedGPU || profile.Accelerator != "whpx" {
t.Fatalf("unexpected preview profile %+v", profile)
}
}
+2 -2
View File
@@ -102,13 +102,13 @@ func compactVM(ctx context.Context, cfg *config.Config, driverID, name string) (
return svc.CompactDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, os.Stdout, os.Stderr)
}
func stopVM(ctx context.Context, cfg *config.Config, driverID, name string) error {
func stopVM(ctx context.Context, cfg *config.Config, driverID, name string, force bool) error {
svc, closeService, err := openCLILifecycle(cfg)
if err != nil {
return err
}
defer closeService()
return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, false, os.Stdout, os.Stderr)
return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, force, os.Stdout, os.Stderr)
}
func startInWindow(ctx context.Context, cfg *config.Config, driverID, name string) error {
+5 -17
View File
@@ -20,7 +20,6 @@ type Config struct {
DefaultGPU string `json:"default_gpu,omitempty"`
// RuntimeChannel is "stable" (default, also when empty) or "alpha" (legacy alias "candidate").
RuntimeChannel string `json:"runtime_channel,omitempty"`
QEMUASLR bool `json:"qemu_aslr,omitempty"`
// AppUpdateChannel is "stable" (default, also when empty), "alpha", or "dev":
// controls which Reims-Go client releases CheckAppUpdate offers, and whether
// previous executables/installers are kept on startup for rollback.
@@ -210,22 +209,11 @@ func Load(path string) (*Config, error) {
if path == "" {
path = DefaultConfigPath()
}
cfg, err := LoadExisting(path)
if errors.Is(err, os.ErrNotExist) {
return Default(), nil
}
return cfg, err
}
// LoadExisting reads an existing config and reports a missing file to the caller.
func LoadExisting(path string) (*Config, error) {
var raw []byte
err := retryFileConflict(func() error {
var readErr error
raw, readErr = os.ReadFile(path)
return readErr
})
raw, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return Default(), nil
}
return nil, err
}
cfg := Default()
@@ -269,7 +257,7 @@ func Save(path string, cfg *Config) error {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
return retryFileConflict(func() error { return atomicfile.WriteJSON(path, cfg, 0o644) })
return atomicfile.WriteJSON(path, cfg, 0o644)
}
func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") }
-5
View File
@@ -1,5 +0,0 @@
//go:build !windows
package config
func retryFileConflict(op func() error) error { return op() }
-23
View File
@@ -1,23 +0,0 @@
package config
import (
"errors"
"time"
"golang.org/x/sys/windows"
)
// A reader can briefly deny replacement, and an overlapping replacement
// can briefly deny a new read. A persistent permission error must surface.
func retryFileConflict(op func() error) error {
err := op()
for delay := 5 * time.Millisecond; delay <= 80*time.Millisecond; delay *= 2 {
if !errors.Is(err, windows.ERROR_ACCESS_DENIED) && !errors.Is(err, windows.ERROR_SHARING_VIOLATION) &&
!errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
break
}
time.Sleep(delay)
err = op()
}
return err
}
@@ -1,52 +0,0 @@
package config
import (
"path/filepath"
"testing"
"testing/synctest"
"golang.org/x/sys/windows"
)
func TestConfigRecoversFromWindowsSharingConflict(t *testing.T) {
for _, operation := range []string{"load", "save"} {
t.Run(operation, func(t *testing.T) {
cfg := Config{DataRoot: t.TempDir(), ActiveRuntime: "first"}
path := filepath.Join(cfg.DataRoot, "reims-go.json")
if err := Save(path, &cfg); err != nil {
t.Fatal(err)
}
name, err := windows.UTF16PtrFromString(path)
if err != nil {
t.Fatal(err)
}
handle, err := windows.CreateFile(name, windows.GENERIC_READ, 0, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0)
if err != nil {
t.Fatal(err)
}
synctest.Test(t, func(t *testing.T) {
result := make(chan error, 1)
go func() {
if operation == "load" {
_, err := LoadExisting(path)
result <- err
return
}
cfg.ActiveRuntime = "second"
result <- Save(path, &cfg)
}()
synctest.Wait() // The operation has reached its first retry.
if err := windows.CloseHandle(handle); err != nil {
t.Fatal(err)
}
if err := <-result; err != nil {
t.Fatal(err)
}
})
got, err := LoadExisting(path)
if err != nil || got.ActiveRuntime != cfg.ActiveRuntime {
t.Fatalf("load after %s: got %+v, err %v", operation, got, err)
}
})
}
}
+11
View File
@@ -12,6 +12,7 @@ import (
"strings"
"time"
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
)
@@ -19,6 +20,8 @@ import (
const (
// BuiltinReimsMacOSDriverID is the default driver for all unmarked/existing VMs.
BuiltinReimsMacOSDriverID = "builtin.driver.reims-macos"
// BuiltinStambhaDriverID is the ARM64 macOS driver's persisted ID.
BuiltinStambhaDriverID = "builtin.driver.stambha"
// OwnerMarkerFile persists the owning driver ID inside a VM directory.
OwnerMarkerFile = ".reims-go-driver"
)
@@ -324,6 +327,14 @@ func WriteOwnerDriver(vmDir, driverID string) error {
return os.WriteFile(filepath.Join(vmDir, OwnerMarkerFile), []byte(strings.TrimSpace(driverID)+"\n"), 0o644)
}
// WriteVMRecord atomically replaces a driver's local JSON record in its VM directory.
func WriteVMRecord(vmDir, name string, value any) error {
if !filepath.IsLocal(name) || filepath.Base(name) != name || name == "." {
return fmt.Errorf("invalid VM record name %q", name)
}
return atomicfile.WriteJSON(filepath.Join(vmDir, name), value, 0o600)
}
// HostedReportMaxAge is how long a driver-pushed state counts as fresh; past
// it the host asks the driver with `driver/show` while listing.
const HostedReportMaxAge = 15 * time.Second
-10
View File
@@ -1,10 +0,0 @@
package host
import "errors"
const QEMUASLRHelperArg = "--apply-qemu-aslr"
// The elevated helper has no output channel back to the GUI.
const QEMUASLRImagePolicyExitCode = 78
var ErrQEMUASLRImagePolicy = errors.New("a QEMU path filter would shadow an image-wide Windows setting")
-14
View File
@@ -1,14 +0,0 @@
//go:build !windows
package host
import (
"context"
"errors"
)
func ApplyQEMUASLR(_, _ string) error {
return errors.New("QEMU ASLR requires Windows")
}
func SyncQEMUASLR(ctx context.Context, _, _ string) error { return ctx.Err() }
-364
View File
@@ -1,364 +0,0 @@
package host
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
const (
qemuImage = "qemu-system-x86_64.exe"
qemuIFEO = `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\` + qemuImage
aslrOriginal = "ReimsGoASLROriginal"
filterMode = "ReimsGoASLRFilterMode"
createdFilter = 1 << 8
createdOptions = 1 << 9
)
// SyncQEMUASLR reconciles this runtime directory's owned mitigations. An empty
// target removes them. No elevation is needed when the rules already match.
func SyncQEMUASLR(ctx context.Context, runtimesDir, qemuPath string) error {
if err := ctx.Err(); err != nil {
return err
}
err := ApplyQEMUASLR(runtimesDir, qemuPath)
if !errors.Is(err, windows.ERROR_ACCESS_DENIED) || windows.GetCurrentProcessToken().IsElevated() {
return err
}
exe, err := os.Executable()
if err != nil {
return err
}
args := windows.ComposeCommandLine([]string{QEMUASLRHelperArg, runtimesDir, qemuPath})
// Once authorized, wait for the helper to finish before the caller commits
// or rolls back the corresponding runtime preference.
code, err := runElevatedWait(context.WithoutCancel(ctx), exe, args)
if err != nil {
return err
}
switch code {
case 0:
return nil
case QEMUASLRImagePolicyExitCode:
return ErrQEMUASLRImagePolicy
default:
return fmt.Errorf("apply QEMU ASLR: helper exited with code %d", code)
}
}
func ApplyQEMUASLR(runtimesDir, qemuPath string) error {
// Separate data directories can share the image key and its UseFilter value.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
name := windows.StringToUTF16Ptr(`Global\Reims-Go-QEMU-ASLR`)
mutex, err := windows.CreateMutex(nil, false, name)
if err != nil && !errors.Is(err, windows.ERROR_ALREADY_EXISTS) {
return err
}
defer windows.CloseHandle(mutex)
event, err := windows.WaitForSingleObject(mutex, 5000)
if err != nil {
return err
}
if event != windows.WAIT_OBJECT_0 && event != windows.WAIT_ABANDONED {
return errors.New("timed out waiting for the QEMU policy update")
}
defer windows.ReleaseMutex(mutex)
return reconcileQEMUASLR(registry.LOCAL_MACHINE, qemuIFEO, runtimesDir, qemuPath, windows.GetCurrentProcessToken().IsElevated())
}
func runtimeQEMUPath(root, path string) bool {
rel, err := filepath.Rel(root, path)
if err != nil || !filepath.IsLocal(rel) {
return false
}
parts := strings.Split(rel, `\`)
return (len(parts) == 4 || len(parts) == 5) &&
strings.EqualFold(filepath.Join(parts[len(parts)-3:]...), filepath.Join("qemu", "bin", qemuImage))
}
// Without elevation the same checks run read-only, even if a custom ACL would
// allow writing some of the keys. Declining UAC must leave every key untouched.
func reconcileQEMUASLR(hive registry.Key, imagePath, root, target string, canWrite bool) error {
if !filepath.IsAbs(root) || !strings.EqualFold(filepath.Base(root), "runtimes") ||
(target != "" && (!filepath.IsAbs(target) || filepath.Clean(target) != target || !runtimeQEMUPath(root, target))) {
return fmt.Errorf("invalid QEMU ASLR runtime path %q in %q", target, root)
}
image, err := registry.OpenKey(hive, imagePath, registry.READ)
var createdImage bool
if errors.Is(err, registry.ErrNotExist) {
if target == "" {
return nil
}
if !canWrite {
return windows.ERROR_ACCESS_DENIED
}
var existed bool
image, existed, err = registry.CreateKey(hive, imagePath, registry.READ|registry.WRITE)
createdImage = !existed
}
if err != nil {
return err
}
defer image.Close()
names, err := image.ReadSubKeyNames(-1)
if err != nil {
return err
}
var active string
var stale []string
otherOwner := false
filters := len(names)
for _, name := range names {
path, owned, err := readASLRFilter(image, name)
if aslrKeyGone(err) {
filters--
continue
}
if err != nil {
return err
}
if !runtimeQEMUPath(root, path) {
otherOwner = otherOwner || owned
continue
}
if strings.EqualFold(path, target) {
if active != "" {
return fmt.Errorf("multiple QEMU policy filters for %q", path)
}
active = name
} else if owned {
stale = append(stale, name)
}
}
if target != "" {
if err := enableASLRPathFilters(image, createdImage, active == "", filters, canWrite); err != nil {
return err
}
if active == "" {
active = fmt.Sprintf("Reims-Go-%x", sha256.Sum256([]byte(strings.ToLower(target))))
}
if err := updateASLRFilter(image, active, target, canWrite); err != nil {
return err
}
}
for _, name := range stale {
if err := updateASLRFilter(image, name, "", canWrite); err != nil && !aslrKeyGone(err) {
return err
}
}
if target != "" || otherOwner {
return nil
}
return restoreASLRFilterMode(hive, imagePath, image, canWrite)
}
// A different policy editor can remove a filter after it was enumerated.
func aslrKeyGone(err error) bool {
return errors.Is(err, registry.ErrNotExist) || errors.Is(err, windows.ERROR_KEY_DELETED)
}
func readASLRFilter(image registry.Key, name string) (path string, owned bool, err error) {
k, err := registry.OpenKey(image, name, registry.QUERY_VALUE)
if err != nil {
return "", false, err
}
defer k.Close()
path, _, err = k.GetStringValue("FilterFullPath")
if errors.Is(err, registry.ErrNotExist) {
return "", false, nil // An existing subkey without a path still counts.
}
if err != nil {
return "", false, err
}
_, _, err = k.GetIntegerValue(aslrOriginal)
if errors.Is(err, registry.ErrNotExist) {
return path, false, nil
}
return path, err == nil, err
}
func enableASLRPathFilters(image registry.Key, createdImage, newPath bool, filters int, canWrite bool) error {
if newPath {
values, err := image.ReadValueNames(-1)
if err != nil {
return err
}
for _, v := range values {
if !strings.EqualFold(v, "UseFilter") && !strings.EqualFold(v, filterMode) {
return fmt.Errorf("%w: %q", ErrQEMUASLRImagePolicy, v)
}
}
}
useFilter, _, err := image.GetIntegerValue("UseFilter")
if err != nil && !errors.Is(err, registry.ErrNotExist) {
return err
}
if useFilter == 1 {
return nil
}
if filters != 0 || useFilter != 0 {
return errors.New("QEMU has incompatible Windows path filter settings")
}
if !canWrite {
return windows.ERROR_ACCESS_DENIED
}
// 1 = missing UseFilter, 2 = existing zero, 3 = newly created image.
mode := uint32(1)
if createdImage {
mode = 3
} else if err == nil {
mode = 2
}
w, err := registry.OpenKey(image, "", registry.SET_VALUE)
if err != nil {
return err
}
defer w.Close()
if err := w.SetDWordValue(filterMode, mode); err != nil {
return err
}
return w.SetDWordValue("UseFilter", 1)
}
func restoreASLRFilterMode(hive registry.Key, imagePath string, image registry.Key, canWrite bool) error {
mode, _, err := image.GetIntegerValue(filterMode)
if errors.Is(err, registry.ErrNotExist) {
return nil
}
if err != nil {
return err
}
if !canWrite {
return windows.ERROR_ACCESS_DENIED
}
info, err := image.Stat()
if err != nil {
return err
}
useFilter, _, err := image.GetIntegerValue("UseFilter")
if err != nil && !errors.Is(err, registry.ErrNotExist) {
return err
}
w, err := registry.OpenKey(hive, imagePath, registry.READ|registry.WRITE)
if err != nil {
return err
}
defer w.Close()
if useFilter == 1 && info.SubKeyCount == 0 {
if mode == 3 && info.ValueCount == 2 {
return registry.DeleteKey(hive, imagePath)
}
if mode == 2 {
err = w.SetDWordValue("UseFilter", 0)
} else {
err = w.DeleteValue("UseFilter")
}
if err != nil {
return err
}
}
return w.DeleteValue(filterMode)
}
func updateASLRFilter(image registry.Key, name, target string, canWrite bool) error {
k, err := registry.OpenKey(image, name, registry.READ)
create := errors.Is(err, registry.ErrNotExist)
if create && target != "" {
if !canWrite {
return windows.ERROR_ACCESS_DENIED
}
var existed bool
k, existed, err = registry.CreateKey(image, name, registry.READ|registry.WRITE)
create = !existed
}
if err != nil {
return err
}
defer k.Close()
if create {
if err := k.SetStringValue("FilterFullPath", target); err != nil {
return err
}
} else if target != "" {
path, _, err := k.GetStringValue("FilterFullPath")
if err != nil || !strings.EqualFold(path, target) {
return fmt.Errorf("QEMU policy filter %q does not match %q", name, target)
}
}
options, _, err := k.GetBinaryValue("MitigationOptions")
newOptions := errors.Is(err, registry.ErrNotExist)
if newOptions {
options = make([]byte, 24)
} else if err != nil {
return err
}
if len(options) < 3 {
return errors.New("invalid QEMU MitigationOptions length")
}
original, _, err := k.GetIntegerValue(aslrOriginal)
owned := err == nil
if !owned && !errors.Is(err, registry.ErrNotExist) {
return err
}
// Windows PROCESS_CREATION_MITIGATION_POLICY_*_ASLR fields occupy bits
// 16..17 (bottom-up) and 20..21 (high entropy); value 1 means always on.
if target != "" && options[2]&0x33 == 0x11 {
return nil
}
if !canWrite {
return windows.ERROR_ACCESS_DENIED
}
w, err := registry.OpenKey(image, name, registry.READ|registry.WRITE)
if err != nil {
return err
}
defer w.Close()
if target != "" {
if !owned {
original = uint64(options[2] & 0x33)
if create {
original |= createdFilter
}
if newOptions {
original |= createdOptions
}
if err := w.SetDWordValue(aslrOriginal, uint32(original)); err != nil {
return err
}
}
options[2] = options[2]&^0x33 | 0x11
return w.SetBinaryValue("MitigationOptions", options)
}
for _, shift := range []uint{0, 4} {
mask := byte(3 << shift)
if options[2]&mask == 1<<shift {
options[2] = (options[2] &^ mask) | byte(original)&mask
}
}
if original&createdOptions != 0 && len(bytes.Trim(options, "\x00")) == 0 {
if err := w.DeleteValue("MitigationOptions"); err != nil && !errors.Is(err, registry.ErrNotExist) {
return err
}
} else if err := w.SetBinaryValue("MitigationOptions", options); err != nil {
return err
}
info, err := w.Stat()
if err != nil {
return err
}
if original&createdFilter != 0 && info.SubKeyCount == 0 && info.ValueCount == 2 {
// Only our journal and FilterFullPath remain.
return registry.DeleteKey(image, name)
}
return w.DeleteValue(aslrOriginal)
}
-260
View File
@@ -1,260 +0,0 @@
package host
import (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
func TestReadASLRFilterAfterEnumeration(t *testing.T) {
hive := registry.CURRENT_USER
keyPath := fmt.Sprintf(`Software\Reims-Go-ASLR-Test-%d-%d`, os.Getpid(), time.Now().UnixNano())
image, _, err := registry.CreateKey(hive, keyPath, registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer registry.DeleteKey(hive, keyPath)
defer image.Close()
child, _, err := registry.CreateKey(image, "filter", registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer child.Close()
defer registry.DeleteKey(image, "filter")
names, err := image.ReadSubKeyNames(-1)
if err != nil || len(names) != 1 {
t.Fatalf("enumerated %v: %v", names, err)
}
name := names[0]
if _, owned, err := readASLRFilter(image, name); err != nil || owned {
t.Fatalf("existing subkey without FilterFullPath: owned %v, err %v", owned, err)
}
if err := child.SetDWordValue("FilterFullPath", 1); err != nil {
t.Fatal(err)
}
if _, _, err := readASLRFilter(image, name); err == nil || aslrKeyGone(err) {
t.Fatalf("invalid path value reported as a deleted key: %v", err)
}
if err := registry.DeleteKey(image, name); err != nil {
t.Fatal(err)
}
if _, _, err := readASLRFilter(image, name); !aslrKeyGone(err) {
t.Fatalf("reading a filter removed since enumeration: %v", err)
}
if aslrKeyGone(windows.ERROR_ACCESS_DENIED) || !aslrKeyGone(windows.ERROR_KEY_DELETED) {
t.Fatal("only disappearance should be ignored; access denied must reach UAC")
}
}
func TestQEMUASLRFollowsRuntimeAndRestoresOnlyOwnedRules(t *testing.T) {
imagePath := fmt.Sprintf(`Software\Reims-Go-ASLR-Test-%d-%d`, os.Getpid(), time.Now().UnixNano())
hive := registry.CURRENT_USER
image, _, err := registry.CreateKey(hive, imagePath, registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer func() {
names, _ := image.ReadSubKeyNames(-1)
for _, name := range names {
if err := registry.DeleteKey(image, name); err != nil {
t.Error(err)
}
}
image.Close()
if err := registry.DeleteKey(hive, imagePath); err != nil {
t.Error(err)
}
}()
root := filepath.Join(t.TempDir(), "runtimes")
current := filepath.Join(root, "current", "qemu", "bin", qemuImage)
backup := filepath.Join(root, "backup", "qemu", "bin", qemuImage)
update := func(target string) {
t.Helper()
if err := reconcileQEMUASLR(hive, imagePath, root, target, true); err != nil {
t.Fatal(err)
}
}
countFilters := func(want int) {
t.Helper()
names, err := image.ReadSubKeyNames(-1)
if err != nil || len(names) != want {
t.Fatalf("filters = %v, want %d, err = %v", names, want, err)
}
}
update("")
countFilters(0)
update(current)
update(current)
countFilters(1)
readByte := func(k registry.Key, want byte) {
t.Helper()
b, _, err := k.GetBinaryValue("MitigationOptions")
if err != nil || len(b) != 24 || b[2] != want {
t.Fatalf("mitigations = %x, want byte 2 = %02x, err = %v", b, want, err)
}
}
names, _ := image.ReadSubKeyNames(-1)
active, err := registry.OpenKey(image, names[0], registry.READ)
if err != nil {
t.Fatal(err)
}
readByte(active, 0x11)
active.Close()
probe := func(target string, want error) {
t.Helper()
if err := reconcileQEMUASLR(hive, imagePath, root, target, false); !errors.Is(err, want) {
t.Fatalf("read-only check for %q: got %v, want %v", target, err, want)
}
}
probe(current, nil)
probe("", windows.ERROR_ACCESS_DENIED)
countFilters(1)
// One manual OFF override and unrelated bits on the backup runtime.
manual, _, err := registry.CreateKey(image, "User filter", registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer manual.Close()
if err := manual.SetStringValue("FilterFullPath", backup); err != nil {
t.Fatal(err)
}
b := make([]byte, 24)
b[2] = 0x82
if err := manual.SetBinaryValue("MitigationOptions", b); err != nil {
t.Fatal(err)
}
probe(backup, windows.ERROR_ACCESS_DENIED)
countFilters(2)
readByte(manual, 0x82)
update(backup)
countFilters(1)
readByte(manual, 0x91)
update(current)
countFilters(2)
readByte(manual, 0x82)
update("")
update("")
countFilters(1)
if _, _, err := manual.GetIntegerValue(aslrOriginal); !errors.Is(err, registry.ErrNotExist) {
t.Fatalf("ownership marker remains: %v", err)
}
// Options already ON before enabling continue to belong to the user.
b[2] = 0x91
if err := manual.SetBinaryValue("MitigationOptions", b); err != nil {
t.Fatal(err)
}
update(backup)
update("")
readByte(manual, 0x91)
}
func TestQEMUASLRRestoresImageKey(t *testing.T) {
imagePath := fmt.Sprintf(`Software\Reims-Go-ASLR-Test-%d-%d`, os.Getpid(), time.Now().UnixNano())
root := filepath.Join(t.TempDir(), "runtimes")
target := filepath.Join(root, "current", "qemu", "bin", qemuImage)
hive := registry.CURRENT_USER
update := func(target string) error { return reconcileQEMUASLR(hive, imagePath, root, target, true) }
t.Cleanup(func() {
if err := update(""); err != nil {
t.Error(err)
}
if err := registry.DeleteKey(hive, imagePath); err != nil && !errors.Is(err, registry.ErrNotExist) {
t.Error(err)
}
})
if err := reconcileQEMUASLR(hive, imagePath, root, target, false); !errors.Is(err, windows.ERROR_ACCESS_DENIED) {
t.Fatalf("missing image must require elevation: %v", err)
}
if k, err := registry.OpenKey(hive, imagePath, registry.READ); !errors.Is(err, registry.ErrNotExist) {
k.Close()
t.Fatalf("read-only check created the image key: %v", err)
}
if err := update(target); err != nil {
t.Fatal(err)
}
if err := update(""); err != nil {
t.Fatal(err)
}
if k, err := registry.OpenKey(hive, imagePath, registry.READ); !errors.Is(err, registry.ErrNotExist) {
k.Close()
t.Fatalf("new image key not removed: %v", err)
}
image, _, err := registry.CreateKey(hive, imagePath, registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer image.Close()
if err := image.SetDWordValue("UseFilter", 0); err != nil {
t.Fatal(err)
}
if err := update(target); err != nil {
t.Fatal(err)
}
if err := update(""); err != nil {
t.Fatal(err)
}
if mode, _, err := image.GetIntegerValue("UseFilter"); err != nil || mode != 0 {
t.Fatalf("restored UseFilter = %v, %v", mode, err)
}
if err := update(target); err != nil {
t.Fatal(err)
}
imagePolicy := []byte{1, 0, 0}
if err := image.SetBinaryValue("MitigationOptions", imagePolicy); err != nil {
t.Fatal(err)
}
next := filepath.Join(root, "upgrade", "qemu", "bin", qemuImage)
for _, canWrite := range []bool{false, true} {
if err := reconcileQEMUASLR(hive, imagePath, root, next, canWrite); !errors.Is(err, ErrQEMUASLRImagePolicy) {
t.Fatalf("expected image-wide conflict (write %v), got %v", canWrite, err)
}
}
if got, _, err := image.GetBinaryValue("MitigationOptions"); err != nil || !bytes.Equal(got, imagePolicy) {
t.Fatalf("image policy changed: %x, %v", got, err)
}
names, err := image.ReadSubKeyNames(-1)
if err != nil || len(names) != 1 {
t.Fatalf("unexpected path filters after conflict: %v, %v", names, err)
}
if path, owned, err := readASLRFilter(image, names[0]); err != nil || !owned || path != target {
t.Fatalf("previous filter changed: %q, owned %v, %v", path, owned, err)
}
if err := update(""); err != nil {
t.Fatal(err)
}
if err := image.DeleteValue("MitigationOptions"); err != nil {
t.Fatal(err)
}
if err := image.SetDWordValue("UseFilter", 1); err != nil {
t.Fatal(err)
}
name := fmt.Sprintf("Reims-Go-%x", sha256.Sum256([]byte(strings.ToLower(target))))
filter, _, err := registry.CreateKey(image, name, registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer registry.DeleteKey(image, name)
defer filter.Close()
if err := filter.SetStringValue("FilterFullPath", `C:\Other\`+qemuImage); err != nil {
t.Fatal(err)
}
if err := update(target); err == nil {
t.Fatal("unexpectedly adopted a filter for a different executable")
}
if _, _, err := filter.GetBinaryValue("MitigationOptions"); !errors.Is(err, registry.ErrNotExist) {
t.Fatalf("foreign filter was modified: %v", err)
}
}
-25
View File
@@ -187,11 +187,8 @@ var catalog = map[Locale]map[string]string{
"err.plugin.in_use": "插件「{id}」正在被虚拟机使用,无法停用或卸载:{reason}",
"err.plugin.safe_mode": "当前处于安全模式,已暂停加载和变更第三方插件",
"err.plugin.system_locked": "系统核心组件「{id}」不可停用或卸载",
"err.qemu_aslr.cancelled": "已取消 Windows 管理员授权,QEMU ASLR 设置保持原样",
"err.qemu_aslr.image_policy": "Windows 已按程序名为 qemu-system-x86_64.exe 配置防护,已跳过此运行时的 ASLR 规则。可在 Windows 安全中心的「漏洞保护 → 程序设置」中管理 QEMU 的 ASLR",
"err.quit.stop_failed": "无法关闭虚拟机「{name}」,已取消退出。",
"err.quit.timeout": "虚拟机「{name}」关机超时,已取消退出。",
"err.runtime_changed": "操作期间运行时已切换,请重试以使用当前选定的版本。",
"err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`",
"err.snapshot.name_empty": "请输入恢复点名称",
"err.snapshot.name_invalid": "恢复点名称包含不支持的控制字符或引号",
@@ -541,16 +538,13 @@ var catalog = map[Locale]map[string]string{
"runtime.empty": "尚未安装任何便携运行时。",
"runtime.install_in_use": "停止使用此运行时的虚拟机后再试一次导入",
"runtime.installed": "便携运行时已安装:{commit} -> {dir}",
"runtime.installed_not_activated": "运行时 {commit} 已安装,点击「激活」重试",
"runtime.not_found": "未找到运行时 \"{name}\"",
"runtime.qemu_aslr.warning": "本次启动未能确认 QEMU 的 ASLR 设置。可在「内核」页关闭再开启 ASLR 以重试。",
"runtime.remote.downloading": "下载运行时 {commit}({channel},{size})",
"runtime.remote.empty": "当前通道还没有发布运行时(alpha 版需要加 --alpha)。",
"runtime.remote.paused": "已暂停。再次运行同一命令会从中断处继续。",
"runtime.remove_active": "不能删除当前正在使用的运行时 \"{commit}\",请先切换到其他版本",
"runtime.remove_in_use": "运行时 \"{commit}\" 正被运行中的虚拟机占用,请先停止相关虚拟机后再删除",
"runtime.removed": "已删除运行时:{commit}({dir})",
"runtimeActivationFailed": "运行时激活失败",
"safeModeBanner": "安全模式已启用:已跳过全部第三方插件并回退至内置默认主题",
"safeModeManagePlugins": "管理插件",
"save": "保存",
@@ -661,10 +655,6 @@ var catalog = map[Locale]map[string]string{
"uptimeMinutesSeconds": "{m} 分 {s} 秒",
"uptimeSeconds": "{s} 秒",
"validate.bridge_uplink_required": "选择桥接使用的出口网卡",
"validate.default_dir_not_empty": "默认目录 {dir} 非空,更换名称、选择空目录或先清理旧目录",
"validate.dir_inaccessible": "目标目录 {dir} 无法访问,检查权限或选择其他目录",
"validate.dir_not_directory": "目标路径 {dir} 不是目录,选择新目录或空目录",
"validate.dir_not_empty": "目标目录 {dir} 非空,选择新目录或空目录",
"validate.disk_not_found": "所选虚拟磁盘文件不存在",
"validate.eject_before_controller_change": "切换磁盘控制器前须先弹出 macOS 安装盘",
"validate.gpu_icd_not_found": "所选 Vulkan ICD JSON 文件不存在",
@@ -889,11 +879,8 @@ var catalog = map[Locale]map[string]string{
"err.plugin.in_use": "Plugin “{id}” is currently in use and cannot be disabled or removed: {reason}",
"err.plugin.safe_mode": "Safe mode is active; third-party plugin changes are paused",
"err.plugin.system_locked": "Core system component “{id}” cannot be disabled or removed",
"err.qemu_aslr.cancelled": "Windows authorization was canceled before the QEMU ASLR changes were applied",
"err.qemu_aslr.image_policy": "Windows already has a program-wide rule for qemu-system-x86_64.exe, so this runtime’s ASLR rule was skipped. Manage QEMU’s ASLR in Windows Security under Exploit protection → Program settings.",
"err.quit.stop_failed": "Could not shut down “{name}”. Quit canceled.",
"err.quit.timeout": "Shutdown timed out for “{name}”. Quit canceled.",
"err.runtime_changed": "The selected runtime changed during this operation. Retry to use the current selection.",
"err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install <archive>` first",
"err.snapshot.name_empty": "Enter a restore point name",
"err.snapshot.name_invalid": "Restore point name contains unsupported characters or quotes",
@@ -1243,16 +1230,13 @@ var catalog = map[Locale]map[string]string{
"runtime.empty": "No portable runtimes installed.",
"runtime.install_in_use": "Stop the VMs using this runtime and try the import again",
"runtime.installed": "Portable runtime installed: {commit} -> {dir}",
"runtime.installed_not_activated": "Runtime {commit} is installed. Select Activate to retry activation.",
"runtime.not_found": "runtime \"{name}\" not found",
"runtime.qemu_aslr.warning": "Starting without confirmed QEMU ASLR settings. To retry, turn ASLR off and on in Engine.",
"runtime.remote.downloading": "Downloading runtime {commit} ({channel}, {size})",
"runtime.remote.empty": "No runtime is published on this channel yet (add --alpha for alpha builds).",
"runtime.remote.paused": "Paused. Run the same command again to continue where it stopped.",
"runtime.remove_active": "cannot remove active runtime \"{commit}\"; switch to another version first",
"runtime.remove_in_use": "runtime \"{commit}\" is in use by a running VM; stop the VM and try again",
"runtime.removed": "Removed runtime: {commit} ({dir})",
"runtimeActivationFailed": "Runtime activation failed",
"safeModeBanner": "Safe mode is active: all third-party plugins are disabled and the built-in theme is restored",
"safeModeManagePlugins": "Manage plugins",
"save": "Save",
@@ -1363,10 +1347,6 @@ var catalog = map[Locale]map[string]string{
"uptimeMinutesSeconds": "{m}m {s}s",
"uptimeSeconds": "{s}s",
"validate.bridge_uplink_required": "Choose an uplink adapter for bridged networking",
"validate.default_dir_not_empty": "Default folder {dir} is not empty; use another name, choose an empty folder, or clear it first",
"validate.dir_inaccessible": "Target folder {dir} cannot be accessed; check permissions or choose another folder",
"validate.dir_not_directory": "Target path {dir} is not a folder; choose a new or empty folder",
"validate.dir_not_empty": "Target folder {dir} is not empty; choose a new or empty folder",
"validate.disk_not_found": "Selected disk image file does not exist",
"validate.eject_before_controller_change": "Eject the macOS installer before changing disk controller",
"validate.gpu_icd_not_found": "Selected Vulkan ICD JSON file does not exist",
@@ -1545,7 +1525,6 @@ var paramOrder = map[string][]string{
"resLooksLike": {"h", "w"},
"runtime.activated": {"commit"},
"runtime.installed": {"commit", "dir"},
"runtime.installed_not_activated": {"commit"},
"runtime.not_found": {"name"},
"runtime.remote.downloading": {"commit", "channel", "size"},
"runtime.remove_active": {"commit"},
@@ -1586,10 +1565,6 @@ var paramOrder = map[string][]string{
"uptimeHoursMinutes": {"h", "m"},
"uptimeMinutesSeconds": {"m", "s"},
"uptimeSeconds": {"s"},
"validate.default_dir_not_empty": {"dir"},
"validate.dir_inaccessible": {"dir"},
"validate.dir_not_directory": {"dir"},
"validate.dir_not_empty": {"dir"},
"validate.invalid_audio_backend": {"backend"},
"validate.invalid_cpus": {"max"},
"validate.memory_exceeds_commit": {"mem", "limit", "rec"},
+3
View File
@@ -24,5 +24,8 @@ func Register(reg *plugin.Registry, cb builtin.HostCallbacks, desiredFn func(str
if err := reg.Register(Definition(ver, cb, desiredFn(ID, true))); err != nil {
return err
}
if err := reg.Register(stambhaDefinition(ver, cb, desiredFn)); err != nil {
return err
}
return reg.Register(ImagesDefinition(ver, desiredFn(IDImages, true)))
}
+37
View File
@@ -0,0 +1,37 @@
package guest
import (
"context"
"runtime"
"github.com/Nwflower/reims-go/internal/macos/stambhadriver"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
)
func stambhaDefinition(ver string, cb builtin.HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
drv := stambhadriver.NewStambhaDriver(cb.GetConfig)
pack := plugin.RuntimeKindContribution{
Kind: drv.RuntimeKind(), Name: plugin.LocalizedText{ZhCN: "Stambha 运行时", EnUS: "Stambha Runtime"},
RequiredFiles: stambhadriver.StambhaRuntimeFiles(),
DefaultAPIVer: drv.RuntimeAPIRange(),
}
return plugin.PluginDef{
Manifest: plugin.Manifest{Schema: 1, ID: stambhadriver.StambhaDriverID, Version: ver,
Name: drv.DisplayName(), Publisher: "Reims-Go", License: "Apache-2.0",
Permissions: []string{"driver:vm", "vm:control", "runtime:provider"}, DefaultEnabled: true,
Contributes: plugin.Contributes{RuntimeKinds: []plugin.RuntimeKindContribution{pack},
GuestDrivers: []plugin.GuestDriverContribution{{ID: drv.ID(), Name: drv.DisplayName(), RuntimeKind: drv.RuntimeKind(),
RuntimeAPIRange: drv.RuntimeAPIRange(), Capabilities: drv.Capabilities(),
CreateSchema: drv.CreateSchema(), SettingsSchema: drv.SettingsSchema(),
VMRoots: []string{"data/stambha/vms"}}}},
},
Source: plugin.SourceBuiltin, Trust: plugin.TrustOfficial,
Desired: runtime.GOOS == "windows" && runtime.GOARCH == "amd64" && cb.GetConfig != nil && desiredFn(drv.ID(), true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().RegisterRuntimeKind(sc, pack)
sc.Registry().RegisterGuestDriver(sc, drv.ID(), drv)
return nil
},
}
}
-8
View File
@@ -98,14 +98,6 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
if err := c.CheckCoWCloneSource(ctx, sourceName, srcDisk, cloneName); err != nil {
return err
}
cloneTargetOpts := reims.CreateOpts{Name: cloneName}
registered, err := c.List(ctx)
if err != nil {
return fmt.Errorf("check clone target directory: %w", err)
}
if issue := reims.ValidateCreateTargetDir(cfg.XDGDataDir(), cloneTargetOpts, registered, cfg.Locale); issue != nil {
return errors.New(issue.Message)
}
if _, err := os.Lstat(overlayPath); err == nil {
return fmt.Errorf("clone overlay already exists: %s", overlayPath)
} else if !os.IsNotExist(err) {
-14
View File
@@ -7,7 +7,6 @@ import (
"fmt"
"io"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
@@ -227,19 +226,6 @@ func (d *ReimsMacOSDriver) ValidateCreate(_ context.Context, req driver.CreateRe
cfg := d.getConfig()
rep := host.Inspect(cfg.DataRoot)
issues := reims.ValidateCreate(opts, rep, cfg.Locale)
var registered []reims.VMListItem
xdgDataDir := ""
if strings.TrimSpace(cfg.DataRoot) != "" {
xdgDataDir = cfg.XDGDataDir()
if regVMs, err := reims.ListRegisteredVMs(cfg.DataRoot); err == nil {
for _, vm := range regVMs {
registered = append(registered, reims.VMListItem{Name: vm.Name, Dir: vm.Directory})
}
}
}
if issue := reims.ValidateCreateTargetDir(xdgDataDir, opts, registered, cfg.Locale); issue != nil {
issues = append(issues, *issue)
}
out := make([]driver.ValidationIssue, 0, len(issues))
for _, is := range issues {
out = append(out, driver.ValidationIssue{Field: is.Field, Message: is.Message})
-112
View File
@@ -1,112 +0,0 @@
package macosdriver
import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
)
func TestReimsMacOSDriverValidateCreateRejectsLeftoverDir(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir()}
leftover := filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", "macos-tahoe2")
if err := os.MkdirAll(leftover, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(leftover, "vm.toml"), []byte("name = \"macos-tahoe2\"\n"), 0o644); err != nil {
t.Fatal(err)
}
d := NewReimsMacOSDriver(func() config.Config { return cfg })
issues := d.ValidateCreate(context.Background(), driver.CreateRequest{
Name: "macos-tahoe2",
Options: map[string]any{
"cpus": 2,
"memory": "4G",
"disk_size": "64G",
},
})
found := false
for _, is := range issues {
if is.Field == "dir" {
found = true
break
}
}
if !found {
t.Fatalf("expected dir validation issue for leftover VM folder, got %+v", issues)
}
}
// A running `reims-ctl create` is unregistered and has no vm.toml until it ends,
// so its directory looks the same as one left by a killed create.
func TestReimsMacOSDriverKeepsDirOfRunningCreate(t *testing.T) {
d := newFakeRuntimeDriver(t)
ctx := context.Background()
cfg := d.getConfig()
target := filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", "new-mac")
if err := os.MkdirAll(target, 0o755); err != nil {
t.Fatal(err)
}
disk := filepath.Join(target, "disk.qcow2")
for _, path := range []string{filepath.Join(target, ".reims-ctl-creating"), disk} {
if err := os.WriteFile(path, nil, 0o600); err != nil {
t.Fatal(err)
}
}
var out bytes.Buffer
if err := d.Create(ctx, driver.CreateRequest{Name: "new-mac"}, &out, &out); err == nil {
t.Fatal("Create succeeded in a directory another create is using")
}
if _, err := os.Stat(disk); err != nil {
t.Fatalf("Create removed the directory of a running create: %v", err)
}
source, err := d.Show(ctx, "recovery-vm")
if err != nil {
t.Fatal(err)
}
for name, content := range map[string]string{"vm.toml": "disk = \"disk.qcow2\"\n", "disk.qcow2": ""} {
if err := os.WriteFile(filepath.Join(source.Directory, name), []byte(content), 0o600); err != nil {
t.Fatal(err)
}
}
// The fixture has no qemu-img, so the clone stops when it makes the overlay.
err = d.CloneCoW(ctx, "recovery-vm", "new-mac", &out, &out)
if err == nil || !strings.Contains(out.String(), "Creating CoW overlay") {
t.Fatalf("CloneCoW = %v, want a failure after the target directory check; output: %s", err, out.String())
}
if _, err := os.Stat(disk); err != nil {
t.Fatalf("CloneCoW removed the directory of a running create: %v", err)
}
}
func TestReimsMacOSDriverCreateProtectsRegisteredVMInAbortedDir(t *testing.T) {
d := newFakeRuntimeDriver(t)
vms, err := d.List(context.Background())
if err != nil || len(vms) == 0 {
t.Fatalf("List = %+v, %v", vms, err)
}
parent := filepath.Dir(vms[0].Directory)
marker := filepath.Join(parent, ".reims-ctl-creating")
if err := os.WriteFile(marker, nil, 0o600); err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
err = d.Create(context.Background(), driver.CreateRequest{
Name: "new-mac",
Dir: parent,
}, &stdout, &stderr)
if err == nil {
t.Fatal("expected Create to reject aborted dir holding registered VMs")
}
if _, statErr := os.Stat(vms[0].Directory); statErr != nil {
t.Fatalf("registered VM dir %s must not be removed: %v", vms[0].Directory, statErr)
}
}
+16 -138
View File
@@ -14,7 +14,6 @@ import (
"strings"
"sync"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
@@ -23,37 +22,12 @@ import (
// directory and removed once vm.toml is saved (upstream 3731afd create.rs:451).
const creatingMarker = ".reims-ctl-creating"
// ResolveCreateTargetDir returns the directory `reims-ctl create` will claim
// for opts (opts.Dir if set, otherwise <xdgDataDir>/reims-ctl/vms/<name>).
func ResolveCreateTargetDir(xdgDataDir string, opts CreateOpts) string {
if target := strings.TrimSpace(opts.Dir); target != "" {
return filepath.Clean(config.ExpandHomePath(target))
}
name := strings.TrimSpace(opts.Name)
if name == "" || !reVMName.MatchString(name) || strings.TrimSpace(xdgDataDir) == "" {
return ""
}
return filepath.Join(xdgDataDir, "reims-ctl", "vms", name)
}
// IsAbortedCreateDir reports whether dir holds a `.reims-ctl-creating` marker
// without `vm.toml`, indicating a previously killed `reims-ctl create` run.
func IsAbortedCreateDir(dir string) bool {
if strings.TrimSpace(dir) == "" {
return false
}
markerInfo, err := os.Stat(filepath.Join(dir, creatingMarker))
if err != nil || markerInfo.IsDir() {
return false
}
_, err = os.Stat(filepath.Join(dir, "vm.toml"))
return errors.Is(err, os.ErrNotExist)
}
// CleanAbortedCreateDir removes an unregistered VM target directory left behind
// by a previously killed `reims-ctl create` run. It only removes a directory
// when the name and directory are unregistered and the directory contains
// `.reims-ctl-creating` without `vm.toml`.
// when all three safety conditions hold:
// 1. opts.Name is not present in registered VMs,
// 2. `.reims-ctl-creating` exists inside the directory, and
// 3. `vm.toml` does NOT exist inside the directory.
//
// Returns the removed path if cleaned, or "" if nothing was touched.
func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMListItem) (string, error) {
@@ -66,8 +40,18 @@ func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMLi
return "", nil
}
}
target := ResolveCreateTargetDir(xdgDataDir, opts)
if target == "" || !IsAbortedCreateDir(target) || containsRegisteredVMDir(target, registered) {
target := strings.TrimSpace(opts.Dir)
if target == "" {
if strings.TrimSpace(xdgDataDir) == "" {
return "", nil
}
target = filepath.Join(xdgDataDir, "reims-ctl", "vms", name)
}
markerInfo, err := os.Stat(filepath.Join(target, creatingMarker))
if err != nil || markerInfo.IsDir() {
return "", nil
}
if _, err := os.Stat(filepath.Join(target, "vm.toml")); err == nil {
return "", nil
}
if err := os.RemoveAll(target); err != nil {
@@ -76,112 +60,6 @@ func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMLi
return target, nil
}
var (
targetDirStat = os.Stat
targetDirReadOne = readDirHasEntries
)
func readDirHasEntries(dir string) (bool, error) {
f, err := os.Open(dir)
if err != nil {
return false, err
}
entries, readErr := f.ReadDir(1)
_ = f.Close()
if readErr != nil && !errors.Is(readErr, io.EOF) {
return false, readErr
}
return len(entries) > 0, nil
}
// ValidateCreateTargetDir checks whether the directory `reims-ctl create` will
// claim already exists with conflicting contents. Empty directories and
// unregistered aborted-create directories (cleaned by CleanAbortedCreateDir)
// are allowed.
func ValidateCreateTargetDir(xdgDataDir string, opts CreateOpts, registered []VMListItem, loc i18n.Locale) *ValidationIssue {
target := ResolveCreateTargetDir(xdgDataDir, opts)
if target == "" {
return nil
}
name := strings.TrimSpace(opts.Name)
customDir := strings.TrimSpace(opts.Dir) != ""
isRegistered := false
for _, vm := range registered {
if strings.EqualFold(vm.Name, name) {
isRegistered = true
break
}
}
// When the name itself is already registered and no custom dir was chosen,
// name_taken already reports the conflict on the name field.
if isRegistered && !customDir {
return nil
}
info, err := targetDirStat(target)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return &ValidationIssue{
Field: "dir",
Code: "dir_inaccessible",
Params: map[string]any{"dir": target},
Message: i18n.M(loc, "validate.dir_inaccessible", i18n.Vars{"dir": target}),
}
}
if !info.IsDir() {
return &ValidationIssue{
Field: "dir",
Code: "dir_not_directory",
Params: map[string]any{"dir": target},
Message: i18n.M(loc, "validate.dir_not_directory", i18n.Vars{"dir": target}),
}
}
nonEmpty, readErr := targetDirReadOne(target)
if readErr != nil {
if errors.Is(readErr, os.ErrNotExist) {
return nil
}
return &ValidationIssue{
Field: "dir",
Code: "dir_inaccessible",
Params: map[string]any{"dir": target},
Message: i18n.M(loc, "validate.dir_inaccessible", i18n.Vars{"dir": target}),
}
}
if !nonEmpty {
return nil
}
if !isRegistered && IsAbortedCreateDir(target) && !containsRegisteredVMDir(target, registered) {
return nil
}
msgKey := "validate.default_dir_not_empty"
if customDir {
msgKey = "validate.dir_not_empty"
}
return &ValidationIssue{
Field: "dir",
Code: "dir_not_empty",
Params: map[string]any{"dir": target},
Message: i18n.M(loc, msgKey, i18n.Vars{"dir": target}),
}
}
func containsRegisteredVMDir(target string, registered []VMListItem) bool {
absTarget := absoluteDiskPath(target)
for _, vm := range registered {
if vm.Dir == "" {
continue
}
absVM := absoluteDiskPath(vm.Dir)
if pathInDirectory(target, vm.Dir) || pathInDirectory(absTarget, absVM) ||
pathInDirectory(vm.Dir, target) || pathInDirectory(absVM, absTarget) {
return true
}
}
return false
}
// IsWHPXNoAcceleratorError reports whether QEMU exited because Windows
// Hypervisor was not active. In that branch QEMU logs "WHPX: No accelerator
// found" and returns -ENOSPC ("failed to initialize whpx: No space left on
-158
View File
@@ -335,43 +335,6 @@ func TestCleanAbortedCreateDir(t *testing.T) {
}
}
func TestAbortedCreatePreservesRegisteredVMInTarget(t *testing.T) {
target := filepath.Join(t.TempDir(), "unfinished")
child := filepath.Join(target, "existing")
if err := os.MkdirAll(child, 0o755); err != nil {
t.Fatal(err)
}
for _, path := range []string{filepath.Join(target, creatingMarker), filepath.Join(child, "vm.toml")} {
if err := os.WriteFile(path, nil, 0o600); err != nil {
t.Fatal(err)
}
}
opts := CreateOpts{Name: "new-vm", Dir: target}
registered := []VMListItem{{Name: "existing", Dir: child}}
if removed, err := CleanAbortedCreateDir("", opts, registered); err != nil || removed != "" {
t.Fatalf("cleanup = %q, %v, want registered VM preserved", removed, err)
}
if issue := ValidateCreateTargetDir("", opts, registered, i18n.EnUS); issue == nil || issue.Code != "dir_not_empty" {
t.Fatalf("validation = %+v, want directory conflict", issue)
}
// Symmetric protection: a subdirectory inside a registered VM's folder must not be cleaned either.
nested := filepath.Join(child, "unfinished")
if err := os.MkdirAll(nested, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(nested, creatingMarker), nil, 0o600); err != nil {
t.Fatal(err)
}
nestedOpts := CreateOpts{Name: "nested-vm", Dir: nested}
if removed, err := CleanAbortedCreateDir("", nestedOpts, registered); err != nil || removed != "" {
t.Fatalf("nested cleanup = %q, %v, want registered VM subtree preserved", removed, err)
}
if issue := ValidateCreateTargetDir("", nestedOpts, registered, i18n.EnUS); issue == nil || issue.Code != "dir_not_empty" {
t.Fatalf("nested validation = %+v, want directory conflict", issue)
}
}
func TestWHPXNestedVirtCompat(t *testing.T) {
sampleErr := "2026-11-28T13:04:47Z qemu: -accel whpx: WHPX: Failed to enable nested virtualization, hr=80370302\n"
if !IsWHPXNestedVirtError(sampleErr) {
@@ -499,124 +462,3 @@ func TestDiskImportAndCoWArgs(t *testing.T) {
t.Fatalf("BuildCompactDiskArgs = %q", cmp)
}
}
func TestValidateCreateTargetDir(t *testing.T) {
dataDir := t.TempDir()
vmDir := filepath.Join(dataDir, "reims-ctl", "vms", "macos-tahoe2")
// Missing directory is allowed.
if issue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "macos-tahoe2"}, nil, i18n.EnUS); issue != nil {
t.Fatalf("missing dir should be allowed, got %+v", issue)
}
// Empty directory is allowed.
if err := os.MkdirAll(vmDir, 0o755); err != nil {
t.Fatal(err)
}
if issue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "macos-tahoe2"}, nil, i18n.EnUS); issue != nil {
t.Fatalf("empty dir should be allowed, got %+v", issue)
}
// Unregistered aborted create dir (.reims-ctl-creating without vm.toml) is allowed
// because CleanAbortedCreateDir removes it before create runs.
marker := filepath.Join(vmDir, creatingMarker)
if err := os.WriteFile(marker, nil, 0o644); err != nil {
t.Fatal(err)
}
if issue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "macos-tahoe2"}, nil, i18n.EnUS); issue != nil {
t.Fatalf("aborted create dir should be allowed, got %+v", issue)
}
_ = os.Remove(marker)
// Leftover non-empty directory (e.g. from --keep-files or failed delete) is rejected.
if err := os.WriteFile(filepath.Join(vmDir, "vm.toml"), []byte("name = \"macos-tahoe2\"\n"), 0o644); err != nil {
t.Fatal(err)
}
issueEn := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "macos-tahoe2"}, nil, i18n.EnUS)
if issueEn == nil || issueEn.Field != "dir" || issueEn.Code != "dir_not_empty" || !strings.Contains(issueEn.Message, vmDir) {
t.Fatalf("leftover default dir (en-US) = %+v", issueEn)
}
issueZh := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "macos-tahoe2"}, nil, i18n.ZhCN)
if issueZh == nil || issueZh.Field != "dir" || issueZh.Code != "dir_not_empty" || !strings.Contains(issueZh.Message, vmDir) {
t.Fatalf("leftover default dir (zh-CN) = %+v", issueZh)
}
// Suppress duplicate dir error on default dir when name itself is already registered.
if issue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "macos-tahoe2"}, []VMListItem{{Name: "macos-tahoe2"}}, i18n.EnUS); issue != nil {
t.Fatalf("registered VM default dir should defer to name_taken, got %+v", issue)
}
// Non-empty custom dir is rejected even if VM name differs or is registered.
customDir := filepath.Join(t.TempDir(), "occupied")
if err := os.MkdirAll(customDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(customDir, "notes.txt"), []byte("keep"), 0o644); err != nil {
t.Fatal(err)
}
customIssue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "fresh-vm", Dir: customDir}, nil, i18n.EnUS)
if customIssue == nil || customIssue.Field != "dir" || customIssue.Code != "dir_not_empty" || !strings.Contains(customIssue.Message, customDir) {
t.Fatalf("non-empty custom dir = %+v", customIssue)
}
// Regular file at target path is rejected as dir_not_directory.
filePath := filepath.Join(t.TempDir(), "not-a-dir")
if err := os.WriteFile(filePath, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
fileIssue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "fresh-vm", Dir: filePath}, nil, i18n.EnUS)
if fileIssue == nil || fileIssue.Field != "dir" || fileIssue.Code != "dir_not_directory" {
t.Fatalf("regular file target = %+v", fileIssue)
}
// Invalid VM name with empty Dir must not stat outside vms/.
if issue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "../escape"}, nil, i18n.EnUS); issue != nil {
t.Fatalf("invalid name should return nil target dir issue, got %+v", issue)
}
}
func TestValidateCreateTargetDirInaccessible(t *testing.T) {
dataDir := t.TempDir()
vmDir := filepath.Join(dataDir, "reims-ctl", "vms", "locked-vm")
if err := os.MkdirAll(vmDir, 0o755); err != nil {
t.Fatal(err)
}
origStat := targetDirStat
origRead := targetDirReadOne
t.Cleanup(func() {
targetDirStat = origStat
targetDirReadOne = origRead
})
// Non-NotExist stat error (e.g., permission denied or NTFS delete-pending) must report dir_inaccessible.
targetDirStat = func(string) (os.FileInfo, error) {
return nil, os.ErrPermission
}
issueEn := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "locked-vm"}, nil, i18n.EnUS)
if issueEn == nil || issueEn.Field != "dir" || issueEn.Code != "dir_inaccessible" || !strings.Contains(issueEn.Message, vmDir) {
t.Fatalf("stat permission error (en-US) = %+v", issueEn)
}
issueZh := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "locked-vm"}, nil, i18n.ZhCN)
if issueZh == nil || issueZh.Field != "dir" || issueZh.Code != "dir_inaccessible" || !strings.Contains(issueZh.Message, vmDir) {
t.Fatalf("stat permission error (zh-CN) = %+v", issueZh)
}
// Non-NotExist ReadDir error must also report dir_inaccessible.
targetDirStat = origStat
targetDirReadOne = func(string) (bool, error) {
return false, os.ErrPermission
}
issueRead := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "locked-vm"}, nil, i18n.EnUS)
if issueRead == nil || issueRead.Field != "dir" || issueRead.Code != "dir_inaccessible" {
t.Fatalf("readdir permission error = %+v", issueRead)
}
// If directory vanished between Stat and Open/ReadDir, allow it.
targetDirReadOne = func(string) (bool, error) {
return false, os.ErrNotExist
}
if issue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "locked-vm"}, nil, i18n.EnUS); issue != nil {
t.Fatalf("vanished dir during readdir should be allowed, got %+v", issue)
}
}
+22 -200
View File
@@ -7,7 +7,6 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"runtime"
@@ -262,47 +261,13 @@ func (c *Client) createWithDisk(ctx context.Context, o CreateOpts, args []string
return c.run(ctx, stdout, stderr, args...)
}
var deleteDirRetryDelays = []time.Duration{
50 * time.Millisecond,
100 * time.Millisecond,
150 * time.Millisecond,
250 * time.Millisecond,
400 * time.Millisecond,
600 * time.Millisecond,
800 * time.Millisecond,
}
func (c *Client) lockDeleteRegistry(ctx context.Context) (func(), error) {
if c.imagesDir != "" {
return c.lockCoWRegistry(ctx)
}
if c.registryDir == "" {
return func() {}, nil
}
if err := os.MkdirAll(c.registryDir, 0o755); err != nil {
return nil, err
}
wait, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
release, err := filelock.Acquire(wait, filepath.Join(c.registryDir, ".reims-go-delete.lock"), 0)
if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil {
return nil, i18n.NewCodedError(c.Locale, "E_COW_REGISTRY_BUSY", "err.clone.registry_busy", nil, err)
}
return release, err
}
func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool, stdout io.Writer, removeVM func() error) error {
func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool, removeVM func() error) error {
if keepFiles {
if c.imagesDir != "" || c.registryDir != "" {
registry, err := c.lockDeleteRegistry(ctx)
if err != nil {
return err
}
defer registry()
registry, err := c.lockCoWRegistry(ctx)
if err != nil {
return err
}
return removeVM()
}
if c.registryDir == "" {
defer registry()
return removeVM()
}
@@ -311,17 +276,14 @@ func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool,
return err
}
vm := findRegisteredVM(vms, name)
var disk, managedPath string
if c.imagesDir != "" {
disk, managedPath = c.deletionDisk(vm)
release, err := c.LockCoWDisks(ctx, disk)
if err != nil {
return err
}
defer release()
disk, managedPath := c.deletionDisk(vm)
release, err := c.LockCoWDisks(ctx, disk)
if err != nil {
return err
}
defer release()
registry, err := c.lockDeleteRegistry(ctx)
registry, err := c.lockCoWRegistry(ctx)
if err != nil {
return err
}
@@ -337,10 +299,8 @@ func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool,
if vm.Directory == "" {
return removeVM()
}
if c.imagesDir != "" {
if currentDisk, currentManaged := c.deletionDisk(current); currentDisk != disk || currentManaged != managedPath {
return fmt.Errorf("VM %s changed its disk while waiting to delete it", name)
}
if currentDisk, currentManaged := c.deletionDisk(current); currentDisk != disk || currentManaged != managedPath {
return fmt.Errorf("VM %s changed its disk while waiting to delete it", name)
}
// The upstream tool only removes a directory containing vm.toml. A
@@ -349,73 +309,17 @@ func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool,
if cfgErr != nil && !errors.Is(cfgErr, os.ErrNotExist) {
return cfgErr
}
hadConfig := cfgErr == nil
var overlay diskMatch
if c.imagesDir != "" {
overlay = newDiskMatch(managedPath)
vmDir := absoluteDiskPath(vm.Directory)
match := func(path string) bool {
return overlay.matches(path) || (hadConfig &&
(pathInDirectory(vm.Directory, path) || pathInDirectory(vmDir, absoluteDiskPath(path))))
}
if err := c.checkCoWBackingUse(vms, name, match); err != nil {
return err
}
overlay := newDiskMatch(managedPath)
vmDir := absoluteDiskPath(vm.Directory)
match := func(path string) bool {
return overlay.matches(path) || (cfgErr == nil &&
(pathInDirectory(vm.Directory, path) || pathInDirectory(vmDir, absoluteDiskPath(path))))
}
if hadConfig && c.dirUsedByOtherVM(vms, name, vm.Directory) {
return fmt.Errorf("VM directory %s is used by another registered VM", vm.Directory)
if err := c.checkCoWBackingUse(vms, name, match); err != nil {
return err
}
removeErr := removeVM()
// Upstream `reims-ctl delete` writes vms.toml before calling remove_dir_all
// without retries (reims-vgpu 2df30ff cli.rs:1049-1060). On Windows, a brief
// sharing violation or NTFS delete-pending state can leave the directory behind
// after unregistration, blocking a subsequent create of the same VM name.
if hadConfig {
_, statErr := os.Stat(vm.Directory)
dirExists := !errors.Is(statErr, os.ErrNotExist)
if removeErr != nil || dirExists {
afterVMs, regErr := readRegisteredVMs(c.registryDir)
unregistered := regErr == nil && findRegisteredVM(afterVMs, name).Directory == ""
if !unregistered {
if removeErr != nil {
return removeErr
}
return nil
}
if dirExists {
if c.dirUsedByOtherVM(afterVMs, name, vm.Directory) {
if removeErr != nil {
return removeErr
}
} else if cleanupErr := removeVMDirWithRetry(ctx, vm.Directory); cleanupErr == nil {
if removeErr != nil && stdout != nil {
_, _ = fmt.Fprintf(stdout, "Removed remaining VM directory %s after retry\n", vm.Directory)
}
// In upstream reims-vgpu 2df30ff cli.rs:1049-1060, remove_dir_all is
// the only step after vms.toml is saved; once the leftover directory
// is cleanly removed, the transient remove_dir_all error is recovered
// unless the caller canceled ctx.
if ctx.Err() == nil {
removeErr = nil
}
} else if removeErr != nil {
removeErr = fmt.Errorf("%w (VM unregistered, failed to remove %s: %v)", removeErr, vm.Directory, cleanupErr)
} else {
removeErr = fmt.Errorf("remove %s: %w", vm.Directory, cleanupErr)
}
}
// If !dirExists && removeErr != nil, preserve removeErr instead of
// masking a failure that happened after the directory was already gone.
if managedPath != "" && !c.hasOtherDiskOwner(afterVMs, name, overlay) {
if err := os.Remove(managedPath); err != nil && !errors.Is(err, os.ErrNotExist) {
removeErr = errors.Join(removeErr, fmt.Errorf("remove clone disk %s: %w", managedPath, err))
}
}
return removeErr
}
} else if removeErr != nil {
return removeErr
if err := removeVM(); err != nil {
return err
}
if managedPath != "" && !c.hasOtherDiskOwner(vms, name, overlay) {
@@ -426,88 +330,6 @@ func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool,
return nil
}
func (c *Client) dirUsedByOtherVM(vms []driver.VMInfo, excludeName, dir string) bool {
absDir := absoluteDiskPath(dir)
for _, vm := range vms {
if vm.Name == excludeName {
continue
}
if sameDiskPath(vm.Directory, dir) || sameDiskPath(absoluteDiskPath(vm.Directory), absDir) ||
pathInDirectory(dir, vm.Directory) || pathInDirectory(absDir, absoluteDiskPath(vm.Directory)) {
return true
}
var disk string
if c.imagesDir != "" {
disk = c.registeredDisk(vm)
} else if d, err := vmSystemDisk(vm.Directory); err == nil {
disk = d
}
if disk != "" && (pathInDirectory(dir, disk) || pathInDirectory(absDir, absoluteDiskPath(disk))) {
return true
}
}
return false
}
func removeVMDirWithRetry(ctx context.Context, dir string) error {
var lastErr error
for attempt := 0; attempt <= len(deleteDirRetryDelays); attempt++ {
if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
return nil
}
err := os.RemoveAll(dir)
if err == nil {
if _, statErr := os.Stat(dir); errors.Is(statErr, os.ErrNotExist) {
return nil
}
err = fmt.Errorf("directory still present after removal: %s", dir)
} else if errors.Is(err, os.ErrPermission) {
makeTreeWritable(dir)
if retryErr := os.RemoveAll(dir); retryErr == nil {
if _, statErr := os.Stat(dir); errors.Is(statErr, os.ErrNotExist) {
return nil
}
err = fmt.Errorf("directory still present after removal: %s", dir)
} else {
err = retryErr
}
}
lastErr = err
if attempt == len(deleteDirRetryDelays) {
break
}
delay := deleteDirRetryDelays[attempt]
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return errors.Join(lastErr, ctx.Err())
case <-timer.C:
}
}
return lastErr
}
func makeTreeWritable(dir string) {
_ = filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if d.Type()&(os.ModeSymlink|os.ModeIrregular) != 0 {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if d.IsDir() {
_ = os.Chmod(p, 0o700)
} else {
_ = os.Chmod(p, 0o600)
}
return nil
})
}
func (c *Client) deletionDisk(vm driver.VMInfo) (disk, managedPath string) {
if vm.Directory == "" {
return "", ""
+5 -312
View File
@@ -1,7 +1,6 @@
package reims
import (
"bytes"
"context"
"encoding/binary"
"errors"
@@ -9,16 +8,12 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/filelock"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestResolveCompactQCOW2Options(t *testing.T) {
@@ -142,7 +137,7 @@ func TestCoWRegisteredChainsAndDeletion(t *testing.T) {
damagedVM := testDiskVM(t, "damaged", filepath.Dir(empty), empty)
writeTestRegistrations(t, c, baseVM, middleVM, linkedVM, damagedVM)
err := c.deleteWithCoW(ctx, middleVM.Name, false, nil, func() error {
err := c.deleteWithCoW(ctx, middleVM.Name, false, func() error {
t.Fatal("cannot delete a managed image used by another VM")
return nil
})
@@ -156,7 +151,7 @@ func TestCoWRegisteredChainsAndDeletion(t *testing.T) {
assertCoWInUse(t, err, linkedVM.Name)
writeTestRegistrations(t, c, baseVM, middleVM, damagedVM)
if err := c.deleteWithCoW(ctx, middleVM.Name, false, nil, func() error {
if err := c.deleteWithCoW(ctx, middleVM.Name, false, func() error {
writeTestRegistrations(t, c, baseVM, damagedVM)
return nil
}); err != nil {
@@ -186,12 +181,12 @@ func TestCoWBrokenVMDeletionAndKeepFiles(t *testing.T) {
child := testDiskVM(t, "child", filepath.Join(root, "child"), overlay)
writeTestCoWFile(t, overlay, testBackingHeader(disk))
writeTestRegistrations(t, c, broken, child)
assertCoWInUse(t, c.deleteWithCoW(ctx, broken.Name, false, nil, func() error {
assertCoWInUse(t, c.deleteWithCoW(ctx, broken.Name, false, func() error {
t.Fatal("cannot delete the backing disk inside a broken VM directory")
return nil
}), child.Name)
if err := c.deleteWithCoW(ctx, child.Name, true, nil, func() error {
if err := c.deleteWithCoW(ctx, child.Name, true, func() error {
writeTestRegistrations(t, c, broken)
return nil
}); err != nil {
@@ -200,7 +195,7 @@ func TestCoWBrokenVMDeletionAndKeepFiles(t *testing.T) {
if _, err := os.Stat(overlay); err != nil {
t.Fatalf("keep-files removed the clone disk: %v", err)
}
if err := c.deleteWithCoW(ctx, broken.Name, false, nil, func() error { return nil }); err != nil {
if err := c.deleteWithCoW(ctx, broken.Name, false, func() error { return nil }); err != nil {
t.Fatalf("broken VM with no registered dependents should be deletable: %v", err)
}
}
@@ -425,305 +420,3 @@ func TestParseQCOW2CreateOptionsFromInfoJSON(t *testing.T) {
t.Fatal("expected error for raw format")
}
}
func TestDeleteRetriesDirectoryCleanupAfterUnregister(t *testing.T) {
origDelays := deleteDirRetryDelays
deleteDirRetryDelays = []time.Duration{
10 * time.Millisecond,
20 * time.Millisecond,
30 * time.Millisecond,
50 * time.Millisecond,
80 * time.Millisecond,
}
t.Cleanup(func() { deleteDirRetryDelays = origDelays })
t.Run("recovers_transient_lock_and_cleans_overlay", func(t *testing.T) {
root := t.TempDir()
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
base := filepath.Join(root, "base", "disk.qcow2")
overlay := c.CoWImagePath("macos-tahoe2")
writeTestCoWFile(t, base, nil)
writeTestCoWFile(t, overlay, testBackingHeader(base))
vmDir := filepath.Join(root, "vms", "macos-tahoe2")
vm := testDiskVM(t, "macos-tahoe2", vmDir, overlay)
logPath := filepath.Join(vmDir, "logs", "qemu.log")
writeTestCoWFile(t, logPath, []byte("qemu log"))
writeTestRegistrations(t, c, vm)
// Hold an open handle on Windows so the initial remove_dir_all fails,
// then release it while deleteWithCoW is retrying.
held, err := os.Open(logPath)
if err != nil {
t.Fatal(err)
}
released := make(chan struct{})
go func() {
time.Sleep(25 * time.Millisecond)
_ = held.Close()
close(released)
}()
t.Cleanup(func() { <-released })
err = c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
// Mirror upstream reims-ctl: unregister in vms.toml first, then fail removing dir.
writeTestRegistrations(t, c)
return errors.New("remove dir: sharing violation")
})
if err != nil {
t.Fatalf("expected transient lock recovery, got %v", err)
}
if _, err := os.Stat(vmDir); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected %s to be removed, stat err=%v", vmDir, err)
}
if _, err := os.Stat(overlay); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected CoW overlay %s to be removed, stat err=%v", overlay, err)
}
})
t.Run("preserves_dir_when_still_registered", func(t *testing.T) {
root := t.TempDir()
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
vmDir := filepath.Join(root, "vms", "running-vm")
disk := filepath.Join(vmDir, "disk.qcow2")
writeTestCoWFile(t, disk, nil)
vm := testDiskVM(t, "running-vm", vmDir, disk)
writeTestRegistrations(t, c, vm)
wantErr := errors.New("running-vm is running: stop it first")
err := c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
return wantErr
})
if !errors.Is(err, wantErr) {
t.Fatalf("err = %v, want %v", err, wantErr)
}
if _, statErr := os.Stat(filepath.Join(vmDir, "vm.toml")); statErr != nil {
t.Fatalf("still-registered VM directory should remain untouched: %v", statErr)
}
})
t.Run("preserves_dir_when_used_by_other_vm", func(t *testing.T) {
root := t.TempDir()
c := &Client{registryDir: filepath.Join(root, "registry")}
parentDir := filepath.Join(root, "vms", "parent")
childDir := filepath.Join(parentDir, "nested-child")
parent := testDiskVM(t, "parent", parentDir, filepath.Join(parentDir, "disk.qcow2"))
child := testDiskVM(t, "child", childDir, filepath.Join(childDir, "disk.qcow2"))
writeTestRegistrations(t, c, parent, child)
err := c.deleteWithCoW(context.Background(), parent.Name, false, nil, func() error {
t.Fatal("upstream delete must not run when another VM uses the directory")
return nil
})
if err == nil || !strings.Contains(err.Error(), "used by another registered VM") {
t.Fatalf("delete = %v, want shared directory error", err)
}
if _, statErr := os.Stat(filepath.Join(childDir, "vm.toml")); statErr != nil {
t.Fatalf("shared directory holding another VM must not be removed: %v", statErr)
}
})
t.Run("cleans_readonly_files_without_images_dir", func(t *testing.T) {
root := t.TempDir()
c := &Client{registryDir: filepath.Join(root, "registry")}
vmDir := filepath.Join(root, "vms", "ro-vm")
roFile := filepath.Join(vmDir, "readonly.txt")
writeTestCoWFile(t, roFile, []byte("locked-readonly"))
vm := testDiskVM(t, "ro-vm", vmDir, filepath.Join(vmDir, "disk.qcow2"))
writeTestRegistrations(t, c, vm)
if err := os.Chmod(roFile, 0o444); err != nil {
t.Fatal(err)
}
err := c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
writeTestRegistrations(t, c)
return errors.New("remove dir: permission denied")
})
if err != nil {
t.Fatalf("expected readonly cleanup to succeed, got %v", err)
}
if _, err := os.Stat(vmDir); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected %s to be removed, stat err=%v", vmDir, err)
}
})
t.Run("reports_persistent_lock_on_windows", func(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows sharing violation semantics only")
}
root := t.TempDir()
c := &Client{registryDir: filepath.Join(root, "registry")}
vmDir := filepath.Join(root, "vms", "stuck-vm")
logPath := filepath.Join(vmDir, "logs", "qemu.log")
writeTestCoWFile(t, logPath, []byte("still open"))
vm := testDiskVM(t, "stuck-vm", vmDir, filepath.Join(vmDir, "disk.qcow2"))
writeTestRegistrations(t, c, vm)
held, err := os.Open(logPath)
if err != nil {
t.Fatal(err)
}
defer held.Close()
err = c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
writeTestRegistrations(t, c)
return errors.New("exit status 1")
})
if err == nil || !strings.Contains(err.Error(), vmDir) {
t.Fatalf("expected error naming locked dir %s, got %v", vmDir, err)
}
})
t.Run("preserves_error_when_dir_already_removed", func(t *testing.T) {
root := t.TempDir()
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
base := filepath.Join(root, "base", "disk.qcow2")
overlay := c.CoWImagePath("gone-vm")
writeTestCoWFile(t, base, nil)
writeTestCoWFile(t, overlay, testBackingHeader(base))
vmDir := filepath.Join(root, "vms", "gone-vm")
vm := testDiskVM(t, "gone-vm", vmDir, overlay)
writeTestRegistrations(t, c, vm)
wantErr := errors.New("reims-ctl exited unexpectedly after removal")
err := c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
writeTestRegistrations(t, c)
if rmErr := os.RemoveAll(vmDir); rmErr != nil {
t.Fatal(rmErr)
}
return wantErr
})
if !errors.Is(err, wantErr) {
t.Fatalf("err = %v, want %v (must not mask error when dir was already gone)", err, wantErr)
}
if _, statErr := os.Stat(overlay); !errors.Is(statErr, os.ErrNotExist) {
t.Fatalf("expected orphaned CoW overlay %s to be cleaned, stat err=%v", overlay, statErr)
}
})
t.Run("locks_registry_and_detects_change_without_images_dir", func(t *testing.T) {
root := t.TempDir()
regDir := filepath.Join(root, "registry")
c := &Client{registryDir: regDir}
vmDir := filepath.Join(root, "vms", "race-vm")
otherDir := filepath.Join(root, "vms", "race-vm-moved")
vm := testDiskVM(t, "race-vm", vmDir, filepath.Join(vmDir, "disk.qcow2"))
moved := testDiskVM(t, "race-vm", otherDir, filepath.Join(otherDir, "disk.qcow2"))
writeTestRegistrations(t, c, vm)
unlock, err := filelock.Acquire(context.Background(), filepath.Join(regDir, ".reims-go-delete.lock"), 0)
if err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() {
done <- c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
return errors.New("removeVM must not run after concurrent directory change")
})
}()
time.Sleep(40 * time.Millisecond)
writeTestRegistrations(t, c, moved)
unlock()
select {
case err := <-done:
if err == nil || !strings.Contains(err.Error(), "changed while waiting to delete it") {
t.Fatalf("err = %v, want concurrent change error", err)
}
case <-time.After(3 * time.Second):
t.Fatal("deleteWithCoW timed out waiting for registry lock")
}
})
t.Run("preserves_overlay_when_still_registered_after_nil_remove", func(t *testing.T) {
root := t.TempDir()
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
base := filepath.Join(root, "base", "disk.qcow2")
overlay := c.CoWImagePath("still-there")
writeTestCoWFile(t, base, nil)
writeTestCoWFile(t, overlay, testBackingHeader(base))
vmDir := filepath.Join(root, "vms", "still-there")
vm := testDiskVM(t, "still-there", vmDir, overlay)
writeTestRegistrations(t, c, vm)
if err := c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
return nil
}); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if _, statErr := os.Stat(vmDir); statErr != nil {
t.Fatalf("still-registered VM directory must not be deleted: %v", statErr)
}
if _, statErr := os.Stat(overlay); statErr != nil {
t.Fatalf("overlay for still-registered VM must not be deleted: %v", statErr)
}
})
}
func TestDeleteRealReimsCtlTransientLockAndKeepFiles(t *testing.T) {
ctlPath := os.Getenv("REIMS_GO_TEST_CTL")
if ctlPath == "" {
t.Skip("set REIMS_GO_TEST_CTL to test Client.Delete against a real reims-ctl binary")
}
rtDir := filepath.Dir(filepath.Dir(ctlPath))
dataRoot := t.TempDir()
cfg := &config.Config{DataRoot: dataRoot, Locale: i18n.EnUS}
if err := cfg.EnsureDirs(); err != nil {
t.Fatal(err)
}
client := NewClient(cfg, rt.Installed{Dir: rtDir})
makeVM := func(name string) string {
t.Helper()
vmDir := filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", name)
writeTestCoWFile(t, filepath.Join(vmDir, "vm.toml"), []byte(fmt.Sprintf(
"name = %q\nprofile = \"q35-x86_64\"\ncpus = 4\nmemory_mib = 4096\ndisk = \"disk.qcow2\"\ndisk_format = \"qcow2\"\n",
name,
)))
writeTestCoWFile(t, filepath.Join(vmDir, "disk.qcow2"), []byte("dummy"))
writeTestCoWFile(t, filepath.Join(vmDir, ".reims-go-arg-ledger.json"), []byte("{}"))
writeTestCoWFile(t, filepath.Join(vmDir, "logs", "qemu.log"), []byte("boot\n"))
writeTestRegistrations(t, client, driver.VMInfo{Name: name, Directory: vmDir})
return vmDir
}
// 1. Real reims-ctl delete hitting a transient Windows sharing violation on the first file.
vmDir := makeVM("macos-tahoe2")
lockedPath := filepath.Join(vmDir, ".reims-go-arg-ledger.json")
held, err := os.Open(lockedPath)
if err != nil {
t.Fatal(err)
}
released := make(chan struct{})
go func() {
time.Sleep(120 * time.Millisecond)
_ = held.Close()
close(released)
}()
t.Cleanup(func() { <-released })
var out, errBuf bytes.Buffer
if err := client.Delete(context.Background(), "macos-tahoe2", false, &out, &errBuf); err != nil {
t.Fatalf("real reims-ctl delete failed to recover transient lock: %v (stdout=%q stderr=%q)", err, out.String(), errBuf.String())
}
if _, err := os.Stat(vmDir); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected %s to be deleted after retry, stat err=%v", vmDir, err)
}
if issue := ValidateCreateTargetDir(cfg.XDGDataDir(), CreateOpts{Name: "macos-tahoe2"}, nil, i18n.EnUS); issue != nil {
t.Fatalf("recreating macos-tahoe2 should pass target dir validation after clean delete, got %+v", issue)
}
// 2. Real reims-ctl delete with keepFiles=true leaves the dir, and ValidateCreateTargetDir catches it upfront.
keptDir := makeVM("macos-tahoe-keep")
out.Reset()
errBuf.Reset()
if err := client.Delete(context.Background(), "macos-tahoe-keep", true, &out, &errBuf); err != nil {
t.Fatalf("real reims-ctl delete --keep-files failed: %v (stderr=%q)", err, errBuf.String())
}
if _, err := os.Stat(filepath.Join(keptDir, "vm.toml")); err != nil {
t.Fatalf("keep-files should preserve vm.toml: %v", err)
}
issue := ValidateCreateTargetDir(cfg.XDGDataDir(), CreateOpts{Name: "macos-tahoe-keep"}, nil, i18n.ZhCN)
if issue == nil || issue.Field != "dir" || issue.Code != "dir_not_empty" {
t.Fatalf("expected dir_not_empty after keep-files delete, got %+v", issue)
}
}
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more